Using event receivers you can hook into several predefined SharePoint site/web/list etc. events, get access to event information and run custom code when one occurs.
There’s a basic walkthrough with lots of useful information on MSDN, be sure to check it out.
I wouldn’t list all possible events and sources of events here, the URL above does a nice job in that. Basically you can create an event receiver by subclassing the appropriate class and overriding the self-explanatory virtual methods it provides. There are five classes you can use:
- SPWebEventReceiver: provides events for SPSites and SPWebs.
- SPListEventReceiver: events for SPLists and SPFields, basically to the schema.
- SPItemEventReceiver: events for SPListItems, to the data.
- SPEmailEventReceiver: one event for e-mail enabled lists and webs..
- SPWorkflowEventReceiver: events for workflows.
Most implementations have two types of events: before and after events. This resembles Windows Forms or WPF programming, where you had Clicking and Clicked events. Before events occurs before the event takes place (before SharePoint updates the content database), run on the same thread as the event itself, and provides cancellation and access to the event data. You can access almost every piece of information that will be stored in the After property of the SPItemEventProperties class, except the new item’s (if any) id, which hasn’t been generated yet at this point.
After events lets you run your code after a specific event occurred. By default they run on a background thread, and there aren’t any guarantees that they’ll be runned by the time your page posts back to you. You can control this behavior by setting the synchronization state of your event receiver to synchronous. Then after events will run on the same thread as the event itself.
It’s easy to trigger a stack overflow with event receivers. Imagine that you’ve subscribed to the updating of an SPListItem, and set a property on the same list item from your event receiver. This’ll cause to recursively call the receiver again, until you run out of stack space. To prevent this, there’s a protected property called EventFiringEnabled. Just set it to false, and to true after you’re done. Note that this works only in your own event receiver subclass, not from the outside.
The before events are appropriate candidates for validation. And, if validation fails, you’ll definitely like to cancel further processing of the event. Event receivers provide a way for that. First, you’d like to set the Status of the SPItemEventProperties class to one of the values that indicates cancellation. This by itself won’t cancel the event, after you’ve done this you’ll need to set the Cancel property of this class to true. You can also provide an error message or redirect to another URL using the same class.