only My site

Sunday, August 19, 2012

SPWebConfigModifications - Add/Remove web.config settings

one way to modify web.config settings is to use the SPWebConfigModificationclass of the Microsoft.SharePoint.Administration namespace, which allows you to dynamically register entities. These modifications are persisted in the configuration database where they function as a kind of virtual web.config that effectively serves as the final layer of the .config file stack for the SharePoint Foundation web application. The changes become effective when the SPWebService.ApplyWebConfigModifications method is called
 
Holds modifications that are made to the web.config.

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.

Add Settings

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();
 Remove Settings sample
SPWebConfigModification configModFound = null;
SPWebApplication webApplication = SPWebApplication.Lookup(new Uri("http://localhost/"));
Collection<SPWebConfigModification> modsCollection = webApplication.WebConfigModifications;

// Find the most recent modification of a specified owner
int modsCount1 = modsCollection.Count;
for (int i = modsCount1 - 1; i > -1; i--)
{
    if (modsCollection[i].Owner == "User Name")
    {
        configModFound = modsCollection[i];
    }
}

// Remove it and save the change to the configuration database  
modsCollection.Remove(configModFound);
webApplication.Update();

// Reapply all the configuration modifications
webApplication.Farm.Services.GetValue<SPWebService>().ApplyWebConfigModifications(); 

No comments: