Hands-On Lab

Windows Server AppFabric Cache:

Lab 3 –Regions and Tags

Lab version:1.0.0

Last updated:9/28/2018

Contents

Overview

Starting Materials

Exercise 1: Creating a cache and using regions

Task 1 – Creating the cache for this lab

Task 2 – Using Regions

Exercise 2 (Optional – Advanced): Extending a sample “admin” application

Task 1– Adding Regions to a Cache

Summary

Overview

Regions are an additional data container that you can place in the cache. Regions are a cache construct: they are not defined in the cluster configuration settings. Regions are optional; if you want to use them, you must explicitly create them at runtime with your application code. With regions, you can retrieve cached objects in other ways than by using the specific key value with which they were cached. Regions let you to search all cached objects in the region by using descriptive strings called tags. You can associate one or more tags to each object stored in the cache.

Setup

You must perform the following steps to prepare your computer for this lab:

  1. Complete the Development Environment Setup lab.
  2. 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.
  3. 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 : Creating a cache and using regions

Exercise 2 : Extending a Sample Admin App

Estimated time to complete this lab: 45minutes.

Starting Materials

This Hands-On Lab includes the following starting materials.

  • Visual Studio solutions. The lab provides Visual Studio solutions that you can use as starting point for the exercises in a Source folder linked from the Hands-on Labs page for this training kit.

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

Exercise 1: Creating a cache and using regions

In this exercise, you will first create a cache specifically for this lab. Then you will use that cache to store data for an ASP.NET Application. When storing data in the Cache you will be using explicit Regions, which is one way of organizing data inside of the Cache.

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 machine’s cluster configuration into the context of your PowerShell session.

PowerShell

Use-CacheCluster

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

PowerShell

Get-CacheHost

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

Figure 1

Get-CacheHost cmdlet execution results

  1. If the Service Status is UP, skip to Task 2. 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

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

Figure 2

Starting the cache host

Task 2 – Using Regions

  1. Create a new cache named Lab3Cache for this lab by typing the following PowerShell command and pressing enter.

PowerShell

New-Cache Lab3Cache

  1. Open the solution using the LabStarter. Choose Ex. 1 of Lab 3 in the Begin column.
  1. After the projects load, hit CTRL+F5 to verify the application works.
  2. Open the Global.asax.cs file (right-click on the Global.asax file in the Solution Explorer and select View Code).
  3. Inside of the Application_Start method, after the existing code – write code that gets the Lab3Cache from the DataCacheFactory. Use the DataCache object to create a region named “RecentRoutes” and one named “UIData”.

C#

var dataCache = dcf.GetCache("Lab3Cache");

dataCache.CreateRegion("RecentRoutes");

dataCache.CreateRegion("UIData");

  1. After adding the code in the last step your Global.asax.cs file should look similar to Figure 3.

Figure 3

Creating regions

  1. Use CTRL+F5 to view the application in the browser to verify the application still works.
  2. Close the browser window.
  3. Switch to Windows PowerShell.
  4. Type Get-Cache and hit Enter.

PowerShell

Get-Cache

  1. You should see a result similar to Figure 4.

Figure 4

Regions added to cache

  1. Switch back to Visual Studio 2010.
  2. Open the Site.Master.cs file (right-click on the Site.Master file in the Solution Explorer and select View Code).
  3. Change the code in the GetCachedName method to both look for and add the data to the “UIData” region.
  4. Add a string variable named region with the value of “UIData”.
  5. Change the call to DataCache.Get to pass the region variable as the second parameter (this is the overload of Get that takes a region name as a parameter).
  6. Change the call to DataCache.Put to pass the region variable as the third parameter.
  7. Your code should look similar to Figure 5.

Figure 5

Using regions

  1. Open the Airports.aspx.csfile (right-clickon Airports.aspx file in the Solution Explorerand select View Code).
  2. Add a string variable named region with the value of “UIData”.
  3. Change the call to DataCache.Get to pass the region variable as the second parameter (this is the overload of Get that takes a region name as a parameter).
  4. Change the call to DataCache.Put to pass the region variable as the third parameter.
  5. Your code should look similar to Figure 6.

Figure 6

Using Regions

  1. Use CTRL+F5 to view the application in the browser to verify the application still works.
  2. Close the browser window.
  3. Go back to Visual Studio 2010.
  4. Open the Airports.aspx file (double-click on it in the Solution Explorer).
  5. Click on the Split view button (at the bottom of the file on the left) to view both the code and design view of the page.
  6. After the second DropDownList, add a br tag, and then an ASP.NET Button control. Set the Text property to “Request Route”.

ASP.NET

br/>

asp:ButtonText="Request Route"runat="server" />

  1. Your page should look similar to Figure 7.

Figure 7

Modified Airports.aspx

  1. In the design view (the bottom part of the screen),double-click on the Request Route button. This will add an eventhandler and put you in the code-behind file.
  2. After the ending curly brace of the Page class- add a class named RouteRequest that has two string properties named FromAirport and ToAirport, and a DateTime property named Requested. Make sure to add the Serializable attribute to your class.

C#

[Serializable]

publicclass RouteRequest

{

publicstring FromAirport { get; set; }

publicstring ToAirport {get;set;}

public DateTime Requested { get; set; }

}

  1. Inside of the Unnamed1_Clickmethod, you are going to add code that pulls the value of both drop downs, creates a new RouteRequest object and puts that object into the RecentRoutes region of the Lab3Cache.

C#

var request = newRouteRequest

{

ToAirport = DropDownList1.SelectedValue,

FromAirport = DropDownList2.SelectedValue,

Requested = DateTime.Now

};

var dcf = Application[Global.CacheFactoryName] asDataCacheFactory;

var cache = dcf.GetCache("Lab3Cache");

var region = "RecentRoutes";

cache.Add(Guid.NewGuid().ToString(), request, region);

  1. After adding the above code your class should look similar to Figure 8.

Figure 8

Adding items to the Recent Routes region

  1. Use CTRL+F5 to start the application.
  2. Select different airports from the drop downs and click Request Route.
  3. Repeat the last step at least two more times.
  4. Close your browser.
  5. Right-click on the AppFabricTest project in the Solution Explorer and select Add | New Item.
  6. Under Installed Templates select Visual C# | Web | Web Form using Master Page, name the file RecentRouteRequests and click Add. See Figure 9.

Figure 9

Adding RecentRouteRequests.aspx

  1. On the Select a Master Page dialog, make sure that Site.Master is highlighted in the right hand side and click OK.
  2. Inside of the Content tag with ID=”Content2”, add an ASP.NET GridView control.

ASP.NET

asp:GridViewID="GridView1" runat="server">

</asp:GridView

  1. After adding the GridView your page should look similar to Figure 10.

Figure 10

GridView added to page

  1. Go to the code behind by hitting F7.
  2. Add a using statement after the existing using statements for Microsoft.ApplicationServer.Caching.

C#

using Microsoft.ApplicationServer.Caching;

  1. Inside of the Page_Load method add code that gets the Lab3Cache, and uses the GetObjectsInRegion method to get all the objects from the RecentRoutes region. Then use the values to databind to the GridView.

C#

var dcf = Application[Global.CacheFactoryName] asDataCacheFactory;

var cache = dcf.GetCache("Lab3Cache");

var region = "RecentRoutes";

var all = cache.GetObjectsInRegion(region);

GridView1.DataSource = (from o in all

select o.Value);

GridView1.DataBind();

  1. After adding the code your class should look similar to Figure 11.

Figure 11

Page_Load

  1. Use CTRL+F5to view the application in the browser.
  2. You should see the requests that you made in the earlier step.
  3. As an extra challenge – add a button to the page. Add an event handler for the Button.Click event, and in the event clear all the objects from the region. Go back to the page and verify you can add items with the Airports.aspx page, and view and clear them in the RecentRouteRequests.aspx page.

Exercise 2 (Optional – Advanced): Extending a sample “admin” application

In this exercise, you will use the basic knowledge you learned in Exercise 1 and dive a little deeper into Regions and understand some of the details of how they work and how to use them.

Task 1– Adding Regions to a Cache

  1. Open the solution using the LabStarter. Choose Ex. 2 of Lab 3 in the Begin column..
  2. After the projects load, hit CTRL+F5 to verify the application works.
  3. The purpose of this application is to show you information about the AppFabric Cache.
  4. The home page will show a list of all the named caches that are available in your cache cluster (based on your local machine’s cache configuration).
  5. If you click on the hyperlinked name of any of the Caches, you will get a list of regions in that cache.
  6. Click on the hyperlink for Lab3Cache. Your page should look similar to Figure 12.

Figure 12

Regions in Lab3Cache

There are already regions in the cache you just created because the application is already using Lab3Cache to cache data, so the cache cluster created default regions.

  1. Close Internet Explorer.
  2. Back in Visual Studio 2010 double-click the RealCachInfoRepository.cs file in the Solution Explorer.
  3. Scroll down to the AddRegion method.
  4. Inside of the AddRegion add code that retrieves the current cache (Constants.CacheName) and creates a region based on the data passed to this method.

C#

var dcf = new DataCacheFactory();

var cache = dcf.GetCache(Constants.CacheName);

var added = cache.CreateRegion(region.Name);

  1. Your code should now look similar toFigure 13.

Figure 13

AddRegion

  1. Set a breakpoint on the ending curly brace of the AddRegion method (put your cursor on that line and hit F9).
  2. Hit F5to begin debugging.
  3. Once Internet Explorer loads, click on Lab3Cache.
  4. On the “region” page – type in a new RegionName and click the Add Region button.
  5. The Visual Studio 2010 debugger should appear. Move your cursor over the “added” variable – verify that its value is “true”. See Figure 14.

Figure 14

AddRegion method loaded into the debugger

  1. Hit F5 to continue the execution of the application.
  2. Back in Internet Explorer – note that your new cache does not appear on the page. Think about why. Close Internet Explorer.
  3. If you want to verify that your code added the region, switch back to PowerShell (if you closed PowerShell you will have to add the Import-Module statements from the beginning of the lab).

PowerShell

Get-Cache

The reason the newly added region (the fact that the added variable’s value was set to true should be proof enough that the region exists) doesn’t appear in the page, is that the application is caching that data. Look at the Caches property at the top of the RealCacheInfoRespository.cs file.

Although this is a recursive example (caching data about the cache), the experience will be the same whenever you cache data – when data is modified your application will need to respond if you don’t want the cache to be out of sync.

  1. In the AddRegionmethod, add another line of code after the cache.CreateRegion method call (at the end of the method block) that calls DataCache.Remove passing in the same key used in the Caches property.

C#

cache.Remove(key);

  1. Your code should now look similar to Figure 15.

Figure 15

DataCache.Remove call added to the AddRegion method

  1. Test this new method by going back and testing that your newly added region appears in the web page.

Summary

In this lab you used Cache Regions. Cache Regions are useful when you want to explicitly store cache items together (since items in a particular region will always be stored together on a single cache machine). You can create regions using code, and query all the items in a particular region at the same time.

1