Skip Ribbon Commands Skip to main content

SharePoint Happenings

Help (new window)
Sign In
Navigate Up
Get Microsoft Silverlight
Install Silverlight plugin for a richer experience...
Blog Home |  Freeware |  Speaking |  About me

Building SharePoint Event Receivers in 2010



Bookmark and Share

Top Tech Links










Top SharePoint Administrator Links









Top SharePoint Developer Links













NOTE: This blog has been moved to http://blog.philwicklund.com. If you'd like assistance, leave a comment on the copied post in the new location (hint, use search on the right to find the post).


If you need some action to occur when a user deletes a document, for example, you may right away think you need a workflow when in fact an event receiver will do. The main difference between the two is a workflow is typically long running, whereas an event receiver is immediate.

 

Why would you want an event receiver? What if all you wanted to do is execute a piece of code when a document is being deleted. Say you wanted with code to archive that document when a user goes to delete it. This is a great example where an event receiver is nice, because that deleting event can trigger your custom code. You could do this with a Visual Studio workflow that just has one activity in it, but that's a lot of overhead for something that an event receiver does with a lot less effort. Alternatively, you could use a SharePoint Designer workflow, but with SPD you can't move documents across the site collection boundary, so custom code is the only way to go. The table below shows more comparisons between workflows and event receivers:

 

Comparing a workflow with an event receivers

Event Receivers

 

Workflows

Immediate fire

Versus

"Long running"

Lives and dies (no state)

Versus

Maintains "state"

.NET code only

Versus

.NET or SharePoint Designer

No human interaction

Versus

Typically involves human interaction

Before or after events

Versus

Only After events

Executes on sites, features, lists, and list items

Versus

Executes on Sites, items, and content types.

 

 

You really can't say one is better than the other. It depends entirely on your business requirements. Besides when documents are deleted, there are many other events you can respond to. The events fall into six categories as shown in the table below. Each category has a few of the more common events shown in the second column, but note there are many more events available as well.

 

Six event receiver categories

List Events

Adding/ed a new list, field.
Updating/ed a field.

List Item Events

Adding/ed a new list item or document.
Document checking/ed in or out.
Adding/ed an attachment.
Deleting/ed an item or document.

List Email Events

A list received an email.

Web Events

Deleting/ed a site collection or site.
Creating/ed a new site collection or sub site.

Feature Events

Feature activating/ed or deactivating/ed.

List Workflow Events

A workflow is starting/ed, postponed, or completed.

 

 

You'll notice two things in this table. First is that there are a ton of events that you can have custom code respond to, and secondly that most events have a "before" and "after" (adding/added) event associated with it. As shown in Figure 1, before events happened before the change is committed to the SharePoint content database. This is helpful when you may want to cancel a change before it is saved. The event receiver for when a site is being deleted is a good example. Before the site is deleted, you could back it up first. On the other hand, there's a corresponding event receiver for after the site was deleted.

 

Figure 1 Events typically have a "before" and an "after" event, corresponding to when the event happens in relation to when the source is committed to the database.

 

To demonstrate how to build an event receiver, we're going to use the Workflow events as an example. The previous table shows how there are four events under the List Workflow Events category. We can respond to when a workflow is starting and when it has started, when a workflow is postponed, and when a workflow has completed. To keep the example simple, let's write an event receiver that creates an announcement when a new calendar event is created.

 

Start by creating a new project in Visual Studio 2010. You'll notice under the SharePoint tab that there's a new project template called Event Receiver (Figure 2). You can use this template to create any of the afore mentioned event receivers.

 

Figure 2 Visual Studio 2010 now has a new project template you can use to easily create new event receivers.

 

After you create the project, you'll get a dialog menu asking you to specify the URL of the site where you want to deploy and unit test your event receiver. Specify the URL and click next. Afterwards you'll be prompted to specify what type of event receiver you want to create (Figure 3). The drop down will contain the event types for each of the six categories except for the feature events category. Feature events are created by right clicking the feature from within the project after it's created. For the announcement example, select the List Workflow Events category:

 

Figure 3 There are six main event categories (five shown).

 

After you select the event category, you'll need to specify the event source. This tells the feature that is to be created what events you want to respond to. Notice in Figure 4 you can handle events from announcements, document libraries, and many others. Select the Calendar source:

 

Figure 4 You'll need to specify the event source that will raise the event and call your event receiver.

 

Next you want to specify what workflow event we want to handle. Specify the A workflow has started event. Now our code will execute any time a workflow is started on a calendar (Figure 5):

 

Figure 5 After you choose the event source, you need to specify the actual event you want to respond to. In this case we want to execute our code when a workflow has started.

 

After you create the project, you'll be sent to a method named WorkflowStarted. This is where we can add our code to create our announcement. Enter the code found in below to create the announcement:

 

 

if (properties.ActivationProperties.List.Title == "Main Calendar")

{

    string siteurl = properties.ActivationProperties.Site.Url;

 

    SPSecurity.RunWithElevatedPrivileges(delegate()

    {

        using (SPSite site = new SPSite(siteurl))

        {

            using (SPWeb web = site.RootWeb)

            {

                SPListItem item = web.Lists["Announcements"].Items.Add();

                item["Title"] = "The workflow has started!";

                item.Update();

            }

        }

    });

}

 

 

The first thing this code block does is look at the activation properties to determine which calendar the event came from. Remember that our source was "Calendar" which just means any calendar on the site will raise this event when a workflow is started. If we have more than one calendar on the site we'll want to determine which calendar the event came from.

 

Next we elevate the privileges of the running use to be the service account. We don't know for sure if the running user has Contribute rights on the announcements list, so we elevate their permissions to be safe. Next we create the announcement, assign a title value, and commit the announcement to the database.

 

With this code in place, all we need to do is deploy the solution. Right click the project name in Visual Studio, and click Deploy. This will deploy the feature and assembly on our before. Next go and create a new calendar entry and start a workflow on that event. Afterwards, a new announcement will show up in the announcements list on that site.

 

 

Phil