Wednesday, January 14, 2009

Programatically adding a sharepoint group and RoleAssignment

Scenario:
Dont ask me why but I was asked to create sharepoint group programatically. Also on top of it attach that group to a particular Roledefinition (i.e "Members" )

Solution:
Object Model , my favorite

Code:

 private void AddGroup(SPWeb web, string GroupName, SPUser groupOwner, string GroupDescription, string roleDefinitionName)
{
SPGroup oGroup = GetSiteGroup(web, GroupName);

if (oGroup == null)
{
web.SiteGroups.Add(GroupName, groupOwner, null, GroupDescription);
oGroup = GetSiteGroup(web, GroupName);
}

// Create the role assignment object
SPRoleAssignment oRoleAssignment = new SPRoleAssignment(oGroup);

// Add the role definition to the role assignemnt.
// This will assign the specific permission to the security principal for this role assignemnt.
oRoleAssignment.RoleDefinitionBindings.Add(web.RoleDefinitions[roleDefinitionName)]);

// Now we need to add the role assignment to the web
web.RoleAssignments.Add(oRoleAssignment);

// Now update the web
web.Update();
}

private SPGroup GetSiteGroup(SPWeb web, string name)
{
foreach (SPGroup group in web.SiteGroups)
if (group.Name.ToLower() == name.ToLower())
return group;

return null;
}
Article:

0 comments: