CloudCasts Blog

Webcasts in the Cloud
posts - 130 , comments - 71 , trackbacks - 120

My Links

News

Tag Cloud

Article Categories

Archives

Post Categories

Image Galleries

Bloggers Guides

AppFabric 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 from an AppFabric service bus queue using the direct programming model. You can either read through to get an idea of the concepts, or implement the solution using Azure AppFabric and Visual Studio. Note that this code is based on the September 2011 release of AppFabric service bus and will not work on the May or June CTP releases due to changes in the service bus API. You will need a Windows Azure account to use the AppFabric queues.
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 an 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.
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. If no namespace is present then one must be created. 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 (ACS) version 2. 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 simple 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 AppFabric 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 an AppFabric 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 AppFabric 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.
 
Complete Code Listings
The complete code listings for the walkthrough are shown below.
AccountDetails.cs
Account details have been removed.

 

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 = "";
    }
}
 
 
PizzaOrder.cs

 

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; }
    }
}
 
 
 
Program.cs

 

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();
 
            // 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 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 the message factory and everything it created.
            factory.Close();
 
        }
    }
}
 
 
 

Print | posted on Friday, September 16, 2011 11:26 PM |

Feedback

Gravatar

# re: AppFabric Walkthrough: Simple Brokered Messaging

Hi, Thank you very much for this sample it is helping a lot. Easy and clear! However I have a question about best practices. Let's assume the same example as you have created here, what is the best practice in keeping this secure? For example you have created a class where you store the key, name and namespace. If we take this scenario and we implement it as a client application, that will be given to customers, how can we store/keep safe the key, namespace and name? How can we have some kind of authentication because I don't want to give this key to the customer client application? What do you recommend in this case? Thanks a lot!
3/18/2012 5:54 PM | Alex
Gravatar

# re: AppFabric Walkthrough: Simple Brokered Messaging

Hi,

This is very helpful information. However when I was trying the code I am getting the following error (40400: Endpoint Not Found.TrackingId:f22318e0-bb89-4099-bfed-4a08cb835c1d_8,TimeStamp:4/26/2012 2:25:45 PM) at queueClient.Send(orderInMsg);

not sure what is wrong.

Thanks
Srinivas
4/26/2012 4:34 PM | Sri
Post A Comment
Title:
Name:
Email:
Comment:
Verification:
 
 

Powered by: