iKnowNothing
iKnowNothing

Reputation: 979

Creating an Azure ServiceBus Queue via code

Apologies, I'm new to Azure. I created a service bus and queue via the Azure portal using this tutorial.

I can write and read from the queue ok. The problem is, to deploy to the next environment, I have to either update the ARM template to add the new queue or create the queue in code. I can't create the queue through the portal in the next environment.

I've chosen the latter: check to see if the queue exists and create as required via code. I already have an implementation for this for a CloudQueueClient (in the Microsoft.WindowsAzure.Storage.Queue namespace). This uses a CloudStorageAccount entity to create the CloudQueueClient, if it doesnt exists.

I was hoping it would be this simple but it appears not. I'm struggling to find a way to create a QueueClint (in the Microsoft.Azure.ServiceBus namespace). All I have is the Service Bus connection string and the queue name but having scoured Microsoft docs, there's talk of a NamespaceManager and MessagingFactory (in a different namespace) involved in the process.

Can anyone point me in the direction of how to achieve this and more importantly, is this the right approach? I'll be using DI to instantiate the queue so the check/creation will only be done once.

The solution is required for a service bus queue and not a storage account queue. Differences outlined here

Thanks

Upvotes: 16

Views: 9427

Answers (5)

Morph
Morph

Reputation: 196

In case you need a more up to date implementation using the newer Azure.Messaging.ServiceBus library, you'll need to install the package System.Linq.Async

It's an extension method for creating "missing" queues from your service bus namespace

using Azure.Messaging.ServiceBus.Administration;
using System.Threading.Tasks;
using System.Linq;
using System;

public static class ServiceBusAdministrationClientExtensions
{
    public static async Task CreateMissingQueuesAsync(this ServiceBusAdministrationClient serviceBusAdministrationClient, params string[] queueNames)
    {
        var allQueues = serviceBusAdministrationClient.GetQueuesAsync();

        var queueList = await allQueues.ToListAsync();

        foreach (var queueName in queueNames) {

            var foundQueue = queueList.Where(q => q.Name == queueName.ToLower()).Any();

            if (!foundQueue)
            {
                var queueOptions = new CreateQueueOptions(queueName)
                {
                    DefaultMessageTimeToLive = TimeSpan.FromHours(1),
                    LockDuration = TimeSpan.FromSeconds(30)
                };
                await serviceBusAdministrationClient.CreateQueueAsync(queueOptions);
            }
        }
    }
}

Then call the extension method with a call like this.

var _serviceBusAdminClient = new ServiceBusAdministrationClient(ServiceBusConnectionString);
await _serviceBusAdminClient.CreateMissingQueuesAsync("queueName");

I adapted this code from the accepted answer in this thread.

Upvotes: 1

Tim Iles
Tim Iles

Reputation: 2340

The Microsoft.Azure.ServiceBus nuget package in the accepted answer is now deprecated. To use the Azure.Messaging.ServiceBus package instead, the code you want is as follows:

using Azure.Messaging.ServiceBus.Administration;

var client = new ServiceBusAdministrationClient(connectionString);

if (!await client.QueueExistsAsync(queueName))
{
    await client.CreateQueueAsync(queueName);
}

Upvotes: 7

iKnowNothing
iKnowNothing

Reputation: 979

Sean Feldman's answer pointed me in the right direction. The main nuget packages/namespaces required (.net core ) are

  • Microsoft.Azure.ServiceBus
  • Microsoft.Azure.ServiceBus.Management

Here's my solution:

private readonly Lazy<Task<QueueClient>> asyncClient;
private readonly QueueClient client;`
  
public MessageBusService(string connectionString, string queueName)
{
    asyncClient = new Lazy<Task<QueueClient>>(async () =>
    {
        var managementClient = new ManagementClient(connectionString);

        var allQueues = await managementClient.GetQueuesAsync();

        var foundQueue = allQueues.Where(q => q.Path == queueName.ToLower()).SingleOrDefault();

        if (foundQueue == null)
        {
            await managementClient.CreateQueueAsync(queueName);//add queue desciption properties
        }


        return new QueueClient(connectionString, queueName);
    });

    client = asyncClient.Value.Result; 
}

Not the easiest thing to find but hope it helps someone out.

Upvotes: 24

Balasubramaniam
Balasubramaniam

Reputation: 421

You can create a Service Bus Queue using NamespaceManager likewise,

QueueDescription _serviceBusQueue = new QueueDescription("QUEUENAME");   //assign the required properties to _serviceBusQueue 

NamespaceManager namespaceManager = NamespaceManager.CreateFromConnectionString("CONNECTIONSTRING");

var queue = await namespaceManager.CreateQueueAsync(_azureQueue);

Upvotes: 0

Sean Feldman
Sean Feldman

Reputation: 26057

To create entities with the new client Microsoft.Azure.ServiceBus you will need to use ManagemnetClient by creating an instance and invoking CreateQueueAsync().

Upvotes: 5

Related Questions