Microsoft Azure Service Bus Basics And Understanding Topics And Queues

Azure Service Bus is a generic, Cloud-based messaging system. It connects apps running on Azure, on-premises systems or both. There are four different communication mechanisms of connection, each of which connects applications in a different way.

  • Queues, allow one-directional communication. Each queue acts as an intermediary (broker) that stores sent messages until they are received. Each message is received by a single recipient.

  • Topics, provids one-directional communication using subscriptions, a single topic can have multiple subscriptions. Like a queue, a topic acts as a broker, but each subscription can optionally use a filter to receive only messages that match specific criteria.

  • Relays, provide bi-directional communication. Unlike queues and topics, a relay doesn't store messages. Instead, it just passes them on to the destination application.

  • Event Hubs, is a highly scalable ingestion system that can process millions of events per second, enabling application to process and analyze the massive amounts of data produced by the connected devices and applications.

We can use one or more instances of four communication mechanisms depending on our requirement.

Reference - Azure Service Bus.

Creating Service Bus Namespace,

  1. Log on to the Azure portal.

  2. Click On New button. Select Hybrid Integration and select Service Bus.



  3. Click on Create button at bottom.



  4. Provide input as below and click Ok.

Using Service Bus Queue

Creating Service Bus Queue using Management Portal

  1. Once created select Service Namespace and select Queue option.

  2. Click on Create New Queue. Select Quick Create and provide the inputs.



  3. Click Create A New Queue.

Creating Service Bus Queue programmatically

  1. Open Visual Studio and create new console application.

  2. In Solution Explorer, right-click References, then click Manage NuGet Packages.

  3. Select the Microsoft Azure Service Bus item. Click Install.

  4. Open App.confgig file, under appSettings you can see key for Connection String is added as below.
    1. <appSettings>  
    2. <!-- Service Bus specific app setings for messaging connections -->  
    3. <addkey="Microsoft.ServiceBus.ConnectionString"  
    4. value="Endpoint=sb://[your namespace].servicebus.windows.net;SharedAccessKeyName=RootManageSharedAccessKey;SharedAccessKey=[your secret]"/>  
    5.   
    6. </appSettings>  
  5. Go to Management portal. Click on Configuration Information button at bottom.



  6. Copy the connection string and replace value of connectionString key in App.config file.

  7. Write below code in program.cs file.

    Add the following references.
    1. using Microsoft.ServiceBus;  
    2. using Microsoft.WindowsAzure;

Add the following code in Main() method 

  1. stringconnectionString = CloudConfigurationManager.GetSetting("Microsoft.ServiceBus.ConnectionString");    
  2.     
  3. var namespaceManager = NamespaceManager.CreateFromConnectionString(connectionString);    
  4.     
  5. if (!namespaceManager.QueueExists("azservicequeue"))    
  6. {    
  7. namespaceManager.CreateQueue("azservicequeue");    
  8. }    
 
This will create "azservicequeue" service bus queue.

Send messages to a queue
  1. string connStr = "[connection string]";  
  2. MessagingFactory factory = MessagingFactory.CreateFromConnectionString(connStr);  
  3. MessageSendertestQueueSender = factory.CreateMessageSender("azservicequeue");  
  4. BrokeredMessage message = new BrokeredMessage("This is sample message.");  
  5. testQueueSender.Send(message);  
Retrieve message form queue
  1. string connStr = "[connection string]";  
  2. QueueClient Client = QueueClient.CreateFromConnectionString(connStr, "azservicequeue");  
  3. OnMessageOptions options = newOnMessageOptions();  
  4. options.AutoComplete = false;  
  5. options.AutoRenewTimeout = TimeSpan.FromMinutes(1);  
  6. Client.OnMessage((message) =>  
  7. {  
  8.     try  
  9.     {  
  10.         Console.WriteLine("Message: " + message.GetBody < string > ());  
  11.         // Remove message from queue.  
  12.         message.Complete();  
  13.     }  
  14.     catch (Exception)  
  15.     {  
  16.         // Indicates a problem, unlock message in queue.  
  17.         message.Abandon();  
  18.     }  
  19. }, options);  
Message can be retrieve in two different mode RecieveAndDelete or PeekLock.

By default, a message is retrieved using the PeekLock mode, this means that the message is locked on the queue so that it cannot be retrieved by another consumer. Once the retrieval code has finished processing, it calls Complete on the message. This notifies the service bus that this message is completed and can be permanently removed from the queue. Likewise, if something goes wrong during the processing and an exception is thrown, then the code calls Abandon on the message, notifying the service bus that the message could not be processed and it can be retrieved by another consumer.

Reference - Get started with Service Bus Queues.

Using Service Bus Topics

Creating Service Bus Topic
  1. Open Visual Studio and create new console application.

  2. Add NuGet Packages for Service Bus. And configure the “Microsoft.ServiceBus.ConnectionString” as we did in previous application.

  3. Write below code in program.cs file.
    1. string connectionString = CloudConfigurationManager.GetSetting("Microsoft.ServiceBus.ConnectionString");  
    2.   
    3. var namespaceManager = NamespaceManager.CreateFromConnectionString(connectionString);  
    4.   
    5. if (!namespaceManager.TopicExists("azservicetopic"))  
    6. {  
    7.    namespaceManager.CreateTopic("azservicetopic");  
    8. }  

Creating a subscription with the default (MatchAll) filter

The MatchAll filter is the default filter that is used if no filter is specified when a new subscription is created.

  1. string connectionString = CloudConfigurationManager.GetSetting("Microsoft.ServiceBus.ConnectionString");  
  2.   
  3. var namespaceManager = NamespaceManager.CreateFromConnectionString(connectionString);  
  4.   
  5. if (!namespaceManager.SubscriptionExists("azservicetopic""AllMessages"))  
  6. {  
  7.    namespaceManager.CreateSubscription("azservicetopic""AllMessages");  
  8. }  
Creating subscriptions with filters

The following example creates a subscription named HighProperty with a SqlFilter object that only selects messages that have a custom MessageNumber property greater than 3.
  1. SqlFilter highMessagesFilter =new SqlFilter("MessageNumber> 3");  
  2.   
  3. namespaceManager.CreateSubscription("azservicetopic","HighProperty",highMessagesFilter);  
Send messages to a topic
  1. TopicClient Client = TopicClient.CreateFromConnectionString(connectionString, "azservicetopic");  
  2.   
  3. BrokeredMessage message = newBrokeredMessage("This is sample message ");  
  4. Client.Send(message);  
We can also add custom property to BroderdMessage object.

You can get example in sample code.

Receive messages from a subscription
  1. SubscriptionClient Client = SubscriptionClient.CreateFromConnectionString(connectionString, "azservicetopic""HighProperty");  
  2. // Configure the callback options.  
  3. OnMessageOptions options = new OnMessageOptions();  
  4. options.AutoComplete = false;  
  5. options.AutoRenewTimeout = TimeSpan.FromMinutes(1);  
  6. Client.OnMessage((message) =>  
  7. {  
  8.     try  
  9.     {  
  10.         // Process message from subscription.  
  11.         Console.WriteLine("High Property Messages");  
  12.         Console.WriteLine("Message: " + message.GetBody < string > ());  
  13.         Console.WriteLine("Message Number: " +  
  14.             message.Properties["MessageNumber"]);  
  15.         // Remove message from subscription.  
  16.         message.Complete();  
  17.     }  
  18.     catch (Exception)  
  19.     {  
  20.         // Indicates a problem, unlock message in subscription.  
  21.         message.Abandon();  
  22.     }  
  23. }, options);  
  24. }