Search This Blog

Friday, December 19, 2014

Create Event Handlers for Sharepoint List

Introduction

Sharepoint provides lots of inbuild features for storing documents, managing data, creating sub sites. You can create your own lists, documents libraries, announancement, calendar. Each list has its own events i.e Item Created, Item Updated Item Deleted etc. But if you want to do some thing on any event, you need to write custom code for this. This can be done by using Event handlers. 

Event handler is occuring when some action happened in SharePoint site. e.g. You are adding an item to sharepoint list, you are deleting item from sharepoint list etc. Basically there are 4 types of classes available for event handler.

•   List Items – SPItemEventReceiver
•   List Columns – SPListEventReceiver
•   Site – SPWebEventReceiver
•   Email – SPEmailEventReceiver

Basically event handler is the set of custom code written by the user that inherits SharePoint predefined classes to handle the code functionality of these events.

Sceanrio

Suppose there are two lists Employee and Comments.

Employee list's fields :
1) Name
2) Department
3) Location
4) EmpCode
5) CommentsPosted

Comments list's fields:
1) Comment
2) Created
3) CreatedBy

In Employee list Comments Posted is the total no. of comments posted by the employee. If an employee post the comment then Comments Posted field value for that particular employee should be increased.

To achive this functionality you need to write the event handler for Item Created event on Comments list. 

Assumption

In this article I am using Visual Studio 2010 Ultimate and Sharepoint Foundation Server 2010 to create the event handler.

Implementation

Open Visual Studio 2010. Create New Project from File -> New Project as shown in Figure 1



Figure 1
Choose the appropriate location where you want to store project files and give a suitable name and click 
on OK.

A wizard will appear. Here we need to specify some settings in these steps.

Step 1 Specify the site and security level of debugging:

It will ask for What local site do you want to use for debugging? Specify the site root path. In What is the
 trust levelfor this SharePoint solution? Choose Deploy as farm solution option and click on Next.




Step 2 Choose Event receiver Settings:

It will ask you What type of event receiver do you want? Choose List Item Events. Then It will ask for 
What item should be the event source? Choose Custom List. Next choose the event which you want to
 handle. In current example I choosing the event “An item is being added”. Click on Finish.



It will create a Event Handler project for you as shown in Figure 4.



Open the EventReceiver1.cs. There should be a event ItemAdded.

ItemAdded event fired when an item has been added in any list. But in current sceanrio we want to check the 
event for Comments list. So for this we need to check that on which list, event has been fired. ItemAdded event has one parameter named properties which contains the all the properties of the event such as the name of the list by which event has been fired, fields values etc. We check the name of the list.

See the code block below :

Introduction

Sharepoint provides lots of inbuild features for storing documents, managing data, creating sub sites. You can create your own lists, documents libraries, announancement, calendar. Each list has its own events i.e Item Created, Item Updated Item Deleted etc. But if you want to do some thing on any event, you need to write custom code for this. This can be done by using Event handlers.

Event handler is occuring when some action happened in SharePoint site. e.g. You are adding an item to sharepoint list, you are deleting item from sharepoint list etc. Basically there are 4 types of classes available for event handler.

•   List Items – SPItemEventReceiver
•   List Columns – SPListEventReceiver
•   Site – SPWebEventReceiver
•   Email – SPEmailEventReceiver

Basically event handler is the set of custom code written by the user that inherits SharePoint predefined classes to handle the code functionality of these events.

Sceanrio

Suppose there are two lists Employee and Comments.

Employee list's fields :
1) Name
2) Department
3) Location
4) EmpCode
5) CommentsPosted

Comments list's fields:
1) Comment
2) Created
3) CreatedBy

In Employee list Comments Posted is the total no. of comments posted by the employee. If an employee post the comment then Comments Posted field value for that particular employee should be increased.

To achive this functionality you need to write the event handler for Item Created event on Comments list. 

Assumption

In this article I am using Visual Studio 2010 Ultimate and Sharepoint Foundation Server 2010 to create the event handler.

Implementation

   public override void ItemAdded(SPItemEventProperties properties)
   { 
      try 
      { 
            if (properties.ListTitle == "Comments") 
            { 
               UpdateCommentPosted(properties); 
            } 
      } 
      catch (Exception ex) 
      { 
         properties.Status = SPEventReceiverStatus.CancelWithError; 
         properties.ErrorMessage = ex.Message; 
         properties.Cancel = true; 
      } 
   } 

   
   private void UpdateCommentPosted(SPItemEventProperties properties) 
   { 
      string createdBy = properties.AfterProperties["CreatedBy"].ToString(); 
      SPUser privilegedAccount = properties.Web.AllUsers[@"SHAREPOINT\SYSTEM"]; 
      SPUserToken privilegedToken = privilegedAccount.UserToken; 
      try 
      { 
         using (SPSite elevatedSite = new SPSite(properties.Web.Url, privilegedToken)) 
         { 
            using (SPWeb elevatedWeb = elevatedSite.OpenWeb()) 
            { 
               SPQuery query = new SPQuery(); 
               query.Query = "<Where>" + 
                              "<Eq>" + 
                              "<FieldRef Name='Author' />" + 
                              "<Value Type='Person'>" + createdBy + "</Value>" + 
                              "</Eq>" + 
                              "</Where>"; 
               SPListItem item = elevatedWeb.Lists["Employee"].GetItems(query)[0]; 
               item["CommentsPosted"] = Convert.ToInt32(item["CommentsPosted"]) + 1; 
               elevatedWeb.AllowUnsafeUpdates = true; 
               item.Update(); 
               elevatedWeb.AllowUnsafeUpdates = false; 
            } 
         } 
      } 
      finally { } 
   }

No comments:

Post a Comment