Navigation

Monday, 12 January 2015

Attach event receiver in a particular list by Feature receiver

const string _listName = Constants.ListName;

        public override void FeatureActivated(SPFeatureReceiverProperties properties)
        {
            try
            {
                SPWeb oWeb = (SPWeb)properties.Feature.Parent;
                SPList oList = oWeb.Lists[_listName];
                DeleteReceiver(oList);
                oWeb.Lists[_listName].EventReceivers.Add(SPEventReceiverType.ItemAdded, Assembly.GetExecutingAssembly().FullName, "Class Name_Reviewers.SetReviewers.SetReviewers");
                oWeb.Lists[_listName].EventReceivers.Add(SPEventReceiverType.ItemUpdated, Assembly.GetExecutingAssembly().FullName, "ClassName_Reviewers.SetReviewers.SetReviewers");
            }
            catch (Exception ex)
            {
                Constants.LogToUls(Constants.LogCategory, string.Format("Exception occured on featureactivation: Message {0} - Stacktrace {1} ", ex.Message, ex.StackTrace));
            }
        }

------------
public override void FeatureDeactivating(SPFeatureReceiverProperties properties)
        {
            try
            {
                SPWeb oWeb = (SPWeb)properties.Feature.Parent;
                SPList oList = oWeb.Lists[_listName];
                DeleteReceiver(oList);
            }
            catch (Exception ex)
            {
                Constants.LogToUls(Constants.LogCategory, string.Format("Exception occured on FeatureDeactivating: Message {0} - Stacktrace {1} ", ex.Message, ex.StackTrace));
            }
        }
-------------------
private void DeleteReceiver(SPList oList)
        {
            try
            {
                for (int i = oList.EventReceivers.Count - 1; i >= 0; i--)
                {
                    if (oList.EventReceivers[i].Type.Equals(SPEventReceiverType.ItemAdded) || oList.EventReceivers[i].Type.Equals(SPEventReceiverType.ItemUpdated))
                    {
                        oList.EventReceivers[i].Delete();
                    }
                }
            }
            catch (Exception ex)
            {
                Constants.LogToUls(Constants.LogCategory, string.Format("Exception occured on delete receiver: Message {0} - Stacktrace {1} ", ex.Message, ex.StackTrace));
                throw;
            }
        }

No comments:

Post a Comment