Introduction
We may came across the situation to remove all the custom webparts while feature deactivating. Here we are going to see how to remove the webparts programmatically.
Code
Paste the below code in FeatureDeactivating method
SPSite site = properties.Feature.Parent as SPSite;
if (site != null)
{
var definedElements = properties.Definition.GetElementDefinitions(CultureInfo.InvariantCulture);
var allFiles = definedElements.Cast<SPElementDefinition>()
.SelectMany(x => x.XmlDefinition.ChildNodes.Cast<XmlElement>()
.Where(f => f.Name.Equals("File"))
.Select(f => f.Attributes["Url"].Value)).ToList();
var webPartGallery = site.RootWeb.Lists["Webpart Gallery Name"];
var webPartsToDelete = webPartGallery.Items.Cast<SPListItem>()
.Where(w => allFiles.Contains(w.File.Name)).ToList();
for (var index = webPartsToDelete.Count - 1; index >= 0; --index)
{
var webPartItem = webPartsToDelete[index];
webPartItem.Delete();
}
}
No comments:
Post a Comment