At my current place of employment, my development environment is limited to creating custom SharePoint tools through SharePoint Designer. I typically create an override to the OnLoad method to get my work done.
Today’s topic: a simple interface for checking out who has group memberships and where they have them. I came up with the idea after seeing the constant organizational changes and the employee role changes associated with them. So let’s talk about the two parts. If you just want the code without the breakdown, scroll to the bottom of the full article.
User Lookup
There are three methods to this (in addition to a base of methods that I find helpful with my custom pages). First let’s take a look at my basic header.
<%@ Page language="C#"
MasterPageFile="~masterurl/default.master"
SmartNavigation="true"
Inherits="Microsoft.SharePoint.WebPartPages.WebPartPage,
Microsoft.SharePoint,
Version=12.0.0.0,
Culture=neutral,
PublicKeyToken=71e9bce111e9429c"
meta:progid="SharePoint.WebPartPage.Document" %>
<%@ Import Namespace="Microsoft.SharePoint" %>
It really is this simple. You only need the Microsoft.SharePoint library! Now I begin my <script> section that contains the OnLoad override and other methods needed.
protected SPSite site;
protected SPWeb web;
protected override void OnLoad(EventArgs e)
{
try
{
site = new SPSite("http://server/");
web = site.OpenWeb("webdev");
SPGroup grpMembers = web.SiteGroups["Website Development Members"];
if(grpMembers.ContainsCurrentUser)
{
mvViewManager.ActiveViewIndex = 1;
runPage();
}
}
catch (Exception err)
{
litError.Visible = true;
litError.Text = err.Message;
}
}
The first thing I do is just a simple check to make sure that the user is in a group that is allowed to perform these tasks. I also wrap the entire thing in a try/catch just to make my life easier for error catching and display it in a Literal that is in the content of the page (you’ll see later). I have been playing around with ViewManagers lately, and that controls what content is displayed on the page. The content of the page is as follows.
<asp:Content ContentPlaceHolderID="PlaceHolderPageTitle" runat="server">
Web Development Admin Tools - User Audit
</asp:Content>
<asp:Content ContentPlaceHolderID="PlaceHolderMain" runat="server">
<asp:MultiView ID="mvViewManager" runat="server" ActiveViewIndex="0">
<asp:View ID="vNoPerms" runat="server">
<h3>You do not have permissions to view this page!</h3>
</asp:View>
<asp:View ID="vMain" runat="server">
<asp:DropDownList ID="ddlUsers" runat="server" AutoPostBack="true" OnSelectedIndexChanged="findUser"/>
<br/>
<br/>
<asp:Literal ID="litOutput" runat="server"/>
</asp:View>
</asp:MultiView>
<asp:Literal ID="litError" runat="server" Visible="false"/>
</asp:Content>
The litOutput and litError Literals are used for displaying information. The ddlUsers DropDownList is used for displaying a list of all users. As mentioned before, there are two views inside the ViewManager mvViewManager. The first view (index 0) is the default view. If the group evaluation from OnLoad passes, the second view (index 1) is displayed. The rest of this section is pretty self explanatory. Onto the methods that manipulate the DropDownList and output Literal.
protected void runPage()
{
if(Request.HttpMethod != "POST")
{
populateUsers();
}
}
protected void populateUsers()
{
foreach(SPUser user in site.RootWeb.AllUsers)
{
ListItem li = new ListItem();
li.Text = user.Name;
li.Value = user.ID.ToString();
ddlUsers.Items.Add(li);
}
}
protected void findUser(Object sender, EventArgs e)
{
SPUser user = site.RootWeb.AllUsers.GetByID(Convert.ToInt32(ddlUsers.SelectedItem.Value));
litOutput.Text = “”" + user.Name + “” belongs to the following groups:<br/><br/>”;
litOutput.Text += userMembership(user, site.RootWeb, “”);
}
protected string userMembership(SPUser user, SPWeb web, string webPath)
{
StringBuilder retVal = new StringBuilder();
//retVal.AppendFormat(“{0}<br/>”, web.Name == “” ? “Root” : web.Name);
webPath += (webPath == “” ? “” : “/”) + web.Name;
foreach(SPGroup group in web.Groups)
{
try
{
group.Users.GetByID(user.ID);
retVal.AppendFormat(“<b>{0}</b> – <a href=”removeUserFromGroup.aspx?uid={1}&gid={2}&web={3}”>REMOVE</a><br/>”,
group.Name,
user.ID,
group.ID,
webPath);
}
catch { }
}
foreach(SPWeb subweb in web.Webs)
{
retVal.AppendFormat(“{0}”, userMembership(user, subweb, webPath));
}
return retVal.ToString();
}
</script>
The methods we have here are: runPage(), populateUsers(), findUser(Object sender, EventArgs e), and userMembership(SPUser user, SPWeb web, string webPath). I try to keep my methods in the order in which they are called. This makes my life easier when debugging, etc. The first method called is runPage(). It is just a simple starter that does a check to make sure that the page was not a POST. If it was a POST, then someone must have accessed the page incorrectly or someone chose a user from the DropDownList. This avoids duplicate population of the user DropDownList, and improper access of the page. That takes us to populateUsers(). This method uses SPWeb.AllUsers to find all the users in the system and add them to the DropDownList. It makes their name the Text property and their userID the Value property. Notice the DropDownList gets the AutoPostBack property set to True and the OnSelectedIndexChanged property set to the findUser() method. This writes some header information to the output Literal, then kicks off a call to the recursive method userMembership. Using the SPUser object of the user chosen, SPWeb object of the current web in which we’re looking, and a string of the path to the web in which we’re looking, userMembership will traverse all webs and sub-webs in the site collection looking for memberships to groups in those webs. It will return a string that provides the group name and a link to remove that person from the group.
Removing Users from a Group
This page is fairly simple. It takes three GET parameters to determine which SPWeb to use, the SPUser.ID, and SPGroup.ID. The same permissions logic is used to determine if the person should be viewing this page. Then, it also makes sure that the Request.HttpMethod is set to GET. The runPage() method then takes these parameters and removes the user from that group. The code is below the userAudit.aspx code provided.
userAudit.aspx
<%@ Page language="C#"
MasterPageFile="~masterurl/default.master"
SmartNavigation="true"
Inherits="Microsoft.SharePoint.WebPartPages.WebPartPage,
Microsoft.SharePoint,
Version=12.0.0.0,
Culture=neutral,
PublicKeyToken=71e9bce111e9429c"
meta:progid="SharePoint.WebPartPage.Document" %>
<%@ Import Namespace="Microsoft.SharePoint" %>
<script type="text/c#" runat="server">
protected SPSite site;
protected SPWeb web;
protected override void OnLoad(EventArgs e)
{
try
{
site = new SPSite("http://server/");
web = site.OpenWeb("webdev");
SPGroup grpMembers = web.SiteGroups["Website Development Members"];
if(grpMembers.ContainsCurrentUser)
{
mvViewManager.ActiveViewIndex = 1;
runPage();
}
}
catch (Exception err)
{
litError.Visible = true;
litError.Text = err.Message;
}
}
protected void runPage()
{
if(Request.HttpMethod != “POST”)
{
populateUsers();
}
}
protected void populateUsers()
{
foreach(SPUser user in site.RootWeb.AllUsers)
{
ListItem li = new ListItem();
li.Text = user.Name;
li.Value = user.ID.ToString();
ddlUsers.Items.Add(li);
}
}
protected void findUser(Object sender, EventArgs e)
{
SPUser user = site.RootWeb.AllUsers.GetByID(Convert.ToInt32(ddlUsers.SelectedItem.Value));
litOutput.Text = “”" + user.Name + “” belongs to the following groups:<br/><br/>”;
litOutput.Text += userMembership(user, site.RootWeb, “”);
}
protected string userMembership(SPUser user, SPWeb web, string webPath)
{
StringBuilder retVal = new StringBuilder();
//retVal.AppendFormat(“{0}<br/>”, web.Name == “” ? “Root” : web.Name);
webPath += (webPath == “” ? “” : “/”) + web.Name;
foreach(SPGroup group in web.Groups)
{
try
{
group.Users.GetByID(user.ID);
retVal.AppendFormat(“<b>{0}</b> – <a href=”removeUserFromGroup.aspx?uid={1}&gid={2}&web={3}”>REMOVE</a><br/>”,
group.Name,
user.ID,
group.ID,
webPath);
}
catch { }
}
foreach(SPWeb subweb in web.Webs)
{
retVal.AppendFormat(“{0}”, userMembership(user, subweb, webPath));
}
return retVal.ToString();
}
</script>
<asp:Content ContentPlaceHolderID=”PlaceHolderPageTitle” runat=”server”>
Web Development Admin Tools – User Audit
</asp:Content>
<asp:Content ContentPlaceHolderID=”PlaceHolderMain” runat=”server”>
<asp:MultiView ID=”mvViewManager” runat=”server” ActiveViewIndex=”0″>
<asp:View ID=”vNoPerms” runat=”server”>
<h3>You do not have permissions to view this page!</h3>
</asp:View>
<asp:View ID=”vMain” runat=”server”>
<asp:DropDownList ID=”ddlUsers” runat=”server” AutoPostBack=”true” OnSelectedIndexChanged=”findUser”/>
<br/>
<br/>
<asp:Literal ID=”litOutput” runat=”server”/>
</asp:View>
</asp:MultiView>
<asp:Literal ID=”litError” runat=”server” Visible=”false”/>
</asp:Content>
removeUserFromGroup.aspx
<%@ Page language="C#"
MasterPageFile="~masterurl/default.master"
SmartNavigation="true"
Inherits="Microsoft.SharePoint.WebPartPages.WebPartPage,
Microsoft.SharePoint,
Version=12.0.0.0,
Culture=neutral,
PublicKeyToken=71e9bce111e9429c"
meta:progid="SharePoint.WebPartPage.Document" %>
<%@ Import Namespace="Microsoft.SharePoint" %>
<script type="text/c#" runat="server">
protected SPSite site;
protected SPWeb web;
protected override void OnLoad(EventArgs e)
{
try
{
site = new SPSite("http://server/");
web = site.OpenWeb("webdev");
SPGroup grpMembers = web.SiteGroups["Website Development Members"];
if(grpMembers.ContainsCurrentUser && Request.HttpMethod == "GET")
{
mvViewManager.ActiveViewIndex = 1;
runPage();
}
}
catch (Exception err)
{
litError.Visible = true;
litError.Text = err.Message;
}
}
protected void runPage()
{
int uid = Convert.ToInt32(Request.QueryString["uid"]);
int gid = Convert.ToInt32(Request.QueryString["gid"]);
litOutput.Text += uid + " " + gid;
SPWeb thisWeb = site.OpenWeb(Request.QueryString["web"]);
SPGroup group = thisWeb.Groups.GetByID(gid);
SPUser user = site.RootWeb.AllUsers.GetByID(uid);
thisWeb.AllowUnsafeUpdates = true;
thisWeb.Update();
group.Users.RemoveByID(uid);
thisWeb.AllowUnsafeUpdates = false;
thisWeb.Update();
litOutput.Text = """ + user.Name + "" REMOVED FROM: " + group.Name;
}
</script>
<asp:Content ContentPlaceHolderID="PlaceHolderPageTitle" runat="server">
Web Development Admin Tools - Remove User From Group
</asp:Content>
<asp:Content ContentPlaceHolderID="PlaceHolderMain" runat="server">
<asp:MultiView ID="mvViewManager" runat="server" ActiveViewIndex="0">
<asp:View ID="vNoPerms" runat="server">
<h3>You do not have permissions to view this page!</h3>
</asp:View>
<asp:View ID="vMain" runat="server">
<asp:Literal ID="litOutput" runat="server"/>
</asp:View>
</asp:MultiView>
<asp:Literal ID="litError" runat="server" Visible="false"/>
</asp:Content>