Count number of messages in a clustered MSMQ

35 Views Asked by At

I'm trying to get a count of number of messages in a transactional queue on a clustered MSMQ, but for some reason this code:

    static int GetMessageCount(MessageQueue q)
    {
        var filter = new MessagePropertyFilter()
        {
            AdministrationQueue = false,
            ArrivedTime = false,
            CorrelationId = false,
            Priority = false,
            ResponseQueue = false,
            SentTime = false,
            Body = false,
            Label = false,
            Id = false
        };
        q.MessageReadPropertyFilter = filter;
     
        return q.GetAllMessages().Length;
    }

With the queue path provided as:

FormatName:Direct=OS:cl-msmq\private$\t_Main.DroppedData

Give me a result of "0". If I check the queue it has 53 messages in queue. I've tried other variants of the path to the queue, but the one above is the only one NOT throwing an exception that it can't use the path.

Where am I going wrong here?

I'm able to send messages to that queue from the server in question, just not give a count. I've tried stepping through the queue using .Peek, message by message, but that also just give me "0" messages.

2

There are 2 best solutions below

2
John Breakwell On

Maybe it's an RPC/permissions issue where you're not able to read the data from MSMQ (even though you can write to MSMQ as that doesn't use RPC). Would have expected an error, though. Is there code to swallow exceptions?

0
JaggenSWE On

Not sure where, in all my google journeys during the last 2 days, I read about this. But here goes.

  1. Add a reference to the Type Library

C:\Windows\System32\mqoa30.tlb

Then this piece of code will sort everything out:

    public static uint GetMessageCount(string machineName)
    {
        var formatName = @"Direct=OS:"+ machineName +"\private$\t_Main.DroppedData";

        try
        {
            var msmqManagement = new MSMQ.MSMQManagement();
            msmqManagement.Init(machineName, null, formatName);
         
            return (uint)msmqManagement.MessageCount;
        }
        catch (COMException ex)
        {
            if (ex.ErrorCode == -1072824316)
            {
                return 0;
            }

            throw;
        }
    }

As a gotcha, do NOT include the FormatName: in the MSMQ path since it's already implied in the call.

Still not sure WHY this approach worked, but the regular .NET way just didn't want to play ball when it was a transactional queue on a clustered MSMQ.