Last active
June 28, 2021 21:23
-
-
Save nramsbottom/7760cf6c4d4c528e87266a71553a8eeb to your computer and use it in GitHub Desktop.
Azure Queue Writer
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
using System; | |
using System.Text; | |
using System.Text.Json; | |
using System.Threading.Tasks; | |
using Azure.Storage.Queues; // Azure.Storage.Queues@12.7.0 | |
namespace GitHub.nramsbottom.Azure.Storage.Queues | |
{ | |
public class AzureQueueWriter<T> where T : class, new() | |
{ | |
private readonly QueueClient _queueClient; | |
public AzureQueueWriter(string connectionString, string queueName) | |
{ | |
if (connectionString == null) throw new ArgumentNullException(nameof(connectionString)); | |
if (queueName == null) throw new ArgumentNullException(nameof(queueName)); | |
try | |
{ | |
_queueClient = new QueueClient(connectionString, queueName); | |
} | |
catch (Exception ex) | |
{ | |
throw new AzureQueueException("Unable to create Azure QueueClient.", ex); | |
} | |
} | |
public async Task Enqueue(T obj, TimeSpan? ttl = null) | |
{ | |
var json = SerializeJson(obj); | |
var base64 = SerializeBase64(json, Encoding.UTF8); | |
try | |
{ | |
await _queueClient.SendMessageAsync(base64, timeToLive: ttl); | |
} | |
catch (Exception ex) | |
{ | |
throw new AzureQueueException("Could not send message to queue.", ex); | |
} | |
} | |
private static string SerializeJson(T obj) | |
{ | |
return JsonSerializer.Serialize(obj); | |
} | |
private static string SerializeBase64(string s, Encoding encoding) | |
{ | |
var bytes = encoding.GetBytes(s); | |
return Convert.ToBase64String(bytes); | |
} | |
} | |
[Serializable] | |
public class AzureQueueException : Exception | |
{ | |
public AzureQueueException() { } | |
public AzureQueueException(string message) : base(message) { } | |
public AzureQueueException(string message, Exception inner) : base(message, inner) { } | |
protected AzureQueueException( | |
System.Runtime.Serialization.SerializationInfo info, | |
System.Runtime.Serialization.StreamingContext context) : base(info, context) { } | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment