Friday, December 13, 2013

How to Add User to Default SharePoint Groups Programatically

As every SharePoint developer or user know that when a new Site is created, Obviously 3 commonly used site specific groups will be created automatically along with some general groups.
<Site Name> Owners
<Site Name> Members
<Site Name> Visitors

To add an user to any of the above three groups of a site, we have a API method to get the groups associated with that site, programatically.
using (SPSite site = new SPSite("http://siteurl"))
{
    using (SPWeb web = site.RootWeb)
    {
        ////Get the site default groups
        SPGroup owernsGroup = web.AssociatedOwnerGroup;
        SPGroup membersGroup = web.AssociatedMemberGroup;
        SPGroup visitorsGroup = web.AssociatedVisitorGroup;

        ////Add user to groups
        SPUser user = web.EnsureUser("login");
        if (null != user)
        {
            owernsGroup.AddUser(user);
            membersGroup.AddUser(user);
            visitorsGroup.AddUser(user);
        }
    }
}

Also we can add user to other default groups like Approvers, Designers and Viewers etc., But there is no API property for web to get these groups. So we can get the group by Name.
if (web.GroupExists("Approvers"))
{
    ////Get approvers group
    SPGroup approversGroup = web.Groups["Approvers"];            
    if (null != approversGroup)
    {
        ////Add user to group
        SPUser user = web.EnsureUser("login");
        approversGroup.AddUser(user);
    }
}

Check User exists in SharePoint Group

I was looking for direct API method to check whether specified user exists in SharePoint group. Unfortunately there is no direct API check.

I found below single statement is efficient for this check. I made it a generic for re-usability.

SPGroup spGroup = web.Groups["Group Name"];
if (null != spGroup)
{
  SPUser spUser = web.EnsureUser("Login Account");
  if (null != spUser)
  {
    bool userExsists = spUser.Groups.Cast<SPGroup>().Any(g => g.Name.ToLower() == spGroup.Name.ToLower());
     if (!userExsists)
     {
        spGroup.AddUser(spUser);
     }
  }
}