Beispiel #1
0
        static void Main(string[] args)
        {
            //add event subscriptions
            EventSubscriptions.Add<EmailOrderConfirmation>();
            EventSubscriptions.Add<NotifyWarehouse>();
            EventSubscriptions.Add<DeductOnHandInventory>();

            //publish
            IEventPublisher eventPublisher = new EventPublisher(new EventSubscriptions());
            eventPublisher.PublishAsync<OrderSubmittedEvent>(new OrderSubmittedEvent { OrderId = Guid.NewGuid().ToString() });
            eventPublisher.PublishAsync<OrderSubmittedEvent>(new OrderSubmittedEvent { OrderId = Guid.NewGuid().ToString() });

            //Console.ReadKey();
        }
Beispiel #2
0
        public void PublishAsyncWithRawDataCallsSendMessageWithExpectedMessage(long timestamp, string topic, string eventType, string body)
        {
            // Arrange
            Mock <IBusContext <IConnection> > contextMock = new Mock <IBusContext <IConnection> >();
            Mock <IMessageSender>             senderMock  = new Mock <IMessageSender>();

            contextMock.Setup(e => e.CreateMessageSender())
            .Returns(senderMock.Object);

            EventMessage result = new EventMessage();

            senderMock.Setup(e => e.SendMessage(It.IsAny <EventMessage>()))
            .Callback <EventMessage>(e => result = e);

            EventPublisher publisher = new EventPublisher(contextMock.Object);

            Guid calculatedGuid = Guid.NewGuid();

            // Act
            publisher.PublishAsync(timestamp, topic, calculatedGuid, eventType, body);

            Thread.Sleep(AsyncWaitTime);

            // Assert
            Assert.AreEqual(timestamp, result.Timestamp);
            Assert.AreEqual(topic, result.Topic);
            Assert.AreEqual(eventType, result.EventType);
            Assert.AreEqual(body, Encoding.Unicode.GetString(result.Body));
            Assert.AreEqual(calculatedGuid, result.CorrelationId);
        }
Beispiel #3
0
            public Task Should_Throw_If_Cancellation_Token_Source_Is_Cancelled()
            {
                return(Assert.ThrowsAnyAsync <OperationCanceledException>(async() =>
                {
                    var asyncHandler1 = new TestEventAsyncHandler1(_testOutputHelper);

                    var registration = new EventHandlerRegistration();
                    registration.Register <TriggerLongRunningEvent>(() => asyncHandler1);

                    var publisher = new EventPublisher(registration);

                    publisher.OnError += (@event, ex) =>
                    {
                        _testOutputHelper.WriteLine(ex.Message);
                    };

                    var cts = new CancellationTokenSource();

                    Task publishTask = publisher.PublishAsync(new TriggerLongRunningEvent(1000), cts.Token);

                    cts.Cancel();

                    try
                    {
                        await publishTask;
                    }
                    catch (Exception ex)
                    {
                        _testOutputHelper.WriteLine(ex.Message);
                        throw;
                    }
                }));
            }
Beispiel #4
0
        public async Task Events_should_be_published_on_correct_order()
        {
            var ids = new List <Tuple <Guid, int> >();

            var handler1 = new OrderTestEventHandler(ids);

            var handlers = new List <Action <OrderedTestEvent> >
            {
                evt => handler1.ExecuteAsync(evt)
            };

            var eventRouter = CreateEventRouter(handlers);

            EventPublisher eventPublisher = new EventPublisher(eventRouter);

            var orderTestEvent  = new OrderedTestEvent(Guid.NewGuid(), 1);
            var orderTestEvent2 = new OrderedTestEvent(Guid.NewGuid(), 2);
            var orderTestEvent3 = new OrderedTestEvent(Guid.NewGuid(), 3);

            await eventPublisher.PublishAsync <IDomainEvent>(new[]
            {
                orderTestEvent,
                orderTestEvent2,
                orderTestEvent3
            }).ConfigureAwait(false);

            await eventPublisher.CommitAsync().ConfigureAwait(false);

            ids[0].Item2.Should().Be(orderTestEvent.Order);

            ids[1].Item2.Should().Be(orderTestEvent2.Order);

            ids[2].Item2.Should().Be(orderTestEvent3.Order);
        }
Beispiel #5
0
            public async Task Should_Invoke_All_Registered_Event_Handlers_In_Registration()
            {
                var asyncHandler1 = new TestEventAsyncHandler1(_testOutputHelper);
                var asyncHandler2 = new TestEventAsyncHandler2(_testOutputHelper);
                var asyncHandler3 = new TestEventAsyncHandler3(_testOutputHelper);
                var handler1      = new TestEventHandler1(_testOutputHelper);
                var handler2      = new TestEventHandler2(_testOutputHelper);
                var handler3      = new TestEventHandler3(_testOutputHelper);

                var registration = new EventHandlerRegistration();

                registration.Register <TestEvent1>(() => handler1);
                registration.Register <TestEvent1>(() => handler2);
                registration.Register <TestEvent1>(() => handler3);
                registration.Register <TestEvent1>(() => asyncHandler1);
                registration.Register <TestEvent1>(() => asyncHandler2);
                registration.Register <TestEvent1>(() => asyncHandler3);

                var publisher = new EventPublisher(registration);

                publisher.OnError += (@event, ex) =>
                {
                    _testOutputHelper.WriteLine(ex.Message);
                };

                await publisher.PublishAsync(new TestEvent1());

                // Event may not have yet been handled in background.
                await Task.Delay(500);

                // AsyncHandler1 should have 1 event.
                // 1. TestEvent1
                Assert.Equal(1, asyncHandler1.HandledEvents.Count);
                Assert.Contains(asyncHandler1.HandledEvents, (e) => e is TestEvent1);

                // AsyncHandler2 should have 1 event.
                // 1. TestEvent1
                Assert.Equal(1, asyncHandler2.HandledEvents.Count);
                Assert.Contains(asyncHandler2.HandledEvents, (e) => e is TestEvent1);

                // AsyncHandler3 should have 1 event.
                // 1. TestEvent1
                Assert.Equal(1, asyncHandler3.HandledEvents.Count);
                Assert.Contains(asyncHandler3.HandledEvents, (e) => e is TestEvent1);

                // Handler1 should have 1 event.
                // 1. TestEvent1
                Assert.Equal(1, handler1.HandledEvents.Count);
                Assert.Contains(handler1.HandledEvents, (e) => e is TestEvent1);

                // Handler2 should have 1 event.
                // 1. TestEvent1
                Assert.Equal(1, handler2.HandledEvents.Count);
                Assert.Contains(handler2.HandledEvents, (e) => e is TestEvent1);

                // Handler3 should have 1 event.
                // 1. TestEvent1
                Assert.Equal(1, handler3.HandledEvents.Count);
                Assert.Contains(handler3.HandledEvents, (e) => e is TestEvent1);
            }
        public void EventListenerReceivesMessageAsync(string firstName, string lastName, string email, string phone)
        {
            // Arrange
            using var busContext = new RabbitMqContextBuilder()
                                   .WithExchange("TestExchange")
                                   .WithConnectionString("amqp://*****:*****@localhost")
                                   .CreateContext();

            using var host = new MicroserviceHostBuilder()
                             .WithBusContext(busContext)
                             .AddEventListener <PersonEventListener>()
                             .CreateHost();

            host.Start();

            var publisher = new EventPublisher(busContext);

            var personEvent = new PersonAddedEvent {
                Person = new Person
                {
                    FirstName   = firstName,
                    LastName    = lastName,
                    Email       = email,
                    PhoneNumber = phone
                }
            };

            // Act
            publisher.PublishAsync(personEvent);
            Thread.Sleep(WaitTime);

            // Assert
            Assert.AreEqual(personEvent, PersonEventListener.ResultEvent);
        }
Beispiel #7
0
        public void PublishAsyncCallsSendMessageWithExpectedMessageOnSender(string topic, string body)
        {
            // Arrange
            Mock <IBusContext <IConnection> > contextMock = new Mock <IBusContext <IConnection> >();
            Mock <IMessageSender>             senderMock  = new Mock <IMessageSender>();

            contextMock.Setup(e => e.CreateMessageSender())
            .Returns(senderMock.Object);

            EventMessage result = new EventMessage();

            senderMock.Setup(e => e.SendMessage(It.IsAny <EventMessage>()))
            .Callback <EventMessage>(e => result = e);

            EventPublisher publisher = new EventPublisher(contextMock.Object);

            TestEvent domainEvent = new TestEvent(topic)
            {
                DataField = body
            };
            string jsonBody = JsonConvert.SerializeObject(domainEvent);

            // Act
            publisher.PublishAsync(domainEvent);

            Thread.Sleep(AsyncWaitTime);

            // Assert
            Assert.AreEqual(topic, result.Topic);
            Assert.AreEqual(jsonBody, Encoding.Unicode.GetString(result.Body));
            Assert.AreEqual(domainEvent.Timestamp, result.Timestamp);
            Assert.AreEqual(domainEvent.Id, result.CorrelationId);
        }
        public async Task PublishAsync_SendsPublishCommandWithGivenEvent(string key, string value)
        {
            var now = DateTime.Now;
            var configurationChangedEvent = new ConfigurationChangedEvent(key, value, now);
            await _publisher.PublishAsync(configurationChangedEvent);

            _fixture.MockConnectionMultiplexer.Verify(x => x.GetSubscriber(It.IsAny <object>()), Times.Once);
            _fixture.MockSubscriber.Verify(x => x.PublishAsync(ConfigurationChangedEvent.EventName, JsonConvert.SerializeObject(configurationChangedEvent), It.IsAny <CommandFlags>()), Times.Once);
        }
Beispiel #9
0
        static void Main(string[] args)
        {
            //add event subscriptions
            EventSubscriptions.Add <EmailOrderConfirmation>();
            EventSubscriptions.Add <NotifyWarehouse>();
            EventSubscriptions.Add <DeductOnHandInventory>();

            //publish
            IEventPublisher eventPublisher = new EventPublisher(new EventSubscriptions());

            eventPublisher.PublishAsync <OrderSubmittedEvent>(new OrderSubmittedEvent {
                OrderId = Guid.NewGuid().ToString()
            });
            eventPublisher.PublishAsync <OrderSubmittedEvent>(new OrderSubmittedEvent {
                OrderId = Guid.NewGuid().ToString()
            });

            //Console.ReadKey();
        }
Beispiel #10
0
        protected override Task PublishModelCollectionLoadedEvent(IReadOnlyCollection <ContactAccountModel> contactAccountModelCollection)
        {
            NullGuard.NotNull(contactAccountModelCollection, nameof(contactAccountModelCollection));

            lock (SyncRoot)
            {
                EventPublisher.PublishAsync(new ContactAccountModelCollectionLoadedEvent(DbContext, contactAccountModelCollection, StatusDate))
                .GetAwaiter()
                .GetResult();
            }

            return(Task.CompletedTask);
        }
Beispiel #11
0
            public async Task Should_Be_Good_If_No_Event_Handler_Is_Registered_In_Container()
            {
                var container            = new Container();
                var adapter              = new SimpleInjectorContainerAdapter(container);
                var eventHandlerResolver = new ContainerEventHandlerResolver(adapter);
                var publisher            = new EventPublisher(eventHandlerResolver);

                publisher.OnError += (@event, ex) =>
                {
                    _testOutputHelper.WriteLine(ex.Message);
                };

                await publisher.PublishAsync(new TestEvent1());
            }
Beispiel #12
0
        public void Send(string address, string subject, string content, ITransactionContext?transactionContext)
        {
            if (subject.IsNullOrEmpty())
            {
                throw ResponseException.ArgError("邮件标题不能为空");
            }

            if (!Mail.LimitCheck(address, subject))
            {
                throw ResponseException.LogicalError("操作过于频繁");
            }

            EventPublisher.PublishAsync(new SendMailEvent()
            {
                Address = address, Subject = subject, Content = content
            }, transactionContext).Wait();
        }
Beispiel #13
0
 public Task Should_Throw_If_Null_Is_Being_Published()
 {
     return(Assert.ThrowsAsync <ArgumentNullException>(async() =>
     {
         var registration = new EventHandlerRegistration();
         var publisher = new EventPublisher(registration);
         try
         {
             await publisher.PublishAsync((IEvent)null);
         }
         catch (Exception ex)
         {
             _testOutputHelper.WriteLine(ex.Message);
             throw;
         }
     }));
 }
Beispiel #14
0
            public async Task Should_Trigger_OnError_If_EventHandlerAttributeRegistration_Produces_Null_Instance()
            {
                var registration = new EventHandlerAttributeRegistration();

                // Produces null.
                registration.Register <TestAttributedEventHandler1>(() => null);

                var publisher = new EventPublisher(registration);

                publisher.OnError += (eventHandler, ex) =>
                {
                    _testOutputHelper.WriteLine(ex.Message);

                    Assert.IsType <InvalidOperationException>(ex);
                };

                await publisher.PublishAsync(new TestEvent1());
            }
Beispiel #15
0
            public async Task Should_Invoke_All_Registered_Event_Handlers_In_Attribute_Registration()
            {
                var attributedHandler1 = new TestAttributedEventHandler1(_testOutputHelper);
                var attributedHandler2 = new TestAttributedEventHandler2(_testOutputHelper);
                var attributedHandler3 = new TestAttributedEventHandler3(_testOutputHelper);

                var registration = new EventHandlerAttributeRegistration();

                registration.Register(() => attributedHandler1);
                registration.Register(() => attributedHandler2);
                registration.Register(() => attributedHandler3);

                var publisher = new EventPublisher(registration);

                publisher.OnError += (eventHandler, ex) =>
                {
                    _testOutputHelper.WriteLine(ex.Message);
                };

                await publisher.PublishAsync(new TestEvent1());

                // Just to make sure that events have been processed.
                await Task.Delay(200);

                // Handler1 should have 2 events.
                // It contains sync and async handlers for:
                // 1. TestEvent
                Assert.Equal(2, attributedHandler1.HandledEvents.Count);
                Assert.Contains(attributedHandler1.HandledEvents, e => e is TestEvent1);

                // Handler2 should have 2 events.
                // It contains sync and async handlers for:
                // 1. TestEvent
                Assert.Equal(2, attributedHandler2.HandledEvents.Count);
                Assert.Contains(attributedHandler2.HandledEvents, e => e is TestEvent1);

                // Handler3 should have 2 events.
                // It contains sync and async handlers for:
                // 1. TestEvent
                Assert.Equal(2, attributedHandler3.HandledEvents.Count);
                Assert.Contains(attributedHandler3.HandledEvents, e => e is TestEvent1);
            }
Beispiel #16
0
        public void PublishAsyncCallsSendMessageOnSender()
        {
            // Arrange
            Mock <IBusContext <IConnection> > contextMock = new Mock <IBusContext <IConnection> >();
            Mock <IMessageSender>             senderMock  = new Mock <IMessageSender>();

            contextMock.Setup(e => e.CreateMessageSender())
            .Returns(senderMock.Object);

            EventPublisher publisher = new EventPublisher(contextMock.Object);

            TestEvent domainEvent = new TestEvent("Topic");

            // Act
            publisher.PublishAsync(domainEvent);

            Thread.Sleep(AsyncWaitTime);

            // Assert
            senderMock.Verify(e => e.SendMessage(It.IsAny <EventMessage>()), Times.Once);
        }
Beispiel #17
0
        public async Task When_a_single_event_is_published_to_the_bus_containing_a_single_EventHandler()
        {
            var testEvent = new TestEvent(Guid.NewGuid());

            var handler = new FirstTestEventHandler();

            var handlers = new List <Action <TestEvent> >
            {
                evt => handler.ExecuteAsync(evt)
            };

            var eventRouter = CreateEventRouter(handlers);

            EventPublisher eventPublisher = new EventPublisher(eventRouter);

            await eventPublisher.PublishAsync <IDomainEvent>(new[] { testEvent }).ConfigureAwait(false);

            await eventPublisher.CommitAsync().ConfigureAwait(false);

            handler.Ids.First().Should().Be(testEvent.AggregateId);
        }
Beispiel #18
0
            public async Task Should_Invoke_All_Registered_Event_Handlers_In_Container()
            {
                var container = new Container();

                container.RegisterCollection(typeof(IEventAsyncHandler <>), typeof(TestEvent1).Assembly);
                container.RegisterCollection(typeof(IEventHandler <>), typeof(TestEvent1).Assembly);
                container.Register(() => _testOutputHelper);

                var adapter = new SimpleInjectorContainerAdapter(container);
                var eventHandlerResolver = new ContainerEventHandlerResolver(adapter);
                var publisher            = new EventPublisher(eventHandlerResolver);

                publisher.OnError += (@event, ex) =>
                {
                    _testOutputHelper.WriteLine(ex.Message);

                    Assert.IsType <TestEventHandlerException>(ex);
                };

                await publisher.PublishAsync(new TestEvent1());
            }
Beispiel #19
0
            public async Task Should_Invoke_All_Registered_Event_Handlers_In_Attribute_Registration_For_Each_Events()
            {
                var attributedHandler1 = new TestAttributedEventHandler1(_testOutputHelper);
                var attributedHandler2 = new TestAttributedEventHandler2(_testOutputHelper);
                var attributedHandler3 = new TestAttributedEventHandler3(_testOutputHelper);

                var registration = new EventHandlerAttributeRegistration();

                registration.Register(() => attributedHandler1);
                registration.Register(() => attributedHandler2);
                registration.Register(() => attributedHandler3);

                var publisher = new EventPublisher(registration);

                publisher.OnError += (@event, ex) =>
                {
                    _testOutputHelper.WriteLine(ex.Message);
                };

                await publisher.PublishAsync(new List <IEvent> {
                    new TestEvent1(), new TestEvent2(), new TestEvent3()
                });
            }
Beispiel #20
0
            public async Task Should_Invoke_All_Registered_Event_Handlers_In_Container_For_Each_Events()
            {
                var container = new Container();

                container.RegisterCollection(typeof(IEventAsyncHandler <>), typeof(TestEvent1).Assembly);
                container.RegisterCollection(typeof(IEventHandler <>), typeof(TestEvent1).Assembly);
                container.Register(() => _testOutputHelper);

                var adapter = new SimpleInjectorContainerAdapter(container);
                var eventHandlerResolver = new ContainerEventHandlerResolver(adapter);
                var publisher            = new EventPublisher(eventHandlerResolver);

                publisher.OnError += (@event, ex) =>
                {
                    _testOutputHelper.WriteLine(ex.Message);
                };

                await publisher.PublishAsync(new List <IEvent> {
                    new TestEvent1(), new TestEvent2(), new TestEvent3()
                });

                // Event may not have yet been handled in background.
                await Task.Delay(500);
            }