Tuesday, September 6, 2011

How to read web.config from a timer job in Sharepoint

Reading web.config from a timer job::

I gotta say that I am pretty proud about this one. The scenario is that you have a timer job that connects to a database somewhere, and the connection string is stored in the web.config file. Now since your timer job doesnt run inside of IIS, it runs under the OWSTIMER executable, you can’t access it directly. The workaround is very, very easy though – 2 lines of code in fact!
The first thing you need is a reference to the SPWebApplication object. Once you have your SPWebApplication you can get your configuration file through the WebConfigurationmanager class. Here is an example of an execute method of a timer job that will get a setting for you:
   1: public override void Execute(Guid targetInstanceId)
   2: {
   3:     SPWebApplication webApplication = this.Parent as SPWebApplication;
   4:  
   5:     Configuration config = WebConfigurationManager.OpenWebConfiguration("/", webApplication.Name);
   6:     String myValue = config.AppSettings.Settings["mySettingName"].Value;
   7: }
So a couple of notes about the above code:
  • You might be wondering what I use the settings property of the AppSettings property – the answer is that when I use AppSettings["mySettingName"] directly I was getting an error that it was not accessible due to its access level, but the Settings property works just as good
  • This code assumes that you have not gone and renamed your SharePoint sites in IIS directly – the OpenWebConfiguration method uses a relative site URL within the IIS site, and the name of the site as it appears in IIS to load the configuration file. By default with SharePoint this will always match up the the SPWebApplication’s name property, but it is something to keep in mind
The above code should work for any SharePoint web application, so this means you can read the web.config files from each web application that use your timer job (perfect for what I needed as the connection string was unique per web app). The coolest part about this though is that it is only two lines of code! When I had a quick Google search around for this I didn’t find much, most people just recommended storing the connection strings in the registry or something like that, so this is a nice alternative

No comments:

Post a Comment

Popular Posts