Beispiel #1
0
        protected override void DoTearDown()
        {
            timeoutService.Stop();

            MsmqUtil.Delete(SagaBusInputQueueName);
            MsmqUtil.Delete(ServiceBusInputQueueName);
        }
Beispiel #2
0
        /// <summary>
        /// Sends the given <see cref="TransportMessageToSend"/> to the input queue specified by <see cref="inputQueueName"/>
        /// using MSMQ
        /// </summary>
        public void Send(string destinationQueueName, TransportMessageToSend message, ITransactionContext context)
        {
            var recipientPath = MsmqUtil.GetSenderPath(destinationQueueName);

            try
            {
                if (!context.IsTransactional)
                {
                    using (var outputQueue = GetMessageQueue(recipientPath))
                        using (var transaction = new MessageQueueTransaction())
                        {
                            transaction.Begin();
                            outputQueue.Send(message, transaction);
                            transaction.Commit();
                        }
                    return;
                }

                using (var outputQueue = GetMessageQueue(recipientPath))
                {
                    outputQueue.Send(message, GetTransaction(context));
                }
            }
            catch (Exception e)
            {
                throw new ApplicationException(string.Format("An error occurred while attempting to send {0} to {1}",
                                                             message, destinationQueueName), e);
            }
        }
        BuiltinContainerAdapter GetBus(string inputQueueName, bool encryption, bool compression)
        {
            var adapter = TrackDisposable(new BuiltinContainerAdapter());

            MsmqUtil.PurgeQueue(inputQueueName);

            Configure.With(adapter)
            .Logging(l => l.ColoredConsole(LogLevel.Warn))
            .Transport(t => t.UseMsmq(inputQueueName, ErrorQueueName))
            .MessageOwnership(o => o.Use(this))
            .Decorators(d =>
            {
                // make this the first decoration step and thus the innermost decorator
                d.AddDecoration(b => b.SendMessages = new TellTaleSender(b.SendMessages));

                if (encryption)
                {
                    d.EncryptMessageBodies("NLEJVjDYnKfxEUAl2gxflFJfixHwh94iWDltaoayjTM=");
                }

                if (compression)
                {
                    d.CompressMessageBodies(0);
                }
            })
            .CreateBus()
            .Start();

            return(adapter);
        }
Beispiel #4
0
        private void SendToAllWorkers(Message message, string logMessage)
        {
            var values = KnownWorkers.GetValues();

            foreach (var worker in values)
            {
                var workerEndpoint = endpointRouter.GetRoutedEndpoint(worker);
                using (var workerQueue = MsmqUtil.GetQueuePath(workerEndpoint).Open(QueueAccessMode.Send))
                {
                    logger.DebugFormat(logMessage, Endpoint.Uri, worker);
                    workerQueue.Send(message);
                }
            }
            if (values.Length == 0)
            {
                return;
            }

            var copy = MessageBatchSentToAllWorkers;

            if (copy != null)
            {
                copy(message);
            }
        }
Beispiel #5
0
        protected override void BeforeStart(OpenedQueue queue)
        {
            try
            {
                queueStrategy.InitializeQueue(Endpoint, QueueType.LoadBalancer);
            }
            catch (Exception e)
            {
                throw new TransportException(
                          "Could not open queue for load balancer: " + Endpoint + Environment.NewLine +
                          "Queue path: " + MsmqUtil.GetQueuePath(Endpoint), e);
            }

            try
            {
                ReadUrisFromSubQueue(KnownWorkers, SubQueue.Workers);
            }
            catch (Exception e)
            {
                throw new InvalidOperationException("Could not read workers subqueue", e);
            }

            try
            {
                ReadUrisFromSubQueue(KnownEndpoints, SubQueue.Endpoints);
            }
            catch (Exception e)
            {
                throw new InvalidOperationException("Could not read endpoints subqueue", e);
            }

            RemoveAllReadyToWorkMessages();
        }
Beispiel #6
0
        public void CanSendOldFormat()
        {
            _bus.Advanced.Routing.Send(_oldEndpoint, new OldSchoolMessage {
                KeyChar = "g"
            }).Wait();

            using (var queue = new MessageQueue(MsmqUtil.GetFullPath(_oldEndpoint)))
            {
                var message = queue.GetNextMessage();

                using (var streamReader = new StreamReader(message.BodyStream, Encoding.UTF7))
                {
                    var jsonText = streamReader.ReadToEnd();

                    Assert.That(jsonText.ToNormalizedJson(), Is.EqualTo(ValidLegacyRebusMessage.ToNormalizedJson()));
                }

                var headers = message.DeserializeHeaders();

                Console.WriteLine(@"Headers:
{0}", string.Join(Environment.NewLine, headers.Select(kvp => string.Format("    {0}: {1}", kvp.Key, kvp.Value))));

                Assert.That(headers["rebus-msg-id"], Is.Not.Empty);
                Assert.That(headers["rebus-content-type"], Is.EqualTo("text/json"));
                Assert.That(headers["rebus-encoding"], Is.EqualTo("utf-7"));
                Assert.That(headers["rebus-return-address"], Is.EqualTo(_newEndpoint + "@" + Environment.MachineName));
            }
        }
Beispiel #7
0
        private void PersistEndpoint(OpenedQueue queue, Message message)
        {
            var queueUri = MsmqUtil.GetQueueUri(message.ResponseQueue);

            if (queueUri == null)
            {
                return;
            }
            bool needToPersist = knownEndpoints.Add(queueUri);

            if (needToPersist == false)
            {
                return;
            }

            logger.InfoFormat("Adding new endpoint: {0}", queueUri);
            var persistedEndPoint = new Message
            {
                Formatter = new XmlMessageFormatter(new[] { typeof(string) }),
                Body      = queueUri.ToString(),
                Label     = ("Known end point: " + queueUri).EnsureLabelLength()
            };

            queue.Send(persistedEndPoint.SetSubQueueToSendTo(SubQueue.Endpoints));

            SendToQueue(secondaryLoadBalancer, new NewEndpointPersisted
            {
                PersistedEndpoint = queueUri
            });
            Raise(SentNewEndpointPersisted);
        }
Beispiel #8
0
        protected override void SetUp()
        {
            MsmqUtil.Delete(InputQueueName);

            _handlerActivator = new BuiltinHandlerActivator();

            _bus = Configure.With(_handlerActivator)
                .Logging(l => l.Console())
                .Transport(t =>
                {
                    t.UseMsmq(InputQueueName)
                        .OnCreated(queue =>
                        {
                            queue.ResetPermissions();

                            var user = new SecurityIdentifier(WellKnownSidType.WorldSid, null)
                                .Translate(typeof(NTAccount))
                                .ToString();

                            queue.SetPermissions(user, MessageQueueAccessRights.FullControl);
                        });
                })
                .Routing(r => r.TypeBased().Map<string>(InputQueueName))
                .Options(o => o.SetNumberOfWorkers(1))
                .Start();

            Using(_bus);
        }
        public void MangledMessageIsNotReceived()
        {
            using (var messageQueue = new MessageQueue(MsmqUtil.GetPath(_inputQueueName)))
            {
                var transaction = new MessageQueueTransaction();
                transaction.Begin();
                messageQueue.Send(new Message
                {
                    Extension = Encoding.UTF32.GetBytes("this is definitely not valid UTF8-encoded JSON")
                }, transaction);
                transaction.Commit();
            }

            Thread.Sleep(5000);

            CleanUpDisposables();

            using (var messageQueue = new MessageQueue(MsmqUtil.GetPath(_inputQueueName)))
            {
                messageQueue.MessageReadPropertyFilter = new MessagePropertyFilter
                {
                    Extension = true
                };

                var transaction = new MessageQueueTransaction();
                transaction.Begin();

                var message = messageQueue.Receive(transaction);

                Assert.That(message, Is.Not.Null);
                Assert.That(Encoding.UTF32.GetString(message.Extension), Is.EqualTo("this is definitely not valid UTF8-encoded JSON"));

                transaction.Commit();
            }
        }
Beispiel #10
0
        private void HandleStandardMessage(OpenedQueue queue, Message message)
        {
            var worker = readyForWork.Dequeue();

            if (worker == null)             // handle message later
            {
                queue.Send(message);

                continuousDeliveryFailures++;

                if (continuousDeliveryFailures >= 100)
                {
                    System.Threading.Thread.Sleep(1000);
                    continuousDeliveryFailures = 0;
                }
            }
            else
            {
                continuousDeliveryFailures = 0;
                var workerEndpoint = endpointRouter.GetRoutedEndpoint(worker);
                using (var workerQueue = MsmqUtil.GetQueuePath(workerEndpoint).Open(QueueAccessMode.Send))
                {
                    logger.DebugFormat("Dispatching message '{0}' to {1}", message.Id, workerEndpoint.Uri);
                    workerQueue.Send(message);
                }
            }
        }
Beispiel #11
0
        void MoveMessage(Message message)
        {
            var sourceQueuePath      = message.QueuePath;
            var destinationQueuePath = MsmqUtil.GetFullPath(message.Headers[Headers.SourceQueue]);

            using (var transaction = new MessageQueueTransaction())
            {
                transaction.Begin();
                try
                {
                    var sourceQueue = new MessageQueue(sourceQueuePath)
                    {
                        MessageReadPropertyFilter = DefaultFilter()
                    };
                    var destinationQueue = new MessageQueue(destinationQueuePath);

                    var msmqMessage = sourceQueue.ReceiveById(message.Id, transaction);
                    destinationQueue.Send(msmqMessage, transaction);

                    transaction.Commit();
                }
                catch
                {
                    transaction.Abort();
                    throw;
                }
            }

            Messenger.Default.Send(new MessageMoved(message, sourceQueuePath, destinationQueuePath));
        }
Beispiel #12
0
 static void DeleteQueueIfExists()
 {
     if (MessageQueue.Exists(MsmqUtil.GetPath(QueueName)))
     {
         MsmqUtil.Delete(QueueName);
     }
 }
        protected override void DoTearDown()
        {
            disposables.ForEach(d => d.Dispose());

            MsmqUtil.Delete(AzureReceiverInputQueueName);
            MsmqUtil.Delete(MsmqSenderInputQueueName);
        }
        public void MangledMessageIsReceived()
        {
            using (var messageQueue = new MessageQueue(MsmqUtil.GetPath(_inputQueueName)))
            {
                var transaction = new MessageQueueTransaction();
                transaction.Begin();
                messageQueue.Send(new Message
                {
                    Extension = Encoding.UTF32.GetBytes("this is definitely not valid UTF8-encoded JSON")
                }, transaction);
                transaction.Commit();
            }

            Thread.Sleep(5000);

            CleanUpDisposables();

            using (var messageQueue = new MessageQueue(MsmqUtil.GetPath(_inputQueueName)))
            {
                messageQueue.MessageReadPropertyFilter = new MessagePropertyFilter
                {
                    Extension = true
                };

                Assert.Catch <MessageQueueException>(() => messageQueue.Receive(TimeSpan.FromSeconds(2)));
            }
        }
Beispiel #15
0
        public void CanReceiveOldFormat()
        {
            var gotIt = new ManualResetEvent(false);

            _activator.Handle <OldSchoolMessage>(async message =>
            {
                if (message.KeyChar == "g")
                {
                    gotIt.Set();
                }
            });

            var correlationId = Guid.NewGuid().ToString();
            var messageId     = Guid.NewGuid().ToString();

            var headers = new Dictionary <string, string>
            {
                { "rebus-return-address", _newEndpoint },
                { "rebus-correlation-id", correlationId },
                { "rebus-msg-id", messageId },
                { "rebus-content-type", "text/json" },
                { "rebus-encoding", "utf-7" }
            };

            var jsonBody = ValidLegacyRebusMessage;

            using (var queue = new MessageQueue(MsmqUtil.GetFullPath(_newEndpoint)))
            {
                queue.SendLegacyRebusMessage(jsonBody, headers);
            }

            gotIt.WaitOrDie(TimeSpan.FromSeconds(5));
        }
Beispiel #16
0
 private void RemoveAllReadyToWorkMessages()
 {
     using (var tx = new TransactionScope())
         using (var readyForWorkQueue = MsmqUtil.GetQueuePath(Endpoint).Open(QueueAccessMode.SendAndReceive))
             using (var enumerator = readyForWorkQueue.GetMessageEnumerator2())
             {
                 try
                 {
                     while (enumerator.MoveNext())
                     {
                         while (
                             enumerator.Current != null &&
                             enumerator.Current.Label == typeof(ReadyToWork).FullName)
                         {
                             var current = enumerator.RemoveCurrent(readyForWorkQueue.GetTransactionType());
                             HandleLoadBalancerMessage(readyForWorkQueue, current);
                         }
                     }
                 }
                 catch (MessageQueueException e)
                 {
                     if (e.MessageQueueErrorCode != MessageQueueErrorCode.IOTimeout)
                     {
                         throw;
                     }
                 }
                 readyForWork.Clear();
                 tx.Complete();
             }
 }
Beispiel #17
0
        public void CorrectlyHandlesMultipleLogicalMessages()
        {
            var gotWhat = new Dictionary <string, ManualResetEvent>
            {
                { "a", new ManualResetEvent(false) },
                { "b", new ManualResetEvent(false) },
                { "c", new ManualResetEvent(false) },
            };

            _activator.Handle <OldSchoolMessage>(async message =>
            {
                gotWhat[message.KeyChar].Set();
            });

            var correlationId = Guid.NewGuid().ToString();
            var messageId     = Guid.NewGuid().ToString();

            var headers = new Dictionary <string, string>
            {
                { "rebus-return-address", _newEndpoint },
                { "rebus-correlation-id", correlationId },
                { "rebus-msg-id", messageId },
                { "rebus-content-type", "text/json" },
                { "rebus-encoding", "utf-7" }
            };

            var jsonBody = ValidLegacyRebusMessageWithMultipleLogicalMessages;

            using (var queue = new MessageQueue(MsmqUtil.GetFullPath(_newEndpoint)))
            {
                queue.SendLegacyRebusMessage(jsonBody, headers);
            }

            gotWhat.ForEach(kvp => kvp.Value.WaitOrDie(TimeSpan.FromSeconds(5), string.Format("Did not get message with KeyChar = '{0}'", kvp.Key)));
        }
Beispiel #18
0
        protected override void DoTearDown()
        {
            CleanUpTrackedDisposables();

            MsmqUtil.Delete(AzureReceiverInputQueueName);
            MsmqUtil.Delete(MsmqSenderInputQueueName);
        }
Beispiel #19
0
        public MsmqFlatQueueTestBase()
        {
            defaultTestBase = new MsmqTestBase();

            testQueueEndPoint = new Endpoint
            {
                Uri = new Uri("msmq://localhost/test_queue")
            };
            testQueuePath = MsmqUtil.GetQueuePath(testQueueEndPoint).QueuePath;

            transactionalTestQueueEndpoint = new Endpoint
            {
                Uri = new Uri("msmq://localhost/transactional_test_queue")
            };
            transactionalTestQueuePath = MsmqUtil.GetQueuePath(transactionalTestQueueEndpoint).QueuePath;

            subscriptionsEndpoint = new Endpoint
            {
                Uri = new Uri(testQueueEndPoint.Uri + "#" + subscriptions)
            };
            subscriptionQueuePath = MsmqUtil.GetQueuePath(subscriptionsEndpoint).QueuePath;


            SetupQueues();

            queue = MsmqUtil.GetQueuePath(testQueueEndPoint).Open();
            transactionalQueue = MsmqUtil.GetQueuePath(transactionalTestQueueEndpoint).Open();
            subscriptions      = MsmqUtil.GetQueuePath(subscriptionsEndpoint).Open(QueueAccessMode.SendAndReceive,
                                                                                   new XmlMessageFormatter(new[]
            {
                typeof(string)
            }));
        }
Beispiel #20
0
        public void LoadBalancer_is_singleton()
        {
            var queuePath = MsmqUtil.GetQueuePath(new Endpoint
            {
                Uri = new Uri("msmq://localhost/test.balancer")
            });
            var queueAcceptingPath = MsmqUtil.GetQueuePath(new Endpoint
            {
                Uri = new Uri("msmq://localhost/test.balancer.acceptingwork")
            });

            if (MessageQueue.Exists(queuePath.QueuePath) == false)
            {
                MessageQueue.Create(queuePath.QueuePath);
            }
            if (MessageQueue.Exists(queueAcceptingPath.QueuePath) == false)
            {
                MessageQueue.Create(queueAcceptingPath.QueuePath);
            }

            new LoadBalancerConfiguration()
            .UseAutofac(container)
            .UseStandaloneConfigurationFile("LoadBalancer.config")
            .Configure();

            var startable    = container.Resolve <IStartable>();
            var loadBalancer = container.Resolve <MsmqLoadBalancer>();

            Assert.Same(startable, loadBalancer);
        }
Beispiel #21
0
 protected override IDuplexTransport CreateTransport(string inputQueueName)
 {
     RegisterForDisposal(new DisposableAction(() => MsmqUtil.Delete(inputQueueName)));
     RegisterForDisposal(new DisposableAction(() => MsmqUtil.Delete(ErrorQueueName)));
     MsmqUtil.EnsureMessageQueueExists(MsmqUtil.GetPath(ErrorQueueName));
     return(new MsmqMessageQueue(inputQueueName).PurgeInputQueue());
 }
Beispiel #22
0
 protected override void DoTearDown()
 {
     CleanUpTrackedDisposables();
     MsmqUtil.Delete(InputQueueName);
     MsmqUtil.Delete(ErrorQueueName);
     base.DoTearDown();
 }
        IBus StartBus(int numberOfWorkers, List <string> log = null, int?numberOfRetries = null)
        {
            MsmqUtil.PurgeQueue(InputQueue);
            MsmqUtil.PurgeQueue(ErrorQueue);

            return(Configure.With(adapter)
                   .Logging(l =>
            {
                if (log == null)
                {
                    l.ColoredConsole(minLevel: LogLevel.Warn);
                }
                else
                {
                    l.Use(new ListLoggerFactory(log));
                }
            })
                   .Behavior(b =>
            {
                if (numberOfRetries != null)
                {
                    b.SetMaxRetriesFor <Exception>(numberOfRetries.Value);
                }
                else
                {
                    b.SetMaxRetriesFor <Exception>(0);
                }
            })
                   .Transport(t => t.UseMsmq(InputQueue, ErrorQueue))
                   .CreateBus()
                   .Start(numberOfWorkers));
        }
Beispiel #24
0
        static void MoveMessage(Message message, string destinationQueueName, bool leaveCopyInSourceQueue)
        {
            var sourceQueuePath      = message.QueuePath;
            var destinationQueuePath = MsmqUtil.GetFullPath(destinationQueueName);

            using (var transaction = new MessageQueueTransaction())
            {
                transaction.Begin();
                try
                {
                    var sourceQueue = new MessageQueue(sourceQueuePath)
                    {
                        MessageReadPropertyFilter = DefaultFilter()
                    };
                    var destinationQueue = new MessageQueue(destinationQueuePath);

                    var msmqMessage = sourceQueue.ReceiveById(message.Id, transaction);
                    destinationQueue.Send(msmqMessage, transaction);

                    if (leaveCopyInSourceQueue)
                    {
                        sourceQueue.Send(msmqMessage, transaction);
                    }

                    transaction.Commit();
                }
                catch
                {
                    transaction.Abort();
                    throw;
                }
            }

            Messenger.Default.Send(new MessageMoved(message, sourceQueuePath, destinationQueuePath, leaveCopyInSourceQueue));
        }
Beispiel #25
0
        protected override void DoTearDown()
        {
            Console.WriteLine("Tearing down the service");
            service.Stop();

            MsmqUtil.Delete(DestinationQueueName);
        }
Beispiel #26
0
        static List <int> SendMessages(int messageCount)
        {
            var transport = new MsmqTransport(QueueName, new ConsoleLoggerFactory(true));

            MsmqUtil.EnsureQueueExists(MsmqUtil.GetPath(QueueName));

            var sendIds = new List <int>();

            Enumerable.Range(0, messageCount)
            .Select(id => new SomeMessage {
                Id = id
            })
            .ToList()
            .ForEach(msg =>
            {
                using (var scope = new RebusTransactionScope())
                {
                    transport.Send(QueueName, TransportMessageHelpers.FromString(JsonConvert.SerializeObject(msg)), scope.TransactionContext).Wait();

                    scope.Complete();

                    sendIds.Add(msg.Id);
                }
            });

            return(sendIds);
        }
Beispiel #27
0
        public MsmqMessageQueue(string inputQueueName)
        {
            if (inputQueueName == null)
            {
                return;
            }

            try
            {
                machineAddress = GetMachineAddress();

                inputQueuePath = MsmqUtil.GetPath(inputQueueName);
                MsmqUtil.EnsureMessageQueueExists(inputQueuePath);
                MsmqUtil.EnsureMessageQueueIsTransactional(inputQueuePath);
                EnsureMessageQueueIsLocal(inputQueueName);

                inputQueue = GetMessageQueue(inputQueuePath);

                this.inputQueueName = inputQueueName;
            }
            catch (MessageQueueException e)
            {
                throw new ArgumentException(
                          string.Format(
                              @"An error occurred while initializing MsmqMessageQueue - attempted to use '{0}' as input queue",
                              inputQueueName), e);
            }
        }
Beispiel #28
0
        protected override void DoSetUp()
        {
            MsmqUtil.Delete(DestinationQueueName);

            Console.WriteLine("Creating new service");
            service = new InboundService(ListenUri, DestinationQueueName);
            service.Start();
        }
Beispiel #29
0
        protected override void DoSetUp()
        {
            MsmqUtil.Delete(SenderInputQueueName);
            MsmqUtil.Delete(ReceiverInputQueueName);
            MsmqUtil.Delete(ErrorQueueName);

            MsmqUtil.EnsureMessageQueueExists(MsmqUtil.GetPath(ErrorQueueName));
        }
        public override void TestInitialize()
        {
            MsmqUtil.ValidateMsmqIsRunning();
            MsmqUtil.DeletePrivateTestQ();
            MsmqUtil.CreatePrivateTestQ();

            base.TestInitialize();
        }