Wednesday, August 8, 2007

Strange Results When Adding Web.Config Values

SharePoint provides a programmatic way of editing existing values and adding new values to a web application's web.config file - through the use of the SPWebConfigModification class (defined in the Microsoft.SharePoint.Adminstration namespace).

There are plenty of posts around explaining how to use this class, the basic pattern for adding a custom value being the following:

        private void AddWebConfigEntry(
string keyName, string entryValue)
        {
            SPWebConfigModification modification 
= new SPWebConfigModification
                 (string.Format("add[@key=\"{0}\"]", keyName)
                 , 
"configuration/appSettings");
            
modification.Owner Constants.FEATURE_NAME;
            
modification.Sequence 0;
            
modification.Type SPWebConfigModification.SPWebConfigModificationType.EnsureChildNode;
            
modification.Value entryValue;
            
_webApp.WebConfigModifications.Add(modification);
            
_webApp.Update();
        
}

Wen I first wrote and used this function, I found that the key was correctly added to the web.config file, but was not being removed by a similar deletion function I wrote. And everytime I called this AddWebConfigEntry function, a duplicate entry was written to the file.

Turned out that I had missed the escaped double quotes in the first argument of the SPWebConfigModification constructor call. What made this a tricky effect to fault-find was the fact that the new web.config entry was being created.

So the morale of this tale is - be VERY careful with the arguments to that constructor!

No comments: