Azure Service Bus Topic Example C#

Azure Service Bus Topic Example C#

Well, in this article, we will discuss an azure service bus topic example using c#. We will discuss how we can 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. If you don’t have an Azure account, nothing to worry about, create an Azure free account now.
  • You need to install Visual Studio 2019 or a higher version on your PC.

On a high level, below are 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 so I am going to use that existing namespace here. 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.
Create Azure service bus topics in Azure Portal

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

How to Create Azure service bus topics in Azure Portal

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

create azure service bus topics in azure portal using c#

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

create service bus topics in Azure

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 on the Create button to create the topic in Azure Service Bus.

How to create service bus topics in Azure Portal

It took a span of seconds and created the Azure Service Bus topic successfully.

Create service bus topics in Azure Portal

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 able to see the topic that we have created.

Create service bus topic in Azure Portal

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.
How to create a subscription in Azure Service Bus Topic

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

  • Name: Provide a unique name for the subscription.
  • Max delivery count: Specify the max 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 which will 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 subqueue: You can enable this option if you want to move the messages to the dead-letter subqueue that are 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
Create a Subscription for the Azure Service Bus Topic

After providing all the details, click on 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 to 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.
azure service bus topics and subscriptions example

3. On the Configure your new project window, Enter the project name, Choose a location to save the project, and most importantly, make sure to 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 below code into the Program.cs file and make sure to 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>());
            });
        }
    }
}

You will see the namespace error for TopicClient, SubscriptionClient, and BrokeredMessage like below. 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 statement.

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 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() and comment on the SendingMessageToTopic(), and press F5 to run the code, you can able to see the below expected output that the message is received via subscription.

azure service bus c

And, now if you will again navigate to the subscription, 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 below articles

Wrapping Up

In this article, we have discussed Azure Service Bus Topic Example using C# and Visual Studio 2019. Thanks for reading this article !!!