November 25, 2009

MSMQ Count with C#

We had a bug in our production environment that filled up MSMQ and would be tied to a specific windows service that we had running. In order to fix this, the solution was to stop and start the windows service. The catch was that we only wanted to do this when the MessageQueue count was above a certain number. You can get access to the class here. A snippet of the main code is below:
public void Run()
{
if (TotalMessagesInAllQueues() >= MessagesCriticalCount)
{
StopService();
SendEmail();
StartService();
}
}

private ManagementObject GetServiceByName(string name)
{
List list = SearchObjects(string.Format("Select * From Win32_Service WHERE Name='{0}'", name));

if (list.Count == 0)
throw new Exception(string.Format("Service '{0}' can not be found", name));

return list[0];
}

private ulong TotalMessagesInAllQueues()
{
var list = SearchObjects("Select * From Win32_PerfRawData_MSMQ_MSMQService");
return (ulong)list[0].GetPropertyValue("TotalMessagesInAllQueues");
}

1 comment: