天天看点

SharePoint 2010/2013 在某块代码段中临时禁用触发event handler(receiver)

本文讲述如何在SharePoint 2010/2013的解决方案中的某块代码段中临时禁用触发event handler(receiver):

新建类DisabledItemEventsScope:

/// <summary>
///   Disable event firing while item update. Should be used for SharePoint 2010
///   only.
/// </summary>
public class DisabledItemEventsScope : SPItemEventReceiver, IDisposable
{
    private readonly bool oldValue;
 
    /// <summary>
    /// Initializes a new instance of the <see cref="DisabledItemEventsScope"/>
    /// class.
    ///   Default constructor.
    /// </summary>
    public DisabledItemEventsScope()
    {
        oldValue = EventFiringEnabled;
        EventFiringEnabled = false;
    }
 
    public void Dispose()
    {
        EventFiringEnabled = oldValue;
    }
}
           

使用DisabledItemEventsScope的实例代码如下:

/// <summary>
///   Extension methods for <c>SPListItem</c>.
/// </summary>
public static class SPListItemExtensions
{
    /// <summary>
    ///   Provides ability to update list item without firing event receiver.
    /// </summary>
    /// <param name="listItem">SharePoint list item instance.</param>
    /// <param name="fireEvents">Disables firing event receiver while updating
    /// item.</param>
    public static void Update(this SPListItem listItem, bool fireEvents)
    {
        if (fireEvents == false)
        {
            using (new DisabledItemEventsScope())
            {
                listItem.Update();
            }
        }
        else
        {
            listItem.Update();
        }
    }
}
           

继续阅读