Skip to content

Instantly share code, notes, and snippets.

@mhagrelius
Created April 28, 2021 22:24
Show Gist options
  • Save mhagrelius/58c54fd0b7092edbb41f10de9f6420cc to your computer and use it in GitHub Desktop.
Save mhagrelius/58c54fd0b7092edbb41f10de9f6420cc to your computer and use it in GitHub Desktop.
Azure Service Bus Dead Letter Queue Drain
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<OutputType>Exe</OutputType>
<TargetFramework>net5.0</TargetFramework>
</PropertyGroup>
<ItemGroup>
<PackageReference Include="Azure.Messaging.ServiceBus" Version="7.1.2"/>
<PackageReference Include="CsvHelper" Version="27.0.2"/>
</ItemGroup>
</Project>
using System;
using System.Collections.Generic;
using System.Globalization;
using System.IO;
using Azure.Messaging.ServiceBus;
using CsvHelper;
string connectionString = @"";
string topicName = "";
string subscriptionName = "";
await using var client = new ServiceBusClient(connectionString);
var receiver = client.CreateReceiver(topicName, subscriptionName, new ServiceBusReceiverOptions
{
SubQueue = SubQueue.DeadLetter,
});
List<DeadLetterQueueEntry> entries = new();
ServiceBusReceivedMessage message = null;
try
{
while (true)
{
message = await receiver.ReceiveMessageAsync(TimeSpan.FromSeconds(5));
if (message == null)
{
break;
}
entries.Add(new DeadLetterQueueEntry(message.DeadLetterReason, message.EnqueuedTime, message.Body.ToString()));
await receiver.CompleteMessageAsync(message);
Console.WriteLine("Successfully pulled a new message from DLQ.");
}
}
catch
{
await receiver.AbandonMessageAsync(message);
}
finally
{
// A safer alternative would be to write each out as received and instead flush here.
// See https://joshclose.github.io/CsvHelper/getting-started/
using StreamWriter writer = new("messages.csv");
using CsvWriter csv = new(writer, CultureInfo.InvariantCulture);
csv.WriteRecords(entries);
}
public record DeadLetterQueueEntry(string Reason, DateTimeOffset EqueuedTime, string MessageBody);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment