Many posts are about breaking role inheritance on item level or remove the item permissions, but what can you do if you want to change them to only read permission on special items? For a special item if you break the role inheritance the permissions stay as parent or they will be removed. I wrote a small script which does not remove the permissions on the item but change all permissions to read. The great thing is, that all users which had permissions to delete, edit or read will now have only read permissions.
Let’s have a look at the code.
[sourcecode language=”csharp”]
//break roleinheritance
currentItem.BreakRoleInheritance(true);
//set a roledefinition to read
SPRoleDefinition roleDef = SPContext.Current.Web.RoleDefinitions.GetByType(SPRoleType.Reader);
//for this item, read all role assignments
SPRoleAssignmentCollection SPRoleAssColn = currentItem.RoleAssignments;
for (int i = 0; i < SPRoleAssColn.Count; i++)
{
//and read for each role assignment the role definitions
foreach (SPRoleDefinition currentRoleDef in SPRoleAssColn[i].RoleDefinitionBindings)
{
//if roledefinition is not read, then add roledef with read and delete the current roledefinition
if (currentRoleDef.Type != SPRoleType.Reader)
{
SPRoleAssignment newAssignment = new SPRoleAssignment(SPRoleAssColn[i].Member);
newAssignment.RoleDefinitionBindings.Add(roleDef);
currentItem.RoleAssignments.Add(newAssignment);
currentItem.Update();
//Now remove the current role definition
SPRoleAssColn[i].RoleDefinitionBindings.Remove(currentRoleDef);
SPRoleAssColn[i].Update();
}
}
}
[/sourcecode]
The script is easy. At first we iterate through all role assignments (e.g. Members). In each role assignment we iterate through the role definition like Read, Full Control, Design, Contribute. If the current role definition in this role assignment is not read, we add read and remove the current role definition. Important is to set the currentItem.BreakRoleInheritance(true) to true, cause if you set it to false, it will remove every role assignment.
The result is that each user and each group will have only read permissions and of course limited access which is automatically added.
Hope this helps you anytime.
..:: I LIKE SHAREPOINT ::..