Changing the SharePoint List listitem's permission in event handler



Changing the SharePoint List listitem's permission in event handler


In MOSS 2007 ListItem permission's could be changed by overriding Add\Update event in eventhandler.


Write a eventhandler class (which inherits from SPItemEventReceiver class) as given below...


public override void ItemUpdated(SPItemEventProperties properties)
{
string
sGroupName = "Group Name";
spWeb = properties.OpenWeb();
spWeb.AllowUnsafeUpdates = true;
SPGroupCollection spGroupCollection = spWeb.SiteGroups;
SPRoleDefinition spRoleDefinition = spWeb.RoleDefinitions.GetByType(SPRoleType.Reader);
properties.ListItem.BreakRoleInheritance(true);


foreach (SPRoleAssignment spRoleAssignment in properties.ListItem.RoleAssignments)
{
//Add your conditions to remove/not remove the existing permissions
spRoleAssignment.RoleDefinitionBindings.RemoveAll();
spRoleAssignment.Update();
}


if (spGroupCollection != null)
{
SPRoleAssignment spRoleAssignment = new SPRoleAssignment((SPPrincipal)spGroupCollection[sGroupName]);
spRoleAssignment.RoleDefinitionBindings.Add(spRoleDefinition);
properties.ListItem.RoleAssignments.Add(spRoleAssignment);
}


this.DisableEventFiring();
UpdateUserGroups(spWeb, properties);
this.EnableEventFiring();
spWeb.AllowUnsafeUpdates = false;
spWeb.Dispose();
}


the above code dose the following...

  • overrides ItemUpdated event (you can do the same for any Item level event)
  • removes all existing permission for the current updated list item
  • adds the Reader permission only for group sGroupName (You can also give contributor permission by changing SPRoleType.Reader to Contributor)

Deploy and attach this event handler to the list where you want to change the ListItem permission whenever the user updates the list item...