Creating SharePoint 2010 Event Receivers in Visual Studio 2010

Overview

Microsoft Visual Studio 2010 provides a project type that enables you to build event receivers that perform actions before or after selected events on a Microsoft SharePoint 2010 site.

Event Receiver Targets

You can create event receiver classes and override specific events by using visual studio 2010 templates for SharePoint 2010. You can add event receivers for following types of objects in SharePoint 2010:

  • List items
  • E-mails received by lists
  • Workflows attached to lists
  • List objects
  • Webs
  • Features

These events in event receiver classes are categorize in to two categories. Those are before events and after events.

Before events

Before events are synchronous events for which you can write code, and have that code run before the operation that raised the event has completed. The synchronous nature of before events, and the fact that the operation has not yet completed, provides you with the ability to cancel the event. By canceling an event, you can effectively cancel the operation that raised the event. For example, you can cancel the adding, editing, or deleting of a list item, and you can cancel the adding or deleting of a field in a list.

After events

After events are asynchronous events for which you can write code, and have that code run after the operation that raised the event has completed. The asynchronous nature of after events, and the fact that the operation has already completed, means that you cannot cancel the operation that raised the event; however, you can be sure that all data changes associated with the event have completed when your After-event handlers are raised.

In this article I am going to discuss about how to create and deploy event receiver for List item object using visual studio 2010.

Scenario

In this scenario, a secure sub site contains a list named Job Definitions that specifies allowed job titles for roles in the organization. Along with job titles, the list also contains confidential salary information for the job title and is therefore secured from users. In the main site, a list named Open Positions tracks vacancies in the organization. You create two event receivers for the itemAdding and itemUpdating events that verify that the title of the open position matches one of the approved titles in the Job Definitions list.

Solution

Step 1: Create the Job Definitions sub site

1. On the main site, on the Site Actions menu, click New Site

2. In the New Site dialog box, click Blank Site

3. On the right of the dialog box, click More Options

4. In the Title box, type Job Definitions

5. In the Web Site Address box, type JobDefinitions

6. In the Permissions section, click Use Unique Permissions, and then click Create

7. In the Visitors to this site section, select Use an existing group, and then select Home Owners. Click OK.

Step 2: Create the Job Definitions list

1. In the New Site Select List from left panel.

2. Then Click Create option to create a new List.

3. In the Create dialog box, Select Custom List.

4. In the Name box, type Job Definitions.

5. In the ribbon select List then Click Create Column.

6.Add following columns to the list one by one, selecting given type within brackets.

  • Title (Default column)
  • MinSalary (Currency)
  • MaxSalar (Currency)
  • Role Type (Choice: Permanent, Contract)

7. Add few jobs to this list.

Note: The titles that you specify for each job that you create because you will need them later.

Step 3:Create the Open Positions list

In the parent site, create a custom list named Open Positions with the following columns:

Title (Default column)

Location (Single line of text)

Step 4: Create a SharePoint 2010 event receiver in Visual Studio 2010

1. Start Visual Studio 2010.

2. On the File menu, click New, and then click Project

3. In the New Project dialog box, in the Installed Templates section, expand either Visual Basic or Visual C#, expand SharePoint, and then click 2010

4. In the template list, click Event Receiver

5. In the Name box, type VerifyJob

6. Leave other fields with their default values, and click OK

7. In the What local site do you want to use for debugging? List, select your site.

8. Select the Deploy as a farm solution option, and then click Next

9. On the Choose Event Receiver Settings page, in the What type of event receiver do you want? List, select List Item Events

10. In the What Item should be the event source? List, select Custom List

11. Under Handle the following events select the An item is being added and the An item is being updated check boxes. Click Finish

Step 5: Add following constant variables to the event receiver file.

private const string OpenPositionsListTitle = "Open Positions";
private const string TitleProperty = "Title";
private const string LoginName = @"SHAREPOINT\SYSTEM";
private const string JobDefinitionsListTitle = "Job Definitions";
private const string SubSiteName = "JobDefinitions";
private const string ErrorMessage = "The job you have entered is not defined in the Job Definitions List";

Step 6: Add a new method called checkItem to the event receiver file.

Private bool checkItem(SPItemEventProperties properties)
  {
      string jobTitle = properties.AfterProperties[EventReceiver1.TitleProperty].ToString();
      bool allowed = false;
      SPWeb jobDefWeb = null;
      SPList jobDefList;
      SPUser privilegedAccount = properties.Web.AllUsers[EventReceiver1.LoginName];
      SPUserToken privilegedToken = privilegedAccount.UserToken;
      try
      {
          using (SPSite elevatedSite = new SPSite(properties.Web.Url, privilegedToken))
          {
              using (SPWeb elevatedWeb = elevatedSite.OpenWeb())
              {
                  jobDefWeb = elevatedWeb.Webs[EventReceiver1.SubSiteName];
                  jobDefList = jobDefWeb.Lists[EventReceiver1.JobDefinitionsListTitle];
                  foreach (SPListItem item in jobDefList.Items)
                  {
                      if (item[EventReceiver1.TitleProperty].ToString() == jobTitle)
                      {
                          allowed = true;
                          break;
                      }
                  }
              }
          }
          return (allowed);
      }
      finally
      {
          jobDefWeb.Dispose();
      }
  }

Step 7: Replace the ItemAdding method with the following code.

public override void ItemAdding(SPItemEventProperties properties)
    {
      try
        {
            bool allowed = true;

            if (properties.ListTitle == EventReceiver1.OpenPositionsListTitle)
            {
             allowed = checkItem(properties);
            }

               if (!allowed)
            {
               properties.Status = SPEventReceiverStatus.CancelWithError;
               properties.ErrorMessage = EventReceiver1.ErrorMessage;
               properties.Cancel = true;
            }
        }
        catch (Exception ex)
        {
            properties.Status = SPEventReceiverStatus.CancelWithError;
            properties.ErrorMessage = ex.Message;
            properties.Cancel = true;
        }
    }

Step 8: Replace the ItemUpdating method with the following code.

public override void ItemUpdating(SPItemEventProperties properties)
    {

        bool allowed = true;

        if (properties.ListTitle == EventReceiver1.OpenPositionsListTitle)
        {
            allowed = checkItem(properties);
        }

        try
        {

            if (!allowed)
            {
                properties.Status = SPEventReceiverStatus.CancelWithError;
                properties.ErrorMessage = EventReceiver1.ErrorMessage;
                properties.Cancel = true;
            }
        }
        catch (Exception ex)
        {
            properties.Status = SPEventReceiverStatus.CancelWithError;
            properties.ErrorMessage = ex.Message;
            properties.Cancel = true;
        }
    }

Step 9: Deploy the project.

1. In Solution Explorer, right-click the project.

2. Then click Deploy

Step 10: Test the site

1. In the SharePoint site, in the Open Positions list, click Add new item

2. In the Title field, provide a title for a job description that does not exist in the Job Definitions list in the secured sub site.

3. Click Save You receive a message from the event receiver.

4. In the Title field, provide a title for a job description that exists in the Job Definitions list in the secured sub site.

5. Click Save. The position is created.

Enhancement

Once you done all the steps above mention this is work perfectly. But if you add another custom List to the same site, if you add a new item to that list, above event receiver will execute but nothing will happen because of in the code we check the list name before do anything.

But I want to make this event receiver execute only for the Open Positions list. To do this, you have to change few attributes in Elements.xml file inside the event receiver.

Receivers element in the Elements.xml file look like this in your project

<Receivers ListTemplateId=100>

Do the changes to this element as follows to make your event receiver to execute only when you do some changes to Open Positions list.

<Receivers  ListUrl=Lists/Open Positions>

 

Leave a comment

  1. i want to create the list in a subsite and not in my site colection rootsite but teh event handler does not fire . please help

  2. did you try this
    ListUrl=“[subSite]/Lists/[ListName]“

    replace the sub site and list name with correct details.

    I am not sure this will work. if this work please let me know

  3. Make the feature “web” scoped. Deploy to the site where your list is by specifying your “Site URL” in the Projects properties. For me it worked to specify the list Url in the following format