Blog Archive

Tuesday, November 23, 2010

Adding a SPUser to SharePoint Group

For adding a SharePoint user to a particular SharePoint group
following code can be useful.



SPSecurity.RunWithElevatedPrivileges(delegate()
{
    using (SPSite site = new SPSite(siteURL))
    {
      using (SPWeb web = site.OpenWeb())
      {
        Microsoft.SharePoint.Administration.SPWebApplication webApp = 
        web.Site.WebApplication;
        webApp.FormDigestSettings.Enabled = false;

        web.AllowUnsafeUpdates = true;
       //Assign role and add user to site
       SPGroupCollection groupColl = web.SiteGroups;
       if (GroupExists(groupColl, GroupName))
       {
         //Add the user to a group.
         SPGroup roleGroup = web.SiteGroups[GroupName];
         using (SPSite newSite = new SPSite(baseSiteURL))
         {
           using (SPWeb newWeb = newSite.OpenWeb())
           {
               reply = addUserToGroup(newWeb, roleGroup,
               userName, firstName, lastName, userEmailId);
            }
         }
       }
       else
       {
         reply = false;
       }
       web.Update();
       webApp.FormDigestSettings.Enabled = true;
    }
  }
 });

Another private method we have to write here.

private bool addUserToGroup(SPWeb web, SPGroup group, 
string userName, string FirstName, string LastName, string userEmail)
{
  bool updateFlag = false;
  try
  {
    //Make Allow unsafe updates true so that security problem should not come.
    web.AllowUnsafeUpdates = true;
    group.AddUser(userName, userEmail, FirstName, "Automatically Added User");
    group.Update();
    web.Update();
    updateFlag = true;
  }
  catch (Exception ex)
  {
     updateFlag = false; 
     throw ex;
  }
}

No comments:

Post a Comment