In this post, I am going to write an event handler that:
- is triggered when an item is added to a document library (i.e. ItemAdded)
- sends an email to some email address notifying that an item has been added to the document library
- is deployed to a List using SharePoint Features
Okey, lets get started. Create a subsite under your site collection. In the subsite create a Document Library named AlertMe.
JumpStart – > JumpStartWeb -> AlertMe

Create the Event Handler:
Go to Visual Studio 2008. Click File -> New -> Project …..and select Class Library:

Give any name to your project e.g. ”EventHandler.SharePoint.SendEmail.Feature”. This will also become the name of your namespace

Add the directives as shown below:

Top four directives will already be there.
- “Microsoft.SharePoint” is to use sharepoint object model.
- “System.Reflection” is to get assembly information as we will need that to register the event handler with the document library.
- “Microsoft.SharePoint.Utilities” is to send email from SharePoint.
Your namespace name is the name you selected for your project. Rename Class1 to “EmailAlertsEventHandler” and make it to inherit from SPItemEventReceiver class. Rename the class in Solution Explorer window as well:

You might have noted that SPItemEventReceiver class name appears in black coloured font, that’s because we are missing a reference to Windows SharePoint Services.
Lets add the reference as shown below:

Right click “References” -> in the Solution Explorer window and click Add Reference.
Select Windows SharePoint Services as shown below:

As soon as you will add this reference, Microsoft.SharePoint will appear under References and SPItemEventReceiver will change its colour to green which means that it is recognized as a class now.
If you want to see what SPItemEventReceiver contains, press Alt+Cntrl+j, Object Browser window will open. Expand Microsoft.SharePoint -> Microsoft.SharePoint -> SPItemEventReceiver. You will see all the methods in this class in the right hand pane. You will also see the ItemAdded method which we are going to use for our event handler.

Alright, lets add a few methods to our class. As you will write “public override” and press space, intellisence will provide for you the list of all methods available in SPItemEventReceiver, as we saw in the Object Browser:

Select ItemAdded from the list and enjoy the intelligence of VS, you will find a few things automatically done for you:

Here is the code for “EmailAlertsEventHandler.cs”:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Microsoft.SharePoint;
using System.Reflection;
using Microsoft.SharePoint.Utilities;
namespace EventHandler.SharePoint.SendEmail.Feature
{
public class EmailAlertsEventHandler : SPItemEventReceiver
{
public override void ItemAdded(SPItemEventProperties properties)
{
base.ItemAdded(properties);
SPListItem myItem = properties.ListItem;
try
{
SPSecurity.RunWithElevatedPrivileges(delegate()
{
using (SPSite site = new SPSite(properties.WebUrl))
{
using (SPWeb web = site.OpenWeb())
{
string emailSubject = "New Items Added to JumpStart";
string emailBody = myItem.Name.ToString() +
" has been added to AlertMe Document Library for your review." + "\n" +
"\n" + "Thanks," + "\n" + "JumpStart EmailAlertsEventHandler!";
SPUtility.SendEmail(web, true, true, "rehman.gul@hotmail.com", emailSubject, emailBody);
}
}
});
}
catch (Exception ex)
{
}
}
public static void AddOrRemoveEventHandler(SPList list, bool doAdd)
{
Assembly asm = Assembly.GetExecutingAssembly();
string className = typeof(EmailAlertsEventHandler).FullName;
if (doAdd)
{
SPEventReceiverDefinition eventDef = list.EventReceivers.Add();
eventDef.Type = SPEventReceiverType.ItemAdded;
eventDef.Assembly = asm.FullName;
eventDef.Class = className;
eventDef.Name = className + "." + eventDef.Type.ToString();
eventDef.SequenceNumber = 10001;
eventDef.Data = null;
eventDef.Update();
}
else
{
List<SPEventReceiverDefinition> eventsToDelete = new List<SPEventReceiverDefinition>();
foreach (SPEventReceiverDefinition eventDef in list.EventReceivers)
{
if (eventDef.Assembly == asm.FullName && eventDef.Class == className)
{
eventsToDelete.Add(eventDef);
}
}
foreach (SPEventReceiverDefinition eventDef in eventsToDelete)
{
eventDef.Delete();
}
}
}
}
}
As you can see in the code above, there are only two functions ItemAdded and AddOrRemoveEventHandler. ItemAdded opens the web, gets the name of the item which invokes the event handler and sends an email to the specified address. AddOrRemoveEventHandler adds the event handler to the list or removes it, depending on the bool value “doAdd”.
Create the Feature Receiver:
Now how do we attach this Event Handler with a specific list. For that we said we will use Features, such that when the feature is activated, the event handler is attached to our list, and when the feature is deactivated, the event handler is detached from the list.
So, we have to write some code to capture Activate and Deactivate events of the feature. Right click on your project in the solution explorer -> Add -> Class ………..as shown below:

Select Class, give it a name like EmailAlertsFeatureInstaller:

Add the directives Microsoft.SharePoint, System.Reflection and Microsoft.SharePoint.Utilities on the top as shown below. Inherit the class EmailAlertsFeatureInstaller from SPFeatureReceiver. You can open the Object Browser to see all the methods available in SPFeatureReceiver..

Before I move to add methods to this class, lemme explain what is SPFeatureReceiver doing here. Every feature can have four events i.e Feature Activation, Feature Deactivation, Feature Installation and Feature Uninstallation. Against these four events, SPFeatureReceiver class provides us with four methods respectively i.e. FeatureActivated, FeatureDeactivating, FeatureInstalled and FeatureUninstalling. These methods will be executed as the events take place. So, if we override these methods and put our custom code inside, our custom code will be executed whenever a feature is activated, deactivated, installed or uninstalled.
And thats what we wanted i.e. when a feature is Activated, our event handler gets attached to our AlertMe document library. And when the feature is Deactivated, our event handler is detached from our AlertMe document library.
Here is the full code for EmailAlertsFeatureInstaller.cs:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Microsoft.SharePoint;
using System.Reflection;
using Microsoft.SharePoint.Utilities;
namespace EventHandler.SharePoint.SendEmail.Feature
{
class EmailAlertsFeatureInstaller : SPFeatureReceiver
{
public override void FeatureActivated(SPFeatureReceiverProperties properties)
{
SPSecurity.RunWithElevatedPrivileges(delegate()
{
using (SPWeb web = (SPWeb)properties.Feature.Parent)
{
SPList list = web.Lists["AlertMe"];
EmailAlertsEventHandler.AddOrRemoveEventHandler(list, true);
}
});
}
public override void FeatureDeactivating(SPFeatureReceiverProperties properties)
{
SPSecurity.RunWithElevatedPrivileges(delegate()
{
using (SPWeb web = (SPWeb)properties.Feature.Parent)
{
List<SPList> webLists = new List<SPList>();
foreach (SPList list in web.Lists)
{
webLists.Add(list);
}
foreach (SPList list in webLists)
{
EmailAlertsEventHandler.AddOrRemoveEventHandler(list, false);
}
}
});
}
public override void FeatureInstalled(SPFeatureReceiverProperties properties)
{
}
public override void FeatureUninstalling(SPFeatureReceiverProperties properties)
{
}
}
}
As you can see we have overriden only two methods of SPFeatureReceiver class i.e. FeatureActivated and FeatureDeactivating. On FeatureActivated we get to our list AlertMe and call AddOrRemoverEventHandler with a ‘true’ value i.e. attach the event handler. On FeatureDeactivating we iterate through all the lists and call AddOrRemoveEventHandler with a ‘false’ value i.e. detach the event handler.
Also, you can see above in the code that we have added FeatureInstalled and FeatureUninstalling methods though there is no functionality added to them. This is mandatory, if you will not add these methods you will receive an error message because these are abstract members of SPFeatureReceiver class and we must implement them in our class.
Alright we are ready to build our project. Try building and it should work.
Put your assembly in the GAC:
Now lets put our assembly (dll) in Global Assembly Cache (GAC) so that it is available to SharePoint. For that we have to strongly name our assembly as it will be placed in a shared location (GAC).
To strongly name your assembly, right click on your project in Solution Explorer window and click Properties:

Select Signing at the bottom and fill the check box saying “Sign the assembly”. In “Choose a stong name key file” drop down, select <New…>. In “Key file name” text box, give name of your project (assembly) like “EventHandler.SharePoint.SendEmail.Feature”……..click OK…….as shown below:

You will that a file named “EventHandler.SharePoint.SendEmail.Feature.snk” has been added to our project. If you click the file, you will see something similar:

Now our assembly is ready to go to GAC. Go to your working directory on the file system, move to \bin\Debug folder e.g.
C:\Work\EventHandler.SharePoint.SendEmail.Feature\EventHandler.SharePoint.SendEmail.Feature\
bin\Debug
Here you will find your assembly i.e. EventHandler.SharePoint.SendEmail.Feature.dll
Open GAC i.e. c:\windows\assembly and drag and drop your dll in the GAC as shown below:

Do an IISRESET.
Create the Feature:
Now comes the second part of our project i.e. to create the Feature. Remember, we have created a Feature Receiver until now, Feature itself is still to be created.
All Features in SharePoint lies in 12 hive under Features directory:
C:\Program Files\Common Files\Microsoft Shared\Web Server Extensions\12\TEMPLATE\FEATURES
Browse through a few Feature directories and you will find that all of them have a feature.xml file……and some will also have an elements.xml.
Lets create a Feature of our own. Create a folder under Features directory and name it EventHandler.SharePoint.SendEmail.Feature………..could be any name..

Go inside the folder, right click -> New -> Text Document and rename the text document as feature.xml file. Create another file in the same manner and save it as elements.xml:

Right click feature.xml file and Open With -> Notepad. Paste the following xml in the file and save:
<?xml version="1.0" encoding="utf-8"?>
<Feature Id="F2F6FE98-7A4C-4db7-B1E3-BC9C6E5CC9D7"
Title="EventHandler SharePoint SendEmail Feature"
Description="Email Alerts for AlertMe Library"
Version="1.0.0.0"
Hidden="FALSE"
Scope="Web"
DefaultResourceFile="core"
ReceiverAssembly="EventHandler.SharePoint.SendEmail.Feature, Version=1.0.0.0, Culture=neutral, PublicKeyToken=74b4a55dc039bd07"
ReceiverClass="EventHandler.SharePoint.SendEmail.Feature.EmailAlertsFeatureInstaller"
xmlns="http://schemas.microsoft.com/sharepoint/">
<ElementManifests>
<ElementManifest Location="elements.xml"/>
</ElementManifests>
</Feature>
Note that you have to be careful about four items in this xml. Feature Id, ReceiverAssembly, PublicKeyToken and ReceiverClass. They could be different in your case, so use the ones that you have.
For PublikKeyToken, go to GAC, take properties of your assembly and copy/paste into your feature.xml.
Feature Id is just a GUID. Here is how you can get one of your own:
Go to Visual Studio, click Tools ->Create GUID. If Create GUID option is greyed out, click Tools -> External Tools. Make the following settings as shown in the figure below and click OK. This will enable Create GUID option.
“Initial directory” in VS 2008 will be
C:\Program Files (x86)\Microsoft Visual Studio 9.0\Common7\Tools\

Click Create GUID and you will receive it as under:

Click copy and paste it into Feature Id in feature.xml as shown above.
Open elements.xml and paste the following xml into it:
<?xml version="1.0" encoding="utf-8" ?>
<Elements xmlns="http://schemas.microsoft.com/sharepoint/">
</Elements>
Install and Activate the Feature:
Alright, coool, our feature is ready to be installed now.
Open the command prompt and move to the Features directory. Enter the following command:
stsadm -o installfeature -name EventHandler.SharePoint.SendEmail.Feature

After you have received the “Operation completed successfully” message, navigate to your site in SharePoint. In my case the heirarchy was JumpStart -> JumpStartWeb -> AlertMe.
So, I’ll move to JumpStartWeb -> Site Actions -> Site Settings -> under Site Administration click Site Features. You will see your feature available there as shown below:.

Click Activate button in front of your feature to Activate the feature:

Test your Event Handler:
Go to your document library, in my case it is AlertMe and upload a document:

As soon as you upload the file, you should receive an email to the address specified in your event handler:

Hope this helps–