Getting Started with Azure Service Bus

This post assumes you have already setup an Azure Service Bus if you haven't see here

We're going to create two Console applications in C# to read and write messages to the Azure Service bus.

We will also need shared access keys setup on Azure service bus, if you haven't done that or are unsure where to get them check here

First off we need to add the nuget package to our projects.

PM> Install-Package WindowsAzure.ServiceBus

On nuget: WindowsAzure.ServiceBus

Writing to Azure Service bus

Code for this is here

Create a C# Console app in Visual Studio and add the nuget package

Now we need to add the shared access key. So on the Azure Service bus in the portal open the Shared Access keys and copy the primary Endpoint will look something like this

Endpoint=sb://serversncodeX.servicebus.windows.net/;SharedAccessKeyName=RootManageSharedAccessKey;SharedAccessKey=XXXXXXXX

In the app.config

Under appSettings for the Microsoft.ServiceBus.ConnectionString add the end point.

<appSettings>
    <add key="Microsoft.ServiceBus.ConnectionString" value="Endpoint=sb://serversncodeX.servicebus.windows.net/;SharedAccessKeyName=RootManageSharedAccessKey;SharedAccessKey=XXXXXXXX"/>
</appSettings>

So back to program.cs

        string connectionString = CloudConfigurationManager.GetSetting("Microsoft.ServiceBus.ConnectionString");

We added a connection string and told it to go to our app.config and get the connection string to our Service Bus Endpoint.

        QueueClient Client = QueueClient.CreateFromConnectionString(connectionString, "serversncodedemoqueue");

We have created a QueueClient with the connectionstring and connected to the queue we created called "serversncodedemoqueue"

If you followed along with the last post we created a queue(note you can do that from code but for this demo I have skipped it) as a side note I think when you can it's better to create the queue yourself in the interface rather then code. It can be costly to check if a queue exists and then create it in code all the time. Also with some of the advanced things you can do with Keys and queues which we'll go into in time it's better to do all the setup up front.

Ok so we have our client created and ready to go lets send a message. For this we're going to play make believe. We have a new user signed up to our great App and we want to send a message to that user. They have just signed up, our app has written it to the database and got the user ID and User Code and wants to tell our email application that it can send an email to this user.

        // Create message, passing a string message for the body.
        BrokeredMessage message = new BrokeredMessage("");

        // Set some addtional custom app-specific properties.
        message.Properties["UserCode"] = "dascdcasas";
        message.Properties["UserId"] = "4550"; 

        // Send message to the queue.
        Client.Send(message);

BrokeredMessage is the class for the message we will send. We create two custom properties for our App and pass the values in from our Database.

Then we send the message.

And that's kinda that. We've now put a message onto the service bus. If you look in the portal on the queue it will show you there is an active message in the queue so lets go ahead and read it.

Reading Messages from Azure Service bus

Code sample is here

The first part of this application is the same as our app 1. We create the connection string and then add it in.

So to recap

  • Create C# Console app
  • Add Nuget package PM> Install-Package WindowsAzure.ServiceBus
  • Add connection string to app.config.

Now lets create the program.cs to read the service bus.

        string connectionString = CloudConfigurationManager.GetSetting("Microsoft.ServiceBus.ConnectionString");

        QueueClient Client = QueueClient.CreateFromConnectionString(connectionString, "serversncodedemoqueue");

        OnMessageOptions options = new OnMessageOptions();
        options.AutoComplete = false;
        options.AutoRenewTimeout = TimeSpan.FromMinutes(1);

The first two parts we've seen before, create our connection string and then create our client with the connection string and call our queue.

The next parts are new, these are the options we're going to allow our client to have as we read the service bus.

  • AutoComplete - Should the message be set to complete automaticlly once we've processed it. Actually this is once we've read it. It's a real fire and forget kind of thing. Your assuming you aren't going to crash.
  • AutoRenewTimeout - the maximum duration within which the lock will be renewed automatically. There are message locks in Service Bus so a message won't be read by someone else but at some stage you need to wonder if the message has crashed out and something else should read it.

Now the bit your waiting for.

        Client.OnMessage((message) =>
        {
            try
            {
                string sMessage = " UserCode: " + message.Properties["UserCode"];

                Console.WriteLine("Found new User - " + sMessage);


                // Remove message from queue.
                message.Complete();


            }
            catch (Exception ex)
            {
                // Indicates a problem, unlock message in queue.
                message.Abandon();
            }
        }, options);

That's it, no really that's it,

Client.OnMessage is a method in the QueueClient, on a message we then pass the message as a parameter into our method and at the end of the call back we set the options to use.

Once in there we then get the message properties we setup in our other app. We passed "UserCode" as a parameter. We read it and it writes the message to our console. It then marks it as Complete and moves on. There is no schema to the properties on the service bus, you can go as mad as you want and have different properties on the same queue just keep in mind only 1 process can read a message at a time.

When you run this code it will remain open and running as it is reading the service bus for any messages. Each time you run the other app and write a message to the service bus it will appear on the screen.

Also note if you run two reader apps then only 1 reads the message, this is the locks in action only 1 process can handle each message.

This post assumes you have already setup an Azure Service Bus if you haven't see here We're going to create two Console applications in C# to read and write messages to the Azure Service bus. We will also need shared access keys setup on Azure service bus, if you haven't…

Read More

Setup Azure Service bus

What is Azure Service Bus messaging?

Azure Service Bus messaging is an asynchronous messaging cloud platform that enables you to send data between decoupled systems. Azure Service bus is developed and provided by Microsoft.

Azure Service bus is hosted on Azure. There are different types of messaging built into Azure Service bus but for now and the purpose of this post I'm focused solely on Queues and the basic messaging we need to get started.

Pricing

There are 3 pricing levels for Azure Service bus. Each level comes with some added features.

Basic - €0.0422 per million operations

Standard - €8.433/mo for the First 12.5M Operations

  • Next 88M Ops (13M - 100M Ops) / Month €0.6746 per million operations
  • Next 2,400M Ops (100M - 2,500M Ops) / Month €0.4217 per million operations
  • Over 2,501M Ops / Month €0.1687 per million operations

Premium

Daily €18.77 fixed rate per Message Unit

As pointed out above we're focusing on Queues at the moment so I'm ignoring brokered connections and topics for the moment.

All prices for North Europe in EURO for more Azure Service Bus Pricing

Get Started

To get started we need to go to Azure Portal

On the left click new and search for "Service Bus" this will open the market place and let you select Service bus
Create Azure Service Bus

Select Service Bus, and then select Create.

Next we need to give it a name and resource group and stuff.

Define Service Bus

Select a name, Subscription and then Set the resource group to use an existing or to create a new one.

Also select the pricing tier you want to use.

And hit Create.

That's it your service bus is now being setup for use.

Service Bus up and running

Setup the Queue and access keys

So now we have our service bus created we need to create the queue. Under General select Queues

Create queue

Select Add Queue, and give it a name.

Create queue

We need to get the access keys so we can use the queue. Above queue select "Shared Access Policies" after a second a default "RootManageSharedAccessKey" will appear,

Open the "RootManageSharedAccessKey"

Azure Shared access keys

These keys you will need next so we can use this service bus queue.

What is Azure Service Bus messaging? Azure Service Bus messaging is an asynchronous messaging cloud platform that enables you to send data between decoupled systems. Azure Service bus is developed and provided by Microsoft. Azure Service bus is hosted on Azure. There are different types of messaging built into Azure…

Read More