Friday, October 24, 2008

How to register your custom events in MOSS 2007

You can register your custom MOSS event handlers using a few techniques. I have always been a fan of a simple Console application which will do the trick. The pre-requisites are:
1) Ensure that the assembly implementing the custom event handlers in strongly typed 
2) Ensure that your custom event handlers strongly typed assembly has been registered in the GAC of the server (or on each server on a web farm).

Once you have checked the pre-requisites you can write a Console application to do your job. An example is as below:

using System;
using System.Collections.Generic;
using System.Text;
using Microsoft.SharePoint;

namespace trusharWebsite.Website.RegisterEventHandlers
{
// Console application to register custom event handlers on a specific list called "Comments" on the website
class Program
{
static void Main(string[] args)
{
SPSite curSite = new SPSite("http://trushar/trusharBlog");
SPWeb curWeb = curSite.OpenWeb();

SPList commentsList = curWeb.Lists["Comments"];

string asmName = "trusharWebsite.WebSite.EventHandler, Version=1.0.0.0, Culture=neutral, PublicKeyToken=342fb345e6f432a";
string className = "trusharWebsite.WebSite.EventHandler.AddmyItemHandler";

commentsList.EventReceivers.Add(SPEventReceiverType.ItemAdding, asmName, className);
commentsList.EventReceivers.Add(SPEventReceiverType.ItemUpdating, asmName, className);
}
}
}