public async Task Should_put_incoming_message_on_error_queue_when_outgoing_is_too_big_WithoutRenewal()
        {
            using var gotCalledFiveTimes = new CountdownEvent(5);

            _activator.Handle <string>(async(innerBus, context, _) =>
            {
                Console.WriteLine($"Got message with ID {context.Headers.GetValue(Headers.MessageId)} - Sending off huge message");

                var hugeMessage = GetHugeMessage();
                await innerBus.SendLocal(hugeMessage);
                gotCalledFiveTimes.Signal();

                Console.WriteLine($"{gotCalledFiveTimes.CurrentCount} tries left");
            });

            _busStarter.Start();

            await _bus.SendLocal("Get going....");

            gotCalledFiveTimes.Wait(TimeSpan.FromSeconds(120));

            //There should now be a message in the error queue.
            _ = await _errorQueueListener.WaitForNextMessage(timeoutSeconds : 5);

            //the error should be logged
            Assert.IsTrue(_listLoggerFactory.Any(l => l.Level == LogLevel.Error));
        }
Пример #2
0
    public async Task ItWorksInSimpleScenario()
    {
        var events     = new ConcurrentQueue <string>();
        var gotMessage = new AutoResetEvent(false);

        _handlerActivator.Handle <BaseMessage>(async msg =>
        {
            events.Enqueue($"Got {msg.GetType().Name} with {msg.Payload}");

            gotMessage.Set();
        });

        StartBus();

        await _bus.SendLocal(new SpecializationA { Payload = "a" });

        await _bus.SendLocal(new SpecializationB { Payload = "b" });

        gotMessage.WaitOrDie(BlockingWaitTimeout, "Did not get the first message");
        gotMessage.WaitOrDie(BlockingWaitTimeout, "Did not get the second message");

        Assert.That(events.ToArray(), Is.EqualTo(new[]
        {
            "Got SpecializationA with a",
            "Got SpecializationB with b",
        }));
    }
Пример #3
0
        public async Task WhatHappensQuestionMark()
        {
            var gotMessage2 = new ManualResetEvent(false);

            var activator = new BuiltinHandlerActivator();

            Using(activator);

            activator.Handle <Message1>(async(bus, m1) =>
            {
                await bus.Send(new Message2()).ConfigureAwait(false);

                throw new Exception("-|The Most Mundane Exception In The World|-");
            });

            activator.Handle <Message2>(async m2 => gotMessage2.Set());

            Configure.With(activator)
            .Transport(t => t.UseInMemoryTransport(new InMemNetwork(), "daw do"))
            .Routing(r => r.TypeBased().Map <Message1>("daw do").Map <Message2>("daw do"))
            .Start();

            await activator.Bus.Send(new Message1());

            Assert.Throws <AssertionException>(() => gotMessage2.WaitOrDie(TimeSpan.FromSeconds(2)));
        }
Пример #4
0
    public void TakeTime(int count)
    {
        var activator = new BuiltinHandlerActivator();

        Using(activator);

        activator.Handle <string>(async str => { });
        activator.Handle <string>(async(bus, str) => { });
        activator.Handle <string>(async(bus, context, str) => { });

        var stopwatch = Stopwatch.StartNew();

        for (var counter = 0; counter < count; counter++)
        {
            using (var scope = new FakeMessageContextScope())
            {
                // ReSharper disable once UnusedVariable
                var handlers = _activator.GetHandlers("hej med dig", scope.TransactionContext).Result;
            }
        }

        var elapsedSeconds = stopwatch.Elapsed.TotalSeconds;

        Console.WriteLine($"{count} resolutions took {elapsedSeconds:0.0} s - that's {count/elapsedSeconds:0.0} /s");
    }
Пример #5
0
        public async Task ItWorks()
        {
            const int numberOfRetries = 5;

            InitializeBus(numberOfRetries);

            var attemptedDeliveries = 0;

            _handlerActivator.Handle <string>(async _ =>
            {
                Interlocked.Increment(ref attemptedDeliveries);
                throw new ApplicationException("omgwtf!");
            });

            await _bus.Send("hej");

            using (var errorQueue = new MsmqTransport(ErrorQueueName, new ConsoleLoggerFactory(true)))
            {
                var failedMessage = await errorQueue.AwaitReceive();

                Assert.That(attemptedDeliveries, Is.EqualTo(numberOfRetries));
                Assert.That(failedMessage.Headers.GetValue(Headers.ErrorDetails), Contains.Substring("5 unhandled exceptions"));
                Assert.That(failedMessage.Headers.GetValue(Headers.SourceQueue), Is.EqualTo(InputQueueName));
            }
        }
Пример #6
0
        public async Task IncomingMessageHasNoHeaders()
        {
            var gotMessage = false;

            _adapter.Handle <string>(async str => gotMessage = true);

            var body = BodyWith("hej med dig min ven");
            var headersWithoutMessageId = new Dictionary <string, string>();

            _network.Deliver("test", new TransportMessage(headersWithoutMessageId, body).ToInMemTransportMessage());

            await Task.Delay(1000);

            PrintLogs();

            Assert.That(gotMessage, Is.False, "Did not expect to receive the message");

            var loggedErrors = _listLoggerFactory
                               .Where(l => l.Level == LogLevel.Error)
                               .ToList();

            Assert.That(loggedErrors.Count, Is.EqualTo(1));

            var errorLogLine = loggedErrors.Single(e => e.Level == LogLevel.Error);

            Assert.That(errorLogLine.Text, Contains.Substring(
                            $"Received message with empty or absent '{Headers.MessageId}' header"));
        }
        public async Task CorrectlySetsReturnAddressAndSenderAddress_Defaults()
        {
            var messageHandled = new ManualResetEvent(false);
            var returnAddress  = "";
            var senderAddress  = "";

            _activator.Handle <string>(async(bus, context, message) =>
            {
                var headers = context.Headers;

                returnAddress = headers.GetValueOrNull(Headers.ReturnAddress);
                senderAddress = headers.GetValueOrNull(Headers.SenderAddress);

                messageHandled.Set();
            });

            _starter.Start();

            await _activator.Bus.SendLocal("hej med dig");

            messageHandled.WaitOrDie(TimeSpan.FromSeconds(2));

            Assert.That(returnAddress, Is.EqualTo(QueueName));
            Assert.That(senderAddress, Is.EqualTo(QueueName));
        }
Пример #8
0
        public async Task Dispose_WaitsDefinedTimeout_WhenPendingTasksTakeLonger()
        {
            // arrange
            var startedHandle = new ManualResetEvent(false);

            _handlerActivator.Handle <string>(async str =>
            {
                startedHandle.Set();

                await Task.Delay(TimeSpan.FromSeconds(10));
            });

            // act
            await _bus.Send("something");

            startedHandle.WaitOne();

            var timer = Stopwatch.StartNew();

            _bus.Dispose();

            timer.Stop();

            // assert

            Assert.That(timer.Elapsed, Is.GreaterThan(TimeSpan.FromSeconds(4)).And.LessThan(TimeSpan.FromSeconds(6)));
        }
Пример #9
0
        public async Task DeferringRequestDoesNotBreakAbilityToReply_DeferWithMessageApi()
        {
            _service.Handle <string>(async(bus, context, str) =>
            {
                const string deferredMessageHeader = "this message was already deferred";

                if (!context.TransportMessage.Headers.ContainsKey(deferredMessageHeader))
                {
                    var extraHeaders = new Dictionary <string, string>
                    {
                        { deferredMessageHeader, "" },
                        { Headers.ReturnAddress, context.Headers[Headers.ReturnAddress] }
                    };

                    Console.WriteLine($"SERVICE deferring '{str}' 1 second (elapsed: {_stopwatch.Elapsed.TotalSeconds:0.# s})");
                    await bus.Defer(TimeSpan.FromSeconds(1), str, extraHeaders);
                    return;
                }

                const string reply = "yeehaa!";
                Console.WriteLine($"SERVICE replying '{reply}'  (elapsed: {_stopwatch.Elapsed.TotalSeconds:0.# s})");
                await bus.Reply(reply);
            });

            await RunDeferTest();
        }
Пример #10
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));
        }
Пример #11
0
        public void CorrelationSequenceIsIncremented()
        {
            var correlationSequenceNumbers = new List <int>();
            var counter = new SharedCounter(1);

            _activator1.Handle <string>(async(bus, ctx, str) =>
            {
                correlationSequenceNumbers.Add(int.Parse(ctx.Headers[Headers.CorrelationSequence]));
                await bus.Advanced.Routing.Send("bus2", "hej!");
            });
            _activator2.Handle <string>(async(bus, ctx, str) =>
            {
                correlationSequenceNumbers.Add(int.Parse(ctx.Headers[Headers.CorrelationSequence]));
                await bus.Advanced.Routing.Send("bus3", "hej!");
            });
            _activator3.Handle <string>(async(bus, ctx, str) =>
            {
                correlationSequenceNumbers.Add(int.Parse(ctx.Headers[Headers.CorrelationSequence]));
                counter.Decrement();
            });

            _activator1.Bus.SendLocal("heeeej!").Wait();

            counter.WaitForResetEvent();

            Assert.That(correlationSequenceNumbers, Is.EqualTo(new[] { 0, 1, 2 }));
        }
        public async Task Dispose_WaitsDefinedTimeout_WhenPendingTasksTakeLonger()
        {
            // arrange
            var startedHandle = new ManualResetEvent(false);

            _handlerActivator.Handle <string>(async str =>
            {
                startedHandle.Set();

                await Task.Delay(TimeSpan.FromSeconds(10))
                .ConfigureAwait(false);
            });

            // act
            await _bus.Send("something");

            startedHandle.WaitOne();

            var timer = Stopwatch.StartNew();

            _bus.Dispose();

            timer.Stop();

            // assert

            timer.Elapsed
            .Should().BeCloseTo(TimeSpan.FromSeconds(5), 1000);
        }
        public async Task CanUseAlternativeTimeoutManager()
        {
            var gotTheString = new ManualResetEvent(false);

            _activator.Handle <string>(async str =>
            {
                Console.WriteLine($"Received string: '{str}'");

                gotTheString.Set();
            });

            var bus = Configure.With(_activator)
                      .Transport(t =>
            {
                var options = new AzureStorageQueuesTransportOptions {
                    UseNativeDeferredMessages = false
                };

                t.UseAzureStorageQueues(_storageAccount, QueueName, options: options);
            })
                      .Timeouts(t => t.Register(c => new InMemoryTimeoutManager(new DefaultRebusTime())))
                      .Start();

            await bus.DeferLocal(TimeSpan.FromSeconds(5), "hej med dig min ven!!!!!");

            gotTheString.WaitOrDie(TimeSpan.FromSeconds(10), "Did not receive the string withing 10 s timeout");
        }
Пример #14
0
        public async Task ItWorks()
        {
            var counter = new SharedCounter(1);

            Using(counter);

            _activator.Handle <string>(async str =>
            {
                throw new ApplicationException("1st level!!");
            });

            _activator.Handle <Failed <string> >(async failed =>
            {
                if (failed.Message != "hej med dig!")
                {
                    counter.Fail("Did not receive the expected message!");
                    return;
                }

                counter.Decrement();
            });

            await _bus.SendLocal("hej med dig!");

            counter.WaitForResetEvent();
        }
Пример #15
0
        public async Task ItWorksWithCovarianceToo()
        {
            var counter = new SharedCounter(1);

            Using(counter);

            _activator.Handle <BaseMessage>(async baseMessage =>
            {
                throw new ApplicationException("1st level!!");
            });

            _activator.Handle <IFailed <BaseMessage> >(async failed =>
            {
                if (failed.Message is ConcreteMessage)
                {
                    counter.Decrement();
                    return;
                }

                counter.Fail("Did not receive the expected message!");
            });

            await _bus.SendLocal(new ConcreteMessage());

            counter.WaitForResetEvent();
        }
Пример #16
0
        public async Task DoesNotCopyFailedMessage()
        {
            _adapter.Handle <string>(async _ =>
            {
                throw new Exception("w00t!!");
            });

            await _bus.SendLocal("woohooo!!!!");

            await Task.Delay(TimeSpan.FromSeconds(3));

            var message = _network.GetNextOrNull("audit");

            Assert.That(message, Is.Null, "Apparently, a message copy was received anyway!!");
        }
Пример #17
0
        public async Task SusbcriberDoesNotReceiveMessagesWhenItHasNotYetSubscribed()
        {
            var receivedStringMessage = false;

            _subscriberHandlers.Handle <string>(async str =>
            {
                receivedStringMessage = true;
            });

            await _publisherBus.Advanced.Topics.Publish("someTopic", "hej med dig min ven!!!!!");

            await Task.Delay(2000);

            Assert.That(receivedStringMessage, Is.False, "Did not expect to receive the string message in the subscriber because it has not subscribed");
        }
        public async Task CanReceiveBunchOfMessages()
        {
            var events = new ConcurrentQueue<string>();

            using (var activator = new BuiltinHandlerActivator())
            {
                activator.Handle<string>(async s => events.Enqueue(s));

                Configure.With(activator)
                    .Logging(l => l.Console(minLevel:LogLevel.Info))
                    .Transport(t => t.UseInMemoryTransport(new InMemNetwork(), "bimse"))
                    .Options(o =>
                    {
                        o.Register<IWorkerFactory>(c =>
                        {
                            var transport = c.Get<ITransport>();
                            var pipeline = c.Get<IPipeline>();
                            var pipelineInvoker = c.Get<IPipelineInvoker>();
                            var rebusLoggerFactory = c.Get<IRebusLoggerFactory>();
                            return new AsyncTaskWorkerFactory(transport, pipeline, pipelineInvoker, rebusLoggerFactory);
                        });
                        o.SetNumberOfWorkers(100);
                    })
                    .Start();

                var bus = activator.Bus;

                await Task.WhenAll(Enumerable.Range(0, 100)
                    .Select(i => bus.SendLocal(string.Format("msg-{0}", i))));

                await Task.Delay(1000);

                Assert.That(events.Count, Is.EqualTo(100));
            }
        }
Пример #19
0
        public async Task CanMoveMessageToErrorQueueEvenThoughExceptionIsNotSerializable()
        {
            using (var activator = new BuiltinHandlerActivator())
            {
                activator.Handle<string>(async str =>
                {
                    throw new ThisOneCannotBeSerialized("BAM!!!!!!!!!!!11111111111111111");
                });

                var network = new InMemNetwork();

                var bus = Configure.With(activator)
                    .Transport(t => t.UseInMemoryTransport(network, "unserializable exceptions"))
                    .Options(o => o.SimpleRetryStrategy(maxDeliveryAttempts: 1))
                    .Start();

                const string knownString = "JUST SOME LISP!!!!11((((((((((((((((((()))))))))))))))))))))))";

                await bus.SendLocal(knownString);

                var failedMessage = await network.WaitForNextMessageFrom("error");

                Assert.That(Encoding.UTF8.GetString(failedMessage.Body), Is.EqualTo(JsonConvert.SerializeObject(knownString)));
            }
        }
Пример #20
0
        static void Main()
        {
            using (var adapter = new BuiltinHandlerActivator())
            {
                adapter.Handle<Job>(async job =>
                {
                    Console.WriteLine("Processing job {0}", job.JobNumber);

                    await Task.Delay(TimeSpan.FromMilliseconds(300));
                });

                Configure.With(adapter)
                    .Logging(l => l.ColoredConsole(LogLevel.Warn))
                    .Transport(t => t.UseSqlServer("server=.; initial catalog=rebus; integrated security=true", "Messages", "consumer"))
                    .Options(o =>
                    {
                        o.SetNumberOfWorkers(1);
                        o.SetMaxParallelism(20);
                    })
                    .Start();

                Console.WriteLine("Consumer listening - press ENTER to quit");
                Console.ReadLine();
            }
        }
Пример #21
0
        public void ItWorksWithComplexMessage(bool withCompressionEnabled)
        {
            var activator = new BuiltinHandlerActivator();
            var gotIt = new ManualResetEvent(false);

            activator.Handle<TextMessage>(async str =>
            {
                if (string.Equals(str.Text, LongText))
                {
                    gotIt.Set();
                }
                else
                {
                    throw new Exception(string.Format("Received text with {0} chars did not match expected text with {1} chars!",
                        str.Text.Length, LongText.Length));
                }
            });

            Using(activator);

            var bus = CreateBus(withCompressionEnabled, activator);

            bus.SendLocal(new TextMessage {Text = LongText}).Wait();

            gotIt.WaitOrDie(TimeSpan.FromSeconds(10));
        }
Пример #22
0
        static IBus StartBus(InMemNetwork network, string queueName, ConcurrentQueue<string> recordedEvents)
        {
            var activator = new BuiltinHandlerActivator();

            activator.Handle(async (string message) =>
            {
                recordedEvents.Enqueue($"GOT MESSAGE: {message}");
            });

            return Configure.With(activator)
                .Transport(t => t.UseInMemoryTransport(network, queueName))
                .Options(o =>
                {
                    o.Decorate(c =>
                    {
                        var events = c.Get<BusLifetimeEvents>();

                        events.BusStarting += () => recordedEvents.Enqueue("Bus starting");
                        events.BusStarted += () => recordedEvents.Enqueue("Bus started");
                        events.BusDisposing += () => recordedEvents.Enqueue("Bus disposing");
                        events.BusDisposed += () => recordedEvents.Enqueue("Bus disposed");

                        return events;
                    });
                })
                .Start();
        }
        public async Task DoIt()
        {
            var builtinHandlerActivator = new BuiltinHandlerActivator();
            var allDone = false;
            var gotMessage = new ManualResetEvent(false);

            builtinHandlerActivator.Handle<string>(async _ =>
            {
                gotMessage.Set();

                await Task.Delay(2000);

                allDone = true;
            });

            var bus = Configure.With(builtinHandlerActivator)
                .Transport(t => t.UseInMemoryTransport(new InMemNetwork(), "shutdown with pending tasks"))
                .Start();

            using (bus)
            {
                await bus.SendLocal("hej");

                gotMessage.WaitOrDie(TimeSpan.FromSeconds(2));

                // make bus shut down here
            }

            Assert.That(allDone, Is.True, "The message was apparently not handled all the way to the end!!!");
        }
Пример #24
0
        static void Main()
        {
            using (var adapter = new BuiltinHandlerActivator())
            {
                adapter.Handle<Job>(async job =>
                {
                    Console.WriteLine("Processing job {0}", job.JobNumber);

                    await Task.Delay(TimeSpan.FromMilliseconds(300));
                });

                Configure.With(adapter)
                    .Logging(l => l.ColoredConsole(LogLevel.Warn))
                    .Transport(t => t.UsePostgreSql("server=localhost;port=5433;database=rebus2_test; user id=test; password=test; maximum pool size=30", "messages", "consumer"))
                    .Options(o =>
                    {
                        o.SetNumberOfWorkers(10);
                        o.SetMaxParallelism(20);
                    })
                    .Start();

                Console.WriteLine("Consumer listening - press ENTER to quit");
                Console.ReadLine();
            }
        }
        public async Task NizzleName()
        {
            var gotMessage = new ManualResetEvent(false);

            using (var activator = new BuiltinHandlerActivator())
            {
                activator.Handle<string>(async s =>
                {
                    Console.WriteLine("Got message: {0}", s);
                    gotMessage.Set();
                });

                Configure.With(activator)
                    .Transport(t => t.UseInMemoryTransport(new InMemNetwork(), "bimse"))
                    .Options(o =>
                    {
                        o.Register<IWorkerFactory>(c =>
                        {
                            var transport = c.Get<ITransport>();
                            var pipeline = c.Get<IPipeline>();
                            var pipelineInvoker = c.Get<IPipelineInvoker>();
                            var rebusLoggerFactory = c.Get<IRebusLoggerFactory>();
                            return new AsyncTaskWorkerFactory(transport, pipeline, pipelineInvoker, rebusLoggerFactory);
                        });
                    })
                    .Start();

                await activator.Bus.SendLocal("hej med dig min ven");

                gotMessage.WaitOrDie(TimeSpan.FromSeconds(3));
            }
        }
        public void DoesNotDispatchMessageWithNullBus()
        {
            var busInstances = new ConcurrentQueue<IBus>();

            using (var activator = new BuiltinHandlerActivator())
            {
                activator.Handle<string>(async (bus, message) =>
                {
                    busInstances.Enqueue(bus);
                });

                Configure.With(activator)
                    .Logging(l => l.ColoredConsole(LogLevel.Warn))
                    .Transport(t => t.UseInMemoryTransport(new InMemNetwork(), "race-condition"))
                    .Options(o =>
                    {
                        o.SetNumberOfWorkers(1);
                        o.SetMaxParallelism(1);
                    })
                    .Start();

                Task.WaitAll(Enumerable.Range(0, 1000)
                    .Select(i => activator.Bus.SendLocal($"message-{i}"))
                    .ToArray());
            }

            Thread.Sleep(1000);

            var numberOfNulls = busInstances.Count(i => i == null);

            Assert.That(numberOfNulls, Is.EqualTo(0),
                "Did not expect any messages to be dispatched with a NULL bus instance");
        }
            public void DoesNotBarfInTheBackground()
            {
                var doneHandlingMessage = new ManualResetEvent(false);

                _activator.Handle <string>(async str =>
                {
                    for (var count = 0; count < 5; count++)
                    {
                        Console.WriteLine("waiting...");
                        await Task.Delay(TimeSpan.FromSeconds(20));
                    }

                    Console.WriteLine("done waiting!");

                    doneHandlingMessage.Set();
                });

                _activator.Bus.SendLocal("hej med dig min ven!").Wait();

                doneHandlingMessage.WaitOrDie(TimeSpan.FromMinutes(2));

                var logLinesAboveInformation = _loggerFactory
                                               .Where(l => l.Level >= LogLevel.Warn)
                                               .ToList();

                Assert.That(!logLinesAboveInformation.Any(), "Expected no warnings - got this: {0}", string.Join(Environment.NewLine, logLinesAboveInformation));
            }
        public async Task CanRoundtripSingleMessageWithBus()
        {
            var brilliantQueueName = TestConfig.GetName("roundtrippin-single-bus");
            var transport          = AmazonSqsTransportFactory.CreateTransport(brilliantQueueName, TimeSpan.FromSeconds(30));

            Using(transport);

            using (var activator = new BuiltinHandlerActivator())
            {
                var gotTheMessage = new ManualResetEvent(false);

                activator.Handle <string>(async message =>
                {
                    gotTheMessage.Set();
                });

                Configure.With(activator)
                .Transport(t => t.Register(c => transport))
                .Start();

                await activator.Bus.SendLocal("HAIIIIIIIIIIIIIIIIII!!!!111");

                gotTheMessage.WaitOrDie(TimeSpan.FromSeconds(5));
            }
        }
        public void Yes()
        {
            using (var activator = new BuiltinHandlerActivator())
            {
                var gotMessage = new ManualResetEvent(false);

                activator.Handle <string>(async(bus, context, message) =>
                {
                    var uow = (Uow)context.TransactionContext.Items["uow"];

                    if (uow == null)
                    {
                        throw new RebusApplicationException("uow was null");
                    }

                    gotMessage.Set();
                });

                Configure.With(activator)
                .Transport(t => t.UseInMemoryTransport(new InMemNetwork(), "uow-test"))
                .Options(o => o.EnableUnitOfWork(Create, (context, uow) => uow.Commit()))
                .Start();

                activator.Bus.Advanced.SyncBus.SendLocal("hej med dig min ven!");

                gotMessage.WaitOrDie(TimeSpan.FromSeconds(3));
            }
        }
Пример #30
0
        public async Task ItHasBeenFixed()
        {
            var activator = new BuiltinHandlerActivator();

            Using(activator);

            var receivedMessageIds = new ConcurrentBag<string>();

            activator.Handle<string>(async (_, context, message) =>
            {
                receivedMessageIds.Add(context.TransportMessage.Headers[Headers.MessageId]);
            });

            var bus = Configure.With(activator)
                .Transport(t => t.UseInMemoryTransport(new InMemNetwork(), "buggerino"))
                .Start();

            var customHeaders = new Dictionary<string, string>
            {
                {"custom-header", "woohoo"}
            };

            const string repeatedMessage = "hej med dig";

            await bus.SendLocal(repeatedMessage, customHeaders);
            await bus.SendLocal("hej igen med", customHeaders);
            await bus.SendLocal(repeatedMessage, customHeaders);

            await Task.Delay(TimeSpan.FromSeconds(1));

            Assert.That(receivedMessageIds.Distinct().Count(), Is.EqualTo(3), "Expected three unique message IDs - got: {0}", string.Join(", ", receivedMessageIds));
        }
Пример #31
0
        public async Task Yeas()
        {
            var gotTheString = new ManualResetEvent(false);

            var activator = new BuiltinHandlerActivator();

            Using(activator);

            activator.Handle <string>(async str => gotTheString.Set());

            Configure.With(activator)
            .Transport(t =>
            {
                var config = new AmazonSQSConfig {
                    RegionEndpoint = RegionEndpoint.EUWest2
                };

                t.UseAmazonSQS("queue", config);
            })
            .Start();

            await activator.Bus.SendLocal("HEJ MED DIG MIN VEN");

            gotTheString.WaitOrDie(TimeSpan.FromSeconds(3), "Did not get the string within 3 s timeout");
        }
Пример #32
0
    public async Task CannotDeadletterTwice()
    {
        var caughtExceptions = new ConcurrentQueue <Exception>();

        using var activator = new BuiltinHandlerActivator();

        activator.Handle <string>(async(bus, _) =>
        {
            await bus.Advanced.TransportMessage.Deadletter(errorDetails: "has been manually dead-lettered");

            try
            {
                await bus.Advanced.TransportMessage.Deadletter(errorDetails: "has been manually dead-lettered");
            }
            catch (Exception exception)
            {
                caughtExceptions.Enqueue(exception);
            }
        });

        Configure.With(activator)
        .Transport(t => t.UseInMemoryTransport(new InMemNetwork(), "manual-deadlettering"))
        .Start();

        await activator.Bus.SendLocal("HEJ MED DIG MIN VEN");

        var caughtException = await caughtExceptions.DequeueNext(timeoutSeconds : 5);

        Console.WriteLine(caughtException);

        Assert.That(caughtException, Is.TypeOf <InvalidOperationException>());
    }
Пример #33
0
        public async Task CanReceiveBunchOfMessages()
        {
            var events = new ConcurrentQueue <string>();

            using (var activator = new BuiltinHandlerActivator())
            {
                activator.Handle <string>(async s => events.Enqueue(s));

                Configure.With(activator)
                .Logging(l => l.Console(minLevel: LogLevel.Info))
                .Transport(t => t.UseInMemoryTransport(new InMemNetwork(), "bimse"))
                .Options(o =>
                {
                    o.Register <IWorkerFactory>(c =>
                    {
                        var transport          = c.Get <ITransport>();
                        var pipeline           = c.Get <IPipeline>();
                        var pipelineInvoker    = c.Get <IPipelineInvoker>();
                        var rebusLoggerFactory = c.Get <IRebusLoggerFactory>();
                        return(new AsyncTaskWorkerFactory(transport, pipeline, pipelineInvoker, rebusLoggerFactory));
                    });
                    o.SetNumberOfWorkers(100);
                })
                .Start();

                var bus = activator.Bus;

                await Task.WhenAll(Enumerable.Range(0, 100)
                                   .Select(i => bus.SendLocal(string.Format("msg-{0}", i))));

                await Task.Delay(1000);

                Assert.That(events.Count, Is.EqualTo(100));
            }
        }
        public IBus GetBus <TMessage>(string inputQueueAddress, Func <TMessage, Task> handler)
        {
            var builtinHandlerActivator = new BuiltinHandlerActivator();

            builtinHandlerActivator.Handle(handler);

            PurgeQueue(inputQueueAddress);

            var bus = Configure.With(builtinHandlerActivator)
                      .Transport(t =>
            {
                var info = AmazonSqsTransportFactory.ConnectionInfo;

                var amazonSqsConfig = new AmazonSQSConfig {
                    RegionEndpoint = info.RegionEndpoint
                };

                t.UseAmazonSQS(info.AccessKeyId, info.SecretAccessKey, amazonSqsConfig, inputQueueAddress);
            })
                      .Options(o =>
            {
                o.SetNumberOfWorkers(10);
                o.SetMaxParallelism(10);
            })
                      .Start();

            _stuffToDispose.Push(bus);

            return(bus);
        }
Пример #35
0
        public async Task CanSendAndReceive()
        {
            var gotMessage = new ManualResetEvent(false);

            _handlerActivator
            .Handle <string>(async(bus, str) =>
            {
                if (str == "hej med dig min ven!")
                {
                    Console.WriteLine("w00t!");

                    await bus.Reply("t00t!");
                }

                if (str == "t00t!")
                {
                    Console.WriteLine("got t++t!!!");

                    gotMessage.Set();
                }
            });

            await _bus.Send("hej med dig min ven!");

            gotMessage.WaitOrDie(TimeSpan.FromSeconds(30));
        }
Пример #36
0
    public async Task CanDoIt()
    {
        using var gotTheEvent = new ManualResetEvent(initialState: false);
        using var activator   = new BuiltinHandlerActivator();

        var subscriberStore = new InMemorySubscriberStore();
        var network         = new InMemNetwork();

        var starter = Configure.With(activator)
                      .Transport(t => t.UseInMemoryTransport(network, "buggerino"))
                      .Subscriptions(s => s.StoreInMemory(subscriberStore))
                      .Create();

        var publisher = Configure.With(Using(new BuiltinHandlerActivator()))
                        .Transport(t => t.UseInMemoryTransportAsOneWayClient(network))
                        .Subscriptions(s => s.StoreInMemory(subscriberStore))
                        .Start();

        Task Handle(ThisIsTheEventWeAreTalkingAbout configurationUpdatedEvent)
        {
            Console.WriteLine($"Got event: {configurationUpdatedEvent}");
            gotTheEvent.Set();
            return(Task.CompletedTask);
        }

        activator.Handle <ThisIsTheEventWeAreTalkingAbout>((ThisIsTheEventWeAreTalkingAbout e) => Handle(e));

        await starter.Bus.Subscribe(typeof(ThisIsTheEventWeAreTalkingAbout));

        starter.Start();

        await publisher.Publish(new ThisIsTheEventWeAreTalkingAbout());

        gotTheEvent.WaitOrDie(timeout: TimeSpan.FromSeconds(2));
    }
Пример #37
0
        static void Main()
        {
            using (var adapter = new BuiltinHandlerActivator())
            {
                adapter.Handle<Reply>(async reply =>
                {
                    Console.WriteLine("Got reply '{0}' (from OS process {1})", reply.KeyChar, reply.OsProcessId);
                });

                Configure.With(adapter)
                    .Logging(l => l.ColoredConsole(minLevel: LogLevel.Warn))
                    .Transport(t => t.UseSqlServer("server=.; database=rebus; trusted_connection=true", "Messages", "producer.input"))
                    .Routing(r => r.TypeBased().MapAssemblyOf<Job>("consumer.input"))
                    .Start();

                Console.WriteLine("Press Q to quit or any other key to produce a job");
                while (true)
                {
                    var keyChar = char.ToLower(Console.ReadKey(true).KeyChar);

                    switch (keyChar)
                    {
                        case 'q':
                            goto quit;

                        default:
                            adapter.Bus.Send(new Job(keyChar)).Wait();
                            break;
                    }
                }

            quit:
                Console.WriteLine("Quitting...");
            }
        }
Пример #38
0
        public void DispatchesDynamicMessageWhenDotNetTypeCannotBeFound()
        {
            var gotTheMessage = new ManualResetEvent(false);

            string messageText = null;

            _builtinHandlerActivator.Handle <dynamic>(async message =>
            {
                Console.WriteLine("Received dynamic message: {0}", message);

                messageText = message.something.text;

                gotTheMessage.Set();
            });

            var headers = new Dictionary <string, string>
            {
                { Headers.MessageId, Guid.NewGuid().ToString() },
                { Headers.ContentType, "application/json;charset=utf-8" },
            };

            var transportMessage = new TransportMessage(headers, Encoding.UTF8.GetBytes(@"{
    ""something"": {
        ""text"": ""OMG dynamic JSON BABY!!""
    }
}"));

            _network.Deliver(InputQueueName, new InMemTransportMessage(transportMessage));

            gotTheMessage.WaitOrDie(TimeSpan.FromSeconds(2));

            Assert.That(messageText, Is.EqualTo("OMG dynamic JSON BABY!!"));
        }
Пример #39
0
        public async Task ItHasBeenFixed()
        {
            var activator = new BuiltinHandlerActivator();

            var receivedMessageIds = new ConcurrentBag <string>();

            activator.Handle <string>(async(_, context, message) =>
            {
                receivedMessageIds.Add(context.TransportMessage.Headers[Headers.MessageId]);
            });

            Using(activator);

            var bus = Configure.With(activator)
                      .Transport(t => t.UseInMemoryTransport(new InMemNetwork(), "buggerino"))
                      .Start();

            var customHeaders = new Dictionary <string, string>
            {
                { "custom-header", "woohoo" }
            };


            const string repeatedMessage = "hej med dig";

            await bus.SendLocal(repeatedMessage, customHeaders);

            await bus.SendLocal("hej igen med", customHeaders);

            await bus.SendLocal(repeatedMessage, customHeaders);

            await Task.Delay(TimeSpan.FromSeconds(1));

            Assert.That(receivedMessageIds.Distinct().Count(), Is.EqualTo(3), "Expected three unique message IDs - got: {0}", string.Join(", ", receivedMessageIds));
        }
Пример #40
0
    public async Task ItWorks()
    {
        using var gotTheString = new ManualResetEvent(initialState: false);

        var connectionString = SqlTestHelper.ConnectionString;

        using var timeoutManager = new BuiltinHandlerActivator();

        Configure.With(timeoutManager)
        .Transport(t => t.UseSqlServer(new SqlServerTransportOptions(connectionString), "TimeoutManager").DisableNativeTimeoutManager())
        .Timeouts(t => t.StoreInSqlServer(connectionString, "Timeouts"))
        .Start();

        using var ordinaryEndpoint = new BuiltinHandlerActivator();

        ordinaryEndpoint.Handle <string>(async str => gotTheString.Set());

        Configure.With(ordinaryEndpoint)
        .Transport(t => t.UseSqlServer(new SqlServerTransportOptions(connectionString), "OrdinaryEndpoint").DisableNativeTimeoutManager())
        .Timeouts(t => t.UseExternalTimeoutManager("TimeoutManager"))
        .Start();

        await ordinaryEndpoint.Bus.DeferLocal(TimeSpan.FromSeconds(2), "HEJ MED DIG MIN VEN 🤠");

        gotTheString.WaitOrDie(timeout: TimeSpan.FromSeconds(5), errorMessage: "Did not receive the expected string message within 5 s timeout");
    }
Пример #41
0
        public async Task NizzleName()
        {
            var gotMessage = new ManualResetEvent(false);

            using (var activator = new BuiltinHandlerActivator())
            {
                activator.Handle <string>(async s =>
                {
                    Console.WriteLine("Got message: {0}", s);
                    gotMessage.Set();
                });

                Configure.With(activator)
                .Transport(t => t.UseInMemoryTransport(new InMemNetwork(), "bimse"))
                .Options(o =>
                {
                    o.Register <IWorkerFactory>(c =>
                    {
                        var transport          = c.Get <ITransport>();
                        var pipeline           = c.Get <IPipeline>();
                        var pipelineInvoker    = c.Get <IPipelineInvoker>();
                        var rebusLoggerFactory = c.Get <IRebusLoggerFactory>();
                        return(new AsyncTaskWorkerFactory(transport, pipeline, pipelineInvoker, rebusLoggerFactory));
                    });
                })
                .Start();

                await activator.Bus.SendLocal("hej med dig min ven");

                gotMessage.WaitOrDie(TimeSpan.FromSeconds(3));
            }
        }
Пример #42
0
        public void IncludesCorrelationIdInTheThreeLoggedLines()
        {
            // ${basedir}/logs/logfile.log
            var logFilePath = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "logs", "logfile.log");
            if (File.Exists(logFilePath))
            {
                File.Delete(logFilePath);
            }

            var activator = new BuiltinHandlerActivator();

            Configure.With(Using(activator))
                .Logging(l => l.NLog())
                .Transport(t => t.UseInMemoryTransport(new InMemNetwork(), "test"))
                .Start();

            var counter = new SharedCounter(1);

            Using(counter);

            var logger = LogManager.GetLogger("test");

            activator.Handle<string>(async str =>
            {
                logger.Info("1");

                await Task.Delay(100);

                logger.Info("2");

                await Task.Delay(100);

                logger.Info("3");

                counter.Decrement();
            });

            var headers = new Dictionary<string,string>
            {
                {Headers.CorrelationId, "known-correlation-id" }
            };

            activator.Bus.SendLocal("hej med dig min ven!!!", headers).Wait();

            counter.WaitForResetEvent();

            WaitForFile(logFilePath);

            var loggedLines = File.ReadAllLines(logFilePath);

            AssertLineIsThere(loggedLines, "1|known-correlation-id");
            AssertLineIsThere(loggedLines, "2|known-correlation-id");
            AssertLineIsThere(loggedLines, "3|known-correlation-id");

        }
Пример #43
0
        IBus GetBus(ConcurrentQueue<string> receivedMessages, int numberOfWorkers)
        {
            var activator = new BuiltinHandlerActivator();
            activator.Handle<string>(async str => receivedMessages.Enqueue(str));

            var bus = Configure.With(activator)
                .Transport(t => t.UseMsmq(_inputQueueName))
                .Options(o => o.SetNumberOfWorkers(numberOfWorkers))
                .Start();

            return bus;
        }
Пример #44
0
        static void ConfigureSubscriber(BuiltinHandlerActivator activator, string inputQueueName)
        {
            activator.Handle<string>(async str =>
            {
                Console.WriteLine("{0} => '{1}'", str, inputQueueName);
            });

            Configure.With(activator)
                .Logging(l => l.ColoredConsole(MinimumLogLevel))
                .Transport(t => t.UseRabbitMq(ConnectionString, inputQueueName))
                .Start();
        }
        IBus CreateBus(string inputQueueName, Func<string, Task> stringHandler)
        {
            var activator = new BuiltinHandlerActivator();

            activator.Handle(stringHandler);

            var bus = Configure.With(activator)
                .Logging(l => l.ColoredConsole(minLevel: LogLevel.Warn))
                .Transport(t => t.UseSqlServer(SqlTestHelper.ConnectionString, _messagesTableName, inputQueueName))
                .Subscriptions(s => s.StoreInSqlServer(SqlTestHelper.ConnectionString, _subscriptionsTableName, isCentralized: true))
                .Start();

            return Using(bus);
        }
        public async Task YesItDoes()
        {
            using (var activator = new BuiltinHandlerActivator())
            {
                var counter = new SharedCounter(1);
                activator.Handle<string>(async str => counter.Decrement());

                var bus = Configure.With(activator)
                    .Transport(t => t.UseAzureServiceBus(_connectionString, _queueName).EnablePartitioning())
                    .Start();

                await bus.SendLocal("hej med dig min ven!!!");

                counter.WaitForResetEvent();
            }
        }
Пример #47
0
        protected override void SetUp()
        {
            var network = new InMemNetwork();
            var subscriberStore = new InMemorySubscriberStore();
            _publisher = GetEndpoint(network, "publisher", c =>
            {
                c.Subscriptions(s => s.StoreInMemory(subscriberStore));
                c.Routing(r => r.TypeBased());
            });

            _client1GotTheEvent = new ManualResetEvent(false);
            _client1 = GetEndpoint(network, "client1", c =>
            {
                c.Routing(r => r.TypeBased().Map<SomeKindOfEvent>("publisher"));
            });
            _client1.Handle<SomeKindOfEvent>(async e => _client1GotTheEvent.Set());
        }
Пример #48
0
        BuiltinHandlerActivator GetBus(string queueName, Func<string, Task> handlerMethod = null)
        {
            var activator = new BuiltinHandlerActivator();

            Using(activator);

            if (handlerMethod != null)
            {
                activator.Handle(handlerMethod);
            }

            Configure.With(activator)
                .Transport(t => t.UseRabbitMq(RabbitMqTransportFactory.ConnectionString, queueName))
                .Start();

            return activator;
        }
Пример #49
0
        static void Main()
        {
            using (var activator = new BuiltinHandlerActivator())
            {
                activator.Handle<string>(async message =>
                {
                    Console.WriteLine($"Received message {message}");
                });

                Configure.With(activator)
                    .Logging(l => l.ColoredConsole(LogLevel.Warn))
                    .Transport(t => t.UseMsmq("server"))
                    .Start();

                Console.WriteLine("Press ENTER to quit");
                Console.ReadLine();
            }
        }
Пример #50
0
        static void Main()
        {
            using (var adapter = new BuiltinHandlerActivator())
            {
                adapter.Handle<Job>(async (bus, job) =>
                {
                    await bus.Reply(new Reply(job.KeyChar, Process.GetCurrentProcess().Id));
                });

                Configure.With(adapter)
                    .Logging(l => l.ColoredConsole(minLevel: LogLevel.Warn))
                    .Transport(t => t.UseSqlServer("server=.; database=rebus; trusted_connection=true", "Messages", "consumer.input"))
                    .Start();

                Console.WriteLine("Press ENTER to quit");
                Console.ReadLine();
            }
        }
Пример #51
0
        protected override void SetUp()
        {
            SqlTestHelper.DropTable("subscriptions");

            var network = new InMemNetwork();
            _publisher = GetEndpoint(network, "publisher", c =>
            {
                c.Subscriptions(s => s.StoreInSqlServer(SqlTestHelper.ConnectionString, "subscriptions"));
                c.Routing(r => r.TypeBased());
            });

            _client1GotTheEvent = new ManualResetEvent(false);
            _client1 = GetEndpoint(network, "client1", c =>
            {
                c.Routing(r => r.TypeBased().Map<SomeKindOfEvent>("publisher"));
            });
            _client1.Handle<SomeKindOfEvent>(async e => _client1GotTheEvent.Set());
        }
Пример #52
0
        public async Task WorksOutOfTheBoxWithInternalTimeoutManager()
        {
            var gotTheMessage = new ManualResetEvent(false);
            var activator = new BuiltinHandlerActivator();

            activator.Handle<string>(async str => gotTheMessage.Set());

            Configure.With(activator)
                .Transport(t => t.UseMsmq(_queueName))
                .Start();

            var stopwatch = Stopwatch.StartNew();

            await activator.Bus.Defer(TimeSpan.FromSeconds(5), "hej med dig min ven!");

            gotTheMessage.WaitOrDie(TimeSpan.FromSeconds(6), "Message was not received within 6,5 seconds (which it should have been since it was only deferred 5 seconds)");
            
            Assert.That(stopwatch.Elapsed, Is.GreaterThan(TimeSpan.FromSeconds(5)), "It must take more than 5 second to get the message back");
        }
Пример #53
0
        static void Main()
        {
            using (var adapter = new BuiltinHandlerActivator())
            {
                adapter.Handle<Job>(async job =>
                {
                    Console.WriteLine("Processing job {0}", job.JobNumber);
                    Thread.Sleep(100);
                });

                Configure.With(adapter)
                    .Logging(l => l.ColoredConsole(LogLevel.Warn))
                    .Transport(t => t.UseRabbitMq("amqp://localhost", "consumer"))
                    .Start();

                adapter.Bus.Subscribe<Job>().Wait();

                Console.WriteLine("Consumer listening - press ENTER to quit");
                Console.ReadLine();
            }
        }
Пример #54
0
        static void Main()
        {
            using (var adapter = new BuiltinHandlerActivator())
            {
                adapter.Handle<Job>(async (bus, job) =>
                {
                    var keyChar = job.KeyChar;
                    var processId = Process.GetCurrentProcess().Id;
                    var reply = new Reply(keyChar, processId);

                    await bus.Reply(reply);
                });

                Configure.With(adapter)
                    .Logging(l => l.ColoredConsole(minLevel: LogLevel.Warn))
                    .Transport(t => t.UseSqlServer(ConnectionString, "Messages", "consumer.input"))
                    .Start();

                Console.WriteLine("Press ENTER to quit");
                Console.ReadLine();
            }
        }
        public async Task CanUseCustomExchangeName()
        {
            const string connectionString = RabbitMqTransportFactory.ConnectionString;

            const string customDirectExchangeName = "Dingo";
            const string customTopicExchangeName = "Topico";

            RabbitMqTransportFactory.DeleteExchange(RabbitMqOptionsBuilder.DefaultDirectExchangeName);
            RabbitMqTransportFactory.DeleteExchange(RabbitMqOptionsBuilder.DefaultTopicExchangeName);
            RabbitMqTransportFactory.DeleteExchange(customDirectExchangeName);
            RabbitMqTransportFactory.DeleteExchange(customTopicExchangeName);

            using (var activator = new BuiltinHandlerActivator())
            {
                var gotString = new ManualResetEvent(false);
                activator.Handle<string>(async str => gotString.Set());

                Configure.With(activator)
                    .Transport(t =>
                    {
                        var queueName = TestConfig.QueueName("custom-exchange");

                        t.UseRabbitMq(connectionString, queueName)
                            .ExchangeNames(directExchangeName: customDirectExchangeName, topicExchangeName: customTopicExchangeName);
                    })
                    .Start();

                await activator.Bus.SendLocal("hej");

                gotString.WaitOrDie(TimeSpan.FromSeconds(3));
            }

            Assert.That(RabbitMqTransportFactory.ExchangeExists(RabbitMqOptionsBuilder.DefaultDirectExchangeName), Is.False);
            Assert.That(RabbitMqTransportFactory.ExchangeExists(RabbitMqOptionsBuilder.DefaultTopicExchangeName), Is.False);
            Assert.That(RabbitMqTransportFactory.ExchangeExists(customDirectExchangeName), Is.True);
            Assert.That(RabbitMqTransportFactory.ExchangeExists(customTopicExchangeName), Is.True);
        }
Пример #56
0
        BuiltinHandlerActivator GetBus(string queueName, Func<string, Task> handlerMethod = null)
        {
            var activator = new BuiltinHandlerActivator();

            Using(activator);

            if (handlerMethod != null)
            {
                activator.Handle(handlerMethod);
            }

            Configure.With(activator)
                .Transport(t =>
                {
                    t.UseRabbitMq(RabbitMqTransportFactory.ConnectionString, queueName)
                        .AddClientProperties(new Dictionary<string, string>
                        {
                            {"description", "pub-sub test in RabbitMqPubSubTest.cs"}
                        });
                })
                .Start();

            return activator;
        }
Пример #57
0
        public async Task NizzleName(int numberOfMessages, int numberOfWorkers)
        {
            var activator = new BuiltinHandlerActivator();
            var sentmessageIds = new ConcurrentDictionary<int, int>();
            var receivedMessageIds = new ConcurrentDictionary<int, int>();

            activator.Handle<SomeMessage>(async message =>
            {
                var id = message.Id;
                receivedMessageIds.AddOrUpdate(id, i => 1, (i, existing) => existing + 1);
            });

            var bus = (RebusBus)Configure.With(activator)
                .Logging(l => l.None())
                .Transport(t => t.UseMsmq(InputQueueName))
                .Routing(t => t.TypeBased().Map<SomeMessage>(InputQueueName))
                .Options(o => o.SetNumberOfWorkers(0))
                .Start();

            Using(bus);

            var sendStopwatch = Stopwatch.StartNew();

            Console.WriteLine("Sending {0} messages", numberOfMessages);

            await Task.WhenAll(Enumerable
                .Range(0, numberOfMessages)
                .Select(id => bus.Send(new SomeMessage { Id = id })));

            var elapsedSending = sendStopwatch.Elapsed;

            Console.WriteLine("SENT {0} messages in {1:0.0} s - that's {2:0.0}/s",
                numberOfMessages, elapsedSending.TotalSeconds, numberOfMessages / elapsedSending.TotalSeconds);

            bus.SetNumberOfWorkers(numberOfWorkers);

            var receiveStopwatch = Stopwatch.StartNew();
            Console.WriteLine("Waiting until they have been received");

            while (receivedMessageIds.Count < numberOfMessages)
            {
                Console.WriteLine("got {0} messages so far...", receivedMessageIds.Count);
                await Task.Delay(1000);
            }

            var elapsedReceiving = receiveStopwatch.Elapsed;

            Console.WriteLine("RECEIVED {0} messages in {1:0.0} s - that's {2:0.0}/s", 
                numberOfMessages, elapsedReceiving.TotalSeconds, numberOfMessages/elapsedReceiving.TotalSeconds);

            var sentButNotReceived = sentmessageIds.Keys.Except(receivedMessageIds.Keys).ToList();
            var receivedMoreThanOnce = receivedMessageIds.Where(kvp => kvp.Value > 1).ToList();

            if (sentButNotReceived.Any())
            {
                Assert.Fail("The following IDs were sent but not received: {0}", string.Join(", ", sentButNotReceived));
            }

            if (receivedMoreThanOnce.Any())
            {
                Assert.Fail("The following IDs were received more than once: {0}",
                    string.Join(", ", receivedMoreThanOnce.Select(kvp => string.Format("{0} ({1})", kvp.Key, kvp.Value))));
            }
        }
Пример #58
0
        public void VerifyThatEndpointCanRecoverAfterLosingRabbitMqConnection()
        {
            const int numberOfMessages = 100;
            const int millisecondsDelay = 300;

            var expectedTestDuration = TimeSpan.FromMilliseconds(numberOfMessages * millisecondsDelay);

            Console.WriteLine($"Expected test duration {expectedTestDuration}");

            using (var activator = new BuiltinHandlerActivator())
            {
                var receivedMessages = 0;
                var allMessagesReceived = new ManualResetEvent(false);

                activator.Handle<string>(async message =>
                {
                    await Task.Delay(millisecondsDelay);

                    receivedMessages++;

                    if (receivedMessages == numberOfMessages)
                    {
                        allMessagesReceived.Set();
                    }
                });

                Configure.With(activator)
                    .Logging(l => l.Console(LogLevel.Warn))
                    .Transport(t => t.UseRabbitMq(ConnectionString, QueueName))
                    .Options(o =>
                    {
                        o.SetNumberOfWorkers(0);
                        o.SetMaxParallelism(1);
                        o.SimpleRetryStrategy(maxDeliveryAttempts: 1);
                    })
                    .Start();

                Console.WriteLine($"Sending {numberOfMessages} messages");

                Enumerable.Range(0, numberOfMessages)
                    .Select(i => $"this is message {i}")
                    .ToList()
                    .ForEach(message => activator.Bus.SendLocal(message).Wait());

                Console.WriteLine("Starting receiver");

                activator.Bus.Advanced.Workers.SetNumberOfWorkers(1);

                Console.WriteLine("Waiting a short while");

                Thread.Sleep(5000);

                Console.WriteLine("Stopping RabbitMQ service");

                Execute("net stop rabbitmq");

                Console.WriteLine("Waiting a short while");

                Thread.Sleep(5000);

                Console.WriteLine("Starting RabbitMQ service");

                Execute("net start rabbitmq");

                Console.WriteLine("Waiting for the last messages");

                allMessagesReceived.WaitOrDie(TimeSpan.FromMinutes(5));
            }
        }
Пример #59
0
        public void Run(string inputQueueName)
        {
            var endpointName = string.Format("{0} ({1})", Assembly.GetEntryAssembly().GetName().Name, inputQueueName);

            using (var adapter = new BuiltinHandlerActivator())
            {
                adapter.Handle<string>(async str =>
                {
                    Console.WriteLine("Got message: {0}", str);
                });

                Console.WriteLine("Starting {0} bus", endpointName);

                Configure.With(adapter)
                    .Logging(l => l.ColoredConsole(minLevel: LogLevel.Warn))
                    .Transport(t => t.UseMsmq(inputQueueName))
                    .Subscriptions(s => s.StoreInSqlServer("server=.; database=messagebus; trusted_connection=true", "subscriptions", isCentralized: true))
                    .Start();

                Console.WriteLine(@"-------------------------------
A) Subscribe to System.String
B) Unsubscribe to System.String
C) Publish System.String
Q) Quit
-------------------------------
");

                var keepRunning = true;

                while (keepRunning)
                {
                    var key = Console.ReadKey(true);

                    switch (char.ToLower(key.KeyChar)) 
                    {
                        case 'a':
                            Console.WriteLine("Subscribing!");
                            adapter.Bus.Subscribe<string>().Wait();
                            break;

                        case 'b':
                            Console.WriteLine("Unsubscribing!");
                            adapter.Bus.Unsubscribe<string>().Wait();
                            break;

                        case 'c':
                            Console.WriteLine("Publishing!");
                            adapter.Bus.Publish(string.Format("Greetings to subscribers from {0}", endpointName)).Wait();
                            break;

                        case 'q':
                            Console.WriteLine("Quitting!");
                            keepRunning = false;
                            break;
                    }
                }

                Console.WriteLine("Stopping the bus....");
            }

        }
        public async void ShouldBeAbleToRecieveEvenWhenNotCreatingQueue(AzureServiceBusMode mode)
        {
            var consoleLoggerFactory = new ConsoleLoggerFactory(false);
            var transport = new AzureServiceBusTransport(StandardAzureServiceBusTransportFactory.ConnectionString, QueueName, consoleLoggerFactory, new TplAsyncTaskFactory(consoleLoggerFactory), new BusLifetimeEvents());
            transport.PurgeInputQueue();
            //Create the queue for the receiver since it cannot create it self beacuse of lacking rights on the namespace
            transport.CreateQueue(QueueName);

            var recieverActivator = new BuiltinHandlerActivator();
            var senderActivator = new BuiltinHandlerActivator();

            var receiverBus = Configure.With(recieverActivator)
                .Logging(l => l.ColoredConsole())
                .Transport(t =>
                    t.UseAzureServiceBus(StandardAzureServiceBusTransportFactory.ConnectionString, QueueName)
                        .DoNotCreateQueues())
                .Start();

            var senderBus = Configure.With(senderActivator)
                .Transport(t => t.UseAzureServiceBus(StandardAzureServiceBusTransportFactory.ConnectionString, "sender", mode))
                .Start();

            Using(receiverBus);
            Using(senderBus);

            var gotMessage = new ManualResetEvent(false);

            recieverActivator.Handle<string>(async (bus, context, message) =>
            {
                gotMessage.Set();
                Console.WriteLine("got message in readonly mode");
            });
            await senderBus.Advanced.Routing.Send(QueueName, "message to receiver");

            gotMessage.WaitOrDie(TimeSpan.FromSeconds(10));


        }