When writing Item Event receiver one way to register the event with list is using Feature Receivers. I will go through this approach in this post. What is really needed to modify lists by adding event receivers to the list in the FeatureActivated event and doing reverse i.e. deleting the Item event in Feature deactivating event. However SPFeature Receiver contains all abstract method so you will need to override them as well.
public class DFeatureReceiver: SPFeatureReceiver
{
public override void FeatureActivated(SPFeatureReceiverProperties properties)
{
SPWeb MyCurrentWeb = properties.Feature.Parent as SPWeb;
SPSecurity.RunWithElevatedPrivileges(delegate
{
using (SPSite site = new SPSite(MyCurrentWeb.Site.ID))
{
using (SPWeb web = site.OpenWeb(MyCurrentWeb.ID))
{
SPList listDisc = web.Lists["My List"];
string strTypeName = Assembly.GetExecutingAssembly().FullName;
string strReceiverClass = "a.b.c.DIReciever";
if(listDisc!=null)
{
listDisc.EventReceivers.Add(SPEventReceiverType.ItemAdded, strTypeName, strReceiverClass);
}
}
}
});
}
public override void FeatureDeactivating(SPFeatureReceiverProperties properties)
{
SPWeb MyCurrentWeb = properties.Feature.Parent as SPWeb;
SPSecurity.RunWithElevatedPrivileges(delegate
{
using (SPSite site = new SPSite(MyCurrentWeb.Site.ID))
{
using (SPWeb web = site.OpenWeb(MyCurrentWeb.ID))
{
SPList listDisc = web.Lists["My List"];
string strTypeName = Assembly.GetExecutingAssembly().FullName;
SPEventReceiverDefinitionCollection evntRecDefnColl = listDisc.EventReceivers;
Guid[] arrGuids = new Guid[evntRecDefnColl.Count];
int intCtr = 0;
foreach (SPEventReceiverDefinition erd in evntRecDefnColl)
{
if (erd.Assembly.ToLower().Equals(strTypeName.ToLower()))
{
arrGuids[intCtr++] = erd.Id;
}
}
Guid guidTmp = new Guid("{00000000-0000-0000-0000-000000000000}");
for (int i = 0; i < arrGuids.Length; i++)
{
if (arrGuids[i] != null && arrGuids[i] != guidTmp)
{
evntRecDefnColl[arrGuids[i]].Delete();
}
}
}
}
});
}
catch (Exception ex)
{}
}
Now moving on to Item Event reciever just inherit class from SPItemEventReceiver and override the methods .. remember one thing that all ...ing events are before events and ...ed events are after events (generally written as async event but doesnt executes asynchronously)
public class DIReciever: SPItemEventReceiver
{
public override void ItemAdded(SPItemEventProperties properties)
{
base.ItemAdded(properties);
SPListItem lstItem= properties.ListItem;
}
}
Thursday, June 25, 2009
Subscribe to:
Post Comments (Atom)

No comments:
Post a Comment