Sunteți pe pagina 1din 31

Hands-On Lab

Windows Server AppFabric Cache:


Lab 2 Programming the Cache
Lab version: 1.0.0
Last updated: 7/27/2017

1
CONTENTS

OVERVIEW 3
Starting Materials 3

EXERCISE 1: CREATING THE CACHE FOR THIS LAB 4


Task 1 Creating the cache for this lab................................................................................................4
Task 2 Using the cache to cache reference data................................................................................5

EXERCISE 2: BUILDING AN ADMIN APPLICATION 15


Task 1 Retrieving Data about the Cache..........................................................................................15
Task 3 Adding Data to the Cache.....................................................................................................26

Summary 29

2
Overview
This lab introduces the basics of using the Windows Server App Fabric Cache client APIs for storing and
retrieving data in the Cache.

Objectives
The objectives for this lab are
Use the basic Cache Client API
Learn how to configure your application to use the Local 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 Visual Studio for you automatically.

Exercises
This Hands-On Lab comprises the following exercises:
Exercise 1: Creating the Cache for this lab

Estimated time to complete this lab: 60 minutes.

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.
3
Note: Inside each exercise folder, you will find an end folder containing a solution with the
completed lab exercise.

4
Exercise 1: Creating the Cache for this lab
In this exercise, you will be creating a named cache, and then using it to store some simple reference
data for an ASP.NET Web Application.
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
Checking the cache host status

.5 If the Service Status is UP, skip to Task 2. 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. Use only the code below followed by ENTER.
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

Task 2 Using the cache to cache reference data


.8 Create a new cache named Lab2Cache for this lab by typing the following PowerShell
command and pressing Enter.
PowerShell
New-Cache Lab2Cache

.9 Open the solution using the LabStarter. Choose Ex. 1 of Lab 2 in the Starting column under
the Caching tab.
.10 Open the Web.Config file by double-clicking on it in the Solution Explorer.
.11 Replace the value of the name attribute in the host element under the dataCacheClient entry
with the name of your machine. See Figure 3.

Figure 3
Data Cache client configuration in Web.Config
.12 Close the Web.Config file and click YES to save it.
.13 Right-click on the App_Data folder in the Solution Explorer and select Add | Existing Item. .
See Figure 4.

6
Figure 4
Adding an existing item
.14 Navigate up 4 levels to the \Source directory, then down into .\Assets..
.15 Pick BlueYonderAirlines.mdf and select Add. . This will be your data source for this exercise.
.16 Add a new ADO.NET Entity Data Model class to your project by right-clicking on the
AppFabricTest project in the Solution Explorer and selecting Add | New Item.
.17 Under Installed Templates, select Visual C# | Data | ADO.NET Entity Data Model and click
Add. See Figure 5.

Figure 5
Add New ADO.NET Entity Data Model

7
.18 In the Entity Data Model Wizard dialog, keep the Generate from database selected and press
Next. See Figure 6.

Figure 6
Entity Data Model Wizard

.19 On the next wizard page, keep the defaults and select Next.

8
Figure 7
Choosing the data connection
.20 In the next wizard page, click the checkbox next to Tables and select Finish. See Figure 8.

Figure 8
Database object page
.21 You have now added an ADO.NET Entity Data Model for the Airport table that contains a list
of airports and airport three letter codes (TLC) from around the world.
.22 Right-click on the AppFabricTest project in the Solution Explorer and select Add | New Item.
.23 Under Installed Templates, select Visual C# | Web | Web Form using Master Page, name the
file Airports , and click Add. . See Figure 9.

9
Figure 9
Adding a new Web Form
.24 On the Select a Master Page dialog, make sure that Site.Master is highlighted in the right-
hand side and click OK.
.25 Inside of the Content tag with ID=Content2, put the following ASP.NET controls:
ASP.NET
From:
<asp:DropDownList ID="DropDownList1" runat="server">
</asp:DropDownList>
To:
<asp:DropDownList ID="DropDownList2" runat="server">
</asp:DropDownList>

.26 Your page should look similar to Figure 10.

10
Figure 10
Page with Controls added
.27 Press F7 to go to the code-behind of the page
.28 Inside of the Page_Load method, add code that checks to see if the request is a post-back or
not, then data-bind the two drop-down lists to the Airport entities you created earlier. Set the
DataTextField of the two drop- downs to AirportName and the DataValueField to AirportTLC
C#
if (!IsPostBack)
{
var ctx = new BlueYonderAirlinesEntities();
DropDownList1.DataSource = ctx.Airports;
DropDownList1.DataTextField = "AirportName";
DropDownList1.DataValueField = "AirportTLC";
DropDownList2.DataSource = ctx.Airports;
DropDownList2.DataTextField = "AirportName";
DropDownList2.DataValueField = "AirportTLC";
DataBind();
}

.29 Press CTRL+F5 to show the page in the browser. . It should look similar to Figure 11.

11
Figure 11
Airports in the browser
.30 Make sure to refresh the browser a few times to get the execution time to a consistent
number (the first time you hit the page you will see the overhead from the ASP.NET
compilation).
.31 Close the browser and go back to Visual Studio 2010.
.32 Add a using statement for Microsoft.ApplicationServer.Caching and AppFabricTest.code after
all the other using statements at the top of the Airports.aspx.cs file.
C#

using Microsoft.ApplicationServer.Caching;
using AppFabricTest.Code;

.33 Inside of the Page_Load method, modify the code to use the AppFabric Cache to store the
Airport data (use the cache-aside pattern, first checking to see if the data is in the cache). . You
will also need to call ToList on the Airports property to change the list into a serializable
reference. . Finally, use HttpContext.Current.Items (using SimpleTimingModule.ExtraMsg as
the key) to set a message about whether the data is from the cache or from the database.
C#
var dcf = Application[Global.CacheFactoryName] as DataCacheFactory;
var cache = dcf.GetCache("Lab2Cache");
var key = "Airports";
var data = cache.Get(key) as IEnumerable<Airport>;

12
if (data == null)
{
var ctx = new BlueYonderAirlinesEntities();
data = ctx.Airports.ToList();
cache.Put(key, data);
HttpContext.Current.Items[SimpleTimingModule.ExtraMsg] = " Data From
Database";
}
else
HttpContext.Current.Items[SimpleTimingModule.ExtraMsg] = " Data From
Cache";
DropDownList1.DataSource = data;
DropDownList1.DataTextField = "AirportName";
DropDownList1.DataValueField = "AirportTLC";
DropDownList2.DataSource = data;
DropDownList2.DataTextField = "AirportName";
DropDownList2.DataValueField = "AirportTLC";
DataBind();

.34 After the last step, your code should look similar to Figure 12.

Figure 12
Page_Load after adding caching code
.35 Use CTRL+F5 to start the application. Make sure to refresh the browser window a few times. .
Your browser window should look similar to Figure 13.

13
Figure 13
Data Cached
.36 Open the Web.config (double-click on the file in the Solution Explorer) to add support for
using the local AppFabric Cache. . Add the localCache element under the hosts element.
XML Configuration
<localCache
isEnabled="true"
sync="TimeoutBased"
objectCount="100000"
ttlValue="300" />

.37 Click Save, your Web.config should now look similar to Figure 14.

14
Figure 14
Web.config with local cache configuration
.38 Open Airports.aspx again in Visual Studio 2010.
.39 Again use CTRL+F5 to display your page
.40 Press F5 (or refresh the browser) several times until you get similar values for the page
execution time.
.41 You should see that enabling the local cache speeds up the AppFabric cache.
.42 Click here to enter text.

15
Exercise 2: Building an admin
application

In this optional exercise, you will begin building an application in ASP.NET that can act as an admin
application for the Cache. . The purpose of this exercise is to give you more experience writing code
against the APIs that control the cache, not just the APIs that store and retrieve data from the cache.
One thing you should note about this application is that it needs to reference the Caches server APIs, so
it would need to be installed on a full Cache server.
Task 1 Retrieving Data about the Cache
In this task, you will be adding code to a simple ASP.NET application that displays data stored in the
cache and enables adding new data to the cache (and the underlying data store). . The ASP.NET
application currently uses a faux data source, so your task will be to replace that data source with one
that pulls information from the AppFabric Cache.
.43

.44 Open the solution using the LabStarter. Choose Ex. 2 of Lab 2 in the Starting column under
the Caching tab.
.45 Hit CTRL-F5 to start the application outside of the debugger.
.46 You should see a page similar to Figure 15.

16
Figure 15
Application showing faux data.
.47 There are two things to note in the web page in Figure 3. . First, notice the page execution
time displayed in the upper- left corner. . This will be useful when you want to see the effect of
adding code using the cache.
.48 Also note that each of the boxes with the faux cache names are hyperlinks; if you click on
one of them it will take you to a page that displays all of the regions in the named cache youve
selected. See Figure 16.

17
Figure 16
Region page
.49 From the page in Figure 16, you can click the Region link to see all the items (the items page
has similar functionality), as well as enter a new region.
.50 Now you will add code that replaces the faux data with real data from AppFabric.
.51 Close Internet Explorer.
.52 Go back to Visual Studio 2010. Right-click on the AppFabricLabs.Interfaces project in the
Solution Explorer and select Add Reference.
.53 In the Add Reference dialog box, click on the Browse tab.Navigate up 4 levels to the \Source
directory, then down into .\Assets\AppFabricCacheDlls.
.54 Pick All3 (Microsoft.ApplicationServer.Caching.Client.dll,
Microsoft.ApplicationServer.Core.dll, and Microsoft.Error: Reference source not
foundApplicationServer.Caching.Management.dll) from the list of assemblies in the folder.
Then press OK.

.55 In the Solution Explorer, double-click on the ICacheInfoRepository.cs file in the


AppFabricLabs.Interfaces project. See Figure 17.

18
Figure 17
ICacheInfoRespository interface.
.56 The ICacheInfoRespository interface is the interface you are going to implement to provide
the data access to the application.
.57 Right-click on the AppFabricLabs.Interfaces project and select Add | New Item.
.58 In the Add New Item dialog, pick the Class template. . Name the class
RealCacheInfoRepository See Figure 18.

Figure 18
Add New Item dialog
.59 In the RealCacheInfoRespository.cs file (which should have appeared in the editor when you
added the item). Add the public keyword to the class definition.
C#
public class RealCacheInfoRespository

19
{
}

.60 Add ICacheInfoRespository interface to the inheritance chain of the RealCachInfoRespository


class.
C#
public class RealCacheInfoRespository : ICacheInfoRespository
{
}

.61 Implement the ICacheInfoRespository interface. One easy way to do this is to right-click on
ICacheInfoRespository in the editor, and select Implement Interface | Implement Interface.
See Figure 19.

Figure 19
Implement interface
.62 If you used the Implement Interface functionality, remove the throw statements from inside
of the members (inside of the get block you will need to add a return null statement). Now
your code file should look like this:
C#
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace AppFabricLabs.Interfaces
{
public class RealCacheInfoRespository : ICacheInfoRespository
{
public IQueryable<CacheModel> Caches
{

20
get { return null; }
}

public void AddRegion(CacheRegionModel region)


{

public void AddItem(string cache, string region, string key, string


value)
{

}
}
}

.63 Add the following using statements after all of the existing using statements in the
RealCacheInfoRespository.cs file.
C#
using Microsoft.ApplicationServer.Caching;
using System.Management.Automation;
using System.Management.Automation.Runspaces;
using Microsoft.ApplicationServer.Caching.AdminApi;
using System.ComponentModel.Composition;

.64 Now add the MEF Export attribute to the RealCacheInfoRespository class. See Figure 20.
C#
[Export(typeof(ICacheInfoRespository))]

21
Figure 20
The Export attribute added to the class definition.
.65 Open the FauxCacheRepository.cs file from the Solution Explorer by double-clicking on it.
.66 Comment out the Export attribute on the FauxCacheRespository class. See Figure 21.

Figure 21
Commenting out Export attribute

This project uses the Managed Extensibility Framework (MEF) to dynamically load the type that
will provide access to the underlying data store. In the earlier test, the
FauxCacheInfoRepository class was providing faux data to the Web UI. Your task in this lab
will be to implement access to real data.

.67 Debug the application to verify that the RealCacheInfoRespository type is being loaded and
used as the data access layer.

22
.68 Place your cursor inside of the Caches propertys get block and hit F9 to set a breakpoint. See
Figure 22.

Figure 22
Breakpoint in the Caches get block
.69 Hit F5 (or use the Debug | Start Debugging from the menu)
.70 Visual Studio 2010 should hit a breakpoint in the Caches get block. See Figure 23. Press F5
to continue execution of the application.

Figure 23
Visual Studio breakpoint
.71 Internet Explorer will open. . It should look similar to Figure 24. . There should be no data
displayed.

23
Figure 24
No data in page
.72 Close the browser window, which will bring you back to Visual Studio 2010 after the
debugging session has stopped.
.73 Back inside of the Cache propertys get block, delete the return null; line of code.
.74 Press CTRL+K,CTRL+X to bring up the snippets menu, select My Code Snippets >
AppFabric_Lab2_Ex2_CacheGet as the snippet and hit Enter. You can also type the following
code inside of the get block.
C#
get {
var state = InitialSessionState.CreateDefault();
state.ImportPSModule(new string[] { "DistributedCacheAdministration",
"DistributedCacheConfiguration" });
state.ThrowOnRunspaceOpenError = true;
var rs = RunspaceFactory.CreateRunspace(state);
rs.Open();
var pipe = rs.CreatePipeline();
pipe.Commands.Add(new Command("Use-CacheCluster"));
pipe.Commands.Add(new Command("Get-Cache"));
var output = pipe.Invoke();
var result = from c in output
select new CacheModel { Name =
((CacheInfo)c.BaseObject).CacheName };

return result.AsQueryable();

.75 Your code should look similar to Figure 25.

24
Figure 25
Snippet- added code
.76 This code is using the PowerShell API to execute the Use-CacheCluster and Get-Cache
cmdlets.
.77 The result from Get-Cache is being queried using LINQ- to- Objects to build up a list of the
caches on your machine for the Web UI to data bind to.
.78 Use CTRL+F5 to start the application without debugging. You should see something similar to
Figure 26.

Figure 26
Showing real data

25
.79 Press F5 or refresh the browser a few times in the browser and take note of the quickest
execution time.
.80 Close the browser and go back to Visual Studio 2010.
.81 In the RealCachInfoRespository.cs file, put your cursor inside of the ending curly brace next
to where it says .CacheName.
.82 Add a comma and press Return.
.83 Without moving your cursor, hit CTRL+K,CTRL+X to bring up the snippets menu and select My
Code Snippets > AppFabric_Lab2_Ex2_RegionsAssignment,
.84 In the RealCachInfoRespository.cs file, put your cursor after the ending curly brace for the
Caches property.
.85 Use CTRL+K+X to bring up the snippets menu and select My Code Snippets >
AppFabric_Lab2_Ex2_InitRegions. You can also enter the following code.
C#
private IEnumerable<CacheRegionModel> InitRegion(String cachename)
{
var state = InitialSessionState.CreateDefault();
state.ImportPSModule(new string[]
{ "DistributedCacheAdministration", "DistributedCacheConfiguration" });
state.ThrowOnRunspaceOpenError = true;
var rs = RunspaceFactory.CreateRunspace(state);
rs.Open();
var pipe = rs.CreatePipeline();
var cmd = new Command("Get-CacheRegion");
cmd.Parameters.Add(new CommandParameter("CacheName", cachename));
pipe.Commands.Add(cmd);
var regions = pipe.Invoke();
var regionResult = from r in regions
select new CacheRegionModel { CacheName =
cachename, Name = ((RegionInfo)r.BaseObject).RegionName };
return regionResult;
}

.86 At this point, your code should look similar to Figure 27.

26
Figure 27
InitRegion code
.87 The code you just added uses the same PowerShell scripts to get the region names for each
Cache.
.88 Again, do a CTRL+F5 to bring the web application up in the browser.
.89 You should now be able to click on the name of the cache and see the list of its regions.
.90 Close the browser window
.91

27
Task 3 Adding Data to the Cache
In this task, you will be taking the information you retrieved about the Cache in the last task and storing
that data in the cache.
.92 In the RealCachInfoRespository.cs file, delete the last line of code in the Caches get block
(return result.AsQueryable();).
.93 You will now add code to this block to create a new DataCacheFactory object to retrieve the
cache named Lab2Cache. Then try to find an item in the cache named CacheOfCacheData. If
it isnt found in the cache, use the existing code to retrieve the data, then put that data as a
List<CacheModel> into the cache using the same key you tried to retrieve it with. Then return
the result as IQueryable<CacheModel>. Your code should look like Figure 28. (If you want to
use a snippet to add this code move on to the next step).

Figure 28
Code to cache data about the cache, in the cache
.94 To use the snippet, - highlight the rest of the code inside of the Caches get block and use
CTRL+K+S to bring up the surrounds with snippets. Pick
App_Fabric_Lab2_Ex2_CacheInfoCaching from the list and press Enter. See Figure 29. You can
also replace the code inside of the get block with the following:
C#
var dcf = new DataCacheFactory();
var cache = dcf.GetCache(Constants.CacheName);
var key = "CacheOfCacheData";
var caches = cache.Get(key) as List<CacheModel>;

28
if (caches == null)
{

var state = InitialSessionState.CreateDefault();


state.ImportPSModule(new string[]
{ "DistributedCacheAdministration", "DistributedCacheConfiguration" });
state.ThrowOnRunspaceOpenError = true;
var rs = RunspaceFactory.CreateRunspace(state);
rs.Open();
var pipe = rs.CreatePipeline();
pipe.Commands.Add(new Command("Use-CacheCluster"));
pipe.Commands.Add(new Command("Get-Cache"));
var output = pipe.Invoke();
var result = from c in output
select new CacheModel { Name =
((CacheInfo)c.BaseObject).CacheName, Regions =
InitRegion(((CacheInfo)c.BaseObject).CacheName) };
caches = result.ToList();
cache.Add(key, caches);
}
return caches.AsQueryable();

Figure 29
Using CacheInfoCaching snippet
.95 Hit CTRL+F5 to start the application.
.96 Note that you get an error (it should be the same or similar to Figure 30).

29
Figure 30
Serialization exception
.97 Note that AppFabric Cache could serialize the List<CacheModel> successfully, but not the list
of Regions (this is because of the way the code is written).

The moral of the story here is that you must consider the potential side effects of using the
cache.

.98 Close the browser.


.99 To fix this issue, go back to the RealCachInfoRespository.cs file.
.100 Inside of the InitRegion method, change the last line of code from return regionResult; to
be regionResult.ToList().
C#
return regionResult.ToList();

.101 Adding this line of code forces the LINQ query to run immediately rather than later (which is
why the exception is happening).
.102 Hit CTRL+F5 again to start the application.
.103 Once the page appears in the browser, hit F5 (refresh) a few times and, note the difference
between the cached and the non-cached execution time.

30
Summary
In this lab, you created a new cache using the AppFabric Cache PowerShell module. You also used that
same module from .NET code to retrieve interesting information about the cache.

Finally you used the cache itself to cache data for display inside of a simple ASP.NET application.
Although this data is data about the cache itself, you will use the same methodolgy to use the AppFabric
Cache to cache any interesting or useful data.

31

S-ar putea să vă placă și