SharePoint 2010: Event Receivers Part 1- Create Event Receiver for Content Types


Creating Event receivers in SharePoint is a very common task With the new Visual Studio 2010, its more easy than before though you could do same with WSP builder in SharePoint 2007. Also the VSEWSS provided a few templates that could be used. Lets look at what has changed and what hasn’t changed in SharePoint 2010

  1. Fire up Visual Studio 2010 and from the templates select “Event Receiver” for the new project under SharePoint 2010 and name the project as “MyCustomEventReceiver”

    image

  2. Create the Event Receiver and it would ask you for the URL of the site against which you would like to create the Event Receiver and next you would see a dialog to select various options for type of events as below

    image

  3. The next set of options for the List/Library against  you would like to deploy the event receiver

    image

    Damn!!! but where is the option I could select a content type so that Visual Studio takes care of registering against the list /library to which I would like to deploy that Event Receiver… I don’t want to deploy MyCustomEventReceiver against all the Calendar Lists in the Site.
    I am not sure why MS VS 2010 team couldn’t provide DEV’s this feature…

  4. Okay lets see what VS 2010 provides us when I select Calendar List and Events as ItemAdded, ItemUpdated and ItemUpdating. VS 2010 created a .cs file and an Elements.xml file. Lets look at the .xml file created
    <?xml version="1.0" encoding="utf-8"?>
    <Elements xmlns="http://schemas.microsoft.com/sharepoint/">
      <Receivers ListTemplateId="106">
          <Receiver>
            <Name>MyCustomEventReceiverItemUpdating</Name>
            <Type>ItemUpdating</Type>
            <Assembly>$SharePoint.Project.AssemblyFullName$</Assembly>
            <Class>MyCustomEventReceiver.MyCustomEventReceiver.MyCustomEventReceiver</Class>
            <SequenceNumber>10000</SequenceNumber>
          </Receiver>
          <Receiver>
            <Name>MyCustomEventReceiverItemAdded</Name>
            <Type>ItemAdded</Type>
            <Assembly>$SharePoint.Project.AssemblyFullName$</Assembly>
            <Class>MyCustomEventReceiver.MyCustomEventReceiver.MyCustomEventReceiver</Class>
            <SequenceNumber>10000</SequenceNumber>
          </Receiver>
          <Receiver>
            <Name>MyCustomEventReceiverItemUpdated</Name>
            <Type>ItemUpdated</Type>
            <Assembly>$SharePoint.Project.AssemblyFullName$</Assembly>
            <Class>MyCustomEventReceiver.MyCustomEventReceiver.MyCustomEventReceiver</Class>
            <SequenceNumber>10000</SequenceNumber>
          </Receiver>
    
      </Receivers>
    </Elements>
    

    As you would see the EventReceiver created is against ListTemplateId = 106 since I selected Calendar List. Next we will see what we need to do to register against a content type

  5. Look at the code below which is modified to add a GUID on top of the class name. You can create a GUID using External Tools—>Create GUID from VS IDE

Note: The namespace System.Runtime.InteropServices; has been added. In the example below I am changing the tile to be automated based on the Title and current month and year.

using System;
using System.Security.Permissions;
using System.Runtime.InteropServices;–>NAMESPACE
using Microsoft.SharePoint;
using Microsoft.SharePoint.Security;
using Microsoft.SharePoint.Utilities;
using Microsoft.SharePoint.Administration;
using System.Data;

namespace MyCustomEventReceiver.MyCustomEventReceiver 
{
    /// <summary>
    /// List Item Events
    /// </summary>
    [Guid("db9b8706-8d95-40ff-9e93-1a7335af7a3b")] –>GUID ADDED HERE
    public class MyCustomEventReceiver : SPItemEventReceiver
    {
        
        /// <summary>
        /// An item was added.
        /// </summary>
        public override void ItemAdded(SPItemEventProperties properties)
        {
            
            setPropertiesOnDocument(properties);

        }

        private void setPropertiesOnDocument(SPItemEventProperties properties)
        {
            SPWeb web = properties.Web;
            try
            {

                SPListItem item = properties.ListItem;

               
             
                web.AllowUnsafeUpdates = true;

                item["Title"] = item["Title"] + 
                                 "_" + DateTime.Now.Month 
                               + "_" + DateTime.Now.Year;

            
                web.AllowUnsafeUpdates = false;

            }

            catch (Exception ex)
            {
                SPDiagnosticsService.Local.WriteTrace(0,
                    new SPDiagnosticsCategory("MyEventReceiver",
                                                TraceSeverity.Unexpected, EventSeverity.Error),
                                                TraceSeverity.Unexpected,
                                                ex.Message,
                                                ex.StackTrace);
            }
            finally
            {
                this.EventFiringEnabled = true;
                web.AllowUnsafeUpdates = false;
            }

        }


   /// <summary>
        /// An item was updated.
        /// </summary>
        public override void ItemUpdated(SPItemEventProperties properties)
        {
            setPropertiesOnDocument(properties);
        }

        /// <summary>
        /// An item is being updated
        /// </summary>
        public override void ItemUpdating(SPItemEventProperties properties)
        {
            SPListItem item = properties.ListItem;


            if (item["Title"] != null )
                properties.AfterProperties["Title"] = item["Title"];
        }
    }
}

The last step is for you to think why I added the GUID on top of the class name. Visual Studio 2010 has been using a lot of these generate AssemblyFullName and AssemblyClassName . Look into the elements.xml file which has $SharePoint.Project.AssemblyFullName$ for the AssemblyFullName. Also an excellent reference from MSDN on Visual Studio 2010 Replaceable Parameters

 

And like most DEV’s if you think alike here is PART 2 for you…Enjoy and Please feel free put to post comments on a better approach. I am sure there are many ways of doing this.

Cheers

About these ads

4 Comments on “SharePoint 2010: Event Receivers Part 1- Create Event Receiver for Content Types”

  1. Faseela A January 7, 2012 at 8:16 am #

    GUID you mentioned here is of ContentType?

    • atulchhoda October 2, 2012 at 1:55 pm #

      GUID is the replacable parameter which can be used to get the assembly token in the feature receiver to attach to the list.
      The ListUrl is good in the element.xml but you cannot have multiple ListUrl.

  2. Sam September 27, 2012 at 11:22 am #

    Thanks that was really helpful.

  3. pmsunilss January 28, 2013 at 8:59 am #

    Thanks

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

Follow

Get every new post delivered to your Inbox.

Join 81 other followers

%d bloggers like this: