Hello,
We had a requirement like when one of the sub site gets created, permission inheritance should be broken and new group with specific permission level should be added.
Here I will discuss the steps to break the inheritance and adding custom SharePoint group with custom permission level. We write one feature and included in our custom site definition for the given sub site. We did our code in FeatureActivated event.
1. Allow unsafe update on the web, this can be done as follows:
-
- SPWeb web = properties.Feature.Parent as SPWeb;
-
-
- bool allowunsafeupdate = web.AllowUnsafeUpdates;
-
-
- web.AllowUnsafeUpdates = true;
2. Break the inheritance permission, this can be done by calling BreakRoleInheritance() method as follows:
-
- web.BreakRoleInheritance(false);
Reference: SPWeb.BreakRoleInheritance method.
The false argument indicates not to copy the roles assignment from parent object.
Now to add the group to current web, there is a property AssociatedGroups which returns list of SPGroup instance and then using Add() method we can add the group. This Add() method requires instance of SPGroup.
So to get the instance of SPGroup which we need to add, we need to go through the each group for root web(or parent web) and compare with which we need to add like as follows:
-
- string myCustomGroupName = “MyCustomGroupName”;
-
-
- IList<SPGroup> associatedGroups = web.Site.RootWeb.AssociatedGroups;
-
-
- SPGroup myCustomGroup = null;
-
-
- foreach(SPGroup group in associatedGroups){
-
-
-
- if(group.Name.Equals(myCustomGroupName, StringComparison.InvariantCultureIgnoreCase)){
- myCustomGroup = group;
- break;
- }
- }
-
- if(myCustomGroup!= null){
-
- web.AssociatedGroups.Add(myCustomGroup);
- }
Now to assign the custom permission level to my custom group.
-
- SPRoleDefinition customPermissionRole = web.RoleDefinitions["CustomPermission", web.Site.RootWeb)];
-
-
- SPRoleAssignment customRoleAssignment = new SPRoleAssignment(myCustomGroup);
-
-
- customRoleAssignment.RoleDefinitionBindings.Add(customPermissionRole);
-
- web.RoleAssignments.Add(customRoleAssignment);
3. Update the web and reset the AllowUnsafeUpdates property.
- web.Update();
- web.AllowUnsafeUpdates = allowunsafeupdate;
Any comments / suggestions are welcome.
Hope this will help you! Enjoy reading!
Thanks!