You are on page 1of 12

Hands-On Lab

Windows Server AppFabric Cache:


Lab 4 Patterns of Use
Lab version: 1.0.0
Last updated: 7/27/2017

1
CONTENTS

OVERVIEW 3
Starting Materials 3

EXERCISE 1: USING OPTIMISTIC CONCURRENCY 4


Task 1 Creating the cache for this lab................................................................................................4
Task 2 Using optimistic concurrency.................................................................................................5

SUMMARY 11

2
Overview
This lab introduces the idea of optimistic concurrency when using the Windows Server App Fabric Cache.
The Cache does not provide any automatic concurrency. When you have shared data between different
users, and can change with some frequency, you may need to be concerned about cache coherency. If
you are, one way you can deal with that in your programs is, before doing an update on an item in the
cache, to use DataCacheItem.Version to verify if the version has changed since the last time you
performed a get.

Objectives
The objectives of this lab are:
To understand how concurrency works in the Cache
To learn how to use DataCacheItem.Version to perform optimistic concurrency
.1

Setup
You must perform the following steps to prepare your computer for this lab:
.2 Complete the Development Environment Setup lab.
.3 To simplify the process of opening the Windows Server AppFabric Caching Labs, we have
provided a utility called LabStarter that you should run as the first step in any lab.
.4 To use it, run LabStarter.exe from the %InstallFolder%\Assets directory, click the Caching tab,
and click the button corresponding to the Lab exercise you wish to open. This will open the
desired solution in Visual Studio for you automatically.

Exercises
This Hands-On Lab comprises the following exercises:
Exercise 1: Using Optimistic Concurrency

Estimated time to complete this lab: 30 minutes.

Starting Materials
This Hands-On Lab includes the following starting materials:

3
Visual Studio solutions. The lab Visual Studio solutions that you can use as starting point for
the exercises in the begin folder.

Note: Inside each exercise folder, you will find an end folder containing a solution with the
completed lab exercise.

4
Exercise 1: Using optimistic concurrency
In this exercise, you will first create a named cache for use in this lab. Then you will use optimistic
concurrency to check if an item in the cache has changed since the last time your application retrieved it.
Task 1 Creating the cache for this lab
Note: If you have already started your Cache and have PowerShell open from the previous lab, you can
skip this task.

.1 To verify the installation and start the cache host, open PowerShell from Windows Server
AppFabric | Caching Administration Windows PowerShell.
.2 Execute the Use-CacheCluster cmdlet to bring the current machines cluster configuration
into the context of your PowerShell session.
PowerShell
Use-CacheCluster

.3 Execute the Get-CacheHost cmdlet to see the state of your cache cluster
PowerShell
Get-CacheHost

.4 You should see something that looks similar to Figure 1. Note that the Service Status is
DOWN.

Figure 1
Get-CacheHost cmdlet execution results
.5 If the Service Status is UP, skip to Step 9. If the Service Status is DOWN, start the cache host
by using the Start-CacheHost cmdlet. Start-CacheHost requires two parameters: the host name,
and the port number. Set the value of the Get-CacheHost cmdlet to a variable named $myhost,
and then use the $myhost.HostName and $myhost.PortNo properties as the input to Start-
CacheHost.
PowerShell

5
$myhost = Get-CacheHost
Start-CacheHost $myhost.HostName $myhost.PortNo

.6 Your PowerShell command screen should look similar to Figure 2. Your Service Status should
now be UP.

Figure 2
Starting the cache host
.7 Create a new cache for this lab named Lab4Cache by typing the following PowerShell
command and pressing Enter. Note you need to create this cache with notifications enabled!
PowerShell
New-Cache Lab4Cache NotificationsEnabled true
.8

Task 2 Using optimistic concurrency


.9 Use the LabStarter to open this labs solution file with Visual Studio 2010.
.10 Open RecentRouteRequests.aspx.cs (right-click on RecentRouteRequests.aspx in the Solution
Explorer and select View Code).
.11 Scroll down to the GridView1_RowUpdating method. You will be changing this method in a
moment to use optimistic concurrency. Note that currently it just calls DataCache.Put to update
cached data.
.12 After the projects load, hit CTRL+F5 to verify the application works.
.13 Click on the Airports menu. This will take you to the page where you can select a route to
suggest to the mythical airline. See Figure 3.

6
Figure 3
Airports page
.14 Once you select a route, you can put on a different role that of the internal airline
employee who wants to see the list of requests. Click on the Requests menu item. See Figure 4.

Figure 4
List of requests.
.15 Click Edit on any of the items in the grid.
.16 Now you will open and use another application that can also modify cached items.

7
.17 Use Windows Explorer to go to %AppFabricTrainingKit%\Labs\AFC
Lab04\Source\Assets\AppFabricCacheApp, then start the AppFabricCacheApp.exe application.

Note: If you are not running this lab on the provided Virtual Machine, you will need to open
the AppFabricCacheApp.exe.config file found in that directory and change the host name to
point to the correct machine.

.18 When the Open File dialog appears, navigate to %AppFabricTrainingKit%\Labs\AFC


Lab04\Source\Ex1\Begin\AppFabricTest\AppFabricTest\bin, pick AppFabricTest.dll, and press
Open. See Figure 5.

Figure 5
Pre-loading assemblies for the cache tool

To allow viewing and editing of the objects in the cache, this tool needs to be able to load the
assembly that contains the cached object type.

.19 Navigate in the tree in the left of the application to find Lab4Cache and the RecentRoutes
region. See Figure 6.

8
Figure 6
Navigating the cache application
.20 If you can, position both windows side-by-side (if you are using Windows 7 or Windows
Server 2008 you can drag each window to a side of your monitor). See Figure 7.

Figure 7
The two applications side by side
.21 In the Cache Application, change the FromAirport in the property grid from whatever the
value is (Figure 6 shows it as SYD) to LAX.
.22 Go to the File menu and select Save current object.
.23 In the browser window, change the FromAirport to YYZ.
.24 Press the update link to save the change.
.25 Go back to the application and select File | Refresh.
.26 Note that the change to LAX has been lost. This is the effect of multiple actors (nodes or
applications) changing data in the cache without any kind of concurrency control. Now you will
add optimistic concurrency to the web application.

9
.27 Close both the browser window and the application and return to Visual Studio 2010.
.28 Go to the RecentRouteRequests.aspx.cs file. If it is not open , open it (right-click on
RecentRouteRequests.aspx in the Solution Explorer and select View Code).
.29 Scroll to find the GridView1_RowEditing method. Inside of it is a TODO comment. Below that
line of code, put in code that gets the DataCacheItemVersion by calling
DataCache.GetCacheItem on the item currently being edited.
C#
var key = GridView1.DataKeys[0].Value.ToString();
var dcf = Application[Global.CacheFactoryName] as DataCacheFactory;
var cache = dcf.GetCache("Lab4Cache");
var region = "RecentRoutes";
var item = cache.GetCacheItem(key,region);
Session["DataCacheItemVersion"] = item.Version;

.30 After adding this code, your GridView1_RowEditing should look like Figure 8.

Figure 8
GridView1_RowEditing after edits
.31 Now scroll down to the GridView1_RowUpdating method.
.32 At the bottom of that method is another TODO comment.
.33 Comment out the line that calls cache. (type // in front of the code)
.34 After that line, put in code that gets the DataCacheItemVersion from the Session object.
Then, inside of a try block, call the overload of cache.Put that takes a DataCacheItemVersion. In
a catch block for DataCacheException, call Page.Validators.Add and pass in a new
CustomErrMsgValidator to display an error message.
C#
var version = Session["DataCacheItemVersion"] as DataCacheItemVersion;
try
{
cache.Put(request.Id, request, version, region);
10
}
catch (DataCacheException ex)
{
Page.Validators.Add(new CustomErrMsgValidator {
ErrorMessage =
String.Format("Sorry - someone already changed that data {0}", ex.Message)
});
}

.35 After adding this code, your code should look similar to Figure 9.

Figure 9
GridView1_Updating method after edits.
.36 You will now repeat the steps you did at the beginning of this task.
.37 Hit CTRL+F5 to bring the web application up in the browser.
.38 Again, add a route using the Airports page.
.39 Click on the Requests page.
.40 Click to Edit the request by clicking the Edit hyperlink to the left of the request data.
.41 Open the cache application again and select AppFabricTest.dll as you did previously.
.42 Find the item in the tree view and change its FromAirport to LAX.
.43 Go to File | Save current object to update the cache.
.44 Go back to the browser, and click update.
.45 You should now see an error message like the one in Figure 10.

11
Figure 10
Optimistic concurrency violation error message shown in browser.
.46

Summary

In this lab you used optimistic concurrency with the Cache by using the DataCacheItem.Version property
to ensure that an item in the cache hadnt changed before you used DataCache.Put to update it.

12

You might also like