Building Windows Azure Applications with the Caching Service

In this Article, 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 Caching service provides your application with a cache that provides low latency and high throughput without having to configure, deploy, or manage the serviceOverview

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 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.

Exercises

This 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
Advertisements

Connecting Apps with Windows Azure Connect

Windows Azure Connect’s primary scenario is enabling IP-level network connectivity between Azure services and external resources. The underlying connectivity model that supports this is quite flexible. For example, you can use Sydney to setup networking between arbitrary groups of machines that are distributed across the internet in a very controlled and secure manner.

Overview

To enable IP-level network connectivity between Azure services and external resources, Windows Azure Connect can be used. The underlying connectivity model that supports this is quite flexible. For example, you can use Windows Azure Connect to setup networking between arbitrary groups of machines that are distributed across the internet in a very controlled and secure manner.

The following diagram illustrates the key elements of the Windows Azure Connect model.

Windows Azure Connect creates a logical “virtual network” which can contain two types of entities: Azure Role groups and Machine groups.

  • Role groups map to Azure roles, which have been enabled for Windows Azure Connect. Only the Azure VM instances for a role are members of a role group – the admin cannot manually add or remove members. Windows Azure Connect automatically manages the membership of role groups – if you add or remove role instances, Windows Azure Connect will track this and update the role group membership appropriately.
  • Machine groups are admin-defined collections of external machines, which have been enabled for Windows Azure Connect through installation of the Windows Azure Connect Endpoint Software. An external machine can belong to at most one machine group.

Connectivity within the Windows Azure Connect virtual network is based on the following rules:

  • A role group can be “linked” to a machine group – this enables connectivity between the members of those groups. A role group can be linked to multiple machine groups – e.g. you could have an Azure web role that is connected to your “My Servers” and “My Laptops” machine groups as shown in the diagram above.
  • Members of a role group (the Azure VM instances) do not have connectivity with each other. In addition, a role group cannot be linked to another role group. These limitations are intentional – the Azure service model controls connectivity between roles and the Azure runtime supports connectivity between role instances. We did not want the Windows Azure Connect model to interfere with this behavior.
  • Machine groups can be linked, as mentioned above, to role groups. Machine groups can also be linked to other machine groups to enable connectivity between members of those groups.
  • Links are not transitive from a connectivity perspective. For example, suppose Group A is linked to Group B, and Group B is linked to Group C. Machines in Group A can communicate with those in Group B, and machines in Group B can communicate with those in Group C. However, machines in Group A cannot communicate with those in Group C.
  • A machine group has an “interconnected” property – if it is set to true, then all members of that group can communicate with each other. If it is set to false, then communication between the members is not allowed.
  • It is important to note that Windows Azure Connect does not affect or interfere with a machine’s existing network connectivity.

Objectives

In this lab, you will learn how to:

  • Provision a Windows Azure Connect service and associate it with your Azure subscription.
  • Setup network connectivity between Azure Roles and external machines.

Exercises

This lab includes the following exercise:

  1. Connecting an Azure Web Role to an External SQL Server Database with Windows Azure Connect
  2. Connecting an Azure Web Role to a on premise services with Windows Azure Connect

Windows Azure CDN

In this Article, you will learn how to scale your static blob content out to the Content Distribution Network (CDN) available in Windows Azure.

Overview

Windows Azure provides the Windows Azure Content Delivery Network (CDN) to deliver Windows Azure Blob content. Windows Azure CDN offers developers a global solution for delivering high-bandwidth content.

Windows Azure CDN has several locations globally (United States, Europe, Asia, Australia and South America) and continues to expand. Windows Azure CDN caches your Windows Azure blobs at strategically placed locations to provide maximum bandwidth for delivering your content to users. You can enable CDN delivery for any storage account via the Windows Azure Management Portal. The CDN provides edge delivery only to blobs that are in public blob containers, which are available for anonymous access.

The benefit of using a CDN is better performance and user experience for users who are farther from the source of the content stored in the Windows Azure blob storage.

When you enable CDN access for a storage account, the Management Portal provides you with a domain name of the following format: http:/ /<identifier>.vo.msecnd.net/. This domain name can then be used to access blobs in a public container. For example, given a public container “images” and a storage account “youraccount”, once the storage account is enabled for CDN access, users can access the blobs in that container using either of the following two URLs:

When a request is made using the Windows Azure Blob service URL, the blob is read directly from the Windows Azure Blob service. When a request is made using the Windows Azure CDN URL, the request is redirected to the CDN endpoint closest to the location from which the request was made to provide access to the blob. If the blob is not found at that endpoint, then it is retrieved from blob storage and cached at the endpoint, where a time-to-live (TTL) setting is maintained for the cached blob. The TTL specifies that the blob should be cached for that amount of time in the CDN until it is refreshed by the Blob service. The CDN attempts to refresh the blob from Windows Azure blob storage only once the TTL has elapsed. As described in this msdn article, the default TTL is calculated as 20% of the interval between the present time and the last-modified time, up to a maximum interval of 72 hours. For example, a blob whose last-modified time was 30 minutes ago will be considered fresh for six minutes in the CDN cache. If this value is specified for a blob, then the TTL period will be set to the value specified in Cache-Control HTTP header.

The value of caching blobs in the Windows Azure CDN is realized only when the content is delivered from the CDN edge cache, so content requested only once during the blob’s TTL period will not get performance improvements from edge caching. The blob content that benefits the most from caching are blobs accessed frequently during their cached TTL period.

Blobs already cached in the CDN will remain cached until the TTL for each blob expires. When the TTL expires, the Windows Azure CDN will check to see whether the CDN endpoint is still valid and the Windows Azure blob is still anonymously accessible. If it is not, then the blob will no longer be cached. This means that if you want to change the content of the blob and the blob is currently cached in the CDN, the new content will not be available via the CDN until the CDN refreshes its content when the cached content TTL expires.

When you enable the CDN the configuration created for this endpoint is not immediately available; it can take up to 60 minutes for the registration to propagate through the CDN network worldwide. Users who try immediately to use the CDN domain name will get a 400 error until the configuration is updated worldwide.

Objectives

In this lab, you will learn how to:

  • Enable Windows Azure CDN
  • Leverage Windows Azure CDN for static content
  • Use TTL headers to control CDN caching scenarios

Prerequisites

The following is required to complete this lab:

  • IIS 7 (with ASP.NET, WCF HTTP Activation)
  • Microsoft Visual Studio 2010
  • Microsoft .NET Framework 4.0
  • Windows Azure Tools for Microsoft Visual Studio 1.6

Exercises

This lab includes the following exercises:

  1. Using the CDN to Deliver Static Content
  2. Managing Cache Expiration and Resource Versioning
  3. Caching Content from Hosted Services

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.

Azure Zone Web Role Service Configuration(HTTPs)

 Overview

Secure Sockets Layer (SSL), are cryptographic protocols that provide communications security over the Internet.TLS/SSL encrypt the segments of network connections above the Transport Layer, using symmetric cryptography for privacy and a keyed message authentication code for message reliability.

Targeted Audience

This specification is intended for Architects, Project Managers, Software Design Engineers and Developer.

SSL Certificate

SSL uses an encryption mechanism to transport the data from Client-Server. The encryption using a private key/public key pair ensures that the data can be encrypted by one key but can only be decrypted by the other key pair

The trick in a key pair is to keep one key secret (the private key) and to distribute the other key (the public key) to everybody (client). A client side public key is stored in certificate.

A certificate contains information about the owner, like e-mail address, owner’s name, certificate usage, duration of validity and the certificate ID of the person who certifies (signs) this information.

Certificate contains also the public key and finally a hash to ensure that the certificate has not been tampered with. Usually your browser or application has already loaded the root certificate of well known Certification Authorities (CA) or root CA Certificates. The CA maintains a list of all signed certificates as well as a list of revoked certificates.

Note: Developer can also generate Self Signed certificate for development and testing purpose.

Certificate Generation

Below steps is not required if developer has valid certificate.

Step-1 Generate Self Signed Certificate (Makecert.exe)
Developer can generate certificate for development and testing purpose. Follow below steps to generate Self Signed Certificate
Goto – > “Visual Studio Tool” ->“Visual Studio Command Prompt
Right click “Visual Studio Command Prompt” and select “Run as Administrator” as highlighted below.

Step 2: Use the following command from command prompt. Before running the command don’t forget to replace www.yourserver.com with service URL. It is mandatory to have CN value same as service URL to expose the service on HTTPs

makecert -r -pe -n “CN=www.yourserver.com” -b 01/01/2000 -e 01/01/2036 -eku 1.3.6.1.5.5.7.3.1 -ss my -sr localMachine -sky exchange -sp “Microsoft RSA SChannel Cryptographic Provider” -sy 12

Step 3 After execution of above command execute MMC command from “RUN”. This will open below highlighted window

Step 4 : Click on File -> “Add/Remove Snap-in”

Step 5: Select Certificate -> Click on “Add” button

Step 6: Select Computer Account -> Click on “Next” button on next screen

Step 7: Click on “Finish” -> “Ok” button on next screen. You should be able to view the  certificate.

Note: It is recommended to NOT to use Self Signed certificate in production environment.

Export Private Key

Once certificate is generated, we need to export the Private key. Private Key required to upload on Windows Azure along with service package and configuration file.

1.Right click on your certificate and navigate to “All Task”->”Export”.

2.Click on Button “Next

3.Select “Yes, Export the private Key“ option and click on “Next” Button as sown below

4.Click on “Next” Button as shown below.

5.Type the Password and Confirm Password (example: sonata) and click on Next Button

6. Brows the location to save the private key on next screen

   Configure Web service on Secure Channel (HTTPs)

1.  Web Role Configuration

Assuming that user has Private key configured in certificate store at development m/c Open the Service solution in Visual Studio and right click on Web Role and select property

Previous steps will open property windows having following highlighted Tab.

Click on “Certificates” Tab, -> Click on “Add Certificates”. This step will display the below screen

Click on button at “Thumbprint” column to brows the certificate from certificate store, select your certificate and click on Ok button.

Now switch to “Endpoints” tab and make the below highlighted configuration and select SSL Certificate from dropdown. It is the same certificate created in previous step.

Now switch to “Configuration” tab and make the below highlighted configuration

Build the project and launch the service, It should be launched on HTTPs protocol.

Web.Config Configuration

Apart from above changes, few more changes to be made on service Web.config file to complete the configuration.
i.  Add the following property to ServiceMetaData Tag as highlighted <serviceMetadata httpsGetEnabled=”true” httpGetEnabled=”true”/>

Make the web config changes as highlighted  below

<?xml version=”1.0″?>
<configuration><system.diagnostics>
<trace>
<listeners>
<add type=”Microsoft.WindowsAzure.Diagnostics.DiagnosticMonitorTraceListener, Microsoft.WindowsAzure.Diagnostics, Version=1.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35″ name=”AzureDiagnostics”>
<filter type=”” />
</add>
</listeners>
</trace>
</system.diagnostics>
<system.web>
<compilation debug=”true” targetFramework=”4.0″>
<assemblies>
<add assembly=”Microsoft.IdentityModel, Version=3.5.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35″ />
</assemblies>
</compilation>
<customErrors mode=”Off” />
</system.web>
<system.serviceModel>
<bindings>
<basicHttpBinding>
<!–secure wcf by TransportWithMessageCredential security–>
<binding name=”binding1″>
<security mode=”TransportWithMessageCredential”>
<message clientCredentialType=”UserName” />
</security>
</binding>
</basicHttpBinding>
</bindings>
<services>
<service name=”AzureZoneWebRole.TimeSheetService” behaviorConfiguration=”sb1″>
<endpoint address=”” binding=”basicHttpBinding” contract=”AzureZone.TimeSheetContract.ISeemlessOfflineContract” bindingConfiguration=”binding1″ />
<endpoint address=”mex” binding=”mexHttpBinding” contract=”IMetadataExchange” />
</service>
<service name=”AzureZoneWebRole.AuthenticationService” behaviorConfiguration=”sb1″>
<endpoint address=”” binding=”basicHttpBinding” contract=”AzureZone.AuthContract.IAuthenticationService” bindingConfiguration=”binding1″ />
<endpoint address=”mex” binding=”mexHttpBinding” contract=”IMetadataExchange” />
</service>
</services>
<behaviors>
<serviceBehaviors>
<behavior name=”sb1″>
<serviceCredentials>
<userNameAuthentication userNamePasswordValidationMode=”Custom” customUserNamePasswordValidatorType=”AzureZoneWebRole.MyCustomUsernamePasswordValidator,AzureZoneWebRole” />
</serviceCredentials>
<!– To avoid disclosing metadata information, set the value below to false and remove the metadata endpoint above before deployment –>
<serviceMetadata httpsGetEnabled=”true” httpGetEnabled=”true”/>
<!– To receive exception details in faults for debugging purposes, set the value below to true.  Set to false before deployment to avoid disclosing exception information –>
<serviceDebug includeExceptionDetailInFaults=”false”/>
</behavior>
<behavior name=””>
<serviceCredentials>
<serviceCertificate storeLocation=”LocalMachine” storeName=”My” x509FindType=”FindByThumbprint” findValue=”482C7073ECFD9B90385318C7566A441C4CFB2F8C” />
</serviceCredentials>
</behavior>
<behavior name=”ServiceBehavior”>
<!– To avoid disclosing metadata information, set the value below to false and remove the metadata endpoint above before deployment –>
<serviceMetadata httpsGetEnabled=”true” httpGetEnabled=”true”/>
<!– To receive exception details in faults for debugging purposes, set the value below to true.  Set to false before deployment to avoid disclosing exception information –>
<serviceDebug includeExceptionDetailInFaults=”true”/>
</behavior>
</serviceBehaviors>
</behaviors>
<serviceHostingEnvironment multipleSiteBindingsEnabled=”true” />
</system.serviceModel>
<system.webServer>
<modules runAllManagedModulesForAllRequests=”true” />
</system.webServer>
<system.net>
<defaultProxy useDefaultCredentials=”true”>
</defaultProxy>
</system.net>
</configuration>

Build the project and launch the service, It should be launched on HTTPs protocol. Package the Service and Upload to Windows Azure with following

  •   Service Package
  •   Service Configuration
  • Certificate Private Key

 Configure Client on Secure Channel (HTTPs)

Once the Service reference is added of above service following code change is required at client-
Client Credential need to be passed on Proxy.
Sample code:  AzureZoneContractClient proxy = new AzureZoneContractClient();
              if (proxy.ClientCredentials.UserName.UserName == null)
               {
                   proxy.ClientCredentials.UserName.UserName = CommonFunction.UserID;
               } 

Windows and Web Client: 

During the development and testing self sign certificate are used, which is not recognized by standard CA and application throws error.  To suppress the error following modification to made to client side code.

Note: This steps is not required, If Service is configured with valid SSL certificate.

a)     Add following class to client solution

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Net;
using System.Net.Security;
using System.Security.Cryptography.X509Certificates;
public static class CertificateUtils
{
        /// <summary>
        /// Sets the cert policy.
        /// </summary>
        public static void SetCertificatePolicy()
        {
            ServicePointManager.ServerCertificateValidationCallback
            += RemoteCertificateValidate;
        }
        /// <summary>
        /// Remotes the certificate validate.
        /// </summary>
        private static bool RemoteCertificateValidate(
        object sender, X509Certificate cert,
        X509Chain chain, SslPolicyErrors error)
        {
            // trust any certificate!!!
           // System.Console.WriteLine(“Warning, trust any certificate”);
            return true;
        }
    }

a)     Add the following code only once before making service call. This would suppress the certificate error.

CertificateUtils.SetCertificatePolicy();