Adding and removing Web config modifications

When building an application for SharePoint, if you’re making changes to the Web.config, they should be deployed SPWebconfigModifications. This isn’t that easy, really, but works well enough, and there are good articles about how to add them – but my code looks like:

SPWebConfigModification modification = new SPWebConfigModification(
     "add[@name='MyNavProvider']",
     "configuration/system.web/siteMap/providers");
modification.Value = "<add name="MyNavProvider" type="{Assembly info here!}" />";;
modification.Sequence = 0;
modification.Type = SPWebConfigModification.SPWebConfigModificationType.EnsureChildNode;
modification.Owner = "MyConfigModification;

webApp.WebConfigModifications.Add(modification);
webApp.Update();

That works, but what about removing them? It’s important to do this – otherwise you can cripple a system. Well, I basically do the same as Vincent Rothwell – loop through the existing modifications finding ones with the correct owner, then then delete them.

However, I did have a problem the other day which took hours to track down. When I tried to remove my SPWebConfigModification, it would be removed – but the XML remained in my web.config. Eventually I realised something pretty obvious -the ‘name’ is really part of an XPath query used to find the node we’d added, in order to remove it. From MSDN:

When the type of web.config modification is EnsureChildNode, the Name property refers to an XPath expression that uniquely identifies the node under the parent node, as identified by the Path property

Therefore, the ‘name’ in my Name property must match the ‘name’ in the XML node I’d inserted in my web.config.

Mine were different (though my own stupidity), so the Remove operation was trying to remove a different XML node to the one I’d added.

Adding and removing Web config modifications

2 thoughts on “Adding and removing Web config modifications

  1. Steve says:

    This was exactly what I was looking for – thanks.

    One note though, I had to add the following line after the webApp.Update(); to get it to write to the web.config:
    SPFarm.Local.Services.GetValue().ApplyWebConfigModifications();

    Although now it’s updating all the web.config files…

    Like

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s