Sunday, December 28, 2008

Assigning permission programatically

Windows SharePoint Services manages permissions through role definations. SPRoleDefinition and SPRoleDefinition classes provides methods to assign users to roles. Following code snippet shows how to assign the Contributor role to a custom SharePoint group programatically:

using (SPSite site = new SPSite(siteCollection))
{
using (SPWeb subWeb = site.OpenWeb(siteName))
{
//You need to break role inheritence if you want to assign unique permission to subsite
if (!subWeb.HasUniqueRoleAssignments)
subWeb.BreakRoleInheritance(true);
SPRoleDefinition roleDefination = parentWeb.RoleDefinitions["Contrubute"];
SPRoleAssignment roleAssignment = new SPRoleAssignment("MyCustomerGroup");
roleAssignment.RoleDefinitionBindings.Add(roleDefination);
subWeb.RoleAssignments.Add(roleAssignment);
subWeb.Update();
}
}


Users or Groups can be assigned permission to List or Document library or list item. Following code shows assigning permission on Folder of a document library for a custom sharepoint group:


using (SPSite site = new SPSite(siteCollection))
{
using (SPWeb web = site.OpenWeb(siteName))
{
SPDocumentLibrary docLib = (SPDocumentLibrary)web.Lists[libraryName];
//Get folder
SPListItem item = docLib.Folders[1];
if (!item.HasUniqueRoleAssignments)
item.BreakRoleInheritance(true);
SPRoleAssignment roleAssignment = new SPRoleAssignment(group);
SPRoleDefinition roleDefination = web.RoleDefinitions["Contribute"];
roleAssignment.RoleDefinitionBindings.Add(roleDefination);
item.RoleAssignments.Add(roleAssignment);
item.Update();
}
}

3 comments:

Phil Wicklund said...

Have you done this with AD groups? Any different? For some reason I can't get it to work with AD groups - get an invalid character (\) error.

Nick said...

Use 'domain\\username' instead of 'domain\username'. it works for me.

Anonymous said...

I am getting the following error message

Value does not fall within the expected range.