Share and Enjoy !

As you design an Application solution in SharePoint that involves the use of SharePoint event receivers, you have to consider that event receivers can fire in situations that you may not anticipate. Therefore, you need to code defensively as the object you are expecting to be available in the Event Receiver may be null. Here are two such examples:

Update of a List form (i.e. Newform.aspx, Editform.aspx, etc)

When you update a list form that is tied to a list that contains an event receiver, the “ItemUpdating” event will be fired on the event receiver when you save the changes. In this case, the properties.ListItem will be null. So, in our situation, we check for this condition and return immediately when it is true.

Restore of a deleted item from the Recycle Bin

When you restore a deleted item from the Recycle Bin, the event receiver on the list where the item is being restored will fire. In this scenario, there may be properties that are null or you may want to treat restored items differently than newly created items. In our scenario, we did not want to take any additional action on restored items, so we did an immediate return when we determined it was an item from the Recycle Bin. The ItemId for a restored item is greater than 0 so we used this information to determine this was an item being restored as opposed to a new item where the ItemId would be 0.

So, next time you include an Event Receiver as part of your SharePoint solution, be sure and test as many “corner cases” as possible to ensure your Event Receiver doesn’t break your application or produce unexpected results.

Share and Enjoy !

Related Content: