Event Receiver in SharePoint

Hai,

Event receivers are effective ways to add triggers to SharePoint solution. To create a simple event receiver, follow the steps 

  1. Open SharePoint site and create a new list called SPEventList and leave the list with default Title column
  2. Open Visual Studio –> New Project –> Select Event Receiver in the SharePoint 2010 project template folder
  3. Give a name to project and select \”Deploy as Farm Solution\” in Security level option
  4. When prompted int he wizard, select the List Item Events option under the type of event receiver which we want to associate the event. Select Announcements list under the event source and \”An Item is being added\” as the specific event and then Finish.

In the event receiver class file add the following code

using System;
  using System.Security.Permissions;
  using Microsoft.SharePoint;
  using Microsoft.SharePoint.Security;
  using Microsoft.SharePoint.Utilities;
  using Microsoft.SharePoint.Workflow;
 
  namespace EventReceiverProject1.EventReceiver1
  {
      /// <summary>
      /// List Item Events
      /// </summary>
      public class EventReceiver1 : SPItemEventReceiver
      {
          /// <summary>
          /// An item is being added.
          /// </summary>
          public override void ItemAdding(SPItemEventProperties properties)
          {
              base.ItemAdding(properties);
              string eventName = \"Event List:\";
              LogAnAnnoncement(properties, eventName);
          }
 
          private void LogAnAnnoncement(SPItemEventProperties properties, string eventName)
          {
 
              string listTitle = properties.List.Title;
              string siteURL = \"http://siva-pc:46006\";
              DateTime currentDate = DateTime.Now;
 
              using (SPSite mySPSiteCollection = new SPSite(siteURL))
              {
                  using (SPWeb mySPSite = mySPSiteCollection.RootWeb)
                  {
                      SPList mySPList = mySPSite.Lists[\"SPEventList\"];
                      SPListItem newListItem = mySPList.Items.Add();
                      newListItem[\"Title\"] = eventName + listTitle + \" @ \" + currentDate.ToLongTimeString();
                      newListItem.Update();
                  }
              }
 
 
          }
      }
  }

Build and deploy Event Receiver project in SharePoint site. now go to SharePoint site –> Announcements list –> Add new item.

After finish the new item go to SPEventList (which we created earlier), you will see a new list item. 

An event receiver is, a custom DLL that is deployed to the global assembly cache (GAC) on SharePoint server. Using the project template, Visual Studio creates a feature that then references the custom assembly in the GAC when the action that triggers the event occurs. 

Here we added an event that is triggered whenever someone adds an event to the  Announcements list. 

Leave a Reply

Scroll to Top
%d bloggers like this: