Thursday, December 17, 2009

Removing Group / User Permissions on list item

Title: Removing Group / User Permissions on the List Item
Details: Some point of time you will encounter a scenario that you would want to remove permission of a group or user for a specific list item. So, here is what can be done.

Step # 1: Create a Feature and on Activation, Add Event Receivers to the List / Document Library

web.Lists[docLibraryName].EventReceivers.Add(SPEventReceiverType.ItemAdded, AssemblyName, ClassName);


Step # 2: On the Item Event Receiver, you can check for some validations ( or rules )etc and break the inheritance and remove the group.

private static void RemoveGroupPermissionsToTheItem(string groupName, SPWeb web, SPListItem listItem)
{
if (!listItem.HasUniqueRoleAssignments)
{
listItem.BreakRoleInheritance(true);

SPGroup group = web.SiteGroups[groupName];
listItem.RoleAssignments.RemoveById(group.ID);
}
}


Step # 3: On Feature Deactivation, make sure you delete the event handler on the list / documentlibrary


private void DeleteItemAddedEventReceiver(SPDocumentLibrary documentLibrary)
{
SPEventReceiverDefinitionCollection eventReceiverDefinitionCollection = documentLibrary.EventReceivers;

foreach (SPEventReceiverDefinition eventReceiverDefinition in eventReceiverDefinitionCollection)
{
if (eventReceiverDefinition.Assembly == AssemblyName && eventReceiverDefinition.Type == SPEventReceiverType.ItemAdded)
{
eventReceiverDefinition.Delete();
break;
}
}
}

No comments: