Thursday, 24 January 2013

Remove All the User Permissions from SPListItem except current user and admin users

We have and event handler to edit the permission as soon as user create a item in splist .

Following method will take the splist item and spweb . Run the following code in Elevated privilege because user might not have permission to edit the permission on a list item


public static void ChangeUserList(SPListItem objSpListItem, SPWeb objWeb, SPUser objSpCurrentUser)
        {
            // Add the current user to role assignment
            objSpListItem.RoleAssignments.Add(GetNewSPRoleAssignment(objWeb.RoleDefinitions.GetByType(SPRoleType.Contributor), (SPPrincipal)objSpCurrentUser));
            for (int i = 0; i < objSpListItem.RoleAssignments.Count; i++)
            {
                    // Check if the role assignment is for Admin user
                    if (!objSpListItem.RoleAssignments[i].RoleDefinitionBindings.Contains(objWeb.RoleDefinitions.GetByType(SPRoleType.Administrator)))
                        objSpListItem.RoleAssignments.Remove(i);
                    i = i - 1;
            }
        }

Following method retrun the role assignment for the respective principal

        public static SPRoleAssignment GetNewSPRoleAssignment(SPRoleDefinition objSPRoleDefinition, SPPrincipal objPrincipal)
        {
            SPRoleAssignment objSPRoleAssignment = new SPRoleAssignment(objPrincipal);
            objSPRoleAssignment.RoleDefinitionBindings.Add(objSPRoleDefinition);
            return objSPRoleAssignment;
        }