Monday, November 26, 2012

Adding configuration settings to a custom SharePoint timer job

If you wish to add custom configuration settings to a custom SharePoint, web application scoped timer job, one possible option is to add those configuration settings into the <appSettings> node of the web.config file of the applicable SharePoint web application(s) and then reference those settings from your custom SharePoint timer job's code.

Your first step is to add your configuration settings into the <appSettings> node of your SharePoint web application.  The custom configuration settings can be added to your web.config file via the following steps:
  1. Log on to your SharePoint WFE server(s)
  2. Open Windows Explorer
  3. Navigate to the C:\inetpub\wwwroot\wss\VirtualDirectories folder
  4. Locate the applicable SharePoint web application listed here and open on that folder
  5. Right-click on the web.config file and select Open with -> Notepad
  6. Scroll down until you find the <appSettings> node
  7. Add a new element within the <appSettings> node to define the key and value of your configuration setting (i.e. "<add key="hoursToExpiration" value="10200" />")
  8. Click File -> Save
  9. Repeat steps 1 - 8 for all web applications that your timer job is activated on
Your next step is to add code to your timer job's class file, that will reference your custom <applicationSettings> elements.  The following code sample provides one possible option for obtaining these settings using my sample "hoursToExpiration" setting:

...
using System.Configuration;
using System.Web.Configuration;
...
public override void Execute(Guid contentDbId)
{
    int hoursToExpiration = 0;
    Configuration config = WebConfigurationManager.OpenWebConfiguration("/", this.WebApplication.Name);
    if (config.AppSettings.Settings["hoursToExpiration"] != null)
    {
        if (!Int32.TryParse(config.AppSettings.Settings["hoursToExpiration"].Value, out hoursToExpiration))
        {
            // Write code to handle that the custom appSetting couldn't be converted to the appropriate data type
        }
    }
    else
    {
        // Write code to handle that the custom appSetting couldn't be found
        ...

Once you've deployed the code update, be certain to cycle the SharePoint timer service to make certain that the change has been picked up (see my previous blog entry for instruction on how to do that).  At that point, your timer job will obtain the custom setting information upon execution of the timer job on that web application.

No comments:

Post a Comment

Note: Only a member of this blog may post a comment.