Jasinski Technical Wiki

Navigation

Home Page
Index
All Pages

Quick Search
»
Advanced Search »

Contributor Links

Create a new Page
Administration
File Management
Login/Logout
Your Profile

Other Wiki Sections

Software

PoweredBy

QueueEngine Class - Azure

RSS
Modified on Tue, Jun 23, 2020, 8:30 AM by Administrator Categorized as Azure, ·Net Framework

Overview

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

Implementation Tasks

  • It's recommended to add the class to the DAL project of your solution
  • Add a "QueueNameEnum" enum to name the queues
  • Add the "Azure.Storage.Queues" package to the project
  • Create the queue(s) in the Azure portal
  • Create public methods as needed to wrap the private method provided

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;
    }
}

ScrewTurn Wiki version 3.0.1.400. Some of the icons created by FamFamFam. Except where noted, all contents Copyright © 1999-2024, Patrick Jasinski.