Today I have been trying to remove web.config entries when a feature is de-activated in WSS. Adding them is easy and there are some good articles (Daniel Larson & Tony Bierman) on how to do that...however, removing them can be problematic when the entries are not configured properly.
I started by reading Daniel's post which includes details of removing entries from web.config, but I could not get it to work!!
It turns out that the Name property (poorly named IMO) of the SPWebConfigModification class is very important when it comes to managing the entry. Not only does it allow the entry to be removed when it is removed from the WebConfigModifications collection, but it also prevents duplicates from being added to web.config.
So my problem was simple...my Name property, which looked fine, was not! I had what appeared to be the correct XPath, add[name='TheKidHandler'], but this was incorrect as 'name' is actually an attribute and so the correct format was add[@name='TheKidHandler'].Once this was corrected everything worked great, including no more duplicates, which I was getting during testing.
The one thing which I did do differently to Daniel was when removing the entries. In his post he suggests you re-create the SPWebConfigModification entry and then call Remove on the WebConfigModifications collection using the new object. I however found it better to loop through the WebConfigModifications collection and remove them based upon the owner, which was my feature. The final code looks like this...
protected void RemoveWebConfigEntries(SPWebApplication oWebApp, string owner)
{
Collection<SPWebConfigModification> oCollection = oWebApp.WebConfigModifications;
int iStartCount = oCollection.Count;
for (int c = iStartCount - 1; c >= 0; c--)
{
SPWebConfigModification oModification = oCollection[c];
if (oModification.Owner == owner)
oCollection.Remove(oModification);
}
if (iStartCount > oCollection.Count)
{
oWebApp.Update();
SPFarm.Local.Services.GetValue<SPWebService>().ApplyWebConfigModifications();
}
}
The morale of this story is that the Name property is really an XPath statement to uniquely identify your element within the parent node specified in the Path property.