Saturday 28 September 2013

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. This example shows how to add an event to the
adding and updating actions for custom list items.
Code It
This SharePoint Visual How To describes the following steps for creating and deploying an event receiver in
Visual Studio 2010:
1. Overriding the itemAdding event and the itemUpdating event.
2. Verifying that the list to which the item is being added is the Open Position list.
3. Elevating permissions so that the code can access a secure site to retrieve approved job titles.
4. Comparing approved Job Titles with the title of a new item that is created in the Open Position list.
5. Canceling the event when the Job Title is not approved.
In this example, a secure subsite 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.
Prerequisites
Before you start, create the subsite and lists that you will need.
To create the Job Definitions subsite
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 Team Site Owners.
8. Click OK.
To create the Job Definitions list
1. In the Job Definitions site, create a custom list named Job Definitions with the following columns:
o  Title (Default column)
o  MinSalary (Currency)
o  MaxSalary (Currency)
o  Role Type (Choice: PermanentContract)
2. Add several jobs to this list. Note the titles that you specify for each job that you create because you will
need them later.
To create the Open Positions list
·    In the parent site, create a custom list named Open Positions with the following columns:
o  Title (Default column)
o  Location (Single line of text)
Creating an Event Receiver
Next, create an Event Receiver project in Visual Studio 2010, and add code to the events receiver file.
To 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.
To modify the events receiver file
1. In the events receiver file, add the following code to the class.
VB
Public Function CheckItem(ByVal properties As SPItemEventProperties) As Boolean
Dim jobTitle As String = properties.AfterProperties("Title").ToString()
    Dim allowed As Boolean = False
    Dim jobDefWeb As SPWeb = Nothing
    Dim jobDefList As SPList
    Dim privilegedAccount As SPUser = properties.Web.AllUsers("SHAREPOINT\SYSTEM")
   Dim privilegedToken As SPUserToken = privilegedAccount.UserToken

    Try
        Using elevatedSite As New SPSite(properties.Web.Url, privilegedToken)
            Using elevatedWeb As SPWeb = elevatedSite.OpenWeb()
                jobDefWeb = elevatedWeb.Webs("JobDefinitions")
                jobDefList = jobDefWeb.Lists("Job Definitions")

                For Each item As SPListItem In jobDefList.Items
                    If item("Title").ToString() = jobTitle Then
                        allowed = True
                        Exit For
                    End If
                Next

            End Using
        End Using

        Return (allowed)

    Finally
        jobDefWeb.Dispose()
    End Try
End Function
C#
bool checkItem(SPItemEventProperties properties)
  {
      string jobTitle = properties.AfterProperties["Title"].ToString();
      bool allowed = false;
      SPWeb jobDefWeb = null;
      SPList jobDefList;
      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())
              {
                  jobDefWeb = elevatedWeb.Webs["JobDefinitions"];
                  jobDefList = jobDefWeb.Lists["Job Definitions"];
                  foreach (SPListItem item in jobDefList.Items)
                  {
                      if (item["Title"].ToString() == jobTitle)
                      {
                          allowed = true;
                          break;
                      }
                  }
              }
          }
          return (allowed);
      }
      finally
      {
          jobDefWeb.Dispose();
      }
  }
2. In the EventReceiver1 file, replace the ItemAdding method with the following code.
VB
Public Overrides Sub ItemAdding(properties as SPItemEventProperties)
    Try
        Dim allowed As Boolean = True

        If properties.ListTitle = "Open Positions" Then
            allowed = CheckItem(properties)
        End If

        If allowed = False Then
            properties.Status = SPEventReceiverStatus.CancelWithError
            properties.ErrorMessage = _
              "The job you have entered is not defined in the Job Definitions List"
            properties.Cancel = True
        End If

    Catch ex As Exception
        properties.Status = SPEventReceiverStatus.CancelWithError
        properties.ErrorMessage = ex.Message
        properties.Cancel = True
    End Try
End Sub

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

            if (properties.ListTitle == "Open Positions")
            {
             allowed = checkItem(properties);
            }
       
               if (!allowed)
            {
               properties.Status = SPEventReceiverStatus.CancelWithError;
               properties.ErrorMessage =
                 "The job you have entered is not defined in the Job Definitions List";
               properties.Cancel = true;
            }
        }
        catch (Exception ex)
        {
            properties.Status = SPEventReceiverStatus.CancelWithError;
            properties.ErrorMessage = ex.Message;
            properties.Cancel = true;
        }
    }
3. In the EventReceiver1 file, replace the ItemUpdating method with the following code.
VB
Public Overrides Sub ItemUpdating(properties as SPItemEventProperties)
        Try
            Dim allowed As Boolean = True

            If properties.ListTitle = "Open Positions" Then
                allowed = CheckItem(properties)
            End If

            If allowed = False Then
                properties.Status = SPEventReceiverStatus.CancelWithError
                properties.ErrorMessage = _
                  "The job you have entered is not defined in the Job Definitions List"
                properties.Cancel = True
            End If

        Catch ex As Exception
            properties.Status = SPEventReceiverStatus.CancelWithError
            properties.ErrorMessage = ex.Message
            properties.Cancel = True

        End Try
End Sub
C#
public override void ItemUpdating(SPItemEventProperties properties)
    {
          
        bool allowed = true;

        if (properties.ListTitle == "Open Positions")
        {
            allowed = checkItem(properties);
        }
       
        try
        {
           
            if (!allowed)
            {
                properties.Status = SPEventReceiverStatus.CancelWithError;
                properties.ErrorMessage =
                  "The job you have entered is not defined in the Job Definitions List";
                properties.Cancel = true;
            }
        }
        catch (Exception ex)
        {
            properties.Status = SPEventReceiverStatus.CancelWithError;
            properties.ErrorMessage = ex.Message;
            properties.Cancel = true;
        }
    }
To deploy the project
1. In Solution Explorer, right-click the project, and then click Deploy.
2. In the SharePoint site, in the Open Positions list, click Add new item.
3. In the Title field, provide a title for a job description that does not exist in the Job Definitions list in the
secured subsite.
4. Click Save. You receive a message from the event receiver.
5. In the Title field, provide a title for a job description that exists in the Job Definitions list in the secured
subsite.
6. Click Save. The position is created.
Read It
·    The solution overrides the ItemAdding and ItemUpdating methods and verifies whether the list that is
being added to is the Open Positions list. If it is, a call is made to the CheckItem method, passing in the
properties that are associated with the event.
·    In the CheckItem method, the permissions are elevated to ensure successful access to the secured subsite.
The job titles that are in the approved list are compared to the job title of the properties.AfterProperties 
property associated with the event. If any title matches, the allowedBoolean variable is set to true, and the
 method returns.
·    Depending on the value of the allowed variable, the calling method either permits the event or sets the
properties.ErrorMessage property and then cancels the event using properties.cancel.

No comments:

Post a Comment