Skip to content

Instantly share code, notes, and snippets.

@SzymonPobiega
Created May 31, 2017 09:22
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save SzymonPobiega/ff01ad3feb50aece16cf19090c18f642 to your computer and use it in GitHub Desktop.
Save SzymonPobiega/ff01ad3feb50aece16cf19090c18f642 to your computer and use it in GitHub Desktop.
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