QueueEngine Class - Azure

Overview

This article provide a generalized class for adding items to an Azure queue.

Implementation Tasks


Reusable Code

using Azure.Storage.Queues;
using System;
using System.Collections.Generic;
using System.Configuration;
using System.Linq;

public static class QueueEngine
{
    //public static int AddToAuditTrailQueue(AuditTransaction txn)
    //{
    //    var json = JsonSerializer.Serialize(txn);

    //    return AddToQueue(new[] { json }, QueueNameEnum.Audit);
    //}

    private static int AddToQueue(IEnumerable<string> values, QueueNameEnum queue, TimeSpan? lifetime = null,
        TimeSpan? delay = null, int? batchSize = null, int? delayMinutesPerBatch = null)
    {
        var result = 0;
        var isBatchDelay = (batchSize != null && delayMinutesPerBatch != null);
        var queueName = queue.ToString().ToLower();

        if (values.Any())
        {
            try
            {
                var scs = ConfigurationManager.AppSettings["StorageConnectionString"];

                var queueClient = new QueueClient(scs, queueName);

                if (queueClient != null)
                {
                    queueClient.CreateIfNotExists();
                    var n = 0;
                    var nmax = values.Count();

                    foreach (var value in values)
                    {
                        n++;

                        if (isBatchDelay)
                        {
                            var batchNum = Math.Truncate((decimal)n / batchSize.Value);
                            delay = new TimeSpan(0, (int)(batchNum * delayMinutesPerBatch.Value), 0);
                        }
                        queueClient.SendMessage(value, delay, lifetime);
                        result = n;
                    }
                }
            }
            catch (Exception ex)
            {
                //SystemLogRepo.Exception($"Unable to add items to the {queueName} queue", ex);
            }
        }
        return result;
    }
}