Creating
a simple Event Receiver in SharePoint 2013 using WSS Object Model.
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 Document Log 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.
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="Lists/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.
The below method start executes and logic excutes
And here's what I get in the DocumentLog
list.
An event receiver is a piece of
managed code that responds to SharePoint events when specific triggering
actions occur on a SharePoint object. Triggering actions include
activities such as adding, updating, deleting, moving, checking in, and
checking out.
2. What Are Event Hosts?
Event hosts are common SharePoint
objects that expect to receive events—in other words, objects whose
event receivers "listen" for SharePoint events. These SharePoint event
host object types include instances of common objects such as SharePoint
site collections, sites, and lists. Each event host type has a specific
set of event receiver base types from which it can inherit.
3. What are the types of event receivers?
There are two types of event receivers available in SharePoint.
1. Syncronous Events: This
event is executed in the same thread in which the triggering action is
occurring. For example, when the user adds an item from the SharePoint
user interface, the event is fully executed before returning to the user
and showing that the item was added. These are before events that
occurs before the currently requested operation happens. This
provides an opportunity for an event receiver to perform tasks before
data is committed to a database. A good example of the use of Before
events is performing data validation, because Before events fire prior
to commitment of data. You can also use Before (or synchronous) events
to cancel user actions—for example, if data validation fails.
(e.g. ItemAdding, ItemUpdating,ItemDeleting)
2. Asynchronous Events: This
event occurs at a later time than the action that triggered it, and it
executes on a thread that is different from the one in which the
triggering action is running. These are after events. After events
trigger event receivers that execute after user actions are committed to
the content database; they invoke code that runs after the content
database has been modified. This allows you to execute logic that occurs
after a user has completed a specific action.
(e.g. ItemAdded, ItemUpdated,ItemDeleted)
4. What is the base class for List events and List Item events?
The Base class for SharePoint events is Microsoft.SharePoint.SPEventReceiverBase. The List and List Item events inherited based on the scope of event host as below.
List Item: Microsoft.SharePoint.SPItemEventReceiver
SharePoint List: Microsoft.SharePoint.SPListEventReceiver
List Item: Microsoft.SharePoint.SPItemEventReceiver
SharePoint List: Microsoft.SharePoint.SPListEventReceiver
5. How to cancel the actions using event receiver?
SharePoint before
events(synchronous) can be cancelled since it get trigged before
completing the operation. Any validation can be applied as well as the
event can be cancelled using event properties.
E.g
public override void ItemAdding(SPItemEventProperties properties)
{
base.ItemAdding(properties);
{
base.ItemAdding(properties);
if(condition=true)
{
properties.Cancel=True;
}
}
6. What is the best practice to get the context of SPSite when using event receiver?
The event properties should be used to get the current SPContext. If we get the current context of the site in different object like SPContext then your connection may get lose when your dispose the site context. Use SPItemEventProperties.Site/SiteID properties to get the current context or use SPItemEventProperties.Context property.
7. Best coding practice of event receiver?
a. Enable / disable firing other event in the same SharePoint object to avoid unnecessary loops.
b. Do not use SPcontext to get the site/web properties, instead user event properties to get site/web properties
c. Dispose if any heavy object process in event receiver in final block
d. Do not use RunWithElevatedPrevillege if event receiver planned to be deployed as sandbox solution
e. Use UserToken to impersonate your current access.
8. What is Enabling and Disabling event receiver?
SharePoint Event is nothing but
triggering action occurs on a SharePoint object. The trigger may come
from manual action (updating item manually) or automatic action
(SPItem.Update). Both actions will fire the events. Sometimes it makes
unnecessary events in the same list. These events many go infinitely and
impact the server performance majorly. To avoid this unnecessary event
firing, we can purposely enable/disable the other event firing on the
same object.
You can achieve this by executing
the DisableEventFiring method on the list item. After the changes are
saved you can activate the event handler again by executing the
EnableEventFiring method on the list item.
Best practice is to execute the
DisableEventFiring method right before any of the update methods and to
execute the EnableEventFiring method right after one of the update
methods.
9. What is before property?
Get the string/value pairs in a hash table before the event occurred on the SharePoint item.
10. What is after property?
Get the string/value pairs in a hash table after the event occurred on the SharePoint item.
11. What is the difference between event receiver and workflow?
Workflows:
· SharePoint Workflow consist a set of task(s) which can be triggered both manually and automatically.
· SharePoint Workflows are created in SharePoint Designer, Microsoft Visio and of course through Visual Studio.
· The workflow is triggered once an action is completed.
· Workflow can be exported and imported
· Workflow can be paused
· Workflow can send mails without attachment
· Does not required coding knowledge to work on SPD workflows
· Multiple forms(initiation, task edit..) can be associated as part of workflow
Event Receivers:
· SharePoint event receiver contains custom coding/logic which can be triggered automatically based on the event host type.
· SharePoint event receivers can be created only in Visual Studio.
· The events can be triggered before action or after action.
· Events cannot be exported and imported
· Events can be cancelled(synchronous) but cannot be paused
· Even receivers can send mails with attachment
· Required coding knowledge
· No custom forms associated as part of event actions














