Creating Event Receivers Share Point 2010

Creating Event Receivers
Now that you understand how event receivers let us implement custom business logic for our SharePoint applications, let’s take a look at how we can create them and hook them up with the platform.

  1. Create a new blank site named Chapter Application service overview. Add a custom list named Test List.
  2. Using Visual Studio, create a new Empty SharePoint Project named DemoEventReceivers, as shown next. Set the debugging site to the new site created in step 1, and then select the Deploy As A Farm Solution option.
  3. Creating Event Receivers

  4. Choose Project | Add New Item. From the Add New Item dialog, select Event Receiver and type the name as ListEventReceiver.
  5. The SharePoint Customization Wizard will prompt for additional settings before creating an event receiver class in the project, as shown next. Let’s take a look at the settings so that we can understand how they relate to the concepts that we discussed earlier.

    Creating Event Receivers
    The options in the What Type Of Event Receiver Do You Want? drop-down list correspond to the receiver base classes discussed earlier. The exception to this is the List Email Events option, which we’ll look at later in this chapter. The items in the What Item Should Be The Event Source? drop-down list correspond to the event host that will raise the event. Each option represents a specific instance of an event host.

  6. For this demonstration, set the type of event receiver to List Item Events and then select Custom List from the event source drop-down. We’re creating an event receiver that will be called by all SPList objects that use the Custom List template.
  7. The Handle The Following Events checkbox list lets us select which events we want to handle in our event receiver. For our demonstration, choose An Item Is Being Added and An Item Was Added.
  8. Click Finish to create the event receiver. The SharePoint customization Wizard will add a file named ListEventReceiver.cs to the solution containing the following code (comments removed for brevity):
  9. From this code snippet, we can see that our event receiver is derived fromthe SPItemEventReceiver base class, and both of the defined methods accept SPItemEventProperties objects as parameters.

  10. Update the ItemAdding method with the following code:
  11. Deploy the event receiver by choosing Build | Deploy Demo Event Receivers. This simple example demonstrates a few of the key features of synchronous event handlers. By adding a new item to the Test List that we created earlier with the title set to Cancel Me, the page will be refreshed and no item will be stored in the list. This illustrates how we can cancel an action by setting the SPItem Event Properties. Status property appropriately.
  12. By creating a new item with the title set to Update Me, the event handler updates the title value before the item is stored in the content database. Setting the title to Throw Error or Redirect illustrates the capability to return a custom error message to the user and to redirect to a custom page. In both of these cases, the item is not added to the list.

  13. Now update the ItemAdded method with the following code:
  1. As mentioned earlier, we can configure whether an after event handler runs synchronously or asynchronously. One easy way to do this is as follows:
  2. In the Elements.xml file, edit the XML as follows:
  3. Note the addition of the Synchronization element for the List Event Receiver Item Added receiver.
    So that we can confirm that our event receiver is being called, update the code in the ItemAdded method like so: public override

  4. Deploy the updated event receiver by choosing Build | Deploy DemoEventReceivers. We can check that our ItemAdded event handler is now running synchronously by creating a new item. The first thing to note is that when you click the Save button, the page will take a bitlonger to refresh than previously, because the Thread.Sleep(5000)instruction is now running synchronously. When the page is refreshed, the new item will not appear in the list; by clicking the Recycle Bin link, we can confirm that the item was created and then moved to the recycle bin by the ItemAdded event receiver.

Enabling or Disabling Event Firing
You"ve seen how to create event handlers using the Share PointCustomization Wizard in Visual Studio. Let’s look at how we can handle additional events in an existing event receiver.

  1. In Visual Studio, select the ListEventReceiver item, as shown:
  2. Enabling or Disabling Event Firing

  3. In the Properties pane, set the values for Handle ItemUpdated and Handle ItemUpdating to True.
  4. In the ListEventReceiver.cs file, the following additional methods have been added to handle the ItemUpdated and ItemUpdating events:
  5. As we did earlier, we can now add whatever custom code we need to these method stubs.

  6. For demonstration purposes, update the ItemUpdated method as follows:
  7. Comment the body of the ItemAdded method to allow new items to be added.
  8. Deploy the updated event receiver, and then edit an existing list item.From the preceding code, we might reasonably expect our edited item to have its title changed to Updated Title0. Another reasonable expectation is that the title will be continually updated since updating an item within an ItemUpdated event handler effectively sets up an infinite loop.In reality, however, neither of these two possibilities occurs. Instead, the item is updated ten times and the title remains at Updated Title9.
  9. This highlights an interesting feature of SharePoint 2010: In previous versions, code such as this would indeed cause an infinite loop and cause major performance problems with a server. With SharePoint 2010, protection is built in for this type of issue.
    Nonetheless, prevention is always better than a cure. Rather than relying on the platform to handle such coding errors gracefully, you should explicitly prevent them.
  10. Revise the ItemUpdated method as follows:

After deploying and repeating the test, we can see that our code now behaves as expected: it updates the item title to Updated Title0.

Binding Events
Fundamentally, you can bind event receivers to event hosts in two ways. The first method, which is used by the SharePoint Customization Wizard in Visual Studio, is via CollaborativeApplication Markup Language (CAML). When an event receiver is added to a SharePoint project, two files are added to the solution: An Elements.xml file and a code file to contain the implementation of the event receiver. The Elements.xml file contains XML similar to this snippet:

Element files and CAML are covered in more detail in Chapter . For the purposes of binding event receivers, the key thing that you need to know is that each Receivers element can contain one or more Receiver elements, where a Receiver element defines an event receiver class.
The second method, which offers a much greater degree of granularity, is to bind event receivers programmatically. While the CAML method is definitely the easiest to use, it has a major drawback in that the lowest level of granularity is the list template. To bind an event receiver to a particular list would require a new list template specific to that list. In our example, we bound our event receivers to the custom list template (ListTemplateID 100).
In our simple test site, only one list used this template, so this didn’t present a problem.
Let’s see what happens if we add another custom list.

  1. In the test site that we created earlier, add a new custom list named Another Test List.
  2. Add a new item to the list with the title Throw Error.

When clicking the Save button, an error page is shown. From this, we can see that our new list is also calling the event handlers that we configured for our test list. To resolve this problem, we need to programmatically attach our event receiver to our test list only. Take the following steps to make this change:

  1. Choose Build | Retract. This will retract our solution from the site, effectively detaching all event handlers that were attached by our CAML file previously.
  2. In the Solution Explorer pane, right-click the Feature1 node, and then select Add Event Receiver.
  3. Uncomment the FeatureActivated method and insert the following code:
  4. So that the event receiver is removed again when the solution is retracted, uncomment the FeatureDeactivating method and add the following code:
  5. In the Elements.xml file, comment out or delete the Receivers element and its contents.
  6. Deploy the revised solution.

E-mail Events
One other type of event receiver base class that we haven’t looked at is the SPEmailEventReceiver. This receiver can be used to handle the Email Received event for a particular document library or list. The first thing to note about e-mail events is that not all lists and libraries can accept incoming e-mail, and those that can accept it include document libraries, announcement lists, calendars, and discussion lists. Also, before e-mail can be sent to a list or library, it must first be configured in Central Administration and within an organization’s network. This is a relatively in-depth process;

All rights reserved © 2018 Wisdom IT Services India Pvt. Ltd Protection Status

Share Point 2010 Topics