đź’ˇ
Update: This article was featured in the May 2008 edition of Microsoft's MSDN Magazine.

PDF archive copy

Summary SharePoint 2007 (WSS and MOSS) allows you to easily and safely add and remove modifications to the web.config file. This post briefly covers what the SPWebConfigModification class can do for you, and how to best to use it.

I hope to improve this post with additions, corrections, and contributions from the public, so please provide any constructive comments and suggestions you have.

Technologies this applies to:

  • Windows SharePoint Services 3.0 (WSS 3.0)
  • Microsoft Office SharePoint Server 2007 (MOSS 2007)

Acknowledgements

While I was scavenging for any information I could find regarding the SPWebConfigModification, there were a few posts I found useful. Information seemed to be scarce and I ended up learning most through trial and error; however, there a couple good nuggets and others I must achnowledge.

  • Shawn Feldman is a coworker (very sharp developer) who was the first to make me aware of the SPWebConfigModification class. Additionally, he provided me with the original code samples, some of which I have since modified and included in my WebConfigurator helper class (a separate post to come).
  • Vincent Rothwell has a post entry that provides, in my opinion, a “Best Practice” on how to best remove your modifications using SPWebConfigModification. It’s simple and right on target.
  • Antonz has a post entry that addresses the proper way to create a section that can be removed.
  • Daniel Larson also has a few a posts that provide a basic overview and examples on how to use SPWebConfigModification.

Overview of SPWebConfigModification

Through the use of the SPWebConfigModification class and xpath you can safely add and remove modifications to the web.config file. There are a number of benefits to using SPWebConfigModificaton to modify the web.config.

SharePoint provides access to a SharePoint web application via the object model using the SPWebApplication class. The SPWebApplication class has a SPWebConfigModifications collection property that contains all the modifications (SPWebConfigModification objects) made to this web application’s web.config file. This is also where we can add new modifications and have them applied to the web.config – or remove them. Additionally, you can iterate through this collection and inspect what changes have been applied. This contains all changes – including yours and those made by other assemblies. You can determine (or attempt to determine) where each change was made by inspecting the owner property.

Every modification has an Owner. Every change made the web.config can be assigned an owner. The owner is nothing more than a string value that uniquely identifies your changes from any other changes that have been made, or may be made in the future.  I suggest using the name of the assembly, or the feature name or feature ID.

Removing is not merely changing a value. By assigning an owner to each new change you make, you can very easily remove your changes. In the case where your original modification was an addition, where you added a new node or attribute, your changes are simply deleted and remove from the web.config file when they are removed. In the case where your modification changed the value of an existing node, upon removing your modification SPWebConfigModification automatically assigns the appropriate previous value. For example, let’s say we wanted to change the Trust level in the web.config to “Full” from whatever it currently is. The Trust level is usually set to a value of “WSS_Medium” by default, but it could easily be some other value before we make our changes. The great thing is that we don’t need worry about what the current value is if ever we need to remove our modification. We do this by removing our change, not by trying to change the value back to a predetermined value such as “WSS_Medium” – SPWebConfigModification manages this for us. This is a big advantage.

Propagate your web.config changes across the farm. SharePoint is designed to be very scalable and easily scalable. The changes you make to the web.config will need to be made to every front-end web server in the farm. SPWebConfigModification can manage this for you very easily.

Also, features are likely the method you will want to use to apply your changes. Using a feature (that can be either hidden or visible) will ensure your web.config changes are applied if a new web server is added to the farm, or rebuilt from scratch. Applying your web.config changes via a feature will ensure your changes are applied to new or newly built web servers – without having to refer to documentation or manually apply your changes to the web.config file on each and every web server.

SPWebConfigModification properties

SPWebConfigModification on MSDN

Name
Gets or sets the name of the attribute or section node to be modified or created.  This is an XPath expression relative to the parent node (specified by the Path property). Sometimes this is nothing more than the name of the new or existing node you want to change. For example: “pages”.

However, this often times needs to contain an XPath expression that is more spcific in order to properly specify the correct node to modify (if it exists) or to create.  For example: “add[@assembly=’myAssemblyName’]”

Owner
Gets or sets the owner of the web.config modification. This should to be a unique string value that will allow you to uniquely identify your modifications from any other modifications made to the web.config.  Suggestions are to use the assembly name, feature name, or feature ID.  This will ensure you are able to easily and cleanly remove your modification when the need arises.

Path
Gets or sets the XPath expression that is used to locate the node that is being modified or created. This value usually contains simple XPath expression to the parent node of the item you intend to change or create. For example: “system.web/httpHandlers” or “system.web/customErrors”.

This can also be a more specific XPath expression to select (or create) a node with a specific attribute value. For example:
“configuration/configSections/sectionGroup[@name=’mySection’]”

Sequence
Gets or sets the sequence number the modification. I have not performed any detailed testing with this parameter. I have always just set this value to zero (0) with no problems.

Type
Gets or sets the type of modification for this object instance. The three values available are defined via the SPWebConfigModification.SPWebConfigModificationType and are EnsureChildNode, EnsureAttribute, and EnsureSection. Caution: Use the EnsureSection type with prudence as nodes created with EnsureSection cannot be removed. See Best Practice section below.

UpgradedPersistedProperties
Gets the collection of field names and values for fields that were deleted or changed. I have not investigated this property and do not know of any need for using it. (inherited from SPAutoSerializingObject)

Value
Gets or sets the value of the item to set. This is usually the complete xml element tag or attribute value for the node specified in the Name property (or as the name parameter in the constructor).

How to use SPWebConfigModification

Using SPWebConfigModification is very easy, which makes it even better.

Below is a quick example of code that changes the mode attribute to a value of “Off”. Here is a sample of what the web.config node might look like that this code would be modifying.

<configuration>
	<system.web>
		<customErrors mode="On">    
	</system.web>
 </configuration>

Here is the quick example that will change the mode attribute to “Off”. Comments are inline describing each section of code.

sprivate void SimpleSample()
{
// Get an instance of my local web application
SPWebApplication webApp = new SPSite("http://localhost").WebApplication;

// Create my new modification to set the mode attibute to "Off".
// Example:
SPWebConfigModification modification = new SPWebConfigModification("mode", "system.web/customErrors");
modification.Owner = "SimpleSampleUniqueOwnerValue";
modification.Sequence = 0;
modification.Type = SPWebConfigModification.SPWebConfigModificationType.EnsureAttribute;     modification.Value = "Off";     // Add my new web.config modification.     webApp.WebConfigModifications.Add(modification);    // Save web.config changes.      webApp.Update();     // Applies the list of web.config modifications to all Web applications in this Web service across the farm.
webApp.Farm.Services.GetValue().ApplyWebConfigModifications }

// Get an instance of my local web applicationSPWebApplication
webApp = new SPSite("http://localhost").WebApplication;

// Create my new modification to set the mode attibute to "Off".
// Example: SPWebConfigModification modification = new SPWebConfigModification("mode", "system.web/customErrors");

modification.Owner = "SimpleSampleUniqueOwnerValue";
modification.Sequence = 0;
modification.Type = SPWebConfigModification.SPWebConfigModificationType.EnsureAttribute;
modification.Value = "Off";

// Add my new web.config modification.
webApp.WebConfigModifications.Add(modification);

// Save web.config changes.
webApp.Update();

// Applies the list of web.config modifications to all Web applications in this Web service across the farm.
webApp.Farm.Services.GetValue().ApplyWebConfigModifications

private void SimpleSample() 
{     
	// Get an instance of my local web application     
	SPWebApplication webApp = new SPSite("http://localhost").WebApplication;      

// Create my new modification to set the mode attibute to "Off".     
// Example: <customErrors mode="Off">
	SPWebConfigModification modification = new 		SPWebConfigModification("mode", "system.web/customErrors");    
	modification.Owner = "SimpleSampleUniqueOwnerValue";     
	modification.Sequence = 0;
	modification.Type = SPWebConfigModification.SPWebConfigModificationType.EnsureAttribute;     modification.Value = "Off";     // Add my new web.config modification.     webApp.WebConfigModifications.Add(modification);    // Save web.config changes.      webApp.Update();     // Applies the list of web.config modifications to all Web applications in this Web service across the farm.     webApp.Farm.Services.GetValue<SPWebService>().ApplyWebConfigModifications }

More examples can be found later in the article.  Additonally, I will be posting my WebConfigurator helper class that contains a number of helper methods to centralize and simplify commonly modified elements in the web.config file.

Best Practices

I found it difficult to fully understand exactly how to use SPWebConfigModification as well as how it should and should not be used, and how I should expect it for function. For this reason I have started a list of best practices when using SPWebConfigModification.

Saving your modifications

While first using the SPWebConfigModification class, everything was going fairly smooth with testing and deployment – as it usually does on the developer machine. Of course my development machine is a single farm configuration, which is standard. Executing my web.config modifications on my single server worked just fine. However, when I deployed my code to two other farm configurations, the changes were not being applied to the web.config on any web server. Searching on the Internet surfaced a few other comments posted by others who were experiencing the same problem.

So, to correctly apply your changes on any farm configuration, be sure to perform the following two steps in your code:

  1. Use the ApplyWebConfigModifications() method on the SPWebApplication object you are saving your SPWebConfigModification object to. I don’t understand why this works over the other way, but it solved the problem for me. Example:myWebApp.Farm.Services.GetValue<SPWebService>().ApplyWebConfigModifications

Note: This code did not work across the farm (I could not tell you why).SPFarm.Local.Services.GetValue< SPWebService>().ApplyWebConfigModifications();

  1. Execute the Update() method on the SPWebApplication object. This will serialize the web application state and propagate changes across the farm – including your web.config changes.myWebApp.Update();

So, whenever you want to save your modification to the web.config file, you should execute the following two statements.

// Save web.config changes.
myWebApp.Update();

// Applies the list of web.config modifications to all Web applications in this Web service across the farm.
myWebApp.Farm.Services.GetValue<SPWebService>().ApplyWebConfigModifications

Removing your modifications

You should remove your modifications by checking the owner property on each SPWebConfigModification object in the SPWebConfigModifications collection. There are many examples that demonstrate removing modifications by creating a new SPWebConfigModification object and then removing that object. A must simpler, cleaner, and safer method is to remove your original SPWebConfigModification object by checking the Owner property on the SPWebConfigModification object.  Credit goes to Vincent Rothwell for sharing this logic.  Here is an example:

public void RemoveConfiguration(string owner)
{
   if (myWebApp != null)
   {
      Collection<SPWebConfigModification> collection = myWebApp.WebConfigModifications;      int iStartCount = collection.Count;      // Remove any modifications that were originally created by the owner.
      for (int c = iStartCount - 1; c >= 0; c--)
      {
         SPWebConfigModification configMod = collection[c];         if (configMod.Owner == owner)
            collection.Remove(configMod);
      }      // Apply changes only if any items were removed.
      if (iStartCount > collection.Count)
      {
         myWebApp.Update();
         myWebApp.Farm.Services.GetValue<SPWebService>().ApplyWebConfigModifications
      }
   }
}

Creating Sections
(EnsureSection vs. EnsureChildNode)

When creating new section you should use the EnsureChildNode modification type value instead of the EnsureSection. This will allow you to remove your custom section when the need arises. Antonz also discovered this as well and has an earlier post worth mentioning. Here is an example of the two options, both creating a section node like this: <mySection></mySection>

This cannot be removed (using EnsureSection):

SPWebConfigModification mod = new SPWebConfigModification("mySection", "configuration");
mod.Type = SPWebConfigModification.SPWebConfigModificationType.EnsureSection;

This can be removed (using EnsureChildNode):

SPWebConfigModification mod = new SPWebConfigModification("mySection", "configuration");
mod.Type = SPWebConfigModification.SPWebConfigModificationType.EnsureChildNode;
mod.Value = "<mySection />";

Save Only Once per Event or Feature Activation

It is important to remember that when developing and testing on a single server installation of SharePoint there are many activities that are able to complete instantly.  However, when that same section of code executes on a SharePoint farm with multiple servers the time it takes to complete a given task is longer.  This is due to timer jobs and farm synchronization events that must occur.

For this reason, you should only execute the ApplyWebConfigModifications() method only once within a feature activation or event handler.  If more than one call to the ApplyWebConfigModifications() method is made in close succession you will likely get the following error:

A web configuration modification operation is already running.

This is because request to save your changes from the first call to the ApplyWebConfigModifications() is not fully completed across the farm.

SPWebConfigModification Sample Feature

I intend to post a blog entry containing code samples of my WebConfigurator class and a sample of how to implement SPWebConfigModification using a web application feature.

WebConfigurator – a helper class to assist in using SPWebConfiguration.

References