Tags

, ,

MSMQ stands for Microsoft Message Queuing which provides a great framework for applications that use messaging infrastructure.

Just like e-mail we can send and receive message from it to provides integration between two or more application.

You can create msmq from computer management snap-in at node under the Services and Applications section, there is one node called [Message Queuing]. From there, you can create Public Queue or Private Queue.

To create Transactional MSMQ, don’t forget the check the “Transactional” checkbox when you create a queue. If you want to have histories of the message queue, you can achieve it by set enable msmq’s journal.

Here is the code for send transactional message to our msmq:

using (TransactionScope scope = new TransactionScope(TransactionScopeOption.RequiresNew))
{
try
{
//Declare queue's name where we want to send our message.
string queuePath = @".\TestQueue"

//Create message queue object
MessageQueue msmq = MessageQueue(queuePath, QueueAccessMode.SendAndReceive);

//Create message object
Message msg = new Message();
msg.UseAuthentication = false;
msg.Recoverable = true;
msg.Body = “Hello World”;

//Send our message
msmq.Send(msg, MessageQueueTransactionType.Automatic);

//Commit transaction
scope.Complete();
}
catch(Exception ex)
{
Console.Writeline(ex.Message);
}
finally
{
//Close message queue object.
msmq.Close();
}
}

Here is the code for receive transactional message to our msmq:


using (TransactionScope scope = new TransactionScope(TransactionScopeOption.Required))
{

try
{
//Declare queue’s name where we want to receive the message.
string queuePath = @”.\TestQueue”

//Create message queue object
MessageQueue msmq= new MessageQueue(queuePath, QueueAccessMode.SendAndReceive);

//Receive message
Message msg = msmq.Receive(new TimeSpan(0), MessageQueueTransactionType.Automatic);

//Validate the message
if (msg != null)
Console.WriteLine(msg.Body);

//Commit transaction
scope.Complete();

}
catch(Exception ex)
{
Console.WriteLine(ex.Message);
}
finally
{
//Close message queue object.
msmq.Close();
}
}

From here, you already know how to send and receive msmq and how to implement to your application. Hope this resource can be usefull for your project.

Advertisements