After completing the process of creating a MOSS configuration list and the SetConfiguration method in the event receiver (Creating Item Level Security for an Event Receiver based upon metadata (Part 1)), it’s now time to create the methods for actually implementing the security for the individual documents.

SetSecurityForItem:

This method will set the applicable security for the document. For my purposes, I added a boolean field in the document library called ChangeSecurity that can be checked if different security needs to be applied.  Once this is done,  we need to call the method BreakRoleInheritance(false) so that it will not copy down the permissions from the library.  I did find when you call the ItemUpdated method, that you need to remove all inherited roles to be able to apply the correct assignment (See line 23). Therefore, one of the parameters passed into the SetSecuritForItem method requires the type of method being called (“ItemAdded”, “ItemUpdated”, etc…) At this point, we need to set the SPRoleDefinitionCollection (I chose to utilize caching in this instance again).  To obtain the role definitons, the SPWeb parameter is called. Following this, a new array of type SPRoleDefinition is created passing in the roleType from the custom list. Last portion of this method is to iterate through the SPFieldUserValue to apply the permission to the document.

addPermissionToListItem is called in SetSecurityForItem which I will go into detail below:

addPermissiontoListItem:

With this method, it allows you to programmatically add security to a list item by the means of iterating through the values of a SharePoint User or Group column, including support for passing in a list of SPRoleDefinition items to grant to the security item. SPPrincipal represents either a user or group that will be assigned permissions.  Once we distinguish the type of SPPrincipal, a new SPRoleAssignment is created and the binding information is then iterated through and added to the role assignment. Finally, the group’s (or user’s) role assignment is then added to the list item. One thing to note about this method is that if the field user value is a User, a lookup is performed to obtain the SPPrincipal value (line 21)

Final Step:

Create your overload methods for ItemAdded and ItemUpdated inheriting from the SPItemEventProperties. Make sure to call the methods above and also set the SPWeb value.

Finally, build your project and deploy as a feature. That’s a brief overview of how to apply item level security based upon a metadata value.