How to create an event receiver change permisions on file added sharepoint 2013

1.9k views Asked by At

I have a library ("Documents") where I want to add an event receiver which will remove permisions on item added. I tryed already multiple ways to do this but i'm not so experimented and I can't figure where i'm wrong. With following code I managed to BreakInheritance, but didn't managed to remove all assignmets and add one new.

public override void ItemAdded(SPItemEventProperties properties)
    {
        base.ItemAdded(properties);
        if (properties.ListTitle.Equals("Documents"))
         I really need help on this one.{
            using (SPSite site = new SPSite(properties.WebUrl))
            {
                site.AllowUnsafeUpdates = true;
                using (SPWeb web = site.OpenWeb())
                {
                    SPUser user = web.CurrentUser;
                    SPSecurity.RunWithElevatedPrivileges(delegate()
                    {
                        try
                        {
                            web.AllowUnsafeUpdates = true;
                            SPListItem li = properties.ListItem;
                            SPFile lf = web.GetFile(li.Url);

                            SPRoleType read = SPRoleType.Guest;
                            lf.Item.BreakRoleInheritance(true);
                            while (lf.Item.RoleAssignments.Count > 0)
                            {
                                lf.Item.RoleAssignments.Remove(0);
                            }
                            AssignPermissionsToItem(lf.Item, user, read);
                            web.AllowUnsafeUpdates = false;

                        }

                        catch (Exception ex)
                        {
                        }

                    });
                }
            }
        }
    }

    public static void AssignPermissionsToItem(SPListItem item, SPPrincipal obj, SPRoleType roleType)
    {
        if (!item.HasUniqueRoleAssignments)
        {
            item.BreakRoleInheritance(true);
        }

        SPRoleAssignment roleAssignment = new SPRoleAssignment(obj);
        SPRoleDefinition roleDefinition = item.Web.RoleDefinitions.GetByType(roleType);
        roleAssignment.RoleDefinitionBindings.Add(roleDefinition);

        item.RoleAssignments.Add(roleAssignment);
    }
1

There are 1 answers

1
zzeneg On

First of all, you need to instantiate new SPSite and SPWeb objects inside SPSecurity.RunWithElevatedPrivileges (link).

Second, if you want to remove all rights, you should call SPListItem.BreakRoleInheritance with false argument. In this case, item will have no rights. And then you can add whatever rights you need.

And my personal advice - you should never use empty catch-block. Send error message to UPS Logging service, it's really easy but helpful.