Registering and Removing Event Handlers
Posted: 24/11/2009 Filed under: Development | Tags: Event Handlers, WSS 3.0 Leave a comment »This post is more of a reminder to myself, as I tend to forget the process of registering and/or removing an Event Handler from SharePoint v3.0
Register
// variable declaration
string asmName = "<4-part-assembly-name>";
string clsName = "<class name>";
// initialisation code
SPList oList = web.Lists["<relevant list>"];
oList.EventReceivers.Add(SPEventReceiverType.ItemAdded, asmName, clsName);
oList.Update();
// clean up code
The above code registers an event handler of type ItemAdded to a list, that is shown as <relevant list>.
Remove
// initialisation code
SPList oList = web.Lists["<relevant list>"];
foreach (SPEventReceiverDefinition erDef in oList.EventReceivers)
{
erDef.Delete();
oList.Update();
}
// clean up code
The above code removes all event handlers from the that is specified, as shown as <relevant list>. Optionally, we can choose to remove event handlers of a particular type, see below.
foreach (SPEventReceiverDefinition erDef in oList.EventReceivers)
{
if(erDef.Type == SPEventReceiverType.ItemAdding)
{
erDef.Delete();
oList.Update();
}
}
The above code removes all event handlers of type ItemAdding. Finally, we can even choose to remove a particular event handler specifically, as shown below.
// variable asmName declared
foreach (SPEventReceiverDefinition erDef in oList.EventReceivers)
{
if(erDef.Assembly == asmName)
{
erDef.Delete();
oList.Update();
}
}
The option to register and/or remove event handler can be done by simply whipping up Console App or a Windows Form App to run the above code. However, it is best practice to have them run within a Feature Receiver.