SharePoint 2013 - SPLessons

SharePoint Synchronous and Asynchronous Event Receivers

Home > Lesson > Chapter 61
SPLessons 5 Steps, 3 Clicks
5 Steps - 3 Clicks

SharePoint Synchronous and Asynchronous Event Receivers

SharePoint Synchronous and Asynchronous Event Receivers

Events can be categorized as Before Event and After Events

  •  Before events fire before the corresponding event action occurs and before SharePoint has written any data to the content database
  •  After events fire after the event action has completed and after SharePoint  has written to the content database to commit the event action. After events do not support cancelling the event action. A common example is sending out email notifications to let all the members of a site know when a new document has been uploaded.

Each event handler is executed under a specific synchronization mode

  • Before events are always executed under a synchronization mode of synchronous. A key point is that synchronous event handlers have a blocking nature because they run on the same thread that is processing the event action.
  • After events are always executed under asynchronous mode.

Following are the event receiver base classes

  • SPItemEventReceiver
  • SPListEventReceiver
  • SPEmailEventReceiver
  • SPWebEventReceiver
  • SPWorkflowEventReceiver

Example

This task will guide you through creating and attaching an Event Receiver to the List “SplessonsDetails”. This event receiver when an item is added into that list ,then immediately one calender document will create . 1. Select the Visual C# | SharePoint | 2013 | Event Receiver project type. 2. Click Add. 3. In the SharePoint Customization Wizard, tick the following 3 events: • An item is being added • An item is being updated 4. Edit EventReceiver1.cs file and the code as below [csharp]public class EvtRcv__AddList : SPItemEventReceiver { /// /// An item is being added. /// public override void ItemAdding(SPItemEventProperties properties) { base.ItemAdding(properties); using (SPSite site = new SPSite("http://splessons:5151/")) { using (SPWeb web = site.OpenWeb()) { if (properties.ListTitle == "SplessonsDetails") { SPList list = web.Lists["SplessonsDetails"]; SPListItem item = list.Items.Add(); string ConferenceRoom = properties.AfterProperties["ConferenceRoom"].ToString(); web.AllowUnsafeUpdates = true; web.Lists.Add("Calender_" + ConferenceRoom, "This list was created programmatically", web.ListTemplates["Calendar"]); properties.AfterProperties["RelatedRoom"] = "Calender_" + ConferenceRoom; item["RelatedRoom"] = properties.AfterProperties["RelatedRoom"]; web.Update(); web.AllowUnsafeUpdates = false; } } } } } [/csharp] 5. From the menu, select Build and Deploy Bugs.