I have a problem in which SharePoint adds dublicate entries in web.config upon feature activation. This is the code i'm currently using:
//Add setting
string entry = "<add key=\"foo\" value=\"bar\" />";
SPWebConfigModification modification = new SPWebConfigModification();
modification.Path = "configuration/appSettings";
modification.Name = "add[@name='foo']";
modification.Value = entry;
modification.Owner = owner;
modification.Sequence = 0;
modification.Type = SPWebConfigModification.SPWebConfigModificationType.EnsureChildNode;
site.WebApplication.WebConfigModifications.Add(modification);
site.WebApplication.Update();
site.WebApplication.Farm.Services.GetValue<SPWebService>().ApplyWebConfigModifications();
// Remove setting
Collection<SPWebConfigModification> oCollection = site.WebApplication.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)
{
site.WebApplication.Update();
SPFarm.Local.Services.GetValue<SPWebService>().ApplyWebConfigModifications();
}
The entry is added but not removed when the feature is deactivated and so multiple entries are added when the feature is reactivated. I've tried following the example at http://msdn.microsoft.com/en-us/library/cc768610.aspx (adding all attributes to the SPWebConfigModification.Name property along with updating the web application and applying web config modifications immediately after being removed) but it did not help. I also tried different combinations on what to put in the SPWebConfigModification.Name property but that did not help either. I tried copying the exact example from http://daniellarson.spaces.live.com/blog/cns!D3543C5837291E93!958.entry and http://blog.thekid.me.uk/archive/2007/03/20/removing-web-config-entries-from-sharepoint-using-spwebconfigmodification.aspx but the entry is still not removed.
I can't figure out whether the problem is related to adding the item or removing it. When debugging the feature deactivation clearly shows that the SPWebApplication.WebConfigModifications collection contains 1 element and when calling Collection<SPWebConfigModification>.Remove(mySPWebConfigModification) the entry is indeed removed from the collection but the change is never provisioned across the farm even though both SPWebApplication.Update() and SPFarm.Local.Services.GetValue<SPWebService>().ApplyWebConfigModifications() are called. Can anyone tell me why this won't work?