Posts Tagged 'eventhandler'

Disable Sharepoint item events firing during item update

In Sharepoint, the attached item events are fired whenever you perform an item.Update()
Ryan posted a solution to this issue, using a custom event handler that disables the events upon request.

What I dislike about the solution, is the risk of leaving the events disabled. Assume an exception occurs, the code will never reach the line where the event firing is enabled (restored) again.

I suggest a using-pattern, much like the TransactionScope class used for db transactions in the entity framework.

    class DisabledItemEventsScope : SPItemEventReceiver, IDisposable
    {
        public DisabledItemEventsScope()
        {
            base.DisableEventFiring();
        }

        #region IDisposable Members

        public void Dispose()
        {
            base.EnableEventFiring();
        }

        #endregion
    }

Now we can use this class together with the using syntax to create a scope within all item event firing is disabled.

                using (DisabledItemEventsScope scope = new DisabledItemEventsScope())
                {
                    item.SystemUpdate(); // will NOT fire events
                }
                item.SystemUpdate(); // will fire events again

This way, the event firing is enabled again as soon as the code leaves the defined scope, be it through normal operation or by exceptions.

Update 1

For SharePoint 2010, use this snippet instead:

    /// <summary>
    /// Disabled item events scope
    /// </summary>
    /// <see cref="https://adrianhenke.wordpress.com/2010/01/29/disable-item-events-firing-during-item-update/"/>
    class DisabledItemEventsScope : SPItemEventReceiver, IDisposable
    {
        bool oldValue;

        public DisabledItemEventsScope()
        {
            this.oldValue = base.EventFiringEnabled;
            base.EventFiringEnabled = false;
        }

        #region IDisposable Members

        public void Dispose()
        {
            base.EventFiringEnabled = oldValue;
        }

        #endregion
    }