Register an event handler
Ok. We just created our first event handler. Now we must register it and attach a list of a SharePoint site. To register the handler, we can use the use of a feature (one of the new mechanisms of Sharepoint Services 3.0, for this implementation refer to the reading of this tutorial ) and to attach it to an object we must write code. NET make a windows form, or simply a console application that transaction through the SharePoint object model. We see, therefore, the implementation of a console application that registers the event handler for example we saw previously:
Code:
namespace AddHandler
{
class Program
{
static void Main (string [] args)
{
SiteURL String = ConfigurationManager.AppSettings ["SiteURL"];
string listname = ConfigurationManager.AppSettings ["listname"];
using (SPSite site = new SPSite (SiteURL))
{
using (SPWeb web = site.OpenWeb ())
{
SPList list = web.Lists [listname];
list.EventReceivers.Add (SPEventReceiverType.ItemAdding,
"Peppe.Sharepoint.Handlers, Version = 1.0.0.0,
Culture = neutral,
PublicKeyToken = 78fde53655a71179 "
"Peppe.Sharepoint.Handlers.HelloEventHandler");
list.Update ();
Console.WriteLine ("Handlers inserted successfully!");
}
}
Console.WriteLine ("Press any key to exit ...");
Console.Read ();
}
}
}
Note: I, for mere convenience, I usually add a second project to my solution and create a console application as soon as this view, that you register handlers. E 'but also a free tool to avoid this job: Event Handler Explorer (directly from the blog of Patrick Tisseghem MVP - U2U). Moreover, the choice of registering the handler in code, was included as a new feature in version 3.0 of Sharepoint (which we will see more news in the next chapter). EventSinkAssembly remain functional properties, and EventSinkClass EventSinkData via web interface.
Before we launch this console application from the server where Sharepoint is installed, we put the assembly containing our handler in the Global Assembly Cache (GAC) of the server itself. To do this, we can go to Control Panel> Administration Tools> Microsoft. NET 2.0 Configuration> Manage the assembly cache> Add an assembly to the assembly cache, and select our dll, or you can create a. Bat file containing these instructions:
Code:
gacutil / U Peppe.Sharepoint.Handlers
gacutil / i Peppe.Sharepoint.Handlers.dll
iisreset
That do nothing to remove the assembly from the GAC (if already installed), install it again (in case there was a new version) and finally to reset the IIS web server.
Note: The reset is necessary to warn of Sharepoint presence of a new version of our assemblies in the GAC.
Now the handler is connected to our list. By creating a new item, you can see its proper functioning.
Bookmarks