38
Hands-On Lab Service Bus Messaging Lab version: 1.0.0 Last updated: 4/13/2022 Page 1

az12722.vo.msecnd.netaz12722.vo.msecnd.net/.../servicebusmessaging1-0-1/Lab.docx · Web viewIn this exercise you will learn to create a Topic and add Subscriptions to it. Subscriptions

  • Upload
    others

  • View
    0

  • Download
    0

Embed Size (px)

Citation preview

Page 1: az12722.vo.msecnd.netaz12722.vo.msecnd.net/.../servicebusmessaging1-0-1/Lab.docx · Web viewIn this exercise you will learn to create a Topic and add Subscriptions to it. Subscriptions

Hands-On LabService Bus MessagingLab version: 1.0.0

Last updated: 5/18/2023

Page 1

Page 2: az12722.vo.msecnd.netaz12722.vo.msecnd.net/.../servicebusmessaging1-0-1/Lab.docx · Web viewIn this exercise you will learn to create a Topic and add Subscriptions to it. Subscriptions

CONTENTS

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

GETTING STARTED: CREATING A SERVICE BUS NAMESPACE.........................................................5Task 1 – Creating your Service Bus Namespace...................................................................................5

EXERCISE 1: USING QUEUES.................................................................................................................. 8Task 1 – Creating a Queue...................................................................................................................9

Task 2 – Sending a Message..............................................................................................................12

Task 3 – Receiving Messages.............................................................................................................15

Verification........................................................................................................................................16

EXERCISE 2: USING TOPICS AND SUBSCRIPTIONS...........................................................................20Task 1 – Creating a Topic and Adding Subscriptions..........................................................................21

Task 2 – Using a Subscription Rule Filter Expression.........................................................................22

Task 3 – Using a Subscription Rule Filter Action................................................................................23

Task 4 – Sending Messages................................................................................................................24

Task 5 – Receiving Messages.............................................................................................................25

Verification........................................................................................................................................28

SUMMARY................................................................................................................................................ 34

Page 2

Page 3: az12722.vo.msecnd.netaz12722.vo.msecnd.net/.../servicebusmessaging1-0-1/Lab.docx · Web viewIn this exercise you will learn to create a Topic and add Subscriptions to it. Subscriptions

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 is Service 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 in this hands-on lab you need to set up your environment.

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

Page 3

Page 4: az12722.vo.msecnd.netaz12722.vo.msecnd.net/.../servicebusmessaging1-0-1/Lab.docx · Web viewIn this exercise you will learn to create a Topic and add Subscriptions to it. Subscriptions

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

Exercises

This hands-on Lab includes the following exercises:

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

Page 4

Page 5: az12722.vo.msecnd.netaz12722.vo.msecnd.net/.../servicebusmessaging1-0-1/Lab.docx · Web viewIn this exercise you will learn to create a Topic and add Subscriptions to it. Subscriptions

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 the Services element.

Figure 1

Page 5

Page 6: az12722.vo.msecnd.netaz12722.vo.msecnd.net/.../servicebusmessaging1-0-1/Lab.docx · Web viewIn this exercise you will learn to create a Topic and add Subscriptions to it. Subscriptions

Configuring Windows Azure Service bus

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

Figure 2Creating a New Namespace

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

Page 6

Page 7: az12722.vo.msecnd.netaz12722.vo.msecnd.net/.../servicebusmessaging1-0-1/Lab.docx · Web viewIn this exercise you will learn to create a Topic and add Subscriptions to it. Subscriptions

Figure 3Creating 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.

Figure 4

Page 7

Page 8: az12722.vo.msecnd.netaz12722.vo.msecnd.net/.../servicebusmessaging1-0-1/Lab.docx · Web viewIn this exercise you will learn to create a Topic and add Subscriptions to it. Subscriptions

Summary page listing available service namespaces

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

Figure 5Summary page listing available service namespaces

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

Figure 6Service 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: Using Queues

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.

Page 8

Page 9: az12722.vo.msecnd.netaz12722.vo.msecnd.net/.../servicebusmessaging1-0-1/Lab.docx · Web viewIn this exercise you will learn to create a Topic and add Subscriptions to it. Subscriptions

Task 1 – Creating a Queue

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

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

2. Open the solution file located at Ex01-UsingQueues\begin\Begin.sln in the Source folder 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 7Launching the service configuration editor

4. Select the Settings tab, click Add Setting and create a new configuration setting named namespaceAddress. 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 .

Page 9

Page 10: az12722.vo.msecnd.netaz12722.vo.msecnd.net/.../servicebusmessaging1-0-1/Lab.docx · Web viewIn this exercise you will learn to create a Topic and add Subscriptions to it. Subscriptions

Figure 8Adding settings to the UsingQueues.Web Web Role

5. Press CTRL + S to save the changes to the Web Role configuration.

6. 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.Web project node and select Add Reference.

7. In the Add Reference dialog, switch to the .NET tab, select the Microsoft.ServiceBus assembly and click OK. Repeat the step to add the Microsoft.WindowsAzure.ServiceRuntime and the System.Runtime.Serialization assemblies.

8. Open the HomeController.cs file under the Controllers folder in the UsingQueues.Web project.

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

using Microsoft.ServiceBus;using Microsoft.ServiceBus.Messaging;using Microsoft.WindowsAzure.ServiceRuntime;using UsingQueues.Web.Models;

10. Add two properties to the HomeController class to enable the communication with the Service Bus Queue.

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

C#

Page 10

Page 11: az12722.vo.msecnd.netaz12722.vo.msecnd.net/.../servicebusmessaging1-0-1/Lab.docx · Web viewIn this exercise you will learn to create a Topic and add Subscriptions to it. Subscriptions

private NamespaceManager namespaceManager;private MessagingFactory messagingFactory;

11. 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 for sending and receiving messages through Queues. Add inside the default constructor of the HomeController class the following code:

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

C#

public HomeController(){ var baseAddress = RoleEnvironment.GetConfigurationSettingValue("namespaceAddress"); var issuerName = RoleEnvironment.GetConfigurationSettingValue("issuerName"); var issuerKey = RoleEnvironment.GetConfigurationSettingValue("issuerKey");

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

this.namespaceManager = new NamespaceManager(namespaceAddress, TokenProvider.CreateSharedSecretTokenProvider(issuerName, issuerKey)); this.messagingFactory = MessagingFactory.Create(namespaceAddress, TokenProvider.CreateSharedSecretTokenProvider(issuerName, issuerKey));}

12. 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]public JsonResult CreateQueue(string queueName){ try { var queueDescription = this.namespaceManager.CreateQueue(queueName); return Json(queueDescription, JsonRequestBehavior.AllowGet); } catch (Exception e) { return Json(false, JsonRequestBehavior.AllowGet);

Page 11

Page 12: az12722.vo.msecnd.netaz12722.vo.msecnd.net/.../servicebusmessaging1-0-1/Lab.docx · Web viewIn this exercise you will learn to create a Topic and add Subscriptions to it. Subscriptions

}}

13. 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.Web project. 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#

namespace UsingQueues.Web.Models{ using System;

[Serializable] public class CustomMessage { private DateTime date; private string body;

public DateTime Date { get { return this.date; } set { this.date = value; } } public string Body { get { return this.body; } set { this.body = value; } } }}

3. Press CTRL + S to save the changes.

Page 12

Page 13: az12722.vo.msecnd.netaz12722.vo.msecnd.net/.../servicebusmessaging1-0-1/Lab.docx · Web viewIn this exercise you will learn to create a Topic and add Subscriptions to it. Subscriptions

4. Next, you will create the method in the HomeController class that allows you to send your custom object to a Queue. Open the HomeController.cs file under the Controllers folder in the UsingQueues.Web project.

5. Add the following method to the class.

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

C#

[HttpPost]public JsonResult SendMessage(string queueName, string message){ QueueClient queueClient = this.messagingFactory.CreateQueueClient(queueName); var customMessage = new CustomMessage() { Date = DateTime.Now, Body = message }; long? messagesInQueue = null;}

6. Next, you will instantiate a CustomMessage object and set its Date property with the current date and its Body property with the text you receive from the UI. This way you are sending a plain 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]public JsonResult SendMessage(string queueName, string message){ QueueClient queueClient = this.messagingFactory.CreateQueueClient(queueName); var customMessage = new CustomMessage() { Date = DateTime.Now, Body = message }; long? messagesInQueue = null;

BrokeredMessage bm = new BrokeredMessage(customMessage);

try { queueClient.Send(bm); messagesInQueue = this.GetMessageCount(queueName); } catch { // TODO: do something

Page 13

Page 14: az12722.vo.msecnd.netaz12722.vo.msecnd.net/.../servicebusmessaging1-0-1/Lab.docx · Web viewIn this exercise you will learn to create a Topic and add Subscriptions to it. Subscriptions

}

return Json(messagesInQueue, JsonRequestBehavior.AllowGet);}

7. 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]public JsonResult SendMessage(string queueName, string message){ QueueClient queueClient = this.messagingFactory.CreateQueueClient(queueName); var customMessage = new CustomMessage() { Date = DateTime.Now, Body = message }; long? messagesInQueue = null;

BrokeredMessage bm = new BrokeredMessage(customMessage); bm.Properties["Urgent"] = "1"; bm.Properties["Priority"] = "High";

try { queueClient.Send(bm); messagesInQueue = this.GetMessageCount(queueName); } catch { // TODO: do something }

return Json(messagesInQueue, JsonRequestBehavior.AllowGet);}

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

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

Page 14

Page 15: az12722.vo.msecnd.netaz12722.vo.msecnd.net/.../servicebusmessaging1-0-1/Lab.docx · Web viewIn this exercise you will learn to create a Topic and add Subscriptions to it. Subscriptions

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

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 = "*")]public JsonResult RetrieveMessage(string queueName){ QueueClient queueClient = this.messagingFactory.CreateQueueClient(queueName, ReceiveMode.PeekLock); BrokeredMessage receivedMessage = queueClient.Receive(new TimeSpan(0,0,30));

if (receivedMessage == null) { return Json(null, JsonRequestBehavior.AllowGet); }

var receivedCustomMessage = receivedMessage.GetBody<CustomMessage>();

var brokeredMsgProperties = new Dictionary<string, 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-dd HH:mm:ss")); brokeredMsgProperties.Add("ExpiresAtUtc", receivedMessage.ExpiresAtUtc.ToString("yyyy-MM-dd HH:mm:ss"));

var messageInfo = new { Label = receivedMessage.Label, Date = receivedCustomMessage.Date, Message = receivedCustomMessage.Body, Properties = receivedMessage.Properties.ToArray(), BrokeredMsgProperties = brokeredMsgProperties.ToArray() };

Page 15

Page 16: az12722.vo.msecnd.netaz12722.vo.msecnd.net/.../servicebusmessaging1-0-1/Lab.docx · Web viewIn this exercise you will learn to create a Topic and add Subscriptions to it. Subscriptions

receivedMessage.Complete(); return Json(new { MessageInfo = messageInfo, MessagesInQueue = this.GetMessageCount(queueName) }, JsonRequestBehavior.AllowGet);}

3. 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 ActionMethods at the end of the HomeController class:

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

C#

[OutputCache(NoStore = true, Duration = 0, VaryByParam = "*")]public JsonResult Queues(){ var queues = this.namespaceManager.GetQueues().Select(c => new { Name = c.Path, Messages = c.MessageCount }).ToArray(); return Json(queues, JsonRequestBehavior.AllowGet);}

public long GetMessageCount(string queueName){ var queueDescription = this.namespaceManager.GetQueue(queueName); return queueDescription.MessageCount;}

4. 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, press F5 to launch the application. The browser will show the default page of the application.

Page 16

Page 17: az12722.vo.msecnd.netaz12722.vo.msecnd.net/.../servicebusmessaging1-0-1/Lab.docx · Web viewIn this exercise you will learn to create a Topic and add Subscriptions to it. Subscriptions

Figure 9UsingQueues Application Home Page

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

Page 17

Page 18: az12722.vo.msecnd.netaz12722.vo.msecnd.net/.../servicebusmessaging1-0-1/Lab.docx · Web viewIn this exercise you will learn to create a Topic and add Subscriptions to it. Subscriptions

Figure 10Creating a Queue

Figure 11The application displays a message when a Queue was successfully created

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

Page 18

Page 19: az12722.vo.msecnd.netaz12722.vo.msecnd.net/.../servicebusmessaging1-0-1/Lab.docx · Web viewIn this exercise you will learn to create a Topic and add Subscriptions to it. Subscriptions

Figure 12Sending a Message to the Queue

4. If not selected, in the dropdown list of the Receive 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.

Page 19

Page 20: az12722.vo.msecnd.netaz12722.vo.msecnd.net/.../servicebusmessaging1-0-1/Lab.docx · Web viewIn this exercise you will learn to create a Topic and add Subscriptions to it. Subscriptions

Figure 13Retrieving the First Message in the Queue

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

Page 20

Page 21: az12722.vo.msecnd.netaz12722.vo.msecnd.net/.../servicebusmessaging1-0-1/Lab.docx · Web viewIn this exercise you will learn to create a Topic and add Subscriptions to it. Subscriptions

Task 1 – Creating a 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.

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

2. Open the begin.sln solution file from \Source\Ex02-UsingTopicsAndSubscriptions\begin\.

3. Set up your own Service Bus namespace settings in the Service Configuration files. To do this, in Solution Explorer expand the Roles folder in the UsingTopics project, right-click UsingTopics.Web and then select Properties.

Figure 14Launching the Service Configuration editor

4. In the Settings tab, click Add Settings and create a new configuration setting named namespaceAddress. Set its type to String and its value with the name of your Service Bus namespace. Add two new keys and name them issuerName and issuerKey, and set its type to String and their values with the ones you previously copied from the Windows Azure Management Portal.

Page 21

Page 22: az12722.vo.msecnd.netaz12722.vo.msecnd.net/.../servicebusmessaging1-0-1/Lab.docx · Web viewIn this exercise you will learn to create a Topic and add Subscriptions to it. Subscriptions

Figure 15Adding settings to the UsingTopics.Web Web Role

5. Press CTRL + S to save the changes to the Web Role configuration.

6. Open the HomeController.cs file under the Controllers folder in the UsingTopics.Web project.

Note: In the previous Exercise, you created a connection to the Service Bus Namespace inside the Constructor method of the HomeController class. For the current Exercise, this was already added for you in the Solution. For more information, refer to the step 12 of Task 1 in Exercise 1.

7. You will create a new Topic with two Subscription, named AllMessages, and UrgentMessages. To do this, add the following method at the end of the HomeController class.

(Code Snippet – Service Bus Queues and Topics – Ex02 – Create Topic and subscriptions - CS)

C#

[HttpPost]public JsonResult CreateTopic(string topicName){ bool success; try { var topic = this.namespaceManager.CreateTopic(topicName); var allMessagesSubscription =

this.namespaceManager.CreateSubscription(topic.Path, "AllMessages"); var urgentMessagesSubscription =

this.namespaceManager.CreateSubscription(topic.Path, "UrgentMessages");

success = true; } catch (Exception) { success = false; }

return Json(success, JsonRequestBehavior.AllowGet);}

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

Task 2 – Using a Subscription Rule Filter Expression

Page 22

Page 23: az12722.vo.msecnd.netaz12722.vo.msecnd.net/.../servicebusmessaging1-0-1/Lab.docx · Web viewIn this exercise you will learn to create a Topic and add Subscriptions to it. Subscriptions

Rule Filters are used in Subscriptions to retrieve messages that match certain rules. That way you can send one message to a Topic, but it virtually replicates through multiple Subscriptions.

1. If not already opened, open the HomeController.cs file under the Controllers folder in the UsingTopics.Web project.

2. In the previous task, you created a Topic with two Subscriptions. Now, you will replace a line of that code to include a SqlFilter to the UrgentMessages Subscription. With this filter, the UrgentMessages subscription will get only the messages that match the rule Urgent = ‘1’. Replace the code you added in the previous task with the following highlighted code.

(Code Snippet – Service Bus Queues and Topics – Ex02 – Create Topic and Subscriptions with Rule Filters - CS)

C#

[HttpPost]public JsonResult CreateTopic(string topicName){ bool success; try { var topic = this.namespaceManager.CreateTopic(topicName); var allMessagesSubscription =

this.namespaceManager.CreateSubscription(topic.Path, "AllMessages"); var urgentMessagesSubscription =

this.namespaceManager.CreateSubscription(topic.Path, "UrgentMessages", new SqlFilter("Urgent = '1'"));

...}

Note: Take into account that you can use SQL92 as Filter Expressions.

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

Task 3 – Using a Subscription Rule Filter Action

Additionally to Rule Filter Expressions, you can use Rule Filter Actions. With this, you can modify the properties of a BrokeredMessage that matches the specified rule. You will create a new Subscription named HighPriorityMessages containing a custom Rule Filter Action. All messages that match the rule Urgent = ‘1’ will be sent to that Subscription with the property Priority set to ‘High’.

Note: Both Filter Expressions and Filter Actions use the properties declared in the BrokeredMessage dictionary named Properties. These rules won’t apply on custom objects inside the body of the BrokeredMessage.

Page 23

Page 24: az12722.vo.msecnd.netaz12722.vo.msecnd.net/.../servicebusmessaging1-0-1/Lab.docx · Web viewIn this exercise you will learn to create a Topic and add Subscriptions to it. Subscriptions

1. If not already opened, open the HomeController.cs file under the Controllers folder in the UsingTopics.Web project.

2. Create a new Subscription object with a RuleDescription. Within this object, you can set a Filter and an Action. This way, if the Filter matches, the specific Action is applied to the BrokeredMessage. In the CreateTopic Action Method, add the highlighted code.

(Code Snippet – Service Bus Queues and Topics – Ex02 – Create Subscription with Action Filter – CS)

C#

[HttpPost]public JsonResult CreateTopic(string topicName){ bool success; try { var topic = this.namespaceManager.CreateTopic(topicName); var allMessagesSubscription =

this.namespaceManager.CreateSubscription(topic.Path, "AllMessages"); var urgentMessagesSubscription =

this.namespaceManager.CreateSubscription(topic.Path, "UrgentMessages", new SqlFilter("Urgent = '1'"));

var ruleDescription = new RuleDescription() { Filter = new SqlFilter("Important= '1' OR Priority = 'High'"), Action = new SqlRuleAction("set Priority= 'High'") }; var highPriorityMessagesSubscription =

this.namespaceManager.CreateSubscription(topic.Path, "HighPriorityMessages", ruleDescription);

success = true; } catch (Exception) { success = false; }

return Json(success, JsonRequestBehavior.AllowGet);}

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

Task 4 – Sending Messages

Page 24

Page 25: az12722.vo.msecnd.netaz12722.vo.msecnd.net/.../servicebusmessaging1-0-1/Lab.docx · Web viewIn this exercise you will learn to create a Topic and add Subscriptions to it. Subscriptions

In this task, you will send messages to a Topic and verify that each message arrives to the proper Subscription. You are going to use the same approach of Exercise 1, sending a serializable object as the Message with custom properties on it.

1. If not already opened, open the HomeController.cs file under the Controllers folder in the UsingTopics.Web project.

2. In order to send a Message you will create a TopicClient using the MessagingFactory. Next, you will create a CustomMessage, add it to the BrokeredMessage and then you will set the Urgent, Important and Priority properties with the values you receive from the UI. Finally, you will use the TopicClient to send the message to the Topic. Add the following method at the end of the HomeController class.

(Code Snippet – Service Bus Queues and Topics – Ex02 – SendMessage – CS)

C#

[HttpPost]public JsonResult SendMessage(string topicName, string message, bool

isUrgent, bool isImportant){ TopicClient topicClient =

this.messagingFactory.CreateTopicClient(topicName); var customMessage = new CustomMessage() { Body = message, Date =

DateTime.Now }; bool success = false;

BrokeredMessage bm = new BrokeredMessage(customMessage); bm.Properties["Urgent"] = isUrgent ? "1" : "0"; bm.Properties["Important"] = isImportant ? "1" : "0"; bm.Properties["Priority"] = "Low";

try { topicClient.Send(bm); success = true; } catch (Exception e) { // TODO: do something }

return Json(success, JsonRequestBehavior.AllowGet);}

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

Page 25

Page 26: az12722.vo.msecnd.netaz12722.vo.msecnd.net/.../servicebusmessaging1-0-1/Lab.docx · Web viewIn this exercise you will learn to create a Topic and add Subscriptions to it. Subscriptions

Task 5 – Receiving Messages

In this task, you will learn how to receive messages from a subscription. You will use a very similar logic used in Exercise 1, but in this case you will instantiate a MessageReceiver object from a SubscriptionClient.

1. If not already opened, open the HomeController.cs file under the Controllers folder in the UsingTopics.Web project.

2. Add the following code at the end of the HomeController class.

(Code Snippet – Service Bus Queues and Topics – Ex02 – RetrieveMessages – CS)

C#

[HttpGet, OutputCache(NoStore = true, Duration = 0, VaryByParam = "*")]public JsonResult RetrieveMessage(string topicName, string

subscriptionName){ SubscriptionClient subscriptionClient =

this.messagingFactory.CreateSubscriptionClient(topicName, subscriptionName, ReceiveMode.PeekLock);

BrokeredMessage receivedMessage = subscriptionClient.Receive(new TimeSpan(0,0,30));

if (receivedMessage == null) { return Json(null, JsonRequestBehavior.AllowGet); }

var receivedCustomMessage = receivedMessage.GetBody<CustomMessage>();

var brokeredMsgProperties = new Dictionary<string, 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-dd HH:mm:ss")); brokeredMsgProperties.Add("ExpiresAtUtc",

receivedMessage.ExpiresAtUtc.ToString("yyyy-MM-dd HH:mm:ss"));

var messageInfo = new { Label = receivedMessage.Label, Date = receivedCustomMessage.Date, Message = receivedCustomMessage.Body, Properties = receivedMessage.Properties.ToArray(), BrokeredMsgProperties = brokeredMsgProperties.ToArray() };

Page 26

Page 27: az12722.vo.msecnd.netaz12722.vo.msecnd.net/.../servicebusmessaging1-0-1/Lab.docx · Web viewIn this exercise you will learn to create a Topic and add Subscriptions to it. Subscriptions

receivedMessage.Complete(); return Json(messageInfo, JsonRequestBehavior.AllowGet);}

Note: In this code you are also adding additional information of the message that you will show in the UI.

3. Add the following code at the end of the HomeController class to retrieve the topics and subscriptions data to the View.

(Code Snippet – Service Bus Queues and Topics – Ex02 – GetTopic and Subscriptions - CS)

C#

[OutputCache(NoStore = true, Duration = 0, VaryByParam = "*")]public JsonResult Subscriptions(string topicName){ var subscriptions =

this.namespaceManager.GetSubscriptions(topicName).Select(c => c.Name); return Json(subscriptions, JsonRequestBehavior.AllowGet);}

[OutputCache(NoStore = true, Duration = 0, VaryByParam = "*")]public JsonResult TopicsWithSubscriptions(){ var topics = this.namespaceManager.GetTopics().Select(c =>

c.Path).ToList(); var toReturn = new Dictionary<string, object>(); topics.ForEach(c => { var subscriptions =

this.namespaceManager.GetSubscriptions(c).Select(d => new { Name = d.Name, MessageCount = d.MessageCount });

toReturn.Add(c, subscriptions); });

return Json(toReturn.ToArray(), JsonRequestBehavior.AllowGet);}

[OutputCache(NoStore = true, Duration = 0, VaryByParam = "*")]public JsonResult Filters(string topicName, string subscriptionName){ var rules = this.namespaceManager.GetRules(topicName,

subscriptionName); var sqlFilters = new List<Tuple<string, string>>();

Page 27

Page 28: az12722.vo.msecnd.netaz12722.vo.msecnd.net/.../servicebusmessaging1-0-1/Lab.docx · Web viewIn this exercise you will learn to create a Topic and add Subscriptions to it. Subscriptions

foreach (var rule in rules) { var expression = rule.Filter as SqlFilter; var action = rule. Action as SqlRuleAction;

if (expression != null) { sqlFilters.Add( new Tuple<string, string>( expression.SqlExpression, action != null ? action.SqlExpression : string.Empty)); } }

return Json(sqlFilters.Select(t => new { Filter = t.Item1, Action = t.Item2 }), JsonRequestBehavior.AllowGet);

}

public long GetMessageCount(string topicName, string subscriptionName){ var subscriptionDescription =

this.namespaceManager.GetSubscription(topicName, subscriptionName); return subscriptionDescription.MessageCount;}

Note: These methods are used by the View to retrieve the information on Topics and Subscriptions via jQuery and AJAX.

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

Verification

You will now launch the updated application in the Windows Azure compute emulator to verify that you can create a Topic with subscriptions, send and receive messages. You will verify that each message will go to the subscription that matches the correct filter.

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

Page 28

Page 29: az12722.vo.msecnd.netaz12722.vo.msecnd.net/.../servicebusmessaging1-0-1/Lab.docx · Web viewIn this exercise you will learn to create a Topic and add Subscriptions to it. Subscriptions

Figure 16UsingTopics Application Home Page

2. In the panel named Topics, enter a topic name, for example MyTopic, and click Create.

Page 29

Page 30: az12722.vo.msecnd.netaz12722.vo.msecnd.net/.../servicebusmessaging1-0-1/Lab.docx · Web viewIn this exercise you will learn to create a Topic and add Subscriptions to it. Subscriptions

Figure 17Creating a Topic

Figure 18The application displays a message when a Topic is created

3. In the Send Message panel, select the previously created Topic from the dropdown list, enter “This is an urgent message” in the TextBox, check Is Urgent and click Send.

Page 30

Page 31: az12722.vo.msecnd.netaz12722.vo.msecnd.net/.../servicebusmessaging1-0-1/Lab.docx · Web viewIn this exercise you will learn to create a Topic and add Subscriptions to it. Subscriptions

Figure 19Sending a message to the topic

4. Check that the message is received only by the UrgentMessages and the AllMessages subscriptions. To do this, select each subscription in the dropdown list located in the Receive Message panel and click Retrieve First message in Subscription.

Page 31

Page 32: az12722.vo.msecnd.netaz12722.vo.msecnd.net/.../servicebusmessaging1-0-1/Lab.docx · Web viewIn this exercise you will learn to create a Topic and add Subscriptions to it. Subscriptions

Figure 20Retrieving a message to the AllMessages subscription

Figure 21Retrieving a message to the HighPriorityMessages subscription

Page 32

Page 33: az12722.vo.msecnd.netaz12722.vo.msecnd.net/.../servicebusmessaging1-0-1/Lab.docx · Web viewIn this exercise you will learn to create a Topic and add Subscriptions to it. Subscriptions

Figure 22Retrieving a message to the UrgentMessages subscription

5. Send another message to the Topic, but this time, uncheck the Is Urgent checkbox and check Mark as important. Retrieve the message from the HighPriorityMessages subscription and verify that the Priority is now set to High.

Page 33

Page 34: az12722.vo.msecnd.netaz12722.vo.msecnd.net/.../servicebusmessaging1-0-1/Lab.docx · Web viewIn this exercise you will learn to create a Topic and add Subscriptions to it. Subscriptions

Figure 23Sending an important message to the Topic

Summary

By completing this hands-on lab, you have reviewed the basic elements of Service Bus Queues, Topics and Subscriptions. You have seen how to send and retrieve messages through a Queue and how to create Topics and Subscriptions to it. Finally, you learned how to apply Expression Filters and Rule Actions to Subscriptions to distribute your messages that matched those rules.

Page 34