Removing Event Handlers in the Feature Deactivated

30 01 2009

If you use a featurereciever to install your event handler when you activate or install your feature then you can also uninstall/remove the event handler from the list/lists when the feature is either uninstalled or deactivated.

The code for removing the event handler is slightly more complex than adding the event handler and involves looping through the event receivers on the list and removing the one that matches the assembly name which you pass in.

Code:

//Open the parent site and web

            using (SPSite site = (SPSite)properties.Feature.Parent)
            {
                using (SPWeb web = site.OpenWeb())
                {
                    //Grab the required lists

                    SPList TheList = web.Lists[“Shared Documents”];

                    //Declare the full assembly name

                    String AssemblyName = “SharedDocumentsHandler, Version=1.0.0.0, Culture=neutral, PublicKeyToken=928f76143tc8cbd2”;

                    //Create a new integer

                    int i;

                    //Use the above integer to loop through the event recievers on the first list and delete the above assembly

                    for (i = 0; i < TheList.EventReceivers.Count; i++)
                    {
                        if (TheList.EventReceivers[i].Assembly.Equals(AssemblyName))

                            TheList.EventReceivers[i].Delete();

                    }

                    //Update the list

                    TheList.Update();

//Update the SharePoint web

                    web.Update();

}

}

You can do the above for the FeatureDeactivating or FeatureUninstalling methods :-).

Advertisements

Actions

Information

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s




%d bloggers like this: