in SharePoint 2007

Using SharePoint Object Model to add entries to web.config

When working with SharePoint projects, sometimes it is necessary to add some entries to the site’s web.config. The web.config file is always there in the virtual directories for you to open and edit, but it is a tedious and repetitive process to do the same thing across various environments.

The SharePoint object model has a neat way to add entries to the web.config. This is a much easier and better way to add entries to your web.config.

Below is the code snippet from MSDN:

SPWebService service = 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 = "User Name";

myModification.Type = SPWebConfigModification.SPWebConfigModificationType.EnsureChildNode;

myModification.Value =
"<SafeControl Assembly='MyCustomAssembly' Namespace='MyCustomNamespace' TypeName='*' Safe='True' />";

service.WebConfigModifications.Add(myModification);


/*Call Update and ApplyWebConfigModifications to save changes*/

service.Update();

service.ApplyWebConfigModifications();

As you can see, it is pretty simple and if you want to apply to the site rather than the whole farm (as shown in the code):

oWebSite.Site.WebApplication.WebConfigModifications.Add(MyModification)

Using the WebConfigModifications Property it is very easy to add/remove your web.config modifications

How should I approach and use it in my projects?

Given that you now know how to add entries to web.config, what would be the best way to take it forward and use it in your projects?

Here is my suggestion – Create a new feature which will add values to the web.config. In this way it is very easy to maintain. You just activate the feature to add values to the web.config.

Write a Comment

Comment

Time limit is exhausted. Please reload the CAPTCHA.