As a part deployment you may find it necessary to push out a change to a SharePoint web application's web.config. A web.config modification definition is expressed as a set of commands that, when processed by the web.config manipulator in Windows SharePoint Services, changes the state of web.config.
I used the WebConfigModifications property of the SPWebApplication class to get the collection of web.config modifications in the Web application.
There are different types of changes you may want to do in web.config.
1) Modify Attribute of some element .
Let’s change trust level to Full. Trust element is child element of section <configuration><system.web> and Trust element has attribute “level”. Code to do this
private void SetWebConfig(SPSite site) // Site can be pass from Activate feature of any other context
{
SPWebApplication webApp = site.WebApplication;
System.Collections.ObjectModel.Collection<SPWebConfigModification> allModifications = webApp.WebConfigModifications;
SPWebConfigModification myModification = new SPWebConfigModification("level", "configuration/system.web/trust");
myModification.Value = "Full"; // the value of the item to set.
myModification.Owner = typeof(FeatureReceiver).FullName; // owner of the web.config modification
myModification.Sequence = 1; // Sequence number the modification if more than one modification to be done increase this by one in each modification
myModification.Type = SPWebConfigModification.SPWebConfigModificationType.EnsureAttribute; // the type of modification implied by the class in our case it is Ensure Attribute
allModifications.Add(myModification);
SPFarm.Local.Services.GetValue<SPWebService>().ApplyWebConfigModifications();
webApp.Update();
}
2) Add new Element in some section
Let’s add new Assembly System.Web.Extensions.dll. Here is code to do this
…
myModification = new SPWebConfigModification("add[@name=\"assembly\"]", "/configuration/system.web/compilation/assemblies");
myModification.Value = "<add assembly=\"System.Web.Extensions, Version=1.0.61025.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35\"/>";
myModification.Sequence = 2;
myModification.Type = SPWebConfigModification.SPWebConfigModificationType.EnsureChildNode;
myModification.Owner = typeof(FeatureReceiver).FullName;
allModifications.Add(myModification);
…
3) Add new Section
Let’s add new section <testSection></testSection> inside configuration . Here is code to do this
…
myModification = new SPWebConfigModification ("testSection", "configuration");
myModification.Value = “"<testSection></testSection>";
myModification.Sequence = 3;
myModification.Type = SPWebConfigModification.SPWebConfigModificationType.EnsureSection;
myModification.Owner = typeof(FeatureReceiver).FullName;
allModifications.Add(myModification);
…
If you are doing multiple changes, call ApplyWebConfigModifications() after all changes added. I have used this code to create MOSS 2007 feature that enables MS AJAX Extension in MOSS site.