Using SPWebConfigModification, Part 1 - The Problem
I've read a lot of posts [this, this, and this, for example] about the SPWebConfigModification beast and I've had a lot of time developing a SharePoint MOSS/WSS feature that utilizes this part of the SharePoint Object Model.
Generally, I see a lot of confusion around the internet about when to use the type EnsureSection vs. EnsureChildNode and the consensus I've seen is to always use EnsureChildNode because it allows you to later delete the section when your feature or site is deleted; I disagree, only partly.
One must realize that SharePoint is a big beast and has a lot of pieces. If you're going to distribute a feature that requires web.config modifications, then you're going to need to ensure that certain sections exist before putting down the child nodes. Go ahead and try to add an appSetting key when the <appSettings> section doesn't exist (as it doesn’t in default WSS installs), it won't work! SharePoint will give a backwards error about not finding the web.config node in the [node] file, like this:
"Failed to apply a web.config modification to file 'configuration/appSettings'. The specified node "C:\Inetpub\wwwroot\wss\VirtualDirectories\80\web.config" was not found in the web.config file."
But as we all know this means it couldn't find the node in the web.config file.
If you debug on MOSS and have a look at the SPWebConfigModification[s] collection inside a web, you might see the httpModules section and the subsequent EnsureChildNode entry for the session state handler. This is a great example of how things should be done, or at least how I think Microsoft thinks it should be done.
Let me quickly mention that there also seems to be some confusion about where to call ApplyWebConfigModifications. The SharePoint SDK documentation states:
To apply modifications that you define through the SPWebConfigModification class to the web.config files in the server farm, call the ApplyWebConfigModifications method on the current content Web service object, as follows: SPWebService.ContentService.ApplyWebConfigModifications.
So, call it from the content service of the web service!
Now, how about a good example...