MSMQ – Basic Console application testing some basic functionalities
Posted by admin on July 25th, 2010Currently I'm doing some r&d on MSMQ and how to use it in an asp.net application. I started with these two links which explain the basics of MSMQ:
I created a small .NET Console Application to test out some of the examples myself. It's basically a lot the same code (some of it is exactly the same), but it made me easily change some settings to check how they worked together. Especially transactions interested me because I'll need them for my final code in our product.
This is the source project: MSMQ Basic - TryOut
Next is the code. I added explanations in the code itself. But you really should read the MSDN documentation as it is very clear. I haven't tried out journaling yet because you need two computers to test that, so I'll do that later on @work. Next up on r&d is MSMQ support in Spring.NET and after that checking a JMS (Java Message Service) implementation (and it's integration in Spring.NET).
-
using System;
-
using System.Messaging;
-
using System.Transactions;
-
-
namespace MSMQ
-
{
-
/// <summary>
-
/// @Author: Lieven Cardoen
-
/// This little program tests some of the functionalities of MSMQ.
-
/// Sending messages synchronously and asynchronously are covered.
-
/// Transactions are also covered, internally by MSMQ and externally by DTC.
-
/// A next step would be to use some threads, but this was just some minor R&D
-
/// that I had to do for our product Edumatic Exam.
-
/// Documentation:
-
/// http://msdn.microsoft.com/en-us/library/ms978425.aspx
-
/// http://msdn.microsoft.com/en-us/library/ms978430.aspx
-
/// </summary>
-
public class MsmqTryOut
-
{
-
protected MessageQueue MessageQueue;
-
private const string NonTransMessageQueueName = ".\\private$\\finishedSessionsNonTrans";
-
private const string IntTransMessageQueueName = ".\\private$\\finishedSessionsIntTrans";
-
private const string ExtTransMessageQueueName = ".\\private$\\finishedSessionsExtTrans";
-
private const string AckQueueName = ".\\private$\\Ack";
-
private const string OrdersQueueName = ".\\private$\\Orders";
-
-
/// <summary>
-
/// Main entry point
-
/// </summary>
-
static void Main()
-
{
-
-
//NON TRANSACTIONAL QUEUE --> SYNC AND ASYNC MESSAGES
-
program.SetUpQueue(NonTransMessageQueueName, false);
-
program.SendMessage(String.Format("Message sent at {0}", DateTime.Now)
-
, "Non-Transactional sync message (first message)", MessageQueueTransactionType.None);
-
program.SendMessage(String.Format("Message sent at {0}", DateTime.Now)
-
, "Non-Transactional async message (second message)", MessageQueueTransactionType.None);
-
/**
-
* Program would hang until a message is delivered (if no messages are in the queue
-
* and none are added anymore, program would hang forever).
-
* Here first message will be received
-
*/
-
program.ReceiveSyncMessage(MessageQueueTransactionType.None);
-
/**
-
* Program wouldn't hang forever. Handler would be triggered when new message in queue.
-
* Here second message will be received. If second message is received, the queue will be deleted
-
* in the async handler.
-
*/
-
program.ReceiveAsyncMessage();
-
-
-
//INTERNAL TRANSACTIONS (MSMQ)
-
program.SetUpQueue(IntTransMessageQueueName, true);
-
//Start the internal msmq transaction
-
msgTx.Begin();
-
program.SendMessage(String.Format("Message sent at {0}", DateTime.Now), "Internal MSMQ Transactional sync Message", msgTx);
-
program.SendMessage(String.Format("Message sent at {0}", DateTime.Now), "Internal MSMQ Transactional sync Message", msgTx);
-
msgTx.Commit();
-
-
//Start new transaction
-
msgTx.Begin();
-
program.ReceiveSyncMessage(msgTx);
-
program.ReceiveSyncMessage(msgTx);
-
Console.WriteLine("----------------------------------------------------------------------------------");
-
Console.WriteLine("Dispose transaction");
-
msgTx.Dispose();
-
//Two messages should still be available because previous receives were disposed
-
program.ReceiveSyncMessage(msgTx);
-
program.ReceiveAsyncMessage(); //queue will be deleted in the async handler
-
-
-
//TRANSACTIONAL QUEUE WITH EXTERNAL TRANSACTIONS (DTC)
-
program.SetUpQueue(ExtTransMessageQueueName, true);
-
//If it's a transactional queue, then Single needs to be used if the message
-
//isn't send in a transaction
-
program.SendMessage(String.Format("Message sent at {0}", DateTime.Now), "DTC Transactional sync Message", MessageQueueTransactionType.Single);
-
program.SendMessage(String.Format("Message sent at {0}", DateTime.Now), "DTC Transactional sync Message", MessageQueueTransactionType.Single);
-
{
-
//If a transaction is used and the queue is externally transactional (DTC),
-
//then Automatic needs to be used
-
program.ReceiveSyncMessage(MessageQueueTransactionType.Automatic);
-
program.ReceiveSyncMessage(MessageQueueTransactionType.Automatic);
-
//ReceiveAsync(); //!!! Apparently this won't be disposed. + error is thrown when async
-
//handler is triggered because the MessageQueue is already deleted.
-
Console.WriteLine("----------------------------------------------------------------------------------");
-
Console.WriteLine("Dispose transaction");
-
scope.Dispose();
-
}
-
//Two messages should still be available
-
program.ReceiveSyncMessage(MessageQueueTransactionType.Single);
-
program.ReceiveAsyncMessage(); //queue will be deleted in the async handler
-
-
//ACKNOWLEDGEMENTS
-
ReceiveAcknowledgementMessages();
-
DeleteQueue(OrdersQueueName);
-
DeleteQueue(AckQueueName);
-
-
-
//Pause the program
-
Console.ReadKey();
-
}
-
-
/// <summary>
-
/// Tests acknowledgements
-
/// </summary>
-
private static void ReceiveAcknowledgementMessages()
-
{
-
Console.WriteLine("----------------------------------------------------------------------------------");
-
if (!MessageQueue.Exists(OrdersQueueName)) MessageQueue.Create(OrdersQueueName);
-
if(!MessageQueue.Exists(AckQueueName)) MessageQueue.Create(AckQueueName);
-
//Send Message
-
{
-
DefaultPropertiesToSend =
-
{
-
AcknowledgeType = AcknowledgeTypes.FullReachQueue |
-
AcknowledgeTypes.FullReceive,
-
}
-
};
-
msgQ.Send("Sample");
-
-
//Receive Message
-
if (msg != null) Console.WriteLine("Message Received {0}", msg.Id);
-
-
//Receive Acknowledgement Messages
-
{
-
MessageReadPropertyFilter = {CorrelationId = true}
-
};
-
do
-
{
-
try
-
{
-
if (msg != null && msg.MessageType == MessageType.Acknowledgment)
-
switch(msg.Acknowledgment)
-
{
-
case Acknowledgment.ReachQueue:
-
Console.WriteLine("Message Reached Queue {0}", msg.CorrelationId);
-
break;
-
case Acknowledgment.Receive:
-
Console.WriteLine("Message Received {0}", msg.CorrelationId);
-
break;
-
}
-
}
-
catch(Exception e)
-
{
-
Console.WriteLine(e.Message);
-
msg = null;
-
}
-
}
-
while (msg != null);
-
}
-
-
/// <summary>
-
/// Get a message out of the queue synchronously
-
/// </summary>
-
/// <param name="messageQueueTransactionType">Type of transaction to be used</param>
-
private void ReceiveSyncMessage(MessageQueueTransactionType messageQueueTransactionType)
-
{
-
Console.WriteLine("----------------------------------------------------------------------------------");
-
var message = MessageQueue.Receive(messageQueueTransactionType);
-
if (message != null)
-
{
-
var text = message.Body as String;
-
var label = message.Label;
-
Console.WriteLine("Received sync message (type:" + messageQueueTransactionType + ")");
-
Console.WriteLine("Text:" + text);
-
Console.WriteLine("Label:" + label);
-
}
-
else
-
{
-
Console.WriteLine("ERROR: Message was null");
-
}
-
}
-
-
/// <summary>
-
/// Get a message out of the queue synchronously
-
/// </summary>
-
/// <param name="mgsTx">The MessageQueueTransaction to be used</param>
-
private void ReceiveSyncMessage(MessageQueueTransaction mgsTx)
-
{
-
Console.WriteLine("----------------------------------------------------------------------------------");
-
var message = MessageQueue.Receive(mgsTx);
-
if (message != null)
-
{
-
//We'll use the XmlMessageFormatter, but you could also use the binary formatter
-
var text = message.Body as String;
-
var label = message.Label;
-
Console.WriteLine("Received sync message (type:" + mgsTx + ")");
-
Console.WriteLine("Text:" + text);
-
Console.WriteLine("Label:" + label);
-
}
-
else
-
{
-
Console.WriteLine("ERROR: Message was null");
-
}
-
}
-
-
/// <summary>
-
/// Get a message out of the queue asynchronously.
-
/// If messages are very large and network is slow for instance, then it
-
/// take some time to get the message. If async is used, program will not
-
/// hang.
-
/// </summary>
-
private void ReceiveAsyncMessage()
-
{
-
MessageQueue.ReceiveCompleted += ReceiveCompletedHandler;
-
MessageQueue.BeginReceive();
-
}
-
-
/// <summary>
-
/// Asynchronous message handler
-
/// </summary>
-
/// <param name="sender">The MessageQueue</param>
-
/// <param name="args">Arguments (message can be accessed through the arguments</param>
-
private static void ReceiveCompletedHandler(Object sender, ReceiveCompletedEventArgs args)
-
{
-
Console.WriteLine("----------------------------------------------------------------------------------");
-
var message = args.Message;
-
//We'll use the XmlMessageFormatter, but you could also use the binary formatter
-
var text = message.Body as String;
-
var label = message.Label;
-
Console.WriteLine("Received async message");
-
Console.WriteLine("Can be received after queue is deleted.");
-
Console.WriteLine("Text:" + text);
-
Console.WriteLine("Label:" + label);
-
var messageQeueue = sender as MessageQueue;
-
-
//We delete the queue when the async message is received
-
//This is weird, but it makes things simple
-
if(messageQeueue != null) DeleteQueue(messageQeueue.Path);
-
else Console.WriteLine("ERROR: messageQueue was null");
-
}
-
-
/// <summary>
-
/// Sets up the queue. If queue doesn't exist, it is created.
-
/// </summary>
-
/// <param name="messageQueueName">Name of the queue</param>
-
/// <param name="transactional">Boolean whether queue should be transactional or not</param>
-
private void SetUpQueue(string messageQueueName, bool transactional)
-
{
-
Console.WriteLine("----------------------------------------------------------------------------------");
-
Console.WriteLine("SetUpQueue(" + messageQueueName + Environment.NewLine + ", "
-
+ (transactional ? "Transactional" : "Non-Transactional") + ")");
-
if (!MessageQueue.Exists(messageQueueName))
-
{
-
try
-
{
-
MessageQueue = MessageQueue.Create(messageQueueName, transactional);
-
}
-
catch (Exception createException)
-
{
-
//Error could occur creating queue if the code does
-
//not have sufficient permissions to create queues.
-
}
-
}
-
else
-
{
-
try
-
{
-
//Warning: If existing queue has a transactional property that
-
//is not equal to the transaction argument of the funtion
-
//the queue should actually be recreated.
-
}
-
catch(Exception getException)
-
{
-
}
-
}
-
//Gets or sets a value that indicates whether the message is guaranteed
-
//to be delivered in the event of a computer failure or network problem.
-
MessageQueue.DefaultPropertiesToSend.Recoverable = true;
-
}
-
-
/// <summary>
-
/// Deletes a queue
-
/// </summary>
-
/// <param name="messageQueueName">Name of the queue</param>
-
private static void DeleteQueue(string messageQueueName)
-
{
-
Console.WriteLine("----------------------------------------------------------------------------------");
-
Console.WriteLine("DeleteQueue(" + messageQueueName + ")");
-
try
-
{
-
MessageQueue.Delete(messageQueueName);
-
}
-
catch (Exception e)
-
{
-
}
-
}
-
-
/// <summary>
-
/// Sends a message to the queue
-
/// </summary>
-
/// <param name="textMessage">Text message</param>
-
/// <param name="label">Label of the message</param>
-
/// <param name="type">Type of transaction</param>
-
private void SendMessage(string textMessage, string label, MessageQueueTransactionType type)
-
{
-
Console.WriteLine("----------------------------------------------------------------------------------");
-
Console.WriteLine("SendMessage(" + textMessage + Environment.NewLine + ", " + label + ", " + type);
-
try
-
{
-
MessageQueue.Send(message, label, type);
-
}
-
catch (Exception e)
-
{
-
}
-
}
-
-
/// <summary>
-
/// Sends a message to the queue
-
/// </summary>
-
/// <param name="textMessage">Text message</param>
-
/// <param name="label">Label of the message</param>
-
/// <param name="msgTx">The MessageQueueTransaction to be used</param>
-
private void SendMessage(string textMessage, string label, MessageQueueTransaction msgTx)
-
{
-
Console.WriteLine("----------------------------------------------------------------------------------");
-
Console.WriteLine("SendMessage(" + textMessage + Environment.NewLine + ", " + label + ", " + msgTx);
-
try
-
{
-
MessageQueue.Send(message, label, msgTx);
-
}
-
catch (Exception e)
-
{
-
}
-
}
-
}
-
}


Recent Comments