Thursday, 26 July 2012

Assigning permission programmatically for site collectin and its sub site item sharepoint 2010 code sp 2010

How to Assigning permission programmatically / dynamically to site collection or its sub site in sharepoint 2007 / 2010 ( SP 2010 ) code

Windows SharePoint 2010 / 2007 (SP 2010) Service manages permissions through Roles and Responsibilities. SPRoleDefinition and SPRoleDefinition classes provides methods to assign users to roles such as “Contributor” or “Site Owner” or “Reader

Sample solution code:

Following code demonstrate how to assign / access  “Reader” to custom SharePoint group “customgroup” programmatically / dynamically by code class method and access the site collection and its sub sites as “reader” permission in sp2010.


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["Reader"];
    SPRoleAssignment roleAssignment = new SPRoleAssignment("customgroup");
    roleAssignment.RoleDefinitionBindings.Add(roleDefination);
    subWeb.RoleAssignments.Add(roleAssignment);
    subWeb.Update();
  }
}

No comments:

Post a Comment