Saturday, March 15, 2014

Best practice for using configuration values in SharePoint

If we need to keep configuration values for SharePoint customizations, the easiest way is to store them in AppSettings section in configuration file (web.config, owstimer.exe.config, etc..). Following is a sample of the usage.
<appSettings>
    <add key="ConfigSite" value="/sites/config" />
    <add key="AppPoolUser" value="dev\spadmin" />
    <add key="ProjectList" value="Projects" />
</appSettings>

But there are some limitations in that approach
  • Settings are not stored in any database. Hence If we stop the “Microsoft SharePoint Foundation Web Application” service in multi server environment web applications will be automatically created in another server but without configuration values.
  • We have to set configuration values in all WFE servers.
  • Modification of configuration files is always risky
To overcome above limitations we can choose from two alternative solutions. One is to use SPWebConfigModification object to programmatically set configuration values.

But I personally prefer the next approach, which is to use web application properties. It is very simple and the best approach to handle external values within the web application. Furthermore we can simply set and modify those values from a PowerShell interface.

Following is the way to set web application properties

  1. $webApp = "http://sp2013/"
  2. $app = Get-SPWebApplication $webApp

  3. $app.Properties.Add("ConfigSite","/sites/config")
  4. $app.Properties.Add("AppPoolUser","dev\spadmin")
  5. $app.Properties.Add("ProjectList","Projects")
  6. $app.Update();

Following is a sample usage of web application properties within an event receiver

  1. public override void FeatureActivated(SPFeatureReceiverProperties properties)
  2. {
  3.   var web = properties.Feature.Parent as SPWeb;
  4.   var webApplication = web.Site.WebApplication;
  5.   var leftNavOrder = webApplication.Properties["ProjectList"].ToString();

No comments: