Tuesday, July 3, 2007

Removing User Permissions From a List Item

Programmatically modifying the item-level permissions in a list involves manipulation of the Role Assignments collection for that item.

This example shows how to remove a specific role definition from each of the members of a user collection:
   /// <summary>
        /// Remove a role definition from each of the members of a user collection for a list item
        /// </summary>
        /// <param name="item">The List Item</param>
        /// <param name="userVals">The collection of users who are to have the role definition removed</param>
        /// <param name="def">The role definition to remove</param>
        
internal static void RemoveRoleDefinitionFromUsers(SPListItem item, SPFieldUserValueCollection userVals, SPRoleDefinition def)
        {
            
if (userVals != null)
            {
                
foreach (SPFieldUserValue userVal in userVals)
                {
                    SPUser user 
userVal.User;
                    
SPRoleAssignment role item.RoleAssignments.GetAssignmentByPrincipal((SPPrincipal)user);
                    if 
(role != null)
                    {
                        
if (role.RoleDefinitionBindings.Contains(def))
                        {
                            role.RoleDefinitionBindings.Remove(def)
;
                            
role.Update();
                            
item.SystemUpdate(false);
                        
}
                    }
                }
            }
        }

No comments: