SharePoint EventHandler: Set Item Level Permission

Sometime, we need to set item permission dynamically for SharePoint List item or SharePoint Document. To do that, we create Item event handler then implement extension method for setting permission to the item.

the code as following:

public static SPListItem SetItemLevelPermission(this SPListItem listItem, SPPrincipal userOrGroup, SPRoleType roleType)
        {
            SPListItem item = listItem;
            Guid listId = listItem.ParentList.ID;
            Guid itemId = listItem.UniqueId;
            SPUserToken token = item.Web.Site.SystemAccount.UserToken;
            SPSecurity.RunWithElevatedPrivileges(
                delegate()
                {
                    using (SPSite site = new SPSite(item.Web.Site.ID, token))
                    {
                        site.AllowUnsafeUpdates = true;
                        using (SPWeb web = site.OpenWeb(item.Web.ID))
                        {
                            web.AllowUnsafeUpdates = true;
                            SPWebApplication webApp = web.Site.WebApplication;
                            webApp.FormDigestSettings.Enabled = false;
                            item = web.Lists[listId].Items[itemId];
                            item.BreakRoleInheritance(false);
                            web.AllowUnsafeUpdates = true;

                            SPRoleDefinition roleDefinition = web.RoleDefinitions.GetByType(roleType);
                            SPRoleAssignment roleAssignment;

                            roleAssignment = new SPRoleAssignment(userOrGroup);
                            roleAssignment.RoleDefinitionBindings.Add(roleDefinition);
                            item.RoleAssignments.Add(roleAssignment);

                            item.Update(); // call this function before finished
                            webApp.FormDigestSettings.Enabled = true;
                            web.AllowUnsafeUpdates = false;
                        }
                    }
                }
                );
            return item;
        }

In the ItemAdding or ItemAdded Event, We use:

public override void ItemAdded(SPItemEventProperties properties)
       {
           SPWeb currentWeb = properties.ListItem.Web;
           SPUser currentUser = currentWeb.CurrentUser;
           properties.ListItem.SetItemLevelPermission(currentUser, SPRoleType.Contributor);
       }

This Post Has 0 Comments

Leave a Reply