Thursday, August 6, 2020

Azure - Service Bus Queue - C# Message Sender / P


In this article we will learn how to send messages to Azure Service Bus queues using C#.NET

Open Visual Studio and create a blank console C# project.

Then add “WindowsAzure.ServiceBus” from NuGet Manager.




After installing the required NuGet package, make note of the following values from the Azure Service Bus created in your subscription.

Navigate to Settings > Shared access policies


Then on the right hand side panel, copy the Primary Connection String.


Use the copied connection string for the following variable.

var connectionString = Endpoint=sb://sbus01.servicebus.windows.net/;SharedAccessKeyName=RootManageSharedAccessKey;SharedAccessKey=r12aot2kdUqaX6ea5r2u62ey0lPY9h0bldPzJawXyqc=";

Next copy the name of the queue.



Use the copied queue name to set the following variable.

var queueName = queue1";

For sending messages to Azure Service Bus queue, create a Windows Forms C# application targeting .NET Framework atleast version 4.6.1 and above – in order to be compatible with the Azure Service Bus NuGet package.

In this case, the windows forms had just a single button as shown below.



While the button code behind had the following code to send messages to Azure Service Bus.

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using Microsoft.ServiceBus.Messaging;

namespace DemoProject
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }

        private void button1_Click(object sender, EventArgs e)
        {
            var connectionString = "Endpoint=sb://sbus01.servicebus.windows.net/;SharedAccessKeyName=RootManageSharedAccessKey;SharedAccessKey=r12aot2kdUqaX6ea5r2u62ey0lPY9h0bldPzJawXyqc=";
            var queueName = "queue1";
            var client = QueueClient.CreateFromConnectionString(connectionString, queueName);
            var message = new BrokeredMessage("Test Message");
            client.Send(message);
        }
    }
}

Stats before sending messages.


Stats after sending a few messages. It takes a few minutes for the statistics to actually show up on the portal.


That's All!

No comments:

Post a Comment