Over the last decade of being in SharePoint, I keep running into various “gotcha’s” with event receivers that aren’t always obvious. Even though SharePoint server side development is going the way of the dodo, I imagine I’m still going to be writing the odd event receiver for client’s for another few years so here’s a list of things I need to remember for next time.
- When you’re doing a list item added event receiver, use the ListItem on the SPItemEventProperties object you’re passed as the ListItemUniqueId won’t resolve anything if you try to access it directly from the list.
- If your event receiver isn’t being fired even though everything appears to be deployed correctly, check that you are actually referencing the correct event receiver in your Elements.xml file. Too many times I move a class from one assembly to another, change a class name etc. and forget to update this file. Often no error messages are logged in ULS so it looks everything is fine.
- This is sort of a “best practice” which you should be doing anyway. Make sure you separate out the innards of your event receiver into a different class that can be easily mocked. Things may work in development and test, but when you move stuff into staging or prod, you shouldn’t have any development tools available to you. In these scenarios, being able to run diagnostics from a PowerShell command line is very helpful and if you have easily “testable” classes, you can instantiate these from PowerShell.