SPGroup


To view users in Sharepoint we have to ge to http://servername/_layouts/people.aspx. There we can see all user groups and users added to each group. Remembering this path might be easy for sharepoint developers but what about common users who want to view a report displaying all users, their email id and usergroups?

To do this, we need to do some amount of custom coding…. which is shown below.

protected void Page_Load(object sender, EventArgs e)
{
string siteUrl = SPControl.GetContextSite(Context).Url;
SPSecurity.RunWithElevatedPrivileges(delegate()
{
string Globaltbl = string.Empty;
using (SPSite ospSite = new SPSite(siteUrl))
{
using (SPWeb site = ospSite.OpenWeb())
{
try
{
SPGroupCollection groups = site.SiteGroups;
dtUserTable.Columns.Add(new DataColumn(“Name”, typeof(string)));
dtUserTable.Columns.Add(new DataColumn(“Email”, typeof(string)));
dtUserTable.Columns.Add(new DataColumn(“Group”, typeof(string)));
Globaltbl += “<table width=’100%’ border=’0′ cellpadding=’6′ cellspacing=’4′ >”;
Globaltbl += “<tr><th align=’left’ style=’width:33%; font-family:verdana, Arial ;font-size:11px; color:#000000;’>Name</th><th align=’left’ style=’width:34%; font-family:verdana, Arial ;font-size:11px; color:#000000;’>Email</th><th align=’left’ style=’width:33%; font-family:verdana, Arial ;font-size:11px; color:#000000;’>Group Name</th></tr>”;
foreach (SPGroup grp in groups)
{

if (grp != null)
{
SPUserCollection users = grp.Users;
if (users != null)
{
if (users.Count > 0)
{
foreach (SPUser user in users)
{
Globaltbl += “<tr width=’100%’><td style=’width:33%; font-family:verdana, Arial ;font-size:11px; color:#000000;’>” + user.Name.ToString() + “</td><td style=’width:34%; font-family:verdana, Arial ;font-size:11px; color:#000000;’>” + user.Email.ToString() + “</td><td style=’width:33%; font-family:verdana, Arial ;font-size:11px; color:#000000;’>” + grp.Name.ToString() + “</td></tr>”;
DataRow temprow = dtUserTable.NewRow();
temprow[“Name”] = user.Name.ToString();
temprow[“Email”] = user.Email.ToString();
temprow[“Group”] = grp.Name.ToString();
dtUserTable.Rows.Add(temprow);
temprow = null;
}
}
}
}
}
Globaltbl += “</table>”;
Page.Controls.Add(new LiteralControl(Globaltbl.Trim()));
}
catch (Exception ex)
{
SPUtility.HandleAccessDenied(ex);
}
finally
{
site.Dispose();
ospSite.Dispose();
}
}
}
});
}

This will display the user records on the web page as:

 

 

Name Email Group Name
Gitolekha Ray gitolekha.ray@someplace.com Admin
Charles Dickens charles.dickens@someplace.com Visitor

 

  This will open a web page displaying all users in the system, their name, email address and user group. In case the user profile only contains the user id and not the name, you can write code to fetch it from the LDAP. You can also export the data to excel so that the user finds it easy to view the records.

The below code is only to show, how to export this data to excel, so that the user can view the user details exactly as shown above in excel, so the code to export to excel is shown below:

This will export the user details to excel in exactly the same format as shown above, so that the user finds it easy to search for a user and see which group he belongs to rather than remembering the complicated sharepoint url.

 
 protected void btnExport_Click(object sender, EventArgse)
{

 string defaultFileName = “UsersReport.xls”;
 Response.ClearContent();
 Response.AddHeader(“content-disposition”, “attachment;filename=”+ defaultFileName);
 Response.ContentType = “application/excel”;
 this.EnableViewState = false;
 Response.Charset = “”;
 StringWriter sw = new StringWriter();
 HtmlTextWriter hw = new HtmlTextWriter(sw);
}

 
public string CreateExcelFile(DataTable dt)
{
 SPSite site = SPContext.Current.Site;
 SPWeb web = site.OpenWeb();
 string sTableStart = “<HTML><BODY><TABLE Border=1>”;
 string sTableEnd = “</TABLE></BODY></HTML>”;
 string sTHead = “<TR>”;
 StringBuilder sTableData = new StringBuilder();
  try
  {

  sTHead += “<th scope=’col’>Name</th><th scope=’col’>Email</th><th scope=’col’>Group   Name</th></tr>”;
    foreach (DataRow row in dt.Rows)
    {
 sTableData.Append(“<TR>”);
 sTableData.Append(“<TD>” + row[“Name”] + “</TD>”);
 sTableData.Append(“<TD>” + row[“Email”] + “</TD>”);
 sTableData.Append(“<TD>” + row[“Group”] + “</TD>”);
  sTableData.Append(“</TR>”);
    }
  }
  catch (Exception ex)
  {
 throw ex;
  }
  finally
  {
 site.Close();
 site.Dispose();
 web.Close();
 web.Dispose();
  }
  string sTable = sTableStart + sTHead + sTableData.ToString() + sTableEnd;
  return sTable;
}

This will open the excel file in exactly the same format as the web page appears.

I was getting the Access Denied page when I tried to access the UsersCollection of a SPGroup Instance or SiteGroups of SPWeb object.
I used RunWithElevatedPrivileges to be able to access the users collection but all in vein.
After searching through the net, I found that all code should be inside elevated priviledge, because if we access SiteGroups from a SPWeb object that was created prior to using elevated priviledge, the problem would still sustain.

So, I changed my code to define the objects inside elevated priviledges like:

SPSecurity.SPWeb (delegate()
{       SPSite ospSite = SPContext.Current.Site;
        SPWeb site = ospSite.OpenWeb();
……code to access users
}

The code was still giving errors because Context, SPContext or SPControl.GetWebContext, etc. cannot be used inside elevated privileges. The reason is that Context object is created before the code with elevated privileges is executed.

So, the change will be:

 string siteUrl = SPControl.GetContextSite(Context).Url;
        SPSecurity.RunWithElevatedPrivileges(delegate()
  {
        string Globaltbl = string.Empty;
        using (SPSite ospSite = new SPSite(siteUrl))
        {
            using (SPWeb oWeb = ospSite.OpenWeb())
            {
                    SPGroupCollection groups = oWeb.SiteGroups;  
                    foreach (SPGroup grp in groups)
                    {
                        SPUserCollection users = grp.Users;
                        if (users != null)
                        {
                            foreach (SPUser user in users)
                            {
                                //MyCode//
                            }
                        }
                    }
}
}
});

And Voila! everything works just fine.