Azure Service Bus Topic Example C#

Azure Service Bus Topic Example C#

In this article, we will discuss an Azure service bus topic example using c#. We will discuss how to send messages using the Service bus topic and subscription via a console application.

Azure Service Bus Topic Example C#

Let’s discuss the prerequisites needed to perform this example. Below are the lists of prerequisites needed here.

  • You must have an Azure Subscription. There is nothing to worry about if you don’t have an Azure account. Create an Azure free account now.
  • You must install Visual Studio 2019 or a higher version on your PC.

On a high level, below is the activity we need to perform here.

  1. We need to create an Azure Service bus namespace in Azure Portal.
  2. Creating Azure service bus topics in Azure Portal.
  3. Creating a subscription for the topic in Azure Portal.
  4. Create a console application using Visual Studio 2019 to send and receive messages.

Since I have already created the Azure service bus namespace, I will use that existing namespace here, and you can refer to the above link to create the Azure service bus namespace.

Let’s create the Azure service bus topics in Azure Portal.

How to create Azure service bus topics in Azure Portal

Follow the below steps to create the Azure service bus topic.

  1. Log in to the Azure Portal.
  2. Search for service bus and click on the search result service bus.
send message to service bus topic c#

3. Now, you will see the Azure Service Bus namespaces lists. Click on the one where you want to create the topic.

send message to azure service bus topic c#

4. On the Service Bus Namespace page, click the + Topic button to create the Azure Service Bus Topic.

c# send message to service bus topic

Or, for the same option, you can click on the Topics link under Entities from the left navigation –> Then click on the + Topic button.

azure service bus real world example

5. On the Create topic window, provide the below details

  • Name: Provide a unique name for the topic.
  • Max topic size: Provide the maximum topic size as per your requirement.
  • Message time to live: Mention the time for the message to live.
  • Enable auto-delete on idle topic: Select this option if you want to enable the automatic deletion of the idle topic.
  • Enable duplicate detection: Select this option if you wish to enable the option to detect duplicates automatically.
  • Enable Partitioning: Check this option if you wish to enable the Partitioning option.

After providing all the above details, click the Create button to create the topic in Azure Service Bus.

azure service bus topic example

It took seconds to create the Azure Service Bus topic successfully.

azure service bus topic example c# .net core

To view the topic we have created, on the Service Bus Namespace page, click on the Topics link that is present under Entities from the left navigation. On the right side, you can see the topic that we have created.

azure service bus topic subscription example

So, our topic is ready. Now, let’s create a subscription for the topic we have created.

Creating Azure Service Bus topic subscription

  1. On the Service Bus Topic page, click on the + Subscription button.
azure service bus topic example c# net core

2. On the Create subscription window, provide the below details

  • Name: Provide a unique name for the subscription.
  • Max delivery count: Specify the maximum delivery count.
  • Auto-delete after idle for: Mention days and time-based on your requirement.
  • Never auto-delete: Check this option if you don’t want the auto-delete option.
  • Forward messages to queue/topic: Select this option if you wish to forward messages to the topic or queue.
  • Enable sessions: You can enable this option to help you first-in-first-out delivery of messages.
  • Message time to live: Specify the duration for the messages to live.
  • Enable dead lettering on message expiration: Select this option if you wish to enable the dead lettering on the message expiration.
  • Move messages that cause filter evaluation exceptions to the dead-letter sub- queue: You can enable this option if you want to move the messages to the dead-letter sub-queue responsible for the exceptions.
  • Message Lock Duration: If you wish to apply the lock for the messages, you need to specify the duration for the lock operation.
Azure service bus topic subscription
send message to service bus topic c#

After providing all the details, click the Create button to create the subscription for the topic.

Now, we have created the Azure Service bus subscription successfully.

How to create service bus subscription

Moving to the next steps, as part of this demo, we need to create a console application using Visual Studio 2019 that will help us send and receive messages.

Creating a console application using Visual Studio 2019

  1. Open Visual Studio 2019 –> Click on the Create a new project button.
  2. Choose the C# Windows Console application template –> Click on the next button.
servicebus c#

3. On the Configure your new project window, Enter the project name, Choose a location to save the project, and most importantly, choose the Framework as .NET Framework 4.7.2 or higher. Click on the Create button to create the console application.

service bus topics and subscriptions example

4. You can copy and paste the code below into the Program.cs file, and change the namespace name and other details as per yours.

using System;
using System.Linq;
using System.Activities;
using System.Activities.Statements;
using Microsoft.ServiceBus.Messaging;

namespace TsinfoApp
{

    class Program
    {
        public static string conn = "Endpoint=sb://tsinfo.servicebus.windows.net/;SharedAccessKeyName=RootManageSharedAccessKey;SharedAccessKey=XESuxxxxx1x08G08pXs3C7SIQPAgj0/yIXfXr8AzVoos=";
        public static string servicebustopicname = "your topic name";

        public static void Main(string[] args)
        {
            SendingMessageToTopic("Hello This is a Hii from Service Bus Topic ");
            GettingMessageViaSubscription();
            Console.ReadKey();
        }
 //This method will help to send the Azure service bus topic
       public static void SendingMessageToTopic(string message)
        {
            var tC = TopicClient.CreateFromConnectionString(conn, servicebustopicname);
            var msg1 = new BrokeredMessage(message);
            tC.Send(msg1);
        }
//This method will help to receive the messages based on your subscription
        public static void GettingMessageViaSubscription()
        {
            var sC = SubscriptionClient.CreateFromConnectionString(conn, servicebustopicname, "Your subscription name");
            sC.OnMessage(m =>
            {
                Console.WriteLine(m.GetBody<string>());
            });
        }
    }
}

Like below, you will see the namespace error for TopicClient, SubscriptionClient, and BrokeredMessage. For instance, “the type or namespace name ‘brokeredmessage’ could not be found” and ‘the name TopicClient does not exist in the current context’. To fix these errors, click on the dropdown just before BrokeredMessage, then select Install package ‘WindowsAzure.ServiceBus’, and after that, click on the Find and install latest version option and make sure to use the using Microsoft.ServiceBus.Messaging using statements.

the type or namespace name 'brokeredmessage' could not be found

In the above code, To get the Endpoint value, check out How to find Azure service bus connection string.

click on the copy button to copy the complete connection string and replace the complete value for the Endpoint point parameter.

Mention your topic name and the subscription name.

Azure Service Bus Topic Example using C#

For better clarity, on the Main(), first, comment on the GettingMessageViaSubscription(); method and press the F5 to run the code. Now, you can navigate to the subscription and will see the active message count is 1.

Azure Service Bus Topic c# Example
Azure Service Bus Topic Example

Now, uncomment the GettingMessageViaSubscription() comment on the SendingMessageToTopic(), and press F5 to run the code. You can see the below-expected output that the message is received via subscription.

send message to azure service bus topic c#

And now, if you navigate to the subscription again, you will find the Active message count is 0. Now, you are done with the Demo.

azure service bus real-world example

You may also like following the articles below

Wrapping Up

This article discussed the Azure Service Bus Topic Example using C# and Visual Studio 2019. Thanks for reading this article !!!