Tuesday, October 18, 2011

Remove Event Receiver in Sharepoint List

I encountered a strange behavior in SharePoint; this phenomenon happens when I created an event handler and attach it to a list template using a web-site level feature. I saved the list as template, the event handler reference is saved inside the list template (STP file) and when I created an instance using the template it caused the following problems:
1.     The event handler activated automatically on a web site where the feature is not enabled.
2.     If the event feature is enabled in the web site the event will pop twice (In my case it was sending mail twice on Item Added event).
I wrote a small console application to remove attached event handlers.

        static void Main(string[] args)
        {
            try
            {
                string strAppUrl = ConfigurationManager.AppSettings["applicationUrl"].ToString();
                string[] strDelimit = { "/" };
                string[] strSites = strAppUrl.Split(strDelimit, StringSplitOptions.RemoveEmptyEntries);
                string strSiteURL = strSites[0] + "//" + strSites[1];
                string strWebRelUrl = strAppUrl.Substring(strSiteURL.Length);
                using (SPSite site = new SPSite(strSiteURL))
                using (SPWeb web = site.OpenWeb(strWebRelUrl))
                {
                    string listName = ConfigurationManager.AppSettings["ListName"].ToString();
                    SPList list = web.Lists[listName];

                    if (list != null)
                    {
                        int countVal = list.EventReceivers.Count;
                        if (countVal > 0)
                        {
                            for (int i = 0; i < countVal; i++)
                            {
                                Console.WriteLine(list.EventReceivers[0].Name.ToString() + "Deleting");
                                list.EventReceivers[0].Delete();
                            }
                            //Update the list.
                            list.Update();
                            Console.WriteLine("Operation completed succesfully");

                            Console.ReadLine();
                        }
                        else
                        {
                            Console.WriteLine("No event handlers are attached to the list : " + list.Title);
                            Console.ReadLine();
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                Console.Write(ex.Message);
                Console.ReadLine();
            }
        }
        

No comments:

Post a Comment