Using a Feature-Receiver to modify the Web.Config File

We had a previous SharePoint project where we installed a custom HTTPModule to the SharePoint Web application. Since the SharePoint manifest file cannot inject entries into the httpModules section of the Web.config file (the manifest file can only insert entries inside the SharePoint section of the Web.config such SafeControl entries), we had to use a custom feature-receiver class, based on the SPFeatureReceiver. The custom feature-receiver class did it’s job nicely; whenever the feature got activated, the required entry in the httpModules section of the Web.config file got inserted.

Sequence property of the WebConfigModification can be used to figure out the uninstall order.

Unnamed sections such as connectionStrings and bindings sections, appear to have an XPATH expression that may result in duplicate matching. But, the ApplyWebConfigModifications method of the WebConfigModifications object will do it correctly as long as:

  • EnsureChildNode is used as the type
  • Add/Remove in order that is logical. Example: add connectionStrings section first then the add elements inside the connectionString section.
  • If you are worried that de-activating a feature will obliterate the connectionStrings section because your feature created it, don’t. SharePoint will only take out the connectionStrings if there are no other entries created by the ApplyWebConfigModifications inside the connectionStrings section. If other features inserted 1 or more connection-string entries there, your feature-receiver will not remove the connectionStrings section. Now, if the connectionString section got edited manually, the SharePoint WebConfigModifcations object will not know this and it doesn’t matter how many child-nodes there are inside the  connectionString object. The root element (connectionString) in this case will be removed because in SharePoint’s perspective, there are no existing Web-config modifications inside connectionString.

Conclusion: if you are going to adopt feature-receivers to install web.config entries such as connection-strings and bindings (for Service-References), you must also adopt to policy to discourage manual insert/modification of the web.config entries. Be consistent.

Be the first to comment

Leave a Reply

Your email address will not be published.