Sayfalar

21 Mart 2012 Çarşamba

Adding and Deleting Role From SPList and SPListItem

When you create a list on sharepoint,It will inherite all permission from paren web. If you want to edit it's permission you must breake role inheritance then add new role. Permission relation between list and parent web is same as list item and list.
Code

Extension For List Item

public static class ExtensionForListItem
{
 public static void DeleteAllRoleAssigments(this SPListItem splistItem)
    {
        if (!splistItem.HasUniqueRoleAssignments)
        {
            splistItem.BreakRoleInheritance(true);
        }
        for (int i = splistItem.RoleAssignments.Count - 1; i >= 0; i--)
        {
            SPRoleAssignment assignment = splistItem.RoleAssignments[i];
            splistItem.RoleAssignments.Remove(assignment.Member);
        }
    }
  public static void AddRole(this SPListItem listItem, SPRoleType RoleType, params SPPrincipal[] RoleOwner)
    {
       SPRoleDefinition contributorRoleDefinition= listItem.ParentList.ParentWeb.RoleDefinitions.GetByType  (RoleType);
        foreach (var item in RoleOwner)
        {
            SPRoleAssignment roleAssignment = new SPRoleAssignment(item);
            roleAssignment.RoleDefinitionBindings.Add(contributorRoleDefinition);
            listItem.RoleAssignments.Add(roleAssignment);
        }
    }
}

Extension For List 
public static class ExtensionForList
{
 public static void DeleteAllRoleAssigments(this SPList dList)
    {
        if (!dList.HasUniqueRoleAssignments)
        {
            dList.BreakRoleInheritance(true);
        }
        for (int i = dList.RoleAssignments.Count - 1; i >= 0; i--)
        {
            SPRoleAssignment assignment = dList.RoleAssignments[i];
            dList.RoleAssignments.Remove(assignment.Member);
        }
    }
 public static void AddRole(this SPList list, SPRoleType RoleType, params SPPrincipal[] RoleOwner)
    {
        SPRoleDefinition contributorRoleDefinition = list.ParentWeb.RoleDefinitions.GetByType(RoleType);
        foreach (var item in RoleOwner)
        {
            SPRoleAssignment roleAssignment = new SPRoleAssignment(item);
            roleAssignment.RoleDefinitionBindings.Add(contributorRoleDefinition);
            list.RoleAssignments.Add(roleAssignment);
        }
    }
}

Hiç yorum yok:

Yorum Gönder