Thursday, October 8, 2009

Code to add SPUser in SPGroup

Following code snippet demonstrate the way to programmatically add SPUser in 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 name in temporary arraylist 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;
}


2 comments:

Jamil Haddadin said...

Change it to this ( >0 not >1))

//1- Check if the user is valid sharepoint user
SPUser user = null;
try
{
user = group.ParentWeb.EnsureUser(fullUserName);
}
catch
{
//TODO: Log an issue about this user!
}

if (user != null)
{
//2- Check the user is not already member of the group ( if yes, remove him )
List groupNames = new List();
foreach (SPGroup userGroup in user.Groups)
{
groupNames.Add(userGroup.Name.ToLower());
}

if ((user.Groups.Count < 1)
|| (user.Groups.Count > 0
&& !groupNames.Contains(group.Name)))
{
group.AddUser(user);
}
}

Anonymous said...

Can we add custom metadata to SPGroups. E.g. I have a requirement to add what type the group belongs to say CategoryA, CategoryB etc.
Any input on this will be apprecaited

Google