In the previous article we have seen the theories on AppFabric Caching service.
In this article, we explore the programming aspects of it.
The following are the steps involved in using the cache.
Step 1: Create the Service Namespace
We need to create the service namespace. You can skip this step if you already
have a namespace. For creating the namespace sign in to the Windows Azure portal
and select the Service Bus, Access Control & Caching item as shown below.
Now click on the New button.
In the appearing dialog enter the cache details as shown below.
Please ensure you entered a unique namespace and click the Create Namepace
button. Wait for a few minutes and your namespace will be ready.
Step 2: Install AppFabric SDK
This application requires AppFabric SDK. You can download it
from
here. You can download the appropriate 32 bit or 64 bit version as shown
below.
Step 3: Create new Web Role
Create a new Azure Project and add a web role into it. Add reference to the
following caching assembly files.
You can locate the files in folder:
C:\Program Files\Windows Azure AppFabric SDK\V1.5\Assemblies\NET4.0\Cache
Modify the web.config of the application by adding the marked section. Enter
your namespace and key information in the respected area.
The configuration entries (namespace and key) can be generated from portal using
the button highlighted.
Now in the Default.aspx page design view add two buttons named Create Cache and
Get Cache as shown below.
Make the click events of buttons as following.
protected
void
CreateCacheButton_Click(object
sender,
EventArgs
e)
{
DataCacheFactory
factory =
new
DataCacheFactory();
factory.GetDefaultCache().Add("Key1",
"Value1");
factory.GetDefaultCache().Add("Key2",
"Value2");
factory.GetDefaultCache().Add("Key3",
"Value3");
factory.GetDefaultCache().Add("Key4",
"Value4");
factory.GetDefaultCache().Add("Key5",
"Value5");
}
protected
void
GetCacheButton_Click(object
sender,
EventArgs
e)
{
DataCacheFactory
factory =
new
DataCacheFactory();
object
value = factory.GetDefaultCache().Get("Key1");
if
(value !=
null)
Label1.Text =
"Value is: "
+ value.ToString();
else
Label1.Text =
"Invalid Key!";
}
You need to place a label control as well to run the above code.
Note: The cache is supporting key value pairs. The above example stores value as
string. We can also store custom class instances as value.
Step 4: Execute the Application
Now you can execute the application and click the buttons to see the Caching
usage.
The above application shows the cache is successfully created and retrieved. The
cache items will be persisting between multiple application executions. You need
to manually delete them or delete the namespace after execution.
Summary
In this article we have seen how to use the Caching Service of AppFabric. The
code attached contains the associated files and you need to change the
configuration entries according to your authentication properties.