Archive for January, 2011

Tree view of all users on a site

Wednesday, January 19th, 2011

Here is a nice little web part I made to show all users and groups in a site and all subsites of a site collection. You can of course modify this to show only those users and groups from the current site and down but I elected to show from the parent site and down.

public class THISCLASS : WebPart
{
protected override void CreateChildControls()
{
try
{

SPSite spSite = SPContext.Current.Site;
SPSecurity.RunWithElevatedPrivileges(delegate()
{

// set the tree view properties
TreeView treeView = new System.Web.UI.WebControls.TreeView();
treeView.ShowLines = true; // show lines
treeView.ExpandDepth = 1;

using (SPSite oSite = new SPSite(spSite.Url))
{

//SPWebCollection collWebsites = oSite.AllWebs;
SPWeb thew = oSite.RootWeb;

TreeNode vsNode = new TreeNode(thew.Title.ToString(), null, null, thew.Url, “_self”);
treeView.Nodes.Add(vsNode);
LoadGroupsAndUsers(thew, vsNode);

foreach (SPWeb siteCol in thew.Webs)
{
TreeNode siteColNode = new TreeNode(siteCol.Title.ToString(), null, null, siteCol.Url, “_self”);
vsNode.ChildNodes.Add(siteColNode);
LoadGroupsAndUsers(siteCol, siteColNode);
LoadTreeViewForSubWebs(siteCol, siteColNode);
siteCol.Dispose();
}
}

this.Controls.Add(treeView);
});
}
catch (Exception e)
{

HtmlTable table = new HtmlTable();
HtmlTableRow row = new HtmlTableRow();
table.Rows.Add(row);
HtmlTableCell cell1 = new HtmlTableCell();
row.Cells.Add(cell1);
Label thelabel = new Label();
thelabel.Text = (e.ToString());
cell1.Controls.Add(thelabel);
this.Controls.Add(table);
}
// this.Controls.Add(node);
}

private void LoadTreeViewForSubWebs(SPWeb currentWeb, TreeNode currentNode)
{
SPSecurity.RunWithElevatedPrivileges(delegate()
{
foreach (SPWeb web in currentWeb.Webs)
{
TreeNode webNode = new TreeNode(web.Title.ToString(), null, null, web.Url, “_self”);
currentNode.ChildNodes.Add(webNode);

LoadGroupsAndUsers(web, webNode);

if (web.Webs != null && web.Webs.Count > 0)
{
LoadTreeViewForSubWebs(web, webNode);
web.Dispose();
}
}
});
}

private void LoadGroupsAndUsers(SPWeb currentWeb, TreeNode currentNode)
{
SPSecurity.RunWithElevatedPrivileges(delegate()
{
foreach (SPGroup thegroups in currentWeb.Groups)
{
TreeNode gnode = new TreeNode(thegroups.Name.ToString());
currentNode.ChildNodes.Add(gnode);

foreach (SPUser theusers in thegroups.Users)
{
//string theurl = null;
string theurl = currentWeb.Url + “/_layouts/userdisp.aspx?” + theusers.ID.ToString();
TreeNode theuser = new TreeNode(theusers.Name.ToString(), null, null, theurl,”_self”);
gnode.ChildNodes.Add(theuser);
}
}
});
}

}