Click here to Skip to main content
13,863,034 members
Click here to Skip to main content
Add your own
alternative version


20 bookmarked
Posted 16 Feb 2011
Licenced CPOL

Using Windows Azure AppFabric Cache (CTP)

, 16 Feb 2011
Rate this:
Please Sign up or sign in to vote.
How to setup and use Windows Azure AppFabric Cache (CTP).


Highly scalable applications that have to serve millions of users everyday are in need of a highly-scalable, highly available, and durable caching platform and architecture. Distributed caching nodes are almost always the best solution to avoid unnecessary round-trips to the database, but they can also be a cause of problems and issues if it implemented incorrectly. Possible problems would be using out-of-date objects holding an older version of data, or failing to retrieve the correct, not necessarily the latest, version of an object from the cache, or expiring an object too soon from the cache.

One of the most anticipated features has been significantly enhanced at the latest CTP version of Windows Azure AppFabric. Caching was introduced back in PDC '10 along with other features like durable messages on Service Bus, more identity providers for Identity Federation, VM Role, Extra small Instances, SQL Azure Reporting, Windows Azure Connect, and a lot of others.

This article is based on Visual Studio 2010 using the latest version of the Windows Azure SDK v1.3 at the time it was published, and also Windows Azure AppFabric SDK v2.0 CTP February release.


Back in the days, Windows Azure AppFabric Cache was referred by the name of "Velocity", but this is not only part of Windows Azure AppFabric, but also part of Windows Server AppFabric which also includes a project referred to by the codename "Dublin". "Dublin" was also demonstrated as a composite building service, where you select all the necessary components of your application and along with WCF and WF hosting and orchestration, you get a lot of new things, like easy scaling, and point and click type of adding new components/services to your application. All of those are just a quick overview of what is included on the Windows Azure/Server AppFabric family. Be aware because they are not aligned, which means that if something exists in Windows Azure AppFabric, it doesn't mean that it exists on the Windows Server AppFabric also.

What is it?

Windows Azure AppFabric Cache removes all the hassle from having to setup a new caching farm with nodes and setting up all the necessary settings to keep those nodes in sync, making sure that nodes have enough resources etc., by providing a Platform as a Service approach just like the whole Windows Azure Platform does. All you have to do is, go to, and sign up and start using all the services Windows Azure AppFabric has to offer, ACL, Service bus, and Caching among others.

How does it work?

Just as any other distributed caching solution, Windows Azure AppFabric Cache has two parts. The server part where the service is running and the client part where the client is using some code and configuration to access it. To create the server part, you have to go to the Windows Azure AppFabric Labs portal mentioned above and select "Cache".

After that, you have to click on "Create Namespace".


There you have to select a subscription to activate the feature. As this is a CTP feature, you won't have any subscription created at the moment, so you'll be prompted by the portal to automatically create one. As you click OK, you'll get a new subscription called "LabsSubscription". Everything will be associated with this subscription as you cannot create a new one on the CTP. When the subscription is ready (takes 3-4 seconds), you have to select a name for your namespace and then check if it's available, then select the Region (only USA is available for the CTP), and finally choose the cache size, either 128 MB or 256 MB. You can change the cache size once every 24 hours if you want.


Now you can click OK and the namespace will be in an "Activating" state for a while.


When it's ready, it will turn green and the indication will be "Activated" which means you can now use it in your application. As I said, the application has two parts; we just activated the server part and we're going to create the client configuration now to access the service. This part is also being done automatically by the portal.


All you have to do is click OK, "View Client Configuration", and select the correct part of the configuration you need, either for a non-Web Application or a Web Application where you can change the session state persistence storage to this cache. From the same menu, you can also change the cache size by clicking on "Change Cache Size". If you click on "View Client Configuration", you get a window containing all the necessary XML you need to put into your app.config or web.config.


After you select the part you need for your application, which in my case is a simple console application to do some very basic demonstration about how to use the cache, you have to place it inside your app.config.

    <section name="dataCacheClient" 


       allowlocation="true" allowdefinition="Everywhere">

  <datacacheclient deployment="Simple">
      <host name="" 


    <securityproperties mode="Message">
      <messagesecurity authorizationinfo="YOUR_KEY_HERE">

Using the code

When you're done adding this XML to your app.config, you'll have to reference two assemblies from the Windows Azure AppFabric SDK v2.0, which you can download here. The assemblies you need are located in \Program Files\Windows Azure AppFabric SDK\V2.0\Assemblies\Cache\ and you need to put a reference on Microsoft.ApplicationServer.Caching.Core.dll and Microsoft.ApplicationServer.Caching.Client.dll.

Adding those two references will allow all the necessary methods and namespaces to be exposed and be used by your code. We particularly need the DataCacheFactory and DataCache classes which contain all the necessary methods to initialize the cache client and interact with the service.

using (DataCacheFactory dataCacheFactory = new DataCacheFactory())
     // Get a default cache client
     DataCache dataCache = dataCacheFactory.GetDefaultCache();

As we don't provide any parameters, the default values read from the configuration file will be initialized and used by the DataCache client.

Using the DataCache client is fairly easy, and it's just like any other distributed cache. It has methods to Put() something in the cache, Get() something from the cache etc. Whenever you Put or Get something from the cache, you have to specify a key that is unique to this object. In our case, I'm using the FullName of our Person class which is returned by a method of the class.

// Put that object into the cache
dataCache.Put(nPerson.GetFullName(), nPerson);

// Get the cached object back from the cache
Person cachedPerson = (Person)dataCache.Get(nPerson.GetFullName());

You might notice that the Person class is decorated with a DataContract attribute and all the properties are decorated with a DataMember attribute. That is needed so the object can be serialized and stored into the cache. Both attributes exist in the System.ServiceModel assembly for which you also have to add a reference to your project. The assembly is located in the GAC as it is part of the .NET Framework.

public class Person
    public string FirstName { get; set; }
    public string Lastname { get; set; }
    private decimal Money { get; set; }

    public Person(string firstname, string lastname)
        FirstName = firstname;
        Lastname = lastname;
        Money = 0;

    public decimal WithdrawMoney(decimal amount)
        return Money -= amount;

    public void DepositMoney(decimal amount)
        Money += amount;

    public decimal GetBalance()
        return Money; 

    public string GetFullName()
        return string.Format("{0} {1}", FirstName, Lastname);

There are other aspects of the Windows Azure AppFabric Cache that I'll explore in future articles, like how to get an object only if it's newer than the version already in the memory, or how to handle versioning of multiple objects in the cache and how to automatically remove an object from the cache after a specific period of time.

All the code is inside Program.cs:

// DataCacheFactory will use settings from app.config
using (DataCacheFactory dataCacheFactory = new DataCacheFactory())
    // Get a default cache client
    DataCache dataCache = dataCacheFactory.GetDefaultCache();

    // Create a new person
    Person nPerson = new Person("Panagiotis", "Kefalidis");
    Console.WriteLine(string.Format("Currently in your account: {0}", 

    // Deposit some money
    Console.WriteLine(string.Format("Currently in your " + 
            "account after deposit: {0}", nPerson.GetBalance()));

    // Put that object into the cache
    dataCache.Put(nPerson.GetFullName(), nPerson);

    // Remove some money

    // Get the cached object back from the cache
    Person cachedPerson = (Person)dataCache.Get(nPerson.GetFullName());

    // How much money do we have now?
    Console.WriteLine(string.Format("Currently in your " + 
       "cached account after withdraw: {0}", cachedPerson.GetBalance()));

    // How much money we REALLY have now?
    Console.WriteLine(string.Format("Currently in your account " + 
                      "after withdraw: {0}", nPerson.GetBalance()));

    // Update the cache with latest information
    dataCache.Put(nPerson.GetFullName(), nPerson);

Points of interest

You can learn more about caching at this URL: Be aware that this is referring to Windows Server AppFabric and not Windows Azure AppFabric, but it is a very good source to learn more and get an overview of what the underlying infrastructure is.

You can also get more information about the Windows Azure platform in general at my blog:


  • 16/02/2011: First version published.


This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


About the Author

Panagiotis Kefalidis
Instructor / Trainer
Belgium Belgium
Panagiotis is a Software Development Consultant & Architect and Trainer. He has been a speaker at domestic and international events such TechEd and ITProDevConnections, delivering trainings and consulting on cloud computing and the Windows Azure Platform for almost 3 years. He also has experience with other cloud platforms like AWS, Google Gears and others. He's a supporter of the EuroCloud movement, likes Pizza, Sushi and fast cars. Born and raised in Greece but currently living and working at Belgium for Devoteam BE.

Panagiotis is a Windows Azure MVP.

You may also be interested in...


Comments and Discussions

GeneralMy Vote of 5 Pin
Alireza_136210-Apr-16 12:46
memberAlireza_136210-Apr-16 12:46 
GeneralMy vote of 5 Pin
Kanasz Robert28-Sep-12 6:39
memberKanasz Robert28-Sep-12 6:39 
QuestionAppFabric Vs NCache Pin
wesnur8-Apr-12 22:30
memberwesnur8-Apr-12 22:30 
GeneralFor DataContract & DataMember attributes.. Pin
Rychus Cortina22-Mar-11 1:47
memberRychus Cortina22-Mar-11 1:47 
GeneralMy vote of 5 Pin
Anupama Roy21-Feb-11 1:42
memberAnupama Roy21-Feb-11 1:42 
Question{"ErrorCode<ERRCMC0003>:SubStatus<ES0001>:Error in client configuration file."} [modified] Pin
Anupama Roy21-Feb-11 1:17
memberAnupama Roy21-Feb-11 1:17 
AnswerRe: {"ErrorCode:SubStatus:Error in client configuration file."} Pin
Panagiotis Kefalidis21-Feb-11 6:35
memberPanagiotis Kefalidis21-Feb-11 6:35 
GeneralRe: {"ErrorCode:SubStatus:Error in client configuration file."} Pin
Anupama Roy21-Feb-11 7:28
memberAnupama Roy21-Feb-11 7:28 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.

Permalink | Advertise | Privacy | Cookies | Terms of Use | Mobile
Web01 | 2.8.190214.1 | Last Updated 16 Feb 2011
Article Copyright 2011 by Panagiotis Kefalidis
Everything else Copyright © CodeProject, 1999-2019
Layout: fixed | fluid