3 out of 6 rated this helpful - Rate this topic

SPWebConfigModification Class

Windows SharePoint Services 3
Holds modifications that are made to the web.config.

Namespace: Microsoft.SharePoint.Administration
Assembly: Microsoft.SharePoint (in microsoft.sharepoint.dll)
[SharePointPermissionAttribute(SecurityAction.LinkDemand, ObjectModel=true)] 
public sealed class SPWebConfigModification : SPAutoSerializingObject

A collection of web.config modifications is a set of commands that, when processed by the web.config manipulator in Windows SharePoint Services, change the state of the web.config file. You can string together a set of these commands to ensure that they apply the desired tags and attributes within web.config. Each modification is expressed as an object in the administrative object model.

Use the WebConfigModifications property of the SPWebApplication or SPWebService class to get the collection of web.config modifications either in the Web application or in all Web applications within the Web service. 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.

The following example adds a safe control entry to the safe controls section in web.config throughout the server farm.

SPWebService myService = SPWebService.ContentService;

SPWebConfigModification myModification = new SPWebConfigModification();
myModification.Path = "configuration/SharePoint/SafeControls";
myModification.Name = "SafeControl[@Assembly='MyCustomAssembly'][@Namespace='MyCustomNamespace'][@TypeName='*'][@Safe='True']";
myModification.Sequence = 0;
myModification.Owner = WebConfigModificationFeatureReceiver.OwnerId;
myModification.Type = SPWebConfigModification.SPWebConfigModificationType.EnsureChildNode;
myModification.Value = "<SafeControl Assembly='MyCustomAssembly' Namespace='MyCustomNamespace' TypeName='*' Safe='True' />";

myService.WebConfigModifications.Add(myModification);
myService.Update(); 
myService.ApplyWebConfigModifications();
System.Object
   Microsoft.SharePoint.Administration.SPAutoSerializingObject
    Microsoft.SharePoint.Administration.SPWebConfigModification
Any public static (Shared in Visual Basic) members of this type are thread safe. Any instance members are not guaranteed to be thread safe.
Did you find this helpful?
(1500 characters remaining)
Community Content Add
Annotations FAQ
Please check out these two implementations
http://blog.thekid.me.uk/archive/2007/03/24/web-config-modification-manager-for-sharepoint.aspx

and 

Based on the above, with some adds
http://www.dynasign.nl/blog/?p=14
SPWebConfigModification sample for adding and removing sections within a web application.

Description:

The following sample demonstrates using the SPWebConfigModification class to programmatically add and delete an entry to a SharePoint Web Application’s web.config file.

Usage scenario:

In this example we are programmatically adding a safe control entry to the web applications web.config. The SPWebConfigModification has an “Owner” assigned to it. This owner allows tracking of changes made through this API. With an owner specified while adding the SPWebConfigModification can be retrieved using the same user name for later modification or removal.

C# Code Sample 

static void AddConfigValueWL()
{
     // Get an instance of the web application we want to modify 
     SPWebApplication spweb = SPWebApplication.Lookup(new Uri("SomeServer"));
     // Create a new modification object to store our change 
     SPWebConfigModification myModification = new SPWebConfigModification();
     // Specify the path to the element of the web.config we want to change
     myModification.Path = "configuration/SharePoint/SafeControls";
     // Specify the element to change via X-Path
     myModification.Name = "SafeControl[@Assembly='MyCustomAssembly'][@Namespace='MyCustomNamespace'][@TypeName='*']     [@Safe='True']";
     myModification.Sequence = 0;
     // Set an owner for the change to track (you can use this value to find the change made and modify/remove it.
     myModification.Owner = "testowner";
     myModification.Type = SPWebConfigModification.SPWebConfigModificationType.EnsureChildNode;
     // Specify the value
     myModification.Value = "<SafeControl Assembly='MyCustomAssembly' Namespace='MyCustomNamespace' TypeName='*' Safe='True' />";
     spweb.WebConfigModifications.Add(myModification);
     // Update and Apply the new settings
     spweb.Update();
     spweb.Farm.Services.GetValue<SPWebService>().ApplyWebConfigModifications();
}

static void DeleteConfigValueWL()
{
    SPWebApplication spweb = SPWebApplication.Lookup(new Uri("http://SomeServer"));
    // Get a collection of all web.config changes made via the api 
         Collection<SPWebConfigModification> modsCollection = spweb.WebConfigModifications;
    List<SPWebConfigModification> modsToRemove = new List<SPWebConfigModification>();
    // Find all modifications by 'testowner' and save them in a list
    foreach (SPWebConfigModification modification in modsCollection)
    {
        if (modification.Owner == "testowner")
            modsToRemove.Add(modification);
    }
    // Go through the list and remove the changes from the web
    foreach (SPWebConfigModification modification in modsToRemove)
    {
        modsCollection.Remove(modification);
        // Update and Apply
        spweb.Update();
        spweb.Farm.Services.GetValue<SPWebService>().ApplyWebConfigModifications();
    }
}
  



VB.NET Example

    
Sub AddConfigValueWL()
   ' Get an instance of the web application we want to modify
   Dim spweb As SPWebApplication = SPWebApplication.Lookup(New Uri("http://SomeServer"))
   ' Get a new modification object to store our change
   Dim myModification As SPWebConfigModification = New SPWebConfigModification()
   ' Specify the path to the element of the web.config we want to change
   myModification.Path = "configuration/SharePoint/SafeControls"
   ' Specify the element to change via X-Path
   myModification.Name = "SafeControl[@Assembly='MyCustomAssembly'][@Namespace='MyCustomNamespace'][@TypeName='*'][@Safe='True']"
   myModification.Sequence = 0
   myModification.Owner = "testowner"
   myModification.Type = SPWebConfigModification.SPWebConfigModificationType.EnsureChildNode
   myModification.Value = "<SafeControl Assembly='MyCustomAssembly' Namespace='MyCustomNamespace' TypeName='*' Safe='True' />"
   ' Add our change to the web application
   spweb.WebConfigModifications.Add(myModification)
   ' Update and apply the new settings
   spweb.Update()
   spweb.Farm.Services.GetValue(Of SPWebService)().ApplyWebConfigModifications()
 End Sub
    
 Sub DeleteConfigValueWL()
   ' Get an instance of the web application we want to modify
   Dim spweb As SPWebApplication = SPWebApplication.Lookup(New Uri("http://SomeServer"))
   ' Get a new modification object to store our change
     Dim modsCollection As Collection(Of SPWebConfigModification) = spweb.WebConfigModifications
   Dim modsCount As Integer = modsCollection.Count
   Dim modsToRemove As List(Of SPWebConfigModification) = New List(Of SPWebConfigModification)
      
   ' Find all modifications by 'testowner' and save them in a list
   For Each modification As SPWebConfigModification In modsCollection
      If modification.Owner = "testowner" Then
          modsToRemove.Add(modification)
      End If
   Next
        
   ' Go through the list and remove the changes from the web
   For Each modification As SPWebConfigModification In modsToRemove
       modsCollection.Remove(modification)
       ' Update and Apply
       spweb.Update()
       spweb.Farm.Services.GetValue(Of SPWebService)().ApplyWebConfigModifications()
   Next
 End Sub
SPWebConfigModification How To and Best Practice

SPWebConfigModification is an excellent utility allowing you to safely apply modifications to the web.config file for your SharePoint servers. However, using SPWebConfigModification can prove to be challenging. This is evident by the number of examples and posts that may work just fine on your single-server development maching, but deploying to a farm may not yield the results you are expecting. For this reason, I have put together a quick list of items I see as a Best Practice to ensure success not only on a single server configuration of SharePoint, but on multi-server SharePoint farms as well. For more information see:

http://www.crsw.com/mark/Lists/Posts/Post.aspx?ID=32

SPWebConfigModification's Top 6 issues

SPWebConfigModification allows your code (that is within your Feature event receivers , console apps or custom installation applications) to dynamically make and propagate changes to web.config files across your farm.You have the option to add/modify/delete sections, child elements and attributes with some limitations and through many workarounds! Find out more : http://blogs.devhorizon.com/reza/?p=459

Reza Alirezaei,MVP
Blog: http://blogs.devhorizon.com/reza

SPWebConfigModification overview

The web application has a collection of WebConfigModifications that it maintains in the content database and in each web.config for the application. The web application’s Web Config Modifications are a collection of modifications to be applied across all instances of the IIS web application across all servers in the farm. These modifications are encapsulated in the SPWebConfigModification class.

SPWebConfigModification provides a way to make changes to web.config and can be used in a console application or feature receiver. Internally, the WSS runtime stores this information in the farm configuration database in the Objects table, and uses xml-serialized objects to persist the class. This lets WSS reapply the objects to new web.config files as new sites come online.

So that the WSS runtime can track this change, the Path property is the xpath expression to the root node containing the child node, and the Name property is the xpath expression from the parent node to the new child node. The Name property is used primarily by WSS to manage the entry over the lifetime of the web application—on subsequent calls to ApplyWebConfigModifications WSS will ensure that all of its modifications are applied or removed. If Name is incorrect on the initial add, the element will still be added however WSS will be unable to manage its removal.

(from Inside Windows SharePoint Services 3.0 , Pattison/Larson 2007 -- http://www.microsoft.com/MSPress/books/9692.aspx )

For more information, see the community content for SPWebConfiguration Members ( http://msdn2.microsoft.com/en-us/library/microsoft.sharepoint.administration.spwebconfigmodification_members.aspx ).

*Note: the MSDN documentation example uses a SafeControls entry. You should NOT use the SPWebConfigModification for SafeControls-- you should use the solution package (WSP) to deploy assemblies and create safecontrols for them, as well as CAS policy entries.