Monday, September 7, 2015

DisableEventFiring is obsolete in SharePoint 2010

ou can check this in msdn. However DisableEventFiring()/EnableEventFiring() still works as per Reflector.
Recommended way now is to use new property EventFiringEnabled. This gives us an option to check current status and save it. I found a great post from Adrian Henke and modified his code using this new feature.

public class DisabledItemEventsScope : SPItemEventReceiver, IDisposable
{
private bool eventFiringEnabledStatus;
public DisabledItemEventsScope()
{
eventFiringEnabledStatus = base.EventFiringEnabled;
base.EventFiringEnabled = false;
}
#region IDisposable Members
public void Dispose()
{
base.EventFiringEnabled = eventFiringEnabledStatus;
}
#endregion
}


The class DisabledItemEventsScope disable/enable event firing for the current thread and could be used in that manner at any place including code behind for the page or web part

item["Title"]="New Title";
using (new DisabledItemEventsScope())
{
item.Update(); // will NOT fire events
}


BTW: There are couple useful SPList extensions to manage SPListItemEventReceiver collection

// Sample:
// list.AddEventReceivers(typeof(TestProject.ListItemEventReceivers.TestReceiver),
// SPEventReceiverType.ItemAdded, SPEventReceiverType.ItemUpdated);
public static void AddEventReceivers(this SPList list,Type erClassType,
params SPEventReceiverType[] erTypes)
{
foreach (SPEventReceiverType erType in erTypes)
{
list.EventReceivers.Add(erType, erClassType.Assembly.FullName,
erClassType.FullName);
}
}
// Sample:
// list.RemoveEventReceivers(typeof(TestProject.ListItemEventReceivers.TestReceiver));
public static void RemoveEventReceivers(this SPList list, Type erClassType, params SPEventReceiverType[] erTypes)
{
List<SPEventReceiverDefinition> receivers = new List<SPEventReceiverDefinition>();
for (int i = 0; i < list.EventReceivers.Count; ++i)
{
SPEventReceiverDefinition r = list.EventReceivers[i];
if (r.Class.Equals(erClassType.FullName) && (erTypes.Length==0 || erTypes.Contains(r.Type)))
receivers.Add(r);
}
foreach (SPEventReceiverDefinition r in receivers)
{
r.Delete();
}
}
view rawSPListExtensions.cs hosted with ❤ by GitHub

No comments:

Post a Comment