using System;
using System.Runtime.InteropServices;
using System.Security.Permissions;
using Microsoft.SharePoint;
using Microsoft.SharePoint.Security;
//Code courtesy of @timferro, @dannyjessee, MSDN, and the internet
namespace SharePointProject1.Features.Feature1
{
///
/// This class handles events raised during feature activation, deactivation, installation, uninstallation, and upgrade.
///
///
/// The GUID attached to this class may be used during packaging and should not be modified.
///
[Guid("7fc8877e-a88a-45d2-9463-3f640a2b4be7")]
public class Feature1EventReceiver : SPFeatureReceiver
{
// Uncomment the method below to handle the event raised after a feature has been activated.
public override void FeatureActivated(SPFeatureReceiverProperties properties)
{
//Add event receiver to Custom List
using (SPWeb web = properties.Feature.Parent as SPWeb)
{
SPSecurity.RunWithElevatedPrivileges(delegate()
{
SPList list = web.Lists["TestCustom"];
AddCustomEventReceivers(list);
});
}
}
private void AddCustomEventReceivers(SPList list)
{
//Clear any existing event receivers from list
ClearExistingCustomEventReceivers(list);
//Add new custom event receivers
string asmName = "SharePointProject1, Version=1.0.0.0, Culture=neutral, PublicKeyToken=43a1773c7939c303";
string itemReceiverName = "SharePointProject1.EventReceiver1.EventReceiver1";
list.EventReceivers.Add(SPEventReceiverType.ItemAdded, asmName, itemReceiverName);
list.EventReceivers.Add(SPEventReceiverType.ItemUpdated, asmName, itemReceiverName);
list.EventReceivers.Add(SPEventReceiverType.ItemUpdating, asmName, itemReceiverName);
list.EventReceivers.Add(SPEventReceiverType.ItemDeleted, asmName, itemReceiverName);
list.EventReceivers.Add(SPEventReceiverType.ItemDeleting, asmName, itemReceiverName);
}
private void ClearExistingCustomEventReceivers(SPList list)
{
for (int x = list.EventReceivers.Count - 1; x >= 0; x--)
{
SPEventReceiverDefinition rcv = list.EventReceivers[x];
if(rcv.Assembly.Contains("SharePointProject1"))
{
list.EventReceivers[x].Delete();
}
}
}
// Uncomment the method below to handle the event raised before a feature is deactivated.
public override void FeatureDeactivating(SPFeatureReceiverProperties properties)
{
}
// Uncomment the method below to handle the event raised after a feature has been installed.
public override void FeatureInstalled(SPFeatureReceiverProperties properties)
{
}
// Uncomment the method below to handle the event raised before a feature is uninstalled.
public override void FeatureUninstalling(SPFeatureReceiverProperties properties)
{
}
// Uncomment the method below to handle the event raised when a feature is upgrading.
//public override void FeatureUpgrading(SPFeatureReceiverProperties properties, string upgradeActionName, System.Collections.Generic.IDictionary parameters)
//{
//}
}
}