2
votes

I am using the SharePoint Object Model to create new sites programmatically (with a custom web part). It works fine but I am wondering if it is possible to grant permission for groups as well?

When I create the site I have set it to not inherit permission

newWeb = SPContext.GetContext(HttpContext.Current).Web.Webs.Add(siteUrl, siteName, siteDescription, (uint)1033, siteTemplate, true, false);

In the GUI I can then go to Site Actions (on the newly created site) -> Grant Permission -> search for groups in the parent site and then grant permission for this group. So, in the parent site myGroup can have Full Access permissions but in this site I can set it to Contribution or whatever. Is it possible to do this when I create the site or just after (programmatically)?

Thanks in advance.

1

1 Answers

2
votes

You must assign a role definition to your group.

Here's a code snippet I wrote to assign a group one of the predefined sharepoint role definitions.

public bool AssignExistingGroupToWeb(SPWeb siteWeb, string GroupName, SPRoleDefinition roleDefinition)
{
//retrieve a group
SPGroup siteGroup = siteWeb.SiteGroups.FindGroupByName(GroupName);

//create a role assignment for the group using the specified SPRoleDefinition
//examples of roles as "Full Control", "Design", etc...
SPRoleAssignment roleAssignment = new SPRoleAssignment(siteGroup);
roleAssignment.RoleDefinitionBindings.Add(roleDefinition);
siteWeb.RoleAssignments.Add(roleAssignment);
siteWeb.Update();
}

You can retrieve a SPRoleDefinition by accessing the RoleDefinitions collection, like so...

siteWeb.RoleDefinitions["Contribute"]