Monday, 13 June 2011

Testing Applications that use the AppFabric Caching Service in the Compute Emulator

One of the recent additions to the set of cloud services available as part of the Windows Azure Platform is the AppFabric Caching Service, and one of the interesting features of the AppFabric Caching Service is an ASP.NET session state provider. This is interesting because it offers a web-farm friendly session state provider, so if you deploy multiple instances of your Windows Azure web role, you now have a working, out-of-the-box, production quality session state provider (previously, if you deployed multiple instances, you had to implement your own, web-farm aware session management in your web role).

Using the AppFabric Caching Service session state provider in your Windows Azure application is simple. First, you need to set up a cache namespace using the Windows Azure portal:


Second, you must modify your application’s Web.config file with the necessary configuration to point to your new cache. This is easy to do, because you can copy and paste the necessary XML from the portal — just click on the View Client Configuration button:


That’s it, no code changes are necessary for your application.

Once you’ve created your cache and updated your Web.config file, you’ll want to test it out. Probably, you’ll want to initially test it out using the local Compute Emulator rather than deploying your application to Windows Azure — so make sure that you configure two or more instances of your web role, and try it out. Unfortunately, you’ll find that it doesn’t work: when the local Compute Emulator switches to another instance, your session state disappears (and reappears if you are switched back to the original instance). It may help to display the current instance id somewhere in your UI to keep track of what’s happening, for example:

Instance: <%=RoleEnvironment.CurrentRoleInstance.Id  %>

It turns out that that the problem lies with the local Compute Emulator and the default settings for the session state provider. By default, the session state provider uses the value of HttpRuntime.AppDomainAppId when it builds its cache keys, and each instance in the local Compute Emulator has a unique value. If you add an additional attribute, applicationName, to your configuration, the session state provider uses this value instead of the value of HttpRuntime.AppDomainAppId and now everything works as it should:

<sessionState mode="Custom" customProvider="AppFabricCacheSessionStoreProvider">
      <add name="AppFabricCacheSessionStoreProvider"
          type="Microsoft.Web.DistributedCache.DistributedCacheSessionStateStoreProvider, Microsoft.Web.DistributedCache"
          dataCacheClientName="default" />

This problem only manifests itself in the local Compute Emulator, you don’t need to use the applicationName attribute when you deploy your application to Windows Azure, although it doesn’t do any harm if it is there.

No comments: