void DoWork()
            {
                while (keepWorking)
                {
                    try
                    {
                        using (var tx = new TransactionScope())
                        {
                            var transactionContext = new AmbientTransactionContext();
                            var message            = queue.ReceiveMessage(transactionContext);
                            if (message == null)
                            {
                                Thread.Sleep(200);
                                continue;
                            }

                            var destinationForThisMessage = getNextDestination();

                            log.Debug("Received message {0} will be forwarded to {1}", message.Id, destinationForThisMessage);

                            queue.Send(destinationForThisMessage, message.ToForwardableMessage(), transactionContext);

                            tx.Complete();
                        }
                    }
                    catch (Exception exception)
                    {
                        log.Error("An error occurred while trying to process a message: {0}", exception);
                    }
                }
            }
        public void DoesNotLeakMessages()
        {
            // arrange
            const string inputQueueName = "test.leak.input";
            var          queue          = new MsmqMessageQueue(inputQueueName);

            disposables.Add(queue);

            var body    = Encoding.UTF8.GetBytes(new string('*', 32768));
            var message = new TransportMessageToSend
            {
                Headers = new Dictionary <string, object> {
                    { Headers.MessageId, "msg-1" }
                },
                Body = body
            };

            var weakMessageRef = new WeakReference(message);
            var weakBodyRef    = new WeakReference(body);


            // act
            queue.Send(inputQueueName, message, new NoTransaction());
            message = null;
            body    = null;

            GC.Collect();
            GC.WaitForPendingFinalizers();

            // assert
            Assert.That(weakMessageRef.IsAlive, Is.False, "Expected the message to have been collected");
            Assert.That(weakBodyRef.IsAlive, Is.False, "Expected the body bytes to have been collected");
        }
Exemple #3
0
        private string SendMessageImpl(object message, string correlationId, TimeSpan timeToBeReceived)
        {
            var transactionOptions = new TransactionOptions {
                IsolationLevel = IsolationLevel.ReadCommitted
            };
            var transactionScope = !IsTransactional
                ? null
                : new TransactionScope(TransactionScopeOption.Required, transactionOptions);

            using (transactionScope)
            {
                try
                {
                    var msg = new Message {
                        Body = message, TimeToBeReceived = timeToBeReceived
                    };

                    if (!string.IsNullOrEmpty(correlationId))
                    {
                        msg.CorrelationId = correlationId;
                    }

                    MsmqMessageQueue.Send(
                        msg,
                        IsTransactional ? MessageQueueTransactionType.Automatic : MessageQueueTransactionType.None);
                    lock (Synch)
                    {
                        AddMessageAudit(msg);
                    }

                    Logger.DebugFormat("Sent message to [{0}]...", QueueName);
                    if (transactionScope != null)
                    {
                        transactionScope.Complete();
                    }

                    return(msg.Id);
                }
                catch (Exception ex)
                {
                    Logger.ErrorFormat(ex, "Exception encountered by [{0}] sending Message [{1}].", this, message);
                    throw;
                }
            }
        }
Exemple #4
0
        public void MessageExpirationWorks()
        {
            // arrange
            var timeToBeReceived = 2.Seconds()
                                   .ToString();

            senderQueue.Send(destinationQueueName,
                             serializer.Serialize(new Message
            {
                Messages = new object[] { "HELLO WORLD!" },
                Headers  = new Dictionary <string, string> {
                    { Headers.TimeToBeReceived, timeToBeReceived }
                },
            }));

            // act
            Thread.Sleep(2.Seconds() + 1.Seconds());

            // assert
            Assert.Throws <MessageQueueException>(() => destinationQueue.Receive(0.1.Seconds()));
        }
Exemple #5
0
        public void CheckSendPerformance(int count)
        {
            var queue = new MsmqMessageQueue("test.msmq.performance").PurgeInputQueue();

            TrackDisposable(queue);

            var transportMessageToSend = new TransportMessageToSend
            {
                Headers = new Dictionary <string, object>(),
                Body    = new byte[1024],
                Label   = "this is just a label"
            };

            var stopwatch = Stopwatch.StartNew();

            count.Times(() => queue.Send("test.msmq.performance", transportMessageToSend, new NoTransaction()));
            var totalSeconds = stopwatch.Elapsed.TotalSeconds;

            Console.WriteLine("Sending {0} messages took {1:0} s - that's {2:0} msg/s",
                              count, totalSeconds, count / totalSeconds);
        }
Exemple #6
0
        public void CanSendAndReceiveMessageToQueueOnLocalhost()
        {
            // arrange
            var queue = new MsmqMessageQueue("test.msmq.loca.input").PurgeInputQueue();

            TrackDisposable(queue);

            const string localHostQualifiedQueueName = "test.msmq.loca.input@localhost";

            // act
            queue.Send(localHostQualifiedQueueName, new TransportMessageToSend {
                Body = Encoding.UTF8.GetBytes("yo dawg!")
            }, new NoTransaction());

            Thread.Sleep(200);

            // assert
            var receivedTransportMessage = queue.ReceiveMessage(new NoTransaction());

            receivedTransportMessage.ShouldNotBe(null);
            Encoding.UTF8.GetString(receivedTransportMessage.Body).ShouldBe("yo dawg!");
        }
Exemple #7
0
        public void CanSendAndReceiveMessageToQueueOnSpecificMachine()
        {
            // arrange
            var queue = new MsmqMessageQueue("test.msmq.mach.input").PurgeInputQueue();

            TrackDisposable(queue);

            var machineQualifiedQueueName = "test.msmq.mach.input@" + Environment.MachineName;

            // act
            queue.Send(machineQualifiedQueueName, new TransportMessageToSend {
                Body = Encoding.UTF8.GetBytes("yo dawg!")
            }, new NoTransaction());

            Thread.Sleep(200);

            // assert
            var receivedTransportMessage = queue.ReceiveMessage(new NoTransaction());

            receivedTransportMessage.ShouldNotBe(null);
            Encoding.UTF8.GetString(receivedTransportMessage.Body).ShouldBe("yo dawg!");
        }
Exemple #8
0
        public void CanSendAndReceiveMessageToQueueOnMachineSpecifiedByIp()
        {
            var ipAddress = GuessOwnIpAddress();

            // arrange
            var queue = new MsmqMessageQueue("test.msmq.ip.input").PurgeInputQueue();

            TrackDisposable(queue);

            var ipQualifiedName = "test.msmq.ip.input@" + ipAddress;

            // act
            queue.Send(ipQualifiedName, new TransportMessageToSend {
                Body = Encoding.UTF8.GetBytes("yo dawg!")
            }, new NoTransaction());

            Thread.Sleep(1.Seconds());

            // assert
            var receivedTransportMessage = queue.ReceiveMessage(new NoTransaction());

            receivedTransportMessage.ShouldNotBe(null);
            Encoding.UTF8.GetString(receivedTransportMessage.Body).ShouldBe("yo dawg!");
        }
Exemple #9
0
        static void Run(Parameters parameters)
        {
            if (string.IsNullOrWhiteSpace(parameters.ErrorQueueName))
            {
                throw new NiceException("Please specify the name of an error queue");
            }

            using (var tx = new TransactionScope())
            {
                var transactionContext = new AmbientTransactionContext();

                if (!MessageQueue.Exists(MsmqUtil.GetPath(parameters.ErrorQueueName)))
                {
                    throw new NiceException("The MSMQ queue '{0}' does not exist!", parameters.ErrorQueueName);
                }

                var msmqMessageQueue = new MsmqMessageQueue(parameters.ErrorQueueName, allowRemoteQueue: true);
                var allTheMessages   = GetAllTheMessages(msmqMessageQueue, transactionContext);

                foreach (var message in allTheMessages)
                {
                    var transportMessageToSend = message.ToForwardableMessage();

                    try
                    {
                        if (!transportMessageToSend.Headers.ContainsKey(Headers.SourceQueue))
                        {
                            throw new NiceException(
                                      "Message {0} does not have a source queue header - it will be moved back to the input queue",
                                      message.Id);
                        }

                        var sourceQueue = (string)transportMessageToSend.Headers[Headers.SourceQueue];

                        if (parameters.AutoMoveAllMessages.GetValueOrDefault())
                        {
                            msmqMessageQueue.Send(sourceQueue, transportMessageToSend, transactionContext);

                            Print("Moved {0} to {1}", message.Id, sourceQueue);
                        }
                        else
                        {
                            var answer = PromptChar(new[] { 'y', 'n' }, "Would you like to move {0} to {1}? (y/n)",
                                                    message.Id, sourceQueue);

                            if (answer == 'y')
                            {
                                msmqMessageQueue.Send(sourceQueue, transportMessageToSend, transactionContext);

                                Print("Moved {0} to {1}", message.Id, sourceQueue);
                            }
                            else
                            {
                                msmqMessageQueue.Send(msmqMessageQueue.InputQueueAddress,
                                                      transportMessageToSend,
                                                      transactionContext);

                                Print("Moved {0} to {1}", message.Id, msmqMessageQueue.InputQueueAddress);
                            }
                        }
                    }
                    catch (NiceException e)
                    {
                        Print(e.Message);

                        msmqMessageQueue.Send(msmqMessageQueue.InputQueueAddress,
                                              transportMessageToSend,
                                              transactionContext);
                    }
                }

                if (parameters.DryRun.GetValueOrDefault())
                {
                    Print("Aborting queue transaction");
                    return;
                }

                if (!parameters.Interactive)
                {
                    tx.Complete();
                    return;
                }

                var commitAnswer = PromptChar(new[] { 'y', 'n' }, "Would you like to commit the queue transaction?");

                if (commitAnswer == 'y')
                {
                    Print("Committing queue transaction");

                    tx.Complete();
                    return;
                }

                Print("Queue transaction aborted");
            }
        }
 private IMessage SendTestMessage()
 {
     return(_sut.Send(new MsmqMessage(new MemoryStream(Encoding.UTF8.GetBytes("test")), "Test Message")));
 }