only My site

Friday, August 24, 2012

SharePoint : Add Event receiver to List programmatically

We may sometimes have need to create Event recivers as a DLL and use it for a particular List. Creating eveint receiver is out of scope of this page and it is easy and please click this link to know more about event receiver

using (SPSite site = new SPSite("http://localhost"))
{
        using (SPWeb web = site.OpenWeb())
                {
                    SPList list = web.Lists["Shared Documents"];
                    SPEventReceiverDefinition def = list.EventReceivers.Add();
                    def.Assembly = "ERDefinition, Version=1.0.0.0, Culture=Neutral, PublicKeyToken=704f58d28567dc00";                    def.Class = "ERDefinition.ItemEvents";
                    def.Name = "ItemAdded Event";
                    def.Type = SPEventReceiverType.ItemAdded;
                    def.SequenceNumber = 1000;
                    def.Synchronization = SPEventReceiverSynchronization.Synchronous;
                    def.Update();
                }
}

Alternative way is as follows

using (SPSite site = new SPSite("http://localhost"))
{
        using (SPWeb web = site.OpenWeb())
                {
                    SPList list = web.Lists["Shared Documents"];
                    string strAssembly="ERDefinition, Version=1.0.0.0, Culture=Neutral, PublicKeyToken=704f58d28567dc00"; 
                    string strClass = "ERDefinition.ItemEvents";
                    web.AllowUnsafeUpdates = true;
                    list.EventReceivers.Add(SPEventReceiverType.ItemAdded, strAssembly, strClass );
                    list.Update();
                    web.AllowUnsafeUpdates = false;
                }
}

Some notes about Event reciver base class

We need to use "SPItemEventReceiver" base class to create event receiver for list items. we need to overwrite the methods from the base class such as ItemAdded, ItemUpdated etc.

The other event reciver base classes are
the base class have 2 methods this.EnableEventFiring() and this.DisableEventFiring() which will help us to stop nested event receiver calls. The following example prevents the nested call of the ItemUpdated method call.

public override void ItemUpdated(SPItemEventProperties properties)

{
    this.DisableEventFiring();
        SPListItem item = properties.ListItem;
    item[
"Title"] = properties.ListItem["Title"].ToString() + " - Item Updated";    item.Update();

        this.DisableEventFiring();
}

No comments: