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.
Leave a comment