Skip Navigation LinksAzure Developers Guide > Azure Service Bus > Brokered Messaging > Walkthrough: Simple Brokered Messaging

Training Courses

All course material is in English, and courses are delivered in English. Feel free to contact me for further information. cloudcasts.net@gmail.com

Walkthrough: Simple Brokered Messaging

This walkthrough will use a basic example to show how to create a queue, send a message, and receive a message using the Service Bus brokered messaging services using the management console and the direct programming model.

Creating a Service Bus Namespace

The first step is to log onto the AppFabric management console and create a service bus namespace. If you have already done this you can skip this section.

The Windows Azure Management console is located at https://windows.azure.com. Once a valid Live ID for a Windows Azure account has been provided the main management page will be displayed.

To get to the AppFabric management page, click the Service Bus, Access Control & Caching link. Clicking the Service Bus link will display the information relating to the service bus artifacts.

console.png

A namespace will need to be created before the service bus can be used. This namespace will be assigned to an Azure datacenter, but must be unique across all Windows Azure accounts. This is done by clicking on the New button in the Service Namespace section at the top left of the console.

The name, data center location and any connection pack configuration is then entered; the name must be checked for availability to ensure that it is unique. Once this is done the namespace may take a few minutes to activate. Once activated, the namespace will be displayed in the management console.

New service bus namespaces will be created to use Azure Access Control Service version 2 (ACSV2). Any namespaces created prior to the release of ACSV2 will use ACSV1. If you want to leverage the ACSV2 functionality you must create a new namespace.

Creating a Queue

Before any messages can be sent, a queue must be created in the service bus namespace. In this example the AppFabric management portal will be used to create the queue. Queue names must be unique within the service bus namespace. To create a queue, select the namespace and click the New Queue button.

In this example a queue named simplebrokeredmessaging is created, with the default settings. The queue is displayed in the management console as shown below.

 

 

Creating the Project

Now that the queue has been created, an application can be developed to use it. Create a Windows C# console application named SimpleBrokeredMessaging in Visual Studio 2010. Once this has been done the target framework should be set to .NET Framework 4.0 in the project properties, and references to the following assemblies added:

·        Microsoft.ServiceBus

·        System.Runtime.Serialization

Setting the Account Details

A class named AccountDetails can then be added to the project to store the service namespace, name and key of the account that will be used to access the service bus.

 

using System;

using System.Collections.Generic;

using System.Linq;

using System.Text;

 

namespace SimpleBrokeredMessaging

{

    class AccountDetails

    {

        public static string Namespace = "";

        public static string Name = "";

        public static string Key = "";

    }

}

 

 

The values for the static variables should be set to the appropriate values for the service bus account. These can be found in the default key property of the namespace in the AppFabric management portal. This class will be used in many of the code samples in the chapter to abstract the security details. Be aware that there is a security risk in placing credential information in code.

Defining a Message Contract

Messages can be created directly from serializable objects using the data contract serializer and this example will use a simple data contract to represent a pizza order. A class named PizzaOrder is added to the project and implemented as follows.

 

using System;

using System.Collections.Generic;

using System.Linq;

using System.Text;

using System.Runtime.Serialization;

 

namespace SimpleBrokeredMessaging

{

    [DataContract]

    public class PizzaOrder

    {

        [DataMember]

        public string Name { get; set; }

 

        [DataMember]

        public string Pizza { get; set; }

 

        [DataMember]

        public int Quantity { get; set; }

    }

}

 

 

 

Creating a Queue Client

The next step is to create a queue client for the simplebrokeredmessaging queue. This involves the creation of a token provider with the appropriate credentials, a URI for the service bus, and a messaging factory. Once these have been created the messaging factory can be used to create a queue client.

 

using System;

using System.Collections.Generic;

using System.Linq;

using System.Text;

using Microsoft.ServiceBus;

using Microsoft.ServiceBus.Messaging;

 

namespace SimpleBrokeredMessaging

{

    class Program

    {

        static void Main(string[] args)

        {

            Console.WriteLine("Creating queue client...");

 

            // Create a token provider with the relevant credentials.

            TokenProvider credentials =

                TokenProvider.CreateSharedSecretTokenProvider

                (AccountDetails.Name, AccountDetails.Key);

 

            // Create a URI for the serivce bus.

            Uri serviceBusUri = ServiceBusEnvironment.CreateServiceUri

                ("sb", AccountDetails.Namespace, string.Empty);

 

            // Create a message factory for the service bus URI using the

            // credentials

            MessagingFactory factory = MessagingFactory.Create

                (serviceBusUri, credentials);

 

            // Create a queue client for the pizzaorders queue

            QueueClient queueClient =

                factory.CreateQueueClient("simplebrokeredmessaging");

 

            Console.WriteLine("Done!");

            Console.WriteLine();

 

        }

    }

}

 

 

 

Creating and Send a Message

The queue client can then be used to send a message to the queue. In order to do this an instance of the pizza order data contract will be created, which will then be used to create a brokered message. The brokered message is then sent to the queue by calling the send operation on the queue client.

 

// Create a queue client for the pizzaorders queue

QueueClient queueClient =

    factory.CreateQueueClient("simplebrokeredmessaging");

 

Console.WriteLine("Done!");

Console.WriteLine();

 

// Create a new pizza order.

PizzaOrder orderIn = new PizzaOrder()

{

    Name = "Alan",

    Pizza = "Hawaiian",

    Quantity = 1

};

 

// Create a brokered message based on the order.

BrokeredMessage orderInMsg = new BrokeredMessage(orderIn);

 

Console.WriteLine("Sending order for {0}...", orderIn.Name);

 

// Send the message to the queue.

queueClient.Send(orderInMsg);

 

Console.WriteLine("Done!");

Console.WriteLine();

 

 

Receive a Message

The next stage is to receive a message from the queue, this is done by calling the receive method on the queue client class. Sending and receiving messages is typically done in different applications, but to keep the implementation as simple as possible, the same application will be used.

 

// Send the message to the queue.

queueClient.Send(orderInMsg);

 

Console.WriteLine("Done!");

Console.WriteLine();

 

// Receive a message from the queue

Console.WriteLine("Receiving order...");

BrokeredMessage orderOutMsg = queueClient.Receive();

 

if (orderOutMsg != null)

{

    // Deserialize the message body to a pizza order.

    PizzaOrder orderOut = orderOutMsg.GetBody<PizzaOrder>();

 

    Console.WriteLine("Received order, {0} {1} for {2}",

        orderOut.Quantity, orderOut.Pizza, orderOut.Name);

 

    // Mark the order message as completed.

    orderOutMsg.Complete();

}

 

 

 

Close Communication Objects

As the communication objects used to connect to the Service Bus will maintain open connections, and connections are a limited resource, these should be closed when no longer used. The following code will close the messaging factory, and all objects it created, so the queue client will also be closed.

 

if (orderOutMsg != null)

{

    // Deserialize the message body to a pizza order.

    PizzaOrder orderOut = orderOutMsg.GetBody<PizzaOrder>();

 

    Console.WriteLine("Received order, {0} {1} for {2}",

        orderOut.Quantity, orderOut.Pizza, orderOut.Name);

 

    // Mark the order message as completed.

    orderOutMsg.Complete();

}

 

// Close the message factory and everything it created.

factory.Close();

 

 

Testing the Application

The application can now be tested, if everything works well, the console should output the following.

 

Summary

This example showed a very simple way of creating interacting with a Service Bus queue to send and receive a message based on a data contract. Feel free to extend on this basic sample to explore the possibilities of Service Bus brokered messaging. You might like to try sending a number of messages to the queue, or using one application to send messages and another application to receive them.

Speaking Engagements