Tuesday, November 24, 2009

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);
//Create the MessageQueue
messageQueue = MessageQueue.Create(queueName);
//Set Queue permission
//messageQueue.SetPermissions("Everyone", MessageQueueAccessRights.FullControl,
// AccessControlEntryType.Set);
MessageQueueAccessRights.PeekMessage |
MessageQueueAccessRights.ReceiveMessage |
MessageQueueAccessRights.DeleteMessage |

oMsg = new Message(myMessage);

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);

Nice link to refer -
Use Microsoft Message Queuing in C# for inter-process communication

No comments: