Beispiel #1
0
        public void CanSendAndReceiveMessageWithHeaders()
        {
            // arrange
            var encoding = Encoding.UTF7;
            var transportMessageToSend = new TransportMessageToSend
            {
                Body    = encoding.GetBytes("this is some data"),
                Headers = new Dictionary <string, object>
                {
                    { "key1", "value1" },
                    { "key2", "value2" },
                }
            };

            // act
            sender.Send(receiver.InputQueue, transportMessageToSend, new NoTransaction());
            Thread.Sleep(MaximumExpectedQueueLatency);
            var receivedTransportMessage = receiver.ReceiveMessage(new NoTransaction());

            // assert
            encoding.GetString(receivedTransportMessage.Body).ShouldBe("this is some data");
            var headers = receivedTransportMessage.Headers;

            headers.ShouldNotBe(null);
            headers.Count.ShouldBe(2);

            headers.ShouldContainKeyAndValue("key1", "value1");
            headers.ShouldContainKeyAndValue("key2", "value2");

            5.Times(() => receiver.ReceiveMessage(new NoTransaction()).ShouldBe(null));
        }
Beispiel #2
0
 /// <summary>
 /// Sends a new message to an existing queue
 /// </summary>
 /// <param name="messageToSend">The message to send.</param>
 /// <param name="data">The additional data.</param>
 /// <returns></returns>
 public IQueueOutputMessage Send(IMessage messageToSend, IAdditionalMessageData data)
 {
     using (var scope = _tracer.StartActivity("SendMessage"))
     {
         scope?.AddCommonTags(data, _connectionInformation);
         scope?.Add(data);
         scope?.SetTag("IsBatch", false);
         if (scope != null)
         {
             messageToSend.Inject(_tracer, scope.Context, _headers.StandardHeaders);
         }
         try
         {
             var outputMessage = _handler.Send(messageToSend, data);
             if (outputMessage.HasError)
             {
                 scope?.SetStatus(Status.Error);
                 if (outputMessage.SendingException != null)
                 {
                     scope?.RecordException(outputMessage.SendingException);
                 }
             }
             scope?.AddMessageIdTag(outputMessage.SentMessage.MessageId);
             return(outputMessage);
         }
         catch (Exception e)
         {
             scope?.SetStatus(Status.Error);
             scope?.RecordException(e);
             throw;
         }
     }
 }
        public List <ScenarioResult> Run(int maxSample, CancellationToken cancellationToken)
        {
            var scenarios = _scenarios;

            if (_selectedScenarios != null)
            {
                scenarios = _scenarios.Where(s => _selectedScenarios.SelectedScenarios.Any(sel => sel.Name == s.Name));
            }

            List <ScenarioResult> results = new List <ScenarioResult>();

            for (int i = 1; i <= maxSample; i = _sampleSizeStep.Increment(i))
            {
                _sender.Send(new SampleSizeChanged {
                    SampleSize = i
                });
                foreach (var scenario in scenarios)
                {
                    _sender.Send(new ScenarioChanged {
                        Scenario = scenario.Name
                    });

                    results.AddRange(scenario.Run(i, cancellationToken));
                }
            }
            return(results);
        }
        public ActionResult Create(Person person)
        {
            CreatePerson command = new CreatePerson(Guid.NewGuid(), person.Name, person.Street, person.StreetNumber);

            bus.Send(command);
            return(this.RedirectToAction("Index"));
        }
 /// <summary>
 /// Sends a new message to an existing queue
 /// </summary>
 /// <param name="messageToSend">The message to send.</param>
 /// <param name="data">The additional data.</param>
 /// <returns></returns>
 public IQueueOutputMessage Send(IMessage messageToSend, IAdditionalMessageData data)
 {
     using (IScope scope = _tracer.BuildSpan("SendMessage").StartActive(finishSpanOnDispose: true))
     {
         scope.Span.AddCommonTags(data, _connectionInformation);
         scope.Span.Add(data);
         scope.Span.SetTag("IsBatch", false);
         messageToSend.Inject(_tracer, scope.Span.Context, _headers.StandardHeaders);
         try
         {
             var outputMessage = _handler.Send(messageToSend, data);
             if (outputMessage.HasError)
             {
                 Tags.Error.Set(scope.Span, true);
                 if (outputMessage.SendingException != null)
                 {
                     scope.Span.Log(outputMessage.SendingException.ToString());
                 }
             }
             scope.Span.AddMessageIdTag(outputMessage.SentMessage.MessageId);
             return(outputMessage);
         }
         catch (Exception e)
         {
             Tags.Error.Set(scope.Span, true);
             scope.Span.Log(e.ToString());
             throw;
         }
     }
 }
        public void RunTests()
        {
            _cancelationToken = new CancellationTokenSource();
            Task.Factory.StartNew(() =>
            {
                _allRunResults = new List <ScenarioInRunResult>();
                _sender.Send(new TestStarted());

                for (int i = 0; i < _config.NumberOfRuns; i++)
                {
                    _sender.Send(new IterationChanged());
                    _allRunResults.AddRange(_runner.Run(_config.MaximumSampleSize, _cancelationToken.Token)
                                            .Select(r =>
                                                    new ScenarioInRunResult
                    {
                        ApplicationTime   = r.ApplicationTime,
                        CommitTime        = r.CommitTime,
                        ConfigurationName = r.ConfigurationName,
                        MemoryUsage       = r.MemoryUsage,
                        SampleSize        = r.SampleSize,
                        ScenarioName      = r.ScenarioName,
                        SetupTime         = r.SetupTime,
                        Status            = r.Status,
                        Technology        = r.Technology,
                        RunNumber         = i + 1
                    }));
                }

                foreach (var formatter in _formatters)
                {
                    formatter.FormatResults(_allRunResults);
                }
                _sender.Send(new TestStopped());
            }, _cancelationToken.Token);
        }
Beispiel #7
0
 public void the_main_application_is_sent_to_the_messaging_service()
 {
     A.CallTo(() => _fakeMessageSender.Send(A <SubmitLrap1Command> .That.Matches(
                                                c => c.Username == _username &&
                                                c.Password == _password &&
                                                c.Payload == _package.Payload)))
     .MustHaveHappened();
 }
Beispiel #8
0
        public void Process(SubmitLrap1Command message)
        {
            var response = _commsService.Send(message);

            if (response == ResponseType.None)
            {
                _messageSender.Send(message);
            }
        }
Beispiel #9
0
        public void CanReceiveAndDoOneSingleSendAtomically(bool commitTransactionAndExpectMessagesToBeThere)
        {
            sender.Send(receiver.InputQueueAddress, MessageWith("hello"), new NoTransaction());

            var destination1 = factory.CreateReceiver("destination1");

            Thread.Sleep(300.Milliseconds());

            // pretend that this is a message handler tx scope...
            using (var tx = new TransactionScope())
            {
                var ctx = new AmbientTransactionContext();

                // arrange
                var receivedTransportMessage = receiver.ReceiveMessage(ctx);
                Assert.That(receivedTransportMessage, Is.Not.Null);

                // act
                sender.Send(destination1.InputQueueAddress, MessageWith("hello mr. 1"), ctx);

                if (commitTransactionAndExpectMessagesToBeThere)
                {
                    tx.Complete();
                }
            }

            Thread.Sleep(300.Milliseconds());

            // assert
            var msg1 = destination1.ReceiveMessage(new NoTransaction());

            if (commitTransactionAndExpectMessagesToBeThere)
            {
                Assert.That(msg1, Is.Not.Null);
                Assert.That(Encoding.GetString(msg1.Body), Is.EqualTo("hello mr. 1"));

                using (new TransactionScope())
                {
                    var ctx = new AmbientTransactionContext();
                    var receivedTransportMessage = receiver.ReceiveMessage(ctx);
                    Assert.That(receivedTransportMessage, Is.Null);
                }
            }
            else
            {
                Assert.That(msg1, Is.Null);

                using (new TransactionScope())
                {
                    var ctx = new AmbientTransactionContext();
                    var receivedTransportMessage = receiver.ReceiveMessage(ctx);
                    Assert.That(receivedTransportMessage, Is.Not.Null);
                    Assert.That(Encoding.GetString(receivedTransportMessage.Body), Is.EqualTo("hello"));
                }
            }
        }
                public void Start()
                {
                    var msg = CreateTransportMessage(2);

                    sendMessages.Send(msg, new SendOptions(Address.Parse("error")));

                    msg = CreateTransportMessage(1);

                    sendMessages.Send(msg, new SendOptions(Address.Parse("error")));

                    msg = CreateTransportMessage(3);

                    sendMessages.Send(msg, new SendOptions(Address.Parse("error")));
                }
Beispiel #11
0
        public void CanReceiveAndDoMultipleSendsAtomically(bool commitTransactionAndExpectMessagesToBeThere)
        {
            sender.Send(receiver.InputQueueAddress, MessageWith("hello"));

            var destination1 = factory.CreateReceiver("destination1");
            var destination2 = factory.CreateReceiver("destination2");

            Thread.Sleep(300);

            // pretend that this is a message handler tx scope...
            using (var tx = new TransactionScope())
            {
                // arrange
                var receivedTransportMessage = receiver.ReceiveMessage();

                // act
                sender.Send(destination1.InputQueueAddress, receivedTransportMessage.ToForwardableMessage());
                sender.Send(destination2.InputQueueAddress, receivedTransportMessage.ToForwardableMessage());

                if (commitTransactionAndExpectMessagesToBeThere)
                {
                    tx.Complete();
                }
            }

            Thread.Sleep(300);

            // assert
            var msg1 = destination1.ReceiveMessage();
            var msg2 = destination2.ReceiveMessage();

            if (commitTransactionAndExpectMessagesToBeThere)
            {
                msg1.ShouldNotBe(null);
                Encoding.GetString(msg1.Body).ShouldBe("hello");

                msg2.ShouldNotBe(null);
                Encoding.GetString(msg2.Body).ShouldBe("hello");

                receiver.ReceiveMessage().ShouldBe(null);
            }
            else
            {
                msg1.ShouldBe(null);
                msg2.ShouldBe(null);
                receiver.ReceiveMessage().ShouldNotBe(null);
            }
        }
Beispiel #12
0
 /// <summary>
 /// Sends a new message to an existing queue
 /// </summary>
 /// <param name="messageToSend">The message to send.</param>
 /// <param name="data">The additional data.</param>
 /// <returns></returns>
 public IQueueOutputMessage Send(IMessage messageToSend, IAdditionalMessageData data)
 {
     using (_sendTimer.NewContext())
     {
         var result = _handler.Send(messageToSend, data);
         if (!result.HasError)
         {
             _sendMeter.Mark("SendMessage", 1);
         }
         else
         {
             _sendErrorMeter.Mark("SendMessage", 1);
         }
         return(result);
     }
 }
                public void Start()
                {
                    context.EndpointNameOfReceivingEndpoint = settings.EndpointName();
                    context.MessageId       = Guid.NewGuid().ToString();
                    context.UniqueMessageId = DeterministicGuid.MakeId(context.MessageId, context.EndpointNameOfReceivingEndpoint).ToString();

                    var transportMessage = new TransportMessage();

                    transportMessage.Headers[Headers.ProcessingEndpoint]                     = context.EndpointNameOfReceivingEndpoint;
                    transportMessage.Headers[Headers.MessageId]                              = context.MessageId;
                    transportMessage.Headers[Headers.ConversationId]                         = "a59395ee-ec80-41a2-a728-a3df012fc707";
                    transportMessage.Headers["$.diagnostics.hostid"]                         = "bdd4b0510bff5a6d07e91baa7e16a804";
                    transportMessage.Headers["$.diagnostics.hostdisplayname"]                = "SELENE";
                    transportMessage.Headers["NServiceBus.ExceptionInfo.ExceptionType"]      = "2014-11-11 02:26:57:767462 Z";
                    transportMessage.Headers["NServiceBus.ExceptionInfo.Message"]            = "An error occurred while attempting to extract logical messages from transport message NServiceBus.TransportMessage";
                    transportMessage.Headers["NServiceBus.ExceptionInfo.InnerExceptionType"] = "System.Exception";
                    transportMessage.Headers["NServiceBus.ExceptionInfo.HelpLink"]           = String.Empty;
                    transportMessage.Headers["NServiceBus.ExceptionInfo.Source"]             = "NServiceBus.Core";
                    transportMessage.Headers["NServiceBus.ExceptionInfo.StackTrace"]         = String.Empty;
                    transportMessage.Headers["NServiceBus.FailedQ"]                          = settings.LocalAddress().ToString();
                    transportMessage.Headers["NServiceBus.TimeOfFailure"]                    = "2014-11-11 02:26:58:000462 Z";
                    transportMessage.Headers["NServiceBus.TimeSent"]                         = "2014-11-11 02:26:01:174786 Z";
                    transportMessage.Headers[Headers.ControlMessageHeader]                   = Boolean.TrueString;
                    transportMessage.Headers[Headers.ReplyToAddress]                         = settings.LocalAddress().ToString();

                    sendMessages.Send(transportMessage, new SendOptions(Address.Parse("error")));
                }
Beispiel #14
0
        /// <summary>
        /// Sends a copy of the specified <see cref="TransportMessageToSend"/> using the underlying implementation of <see cref="ISendMessages"/>
        /// with an encrypted message body and additional headers
        /// </summary>
        public void Send(string destinationQueueName, TransportMessageToSend message, ITransactionContext context)
        {
            var clone = new TransportMessageToSend
            {
                Headers = message.Headers.Clone(),
                Label   = message.Label,
                Body    = message.Body,
            };

            if (compressionHelper != null)
            {
                var compresssionResult = compressionHelper.Compress(clone.Body);
                if (compresssionResult.Item1)
                {
                    clone.Headers[Headers.Compression] = Headers.CompressionTypes.GZip;
                }
                clone.Body = compresssionResult.Item2;
            }

            if (encryptionHelper != null)
            {
                var iv = encryptionHelper.GenerateNewIv();
                clone.Body = encryptionHelper.Encrypt(clone.Body, iv);
                clone.Headers[Headers.Encrypted]      = null;
                clone.Headers[Headers.EncryptionSalt] = iv;
            }

            innerSendMessages.Send(destinationQueueName, clone, context);
        }
 protected void SendMessages(ISendMessages sender, int count)
 {
     for (var i = 0; i < count; i++)
     {
         sender.Send(GenerateTransportMessage(i, "MessageType"), ReceiverAddress);
     }
 }
        private void InnerHandle(TransportMessage message)
        {
            var entity = auditImporter.ConvertToSaveMessage(message);

            using (var session = store.OpenSession())
            {
                session.Store(entity);
                session.SaveChanges();
            }

            if (settings.ForwardAuditMessages)
            {
                TransportMessageCleaner.CleanForForwarding(message);
                forwarder.Send(message, new SendOptions(settings.AuditLogQueue));
            }
        }
        void SendFailureMessage(TransportMessage message, Exception e, string reason)
        {
            if (errorQueue == null)
            {
                Logger.Error("Message processing always fails for message with ID " + message.Id + ".", e);
                return;
            }

            message.SetExceptionHeaders(e, localAddress ?? config.LocalAddress, reason);

            try
            {
                messageSender.Send(message, new SendOptions(errorQueue));
            }
            catch (Exception exception)
            {
                var    queueNotFoundException = exception as QueueNotFoundException;
                string errorMessage;

                if (queueNotFoundException != null)
                {
                    errorMessage = string.Format("Could not forward failed message to error queue '{0}' as it could not be found.", queueNotFoundException.Queue);
                    Logger.Fatal(errorMessage);
                }
                else
                {
                    errorMessage = "Could not forward failed message to error queue.";
                    Logger.Fatal(errorMessage, exception);
                }

                throw new InvalidOperationException(errorMessage, exception);
            }
        }
Beispiel #18
0
        public bool Handle(TransportMessage message)
        {
            using (var session = Store.OpenSession())
            {
                session.Advanced.UseOptimisticConcurrency = true;

                var failedMessage = new Message(message)
                {
                    FailureDetails = new FailureDetails(message),
                    Status         = MessageStatus.Failed,
                    ReplyToAddress = message.ReplyToAddress.ToString()
                };

                try
                {
                    session.Store(failedMessage);

                    session.SaveChanges();
                }
                catch (ConcurrencyException) //there is already a message in the store with the same id
                {
                    session.Advanced.Clear();
                    UpdateExistingMessage(session, failedMessage.Id, message);
                }
            }

            Forwarder.Send(message, Settings.ErrorLogQueue);

            return(true);
        }
            public void WillQueueMessageForProcessing()
            {
                var message = new Message <String>(Guid.NewGuid(), HeaderCollection.Empty, "Test Message");

                messageSender.Send(message);

                Assert.Equal(message.Id, ReceiveMessage().Id);
            }
Beispiel #20
0
        /// <summary>
        /// Publishes the specified <paramref name="payload"/> on the underlying message bus.
        /// </summary>
        /// <param name="headers">The set of message headers associated with the command.</param>
        /// <param name="payload">The command payload to be published.</param>
        public void Publish(IEnumerable <Header> headers, CommandEnvelope payload)
        {
            Verify.NotNull(payload, nameof(payload));

            Log.Trace("Publishing {0} to {1}", payload.Command, payload.AggregateId);

            messageSender.Send(messageFactory.Create(headers, payload));
        }
        public bool Publish(TransportMessage message, IEnumerable <Type> eventTypes)
        {
            var eventTypeTopics = String.Join("/", eventTypes);

            messageSender.Send(message, Address.Parse(String.Format("topic://{0}/EVENTS/{1}", WebSphereMqAddress.GetQueueName(Address.Local), eventTypeTopics)));

            return(true);
        }
Beispiel #22
0
                public void Start()
                {
                    var transportMessage = new TransportMessage(context.MessageId, new Dictionary <string, string> {
                        { Headers.ProcessingEndpoint, settings.EndpointName() }
                    });

                    sendMessages.Send(transportMessage, new SendOptions("audit"));
                }
            public void Send(TransportMessage message, SendOptions sendOptions)
            {
                if (sendOptions.Destination.Queue == context.DecommissionedEndpointName)
                {
                    throw new QueueNotFoundException();
                }

                original.Send(message, sendOptions);
            }
Beispiel #24
0
        /// <summary>
        /// Sends the specified message.
        /// </summary>
        /// <param name="message">The message.</param>
        /// <param name="data">The data.</param>
        /// <returns></returns>
        private IQueueOutputMessage InternalSend(T message, IAdditionalMessageData data)
        {
            Guard.NotNull(() => message, message);
            Guard.NotNull(() => data, data);

            if (!Configuration.IsReadOnly)
            {
                Configuration.SetReadOnly();
            }

            var additionalHeaders = _generateMessageHeaders.HeaderSetup(data);
            var messageToSend     = _messageFactory.Create(message, additionalHeaders);

            _addStandardMessageHeaders.AddHeaders(messageToSend, data);

            //send the message to the transport
            return(_sendMessages.Send(messageToSend, data));
        }
Beispiel #25
0
        private void InnerHandle(TransportMessage message)
        {
            var metadata = new Dictionary <string, object>
            {
                ["MessageId"]           = message.Id,
                ["MessageIntent"]       = message.MessageIntent,
                ["HeadersForSearching"] = string.Join(" ", message.Headers.Values)
            };

            foreach (var enricher in enrichers)
            {
                enricher.Enrich(message.Headers, metadata);
            }

            bodyStorageEnricher.StoreErrorMessageBody(
                message.Body,
                message.Headers,
                metadata);

            var failureDetails = failedMessageFactory.ParseFailureDetails(message.Headers);

            var replyToAddress = message.ReplyToAddress == null ? null : message.ReplyToAddress.ToString();

            var processingAttempt = failedMessageFactory.CreateProcessingAttempt(
                message.Headers,
                metadata,
                failureDetails,
                message.MessageIntent,
                message.Recoverable,
                message.CorrelationId,
                replyToAddress);

            var groups = failedMessageFactory.GetGroups((string)metadata["MessageType"], failureDetails, processingAttempt);

            Store(message.Headers.UniqueId(), processingAttempt, groups);

            AnnounceFailedMessage(message.Headers, failureDetails);

            if (settings.ForwardErrorMessages)
            {
                TransportMessageCleaner.CleanForForwarding(message);
                forwarder.Send(message, new SendOptions(settings.ErrorLogQueue));
            }
        }
        /// <summary>
        /// Sends a new message to an existing queue
        /// </summary>
        /// <param name="messageToSend">The message to send.</param>
        /// <param name="data">The additional data.</param>
        /// <returns></returns>
        public IQueueOutputMessage Send(IMessage messageToSend, IAdditionalMessageData data)
        {
            IQueueOutputMessage result = null;

            if (_policy == null)
            {
                _policies.Registry.TryGet(_policies.Definition.SendMessage, out _policy);
            }

            if (_policy != null)
            {
                _policy.Execute(() => result = _handler.Send(messageToSend, data));
            }
            else //no policy found
            {
                result = _handler.Send(messageToSend, data);
            }
            return(result);
        }
Beispiel #27
0
        public void the_message_is_resent_if_no_response_is_returned()
        {
            //Arrange
            A.CallTo(() => _fakeCommsService.Send(_command)).Returns(ResponseType.None);

            //Act
            _sut.Process(_command);

            //Assert
            A.CallTo(() => _fakeMessageSender.Send(A <SubmitLrap1AttachmentCommand> .Ignored)).MustHaveHappened(Repeated.Exactly.Once);
        }
Beispiel #28
0
        public SubmitLrap1Result Submit(string username, string password, Lrap1Package lrap1Package)
        {
            var applicationId = Guid.NewGuid().ToString();

            var saveResult = _commandInvoker.Execute <CreateLrap1SubmissionCommand, CreateLrap1SubmissionQueryResult>(new CreateLrap1SubmissionCommand()
            {
                ApplicationId = applicationId,
                Username      = username,
                Payload       = lrap1Package.Payload
            });

            var saveAttachmentResult = _commandInvoker.Execute <CreateLrap1AttachmentCommand, CreateLrap1AttachmentQueryResult>(new CreateLrap1AttachmentCommand()
            {
                AttachmentId  = Guid.NewGuid().ToString(),
                ApplicationId = saveResult.Command.ApplicationId,
                Username      = username,
                Payload       = lrap1Package.Attachments[0].Payload
            });

            var sendResult = _messageSender.Send(new SubmitLrap1Command()
            {
                ApplicationId = saveResult.Command.ApplicationId,
                Username      = username,
                Password      = password,
                Payload       = lrap1Package.Payload
            });

            foreach (var attachment in lrap1Package.Attachments)
            {
                _messageSender.Send(new SubmitLrap1AttachmentCommand()
                {
                    AttachmentId  = saveAttachmentResult.Command.AttachmentId,
                    ApplicationId = saveResult.Command.ApplicationId,
                    Username      = username,
                    Password      = password,
                    Payload       = attachment.Payload
                });
            }

            return(sendResult);
        }
                public void Send(TransportMessage message, SendOptions sendOptions)
                {
                    string relatedTimeoutId;

                    if (message.Headers.TryGetValue("NServiceBus.RelatedToTimeoutId", out relatedTimeoutId) && !context.SendingMessageFailedOnce)
                    {
                        context.SendingMessageFailedOnce = true;
                        throw new Exception("simulated exception");
                    }

                    wrappedSender.Send(message, sendOptions);
                }
Beispiel #30
0
        /// <summary>
        /// Sends the specified message.
        /// </summary>
        /// <param name="message">The message.</param>
        /// <param name="responseId">The response identifier.</param>
        /// <param name="inputData"></param>
        /// <returns></returns>
        public IQueueOutputMessage Send(T message, IResponseId responseId, IAdditionalMessageData inputData = null)
        {
            ThrowIfDisposed();

            Guard.NotNull(() => message, message);
            Guard.NotNull(() => responseId, responseId);

            var data = SetupForSend(message, responseId, inputData);

            //send the message to the transport
            return(_sendMessages.Send(data.Item1, data.Item2));
        }
Beispiel #31
0
        public void Init()
        {
            NServiceBus.Configure.With().Log4Net().DefaultBuilder().UnicastBus();

            string errorQueue = ConfigurationManager.AppSettings["ErrorQueue"];
            string audit = ConfigurationManager.AppSettings["ForwardReceivedMessageTo"];
            string listenUrl = ConfigurationManager.AppSettings["ListenUrl"];
            string n = ConfigurationManager.AppSettings["NumberOfWorkerThreads"];
            string remoteUrl = ConfigurationManager.AppSettings["RemoteUrl"];

            connectionString = ConfigurationManager.AppSettings["ConnectionString"];
            inputQueue = ConfigurationManager.AppSettings["InputQueue"];
            outputQueue = ConfigurationManager.AppSettings["OutputQueue"];

            int numberOfWorkerThreads = 10;
            int.TryParse(n, out numberOfWorkerThreads);

            ThreadPool.SetMaxThreads(numberOfWorkerThreads, numberOfWorkerThreads);

            messageSender = new MsmqMessageSender {UseDeadLetterQueue = true, UseJournalQueue = true};

            transport = new TransactionalTransport
            {
                MessageReceiver = new MsmqMessageReceiver(),
                IsTransactional = true,
                NumberOfWorkerThreads = numberOfWorkerThreads
            };

            notifier = new MessageNotifier();

            NServiceBus.Configure.Instance.Configurer.RegisterSingleton<ISendMessages>(messageSender);
            NServiceBus.Configure.Instance.Configurer.RegisterSingleton<ITransport>(transport);
            NServiceBus.Configure.Instance.Configurer.RegisterSingleton<INotifyAboutMessages>(notifier);

            transport.TransportMessageReceived += (s, e) =>
            {
                new MsmqHandler(notifier, listenUrl).Handle(e.Message, remoteUrl);

                if (!string.IsNullOrEmpty(audit))
                    messageSender.Send(e.Message, audit);
            };

            listener = new HttpListener();
            listener.Prefixes.Add(listenUrl);
        }
        public void Init()
        {
            NServiceBus.Configure.With().DefaultBuilder();

            string errorQueue = ConfigurationManager.AppSettings["ErrorQueue"];
            string audit = ConfigurationManager.AppSettings["ForwardReceivedMessageTo"];
            string listenUrl = ConfigurationManager.AppSettings["ListenUrl"];
            string n = ConfigurationManager.AppSettings["NumberOfWorkerThreads"];
            string req = ConfigurationManager.AppSettings["RequireMD5FromClient"];
            string remoteUrl = ConfigurationManager.AppSettings["RemoteUrl"];

            inputQueue = ConfigurationManager.AppSettings["InputQueue"];
            outputQueue = ConfigurationManager.AppSettings["OutputQueue"];

            int numberOfWorkerThreads = 10;
            int.TryParse(n, out numberOfWorkerThreads);

            bool.TryParse(req, out requireMD5FromClient);

            ThreadPool.SetMaxThreads(numberOfWorkerThreads, numberOfWorkerThreads);

            messageSender = new MsmqMessageSender();

            transport = new TransactionalTransport
            {
                MessageReceiver = new MsmqMessageReceiver(),
                IsTransactional = true,
                NumberOfWorkerThreads = numberOfWorkerThreads
            };

            transport.TransportMessageReceived += (s, e) =>
            {
                new MsmqHandler(listenUrl).Handle(e.Message, remoteUrl);

                if (!string.IsNullOrEmpty(audit))
                    messageSender.Send(e.Message, audit);
            };

            listener = new HttpListener();
            listener.Prefixes.Add(listenUrl);
        }
 protected void SendMessages(ISendMessages sender, int count)
 {
     for (var i = 0; i < count; i++)
     {
         sender.Send(GenerateTransportMessage(i, "MessageType"), ReceiverAddress);
     }
 }
        public When_the_submissions_service_is_asked_to_send_an_LRAP1_package()
        {
            _applicationId = "01234567890";
            _username = "******";
            _password = "******";

            _fakeCommandInvoker = A.Fake<ICommandInvoker>();

            var attachments = new List<Lrap1Attachment>
            {
                new Lrap1Attachment() {Payload = "Attachment 1 payload data"},
                new Lrap1Attachment() {Payload = "Attachment 2 payload data"}
            };

            _package = new Lrap1Package()
            {
                Payload = "Lrap1 Payload Data",
                Attachments = attachments
            };

            A.CallTo(
                () =>
                    _fakeCommandInvoker.Execute<CreateLrap1SubmissionCommand, CreateLrap1SubmissionQueryResult>(
                        A<CreateLrap1SubmissionCommand>.Ignored)).Returns(new CreateLrap1SubmissionQueryResult()
                        {
                            Command = new CreateLrap1SubmissionCommand()
                                {
                                    ApplicationId = _applicationId,
                                    Username = _username,
                                    Payload = _package.Payload
                                }
                        });

            A.CallTo(
                () =>
                    _fakeCommandInvoker.Execute<CreateLrap1AttachmentCommand, CreateLrap1AttachmentQueryResult>(
                        A<CreateLrap1AttachmentCommand>.Ignored)).Returns(new CreateLrap1AttachmentQueryResult()
                        {
                            Command = new CreateLrap1AttachmentCommand()
                            {
                                AttachmentId = "98765",
                                ApplicationId = _applicationId,
                                Username = _username,
                                Payload = _package.Payload
                            }
                        });

            _fakeMessageSender = A.Fake<ISendMessages>();

            A.CallTo(() => _fakeMessageSender.Send(A<SubmitLrap1Command>.That.Matches(
                c => c.Username == _username &&
                     c.Password == _password &&
                     c.Payload == _package.Payload)))
                .Returns(new SubmitLrap1Result()
                    {
                        Command = new SubmitLrap1Command()
                        {
                            ApplicationId = _applicationId,
                            Username = _username,
                            Password = _password,
                            Payload = _package.Payload
                        }
                    });

            var sut = new Lrap1SubmissionService(_fakeMessageSender, _fakeCommandInvoker);
            _response = sut.Submit(_username, _password, _package);
        }
        public void Handle(HttpListenerContext ctx, ISendMessages sender, string queue)
        {
            try
            {
                if (ctx.Request.ContentLength64 > 4 * 1024 * 1024)
                {
                    Logger.Warn("Received an Http request larger than 4MB, returning an error to the client " +
                                ctx.Request.RemoteEndPoint);
                    ctx.Response.StatusCode = 413; // Request Entity Too Large
                    ctx.Response.StatusDescription = "Cannot accept messages larger than 4MB.";

                    ctx.Response.Close(Encoding.ASCII.GetBytes("<html><body>" + ctx.Response.StatusDescription + "</body></html>"), false);
                    return;
                }

                string hash = ctx.Request.Headers[Headers.ContentMd5Key];
                if (hash == null && requireMD5FromClient)
                {
                    Logger.Warn("Received an Http request that didn't contain the " + Headers.ContentMd5Key +
                                " header from " + ctx.Request.RemoteEndPoint +
                                ". Rejecting the request. If you wish to allow these kinds of requests, please set the configuration field 'RequireMD5FromClient' to 'false'.");
                    ctx.Response.StatusCode = 400; //Bad Request
                    ctx.Response.StatusDescription = "Required header '" + Headers.ContentMd5Key +
                                                     "' missing. Cannot accept request.";

                    ctx.Response.Close(Encoding.ASCII.GetBytes("<html><body>" + ctx.Response.StatusDescription + "</body></html>"), false);

                    return;
                }

                var length = (int)ctx.Request.ContentLength64;
                var buffer = new byte[length];

                int numBytesToRead = length;
                int numBytesRead = 0;
                while (numBytesToRead > 0)
                {
                    int n = ctx.Request.InputStream.Read(
                        buffer,
                        numBytesRead,
                        numBytesToRead < maximumBytesToRead ? numBytesToRead : maximumBytesToRead);

                    if (n == 0)
                        break;

                    numBytesRead += n;
                    numBytesToRead -= n;
                }

                string myHash = Hasher.Hash(buffer);
                TransportMessage msg;

                if (myHash == hash)
                {
                    msg = new TransportMessage
                    {
                        Body = buffer,
                        ReturnAddress = inputQueue
                    };

                    //check to see if this is a gateway from another site
                    if (ctx.Request.Headers["NServiceBus.Gateway"] != null)
                        HeaderMapper.Map(ctx.Request.Headers, msg);
                    else
                    {
                        msg.MessageIntent = MessageIntentEnum.Send;
                        msg.Recoverable = true;
                        msg.Headers = new Dictionary<string, string>();
                    }

                    if (ctx.Request.Headers[Headers.FromKey] != null)
                        msg.Headers.Add(NServiceBus.Headers.HttpFrom, ctx.Request.Headers[Headers.FromKey]);

                    if (msg.Headers.ContainsKey(HeaderMapper.RouteTo))
                        sender.Send(msg, msg.Headers[HeaderMapper.RouteTo]);
                    else
                        sender.Send(msg, queue);
                }

                if (hash != null)
                {
                    Logger.Debug("Sending HTTP response.");

                    ctx.Response.AddHeader(Headers.ContentMd5Key, myHash);
                    ctx.Response.StatusCode = 200;
                    ctx.Response.StatusDescription = "OK";

                    ctx.Response.Close(Encoding.ASCII.GetBytes("<html><body>" + ctx.Response.StatusDescription + "</body></html>"), false);
                }
            }
            catch (Exception ex)
            {
                Logger.Error("Unexpected error", ex);
                try
                {
                    ctx.Response.StatusCode = 502;
                    ctx.Response.StatusDescription = "Unexpected server error";
                    ctx.Response.Close(
                        Encoding.ASCII.GetBytes("<html><body>" + ctx.Response.StatusDescription + "</body></html>"),
                        false);
                }
                catch (Exception)
                {
                    Logger.Info("Could not notify client about exception.");
                }
            }

            Logger.Info("Http request processing complete.");
        }