Thursday, January 5, 2012

Avoiding Recursion in Event Receivers

While writing the Event Handlers, generally we will have the requirement as checking few of the field values and updating other fields accordingly.
But when you try updating the item again the event handler will fire again and if you observe the version history of the item, the change made by user which triggered the event receiver will be registered as one version and the one triggered by the code will be as another version and also if you see the modified person will be admin.

By adding few lines of code we can avoid the recursion of event firing and the redundant versions.

item[fieldname] = fieldvalue;
this.DisableEventFiring();
item.SystemUpdate(false);
this.EnableEventFiring();

By disabling event firing before update, the recursion will be avoided. And by SystemUpdate(false), ensures that no version is created by this update and also user can see the update as his update rather than Admin's.

No comments:

Post a Comment