Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to programmatically determine the 3 permission groups Visitors/Members/Owners for a web in SharePoint?

In SharePoint, we have the 3 predetermined permission groups:

  • Visitors
  • Members
  • Owners

As setup in the /_layouts/permsetup.aspx page.

(Site settings->People and Groups->Settings->Setup groups)

How can a get these group names programmatically?

(The page logic is obfuscated by Microsoft, so no can do in Reflector)

like image 261
Magnus Johansson Avatar asked Nov 30 '22 11:11

Magnus Johansson


2 Answers

There are properties on the SPWeb class:

  • SPWeb.AssociatedVisitorGroup
  • SPWeb.AssociatedMemberGroup
  • SPWeb.AssociatedOwnerGroup

http://msdn.microsoft.com/en-us/library/microsoft.sharepoint.spweb.associatedmembergroup.aspx

like image 68
DJ. Avatar answered Dec 04 '22 05:12

DJ.


I've found the various "Associated..." properties to often be NULL. The only reliable way is to use the property bag on the SPWeb:

  • Visitors: vti_associatevisitorgroup
  • Members: vti_associatemembergroup
  • Owners: vti_associateownergroup

To convert them to an SPGroup object, you could use:

int idOfGroup = Convert.ToInt32(web.Properties["vti_associatemembergroup"]);
SPGroup group = web.SiteGroups.GetByID(idOfGroup);

However as Kevin mentions, the associations may be lost which would throw exceptions in the above code. A better approach is to:

  1. Check that associations have been set on the web by ensuring the property you are looking for actually exists.

  2. Check that the group with ID given by the property actually exists. Remove the call to SiteGroups.GetByID and instead loop through each SPGroup in SiteGroups looking for the ID.

The more robust solution:

public static SPGroup GetMembersGroup(SPWeb web)
{
    if (web.Properties["vti_associatemembergroup"] != null)
    {
        string idOfMemberGroup = web.Properties["vti_associatemembergroup"];
        int memberGroupId = Convert.ToInt32(idOfMemberGroup);

        foreach (SPGroup group in web.SiteGroups)
        {
            if (group.ID == memberGroupId)
            {
                return group;
            }
        }
    }
    return null;
}
like image 41
Alex Angas Avatar answered Dec 04 '22 03:12

Alex Angas