Remove permissions from list item programmatically

Hi,

I have a custom list which inherits the permission from the site. When a list item is added, I would like to remove the permissions and provide permission to the user who created the request. There are more than 1000 users who have access to the site, and which is inherited by the list item.

I have used this code, but it takes a longer time to get executed. Is the below method correct? Is there any other approach which should be used.

 public static void RemoveAllPermissions(SPListItem CurrentlistItem)
        {
                         CurrentlistItem.BreakRoleInheritance(true);
SPRoleAssignmentCollection SPRoleAssColn = CurrentlistItem.RoleAssignments;

while (CurrentlistItem.RoleAssignments.Count > 0)
  {
 CurrentlistItem.RoleAssignments.Remove(0);
 ReloadListItem(CurrentlistItem);

  using (DisabledItemEventsScope scope = new DisabledItemEventsScope())
  {
       CurrentlistItem.Update();
   }
 }
}

public static SPListItem ReloadListItem(SPListItem item)
{
 if (item == null)
 return null;
return item.ParentList.GetItemByUniqueId(item.UniqueId);
}


public class DisabledItemEventsScope : SPItemEventReceiver, IDisposable
    {
        bool oldValue;
        public DisabledItemEventsScope()
        {
            this.oldValue = base.EventFiringEnabled;
            base.EventFiringEnabled = false;
        }
       
        public void Dispose()
        {
            base.EventFiringEnabled = oldValue;
        }

    }

How to optimize the code? Is the above code correct?

Thanks

April 28th, 2015 2:20pm

ITEM LEVEL PERMISSIONS... ESPECIALLY FOR LARGE LISTS... IS A BAD DESIGN

more reading: http://www.sbrickey.com/Tech/Blog/Post/AntiPattern_User_Based_Item_Level_Securi

April 28th, 2015 4:56pm

HI,

Thanks for the reply.

I agree on that, but depending on the business needs Item level security is required.

I am not sure, how to optimize the above code logic.

Thanks

April 30th, 2015 1:25am

Hi,

May I know, what are you trying to achieve with this code?

If you are trying to give access to an item to only the person who created it (an remove others), then you can try using the ReadSecuirty or WriteSecurity setting for a list or library. You can change these settings through list settings page for a list or through powershell for a document library

This is the powershell snippet.

$web = Get-SPWeb http://site-url/
$list = $web.Lists["Document Library"]
$list.ReadSecurity = 2
$list.WriteSecurity = 2
$list.Update()
$web.Dispose()

Refer this blog for more info - http://sundarnarasiman.net/?p=26

Free Windows Admin Tool Kit Click here and download it now
April 30th, 2015 3:32am

This topic is archived. No further replies will be accepted.

Other recent topics Other recent topics