Wednesday, October 27, 2010

Attach Event Receivers in Sharepoint 2007

How to Attach an Event Receiver with a List Programmatically

An event receiver can be attached with the list by 2 Ways.

1. By XML

2. By Code

1. By XML:

Any event receiver needs a Feature to Attach that Event Receiver with the List Template.

So the Feature.xml file will be like follows.

xml version="1.0" encoding="utf-8"?>

<Feature Id="GUID"

Title="Sample Title"

Description="Sample Description"

Version="12.0.0.0"

Hidden="FALSE"

Scope="Scope of the Feature"

ImageUrl="Optional URL"

xmlns="http://schemas.microsoft.com/sharepoint/">

<ElementManifests>

<ElementManifest Location="Element.xml">ElementManifest>

ElementManifests>

Feature>

The last tag is the ElementManifests Tag. In the ElementManifests Tag, we will mention the Element file. In the ElementFile only we will Attach the EventReceiver with the List by using the ListTemplateID.

The Element.xml file will be as follows.

xml version="1.0" encoding="utf-8" ?>

<Elements xmlns="http://schemas.microsoft.com/sharepoint/">

<Receivers ListTemplateId="101 – ListTemplate ID of the CustomList">

<Receiver>

<Class>Receiver Class Class>

<Assembly>Receiver AssemblyAssembly>

<Name>Name of the Event ReceiverName>

<Type>ItemAddingType>

<SequenceNumber>Any Unique Sequence NumberSequenceNumber>

Receiver>

Receivers>

Elements>

Once the Feature is Activated, then the EventReceiver “ItemAdding” is added with the Custom List. The Receiver Class will be executed when the Item is added in the List.

The EventReceiver Class needs to be inherited from the SPItemEventReceiver Class. Once this is Class is inherited, then the methods can be Overridden.

public override void ItemAdding(SPItemEventProperties properties)

{

}

2. Through Code:

The above mentioned method can be used for SPItemEventReceiver. In the Same Manner, SpWebEventReceiver Class can also be inherited and the Events Related to the Web can be triggered.

public class SearchCenterWebDeletingEventReceiver : SPWebEventReceiver

{

public override void WebDeleting(SPWebEventProperties properties)

{

try

{

}

catch (Exception ex)

{

}

}

}

This EventReceiver class needs to be Attached with the Web while creating the web itself. To accompalish that,

private void AttachWebDeletingEventReceiver(SPWeb web)

{

try

{

SPEventReceiverDefinitionCollection EventReceivers = web.EventReceivers;

SPEventReceiverDefinition EventReceiverDefinition = EventReceivers.Add();

EventReceiverDefinition.Name = EventReceiverName;

EventReceiverDefinition.Assembly = Assembly Name;

EventReceiverDefinition.Class = Class Name;

EventReceiverDefinition.Type = SPEventReceiverType.WebDeleting;

EventReceiverDefinition.SequenceNumber = Any Sequence Number;

EventReceiverDefinition.Update();

}

}

catch (Exception ex)

{

}

}

No comments: