Pages

Thursday 9 May 2013

Removing web parts from the gallery when feature deactivated


Removing web parts from the gallery when feature deactivated

Although I love the solution framework I do have one gripe. It doesn't remove the web parts deployed to the gallery when the solution is retracted. To address this I have written a little custom code in a feature deactivation event:
public override void FeatureDeactivating(SPFeatureReceiverProperties properties)
{
  // manually delete web parts from the gallery

  using (SPSite site = (SPSite)properties.Feature.Parent)
  {
    using (SPWeb web = site.OpenWeb()) 
    {
      SPList list = web.Lists["Web Part Gallery"];

      // go through the items in reverse
      for (int i = list.ItemCount -1; i >= 0; i--)
      {
        // delete web parts that have been added
        if (list.Items[i].Name == "Login.webpart")
        {
          list.Items[i].Delete();
        }
      }
    }
  }
}
Note that I have written this with 'using' clauses to ensure that the web and site objects are properly disposed of after use. I also iterate through the collection in reverse in case I want to delete many items.
To make the code run I will have to add something like the following to the feature.xml
ReceiverAssembly="Provoke.UserAdminFeatures, Version=1.0.0.0, Culture=neutral, PublicKeyToken=083c78f3ca84e8af"
ReceiverClass="Provoke.UserAdminFeatures.FeatureActivation"

No comments:

Post a Comment