Archive for October, 2014

Change SharePoint list item permissions to Read only programmatically

It’s a simple task but keeps slipping my mind, so I though it’s better to save it in the public diary.

So I have a Projects and Tasks master detail lists. When a project is complete, it should become read only together with all its tasks. If it was for only the Project list, I could use the SharePoint designer workflow to change the item permissions.

My projects and tasks lists have ‘Contribute’ and a custom permissions level called ‘Contribute without delete’ assigned to multiple¬†user groups. And I wanted to change all the Contribute access to Read ¬†access upon completion of the project.

Here’s the function I wrote,

public void MakeItemReadonly(SPWeb web, SPListItem item, string permissionToReplace, bool exactMatchOnly)
        {
            List<SPPrincipal> principals = new List<SPPrincipal>();
            foreach (SPRoleAssignment roleAss in item.RoleAssignments)
            {
                foreach (SPRoleDefinition roleDef in roleAss.RoleDefinitionBindings)
                {
                    // condition based on the flag exactMatchOnly 
                    if ((exactMatchOnly?string.Compare(roleDef.Name,permissionToReplace,true)==0: roleDef.Name.Contains(permissionToReplace)))
                        principals.Add(roleAss.Member);
                }

            }

            SPRoleAssignment assignment;
            item.BreakRoleInheritance(true);
            SPRoleDefinition role = web.RoleDefinitions.GetByType(SPRoleType.Reader);
            foreach (SPPrincipal principal in principals)
            {
                // remove the role assignment 
                item.RoleAssignments.Remove(principal);

                // Now add the read role to the same principal 
                assignment = new SPRoleAssignment(principal);
                assignment.RoleDefinitionBindings.Add(role);
                item.RoleAssignments.Add(assignment);
            }
        }

And called the above function the following way,

MakeItemReadonly(web, listItem, "Contribute", false);
Advertisements

Leave a comment