How to GET the message count of MSMQ in .NET without using PerformanceCounter

Link: SQL Server How to GET the message count of MSMQ in .NET without PerformanceCounter?, dotnet samples.

This article explains how to GET the message count of MSMQ in .NET without System.Diagnostics.PerformanceCounter. So we dont need to worry about the security-permission settings.

We can get the message count of a message queue using MSMQ Local Admin API MQMgmtGetInfo(). This API is fully supported by Microsoft on all versions of MSMQ. We can call this API from C#.NET directly as P/Invoke. Or we can write a C++ Managed wrapper over it and then call it from C#.NET. I preferred the second approach because it is much faster and there is no possibility of runtime data type mismatches as it is there in P/Invoke.

To call this API, we need two files; 1) mq.h and 2) mqrt.lib. Both these files should be there in your system if you have VC++ 7.0 (i.e., VC++ of .NET 2003) installed on your system.

Now start a new VC++ Class Library project "MsmqApiLib" in your .NET IDE.

Add mqrt.lib as an external dependency of that project. To do this, follow the steps:
1. Open the Property dialog of the Project.
2. Select "All Configurations" from the Configuration combo box.
3. Go to the "Input" under "Linker".
4. Type "mqrt.lib" in the Additional Dependencies box.
5. Click on OK. :-)

Then include the mq.h in your MsmqApiLib.cpp file –

#include <mq.h>

And then embed the following code in your function body –

//===============================================
// Machine -> Name of the remote machine
//            or NULL for local machine.
// eg, buddha
// Queue   -> Formated name of the queue
//            with "queue=" as prefix.
// eg, queue=DIRECT=OS:buddha\private$\msmqtriggersnotifications
//
// From C#.NET you can use this function as –
//
// MsmqApiLib mqLib = new MsmqApiLib();
// long count = mqLib.GetMessageCount( "buddha",
//    "queue=DIRECT=OS:buddha\private$\msmqtriggersnotifications" );
//
//=================================================
long MsmqApiLib::GetMessageCount( String *Machine, String *Queue )
{
    const wchar_t __pin* m = PtrToStringChars( Machine );
    const wchar_t __pin* q = PtrToStringChars( Queue );
    QUEUEPROPID   propId[1];
    MQPROPVARIANT propVar[1];
    HRESULT       propStatus[1];
    DWORD         cprop = 0;
    propId [cprop] = PROPID_MGMT_QUEUE_MESSAGE_COUNT;
    propVar[cprop].vt = VT_NULL;
    ++cprop;
    MQMGMTPROPS mqProps;
    mqProps.cProp    = cprop;
    mqProps.aPropID  = propId;
    mqProps.aPropVar = propVar;
    mqProps.aStatus  = propStatus;
    HRESULT hr = MQMgmtGetInfo( m, q, &mqProps );
    if( FAILED( hr ) )
    {
        return -1;
    }
    else
    {
        return mqProps.aPropVar[0].ulVal;
    }
}
//================================================

NB: Using this API you will get the message count of only ACTIVE (ie, open) queues.

This entry was posted in Uncategorized. Bookmark the permalink.