Building Windows Azure Applications with the Caching Service

Building Windows Azure Applications with the Caching Service

Hands-On Lab

Building Windows Azure Apps with Caching service

Lab version:2.0.0

Last updated:4/15/2019

Contents

Overview

Getting Started: Provisioning the Service

Task 1 – Provisioning the Cache

Exercise 1: Using the Windows Azure Caching for Session State

Task 1 – Running the Azure Store Sample Site in the Compute Emulator

Task 2 – Configuring Session State Using Windows Azure Caching

Task 3 – Verification

Exercise 2: Caching Data with Windows Azure Caching

Task 1 – Caching Data Retrieved from the SQL Azure Repository

Task 2 – Measuring the Data Access Latency

Task 3 – Enabling the Local Cache

Exercise 3: Creating a Reusable and Extensible Caching Layer

Task 1 – Implementing a Caching Data Source Base Class

Task 2 – Building a Caching Product Catalog Repository

Task 3 – Creating a Data Source Factory Class

Task 4 – Configuring the Application for Caching

Summary

Overview

The Windows Azure Caching service provides a distributed, in-memory cache for your applications.In this lab, you will learn how to use the Windows Azure Caching service for both your ASP.NET session state and to cache data from your data-tier. You will see how the Windows Azure Caching service provides your application with a cache that provides low latency and high throughput without having to configure, deploy, or manage the service.

Objectives

In this hands-on lab, you will learn how to:

  • Easily and quickly provision your cache through the portal
  • Use the caching service for your ASP.NET session state
  • Cache reference data from SQL Azure in the caching service
  • Create a reusable and extensible caching layer for your applications

During this lab, you will explore how to use these features in a simple ASP.NET MVC application.

Prerequisites

The following is required to complete this hands-on lab:

  • Microsoft .NET Framework 4.0
  • Microsoft IIS 7
  • Microsoft Visual Studio 2010
  • Windows Azure SDK and Windows Azure Tools for Microsoft Visual Studio 1.6
  • Windows Azure Libraries for .Net 1.6

Note:This hands-on lab has been designed to use the latest release of the Windows Azure Tools for Visual Studio 2010 (version 1.5) and the new Windows AzureManagement Portal experience.

Setup

In order to execute the exercises inthis hands-on lab you need to set up your environment.

  1. Open a Windows Explorer window and browse to the Source folder.
  2. Double-click the Setup.cmd file in this folder to launch the setup process that will configure your environment and install the Visual Studio code snippets for this lab.
  3. If the User Account Control dialog is shown, confirm the action to proceed.

Note: Make sure you have checked all the dependencies for this lab before running the setup.

Note:This lab requires a SQL Azure database to start.To build the Northwind2 database automatically, the Setup.cmd file will prompt to you with your SQL Azure account information. Remember to update the NorthwingEntities connection string in the application’s configuration file to point to your database for each solution.

Note: Remember to configure the firewall setting your SQL Azure account to allow you to specify a list of IP addresses that can access your SQL Azure Server. The firewall will deny all connections by default, so be sure to configure your allow list so you can connect to the database. Changes to your firewall settings can take a few moments to become effective. For additional information on how to prepare your SQL Azure account, refer to the exercise 1 of the Introduction to SQL Azure lab in the training kit.

Figure 1

SQL Azure database setup

Using the Code Snippets

Throughout the lab document, you will be instructed to insert code blocks. For your convenience, most of that code is provided as Visual Studio Code Snippets, which you can use from within Visual Studio 2010 to avoid having to add it manually.

If you are not familiar with the Visual Studio Code Snippets, and want to learn how to use them, you can refer to the Assets\Setup.docx document, which contains a section describing how to use them.

Exercises

This hands-on lab includes the following exercises:

  1. Using the Windows Azure Caching for Session State
  2. Caching Data with Windows Azure Caching
  3. Creating a Reusable and Extensible Caching Layer

Estimated time to complete this lab: 60 minutes.

Note:When you first start Visual Studio, you must select one of the predefined settings collections. Every predefined collection is designed to match a particular development style and determines window layouts, editor behavior, IntelliSense code snippets, and dialog box options. The procedures in this lab describe the actions necessary to accomplish a given task in Visual Studio when using the General Development Settings collection. If you choose a different settings collection for your development environment, there may be differences in these procedures that you need to take into account.

Getting Started: Provisioning the Service

To complete the exercises in this lab, you will require a Windows Live ID Account. Once you have signed in, you will create a new subscription to use the Windows Azure Caching.

Task 1 – Provisioning the Cache

In this task, you will create a new subscription to use the Windows Azure Caching.

  1. Navigate to the Management Portal and, if necessary, sign in using your Windows Live ID credentials.
  2. Go to Service Bus, Access Control & Caching, located under the navigation pane, and click Cache.

Description D Users AMENEG 1 AppData Local Temp SNAGHTMLa4959d PNG

Figure 2

Windows Azure Cache

  1. Click New Namespace Button to create a new instance of caching. Complete the Cache Service Namespace with a custom name, pick a Country/Region, Cache Size,and click Create Namespace.

Figure 3

Creating a new Cache Service Namespace

Note: A service namespace defines a boundary for each application exposed through the Service Bus, allowingan application to uniquely addressthe service endpoints.

  1. Locate the new entry in the list of configured service namespaces and then wait for its Status column to show the namespace as Active.

Figure 4

Summary list of available cache service namespaces

  1. Click on the namespace created in the previous steps, locate the Propertiespane and record the value shown for the Service URLand the Service Port.

C Users AMENEG 1 AppData Local Temp SNAGHTML6f080ca PNG

Figure 5

Service namespace cache settings

  1. Now click the View button next to Authentication Token in the Properties pane. In the Authentication Token dialog, click Copy to Clipboard next to Authentication Token.For your convenience, save this value on notepad as you will use this value later on to configure the application.

Figure 6

Retrieving the Authentication Token

  1. Click View Client Configurationon the upper ribbonand select all the text from the Client Configuration window.Press CTRL + C to copy, and paste it on a notepad for a later use.
    This XML contains the configuration required to leverage Windows Azure Caching Access Control.

Figure 7

Copying XML from Client Configuration

Exercise 1: Using the Windows Azure Caching for Session State

In this exercise, you will explore the use of the session state provider for Windows AzureCaching as the mechanism for out-of-process storage of session state data. For this purpose, you will use the Azure Store—asample shopping cart applicationimplemented with ASP.NET MVC. You will run this application in the compute emulator and then modify it to take advantage of the Windows Azure Caching as the back-end store for the ASP.NET session state.You will start with a begin solution and explore the sample using the default ASP.NET in-proc session state provider. Next, you will add references to the Windows Azure Caching assemblies and configure the session state provider to store the contents of the shopping cart in the distributed cache cluster provided by Window Azure.

Task 1 – Running the Azure Store Sample Site in the Compute Emulator

In this task, you will run the Azure Store application in the compute emulatorusing the default session state provider; you will change that provider to take advantage of the Windows Azure Caching service later on.

  1. Start Microsoft Visual Studio 2010 as administrator.
  2. Open the Begin solution located at Source\Ex1-CacheSessionState\Begin.

Important: Before you execute the solution, make sure that the start-up project is set. For MVC projects, the start page must be left blank.

To set the start-up project, in Solution Explorer, right-click the AzureStoreService project and select Set as StartUp Project.

To set the start page, in Solution Explorer, right-click the MVCAzureStore project and select Properties. In the Properties window, select the Web tab and in the Start Action, select Specific Page. Leave the value of this field blank.

  1. In the Web.config file, update the NorthwindEntities connection string to point to your database. Replace [YOUR-SQL-AZURE-SERVER-ADDRESS], [SQL-AZURE-USERNAME], and [SQL-AZURE-PASSWORD]in the connectionStrings section with the SQL Azure database server name, Administrator Username and Administrator password that you registered at the portal and used for creating the database during setup.

Note: Make sure that you follow the instructions of the setup sectionto create a copy of the Northwind2 database in your own SQL Azure account and configure your SQL Azure firewall settings.

  1. Press F5 to build and run the application in the compute emulator.
  2. Explore the main page of the application, the Products page, which displaysa listof products obtained from a SQL Azure database.

Figure 8

Azure Store products page

  1. Select a product from the list and click Add item to cart. You may repeat the process to store additional items in the shopping cart.
  2. Click the Checkout link to view the contents of the cart. Verify that the items you selected appear on the list. These items arestored in the current session.

Figure 9

Checkout page showing the contents of the shopping cart

  1. Do not close the browser window or navigate away from the checkout page.
  2. In the task bar, right-click the compute emulator icon and select Show Compute Emulator UI.
  3. In the Compute Emulator, right-click the AzureStoreService node and choose Suspend.

Figure 10

Suspending the service role instance

  1. Open a command window in elevated administrator mode, from Start | All Programs | Accessories | Command Prompt by right clicking the Command Promptshortcut and choosingRun as Administrator and type iisreset.

Figure 11

Executing iisreset command

Note:These two steps, recycling the role and restarting IIS, simulate what would happen in Windows Azure when a role instance is restarted.

  1. Go back to the Compute Emulator and wait until the service is destroyed as indicated by the instance icon turning purple. Now, restart the service instance once again. To do this, right-click the AzureStoreService node and choose Run, thenwait for the service to start.

Note: If you are using as default browser other than Internet Explorer, the suspended instance in the compute emulator may be removed and Visual Studio will stop debugging. If this happens, go back to Visual Studio and press F5 to run the application in the compute emulator again andwait for the service to start.

  1. Switch back to the browser window showing the checkout page and click Refresh. Notice that the order now appears empty.

Note: The application is currently using in-proc session state, whichmaintains the session state in-memory. When you stop the service instance, it discards all session state including the contents of the shopping cart. In the following task, you will configure the application to store session state usingWindows Azure Caching as the storage mechanism, which allows the application to maintain the session state in the presence of restarts and across multiple role instances hosting the application.

  1. Close the browser window to stop the application.

Task 2 – Configuring Session State Using Windows Azure Caching

In this task, you will change the Session State provider to take advantage of the Windows Azure Cache as the storage mechanism. This requires adding the appropriate assemblies to the MVCAzureStore project and then updating the corresponding configuration in the Web.config file.

  1. Go back to Visual Studio 2010 and add a reference to the Microsoft.ApplicationServer.Caching.Client, Microsoft.ApplicationServer.Caching.Core,andMicrosoft.Web.DistributedCache assemblies. In Solution Explorer, right-click the MVCAzureStore project, select Add Reference, click the .NET tab, select the assemblies and click OK.
  2. Make sure to include these assemblies as part of the service package. To do this, right-click the Microsoft.ApplicationServer.Caching.Client assembly and select Properties. In the Project Properties window, verify that the value of theCopy Local setting is set toTrue. Do the same for the other assemblies added in the previous step.

Note: In general, you need to set Copy Local = True for any assembly that is not installed by default in the Windows Azure VMs to ensure that it is deployed with your application.

  1. Open the Web.config file located in the root folder of the MVCAzureStore project.
  2. Go back to the notepad window where you saved the Client Configuration data and copy thetext from the configSections tag.

Figure 12

Copying configSections

  1. Go back to Visual Studio 2010, andpastethe section inside the configuration tag in web.configfile. Make sure that this element is the first element inside the configuration tag.

XML

configuration

configSections

<sectionname="dataCacheClients"type="Microsoft.ApplicationServer.Caching.DataCacheClientsSection, Microsoft.ApplicationServer.Caching.Core"

allowLocation="true"allowDefinition="Everywhere"/>

</configSections

<connectionStrings

...

  1. Go back to the notepad window again and copy thedataCacheClientsconfiguration.

Figure 13

Copying dataCacheClients section

  1. Go back to Visual Studio 2010 andpastethe configuration you have copied, under the closing configSections tag, as shown in the image below.

XML

...

</configSections

dataCacheClients

<dataCacheClientname="default"

<hosts

<hostname="[SERVICE-HOST-NAME]"cachePort="22233" />

</hosts

<securityPropertiesmode="Message"

<messageSecurity

authorizationInfo="[AUTHORIZATION INFO]"

</messageSecurity

</securityProperties

</dataCacheClient

</dataCacheClients

connectionStrings

Note: When copying the dataCacheClients section from the Management Portal, you will find two endpoints declared: one simple and other ssl endpoint. For this lab, we will be using the simple one, so the ssl should not be included in the web.config file.

  1. The last setting you need to configure is the sessionState provider, to do so, go back to the notepad window and copy sessionState element.

Figure 14

Copying sessionState

  1. Go back to Visual Studio 2010 and paste the element you copied inside the system.webconfiguration section.

XML

...

system.web

<sessionStatemode="Custom"customProvider="AzureCacheSessionStoreProvider"

providers

<addname="AzureCacheSessionStoreProvider"

type="Microsoft.Web.DistributedCache.DistributedCacheSessionStateStoreProvider, Microsoft.Web.DistributedCache"

cacheName="default"

useBlobMode="true"

dataCacheClientName="default" />

</providers

</sessionState

<compilationdebug="true"targetFramework="4.0"

...

Note: The DistributedCacheSessionStateStoreProvidersession state provider enables out-of-process storage of session state data using Windows Azure Cache as the storage mechanism.

  1. Press CTRL + S to save your changesto the Web.config file.

Task 3 – Verification

  1. Press F5 to build and run the application.Wait for the browser to launch and show the Products page.
  2. Select one product from the list and click Add item to cart. Repeat the process to store additional items in the cart.
  1. Click the Check Out link to view the contents of the shopping cart. Verify that the items you selected appear on the list.
  2. Do not close the browser window or navigate away from the checkout page.
  3. In the task bar, right-click the compute emulator icon and select Show Compute Emulator UI.
  4. In the Compute Emulator, right-click the AzureStoreService node and choose Suspend. Wait until the service stops as indicated by the instance icon turning purple.
  1. Open a command window in elevated administrator mode and type iisreset.
  2. Now, restart the service instance once again. To do this, right-click the AzureStoreService node and choose Run, thenwait for the service to start.

Note: If you are using as default browser other than Internet Explorer, the suspended instance in the compute emulator may be removed and Visual Studio will stop debugging. If this happens, go back to Visual Studio and press F5 to run the application in the compute emulator again andwait for the service to start.