87
Hands-On Lab Part 1: Introduction to the AppFabric Service Bus Lab version: 2.0.0 Last updated: 4/14/2022 Page 1

Part 1: Introduction to the AppFabric Service Busbandgap.cs.rice.edu/classes/comp410/resources/Using Azure... · Web viewThis lab covers the basics of the AppFabric Service Bus. It

  • Upload
    others

  • View
    2

  • Download
    0

Embed Size (px)

Citation preview

Page 1: Part 1: Introduction to the AppFabric Service Busbandgap.cs.rice.edu/classes/comp410/resources/Using Azure... · Web viewThis lab covers the basics of the AppFabric Service Bus. It

Hands-On LabPart 1: Introduction to the AppFabric Service Bus

Lab version: 2.0.0

Last updated: 5/18/2023

Page 1

Page 2: Part 1: Introduction to the AppFabric Service Busbandgap.cs.rice.edu/classes/comp410/resources/Using Azure... · Web viewThis lab covers the basics of the AppFabric Service Bus. It

CONTENTS

OVERVIEW................................................................................................................................................. 3

GETTING STARTED: CREATING A SERVICE PROJECT........................................................................8Task 1 – Creating your AppFabric Project............................................................................................8

EXERCISE 1: GETTING A BASIC CLIENT AND SERVICE WORKING..................................................13Task 1 – Creating the WCF Service Project and Service Contracts.....................................................14

Task 2 – Hosting the WCF Service through the AppFabric Service Bus..............................................24

Task 3 – Configuring the WCF Service................................................................................................31

Task 4 – Creating the WCF Client Project...........................................................................................31

Task 5 – Consuming the WCF Service Hosted through the App Fabric Service Bus...........................36

Verification........................................................................................................................................40

EXERCISE 2: CONNECTING A WCF SERVICE IN IIS 7.5 TO THE SERVICE BUS...............................44Task 1 – Creating a Virtual Directory for the application...................................................................44

Task 2 – Configuring the WCF Service to be discoverable.................................................................47

Task 3 – Enabling Windows Server App Fabric Auto-Start for the WCF Calculator Service................52

Verification........................................................................................................................................60

EXERCISE 3: MULTICAST MESSAGING THROUGH THE SERVICE BUS...........................................64Task 1 – Building the Internet Relay Chat Application.......................................................................65

Task 2 – Chatting through the AppFabric Service Bus........................................................................69

Task 3 – Adding Message Protection.................................................................................................72

SUMMARY................................................................................................................................................ 75

Page 2

Page 3: Part 1: Introduction to the AppFabric Service Busbandgap.cs.rice.edu/classes/comp410/resources/Using Azure... · Web viewThis lab covers the basics of the AppFabric Service Bus. It

Overview

A common problem when developing connected, peer-to-peer applications is to enable connections with applications through network devices like firewalls and network address translators (NATs).

Network devices like these typically allow applications to initiate outbound network connections but prevent them from accepting inbound network connections.

To establish a connection through these types of network devices, application developers often end up writing custom logic that deals with establishing connections across network topologies. Because there are many different types of network topologies, this logic often becomes very complex.

The AppFabric Service Bus provides the communication infrastructure that protects developers from having to create the complex code necessary to achieve seamless connectivity. It allows you to expose a service to the Internet from behind your firewall or NAT. Several common application messaging patterns are supported allowing bi-directional, peer-to-peer communication, publish, subscribe and storing and forwarding of messages.

Facts

The Service Bus is built on Windows Communication Foundation (WCF) and uses standard Internet protocols.

The service is cloud-based. The technical aim of the Service Bus is to simplify connectivity between services and clients, even if those servers and clients exist behind different firewalls and NAT routers.

Building applications using the Service Bus does not require a significant footprint within an organization and leads to more rapid deployments while keeping the local infrastructure intact.

As a set of hosted integration technologies, the Service Bus reduces the cost involved in building, acquiring, and maintaining systems that might have to be built to do the same things.

Objectives

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

Expose and consume a service through the Service Bus.

Implement the Multicast message pattern through the Service Bus.

Use X.509 certificates for message confidentiality.

Connect a WCF Service in IIS 7.5 to the Service Bus to enable service automatic activation.

Page 3

Page 4: Part 1: Introduction to the AppFabric Service Busbandgap.cs.rice.edu/classes/comp410/resources/Using Azure... · Web viewThis lab covers the basics of the AppFabric Service Bus. It

Prerequisites

You must have the following items to complete this lab:

Microsoft Visual Studio 2010

Microsoft.NET Framework 4

Windows Azure platform AppFabric SDK V1.0

Microsoft Internet Information Services 7.5

IIS Manager for Remote Administration

Windows Server AppFabric

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.

Page 4

Page 5: Part 1: Introduction to the AppFabric Service Busbandgap.cs.rice.edu/classes/comp410/resources/Using Azure... · Web viewThis lab covers the basics of the AppFabric Service Bus. It

Using the Code Snippets

With code snippets, you have all the code you need at your fingertips. The lab document will tell you exactly when you can use them, as shown in the following figure.

Figure 1Using Visual Studio code snippets to insert code into your project

To add a code snippet using the keyboard (C# only)

1. Place the cursor where you would like to insert the code.

2. Start typing the snippet name (without spaces or hyphens).

3. Watch as IntelliSense displays matching snippets' names.

4. Select the correct snippet (or keep typing until the entire snippet's name is selected).

5. Press the Tab key twice to insert the snippet at the cursor location.

Figure 2Start typing the snippet name

Page 5

Page 6: Part 1: Introduction to the AppFabric Service Busbandgap.cs.rice.edu/classes/comp410/resources/Using Azure... · Web viewThis lab covers the basics of the AppFabric Service Bus. It

Figure 3Press Tab to select the highlighted snippet

Figure 4Press Tab again and the snippet will expand

To add a code snippet using the mouse (C#, Visual Basic and XML)

1. Right-click where you want to insert the code snippet.

2. Select Insert Snippet followed by My Code Snippets.

3. Pick the relevant snippet from the list, by clicking on it.

Figure 5Right-click where you want to insert the code snippet and select Insert Snippet

Page 6

Page 7: Part 1: Introduction to the AppFabric Service Busbandgap.cs.rice.edu/classes/comp410/resources/Using Azure... · Web viewThis lab covers the basics of the AppFabric Service Bus. It

Figure 6Pick the relevant snippet from the list, by clicking on it

Exercises

This hands-on Lab includes the following exercises:

1. Getting a Basic Client and Service Working

2. Connecting a WCF Service in IIS 7.5 to the Service Bus

3. Multicast Messaging through the Service Bus

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.

Page 7

Page 8: Part 1: Introduction to the AppFabric Service Busbandgap.cs.rice.edu/classes/comp410/resources/Using Azure... · Web viewThis lab covers the basics of the AppFabric Service Bus. It

Getting Started: Creating a Service Project

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

Task 1 – Creating your AppFabric Project

In this task, you will create a new AppFabric project.

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

2. Create a new project. Type a Project Name, such as your company name or your name, accept the Terms of Use and click the OK button.

Figure 7Creating a new Azure AppFabric project

Page 8

Page 9: Part 1: Introduction to the AppFabric Service Busbandgap.cs.rice.edu/classes/comp410/resources/Using Azure... · Web viewThis lab covers the basics of the AppFabric Service Bus. It

3. Add a service namespace to your project. 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 the Project Name link for your new project to view its information page and then click Add Service Namespace.

Figure 8AppFabric project information page

4. Enter a name for your Service Namespace, select a Region for your service to run in, and click the Create 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.

Page 9

Page 10: Part 1: Introduction to the AppFabric Service Busbandgap.cs.rice.edu/classes/comp410/resources/Using Azure... · Web viewThis lab covers the basics of the AppFabric Service Bus. It

Figure 9Creating 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. Once the namespace is active, click its name in the list of available namespaces to display the Service Namespace information page.

Page 10

Page 11: Part 1: Introduction to the AppFabric Service Busbandgap.cs.rice.edu/classes/comp410/resources/Using Azure... · Web viewThis lab covers the basics of the AppFabric Service Bus. It

Figure 10Project summary page listing available service namespaces

6. In the Service Namespace information page, locate the Service Bus section and record the value shown for Default Issuer Name and Default Issuer Key. You will need these values later on to authenticate using the Access Control.

Page 11

Page 12: Part 1: Introduction to the AppFabric Service Busbandgap.cs.rice.edu/classes/comp410/resources/Using Azure... · Web viewThis lab covers the basics of the AppFabric Service Bus. It

Figure 11Service namespace information page

You have now created a new AppFabric project and defined a namespace for this hands-on lab. To sign in at any time, simply navigate to the Windows Azure platform AppFabric portal, click Sign In and provide your Live ID credentials. Clicking the AppFabric tab on the left will list the projects associated with your account.

Page 12

Page 13: Part 1: Introduction to the AppFabric Service Busbandgap.cs.rice.edu/classes/comp410/resources/Using Azure... · Web viewThis lab covers the basics of the AppFabric Service Bus. It

Figure 12My Projects page showing available AppFabric projects

Exercise 1: Getting a Basic Client and Service Working

In this exercise, you learn how to expose and consume a simple WCF service through the Service Bus.

The Service Bus simplifies many of the communication challenges by providing a universal naming convention for services along with a mechanism for direct/indirect communication between two nodes independent of network topology and configuration.

The Service Bus allows a Windows Communication Foundation-based (WCF) application to listen to a public network address, even if the application is located behind a NAT or network firewall. This functionality can be used to help applications communicate with each other, regardless of network specific structure. Through the use of the Service Bus as an intermediary you can interconnect different applications without the need to write and maintain complex logic and code to traverse networks.

Another core part of the solution is the AppFabric Access Control, a publicly accessible identity and authentication management service. Access Control (AC) is a service designed to secure REST web services allowing them to integrate with both simple clients and enterprise identity technologies using a single code base. Access Control is also used to secure the Service Bus endpoints. To accomplish this task, AC receives an issuer name and an issuer secret (32-bit key). If they are correctly authenticated, it issues a security token (called Simple Web Token) that is then trusted by the service itself. All messages sent to and via the Service Bus must contain a valid security token.

Page 13

Page 14: Part 1: Introduction to the AppFabric Service Busbandgap.cs.rice.edu/classes/comp410/resources/Using Azure... · Web viewThis lab covers the basics of the AppFabric Service Bus. It

Figure 13Service Bus message flow in relayed mode

This exercise will expose several Service Bus features such as:

Access Control authentication methods

Communication between client and service across the Service Bus

Note: To verify that each step is performed correctly, it is recommended to build the solution at the end of each task.

Task 1 – Creating the WCF Service Project and Service Contracts

In this task, you create a WCF Service project that is then hosted and exposed through the Service Bus.

1. Open Microsoft Visual Studio 2010 from Start | All Programs | Microsoft Visual Studio 2010 | Microsoft Visual Studio 2010.

2. In the File menu, point to New, and then click Project.

3. In the New Project dialog, expand the language of your preference (Visual C# or Visual Basic) in the installed templates list and select Windows. Make sure that .NET Framework 4 is selected as the target framework and choose the Console Application template. Set the project name to

Page 14

Page 15: Part 1: Introduction to the AppFabric Service Busbandgap.cs.rice.edu/classes/comp410/resources/Using Azure... · Web viewThis lab covers the basics of the AppFabric Service Bus. It

Service, the solution name to BasicSample and the location to Ex01-BasicSample\begin in the Source folder of this lab. Click OK to create the application project.

Figure 14Creating a new project (C#)

Page 15

Page 16: Part 1: Introduction to the AppFabric Service Busbandgap.cs.rice.edu/classes/comp410/resources/Using Azure... · Web viewThis lab covers the basics of the AppFabric Service Bus. It

Figure 15Creating a new project (Visual Basic)

4. Change the Target Framework to .NET Framework 4 to allow the Service Bus interaction. To do this, in Solution Explorer, right-click the Service project and select Properties.

For Visual C# projects: In the Properties window, select the Application tab and choose .NET Framework 4 in the Target Framework option. If prompted to confirm the target framework change, click Yes to proceed.

For Visual Basic projects: In the Properties window, select the Compile tab, click Advance Compile Options, choose .NET Framework 4 in the Target Framework option, and click OK. If prompted to confirm the target framework change, click Yes to proceed.

Page 16

Page 17: Part 1: Introduction to the AppFabric Service Busbandgap.cs.rice.edu/classes/comp410/resources/Using Azure... · Web viewThis lab covers the basics of the AppFabric Service Bus. It

Figure 16Choosing the target framework for C# projects

Page 17

Page 18: Part 1: Introduction to the AppFabric Service Busbandgap.cs.rice.edu/classes/comp410/resources/Using Azure... · Web viewThis lab covers the basics of the AppFabric Service Bus. It

Figure 17Choosing the target framework for Visual Basic projects

5. Add a reference to the System.ServiceModel.dll assembly. To do this, in Solution Explorer, right-click the Service project and select Add Reference. In the Add Reference dialog box, select the .NET tab and choose the System.ServiceModel assembly. Click OK to add the reference.

Note: The Service Bus is built on Windows Communication Foundation; System.ServiceModel.dll is one of WCF's core assemblies.

6. Now, add a reference to the Service Bus core assembly. Again, right-click the Service project in Solution Explorer, select Add Reference to open the Add Reference dialog, select the .NET tab, choose Microsoft.ServiceBus.dll and click OK.

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

Page 18

Page 19: Part 1: Introduction to the AppFabric Service Busbandgap.cs.rice.edu/classes/comp410/resources/Using Azure... · Web viewThis lab covers the basics of the AppFabric Service Bus. It

7. Create the WCF service contract. In Solution Explorer, right-click the Service project, point to Add and select New Item. In the Add New Item dialog, choose the Code category and select the Interface template. Change the Name to IEchoContract.cs (for Visual C# projects) or IEchoContract.vb (for Visual Basic projects) and click Add to create the interface.

Figure 18Creating the IEchoContract interface (C#)

Figure 19

Page 19

Page 20: Part 1: Introduction to the AppFabric Service Busbandgap.cs.rice.edu/classes/comp410/resources/Using Azure... · Web viewThis lab covers the basics of the AppFabric Service Bus. It

Creating the IEchoContract interface (Visual Basic)

8. At the top of the IEchoContract.cs file (for Visual C# projects) or the IEchoContract.vb file (for Visual Basic projects), add the following namespace directive.

C#

using System.ServiceModel;

Visual Basic

Imports System.ServiceModel

9. Make the interface public and apply the ServiceContract attribute to the IEchoContract interface to indicate that the interface defines a service contract in the WCF application. To do this, replace the current interface definition with the following code.

Note: In Visual Basic, the template for a new interface already declares the interface as Public.

(Code Snippet - Introduction to Service Bus Lab Part 1 - Ex01 Echo Contract - CS)

C#

[ServiceContract(Name = "EchoContract", Namespace = "http://samples.microsoft.com/ServiceModel/Relay/")]public interface IEchoContract{}

(Code Snippet - Introduction to Service Bus Lab Part 1 - Ex01 Echo Contract - VB)

Visual Basic

<ServiceContract(Name:="EchoContract", Namespace:="http://samples.microsoft.com/ServiceModel/Relay/")> _Public Interface IEchoContractEnd Interface

10. Declare the Echo operation contract to indicate that the method defines an operation that is part of a service contract. To do this, paste the following code inside the interface definition.

(Code Snippet - Introduction to Service Bus Lab Part 1 - Ex01 Echo Operation Contract - CS)

C#

Page 20

Page 21: Part 1: Introduction to the AppFabric Service Busbandgap.cs.rice.edu/classes/comp410/resources/Using Azure... · Web viewThis lab covers the basics of the AppFabric Service Bus. It

public interface IEchoContract{ [OperationContract] string Echo(string text);}

(Code Snippet - Introduction to Service Bus Lab Part 1 - Ex01 Echo Operation Contract - VB)

Visual Basic

Public Interface IEchoContract <OperationContract()> _ Function Echo(ByVal text As String) As StringEnd Interface

11. Create the EchoService class to implement the IEchoContract interface. To do this, in Solution Explorer, right-click the Service project, point to Add and select New Item. In the Add New Item dialog box, choose the Class template. Change the Name to EchoService.cs (for Visual C# projects) or EchoService.vb (for Visual Basic projects) and then click Add.

Figure 20Creating the EchoService class (C#)

Page 21

Page 22: Part 1: Introduction to the AppFabric Service Busbandgap.cs.rice.edu/classes/comp410/resources/Using Azure... · Web viewThis lab covers the basics of the AppFabric Service Bus. It

Figure 21Creating the EchoService class (Visual Basic)

12. At the top of the EchoService.cs file, add the following namespace directive.

C#

using System.ServiceModel;

Visual Basic

Imports System.ServiceModel

13. Add an inheritance declaration to make the EchoService class implement the IEchoContract interface and add the public access modifier.

Note: In Visual Basic, the template for a new class already declares the class as Public.

C#

public class EchoService : IEchoContract

Visual Basic

Public Class EchoService Implements IEchoContractEnd Class

Page 22

Page 23: Part 1: Introduction to the AppFabric Service Busbandgap.cs.rice.edu/classes/comp410/resources/Using Azure... · Web viewThis lab covers the basics of the AppFabric Service Bus. It

14. Add a ServiceBehavior attribute to the EchoService class to indicate that the class implements a WCF service. To do this, paste the following code above the class definition.

(Code Snippet - Introduction to Service Bus Lab Part 1 - Ex01 Echo Service Behavior - CS)

C#

[ServiceBehavior(Name = "EchoService", Namespace = "http://samples.microsoft.com/ServiceModel/Relay/")]public class EchoService : IEchoContract{}

(Code Snippet - Introduction to Service Bus Lab Part 1 - Ex01 Echo Service Behavior - VB)

Visual Basic

<ServiceBehavior(Name:="EchoService", Namespace:="http://samples.microsoft.com/ServiceModel/Relay/")> _Public Class EchoService Implements IEchoContract

End Class

15. Implement the Echo method of the IEchoContract interface. To do this, paste the following code inside the class definition.

(Code Snippet - Introduction to Service Bus Lab Part 1 - Ex01 Echo Method - CS)

C#

public class EchoService : IEchoContract{ public string Echo(string text) { Console.WriteLine("Echoing: {0}", text); return text; }}

(Code Snippet - Introduction to Service Bus Lab Part 1 - Ex01 Echo Method - VB)

Visual Basic

Public Class EchoService

Page 23

Page 24: Part 1: Introduction to the AppFabric Service Busbandgap.cs.rice.edu/classes/comp410/resources/Using Azure... · Web viewThis lab covers the basics of the AppFabric Service Bus. It

Implements IEchoContract Public Function Echo(ByVal text As String) As String Implements IEchoContract.Echo Console.WriteLine("Echoing: {0}", text) Return text End FunctionEnd Class

Task 2 – Hosting the WCF Service through the AppFabric Service Bus

In this task, you add code to expose the EchoService service through the Service Bus. The service will then stay listening for incoming messages at a designated URI.

To communicate across the Service Bus, WCF extensibility points have been used to define a new set of bindings available for use with the Service Bus. A WCF binding determines what kind of communication will be exposed or used by a service endpoint. In this lab, you use a binding named NetTcpRelayBinding, which is one of the bindings introduced with the Service Bus. On the service or listener side, the NetTcpRelayBinding enables you to expose an endpoint that is accessible through a global URI supported by the Service Bus. When an endpoint using NetTcpRelayBinding is opened, its URI is registered within the Service Bus and from that moment, any authorized client will be able to send messages to that global URI using a similarly configured client. The Service Bus then becomes the conduit for communication between those two endpoints.

1. Open the Program.cs file (for Visual C# projects) or Module1.vb file (for Visual Basic projects) in the Service project and declare the following namespaces below the existing namespace directives.

(Code Snippet - Introduction to Service Bus Lab Part 1 - Ex01 Namespaces - CS)

C#

using System.ServiceModel;using System.ServiceModel.Description;using Microsoft.ServiceBus;using Microsoft.ServiceBus.Description;

(Code Snippet - Introduction to Service Bus Lab Part 1 - Ex01 Namespaces - VB)

Visual Basic

Imports System.ServiceModelImports System.ServiceModel.DescriptionImports Microsoft.ServiceBusImports Microsoft.ServiceBus.Description

Page 24

Page 25: Part 1: Introduction to the AppFabric Service Busbandgap.cs.rice.edu/classes/comp410/resources/Using Azure... · Web viewThis lab covers the basics of the AppFabric Service Bus. It

2. Next, paste the following code inside the Main method. This will prompt the user to provide a service namespace domain, an issuer name, and an issuer secret.

(Code Snippet - Introduction to Service Bus Lab Part 1 - Ex01 Main Header - CS)

C#

static void Main(string[] args){ Console.Title = "Service"; Console.Write("Your Service Namespace Domain (e.g. sb://<YOUR-NAMESPACE>.servicebus.windows.net/): "); string serviceNamespaceDomain = Console.ReadLine(); Console.Write("Your Issuer Name: "); string issuerName = Console.ReadLine(); Console.Write("Your Issuer Secret: "); string issuerSecret = Console.ReadLine();}

(Code Snippet - Introduction to Service Bus Lab Part 1 - Ex01 Main Header - VB)

Visual Basic

Sub Main() Console.Title = "Service" Console.Write("Your Service Namespace Domain (e.g. sb://<YOUR-NAMESPACE>.servicebus.windows.net/): ") Dim serviceNamespaceDomain As String = Console.ReadLine() Console.Write("Your Issuer Name: ") Dim issuerName As String = Console.ReadLine() Console.Write("Your Issuer Secret: ") Dim issuerSecret As String = Console.ReadLine()End Sub

3. Create the URI for the service based on the service namespace; this is the address where the service will be hosted. To do this, add the following code (shown in bold).

(Code Snippet - Introduction to Service Bus Lab Part 1 - Ex01 Create Uri - CS)

C#

static void Main(string[] args){ // ... // create the service URI based on the service namespace Uri address = ServiceBusEnvironment.CreateServiceUri("sb",

Page 25

Page 26: Part 1: Introduction to the AppFabric Service Busbandgap.cs.rice.edu/classes/comp410/resources/Using Azure... · Web viewThis lab covers the basics of the AppFabric Service Bus. It

serviceNamespaceDomain, "EchoService");}

(Code Snippet - Introduction to Service Bus Lab Part 1 - Ex01 Create Uri - VB)

Visual Basic

Sub Main() ' ...

' create the service URI based on the service namespace Dim address As Uri = ServiceBusEnvironment.CreateServiceUri("sb", serviceNamespaceDomain, "EchoService")End Sub

Note: The URI points to the address where the service will be hosted. The generated URI will have the following format: sb://<serviceNamespace>.servicebus.windows.net/EchoService/

Notice that to create the URI, you are passing "sb" as the scheme, followed by the Service Namespace identity. “EchoService” is being used as part of the URI to host the service.

4. Create a TransportClientEndpointBehavior to specify which type of credentials should be used to authenticate the service with the Service Bus. Specify a CredentialType of type SharedSecret, which relies on the issuer name and issuer key obtained when you signed up for AppFabric in the Getting Started section.

(Code Snippet - Introduction to Service Bus Lab Part 1 - Ex01 Create Credential object for the Endpoint -CS)

C#

static void Main(string[] args){ // ... // create the service URI based on the service namespace Uri address = ServiceBusEnvironment.CreateServiceUri("sb", serviceNamespaceDomain, "EchoService");

// create the credential object for the endpoint TransportClientEndpointBehavior sharedSecretServiceBusCredential = new TransportClientEndpointBehavior(); sharedSecretServiceBusCredential.CredentialType = TransportClientCredentialType.SharedSecret;

Page 26

Page 27: Part 1: Introduction to the AppFabric Service Busbandgap.cs.rice.edu/classes/comp410/resources/Using Azure... · Web viewThis lab covers the basics of the AppFabric Service Bus. It

sharedSecretServiceBusCredential.Credentials.SharedSecret.IssuerName = issuerName; sharedSecretServiceBusCredential.Credentials.SharedSecret.IssuerSecret = issuerSecret;}

(Code Snippet - Introduction to Service Bus Lab Part 1 - Ex01 Create Credential object for the Endpoint -VB)

Visual Basic

Sub Main() ' ...

' create the service URI based on the service namespace Dim address As Uri = ServiceBusEnvironment.CreateServiceUri("sb", serviceNamespaceDomain, "EchoService")

' create the credential object for the endpoint Dim sharedSecretServiceBusCredential As New TransportClientEndpointBehavior() sharedSecretServiceBusCredential.CredentialType = TransportClientCredentialType.SharedSecret sharedSecretServiceBusCredential.Credentials.SharedSecret.IssuerName = issuerName sharedSecretServiceBusCredential.Credentials.SharedSecret.IssuerSecret = issuerSecretEnd Sub

Note: Authentication and authorization are both performed by the AppFabric Access Control. To make these steps simple, the Microsoft.ServiceBus namespace contains a set of transport client credential helpers that automatically handle the acquisition of the required security tokens. The transportClientEndpointBehavior allows you to specify the Credential Type to be used to authenticate the service. In this case, you are using SharedSecret, which relies on the issuer name and issuer key for authentication with the Service Bus.

As well as SharedSecret, there are other credential types:

- SimpleWebToken: The client authenticates with the Service Bus using a SimpleWebToken credential (the SharedSecretCredential.ComputeSimpleWebTokenString(string issuerName, string issuerSecret) method computes the string that is expected by TransportClientEndpointBehavior).

- Unauthenticated: No client credential provided. In the service configuration file, the security configuration for all of the relay bindings contains a relayClientAuthenticationType setting that

Page 27

Page 28: Part 1: Introduction to the AppFabric Service Busbandgap.cs.rice.edu/classes/comp410/resources/Using Azure... · Web viewThis lab covers the basics of the AppFabric Service Bus. It

controls whether or not a client is required to authenticate when accessing the HTTP service. Setting this to “None” means that access is granted to anyone consuming the service. A typical scenario for unauthenticated services is exposing RSS feeds.

5. Create a ServiceHost object to host the EchoService as a WCF Service. Paste the following code below the one inserted previously.

(Code Snippet - Introduction to Service Bus Lab Part 1 - Ex01 Create Service Host - CS)

C#

static void Main(string[] args){ // ... // create the service host reading the configuration ServiceHost host = new ServiceHost(typeof(EchoService), address);}

(Code Snippet - Introduction to Service Bus Lab Part 1 - Ex01 Create Service Host - VB)

Visual Basic

Sub Main() ' ... ' create the service host reading the configuration Dim host As New ServiceHost(GetType(EchoService), address)End Sub

6. To associate a listener endpoint with its Service Bus credentials, you must add a TransportClientEndpointBehavior behavior to the respective endpoint’s behavior collection. If your service exposes multiple endpoints through the relay, you can add the same behavior instance to each endpoint. Paste the following code below the one inserted previously in order to add the behavior for all endpoints.

(Code Snippet - Introduction to Service Bus Lab Part 1 - Ex01 Add Service Bus Credentials to Endpoints - CS)

C#

static void Main(string[] args){ // ...

Page 28

Page 29: Part 1: Introduction to the AppFabric Service Busbandgap.cs.rice.edu/classes/comp410/resources/Using Azure... · Web viewThis lab covers the basics of the AppFabric Service Bus. It

// create the service host reading the configuration ServiceHost host = new ServiceHost(typeof(EchoService), address);

// create the ServiceRegistrySettings behavior for the endpoint IEndpointBehavior serviceRegistrySettings = new ServiceRegistrySettings(DiscoveryType.Public);

// add the Service Bus credentials to all endpoints specified in configuration foreach (ServiceEndpoint endpoint in host.Description.Endpoints) { endpoint.Behaviors.Add(sharedSecretServiceBusCredential); }}

(Code Snippet - Introduction to Service Bus Lab Part 1 - Ex01 Add Service Bus Credentials to Endpoints - VB)

Visual Basic

Sub Main() ' ... ' create the service host reading the configuration Dim host As New ServiceHost(GetType(EchoService), address)

' add the Service Bus credentials to all endpoints specified in configuration For Each endpoint As ServiceEndpoint In host.Description.Endpoints endpoint.Behaviors.Add(sharedSecretServiceBusCredential) Next endpointEnd Sub

7. Add the code to open the host and have it listen at the relay service until the user presses any key. To do this, add the following code to method Main.

(Code Snippet - Introduction to Service Bus Lab Part 1 - Ex01 Open Service Host - CS)

C#

static void Main(string[] args){ // ... // open the service host.Open();

Page 29

Page 30: Part 1: Introduction to the AppFabric Service Busbandgap.cs.rice.edu/classes/comp410/resources/Using Azure... · Web viewThis lab covers the basics of the AppFabric Service Bus. It

Console.WriteLine("Service address: " + address); Console.WriteLine("Press [Enter] to exit"); Console.ReadLine();

// close the service host.Close();}

(Code Snippet - Introduction to Service Bus Lab Part 1 - Ex01 Open Service Host - VB)

Visual Basic

Sub Main() ' ...

' open the service host.Open()

Console.WriteLine("Service address: " & address.ToString()) Console.WriteLine("Press [Enter] to exit") Console.ReadLine()

' close the service host.Close()End Sub

Note: When you call ServiceHost.Open, the NetTcpRelayBinding causes WCF to communicate with the Service Bus in order to authenticate the service identity and to authorize it to listen at the specified URI.

Task 3 – Configuring the WCF Service

In this task, you will configure the WCF Service.

1. In the App.config file, add the following system.serviceModel configuration section to define the EchoService.

XML

<configuration> <system.serviceModel> <services> <service name="Service.EchoService"> </service> </services>

Page 30

Page 31: Part 1: Introduction to the AppFabric Service Busbandgap.cs.rice.edu/classes/comp410/resources/Using Azure... · Web viewThis lab covers the basics of the AppFabric Service Bus. It

</system.serviceModel> ...</configuration>

2. Add an endpoint definition to the service. To do this, add the following code (shown in bold) inside the service configuration.

XML

<!-- Application Service --><service name="Service.EchoService"> <endpoint contract="Service.IEchoContract" binding="netTcpRelayBinding" /></service>

Note: The endpoints are configured to use a binding of type netTcpRelayBinding.

Task 4 – Creating the WCF Client Project

In this task, you create the project for the client WCF application and define the proxy to communicate with the service.

1. Create the Client project. To do this, in the File menu, point to Add and then select New Project. In the New Project dialog, select the Console Application template, ensure that the target framework is set to .NET Framework 4, set the project name to Client and click OK.

Figure 22

Page 31

Page 32: Part 1: Introduction to the AppFabric Service Busbandgap.cs.rice.edu/classes/comp410/resources/Using Azure... · Web viewThis lab covers the basics of the AppFabric Service Bus. It

Creating the client project (C#)

Figure 23Creating the client project (Visual Basic)

2. Change the Target Framework to .NET Framework 4 to allow the Service Bus interaction. To do this, in Solution Explorer, right-click the Client project and select Properties.

For Visual C# projects: In the Properties window, select the Application tab and choose .NET Framework 4 in the Target Framework option. If prompted to confirm the target framework change, click Yes to proceed.

For Visual Basic projects: In the Properties window, select the Compile tab, click Advance Compile Options , choose .NET Framework 4 in the Target Framework option, and click OK. If prompted to confirm the target framework change, click Yes to proceed

Page 32

Page 33: Part 1: Introduction to the AppFabric Service Busbandgap.cs.rice.edu/classes/comp410/resources/Using Azure... · Web viewThis lab covers the basics of the AppFabric Service Bus. It

Figure 24Choosing the target framework for C# projects

Page 33

Page 34: Part 1: Introduction to the AppFabric Service Busbandgap.cs.rice.edu/classes/comp410/resources/Using Azure... · Web viewThis lab covers the basics of the AppFabric Service Bus. It

Figure 25Choosing the target framework for Visual Basic projects

3. Add a reference to the ServiceModel assembly. To do this, in Solution Explorer, right-click the Client project and select Add Reference. In the Add Reference dialog, choose the .NET tab, select the System.ServiceModel assembly. Click OK to add the reference.

4. Now, add a reference to the Service Bus core assembly. Again, right-click the Client project in Solution Explorer, select Add Reference to open the Add Reference dialog, select the .NET tab, choose Microsoft.ServiceBus and click OK.

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

5. Create the Echo client proxy. To do this, in Solution Explorer, right-click the Client project, point to Add and select New Item. In the Add New Item dialog box, choose Code in the categories list, select the Interface template, set the Name to EchoProxy.cs (for Visual C# projects) or EchoProxy.vb (for Visual Basic projects) and click Add.

Page 34

Page 35: Part 1: Introduction to the AppFabric Service Busbandgap.cs.rice.edu/classes/comp410/resources/Using Azure... · Web viewThis lab covers the basics of the AppFabric Service Bus. It

6. In the EchoProxy.cs file (for Visual C# projects) or the EchoProxy.vb file (for Visual Basic projects), add the following namespace directive.

C#

using System.ServiceModel;

Visual Basic

Imports System.ServiceModel

7. Define the interface. To do this, replace the current interface definition (EchoProxy) with the following code (shown in bold).

(Code Snippet - Introduction to Service Bus Lab Part 1 - Ex01 Echo Proxy Contract - CS)

C#

[ServiceContract(Name = "EchoContract", Namespace = "http://samples.microsoft.com/ServiceModel/Relay/")]public interface IEchoContract{}

(Code Snippet - Introduction to Service Bus Lab Part 1 - Ex01 Echo Proxy Contract - VB)

Visual Basic

<ServiceContract(Name:="EchoContract", Namespace:="http://samples.microsoft.com/ServiceModel/Relay/")> _Public Interface IEchoContractEnd Interface

8. Define the Echo operation contract. To do this, paste the following code inside the IEchoContract class.

C#

[ServiceContract(Name = "EchoContract", Namespace = "http://samples.microsoft.com/ServiceModel/Relay/")]public interface IEchoContract{ [OperationContract] string Echo(string text);}

Page 35

Page 36: Part 1: Introduction to the AppFabric Service Busbandgap.cs.rice.edu/classes/comp410/resources/Using Azure... · Web viewThis lab covers the basics of the AppFabric Service Bus. It

Visual Basic

<ServiceContract(Name:="EchoContract", Namespace:="http://samples.microsoft.com/ServiceModel/Relay/")> _Public Interface IEchoContract <OperationContract()> _ Function Echo(ByVal text As String) As StringEnd Interface

Task 5 – Consuming the WCF Service Hosted through the App Fabric Service Bus

In this task, you create the service proxy and connect to the hosted service.

1. In Solution Explorer, locate the Client project, double-click Program.cs (for Visual C# projects) or Module1.vb file (for Visual Basic projects) inside it and paste the following code below the existing namespace directives at the top of the file.

C#

using System.ServiceModel;using Microsoft.ServiceBus;

Visual Basic

Imports System.ServiceModelImports Microsoft.ServiceBus

2. Add code to let you enter the service namespace and credentials and then create a channel to the service. The authentication type used is SharedSecret; the same configuration that was used in step 4 of task 2. To do this, paste the following code inside method Main.

(Code Snippet - Introduction to Service Bus Lab Part 1 - Ex01 Client - CS)

C#

static void Main(string[] args){ Console.Title = "Client"; Console.Write("Your Service Namespace Domain (e.g. sb://<YOUR-NAMESPACE>.servicebus.windows.net/): "); string serviceNamespaceDomain = Console.ReadLine(); Console.Write("Your Issuer Name: "); string issuerName = Console.ReadLine(); Console.Write("Your Issuer Secret: "); string issuerSecret = Console.ReadLine();

// create the service URI based on the service namespace

Page 36

Page 37: Part 1: Introduction to the AppFabric Service Busbandgap.cs.rice.edu/classes/comp410/resources/Using Azure... · Web viewThis lab covers the basics of the AppFabric Service Bus. It

Uri serviceUri = ServiceBusEnvironment.CreateServiceUri("sb", serviceNamespaceDomain, "EchoService");

// create the credentials object for the endpoint TransportClientEndpointBehavior sharedSecretServiceBusCredential = new TransportClientEndpointBehavior(); sharedSecretServiceBusCredential.CredentialType = TransportClientCredentialType.SharedSecret; sharedSecretServiceBusCredential.Credentials.SharedSecret.IssuerName = issuerName; sharedSecretServiceBusCredential.Credentials.SharedSecret.IssuerSecret = issuerSecret;

// create the channel factory loading the configuration ChannelFactory<IEchoContract> channelFactory = new ChannelFactory<IEchoContract>("RelayEndpoint", new EndpointAddress(serviceUri));

// apply the Service Bus credentials channelFactory.Endpoint.Behaviors.Add(sharedSecretServiceBusCredential);

// create and open the client channel IEchoContract channel = channelFactory.CreateChannel(); ((ICommunicationObject)channel).Open();}

(Code Snippet - Introduction to Service Bus Lab Part 1 - Ex01 Client - VB)

Visual Basic

Sub Main() Console.Title = "Client" Console.Write("Your Service Namespace Domain (e.g. sb://<YOUR-NAMESPACE>.servicebus.windows.net/): ") Dim serviceNamespaceDomain As String = Console.ReadLine() Console.Write("Your Issuer Name: ") Dim issuerName As String = Console.ReadLine() Console.Write("Your Issuer Secret: ") Dim issuerSecret As String = Console.ReadLine()

' create the service URI based on the service namespace Dim serviceUri As Uri = ServiceBusEnvironment.CreateServiceUri("sb", serviceNamespaceDomain, "EchoService")

' create the credentials object for the endpoint

Page 37

Page 38: Part 1: Introduction to the AppFabric Service Busbandgap.cs.rice.edu/classes/comp410/resources/Using Azure... · Web viewThis lab covers the basics of the AppFabric Service Bus. It

Dim sharedSecretServiceBusCredential As New TransportClientEndpointBehavior() sharedSecretServiceBusCredential.CredentialType = TransportClientCredentialType.SharedSecret sharedSecretServiceBusCredential.Credentials.SharedSecret.IssuerName = issuerName sharedSecretServiceBusCredential.Credentials.SharedSecret.IssuerSecret = issuerSecret

' create the channel factory loading the configuration Dim channelFactory As New ChannelFactory(Of IEchoContract)("RelayEndpoint", New EndpointAddress(serviceUri))

' apply the Service Bus credentials channelFactory.Endpoint.Behaviors.Add(sharedSecretServiceBusCredential)

' create and open the client channel Dim channel As IEchoContract = channelFactory.CreateChannel() CType(channel, ICommunicationObject).Open()End Sub

3. Add code to request the user to enter a message to be sent to the service and then proceed to send it (by calling EchoChannel.Echo). If the user enters an empty string, the application ends.

(Code Snippet - Introduction to Service Bus Lab Part 1 - Ex01 Client User Interaction - CS)

C#

static void Main(string[] args){ ... ((ICommunicationObject)channel).Open();

Console.WriteLine("Enter text to echo (or [Enter] to exit):"); string input = Console.ReadLine(); while (input != String.Empty) { try { Console.WriteLine("Server echoed: {0}", channel.Echo(input)); } catch (Exception e) { Console.WriteLine("Error: " + e.Message); }

Page 38

Page 39: Part 1: Introduction to the AppFabric Service Busbandgap.cs.rice.edu/classes/comp410/resources/Using Azure... · Web viewThis lab covers the basics of the AppFabric Service Bus. It

input = Console.ReadLine(); }}

(Code Snippet - Introduction to Service Bus Lab Part 1 - Ex01 Client User Interaction - VB)

Visual Basic

Sub Main()

... ' create and open the client channel Dim channel As IEchoContract = channelFactory.CreateChannel() CType(channel, ICommunicationObject).Open()

Console.WriteLine("Enter text to echo (or [Enter] to exit):") Dim input As String = Console.ReadLine() Do While input <> String.Empty Try Console.WriteLine("Server echoed: {0}", channel.Echo(input)) Catch e As Exception Console.WriteLine("Error: " & e.Message) End Try input = Console.ReadLine() LoopEnd Sub

Note: When the relay service receives an incoming message from an authorized sender (Client), it simply relays the message to an instance of the EchoService running locally. EchoService creates an application response and sends it back to the relay service.

The relay service completes the message flow by sending the response to the client containing the EchoService response message.

4. Add code to close both the Channel and the ChannelFactory.

(Code Snippet - Introduction to Service Bus Lab Part 1 - Ex01 Close Channel - CS)

C#

static void Main(string[] args){ ... while (input != String.Empty) {

Page 39

Page 40: Part 1: Introduction to the AppFabric Service Busbandgap.cs.rice.edu/classes/comp410/resources/Using Azure... · Web viewThis lab covers the basics of the AppFabric Service Bus. It

... }

((ICommunicationObject)channel).Close(); channelFactory.Close();}

(Code Snippet - Introduction to Service Bus Lab Part 1 - Ex01 Close Channel - VB)

Visual Basic

Sub Main()

... Do While input <> String.Empty ... Loop

CType(channel, ICommunicationObject).Close() channelFactory.Close()End Sub

5. Add an endpoint and binding configuration for the proxy used in the client side. To do this, paste the following code in App.config.

XML

<configuration> <system.serviceModel> <client> <!-- Application Endpoint --> <endpoint name="RelayEndpoint" contract="Client.IEchoContract" binding="netTcpRelayBinding"/> </client> </system.serviceModel></configuration>

Verification

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

Note: You require an AppFabric project and a service namespace to complete this exercise. If you have not already done so, complete the Getting Started section.

1. Launch the service. To do this, right-click the Service project, point to Debug and select Start new instance.

Page 40

Page 41: Part 1: Introduction to the AppFabric Service Busbandgap.cs.rice.edu/classes/comp410/resources/Using Azure... · Web viewThis lab covers the basics of the AppFabric Service Bus. It

2. Enter your Service Namespace Domain; this is the service namespace you entered when provisioning your account at the portal Web Site. After that, enter your 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.

Figure 26Starting the service application

Note: Note: HTTP services require administrative privileges in order to register a URL. For instance, if you see the following error message:

It means that the namespace where the service is being hosted has not been reserved yet. To solve this, stop debugging, run the following command with administrative privileges, and then launch the service again:

Page 41

Page 42: Part 1: Introduction to the AppFabric Service Busbandgap.cs.rice.edu/classes/comp410/resources/Using Azure... · Web viewThis lab covers the basics of the AppFabric Service Bus. It

netsh http add urlacl url=http://+:80/EchoService/ user=DOMAIN\user

Where DOMAIN\user is the user that will run the Service console application.

Notice that you could also workaround this by launching Visual Studio as an administrator.

3. Start the WCF Client. To do this, in Solution Explorer, right-click the Client project, point to Debug and select Start new instance.

4. Once again, enter the Service Namespace Domain, Default Issuer Name and Default Issuer Key of your service namespace.

Figure 27Starting the client application

Note: In this hands-on-lab, both the client and the service use the same credentials; therefore, no additional steps are required to grant the client access to listen or to send a message to the service through the Service Bus. By default, a credential is granted Listen, Send, and Manage privileges within its own Service Bus service namespace. If the client is using a different credential than the service, a specific Access Control rule is needed for a client credential to gain Listen, Send or Manage privileges in the service namespace for the service.

5. Type some messages at the Client console. Messages will be sent to the Service via the Service Bus.

Page 42

Page 43: Part 1: Introduction to the AppFabric Service Busbandgap.cs.rice.edu/classes/comp410/resources/Using Azure... · Web viewThis lab covers the basics of the AppFabric Service Bus. It

Figure 28Messages sent to the hosted service

6. The Service receives the messages via the relay service and outputs them to the console window.

Figure 29Service receives and outputs the messages

Page 43

Page 44: Part 1: Introduction to the AppFabric Service Busbandgap.cs.rice.edu/classes/comp410/resources/Using Azure... · Web viewThis lab covers the basics of the AppFabric Service Bus. It

Exercise 2: Connecting a WCF Service in IIS 7.5 to the Service Bus

In this exercise you will connect a WCF Service hosted in IIS 7.5 to the Service Bus. Additionally, you will configure the service so it automatically activates once IIS 7.5 starts running. This configuration provides a solution to an important challenge when hosting a WCF service using Service Bus bindings.

In order for the WCF service to start receiving messages from the Service Bus in the cloud (the Relay Service), the service opens an outbound port and creates a bidirectional socket for communication. It connects to the Service Bus, authenticates itself, and starts listening to calls from the relay service before the client sends its requests. IIS\WAS, on the other hand, relies on message-based activation and will launch the host only after the first request comes in.

Consequently, until the first message is received by IIS the service will never establish a connection to the Service Bus; but with no connection to the Service Bus, it will never receive a message.

During the exercise, you will use the Windows App Fabric Auto-Start feature to get the service up and running as soon as the application that it belongs to is started and before the service receives the first WCF message from the client, thus overcoming this limitation.

Task 1 – Creating a Virtual Directory for the application

In this task you create virtual directory for the web site which hosts the WCF service.

1. Open Microsoft Visual Studio 2010 with elevated permissions. To do this, go to Start | All Programs | Microsoft Visual Studio 2010, right-click the Microsoft Visual Studio 2010 option and select Run as Administrator. This is shown in the following figure.

Page 44

Page 45: Part 1: Introduction to the AppFabric Service Busbandgap.cs.rice.edu/classes/comp410/resources/Using Azure... · Web viewThis lab covers the basics of the AppFabric Service Bus. It

Figure 30Running Visual Studio as administrator from the Start menu

2. Click Yes in the User Account Control dialog. Visual Studio will open with Administrator privileges.

Page 45

Page 46: Part 1: Introduction to the AppFabric Service Busbandgap.cs.rice.edu/classes/comp410/resources/Using Azure... · Web viewThis lab covers the basics of the AppFabric Service Bus. It

Figure 31Clicking Yes in the User Account Control dialog opens VS with Administrator privileges

3. In Visual Studio, open the IISHostedCalculatorService.sln solution file from Ex02-IISHostedService\begin\{CS|VB} in the Source folder of the lab.

4. In Solution Explorer, right-click the IISHostedCalculatorService project and select Properties.

5. Update the server to be used by the IISHostedCalculatorService web site. To do this, in the Web tab in the Properties window, select the Use Local IIS Web Server option.

6. Click Create Virtual Directory to create a virtual directory for the Web Site in IIS.

Figure 32 Creating a Virtual Directory in IIS for the Web Site

Note: If you are not running Visual Studio with elevation you will receive an error message similar to the one shown in the following figure.

Page 46

Page 47: Part 1: Introduction to the AppFabric Service Busbandgap.cs.rice.edu/classes/comp410/resources/Using Azure... · Web viewThis lab covers the basics of the AppFabric Service Bus. It

Figure 33Error message when trying to create a virtual directory without elevated permissions

7. In Visual Studio, save all changes by clicking the Save All button.

Task 2 – Configuring the WCF Service to be discoverable

In this task you will update the service's configuration to be able to expose it to the Service Bus. To do this, you will create a custom configuration element that will enable you to set the discoverability policy to "Public" in the configuration file.

1. Add a reference to the Microsoft.ServiceBus.dll assembly. To do this, right-click the IISHostedCalculatorService project in Solution Explorer, select Add Reference to open the Add Reference dialog, select the .NET tab, choose Microsoft.ServiceBus.dll and click OK.

Note: If you cannot find the assembly in the .NET tab, use the Browse tab to locate it inside the C:\%Program Files%\Windows Azure platform AppFabric SDK\V1.0\Assemblies\NET4.0 folder.

2. In Solution Explorer, right-click the IISHostedCalculatorService, point to Add and click Class. The Add New Item dialog appears.

3. Name the class ServiceRegistrySettingsElement, as shown in the following figure.

Figure 34

Page 47

Page 48: Part 1: Introduction to the AppFabric Service Busbandgap.cs.rice.edu/classes/comp410/resources/Using Azure... · Web viewThis lab covers the basics of the AppFabric Service Bus. It

Adding the ServiceRegistrySettingsElement class to the IISHostedCalculatorService project (C#)

Figure 35Adding the ServiceRegistrySettingsElement class to the IISHostedCalculatorService project (Visual Basic)

4. Click Add. In the following steps you will make this class accessible as a BehaviorExtension configuration element. The reason for doing this is that there is not out-of-the-box way to set the discoverability policy to "Public" in the configuration file. This custom BehaviorExtension element will allow you to achieve this functionality.

5. At the top of the ServiceRegistrySettingsElement.cs file (for Visual C# projects) or the ServiceRegistrySettingsElement.vb file (for Visual Basic projects), add the following namespace directives.

(Code Snippet - Introduction to Service Bus Lab Part 1 - Ex02 ServiceRegistrySettingsElement Namespaces -CS)

C#

using System.ServiceModel.Configuration;using Microsoft.ServiceBus;

Page 48

Page 49: Part 1: Introduction to the AppFabric Service Busbandgap.cs.rice.edu/classes/comp410/resources/Using Azure... · Web viewThis lab covers the basics of the AppFabric Service Bus. It

using System.Configuration;

(Code Snippet - Introduction to Service Bus Lab Part 1 - Ex02 ServiceRegistrySettingsElement Namespaces - VB)

Visual Basic

Imports System.ServiceModel.ConfigurationImports Microsoft.ServiceBusImports System.Configuration

6. Update the class' definition as shown in the following code sample. The class inherits from the BehaviorExtensionElement class, which enables the user to customize service or endpoint behaviors. The properties marked with the ConfigurationProperty attributes will be accessible from the configuration file.

(Code Snippet - Introduction to Service Bus Lab Part 1 - Ex02 ServiceRegistrySettingsElement Definition - CS)

C#

public class ServiceRegistrySettingsElement : BehaviorExtensionElement{ private const string displayNameId = "displayName"; private const string discoveryModeId = "discoveryMode";

public override Type BehaviorType { get { return typeof(ServiceRegistrySettings); } }

protected override object CreateBehavior() { return new ServiceRegistrySettings() { DiscoveryMode = this.DiscoveryMode, }; }

[ConfigurationProperty(discoveryModeId, DefaultValue = DiscoveryType.Private)] public DiscoveryType DiscoveryMode { get { return (DiscoveryType)this[discoveryModeId]; } set { this[discoveryModeId] = value; } }

Page 49

Page 50: Part 1: Introduction to the AppFabric Service Busbandgap.cs.rice.edu/classes/comp410/resources/Using Azure... · Web viewThis lab covers the basics of the AppFabric Service Bus. It

public string DisplayName { get { return (string)this[displayNameId]; } set { this[displayNameId] = value; } }}

(Code Snippet - Introduction to Service Bus Lab Part 1 - Ex02 ServiceRegistrySettingsElement Definition - VB)

Visual Basic

Public Class ServiceRegistrySettingsElement Inherits BehaviorExtensionElement

Private Const displayNameId As String = "displayName" Private Const discoveryModeId As String = "discoveryMode"

Public Overrides ReadOnly Property BehaviorType() As Type Get Return GetType(ServiceRegistrySettings) End Get End Property

Protected Overrides Function CreateBehavior() As Object Return New ServiceRegistrySettings() With { _ .DiscoveryMode = Me.DiscoveryMode, _ .DisplayName = Me.DisplayName _ } End Function

<ConfigurationProperty(discoveryModeId, DefaultValue:=DiscoveryType.Public)> _ Public Property DiscoveryMode() As DiscoveryType Get Return DirectCast(Me(discoveryModeId), DiscoveryType) End Get Set(ByVal value As DiscoveryType) Me(discoveryModeId) = value End Set End Property

<ConfigurationProperty(displayNameId)> _ Public Property DisplayName() As String Get Return DirectCast(Me(displayNameId), String) End Get Set(ByVal value As String)

Page 50

Page 51: Part 1: Introduction to the AppFabric Service Busbandgap.cs.rice.edu/classes/comp410/resources/Using Azure... · Web viewThis lab covers the basics of the AppFabric Service Bus. It

Me(displayNameId) = value End Set End PropertyEnd Class

7. In Visual Studio, save all files by clicking the Save All button.

8. In Solution Explorer, double-click the Web.config file to open it in the Visual Studio editor.

9. Replace the <system.servicemodel> element and its children with the following configuration. Make sure to replace the [YOUR-SERVICE-NAMESPACE-DOMAIN], [YOUR-ISSUER-NAME] and [YOUR-ISSUER-KEY] placeholders with the correct values. Note that the code highlighted in bold uses the ServiceRegistrySettingsElement previously created.

XML

<system.serviceModel> <services> <clear /> <service behaviorConfiguration="MyServiceTypeBehavior" name="IISHostedCalculatorService.CalculatorService"> <endpoint address="http://localhost/IISHostedCalculatorService/CalculatorService.svc/LocalCalculatorService" binding="basicHttpBinding" bindingConfiguration="BasicHttpConfig" name="Basic" contract="IISHostedCalculatorService.ICalculatorService" /> <endpoint address="https://[YOUR-SERVICE-NAMESPACE-DOMAIN].servicebus.windows.net/CalculatorServiceHttp/" behaviorConfiguration="sharedSecretClientCredentials" binding="basicHttpRelayBinding" bindingConfiguration="HttpRelayEndpointConfig" name="RelayEndpoint" contract="IISHostedCalculatorService.ICalculatorService" /> <endpoint address="sb://[YOUR-SERVICE-NAMESPACE-DOMAIN].servicebus.windows.net/CalculatorServiceNetTcp/" behaviorConfiguration="sharedSecretClientCredentials" binding="netTcpRelayBinding" bindingConfiguration="NetTcpRelayEndpointConfig" name="RelayEndpoint" contract="IISHostedCalculatorService.ICalculatorService" /> </service> </services> <bindings> <basicHttpBinding> <binding name="BasicHttpConfig" />

Page 51

Page 52: Part 1: Introduction to the AppFabric Service Busbandgap.cs.rice.edu/classes/comp410/resources/Using Azure... · Web viewThis lab covers the basics of the AppFabric Service Bus. It

</basicHttpBinding> <!--service bus binding--> <basicHttpRelayBinding> <binding name="HttpRelayEndpointConfig"> <security relayClientAuthenticationType="RelayAccessToken" /> </binding> </basicHttpRelayBinding> <netTcpRelayBinding> <binding name="NetTcpRelayEndpointConfig"> <security relayClientAuthenticationType="RelayAccessToken" /> </binding> </netTcpRelayBinding> </bindings> <behaviors> <endpointBehaviors> <behavior name="sharedSecretClientCredentials"> <transportClientEndpointBehavior credentialType="SharedSecret"> <clientCredentials> <sharedSecret issuerName="[YOUR-ISSUER-NAME]" issuerSecret="[YOUR-ISSUER-KEY]" /> </clientCredentials> </transportClientEndpointBehavior> <ServiceRegistrySettings discoveryMode="Public"/> </behavior> </endpointBehaviors> <serviceBehaviors> <behavior name="MyServiceTypeBehavior"> <serviceMetadata httpGetEnabled="true" /> <serviceDebug includeExceptionDetailInFaults="true" /> </behavior> </serviceBehaviors> </behaviors> <extensions> <behaviorExtensions> <add name="ServiceRegistrySettings" type="IISHostedCalculatorService.ServiceRegistrySettingsElement, IISHostedCalculatorService, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null" /> </behaviorExtensions> </extensions></system.serviceModel>

10. Build the solution.

Task 3 – Enabling Windows Server App Fabric Auto-Start for the WCF Calculator Service

In this task you will enable the Auto-Start feature provided by Windows Server App Fabric for the WCF Calculator Service hosted by the IISHostedCalculatorService site. As explained previously, you activate

Page 52

Page 53: Part 1: Introduction to the AppFabric Service Busbandgap.cs.rice.edu/classes/comp410/resources/Using Azure... · Web viewThis lab covers the basics of the AppFabric Service Bus. It

Auto-Start to get the service up and running as soon as the application that it belongs to is started. This is done to make up for the following facts:

Until the first message is received by IIS, the service will never establish a connection to the Service Bus.

With no connection to the Service Bus, the service will never receive a message.

Additionally, as Windows Server AppFabric uses the Microsoft.WebAdministration (MWA) API to read and write configuration files, you will provide a custom MWA schema for some of the elements from the Web.config file to be correctly recognized. This will give you the possibility to enable the Auto-Start feature from the Internet Information Services (IIS) Manager.

1. Copy the ServiceBus_schema.xml file located under the Source\Assets folder of this lab to the %SystemRoot%\System32\inetsrv\config\schema directory. This file contains the schema that will be used by the Windows Server App Fabric to read the configuration file for your service.

Figure 36ServiceBus_schema.xml file copied to the %SystemRoot%\System32\inetsrv\config\schema directory

Note: If you want to know what elements are supported by the ServiceBus_schema.xml schema file, you can open it as you would open any other XML file.

Page 53

Page 54: Part 1: Introduction to the AppFabric Service Busbandgap.cs.rice.edu/classes/comp410/resources/Using Azure... · Web viewThis lab covers the basics of the AppFabric Service Bus. It

2. Open Internet Information Services (IIS) Manager from Start | All Programs | Internet Information Services (IIS) 7 Manager. The User Account Control dialog appears, as shown in the following figure.

Figure 37User Account Control dialog when opening the IIS Manager

3. Click Yes.

4. In the Connections tree view, select the IISHostedCalculatorService site, as shown in the following figure.

Figure 38

Page 54

Page 55: Part 1: Introduction to the AppFabric Service Busbandgap.cs.rice.edu/classes/comp410/resources/Using Azure... · Web viewThis lab covers the basics of the AppFabric Service Bus. It

Selecting the IISHostedCalculatorService site

5. In the Actions menu, click Configure under the Manage WCF and WF services submenu. This is shown in the following figure. The Configure WCF and WF for Application dialog appears.

Figure 39Configuring the WCF Calculator service

6. In the list, select Auto-Start, and then select the Custom option. Selecting the custom options allows you manually determine those services that will be auto-started. The outcome configuration is shown in the following figure.

Page 55

Page 56: Part 1: Introduction to the AppFabric Service Busbandgap.cs.rice.edu/classes/comp410/resources/Using Azure... · Web viewThis lab covers the basics of the AppFabric Service Bus. It

Figure 40Selecting the Custom Auto-Start option

7. Click Apply. A warning message explaining that all services in the application might recycle appears.

Figure 41Warning about Application services being recycled

8. Click Yes.

9. In the Configure WCF and WF for Application dialog, click OK.

Page 56

Page 57: Part 1: Introduction to the AppFabric Service Busbandgap.cs.rice.edu/classes/comp410/resources/Using Azure... · Web viewThis lab covers the basics of the AppFabric Service Bus. It

10. Double-click the Services option, which is highlighted in the following picture. The content in the center pane will be replaced with the list of services from your application.

Figure 42Services option

11. Double-click the IISHostedCalculatorService.CalculatorService. The Configuration Service dialog appears.

Page 57

Page 58: Part 1: Introduction to the AppFabric Service Busbandgap.cs.rice.edu/classes/comp410/resources/Using Azure... · Web viewThis lab covers the basics of the AppFabric Service Bus. It

Figure 43Configuration Service dialog

12. In the list, select Auto-Start, and select the Enable option. This is done to enable Auto-Start for the service.

Page 58

Page 59: Part 1: Introduction to the AppFabric Service Busbandgap.cs.rice.edu/classes/comp410/resources/Using Azure... · Web viewThis lab covers the basics of the AppFabric Service Bus. It

Figure 44Enabling Auto-Start for the IISHostedCalculatorService.CalculatorService

13. Click Apply. In the warning message that appears which explains that all services in the application might recycle, click Yes.

14. In the Configuration Service dialog, click OK.

15. Restart Internet Information Services. To do this, Open a Command Prompt as administrator, and type iisreset.

Page 59

Page 60: Part 1: Introduction to the AppFabric Service Busbandgap.cs.rice.edu/classes/comp410/resources/Using Azure... · Web viewThis lab covers the basics of the AppFabric Service Bus. It

Figure 45Restarting Internet Information Services

Verification

In order to verify that you have performed every step in the exercise correctly, perform the steps below.

In this verification you will use an already developed WPF client that consumes the CalculatorService via the service bus. You will first configure the client with the data where the service is published in the service bus. Afterwards, you will verify that all operations work as expected.

Note: You require an AppFabric project and a service namespace to complete this exercise. If you have not already done so, follow the Getting Started section.

1. In Visual Studio, open the CalculatorClient.sln solution file from Assets\CalculatorClient in the Source folder of the lab.

2. Open the application configuration file to setup the service bus data. To do this, double click the app.config file from the Solution Explorer.

Figure 46

Page 60

Page 61: Part 1: Introduction to the AppFabric Service Busbandgap.cs.rice.edu/classes/comp410/resources/Using Azure... · Web viewThis lab covers the basics of the AppFabric Service Bus. It

Application Configuration

3. In the appSettings section of the app.config file, locate the serviceNamespaceDomain setting and replace [YOUR-SERVICE-NAMESPACE-DOMAIN] with the domain service namespace that you registered at the portal.

4. 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 show an example of the app.config file after replacing the setting value.

Figure 47App.config

5. Press F5 in Visual Studio to run the CalculatorClient application. The CalculatorClient application will open.

Page 61

Page 62: Part 1: Introduction to the AppFabric Service Busbandgap.cs.rice.edu/classes/comp410/resources/Using Azure... · Web viewThis lab covers the basics of the AppFabric Service Bus. It

Figure 48Calculator Client application

6. Type some numeric values in the parameters text boxes, and click on the Add ( + ) operation button. This button will execute the Add operation of the CalculatorService via the Service Bus. You will see the service URI below the buttons. Notice that https protocol is used by default.

Figure 49Service Executing

7. When the service finishes executing you will see the result at the bottom of the application. You can verify that all service operations are working by clicking on the other operation buttons (Substract ( - ), Multiply ( * ) and Divide ( / )).

Page 62

Page 63: Part 1: Introduction to the AppFabric Service Busbandgap.cs.rice.edu/classes/comp410/resources/Using Azure... · Web viewThis lab covers the basics of the AppFabric Service Bus. It

Figure 50Service Result

8. On the Connectivity Mode section, check the NetTCPRelay option and click any of the operation buttons. This will cause the Calculator Client to use the TCP protocol to communicate with the service bus. You will notice that the service URI will change.

Figure 51TCP Protocol

Page 63

Page 64: Part 1: Introduction to the AppFabric Service Busbandgap.cs.rice.edu/classes/comp410/resources/Using Azure... · Web viewThis lab covers the basics of the AppFabric Service Bus. It

Exercise 3: Multicast Messaging through the Service Bus

In this exercise, you build a simple internet relay chat application that demonstrates multicast messaging through the Service Bus. Multicast, otherwise known as simple publish/subscribe, enables multiple listeners and senders at a single URI. Every actor is both a listener and a sender at the same time.

To implement a multicast messaging pattern, the Service Bus provides a binding named netEventRelayBinding that you can use for this purpose. This binding enables a publish/subscribe communication pattern over WCF, which is not available from any of the built-in WCF bindings. The netEventRelayBinding binding allows multiple applications to subscribe to messages sent to an endpoint. Any messages sent to that endpoint are received by all applications.

The Service Bus implements the netEventRelayBinding by allowing multiple listeners to register themselves at a URI specified by the first sender. Each service host that has an endpoint listening on that same URI implicitly becomes a subscriber. When a client sends a message to that URI, the message is delivered to all service endpoints currently subscribed. In this scenario, the back-end system plays the role of the WCF client and broadcasts (publishes) a message to all subscribers.

During the exercise, you will also learn how to provide message protection by using X.509 certificates.

Figure 52Multicasting using the netEventRelayBinding

Page 64

Page 65: Part 1: Introduction to the AppFabric Service Busbandgap.cs.rice.edu/classes/comp410/resources/Using Azure... · Web viewThis lab covers the basics of the AppFabric Service Bus. It

This exercise will expose several Service Bus features such as:

Service Bus netEventRelayBinding

Using X.509 certificates for message confidentiality

Note: This exercise could be executed with a single solution, by opening two instances. However, it is interesting to run it using two different machines and two different AppFabric accounts. Also, enabling tracing and message logging allows you to understand how the relay works.

Task 1 – Building the Internet Relay Chat Application

In this task, you build the chat application based on a provided Visual Studio solution.

To be able to chat between two different applications, you need to have two different user accounts.

1. Open Microsoft Visual Studio 2010 from Start | All Programs | Microsoft Visual Studio 2010 | Microsoft Visual Studio 2010.

2. Open the MulticastSample.sln solution file from Ex03-MulticastSample\begin\{CS|VB} in the Source folder of the lab.

3. Create a new binding configuration for the netEventRelayBinding. To do this, in Solution Explorer, double-click App.config and paste the following code (shown in bold) inside the bindings element.

XML

<bindings> <netEventRelayBinding> <binding name="lab" receiveTimeout="00:05:00"> </binding> </netEventRelayBinding></bindings>

Note: The binding specifies a receiveTimeout of 5 minutes to avoid dropping the connection due to inactivity during your testing. You may increase this value if necessary.

4. Change the binding specified in both the client and service endpoints from netTcpRelayBinding to netEventRelayBinding. To do this, in the App.config file, replace the binding attribute for both endpoint tags with the following code (highlighted in bold).

XML

<system.serviceModel> ... <client> <endpoint name="RelayEndpoint"

Page 65

Page 66: Part 1: Introduction to the AppFabric Service Busbandgap.cs.rice.edu/classes/comp410/resources/Using Azure... · Web viewThis lab covers the basics of the AppFabric Service Bus. It

contract="MulticastSample.IMulticastContract" binding="netEventRelayBinding" bindingConfiguration="lab" behaviorConfiguration="SharedSecretCredentials" /> </client>

<services> <service name="MulticastSample.MulticastService" > <endpoint name="RelayEndpoint" contract="MulticastSample.IMulticastContract" binding="netEventRelayBinding" bindingConfiguration="lab" behaviorConfiguration="SharedSecretCredentials" /> </service> </services>

</system.serviceModel>

5. Define the service contract operations. To do this, in Solution Explorer, double-click IMulticastContract.cs (for Visual C# projects) or IMulticastContract.vb (for Visual Basic projects) to open the service contract and paste the following code inside the interface definition. Hello and Bye are methods used within the application to notify participants when a user joins and leaves the chat. The Chat method is called by the application when a user provides a string to contribute to the conversation.

(Code Snippet - Introduction to Service Bus Lab Part 1 - Ex03 Multicast Contract Operations - CS)

C#

public interface IMulticastContract{ [OperationContract(IsOneWay = true)] void Hello(string nickname);

[OperationContract(IsOneWay = true)] void Chat(string nickname, string text);

[OperationContract(IsOneWay = true)] void Bye(string nickname);}

(Code Snippet - Introduction to Service Bus Lab Part 1 - Ex03 Multicast Contract Operations - VB)

Visual Basic

Public Interface IMulticastContract

Page 66

Page 67: Part 1: Introduction to the AppFabric Service Busbandgap.cs.rice.edu/classes/comp410/resources/Using Azure... · Web viewThis lab covers the basics of the AppFabric Service Bus. It

<OperationContract(IsOneWay:=True)> _ Sub Hello(ByVal nickname As String)

<OperationContract(IsOneWay:=True)> _ Sub Chat(ByVal nickname As String, ByVal text As String)

<OperationContract(IsOneWay:=True)> _ Sub Bye(ByVal nickname As String)

End Interface

Note: The netEventRelayBinding requires contracts to expose one way operations only. Therefore, all operations must be marked with “IsOneWay=true” to indicate that the operation only consists of a single input message and has no associated output message.

6. Implement the service operations. To do this, in Solution Explorer, double-click MulticastService.cs (for Visual C# projects) or MulticastService.vb (for Visual Basic projects) to open the service implementation. Paste the following code inside the MulticastService class:

(Code Snippet - Introduction to Service Bus Lab Part 1 - Ex03 Multicast Service Operations - CS)

C#

public class MulticastService : IMulticastContract{ void IMulticastContract.Hello(string nickname) { Console.WriteLine("[" + nickname + "] joins"); }

void IMulticastContract.Chat(string nickname, string text) { Console.WriteLine("[" + nickname + "] says: " + text); }

void IMulticastContract.Bye(string nickname) { Console.WriteLine("[" + nickname + "] leaves"); }}

(Code Snippet - Introduction to Service Bus Lab Part 1 - Ex03 Multicast Service Operations - VB)

Page 67

Page 68: Part 1: Introduction to the AppFabric Service Busbandgap.cs.rice.edu/classes/comp410/resources/Using Azure... · Web viewThis lab covers the basics of the AppFabric Service Bus. It

Visual Basic

Public Class MulticastService Implements IMulticastContract

Private Sub Hello(ByVal nickname As String) Implements IMulticastContract.Hello Console.WriteLine("[" & nickname & "] joins") End Sub

Private Sub Chat(ByVal nickname As String, ByVal text As String) Implements IMulticastContract.Chat Console.WriteLine("[" & nickname & "] says: " & text) End Sub

Private Sub Bye(ByVal nickname As String) Implements IMulticastContract.Bye Console.WriteLine("[" & nickname & "] leaves") End Sub

End Class

7. Implement the chat behavior. To do this, open Program.cs (for Visual C# projects) or Module1.vb (for Visual Basic projects) and paste the following code (shown in bold).

(Code Snippet - Introduction to Service Bus Lab Part 1 - Ex03 Chat behavior - CS)

C#

public static void Main(){ ... Console.WriteLine("Press [Enter] to exit"); Console.WriteLine();

channel.Hello(nickname);

string input = Console.ReadLine(); while (!string.IsNullOrEmpty(input)) { channel.Chat(nickname, input); input = Console.ReadLine(); }

channel.Bye(nickname);

((ICommunicationObject)channel).Close(); channelFactory.Close();

Page 68

Page 69: Part 1: Introduction to the AppFabric Service Busbandgap.cs.rice.edu/classes/comp410/resources/Using Azure... · Web viewThis lab covers the basics of the AppFabric Service Bus. It

host.Close();}

(Code Snippet - Introduction to Service Bus Lab Part 1 - Ex03 Chat behavior - VB)

Visual Basic

Sub Main() ...

Console.WriteLine("Press [Enter] to exit") Console.WriteLine()

channel.Hello(nickname)

Dim input As String = Console.ReadLine() Do While Not String.IsNullOrEmpty(input) channel.Chat(nickname, input) input = Console.ReadLine() Loop

channel.Bye(nickname)

CType(channel, ICommunicationObject).Close() channelFactory.Close() host.Close()End Sub

Note: The Hello method will notify all participating applications of the arrival of a new user. All strings are sent as messages to each application until an empty string is provided as input (MulticastChannel.Chat). Finally, the Bye method notifies all participants of the departure of the client.

Task 2 – Chatting through the AppFabric Service Bus

In this task, you run two instances of the chat application and exchange messages between them by using the Service Bus multicast features.

1. Open the App.config file. In the appSettings section, locate the serviceNamespaceDomain setting and replace [YOUR-SERVICE-NAMESPACE-DOMAIN] with the domain service namespace that you registered at the portal. Next, in the behaviors section inside system.serviceModel, locate the sharedSecret element inside endpointBehaviors | behavior | transportClientEndpointBehavior | clientCredentials and replace [YOUR-ISSUER-NAME] and [YOUR-ISSUER-KEY] with the Default Issuer Name and Default Issuer Key for the service

Page 69

Page 70: Part 1: Introduction to the AppFabric Service Busbandgap.cs.rice.edu/classes/comp410/resources/Using Azure... · Web viewThis lab covers the basics of the AppFabric Service Bus. It

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.

2. Run one instance of the chat application. To do this, right-click the MulticastSample project, point to Debug and select Start new instance.

3. Enter a name for the chat session and press Enter (you might use “ServiceBusChatSession”). Then, enter the nickname you want to use during the chat session.

Figure 53Entering the chat session

4. Run another instance of the chat application. To do this, in Visual Studio, right-click MulticastSample in Solution Explorer, point to Debug and select Start new instance.

5. In this new instance, enter the same name of the chat session you entered previously, when you started the first instance (for example, “ServiceBusChatSession”). Then, type a nickname you want to use during the chat session (different from the previous one).

Note: One endpoint hosted at the Service Bus relay is shared by all the client applications wishing to exchange messages. All client applications will be subscribers to messages sent to the URI: “sb://[yourServiceNamespace].servicebus.windows.net/[chatSessionName]/MulticastService/”. This sounds awkward since any solution hosted at the Service Bus might be able to listen and send events to that endpoint by knowing the URL only. The next task shows how to mitigate that by protecting messages using X509 certificates.

6. Try sending messages from both instances of the application and verify that both participants can receive messages.

Page 70

Page 71: Part 1: Introduction to the AppFabric Service Busbandgap.cs.rice.edu/classes/comp410/resources/Using Azure... · Web viewThis lab covers the basics of the AppFabric Service Bus. It

Figure 54Chatting using the MultiCast service

Note: Each message is sent to the Service Bus, which then relays the messages to all the services currently subscribed to the same URI.

7. Press Enter in one of the consoles to end the chat session running in that instance.

Page 71

Page 72: Part 1: Introduction to the AppFabric Service Busbandgap.cs.rice.edu/classes/comp410/resources/Using Azure... · Web viewThis lab covers the basics of the AppFabric Service Bus. It

Figure 55Leaving the chat session

Note: Notice that the other application receives the notification of the participant leaving the chat session.

8. Press Enter in the other chat application console to end its session and exit.

Task 3 – Adding Message Protection

In this task, you learn how to protect the messages that are sent by the participants by using X.509 certificates to encrypt the messages. For more information, see Message Security with Mutual Certificates.

1. Open a Visual Studio 2010 Command Prompt as administrator and change the current directory to Assets located inside the folder of the lab.

2. Execute the command file SetupCertificates.cmd as shown below specifying the Service Namespace Domain as a parameter; this is the same service namespace, which you have created during the provisioning process at the Web site portal. The command file installs the certificates required to encrypt messages.

Visual Studio Command Prompt

SetupCertificates.cmd YOUR_SERVICE_NAMESPACE-DOMAIN

Page 72

Page 73: Part 1: Introduction to the AppFabric Service Busbandgap.cs.rice.edu/classes/comp410/resources/Using Azure... · Web viewThis lab covers the basics of the AppFabric Service Bus. It

3. Add a new behavior in the configuration file to specify credentials for the service. Open the App.config file, locate the behaviors section inside system.serviceModel and insert the following behavior section, as shown below (in bold text) after replacing [YOUR-SERVICE-NAMESPACE-DOMAIN] in the serviceCertificate element with the service namespace that you created during the provisioning process.

Note: The value of the findValue attribute after you enter your service namespace should match the name of the certificate created in the previous step.

XML

<behaviors> <serviceBehaviors> <behavior name="RelayServiceBehavior"> <serviceCredentials> <serviceCertificate findValue="[YOUR-SERVICE-NAMESPACE-DOMAIN].servicebus.windows.net" storeLocation="LocalMachine" storeName="My" x509FindType="FindBySubjectName" /> <clientCertificate> <authentication certificateValidationMode="PeerOrChainTrust" /> </clientCertificate> </serviceCredentials> </behavior> </serviceBehaviors></behaviors>

4. Assign the service behavior by adding a behaviorConfiguration attribute to the service element as shown below (highlighted in bold).

XML

<services> <service name="MulticastSample.MulticastService" behaviorConfiguration="RelayServiceBehavior"> <endpoint name="RelayEndpoint" contract="MulticastSample.IMulticastContract" binding="netEventRelayBinding" bindingConfiguration="lab" behaviorConfiguration="SharedSecretCredentials" /> </service></services>

5. Now, insert a new endpoint behavior to specify credentials for the client. Locate the endpointBehaviors section inside behaviors and insert the following code (shown in bold text). Once again, replace [YOUR-SERVICE-NAMESPACE-DOMAIN] in the defaultCertificate element

Page 73

Page 74: Part 1: Introduction to the AppFabric Service Busbandgap.cs.rice.edu/classes/comp410/resources/Using Azure... · Web viewThis lab covers the basics of the AppFabric Service Bus. It

with your service namespace. In addition, replace [YOUR-ISSUER-NAME] and [YOUR-ISSUER-KEY] with your Default Issuer Name and Default Issuer Key that you obtained when you registered the service namespace in the developer portal.

XML

<behaviors> <serviceBehaviors> ... </serviceBehaviors>

<endpointBehaviors> <behavior name="ClientCertificateBehavior"> <clientCredentials> <clientCertificate findValue="client.com" storeLocation="CurrentUser" storeName="My" x509FindType="FindBySubjectName" /> <serviceCertificate> <authentication certificateValidationMode="PeerOrChainTrust" /> <defaultCertificate findValue="[YOUR-SERVICE-NAMESPACE-DOMAIN].servicebus.windows.net" storeLocation="LocalMachine" storeName="My" x509FindType="FindBySubjectName" /> </serviceCertificate> </clientCredentials> <transportClientEndpointBehavior credentialType="SharedSecret"> <clientCredentials> <sharedSecret issuerName="[YOUR-ISSUER-NAME]" issuerSecret="[YOUR-ISSUER-KEY]" /> </clientCredentials> </transportClientEndpointBehavior> </behavior> <behavior name="SharedSecretCredentials"> ... </endpointBehaviors></behaviors>

Note: The clientCredentials behaviors define a service certificate. A service certificate is used by a client to authenticate the service and provide message protection. This configuration references a "[YOUR_SERVICE_NAMESPACE].servicebus.windows.net" X.509 certificate installed in this task.

6. Assign the endpoint behavior by changing the value of the behaviorConfiguration attribute in the client’s endpoint configuration from SharedSecretCredentials to ClientCertificateBehavior, as shown below (in bold text).

Page 74

Page 75: Part 1: Introduction to the AppFabric Service Busbandgap.cs.rice.edu/classes/comp410/resources/Using Azure... · Web viewThis lab covers the basics of the AppFabric Service Bus. It

XML

<client> <endpoint name="RelayEndpoint" contract="MulticastSample.IMulticastContract" binding="netEventRelayBinding" bindingConfiguration="lab" behaviorConfiguration="ClientCertificateBehavior" /></client>

7. Configure the security of the netEventRelayBinding to use message security and certificate credentials. To do this, insert a security element inside the binding section as shown below (in bold text).

XML

<bindings> <netEventRelayBinding> <binding name="lab" receiveTimeout="00:05:00"> <security mode="Message"> <message clientCredentialType="Certificate" /> </security> </binding> </netEventRelayBinding></bindings>

Note: You can now follow the steps at the end of Task 2 to verify that the chat application continues to work as expected. If you configure tracing and message logging, you will realize that transport level traces show encrypted payloads.

Summary

By completing this hands-on lab, you’ve learnt to create a service namespace domain and to host and consume your services using the AppFabric Service Bus. Additionally, you’ve seen how to connect a WCF Service hosted in IIS7.5 to the Service Bus and how to automatically activate the service. Finally, you’ve learnt to implement a multicast messaging service, using the netEventRelayBinding binding, and to use X.509 certificates for message confidentiality.

Page 75