Hands-On Lab

Introduction to the Windows Azure AppFabric Service Bus Futures

Lab version: 1.0.0

Last updated: 4/5/2011


Contents

Overview 3

Getting Started: Creating a Service Bus Namespace 5

Task 1 – Provisioning the Service Bus Namespace 5

Exercise 1: Service Bus Management Operations 9

Task 1 – Adding Operations to Create, List and Delete Connection Points 9

Task 2 – Setting Account Information 12

Verification 13

Exercise 2: Service Bus Load Balancing 16

Task 1 – Creating the Service 16

Task 2 – Creating the Client 19

Task 3 – Setting Account Information 23

Verification 23

Exercise 3: Durable Message Buffers 29

Task 1 – Implementing Basic Operations with Message Buffers 29

Task 2 – Setting Account Information 34

Verification 34

Summary 41


Overview

The Windows Azure AppFabric Service Bus provides secure messaging and connectivity capabilities for building distributed and disconnected applications in the cloud. In this lab, learn about the new Windows Azure AppFabric Service Bus capabilities that are now available in the AppFabric LABS. You will use the management service to manage your connection points and the Anycast feature to load balance across different instances of a service. Use Message Buffers for basic asynchronous message processing. These capabilities are part of the incremental updates available as part of new Service Bus Futures.

Objectives

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

· Provision an AppFabric project and create a service namespace.

· Use the Windows Azure AppFabric Service Bus management service to manage connection points.

· Use the Anycast feature to load balance across different instances of a service.

· Use Durable Message Buffers for asynchronous message processing.

Prerequisites

You must have the following items to complete this lab:

· Microsoft Visual Studio 2010

· Microsoft.NET Framework 4

· Windows Azure platform AppFabric SDK V2.0

Setup

For convenience, much of the code used in this hands-on lab is available as Visual Studio code snippets. To check the prerequisites of the lab and install the code snippets:

1. Open a Windows Explorer window and browse to the lab’s Source\Setup folder.

2. Double-click the Dependencies.dep file in this folder to launch the Dependency Checker tool and install any missing prerequisites and the Visual Studio code snippets.

3. If the User Account Control dialog is shown, confirm the action to proceed.

Note: This process may require elevation. The .dep extension is associated with the Dependency Checker tool during its installation. For additional information about the setup procedure and how to install the Dependency Checker tool, refer to the Setup.docx document in the Assets folder of the training kit.

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 Setup.docx document in the Assets folder of the training kit, which contains a section describing how to use them.

Exercises

This hands-on Lab includes the following exercises:

1. Service Bus Management Operations

2. Service Bus Load Balancing

3. Durable Message Buffers

Estimated time to complete this lab: 45 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: Creating a Service Bus Namespace

To follow this lab and complete all the exercises you first need to create an AppFabric Service Bus Namespace. Once you have created, it can be used for all of the AppFabric labs and for your own projects as well.

Task 1 – Provisioning the Service Bus Namespace

In this task, you create a new project and create a service namespace to use the Windows Azure AppFabric Service Bus.

1. Navigate to the Windows Azure platform portal. You will be prompted for your Windows Live ID credentials if you are not already signed in.

2. Click Service Bus, Access Control & Caching link in the left pane, and then select “Service Bus” item under AppFabric element.

Figure 1

Configuring AppFabric Service bus

3. Add a Service Namespace. A service namespace provides an application boundary for each application exposed through the Service Bus and is used to construct Service Bus endpoints for the application. To add a service namespace, click New Namespace button on the upper ribbon bar.

Figure 2

Creating a New Namespace

4. Choose the Subscription, enter a name for your Service Namespace, select a Region for your service to run in, select a Connection Pack Size and click the OK button. Make sure to validate the availability of the name first. Service names must be globally unique as they are hosted in the cloud and accessible by whomever you decide to grant access.

Figure 3

Creating a new Service Namespace

Please be patient while your service is activated. It can take a few minutes while it is provisioned.

Note: You may have to refresh the browser to show the service is active.

5. 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 Service Bus services

6. Once the namespace is active, click its name in the list of available namespaces to display the Service Namespace information page.

Figure 5

Summary page listing available service namespaces

7. In the Properties right pane, locate the Service Bus section and click the Default Issuer View button.

Figure 6

Summary page listing available service namespaces

8. Record the value shown for Default Issuer and Default Key, and click OK. You will need these values later on to authenticate using the Access Control.

Figure 7

Service Bus default keys

Exercise 1: Service Bus Management Operations

In this exercise, you will learn how to use the Windows Azure AppFabric Service Bus management service to manage Connection Points. You will create a console application, leveraging the Service Bus management service, which will enable you to create, enumerate, and delete Connection Points.

Figure 8

Service namespace Service Bus settings

Task 1 – Adding Operations to Create, List and Delete Connection Points

In this task, you will create a console application and add the necessary code to enable the Service Bus management operations that list, add or delete a connection point.

1. Open Microsoft Visual Studio 2010.

2. Open the ServiceBusManagementOperations.sln solution located in the Source\Ex1-ManagementOperations\Begin\CS folder of this lab.

3. Add a reference to the Microsoft.ServiceBus.Channels assembly. To do this, right click on the ServiceBusManagementOperations project and select Add Reference.

Note: If you cannot find the Microsoft.ServiceBus.Channels assembly in the .NET tab, use the Browse tab to locate this assembly inside the %ProgramFiles%\Windows Azure AppFabric SDK\V2.0\Assemblies\ folder.

4. Open the Program.cs file.

5. Add the following using statements at the top of the file.

(Code Snippet – IntroServiceBusFutures - Ex01 Using Statements - CS)

C#

using System.ServiceModel.Syndication;

using System.Xml;

using Microsoft.ServiceBus;

using Microsoft.ServiceBus.Samples;

6. Add the highlighted code, from the following fragment, to the Main method. This code will create the URI used by all connection points management operations, based on the service namespace specified in the configuration.

(Code Snippet – IntroServiceBusFutures - Ex01 CreateManagementGatewayURI - CS)

C#

static void Main(string[] args)

{

// read account info from config

serviceNamespace = ConfigurationManager.AppSettings["ServiceNamespace"];

issuerName = ConfigurationManager.AppSettings["IssuerName"];

issuerSecret = ConfigurationManager.AppSettings["IssuerSecret"];

// Create the URI of the Connection Points Management Gateway

string connectionPointsManagementGateway = string.Format("https://{0}-mgmt.{1}/Resources/ConnectionPoints", serviceNamespace, ServiceBusEnvironment.DefaultServiceHostName);

managementUri = new Uri(connectionPointsManagementGateway);

...

}

7. Replace the body of the DeleteConnectionPoint with the code highlighted in the following snippet. This code first creates the runtime service bus URI where the connection point is located. Afterwards, the runtime service bus URI and the account credential information is used to invoke the DeleteConnectionPoint method, which effectively deletes the connection point.

(Code Snippet – IntroServiceBusFutures - Ex01 DeleteConnectionPoint - CS)

C#

private static void DeleteConnectionPoint(string connectionPointsManagementGateway, string connectionPointName)

{

// create the service URI based on the service namespace

Uri runtimeUri = ServiceBusEnvironment.CreateServiceUri("sb", serviceNamespace, connectionPointName);

Console.WriteLine("Attempting to delete a Connection Point at {0} ...", runtimeUri);

// delete the connection point

ConnectionPointOperations.DeleteConnectionPoint(connectionPointName, runtimeUri, managementUri, serviceNamespace, issuerName, issuerSecret);

}

8. Use the following highlighted code in the ListConnectionPoints method to display all the existing connection points.

(Code Snippet – IntroServiceBusFutures - Ex01 ListConnectionPoints - CS)

C#

private static void ListConnectionPoints()

{

// create web request

WebClient webClient = new WebClient();

webClient.BaseAddress = managementUri.AbsoluteUri;

ACSTokenHelper.AddTokenHeaderToWebClient(webClient, serviceNamespace, issuerName, issuerSecret);

string response = webClient.DownloadString(managementUri);

SyndicationFeed feed = SyndicationFeed.Load(XmlReader.Create(new StringReader(response)));

// Print feeds

foreach (SyndicationItem item in feed.Items)

{

ConnectionPoint connectionPoint = ((XmlSyndicationContent)item.Content).ReadContent<ConnectionPoint>();

Console.WriteLine("Id = {0}\r\nTitle = {1}\r\nMax Listeners = {2}\r\nChannel Shape = {3}\r\n", item.Id, item.Title.Text, connectionPoint.MaxListeners, connectionPoint.ChannelShape);

}

}

9. Update the CreateConnectionPoint method with the following code.

(Code Snippet – IntroServiceBusFutures - Ex01 CreateConnectionPoint - CS)

C#

private static void CreateConnectionPoint(string connectionPointName, string maxListeners)

{

// Create the Service Endpoint URI based on the service namespace

Uri runtimeUri = ServiceBusEnvironment.CreateServiceUri("sb", serviceNamespace, connectionPointName);

Console.WriteLine("Attempting to create a Connection Point for {0} ...", runtimeUri);

// Create the connection point

ConnectionPoint connectionPoint = new ConnectionPoint(int.Parse(maxListeners), ChannelShape.Duplex);

ConnectionPointOperations.CreateConnectionPoint(connectionPointName, runtimeUri, managementUri, serviceNamespace, issuerName, issuerSecret, connectionPoint);

}

10. In Visual Studio, save all files.

Task 2 – Setting Account Information

1. Open the app.config file.

2. In the appSettings section, locate the ServiceNamespace setting and replace [YOUR-SERVICE-NAMESPACE-DOMAIN] with the domain service namespace that you registered at the portal.

3. Next, locate the IssuerName and IssuerSecret settings and replace [YOUR-ISSUER-NAME] and [YOUR-ISSUER-KEY] with the Default Issuer Name and Default Issuer Key for the service namespace; these are the name and key generated for the service namespace at the portal Web Site that you recorded during the Getting Started section. The figure below shows a sample app.config file after replacing the value of these settings.

Figure 9

App.config file after replacing the keys with your information

4. In Visual Studio, save all files.

Verification

In order to verify that you have performed every step in the exercise correctly, proceed as follows:

1. Press F5 to run the application. The console window appears and displays the different management options.

Figure 10

Management options

2. Type 1 and press ENTER to create a new connection point.

3. Name the connection point TestConnectionPoint and set the maximum number of listeners to 5. The program output is shown in the following figure.

Note: The Maximum Number of Listeners defines how many services can listen on a particular endpoint.

Figure 11

Output when creating a new connection point

4. Type 2 and press ENTER to list all connection points. As shown in the following figure, the previously created connection point should be listed.

Figure 12

Connection Points listing

5. Type 3 and press ENTER to delete a connection point.

6. Type TestConnectionPoint and press ENTER to delete the previously created connection point.

Figure 13

Deleting the TestConnectionPoint

7. Type 2 and press ENTER to list all connection points. Verify that no connection points are now listed, as shown in the following figure.

Figure 14

No connection points are listed

8. Close the console application.

Exercise 2: Service Bus Load Balancing

This exercise shows the usage of the Anycast feature to communicate between clients and different instances of an inventory service. This feature allows a service provider to programmatically subscribe a number of listeners to a Service Bus connection point and when a message is sent to that connection point, the Service Bus will randomly choose one listener to deliver this message. This allows the developer to balance the load normally handled by a single instance of a listener among several instances of that listener and provide a lightweight failover feature.

Task 1 – Creating the Service

In this task, you will create a service that implements a simple inventory service contract that contains methods for listing items in stock, as well as creating and selling items. The service creates a connection point for the InventoryService and then hosts the service itself.

1. Open Microsoft Visual Studio 2010.

2. Open the LoadBalancing.sln solution located in the Source\Ex2-LoadBalancing\Begin\CS folder of this lab.

3. In the Service project, add a reference to the Microsoft.ServiceBus.Channels assembly. To do this, right click on the ServiceBusManagementOperations project and select Add Reference.

Note: If you cannot find the Microsoft.ServiceBus.Channels assembly in the .NET tab, use the Browse tab to locate this assembly in the %ProgramFiles%\Windows Azure AppFabric SDK\V2.0\Assemblies\ folder.

4. In the Service project, open the Program.cs file.

5. Add the following highlighted namespace directives at the top of the file.

(Code Snippet – IntroServiceBusFutures - Ex02 ServiceUsingStatements - CS)

C#

using System;

using System.Configuration;

using System.IO;

using System.Net;
using System.ServiceModel;

using System.ServiceModel.Channels;

using System.ServiceModel.Description;

using Microsoft.ServiceBus;

using Microsoft.ServiceBus.Channels;

6. In the Main method, add the following highlighted code to create management and service endpoint URIs for the Connection Point.

(Code Snippet – IntroServiceBusFutures - Ex02 CreateManagementGatewayURI - CS)

C#

static void Main(string[] args)

{

Console.Title = "Service " + ServiceId;

// handle console closeing to close service connection

ConsoleCloseHandler.CloseHandler = CloseServiceConnection;

// read account info from config

serviceNamespace = ConfigurationManager.AppSettings["ServiceNamespace"];

issuerName = ConfigurationManager.AppSettings["IssuerName"];

issuerSecret = ConfigurationManager.AppSettings["IssuerSecret"];

try

{

// Create the URI of the Connection Points Management Gateway

string connectionPointsManagementGateway = string.Format("https://{0}-mgmt.{1}/Resources/ConnectionPoints", serviceNamespace, ServiceBusEnvironment.DefaultServiceHostName);

Uri managementUri = new Uri(connectionPointsManagementGateway);

// Create the URI of the Service Endpoint

Uri runtimeUri = ServiceBusEnvironment.CreateServiceUri("sb", serviceNamespace, "InventoryService");

...

7. Use the following highlighted code to call the RetrieveConnectionPoint method, which uses the management operations discussed in the previous exercise to retrieve the InventoryService connection point (and creates it in case it does not exist).

(Code Snippet – IntroServiceBusFutures - Ex02 RetrieveConnectionPoint - CS)

C#

// Create the URI of the Service Endpoint

Uri runtimeUri = ServiceBusEnvironment.CreateServiceUri("sb", serviceNamespace, "InventoryService");

// Determine whether or not a Connection Point exists for this Service Endpoint and create it if neccesary

RetrieveConnectionPoint(managementUri, runtimeUri);

8. Use the following highlighted code to create WCF custom client binding based on the TcpServiceBusTransportBindingElement, which will enable the Service Bus' Anycast feature.

(Code Snippet – IntroServiceBusFutures - Ex02 CreateBinding - CS)

C#

// Determine whether or not a Connection Point exists for this Service Endpoint and create it if neccesary

RetrieveConnectionPoint(managementUri, runtimeUri);

// Start the Service

// Create custom binding based on the TcpServiceBusTransportBindingElement

var binding = new TcpServiceBusTransportBindingElement();

CustomBinding sdkClientBinding = new CustomBinding(binding);