Config Sync for Windows Azure

It’s been a while since I posted and I apologize. I have a collection of wafer thin justifications for my absence including but not limited to: working on too much ‘non-public’ features, general busyness and a lingering dis-satisifcation with the blog as a means for technical communication.

Whilst working on a personal project I thought the following code might interest some. When working on a Windows Azure app (in this case a Web App) you might use the RoleManager.GetConfigurationSetting() method to retrieve configuration settings stored in the CSCFG (and defined in the CSDEF). The advantage of using these files is the ability to change these values at run-time. The downside of this technique is you have to use RoleManager.GetConfigurationSetting() instead of the more standard ConfigurationManager.AppSettings[] technique.

Each time a web request gets executed I check the ‘age’ of my settings and then attempt to update them.

using System;
using System.Configuration;
using System.Diagnostics;
using Microsoft.ServiceHosting.ServiceRuntime; 

namespace PhilipRichardson.Samples.WebApp
{

public class Global : System.Web.HttpApplication
{
  private bool HasRun;

  private DateTime LastSettingsUpdate;

  protected void Application_BeginRequest(object sender, EventArgs e)
 
{
    bool UpdateSettings;
    if (!HasRun)
   
{
     
UpdateSettings = true;
   
}
   
else
   
{
      if (this.LastSettingsUpdate != null)
     
{
       
TimeSpan age = (DateTime.UtcNow – this.LastSettingsUpdate).Duration();
       
int settingsRefreshSeconds = Convert.ToInt32(ConfigurationManager.AppSettings["SettingsRefreshSeconds"]);
       
TimeSpan timeout = new TimeSpan(0, 0, settingsRefreshSeconds);
       
if (age > timeout)
        
{
        
UpdateSettings = true;
        
}
       
else
       
{
         UpdateSettings = false;
        
}
     
}
     
else
     
{
       
UpdateSettings = true;
     
}
   
}

   if (UpdateSettings)
  
{
    
foreach(string key in ConfigurationManager.AppSettings.AllKeys)
    
{
      
try
      
{
         ConfigurationManager.AppSettings[key] = RoleManager.GetConfigurationSetting(key);
       }
      
catch
      
{
         Trace.WriteLineIf(tracing, String.Format(“Failed to Find/Update the {0} Key”, key));
      
}
    
}
     this.HasRun = true;
    
this.LastSettingsUpdate = DateTime.UtcNow;
  
}
  }
}
}

 

Also note you can’t use Application_Start() method of Global.asax. This is because of the way the fabric integrates with IIS. Check out Steve Marx’s post on this topic.

Update: Improved code formatting, removed tracing and un-needed methods.

Advertisement

Follow

Get every new post delivered to your Inbox.