SPItemEventReceiver

From WSSWiki

Jump to: navigation, search

The SPItemEventReceiver class provides a way for developers to develop custom code around the events the occur on items within SharePoint.

Contents

[edit] Example

The following is an example of an SPItemEventReceiver that strips an item of it's permissions and assigns the members and owners groups as the default.

NOTE: The ItemCheckedIn event is required because the document will remain checked out and only visible to the user if a document is uploaded into SharePoint via the Multiple File Upload screen, or via Explorer View and the library has been setup to require metadata.

public class BreakPermissionItemEventReceiver : SPItemEventReceiver
{

    #region Declarations
    private const string MemberGroup = "vti_associatemembergroup";
    private const string OwnerGroup = "vti_associateownergroup";
    #endregion

    #region Overrides

    public override void ItemAdded(SPItemEventProperties properties)
    {
        if (properties == null)
            return;

        if (properties.ListItem.Level != SPFileLevel.Checkout)
        {
            StripPermissions(properties);
        }

        base.ItemAdded(properties);
    }

    public override void ItemCheckedIn(SPItemEventProperties properties)
    {
        if (properties == null)
            return;

        var list = properties.ListItem;
        if (list.Versions.Count == 1)
            StripPermissions(properties);

        base.ItemCheckedIn(properties);
    }
    #endregion

    #region Methods

    private void StripPermissions(SPItemEventProperties properties)
    {
        using (SPSite site = SecurityHelper.GetElevatedSite(properties.WebUrl))
        {
            using (SPWeb web = site.OpenWeb())
            {
                var item = web.Lists[properties.ListId].GetItemById(properties.ListItemId);

                if (!item.HasUniqueRoleAssignments)
                {
                    item.BreakRoleInheritance(false);
                    var group = web.SiteGroups.GetByID(int.Parse(web.Properties[OwnerGroup]));
                    var assignment = new SPRoleAssignment(group);
                    assignment.RoleDefinitionBindings.Add(web.RoleDefinitions.GetByType(SPRoleType.Administrator));
                    item.RoleAssignments.Add(assignment);

                    group = web.SiteGroups.GetByID(int.Parse(web.Properties[MemberGroup]));
                    assignment = new SPRoleAssignment(group);
                    assignment.RoleDefinitionBindings.Add(web.RoleDefinitions.GetByType(SPRoleType.Contributor));
                    item.RoleAssignments.Add(assignment);

                    item.RoleAssignments.RemoveById(site.SystemAccount.ID);

                    this.DisableEventFiring();
                    item.SystemUpdate(false);
                    this.EnableEventFiring();
                }
            }
        }
    }
    #endregion


}


// Thanks to Daniel Larson for this helper.
public static class SecurityHelper
{
    /// <summary>
    /// Returns an SPSite object that has been elevated to the System Account privileges.
    /// </summary>
    /// <param name="url">URL of the site you want to return.</param>
    /// <returns></returns>
    public static SPSite GetElevatedSite(string url)
    {
        
        using (SPSite site = new SPSite(url))
        {
            var token = GetSystemToken(site);

            return new SPSite(url, token);
        }
    }

    private static SPUserToken GetSystemToken(SPSite site)
    {
        site.CatchAccessDeniedException = false;

        try
        {
            return site.SystemAccount.UserToken;
        }
        catch (UnauthorizedAccessException)
        {
            SPUserToken token = null;

            SPSecurity.RunWithElevatedPrivileges(delegate()
            {
                using (SPSite elevatedSite = new SPSite(site.ID))
                {
                    token = elevatedSite.SystemAccount.UserToken;
                }
            });

            return token;
        }
        finally
        {
            site.CatchAccessDeniedException = true;
        }
    }
}

[edit] External Links

Personal tools