Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
using System;
using System.Collections.Generic;
using System.Linq;
using System.Messaging;
using System.Reflection;
using System.Text;
using System.Threading.Tasks;
namespace MsmqDeadLetterQueuePoC
{
class Program
{
const string PREFIX = "FormatName:" + DIRECTPREFIX;
const string DIRECTPREFIX = "DIRECT=OS:";
const string PRIVATE = "\\private$\\";
static void Main(string[] args)
{
var deadLetter = @"SIMON-MAC\PRIVATE$\DeadLetter"; //GetPath("SIMON-MAC", "DeadLetter");
var notExistingQUeue = GetPath("SIMON-MAC", "timeouts");//GetPath("NoMachine", "NoQueue");
using (var queue = new MessageQueue(notExistingQUeue))
{
var messageType = typeof(Message);
var propType = messageType.Assembly.GetType("System.Messaging.Interop.MessagePropertyVariants");
var flagsInstance = BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic;
var propField = messageType.GetField("properties", flagsInstance);
var setString = propType.GetMethod("SetString", flagsInstance);
var setUI4 = propType.GetMethod("SetUI4", flagsInstance);
var setUI1 = propType.GetMethod("SetUI1", flagsInstance);
var setUI4Vector = propType.GetMethod("SetUI1Vector", flagsInstance);
var message = new Message();
var ctor = propType.GetConstructor(BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance, null, new[] {typeof(int), typeof(int)}, null);
var newProps = ctor.Invoke(new object[] {70, 1});
setUI4Vector.Invoke(newProps, new object[] {2, new byte[20]});
propField.SetValue(message, newProps);
//message.TimeToReachQueue = TimeSpan.FromDays(1000); //TimeSpan.FromSeconds(30);
message.TimeToBeReceived = TimeSpan.FromDays(1000);
setUI1.Invoke(newProps, new object[] { 7, (byte)1 }); //Enable dead letter
var buffer = StringToBytes(deadLetter);
setString.Invoke(newProps, new object[] { 67, buffer });
setUI4.Invoke(newProps, new object[] { 68, deadLetter.Length });
queue.Send(message, MessageQueueTransactionType.Single);
}
Console.WriteLine("Press <enter> to exit");
Console.ReadLine();
}
static string GetPath(string machine, string queue)
{
return PREFIX + machine + PRIVATE + queue;
}
internal static byte[] StringToBytes(string value)
{
//var buffer = new byte[]
//value.CopyTo(0, this.buffer, 0, value.Length);
//this.buffer[value.Length] = '\0';
int length = value.Length * 2 + 1;
byte[] bytes = new byte[length];
bytes[length - 1] = (byte)0;
Encoding.Unicode.GetBytes(value.ToCharArray(), 0, value.Length, bytes, 0);
return bytes;
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment