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.