Probably you know that the permission levels for a specific group can be displayed on the SharePoint UI when selecting View Group Permissions from the group Settings menu.
A sample below shows a typical result displayed on the page.
It would be however nice to achieve the same data from a custom application as well.
The data above is presented through the /_layouts/ViewGroupPermissions.aspx page, by private CreateDataTable method of the Microsoft.SharePoint.WebControls.GroupPermissions control (Microsoft.SharePoint assembly). This method calls the proc_SecGetGroupSecurityScopes stored procedure in the content database and returns the results as a DataTable with two columns: ScopeUrl contains the URL of the resource embedded into HTML text, and Role is the Permission Level (see private AddRow method of the GroupPermissions class.
To be able to invoke the CreateDataTable method vie Reflection without receiving a NullReferenceException, we should inject an SPContext (see implementation details here), and a dummy Page object (as it is being referenced in the AddRow method). Having these two objects, the call itself is rather simple. We should cast the result object to DataTable, iterate through its Rows collection and parse the URL from the HTML text using a Regex in the ScopeUrl column of the DataTable.
- using (SPSite site = new SPSite("http://intranet.contoso.com"))
- {
- using (SPWeb web = site.OpenWeb())
- {
- // inject fake context
- HttpRequest request = new HttpRequest(string.Empty, web.Url, string.Empty);
- HttpResponse response = new HttpResponse(new System.IO.StreamWriter(new System.IO.MemoryStream()));
- HttpContext dummyContext = new HttpContext(request, response);
- dummyContext.Items["HttpHandlerSPWeb"] = web;
- HttpContext.Current = dummyContext;
- var groupPermissions = new GroupPermissions();
- // set your group here
- int groupId = web.SiteGroups["Team Site Owners"].ID;
- groupPermissions.GroupId = groupId;
- // set dummy Page
- groupPermissions.Page = new Page();
- // invoke private CreateDataTable method
- var groupPermissionsType = groupPermissions.GetType();
- var mi_CreateDataTable = groupPermissionsType.GetMethod("CreateDataTable", BindingFlags.NonPublic | BindingFlags.Instance);
- DataTable results = mi_CreateDataTable.Invoke(groupPermissions, null) as DataTable;
- // process results
- if (results != null)
- {
- foreach (DataRow row in results.Rows)
- {
- string rawScopeUrl = row["ScopeUrl"] as string;
- string scopeUrl = rawScopeUrl;
- string regExpPattern = "<span dir=\"ltr\">(?<scopeUrl>.*?)</span>";
- Regex regex = new Regex(regExpPattern);
- Match match = regex.Match(rawScopeUrl);
- if (match.Success)
- {
- scopeUrl = match.Groups["scopeUrl"].Value;
- }
- Console.WriteLine("[{0}] – [{1}]", scopeUrl, row["Role"]);
- }
- }
- }
- }
And the output:
That is the C# implementation. In my next post I try to achieve the same using PowerShell.
