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:
So a couple of notes about the above code:
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: }
- 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
No comments:
Post a Comment