Thursday, May 16, 2013

Creating a simple Event Receiver in SharePoint 2013

Create an empty SharePoint 2013 project in Visual Studio 2012. In the project, select add new item and select Event Receiver


Select the type of event receiver you need to add, and select the events you need to handle.



In this sample I'm trying to update a SharePoint list based on file changes happening to a separate SharePoint library. Basically, the list will act like a log. So we need to create the library and a list. Here, I have created the Department library to add and maintain documents and also created DocumentLog list to log the changes happening to the library. 

In the list I have three columns, Title, Action & DateAndTime in order to catalog the changes happening to the library.


[The created document library and list]

Back to the SharePoint project. Now go to the event receiver .cs file and you'll get a bunch of methods base on your selection during event receiver creation. Edit the code as below to implement the logic. Note that the ItemAdded method is used instead of the ItemAdding method.


public override void ItemAdded(SPItemEventProperties properties)
        {
            //base.ItemAdded(properties);
            using (SPWeb web = properties.OpenWeb())
            {
                try
                {
                    SPList list = web.Lists["DocumentLog"];
                    SPListItem newItem = list.Items.Add();
                    newItem["Title"] = properties.ListItem.Name;
                    newItem["DateAndTime"] = System.DateTime.Now;
                    newItem["Action"] = "Item Added";
                    newItem.Update();
                }
                catch (Exception ex)
                {
                    throw ex;
                }
            }
        }

public override void ItemUpdating(SPItemEventProperties properties)
        {
            //base.ItemUpdating(properties);
            using (SPWeb web = properties.OpenWeb())
            {
                try
                {
                    SPList list = web.Lists["DocumentLog"];
                    SPListItem newItem = list.Items.Add();
                    newItem["Title"] = properties.ListItem.Name;
                    newItem["DateAndTime"] = System.DateTime.Now;
                    newItem["Action"] = "Item Updated";
                    newItem.Update();
                }
                catch (Exception ex)
                {
                    throw ex;
                }
            }
        }

public override void ItemDeleting(SPItemEventProperties properties)
        {
            //base.ItemDeleting(properties);
            using (SPWeb web = properties.OpenWeb())
            {
                try
                {
                    SPList list = web.Lists["DocumentLog"];
                    SPListItem newItem = list.Items.Add();
                    newItem["Title"] = properties.ListItem.Name;
                    newItem["DateAndTime"] = System.DateTime.Now;
                    newItem["Action"] = "Item Deleted";
                    newItem.Update();
                }
                catch (Exception ex)
                {
                    throw ex;
                }
            }
        }


As I am targeting to add the event receiver only to the Department document library, the Elements.xml file requires a change.



 Note that I have commented out the setting which points to all document libraries, instead pointed to Department document library. The edited Elements.xml file is as below:


<?xml version="1.0" encoding="utf-8"?>
<Elements xmlns="http://schemas.microsoft.com/sharepoint/">
  <!--   <Receivers ListTemplateId="101"> -->
  <Receivers ListUrl="Department">

   <Receiver>
        <Name>DepartmentEventReceiverItemAdded</Name>
        <Type>ItemAdded</Type>
        <Assembly>$SharePoint.Project.AssemblyFullName$</Assembly>
        <Class>MySharePointProject.ListEventReceiver.DepartmentEventReceiver</Class>
        <SequenceNumber>10000</SequenceNumber>
      </Receiver>

      <Receiver>
        <Name>ListEventReceiverItemUpdating</Name>
        <Type>ItemUpdating</Type>
        <Assembly>$SharePoint.Project.AssemblyFullName$</Assembly>
        <Class>MySharePointProject.ListEventReceiver.DepartmentEventReceiver</Class>
        <SequenceNumber>10000</SequenceNumber>
      </Receiver>
      <Receiver>
        <Name>ListEventReceiverItemDeleting</Name>
        <Type>ItemDeleting</Type>
        <Assembly>$SharePoint.Project.AssemblyFullName$</Assembly>
        <Class>MySharePointProject.ListEventReceiver.DepartmentEventReceiver</Class>
        <SequenceNumber>10000</SequenceNumber>
      </Receiver>
</Receivers>
</Elements>

Compile and deploy the solution to your site. Now you may play around with the library and observe the changes happening to the list.... :)

I have added a document, uploaded, added, modified the 3 docs and then deleted one of the docs respectively.


And here's what I get in the DocumentLog list.


16 comments:

  1. This comment has been removed by the author.

    ReplyDelete
  2. Thanks for the post. I'm using VS 2013 and Event receiver is not list, but Remote Event Receiver does appear. do you know if they are compatible?

    ReplyDelete
  3. Hi Steve,
    Sorry, I haven't tried it in VS 2013 yet. Still a VS 2012 user :)

    ReplyDelete
  4. After some additional research I find they are not the same. An event receive seems to only be available when creating a SP project, not a SP app. From what I've read, a SP project needs to have SP installed on the machine.

    ReplyDelete
  5. Hi when i tried to deploy it shows error;The list Department is not exists.but i created department as library.could you please help me with this

    ReplyDelete
  6. Hi,

    Thanks, its so I never know that, I was looking to create event for my mobile application on share point. Thanks again for sharing.

    ReplyDelete
  7. Ahamed- Quick question What type of solution did you create Farm Solution or Sandbox solution. I am facing some issues with Sandbox solution.
    Thanks,
    Khushi

    ReplyDelete
    Replies
    1. @Khushi Sorry for the late reply. This is a farm solution

      Delete
    2. Thanks for update Ahamed. I assumed and when i change the solution to Farm it was working fine.

      Regards,

      Delete
  8. Hi Ahamed,
    Thanks for posting. IN case of custom list, how would we limit the scope of our event receiver to certain list only? Right now it triggers on every custom list, even after mentioning the list name in Elements.xml file.
    Please help.

    ReplyDelete
    Replies
    1. Read the article again. He discusses how to target the specific list instance by editing Elements.xml.

      Delete
    2. This comment has been removed by the author.

      Delete
  9. TechnoSoftwares having several years experience working with global customers, connecting our professionals to their business needs, as their IT Development & Support Partner. TechnoSoftwares having a team of dedicated and experienced softwares developers that works for your all business needs. TechnoSoftwaress deals in web design and development, Customized ERPs, CRMs, Web & Mobile Applications, eCommerce platforms etc.

    ReplyDelete
  10. Hi Ahamed,
    The above posted article is really helpful to me.
    I need one clarfication that i have two type of actions like A,B which i need to implemented in ItemAdding.
    Is it possible to implement the action in one priority basisc like,First B action will need to execute before A action.

    ReplyDelete
  11. Where you find information (manual, books) of this this example?

    SPList list = web.Lists["DocumentLog"];
    SPListItem newItem = list.Items.Add();
    newItem["Title"] = properties.ListItem.Name;
    newItem["DateAndTime"] = System.DateTime.Now;
    newItem["Action"] = "Item Added";
    newItem.Update();

    ReplyDelete