How to get the total number of outgoing messages from a remote MSMQ server?
We have to use the COM interface of MSMQ to enumerate every outgoing queue's message count and sum up them to get the number. To get started, add mqoa30.tlb under system32 folder as reference in your VS project. Below is the code.
using System;
using System.Messaging;
using System.Collections;
namespace MSMQOutgoingMsgCount
{
class Program
{
static void Main(string[] args)
{
int MsgCount = 0;
//Set the string to the remote MSMQ server's name
string ServerName = "yinlin";
ArrayList OutgoingQueuenames = new ArrayList();
Console.WriteLine("Outgoing Queue List:");
Console.WriteLine("====================================");
try
{
MSMQ.MSMQApplication mq = new MSMQ.MSMQApplication();
//Set the remote server
mq.Machine = ServerName;
object obj = mq.ActiveQueues;
Object[] oArray = (Object[])obj;
for (int i = 0; i < oArray.Length; i++)
{
if (oArray[i] == null)
continue;
//For an Outgoing queue, its queue name should include "DIRECT=" and doesn't contain the servername.
if (oArray[i].ToString().IndexOf("DIRECT=") >= 0 && !oArray[i].ToString().Contains(ServerName))
{
OutgoingQueuenames.Add(oArray[i].ToString());
}
}
for (int i = 0; i < OutgoingQueuenames.Count; i++)
{
MSMQ.MSMQManagement mgmt = new MSMQ.MSMQManagement();
MSMQ.MSMQOutgoingQueueManagement outgoingMgmt = null;
//Set the remote MSMQ server
object Server = ServerName;
object Path = string.Empty;
object Mode = OutgoingQueuenames[i];
//Use the name of outgoing queue as the first parameter to call MSMQManagement.Init() method to get the MSMQOutgoingQueueManagement object
mgmt.Init(ref Server, ref Path, ref Mode);
outgoingMgmt = (MSMQ.MSMQOutgoingQueueManagement)mgmt;
//Use MSMQManagement.MessageCount to get the message count
MsgCount += outgoingMgmt.MessageCount;
Console.WriteLine(OutgoingQueuenames[i] + ": " + outgoingMgmt.MessageCount);
}
}
catch (Exception ee)
{
Console.WriteLine(ee.ToString());
}
Console.WriteLine();
Console.WriteLine("=======================");
Console.WriteLine("Total Messages: " + MsgCount.ToString());
Console.ReadLine();
}
}
}
Best regards,
WenJun Zhang