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();
        }
    }
}


發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章