1
+ using System ;
2
+ using System . Messaging ;
3
+ using System . Runtime . InteropServices ;
4
+
5
+ static class MsmqExtensions
6
+ {
7
+ /// <remarks>
8
+ /// Source: http://functionalflow.co.uk/blog/2008/08/27/counting-the-number-of-messages-in-a-message-queue-in/
9
+ /// </remarks>
10
+ public static int GetCount ( this MessageQueue self )
11
+ {
12
+ var props = new Win32 . MQMGMTPROPS { cProp = 1 } ;
13
+ try
14
+ {
15
+ props . aPropID = Marshal . AllocHGlobal ( sizeof ( int ) ) ;
16
+ Marshal . WriteInt32 ( props . aPropID , Win32 . PROPID_MGMT_QUEUE_MESSAGE_COUNT ) ;
17
+
18
+ props . aPropVar = Marshal . AllocHGlobal ( Marshal . SizeOf ( typeof ( Win32 . MQPROPVariant ) ) ) ;
19
+ Marshal . StructureToPtr ( new Win32 . MQPROPVariant { vt = Win32 . VT_NULL } , props . aPropVar , false ) ;
20
+
21
+ props . status = Marshal . AllocHGlobal ( sizeof ( int ) ) ;
22
+ Marshal . WriteInt32 ( props . status , 0 ) ;
23
+
24
+ var result = Win32 . MQMgmtGetInfo ( null , "queue=" + self . FormatName , ref props ) ;
25
+ if ( result != 0 )
26
+ {
27
+ throw new InvalidOperationException ( $ "Unable to retrieve queue information (error: { result : x8} ") ;
28
+ }
29
+
30
+ if ( Marshal . ReadInt32 ( props . status ) != 0 )
31
+ {
32
+ return - 1 ;
33
+ }
34
+
35
+ var propVar = ( Win32 . MQPROPVariant ) Marshal . PtrToStructure ( props . aPropVar , typeof ( Win32 . MQPROPVariant ) ) ;
36
+
37
+ return propVar . vt != Win32 . VT_UI4
38
+ ? 0
39
+ : Convert . ToInt32 ( propVar . ulVal ) ;
40
+ }
41
+ finally
42
+ {
43
+ Marshal . FreeHGlobal ( props . aPropID ) ;
44
+ Marshal . FreeHGlobal ( props . aPropVar ) ;
45
+ Marshal . FreeHGlobal ( props . status ) ;
46
+ }
47
+ }
48
+
49
+ static class Win32
50
+ {
51
+ [ DllImport ( "mqrt.dll" ) ]
52
+ internal static extern uint MQMgmtGetInfo ( [ MarshalAs ( UnmanagedType . BStr ) ] string computerName , [ MarshalAs ( UnmanagedType . BStr ) ] string objectName , ref MQMGMTPROPS mgmtProps ) ;
53
+
54
+ public const byte VT_NULL = 1 ;
55
+ public const byte VT_UI4 = 19 ;
56
+ public const int PROPID_MGMT_QUEUE_MESSAGE_COUNT = 7 ;
57
+
58
+ //size must be 16
59
+ [ StructLayout ( LayoutKind . Sequential ) ]
60
+ internal struct MQPROPVariant
61
+ {
62
+ public byte vt ; //0
63
+ public byte spacer ; //1
64
+ public short spacer2 ; //2
65
+ public int spacer3 ; //4
66
+ public uint ulVal ; //8
67
+ public int spacer4 ; //12
68
+ }
69
+
70
+ //size must be 16 in x86 and 28 in x64
71
+ [ StructLayout ( LayoutKind . Sequential ) ]
72
+ internal struct MQMGMTPROPS
73
+ {
74
+ public uint cProp ;
75
+ public IntPtr aPropID ;
76
+ public IntPtr aPropVar ;
77
+ public IntPtr status ;
78
+ }
79
+ }
80
+ }
0 commit comments