How to programmatically add Role Permission to a Role Definition in SharePoint

Ashok Raja
 
Solutions Architect
August 25, 2013
 
Rate this article
 
Views
1193

The below code enables you to add specific SharePoint role permission to a role definition. A set of predefined SharePoint groups will be automatically created in a SharePoint site while its created. These groups would be set with contribute, approve , view only permission types (role definition) depending on the user group. If you would like to add a new role permission o the pre-defined role definition use the below to perform it via code.

Code

 public void AddRolePermission(SPWeb web, string RoleName, string RoleItemName)
 {
     bool tempFlag = web.AllowUnsafeUpdates;
     web.AllowUnsafeUpdates = true;
     SPRoleDefinition roleDef = web.RoleDefinitions[RoleName];
     SPBasePermissions perm = roleDef.BasePermissions;
     perm = perm | (SPBasePermissions)Enum.Parse(perm.GetType(), RoleItemName);
     roleDef.BasePermissions = perm;
     roleDef.Update();
     web.Update();
     web.AllowUnsafeUpdates = tempFlag;
 }

How to Use

 using (SPSite site = new SPSite("[Server URL]"))
 {
     using (SPWeb web = site.OpenWeb())
     {
         AddRolePermission(web, "Contribute", "ApproveItems");
     }
 }
Note : The above code adds the “Approve Items” permission to “Contribute” role definition.
Category : Tips

Author Info

Ashok Raja
 
Solutions Architect
 
Rate this article
 
I am Ashok Raja, Share Point Consultant and Architect based out of Chennai, India. ...read more
 

Leave a comment