Hands-On Lab
Windows Server AppFabric Cache:
Lab 4 –Patterns of Use
Lab version:1.0.0
Last updated:12/3/2018
Contents
Overview
Starting Materials
Exercise 1: Using optimistic concurrency
Task 1 – Creating the cache for this lab
Task 2 – Using optimistic concurrency
Summary
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
Setup
You must perform the following steps to prepare your computer for this lab:
- Complete the Development Environment Setup lab.
- 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.
- 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 VisualStudio for you automatically.
Exercises
This Hands-On Lab comprises the following exercises:
Exercise 1: Using Optimistic Concurrency
Estimated time to complete this lab: 30minutes.
Starting Materials
This Hands-On Lab includes the following starting materials:
- 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 anend folder containing a solution with the completed lab exercise.
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.
- To verify the installation and start the cache host, open PowerShell from Windows Server AppFabric | Caching Administration Windows PowerShell.
- Execute the Use-CacheCluster cmdlet to bring the current machine’s cluster configuration into the context of your PowerShell session.
PowerShell
Use-CacheCluster
- Execute the Get-CacheHost cmdlet to see the state of your cache cluster
PowerShell
Get-CacheHost
- You should see something that looks similar to Figure 1. Note that the Service Status is DOWN.
Figure 1
Get-CacheHost cmdlet execution results
- If the Service Status is UP, skip to Step 9. If theService 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
$myhost = Get-CacheHost
Start-CacheHost $myhost.HostName $myhost.PortNo
- Your PowerShell command screen should look similar to Figure 2. Your Service Status should now be UP.
Figure 2
Starting the cache host
- 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
Task 2 – Using optimistic concurrency
- Use the LabStarter to open this lab’s solution file with Visual Studio 2010.
- Open RecentRouteRequests.aspx.cs (right-click on RecentRouteRequests.aspx in the Solution Explorer and select View Code).
- 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.
- After the projects load, hit CTRL+F5 to verify the application works.
- 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.
Figure 3
Airports page
- 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.
- Click Edit on any of the items in the grid.
- Now you will open and use another application that can also modify cached items.
- Use Windows Explorer to go to %AppFabricTrainingKit%\Labs\cLab04\Source\Assets\AppFabricCacheApp. Build the solutionthen start the AppFabricCacheApp.exeapplication.
Note: If you are not running this lab on the provided Virtual Machine, you will need to open the AppFabricCacheApp.exe.config filefound in that directory and change the host name to point to the correct machine.
- When the Open File dialog appears, navigate back up to the Source folder, then .\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.
- Navigate in the tree in the left of the application to find Lab4Cache and the RecentRoutes region. See Figure 6.
Figure 6
Navigating the cache application
- 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
- In the Cache Application, change the FromAirport in the property grid from whatever the value is (Figure 6 shows it as SYD) to LAX.
- Go to the File menu and select Save current object.
- In the browser window, change the FromAirport to YYZ.
- Press the update link to save the change.
- Go back to the application and select File | Refresh.
- 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.
- Close the browser window and return to Visual Studio 2010.
- Go to the RecentRouteRequests.aspx.csfile. If it is not open , open it (right-click on RecentRouteRequests.aspx in the Solution Explorer and select View Code).
- 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] asDataCacheFactory;
var cache = dcf.GetCache("Lab4Cache");
var region = "RecentRoutes";
var item = cache.GetCacheItem(key,region);
Session["DataCacheItemVersion"] = item.Version;
- After adding this code, your GridView1_RowEditingshould look like Figure 8.
Figure 8
GridView1_RowEditing after edits
- Now scroll down to the GridView1_RowUpdating method.
- At the bottom of that method is another TODO comment.
- Comment out the line that calls cache.Put (//)
- 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"] asDataCacheItemVersion;
try
{
cache.Put(request.Id, request, version, region);
}
catch (DataCacheException ex)
{
Page.Validators.Add(newCustomErrMsgValidator {
ErrorMessage =
String.Format("Sorry - someone already changed that data {0}", ex.Message)
});
}
- After adding this code, your code should look similar to Figure 9.
Figure 9
GridView1_Updating method after edits.
- You will now repeat the steps you did at the beginning of this task.
- Hit CTRL+F5 to bring the web application up in the browser.
- Again, add a route using the Airports page.
- Click on the Requests page.
- Click to Edit the request by clicking the Edit hyperlink to the left of the request data.
- Go to the cache application.Use File | Refresh to refresh the application’s view of the cache.
- Find the item in the tree view and change its FromAirport to LAX.
- Go to File | Save current object to update the cache.
- Go back to the browser, and click update.
- You should now see an error message like the one in Figure 10.
Figure 10
Optimistic concurrency violation error message shown in browser.
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 hadn’t changed before you used DataCache.Put to update it.
1