My Photo

Technical Architect with over 15 years experience in a wide range of technologies.

@TheCodeKing

rss feed

Working with SPWebConfigModification | Wednesday, November 18, 2009

Introduction

The following tips relate to working with the SharePoint SPWebConfigModification API in order to manage changes to the web.config. Note it's not recommended that you modify the web.config directly as this may have side effects with the running of your SharePoint instance, and changes may be lost when installing updates or service packs.

Avoiding Duplicates

When working with the SPWebConfigModification API, the name property should be set to an xPath expression that identifies the configuration change being made. This should be an expression relative to the Path property. This prevents duplicate changes being made in the web.config. If an arbitrary name is used instead, then the system will not throw an error but may lead to duplicate entries.

SPWebService service = SPWebService.ContentService;

SPWebApplication webApp = properties.Feature.Parent as SPWebApplication;

myModification.Path = "configuration/system.web/httpModules";

myModification.Name = "add[@name='myModule']";

myModification.Sequence = 0;
myModification.Owner = this.GetType().FullName;
myModification.Type = SPWebConfigModification.SPWebConfigModificationType.EnsureChildNode;
myModification.Value = "<add name='myModule' type='myModule, myAssembly' />";

service.WebConfigModifications.Add(myModification);
service.Update();
service.ApplyWebConfigModifications();

Removing Entries

To ensure your entries can be removed via code (such on feature deactivate), it's a good idea to set the owner of the SPWebConfigModification instance as in the example above. It's then possible to loop through the config settings and remove the entries that were previously set by the same codebase

SPWebApplication webApp = properties.Feature.Parent as SPWebApplication;
Collection modsCollection = webApp.WebConfigModifications;
int count = modsCollection.Count;
for (int i = count-1; c >= 0; i--)
{
 SPWebConfigModification mod = modsCollection[i];
 if (mod.Owner == this.GetType().FullName)
 {
  modsCollection.Remove(mod);
 }
}
webApp.Update();
webApp.Farm.Services.GetValue().ApplyWebConfigModifications();

No comments:

Post a Comment