There are two good ways you can update the web.config using a feature. The first way that I will write about today is by adding an xml file to the %ProgramFiles%\Common Files\Microsoft Shared\web server extensions\14\CONFIG folder and use a feature receiver to apply the modifications.

This method will apply web.config modifications to all web applications excluding the central admin web application.

Here is the link to the MSDN article: http://msdn.microsoft.com/en-us/library/ms439965.aspx

image

So the first thing I did in Visual studio is to create a mapped folder to the config folder under the 14 hive. After that I created an xml file in the format webconfig.*.xml (replace * with your own text).

This is the contents of my xml file:

<actions>
  <add path="configuration/appSettings" id="{F890379B-C989-457B-A350-26D4C8909FA9}">
    <add key="MySetting" value="MyValue" />
  </add>
</actions>

 

In the xml file I have added an add action that points to the appSettings in the web.config. The child of that element is the element that I want to add under appSettings.

IMPORTANT!!! Now the one thing the MSDN article does not explain is the role of the id attribute. If you do not include an id attribute with a GUID as a value, the modification will be added multiple times to the web.config.

So you see this can be anything from a safeControl Entry to a Custom sitemap provider.

So the next question to ask is “How do you apply the settings?”. Well the answer is quite easy. First I created a farm scoped feature that contains an event receiver.  This event receiver contains one line of code in the FeatureActivated event.

 public override void FeatureActivated(SPFeatureReceiverProperties properties)
 {
     SPWebService.ContentService.ApplyApplicationContentToLocalServer();
 }

 

At this point you can deploy your solution and make sure your feature is activated. Here is a snippet of my web.config after the feature has been activated.

 

image

 

Advantages:

  • Easy set up.
  • Hardly any code.
  • You do not lose any custom web.config entries when SharePoint is updated.
  • An easy way to deploy custom web.config modifications to all web applications (excluding the central admin web application)

 

Disadvantages

  • All web applications receive the modifications and may not be the best way if you want to limit your modifications to one web application. You should use another method. See Part 2

 

In the next couple of days I will have another post (part 2) about modifying the web.config in SharePoint 2010 by using a feature.