MSMQ – Basic Console application testing some basic functionality
Architecture July 25th, 2010
Currently 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).
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 | 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() { var program = new MsmqTryOut(); //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 var msgTx = new MessageQueueTransaction(); 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); using (var scope = new TransactionScope()) { //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 var msgQ = new MessageQueue(OrdersQueueName) { DefaultPropertiesToSend = { AcknowledgeType = AcknowledgeTypes.FullReachQueue | AcknowledgeTypes.FullReceive, AdministrationQueue = new MessageQueue(AckQueueName) } }; msgQ.Send("Sample"); //Receive Message var msg = msgQ.Receive(new TimeSpan(0), MessageQueueTransactionType.Single); if (msg != null) Console.WriteLine("Message Received {0}", msg.Id); //Receive Acknowledgement Messages var adminQ = new MessageQueue(AckQueueName) { MessageReadPropertyFilter = {CorrelationId = true} }; do { try { msg = adminQ.Receive(new TimeSpan(0,0,5)); 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 ///Type of transaction to be used private void ReceiveSyncMessage(MessageQueueTransactionType messageQueueTransactionType) { Console.WriteLine("----------------------------------------------------------------------------------"); var message = MessageQueue.Receive(messageQueueTransactionType); if (message != null) { message.Formatter = new XmlMessageFormatter(new[] {typeof (String)}); 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> ///The MessageQueueTransaction to be used 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 message.Formatter = new XmlMessageFormatter(new[] { typeof(String) }); 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> ///The MessageQueue ///Arguments (message can be accessed through the arguments 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 message.Formatter = new XmlMessageFormatter(new[] { typeof(String) }); 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> ///Name of the queue ///Boolean whether queue should be transactional or not 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. throw new Exception("Error Creating Queue", createException); } } 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. MessageQueue = new MessageQueue(messageQueueName); } catch(Exception getException) { throw new Exception("Error Getting Queue", 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> ///Name of the queue private static void DeleteQueue(string messageQueueName) { Console.WriteLine("----------------------------------------------------------------------------------"); Console.WriteLine("DeleteQueue(" + messageQueueName + ")"); try { MessageQueue.Delete(messageQueueName); } catch (Exception e) { throw new Exception("Deletion Failed", e); } } /// <summary> /// Sends a message to the queue /// </summary> ///Text message ///Label of the message ///Type of transaction private void SendMessage(string textMessage, string label, MessageQueueTransactionType type) { Console.WriteLine("----------------------------------------------------------------------------------"); Console.WriteLine("SendMessage(" + textMessage + Environment.NewLine + ", " + label + ", " + type); try { var message = new Message {Body = textMessage, Recoverable = true}; MessageQueue.Send(message, label, type); } catch (Exception e) { throw new Exception("Error sending message to Queueu", e); } } /// <summary> /// Sends a message to the queue /// </summary> ///Text message ///Label of the message ///The MessageQueueTransaction to be used private void SendMessage(string textMessage, string label, MessageQueueTransaction msgTx) { Console.WriteLine("----------------------------------------------------------------------------------"); Console.WriteLine("SendMessage(" + textMessage + Environment.NewLine + ", " + label + ", " + msgTx); try { var message = new Message { Body = textMessage, Recoverable = true }; MessageQueue.Send(message, label, msgTx); } catch (Exception e) { throw new Exception("Error sending message to Queueu", e); } } } } |
Follow Me!