.NET includes a managed MSMQ API (System.Messaging) to send and receive messages, but unfortunately there's a key functionality missing: obtaining the number of messages currently in the queue. Yoel Arnon talks about this problem with more detail here and here. After reading that, we learn that there are three ways to overcome this limitation: using the MSMQ performance counters (with the .NET Performance Counter API or via WMI), using the MSMQ COM wrapper, or using the MSMQ Admin API directly. The first option is not very reliable and the second one is not available on all versions of MSMQ, so the third one is the preferable way. It's also the most complex. Jared Evans has explained how to do it using a C++ Managed wrapper here, but that approach adds some complexity to the deployment of your application. It forces you to redistribute the Microsoft Visual C++ Redistributable Package, and if you want to support the x64 versions of Windows, you have to build the C++ wrapper for both x86 and x64 and have additional logic in the application installer to know which version of your assembly to install (and the same for the Visual C++ Redistributable which also has two versions). Some months ago, I upgraded my home PC to Windows Vista x64, so at the time I decided to develop a C# only solution for this, as there wasn't any publicly available on the net.
The first approach I tried was to look at the mq.h file and translate all the required structures to C#. This proved to be a nightmare, as at the time the P/Invoke Interop Assistant hadn't been created yet and the structures proved to be a little complex. So instead of trying to translate the whole structures correctly, I turned on the debugger and started examining the fields that were really needed, defining dummy spacer fields for the rest. This took a while, but it was worth it. Here's the code:
using System;
using System.Messaging;
using System.Runtime.InteropServices;
static class MessageQueueExtensions {
[DllImport("mqrt.dll")]
private unsafe static extern int MQMgmtGetInfo(char* computerName, char* objectName, MQMGMTPROPS* mgmtProps);
private const byte VT_NULL = 1;
private const byte VT_UI4 = 19;
private const int PROPID_MGMT_QUEUE_MESSAGE_COUNT = 7;
//size must be 16
[StructLayout(LayoutKind.Sequential)]
private struct MQPROPVariant {
public byte vt; //0
public byte spacer; //1
public short spacer2; //2
public int spacer3; //4
public uint ulVal; //8
public int spacer4; //12
}
//size must be 16 in x86 and 28 in x64
[StructLayout(LayoutKind.Sequential)]
private unsafe struct MQMGMTPROPS {
public uint cProp;
public int* aPropID;
public MQPROPVariant* aPropVar;
public int* status;
}
public static uint GetCount(this MessageQueue queue) {
return GetCount(queue.Path);
}
private static unsafe uint GetCount(string path) {
if (!MessageQueue.Exists(path)) {
return 0;
}
MQMGMTPROPS props = new MQMGMTPROPS();
props.cProp = 1;
int aPropId = PROPID_MGMT_QUEUE_MESSAGE_COUNT;
props.aPropID = &aPropId;
MQPROPVariant aPropVar = new MQPROPVariant();
aPropVar.vt = VT_NULL;
props.aPropVar = &aPropVar;
int status = 0;
props.status = &status;
IntPtr objectName = Marshal.StringToBSTR("queue=Direct=OS:" + path);
try {
int result = MQMgmtGetInfo(null, (char*)objectName, &props);
if (result != 0 || *props.status != 0 || props.aPropVar->vt != VT_UI4) {
return 0;
} else {
return props.aPropVar->ulVal;
}
} finally {
Marshal.FreeBSTR(objectName);
}
}
}
Note that you'll have to go to the project properties and check the "Allow unsafe code" option for this to build.
Here's an example usage:
public static void Main() {
string queueName = @".\Private$\MyQueue";
if (MessageQueue.Exists(queueName)) {
MessageQueue.Delete(queueName);
}
MessageQueue queue = MessageQueue.Create(queueName);
Console.WriteLine("Count should be 0: " + queue.GetCount());
queue.Send("ping", "ping");
Console.WriteLine("Count should be 1: " + queue.GetCount());
queue.Send("ping2", "ping2");
Console.WriteLine("Count should be 2: " + queue.GetCount());
queue.Receive();
Console.WriteLine("Count should be 1: " + queue.GetCount());
queue.Send("ping3", "ping3");
Console.WriteLine("Count should be 2: " + queue.GetCount());
MessageQueue.Delete(queueName);
Console.WriteLine("Count should be 0: " + queue.GetCount());
}
After building and running, it should give you the following output:
Count should be 0: 0
Count should be 1: 1
Count should be 2: 2
Count should be 1: 1
Count should be 2: 2
Count should be 0: 0
Last week my colleague Rui Eugénio at OutSystems was doing a merge that involved similar code and commented to me "Couldn't this be done without using unsafe code?". That left me wondering, so I decided to give it a try. It turns out it wasn't that hard. Here's the safe version of the previous code:
using System;
using System.Messaging;
using System.Runtime.InteropServices;
public static class MessageQueueExtensions {
[DllImport("mqrt.dll")]
private static extern int MQMgmtGetInfo([MarshalAs(UnmanagedType.BStr)]string computerName, [MarshalAs(UnmanagedType.BStr)]string objectName, ref MQMGMTPROPS mgmtProps);
private const byte VT_NULL = 1;
private const byte VT_UI4 = 19;
private const int PROPID_MGMT_QUEUE_MESSAGE_COUNT = 7;
//size must be 16
[StructLayout(LayoutKind.Sequential)]
private struct MQPROPVariant {
public byte vt; //0
public byte spacer; //1
public short spacer2; //2
public int spacer3; //4
public uint ulVal; //8
public int spacer4; //12
}
//size must be 16 in x86 and 28 in x64
[StructLayout(LayoutKind.Sequential)]
private struct MQMGMTPROPS {
public uint cProp;
public IntPtr aPropID;
public IntPtr aPropVar;
public IntPtr status;
}
public static uint GetCount(this MessageQueue queue) {
return GetCount(queue.Path);
}
private static uint GetCount(string path) {
if (!MessageQueue.Exists(path)) {
return 0;
}
MQMGMTPROPS props = new MQMGMTPROPS { cProp = 1 };
try {
props.aPropID = Marshal.AllocHGlobal(sizeof(int));
Marshal.WriteInt32(props.aPropID, PROPID_MGMT_QUEUE_MESSAGE_COUNT);
props.aPropVar = Marshal.AllocHGlobal(Marshal.SizeOf(typeof(MQPROPVariant)));
Marshal.StructureToPtr(new MQPROPVariant { vt = VT_NULL }, props.aPropVar, false);
props.status = Marshal.AllocHGlobal(sizeof(int));
Marshal.WriteInt32(props.status, 0);
int result = MQMgmtGetInfo(null, "queue=Direct=OS:" + path, ref props);
if (result != 0 || Marshal.ReadInt32(props.status) != 0) {
return 0;
}
MQPROPVariant propVar = (MQPROPVariant)Marshal.PtrToStructure(props.aPropVar, typeof(MQPROPVariant));
if (propVar.vt != VT_UI4) {
return 0;
} else {
return propVar.ulVal;
}
} finally {
Marshal.FreeHGlobal(props.aPropID);
Marshal.FreeHGlobal(props.aPropVar);
Marshal.FreeHGlobal(props.status);
}
}
}
public class MessageQueueExtensionsTest {
public static void Main() {
string queueName = @".\Private$\MyQueue";
if (MessageQueue.Exists(queueName)) {
MessageQueue.Delete(queueName);
}
MessageQueue queue = MessageQueue.Create(queueName);
Console.WriteLine("Count should be 0: " + queue.GetCount());
queue.Send("ping", "ping");
Console.WriteLine("Count should be 1: " + queue.GetCount());
queue.Send("ping2", "ping2");
Console.WriteLine("Count should be 2: " + queue.GetCount());
queue.Receive();
Console.WriteLine("Count should be 1: " + queue.GetCount());
queue.Send("ping3", "ping3");
Console.WriteLine("Count should be 2: " + queue.GetCount());
MessageQueue.Delete(queueName);
Console.WriteLine("Count should be 0: " + queue.GetCount());
}
}
Technorati Tags:
MSMQ,
.NET