How can I set a message to deadlettered - Service Bus

Today one of my colleague had an interesting problem in setting the SB Queue message as dead letter message. There are ton of sample around how to create DeadLetterQueue(DLQ) or move or read a DLQ message. But did not get a clear picture or documentation around “how one can set the message as Deadlettered through code”. As you know, messages would get automatically moved to DLQ after ‘n’ retry attempt or expiry but in this case he wanted to move it intentionally after some condition in code. For an example, when you see a body contains some text or invalid business code then I wanted to mark it as DeadLetter so that my other piece of code would drink it with recovery logic.

As usual, we started looking at our official documentation, Github pages, SB Explorer, internal discussion alias – there is lot of noise and confusion around in calling Receive/Defer/Deadletter but none gave a closest hint about marking a message as Deadletter. Spent almost couple of hours figuring out this 5 line of code Sad smile more importantly function call “order”. Failing to have this in order would give you hair pulling exception. So focus follow the “order”, say should mark it as Defer() before Receive() and then finally DeadLetter().

Microsoft.ServiceBus.Messaging.MessageNotFoundException was unhandled
HResult=-2146233088 IsTransient=false
Message=Failed to lock one or more specified messages. The message does not exist. TrackingId:2d6fb843-0bd8-4b73-9fc0-8f9bffe98ca7_G0_B0, SystemTracker:xxxxxx:QueueXXX, Timestamp:9/2/2016 7:34:42 PM 

 

//Sample code to receive a message with sequence number and then Deadletter

using Microsoft.ServiceBus.Messaging;

static void Main(string[] args)

        {

var queue = QueueClient.CreateFromConnectionString("Endpoint=sb://xxx.servicebus.windows.net/;SharedAccessKeyName=RootManageSharedAccessKey;SharedAccessKey=xxxx=", "queuename", ReceiveMode.PeekLock);

           BrokeredMessage msg = queue.Receive();

            msg.Defer();

            msg = queue.Receive(msg.SequenceNumber);

            msg.DeadLetter();

        }

Let me know if you think there is a better way than this.

good weekend !