Wednesday, January 12, 2011

Programmatically adding SPuser to SPgroup

try
{
SPSecurity.RunWithElevatedPrivileges(delegate()
{
using (SPSite spSiteTemp = new SPSite(SPContext.Current.Web.Url))
  using (SPWeb spWebTemp = spSiteTemp.OpenWeb())
  {
    spWebTemp.AllowUnsafeUpdates = true;

   SPGroup spGroup = spWebTemp.SiteGroups["MySPGroup"];

        SPUser spUser = spWebTemp.EnsureUser
("DomainName\" + msUser.UserName); 
 
//Adding group  to check SPUser's existing group. 
ArrayList arrayListGroups = new ArrayList();
      foreach (SPGroup tempGroup in spUser.Groups)
      {
        arrayListGroups.Add(tempGroup.Name.ToLower());
      }

       if ((spUser.Groups.Count < 1) 
        || ((spUser.Groups.Count > 1) 
        && (!arrayListGroups.Contains("myspgroup"))))
       {
         spGroup.AddUser(spUser);
       }

          spWebTemp.AllowUnsafeUpdates = false;
        }
    });
}
catch (SPException)
{
     throw;
}

No comments:


A sales engineer is someone who promise you a bridge, even when there's no river.