Please upgrade your web browser now. Internet Explorer 6 is no longer supported.
Zac Smith
SharePoint, WSS and MOSS development.

Removing web parts from the gallery when feature deactivated

by Zac Smith 16-May-07, 1 Comment

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"

More details about adding events to features can be found in the WSS SDK here.

Categories:
1 response so far:
  • Thanks for providing the solution, I would add return or break at the end of the delete to break out the loop. // delete web parts that have been added if (list.Items[i].Name == "Login.webpart") { list.Items[i].Delete(); return; }

 

Post a Comment:
Name:
URL:
Email:
Comments: