Hands-On Lab

Service Bus Messaging

Lab version:1.0.0

Last updated:12/9/2018

Contents

Overview

Getting Started: Creating a Service Bus Namespace

Task 1 – Creating your Service Bus Namespace

Exercise 1: Using Queues

Task 1 – Creating a Queue

Task 2 – Sending a Message

Task 3 – Receiving Messages

Verification

Exercise 2: Using Topics and Subscriptions

Task 1 – Creating a Topic and Adding Subscriptions

Task 2 – Using a Subscription Rule Filter Expression

Task 3 – Using a Subscription Rule Filter Action

Task 4 – Sending Messages

Task 5 – Receiving Messages

Verification

Summary

Overview

Service Bus Messaging contains a brand-new set of cloud-based, message-oriented-middleware technologies including a fully-featured Message Queue with support for arbitrary content types, rich message properties, correlation, reliable binary transfer, and grouping. Another new feature isService Bus Topics which provide a set of new publish-and-subscribe capabilities and are based on the same backend infrastructure as Service Bus Queues. A Topic consists of a sequential message store just like a Queue, but allows for many concurrent and durable Subscriptions that can independently yield copies of the published messages to consumers. Each Subscription can define a set of rules with simple expressions that specify which messages from the published sequence are selected into the Subscription.

Objectives

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

  • Create a Queue.
  • Send and Receive Messages through a Queue.
  • Inspect Message Properties.
  • Create Topics and Subscriptions.
  • Use Subscription Filter Expressions.
  • Use Subscription Filter Actions.

Prerequisites

You must have the following items to complete this lab:

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

Setup

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

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

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

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 theAssets\Setup.docx document, which contains a section describing how to use them.

Exercises

This hands-on Lab includes the following exercises:

  1. Using Queues
  2. Usings Topics and Subscriptions

Estimated time to complete this lab: 60 minutes.

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

Getting Started: Creating a Service Bus Namespace

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

Task 1 – Creating your Service Bus Namespace

In this task, you will create a new Windows Azure Service Bus Namespace.

  1. Navigate to the Windows Azure 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 the Service Bus item under theServiceselement.

Figure 1

Configuring Windows Azure Service bus

  1. 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 theNewbutton on the upper ribbon bar.

Figure 2

Creating a New Namespace

  1. On the left list, check all the available services. Enter a namefor your service Namespace, select a Region for your service to run in,choose the Subscription and a Cache Size andclick Create Namespace. 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.

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

Figure 4

Summary page listing available service namespaces

  1. In the Properties right pane, locate the Service Bus section and click the Default KeyView button.

Figure 5

Summary page listing available service namespaces

  1. Record the value shown for Default Issuer andDefault Key, and click OK. You will need these values later when configuring your Web Role settings.

Figure 6

Service Bus default keys

You have now created a new Windows Azure namespace for this hands-on lab. To sign in at any time, simply navigate to the Windows Azure Management Portal, click Sign In and provide your Live ID credentials.

Exercise 1: UsingQueues

In this exercise, you will learn how to create and use a Service Bus Queue. You will set up a MVC 3 application to communicate with your Service Bus Namespace, create a new Queue and learn how to send and receive messages from it.

Task 1 – Creating a Queue

In this task, you will create a new Queue into your Service Bus namespace.

  1. Open Microsoft Visual Studio 2010elevated as Administrator from Start | All Programs | Microsoft Visual Studio 2010 | Microsoft Visual Studio 2010.
  2. Open the solution file located atEx01-UsingQueues\begin\Begin.slnin the Sourcefolder of this lab.
  3. Update the service definition to define the configuration settings required to access your Service Bus namespace. To do this, expand the Roles folder of the UsingQueues project in Solution Explorer, right-click UsingQueues.Web, and then select Properties.

Figure 7

Launching the service configuration editor

  1. Select the Settingstab, click Add Setting and create a new configuration setting namednamespaceAddress. Set its type to String, and set its value with the name of your Service Bus namespace. Add two new keys and name them issuerName and issuerKey, set its type to String and their values with the ones you previously copied from the Windows Azure Management Portal.

Figure 8

Adding settings to the UsingQueues.Web Web Role

  1. Press CTRL + S to save the changes to the Web Role configuration.
  2. Next, you will add the required assemblies to the ASP.NET MVC 3 Web project to connect to the Windows Azure Service Bus from your application. In Solution Explorer, right-click on UsingQueues.Webproject node and select Add Reference.
  3. In the Add Reference dialog, switch to the .NET tab, select the Microsoft.ServiceBusassembly and click OK.Repeat the step to add the Microsoft.WindowsAzure.ServiceRuntime and the System.Runtime.Serializationassemblies.
  4. Open the HomeController.cs file under the Controllers folder in theUsingQueues.Webproject.
  5. Add the following namespace directives to declare the Service Bus and the Windows Azure supporting assemblies, and a reference to the Models namespace of the Web project, which you will use in the next tasks.

(Code Snippet – Service Bus Queues and Topics – Ex01 – Adding Namespace Directives- CS)

C#

usingMicrosoft.ServiceBus;

usingMicrosoft.ServiceBus.Messaging;

usingMicrosoft.WindowsAzure.ServiceRuntime;

usingUsingQueues.Web.Models;

  1. Add two properties to the HomeControllerclass to enable the communication with the Service Bus Queue.

(Code Snippet – Service Bus Queues and Topics – Ex01 – Service Bus Properties - CS)

C#

privateNamespaceManagernamespaceManager;

privateMessagingFactorymessagingFactory;

  1. In order to create a Queue, we have to connect to the Service Bus Namespace address and bind this namespace to a MessagingFactory. This class is in charge of creating the entities responsible forsending and receiving messages through Queues.Add inside the default constructor of the HomeControllerclass the following code:

(Code Snippet – Service Bus Queues and Topics – Ex01 –HomeControllerConstructor - CS)

C#

publicHomeController()

{

varbaseAddress = RoleEnvironment.GetConfigurationSettingValue("namespaceAddress");

varissuerName = RoleEnvironment.GetConfigurationSettingValue("issuerName");

varissuerKey = RoleEnvironment.GetConfigurationSettingValue("issuerKey");

UrinamespaceAddress = ServiceBusEnvironment.CreateServiceUri("sb", baseAddress, string.Empty);

this.namespaceManager = newNamespaceManager(namespaceAddress, TokenProvider.CreateSharedSecretTokenProvider(issuerName, issuerKey));

this.messagingFactory = MessagingFactory.Create(namespaceAddress, TokenProvider.CreateSharedSecretTokenProvider(issuerName, issuerKey));

}

  1. Add the following method to the HomeController class. This method uses the namespaceClient object to create a new Queue.

(Code Snippet – Service Bus Queues and Topics – Ex01 - CreateQueue - CS)

C#

[HttpPost]

publicJsonResultCreateQueue(stringqueueName)

{

try

{

varqueueDescription = this.namespaceManager.CreateQueue(queueName);

returnJson(queueDescription, JsonRequestBehavior.AllowGet);

}

catch (Exception e)

{

returnJson(false, JsonRequestBehavior.AllowGet);

}

}

  1. Press CTRL + S to save the changes to the Controller.

Task 2 – Sending a Message

In this task, you learn how to send a message through a Queue.You can send any serializable object as a Message through Queues.You will send a CustomMessage object which has its own properties and is agnostic on how the Service Bus Queue works or interacts with your application.

  1. Create a new class under the Models folder of the UsingQueues.Webproject. To do this, right-clicking the folder, select Add and then Class. In the Add New Item dialog, set the name of the class to CustomMessage.
  2. Replace the entire code of the class with the following:

(Code Snippet – Service Bus Queues and Topics – Ex01 – CustomMessage Class - CS)

C#

namespaceUsingQueues.Web.Models

{

using System;

[Serializable]

publicclassCustomMessage

{

privateDateTime date;

privatestring body;

publicDateTime Date

{

get { returnthis.date; }

set { this.date = value; }

}

publicstring Body

{

get { returnthis.body; }

set { this.body = value; }

}

}

}

  1. Press CTRL + S to save the changes.
  2. Next, you will create the method in the HomeControllerclass that allows you to send your custom object to a Queue.Open the HomeController.cs file under the Controllers folder in the UsingQueues.Webproject.
  3. Add the following method to the class.

(Code Snippet – Service Bus Queues and Topics – Ex01 - NewCustomMessage - CS)

C#

[HttpPost]

publicJsonResultSendMessage(stringqueueName, string message)

{

QueueClientqueueClient = this.messagingFactory.CreateQueueClient(queueName);

varcustomMessage = newCustomMessage() { Date = DateTime.Now, Body = message };

long? messagesInQueue = null;

}

  1. Next, you will instantiatea CustomMessageobject and set itsDate property with the current date and itsBody propertywith the text youreceive from the UI. This way you are sending aplain text message through a Queue along with additional, useful information for processing the messages received from Queues.In order to do this, add the following bolded code inside the SendMessage method:

(Code Snippet – Service Bus Queues and Topics – Ex01 – Send BrokeredMessage - CS)

C#

[HttpPost]

publicJsonResultSendMessage(stringqueueName, string message)

{

QueueClientqueueClient = this.messagingFactory.CreateQueueClient(queueName);

varcustomMessage = newCustomMessage() { Date = DateTime.Now, Body = message };

long? messagesInQueue = null;

BrokeredMessagebm = newBrokeredMessage(customMessage);

try

{

queueClient.Send(bm);

messagesInQueue = this.GetMessageCount(queueName);

}

catch

{

// TODO: do something

}

returnJson(messagesInQueue, JsonRequestBehavior.AllowGet);

}

  1. The BrokeredMessage class has a property named Properties, which is a Dictionary of String/Object key value pairs. You can set your own custom pair of key-values, and use them as needed. These properties are independent of your custom object and intended to be used in the Messaging Logic. You will add two predefined properties that will be inspected when you retrieve the message from the Queue. Add the following highlighted code inside the SendMessage method:

(Code Snippet – Service Bus Queues and Topics – Ex01 – Add Custom Properties - CS)

C#

[HttpPost]

publicJsonResultSendMessage(stringqueueName, string message)

{

QueueClientqueueClient = this.messagingFactory.CreateQueueClient(queueName);

varcustomMessage = newCustomMessage() { Date = DateTime.Now, Body = message };

long? messagesInQueue = null;

BrokeredMessagebm = newBrokeredMessage(customMessage);

bm.Properties["Urgent"] = "1";

bm.Properties["Priority"] = "High";

try

{

queueClient.Send(bm);

messagesInQueue = this.GetMessageCount(queueName);

}

catch

{

// TODO: do something

}

returnJson(messagesInQueue, JsonRequestBehavior.AllowGet);

}

Note: You will see custom properties in actionin the Exercise 2, Task 3 and 4 of this lab.

  1. Press CTRL + S to save the changes to the Controller.

Task 3 – Receiving Messages

In the previous task, we instantiate a QueueClient in order to send messages to a Queue. In this task you learn how to use a QueueClient, to receive a message from a Queue and explore the properties inside the received message.

  1. If not already opened, open the HomeController.cs file under the Controllers folder in the UsingQueues.Webproject.
  2. Add the following method in the class declaration:

(Code Snippet – Service Bus Queues and Topics – Ex01 –RetrieveMessage from a Queue - CS)

C#

[HttpGet, OutputCache(NoStore = true, Duration = 0, VaryByParam = "*")]

publicJsonResultRetrieveMessage(stringqueueName)

{

QueueClientqueueClient = this.messagingFactory.CreateQueueClient(queueName, ReceiveMode.PeekLock);

BrokeredMessagereceivedMessage = queueClient.Receive(new TimeSpan(0,0,30));

if (receivedMessage == null)

{

returnJson(null, JsonRequestBehavior.AllowGet);

}

varreceivedCustomMessage = receivedMessage.GetBodyCustomMessage>();

varbrokeredMsgProperties = newDictionarystring, object>();

brokeredMsgProperties.Add("Size", receivedMessage.Size);

brokeredMsgProperties.Add("MessageId", receivedMessage.MessageId.Substring(0, 15) + "...");

brokeredMsgProperties.Add("TimeToLive", receivedMessage.TimeToLive.TotalSeconds);

brokeredMsgProperties.Add("EnqueuedTimeUtc", receivedMessage.EnqueuedTimeUtc.ToString("yyyy-MM-ddHH:mm:ss"));

brokeredMsgProperties.Add("ExpiresAtUtc", receivedMessage.ExpiresAtUtc.ToString("yyyy-MM-ddHH:mm:ss"));

varmessageInfo = new

{

Label = receivedMessage.Label,

Date = receivedCustomMessage.Date,

Message = receivedCustomMessage.Body,

Properties = receivedMessage.Properties.ToArray(),

BrokeredMsgProperties = brokeredMsgProperties.ToArray()

};

receivedMessage.Complete();

returnJson(new { MessageInfo = messageInfo, MessagesInQueue = this.GetMessageCount(queueName) }, JsonRequestBehavior.AllowGet);

}

  1. The UI requires a way to retrieve the names of the existent queues in the Service Bus and another method to count the number of messages in a specific Queue. For this, add the following ActionMethodsat the end of the HomeControllerclass:

(Code Snippet – Service Bus Queues and Topics – Ex01 – GetQueues and Count- CS)

C#

[OutputCache(NoStore = true, Duration = 0, VaryByParam = "*")]

publicJsonResult Queues()

{

var queues = this.namespaceManager.GetQueues().Select(c => new { Name = c.Path, Messages = c.MessageCount }).ToArray();

returnJson(queues, JsonRequestBehavior.AllowGet);

}

publiclongGetMessageCount(stringqueueName)

{

varqueueDescription = this.namespaceManager.GetQueue(queueName);

returnqueueDescription.MessageCount;

}

  1. Press CTRL + S to save the changes to the Controller.

Verification

You now launch the updated application in the Windows Azure compute emulator to verify that you can create a Queue, send messages to a specific Queue and also receive messages from a Queue.

  1. In Visual Studio, pressF5 to launch the application. The browser will show the default page of the application.

Figure 9

UsingQueues Application Home Page

  1. In the panel named Queues, enter a Queue name in the textbox (like MyQueue) and click Create.

Figure 10

Creating a Queue

Figure 11

The application displays a message when a Queue was successfullycreated

  1. In the Send Message panel, select the previously created Queue from the dropdown list, enter a message in the Textbox, and click Send. Your message will be sent to the Queue.

Figure 12

Sending a Message to the Queue

  1. If not selected, in the dropdown list of theReceive Message panel select the Queue you used in the previous step and then click the Retrieve First Message in Queue button. The Message will be shown in the panel along with its custom properties.

Figure 13

Retrieving the First Message in the Queue

  1. Close Internet Explorer.

Exercise 2: Using Topics and Subscriptions

In this exercise you will learn to create a Topic and add Subscriptions to it. Subscriptions works like a Queue but you can apply filters on it to retrieve only the messages relevant to that Subscription. When you send a Message to a Topic, all the subscriptions verifies if the message has a match with its own subscription rules. If there is a match, the subscription will contain a virtual copy of the message. This is useful to avoid sending multiple messages to different subscriptions. Sending a single message to a Topic will distribute along different Subscriptions by checking Rule Expressions. Additionally, you will learn how to apply Filter Actions to Subscriptions to modify the BrokeredMessage properties of the messages that match a custom rule.

Task 1 – Creatinga Topic and Adding Subscriptions

In this task, you will learn how to create a new Topic and add several subscriptions to it. For this, first you will add the necessary configurations to connect to your Service Bus namespace.