MSMQ operations in C#
Following code snippet demonstrate the way to do some common operations with Microsoft Message Queuing (MSMQ)-
1) Send message in MSMQ -
string queueName = @".\Private$\MyMSMQ";
string myMessage = "Hello World";
MessageQueue messageQueue = null;
Message oMsg = null;
//Sending Messages to MSMQ
if (MessageQueue.Exists(queueName))
{
messageQueue = new MessageQueue(queueName);
oMsg = new Message(myMessage);
messageQueue.Send(oMsg);
}
else
{
//Create the MessageQueue
messageQueue = MessageQueue.Create(queueName);
//Set Queue permission
//messageQueue.SetPermissions("Everyone", MessageQueueAccessRights.FullControl,
// AccessControlEntryType.Set);
messageQueue.SetPermissions("Everyone",
MessageQueueAccessRights.PeekMessage |
MessageQueueAccessRights.ReceiveMessage |
MessageQueueAccessRights.DeleteMessage |
MessageQueueAccessRights.WriteMessage,
AccessControlEntryType.Set);
oMsg = new Message(myMessage);
messageQueue.Send(oMsg);
}
2) Receive Message from MSMQ -
string myMessage= string.Empty;
string queueName = @".\Private$\MyMSMQ";
//Receiving Messages from MSMQ
MessageQueue messageQueue = new MessageQueue(queueName);
//To keep a check that if no messages present in MSMQ,
//control should return back in 1 second.
TimeSpan timeout = new TimeSpan(1);
Message message = null;
//Get all the messages present in the MSMQ and iterate through it.
MessageEnumerator enumerator = messageQueue.GetMessageEnumerator2();
if (enumerator.MoveNext())
message = enumerator.RemoveCurrent(timeout);
if (message != null)
{
messageBody = message.Body.ToString();
}
3) Display all the messages present in the MSMQ (without removing messages from queue)
StringBuilder allMessages = new StringBuilder();
string queueName = @".\Private$\MyMSMQ";
//Enumerating Messages from MSMQ
MessageQueue oMq = new MessageQueue(queueName);
foreach (Message message in oMq)
{
stringBuilder.Append(message.Body + ";");
}
4) Deletes all the messages contained in the MSMQ queue
string queueName = @".\Private$\MyMSMQ";
//Deletes all the messages contained in the MSMQ queue
MessageQueue messageQueue = new MessageQueue(queueName);
messageQueue.Purge();
Nice link to refer -
Use Microsoft Message Queuing in C# for inter-process communication
No comments:
Post a Comment