Saturday, June 22, 2013

Stop Event bubbling in SharePoint event handler

In SharePoint event handler, when you use method like ItemUpdated() or ItemUpdating(), you may come across your handler/method code will execute multiple times. Which is very much incorrect and irritating for you.
In this scenario, you can use  "EventFiringEnabled" property and stop bubbling of events. I tried this in my event handler and worked perfectly.
given bellow is sample code that i used in my demo.



 public override void ItemUpdated(SPItemEventProperties properties)
       {
           base.EventFiringEnabled = false;

           LogEvent("entered item updated method");  //my custom logger method is used here

           SPSite site = properties.OpenSite();
           SPWeb currentWeb = properties.OpenWeb();
           SPWeb rootWeb = site.RootWeb;
           SPList currentList = properties.List;
           SPListItem rootListItem = properties.ListItem;
           rootListItem["Title"] += "modified by event handler";
           rootListItem.SystemUpdate();

           LogEvent("existing item updated method");

           base.EventFiringEnabled = true;
       }

       private void LogEvent(String msg)
       {
           SPSecurity.RunWithElevatedPrivileges(delegate()
           {
               System.Diagnostics.EventLog el = new System.Diagnostics.EventLog();
               el.Source = "DupeEventReceiver";
               el.Log = "Application";
               el.WriteEntry(msg);
           });
       }


happy codding.
Your suggestions and ideas are most welcome.

No comments:

Post a Comment