public static async Task ScrapeAuditLog(IBusContext <IConnection> mainContext, ServiceCollection collection,
                                                DateTime startTime)
        {
            var exchangeName      = "Audit_Bestelling " + Guid.NewGuid();
            var connectionBuilder = new RabbitMQContextBuilder()
                                    .ReadFromEnvironmentVariables().WithExchange(exchangeName);

            var builder = new MicroserviceHostBuilder();

            builder
            .RegisterDependencies(collection)
            .WithContext(connectionBuilder.CreateContext())
            .ExitAfterIdleTime(new TimeSpan(0, 0, 2, 0))
            .UseConventions();

            builder.CreateHost().StartListeningInOtherThread();

            var publisher = new CommandPublisher(mainContext);

            var replayEventsCommand = new ReplayEventsCommand
            {
                ToTimestamp  = startTime.Ticks,
                ExchangeName = exchangeName
            };

            var result = await publisher.Publish <bool>(replayEventsCommand, "AuditlogReplayService",
                                                        "Minor.WSA.AuditLog.Commands.ReplayEventsCommand");
        }
Example #2
0
    // Update is called once per frame in Unity
    void Update()
    {
        if (!started && Input.GetButtonDown("Start"))
        {
            ConnectionStatus.text = "Connected";
            started = true;
            ros     = new ROSBridgeWebSocketConnection("ws://localhost", 8080);

            ros.AddPublisher(typeof(CommandPublisher));
            ros.AddPublisher(typeof(VelocityPublisher));

            // Fire up the subscriber(s) and publisher(s)
            ros.Connect();
        }

        ControlCommand command_msg = GetControlCommand();

        Debug.Log("Sending: " + command_msg.ToYAMLString());
        ControlVelocity velocity_msg = new ControlVelocity(GetPitch(), GetRoll(), GetThrottle(), GetYaw());

        Debug.Log("Sending: " + velocity_msg.ToYAMLString());

        // Publish it (ros is the object defined in the first class)
        ros.Publish(CommandPublisher.GetMessageTopic(), command_msg);
        ros.Publish(VelocityPublisher.GetMessageTopic(), velocity_msg);

        ros.Render();
    }
        public void PublishAsyncCallsPublishAsyncOnSender(string destQueue, string body)
        {
            // Arrange
            var contextMock = new Mock <IBusContext <IConnection> >();
            var senderMock  = new Mock <ICommandSender>();

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

            CommandMessage message = new CommandMessage();

            senderMock.Setup(e => e.SendCommandAsync(It.IsAny <CommandMessage>()))
            .Callback <CommandMessage>(e => message = e);

            var sender = new CommandPublisher(contextMock.Object);

            var command = new TestCommand(destQueue);

            var jsonBody = JsonConvert.SerializeObject(command);

            // Act
            sender.PublishAsync <TestCommand>(command);

            // Assert
            Assert.AreEqual(destQueue, message.DestinationQueue);
            Assert.AreEqual(command.Id, message.CorrelationId);
            Assert.AreEqual(command.Timestamp, message.Timestamp);
            Assert.AreEqual(jsonBody, Encoding.Unicode.GetString(message.Body));
        }
        public async Task CommandPublisherPublishUnknownExceptionThrowsInvalidCastException()
        {
            var sender          = new Mock <ICommandSender>(MockBehavior.Strict);
            var responseCommand = new TestCommand()
            {
                Message = "message2"
            };

            sender.Setup(m => m.SendCommandAsync(It.IsAny <CommandRequestMessage>(), "queue")).Returns(
                Task.FromResult(new CommandResponseMessage("error", "RandomException", null)));

            var iBusContextMock = new Mock <IBusContext <IConnection> >(MockBehavior.Strict);

            iBusContextMock.Setup(m => m.CreateCommandSender()).Returns(sender.Object);

            var target      = new CommandPublisher(iBusContextMock.Object);
            var testCommand = new TestCommand();

            var exception = await Assert.ThrowsExceptionAsync <InvalidCastException>(async() =>
            {
                await target.Publish <TestCommand>(testCommand, "queue");
            });

            Assert.AreEqual("an unknown exception occured (message error), exception type was RandomException", exception.Message);
        }
        public void CommandReturnsProperException(string message)
        {
            // Arrange
            using var busContext = new RabbitMqContextBuilder()
                                   .WithExchange("TestExchange")
                                   .WithConnectionString("amqp://*****:*****@localhost")
                                   .CreateContext();

            using var host = new MicroserviceHostBuilder()
                             .WithBusContext(busContext)
                             .WithQueueName("QueueName2")
                             .AddEventListener <ErrorEventListener>()
                             .CreateHost();

            host.Start();

            var command   = new DummyCommand(message);
            var publisher = new CommandPublisher(busContext);

            // Act
            Task <DummyCommand> Act() => publisher.PublishAsync <DummyCommand>(command);

            // Arrange
            var exception = Assert.ThrowsExceptionAsync <DestinationQueueException>(Act);

            Assert.AreEqual("Received error command from queue Test.Command.Listener", exception.Result.Message);
        }
        public void EmptyBodyThrowsException(string destQueue, string body)
        {
            // Arrange
            var contextMock = new Mock <IBusContext <IConnection> >();
            var senderMock  = new Mock <ICommandSender>();

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

            senderMock.Setup(e => e.SendCommandAsync(It.IsAny <CommandMessage>()))
            .Returns(Task.Run(() => new CommandMessage {
                Body = null
            }));

            var sender = new CommandPublisher(contextMock.Object);

            var command = new TestCommand(destQueue);

            // Act
            async Task <TestCommand> Act() => await sender.PublishAsync <TestCommand>(command);

            // Assert
            DestinationQueueException exception = Assert.ThrowsExceptionAsync <DestinationQueueException>(Act).Result;

            Assert.AreEqual($"ArgumentNullException was thrown, most likely because the destination queue {destQueue} replied with an empty body.", exception.Message);
        }
Example #7
0
        public async Task FinishBestellingLowersVoorraad()
        {
            _magazijnCalled = 0;

            using (var context = new BeheerContext(options))
            {
                var bestelling = new Bestelling
                {
                    KlantId           = "1",
                    AdresRegel1       = "Laagstraat 11",
                    Plaats            = "Laaghoven",
                    Postcode          = "1234FG",
                    BesteldeArtikelen = new List <BestellingItem>
                    {
                        new BestellingItem(1, 3),
                        new BestellingItem(2, 5)
                    }
                };
                var datamapper = new BestellingDatamapper(context);
                await datamapper.Insert(bestelling);
            }


            var commandPublisher = new CommandPublisher(_context);
            var result           = await commandPublisher.Publish <int>(new BestellingAfrondenCommand { Id = 1 },
                                                                        NameConstants.FinishBestellingCommandQueue);

            Thread.Sleep(1000);

            Assert.AreEqual(2, _magazijnCalled);
        }
        public async Task CommandPublisherPublishExceptionTest()
        {
            var sender          = new Mock <ICommandSender>(MockBehavior.Strict);
            var responseCommand = new TestCommand()
            {
                Message = "message2"
            };

            sender.Setup(m => m.SendCommandAsync(It.IsAny <CommandRequestMessage>(), "queue")).Returns(
                Task.FromResult(new CommandResponseMessage("error", typeof(ArgumentException).FullName, null)));

            var iBusContextMock = new Mock <IBusContext <IConnection> >(MockBehavior.Strict);

            iBusContextMock.Setup(m => m.CreateCommandSender()).Returns(sender.Object);

            var target      = new CommandPublisher(iBusContextMock.Object);
            var testCommand = new TestCommand();

            var exception = await Assert.ThrowsExceptionAsync <ArgumentException>(async() =>
            {
                await target.Publish <TestCommand>(testCommand, "queue");
            });

            Assert.AreEqual("error", exception.Message);
        }
            public void PublishCommandsOnSuccessfulSave()
            {
                SagaStore.Setup(mock => mock.CreateSaga(typeof(FakeSaga), SagaId)).Returns(new FakeSaga());

                SagaEventHandler.Handle(EventContext);

                CommandPublisher.Verify(mock => mock.Publish(HeaderCollection.Empty, It.IsAny <CommandEnvelope>()), Times.Once());
            }
Example #10
0
        /// <summary>
        /// Entrypoint
        /// </summary>
        static void Main(string[] args)
        {
            /**
             * Logging is important, so first set up a logger factory
             */
            using var loggerFactory = LoggerFactory.Create(configure =>
            {
                configure.AddConsole().SetMinimumLevel(LogLevel.Information);
            });

            /**
             * Set up a context using environment variables
             */
            using var context = new RabbitMqContextBuilder()
                                .ReadFromEnvironmentVariables()
                                .CreateContext();

            /**
             * Build a host using the loggerfactory, context and register any event listeners in the package.
             */
            using var hostBuilder = new MicroserviceReplayHostBuilder()
                                    .SetLoggerFactory(loggerFactory)
                                    .WithBusContext(context)
                                    .UseConventions();

            /**
             * Now create the host and start it
             */
            using IMicroserviceReplayHost host = (MicroserviceReplayHost)hostBuilder.CreateHost();
            host.Start();

            /**
             * Start spamming events to the auditlogger as a demonstration
             */
            StartSpammingEvents(context);

            /**
             * Now let's start replaying, first create a replay command
             */
            Guid processId = Guid.NewGuid();
            ReplayEventsCommand replayEventsCommand = new ReplayEventsCommand(DateTime.Now.ToFileTimeUtc(), processId)
            {
                Types = new List <string> {
                    "AnimalAddedEvent"
                }
            };

            /**
             * Create the publishers
             */
            ICommandPublisher       publisher = new CommandPublisher(context);
            IReplayCommandPublisher replayCommandPublisher = new ReplayCommandPublisher(host, publisher, loggerFactory);

            /**
             * Commence a replay!
             */
            replayCommandPublisher.Initiate(replayEventsCommand);
        }
Example #11
0
        public static IPublishCommands GetCommandPublisher()
        {
            var commandPublisher = new CommandPublisher();
            var unitOfWork = new EntityFrameworkUnitOfWork(ContextFactory);

            commandPublisher.Subscribe(new ClientService(unitOfWork, Logger));

            return commandPublisher;
        }
Example #12
0
        public static IPublishCommands GetCommandPublisher()
        {
            var commandPublisher = new CommandPublisher();

            commandPublisher.Subscribe(new CommandHandlerProxy<RegisterClient>());
            commandPublisher.Subscribe(new CommandHandlerProxy<UpdateClientAddress>());

            return commandPublisher;
        }
            public void CommandCannotBeNull()
            {
                var messageFactory = new Mock <ICreateMessages>();
                var messageBus     = new Mock <ISendMessages <CommandEnvelope> >();
                var publisher      = new CommandPublisher(messageFactory.Object, messageBus.Object);

                var ex = Assert.Throws <ArgumentNullException>(() => publisher.Publish(GuidStrategy.NewGuid(), null, HeaderCollection.Empty));

                Assert.Equal("command", ex.ParamName);
            }
            public void CommandCannotBeNull()
            {
                var messageFactory = new Mock<ICreateMessages>();
                var messageBus = new Mock<ISendMessages<CommandEnvelope>>();
                var publisher = new CommandPublisher(messageFactory.Object, messageBus.Object);

                var ex = Assert.Throws<ArgumentNullException>(() => publisher.Publish(GuidStrategy.NewGuid(), null, HeaderCollection.Empty));

                Assert.Equal("command", ex.ParamName);
            }
 protected virtual void GenerateCommand()
 {
     if (HelloWorldWasSaid && HelloWorldWasRepliedTo && ConversationWasEnded)
     {
         CommandPublisher.Publish
         (
             new UpdateCompletedConversationReportCommand()
         );
     }
 }
Example #16
0
        public static IPublishCommands GetCommandPublisher()
        {
            var unitOfWork = new EntityFrameworkUnitOfWork(ContextFactory);

            IPublishCommands commandPublisher = new CommandPublisher(unitOfWork, currentUserSession);

            commandPublisher.Subscribe(new ClientService(unitOfWork));

            return(commandPublisher);
        }
Example #17
0
 public ActionResult Orders_Destroy([DataSourceRequest] DataSourceRequest request, [ModelBinder(typeof(NullableGuidBinder))] OrderViewModel order)
 {
     if (ModelState.IsValid)
     {
         // Cast the view model into an delete command, and publish the command, waiting for an OrderDeleted event
         // The Telerik Northwind dashboard website is synchronous not asynchronous.
         var command = (DeleteOrderCommand)order;
         CommandPublisher.PublishAndWait <DeleteOrderCommand, OrderDeleted>(command);
     }
     return(Json(new[] { order }.ToDataSourceResult(request, ModelState)));
 }
            public void CommandsNotPublishedOnFailedSave()
            {
                var saga = new FakeSaga();

                SagaStore.Setup(mock => mock.CreateSaga(typeof(FakeSaga), SagaId)).Returns(saga);
                SagaStore.Setup(mock => mock.Save(saga, It.IsAny <SagaContext>())).Throws(new Exception());

                Assert.Throws <Exception>(() => SagaEventHandler.Handle(EventContext));

                CommandPublisher.Verify(mock => mock.Publish(HeaderCollection.Empty, It.IsAny <CommandEnvelope>()), Times.Never());
            }
Example #19
0
 public void Handle(TestAggregateDidSomethingElse2 message)
 {
     // This could happen out of order in this test
     if (DidSomething)
     {
         CommandPublisher.Publish(new TestAggregateDoSomething3());
         // This is a testing variable
         Responded = true;
     }
     ApplyChange(message);
 }
            public void HeadersCanBeNull()
            {
                var messageFactory = new Mock <ICreateMessages>();
                var messageBus     = new Mock <ISendMessages <CommandEnvelope> >();
                var publisher      = new CommandPublisher(messageFactory.Object, messageBus.Object);
                var payload        = new FakeCommand();

                publisher.Publish(GuidStrategy.NewGuid(), payload, null);

                messageFactory.Verify(mock => mock.Create(null, It.IsAny <CommandEnvelope>()), Times.Once);
                messageBus.Verify(mock => mock.Send(It.IsAny <Message <CommandEnvelope> >()), Times.Once);
            }
            public void HeadersCanBeNull()
            {
                var messageFactory = new Mock<ICreateMessages>();
                var messageBus = new Mock<ISendMessages<CommandEnvelope>>();
                var publisher = new CommandPublisher(messageFactory.Object, messageBus.Object);
                var payload = new FakeCommand();

                publisher.Publish(GuidStrategy.NewGuid(), payload, null);

                messageFactory.Verify(mock => mock.Create(null, It.IsAny<CommandEnvelope>()), Times.Once);
                messageBus.Verify(mock => mock.Send(It.IsAny<Message<CommandEnvelope>>()), Times.Once);
            }
Example #22
0
        static void Main(string[] args)
        {
            ILoggerFactory loggerFactory = new LoggerFactory();

            //Deprecated method, maar kan even niet anders
            ConsoleLoggerOptions options = new ConsoleLoggerOptions();

            loggerFactory.AddProvider(
                new ConsoleLoggerProvider(
                    (text, logLevel) => logLevel >= LogLevel.Debug, true));

            //192.168.99.100
            var connectionBuilder = new RabbitMQContextBuilder()
                                    .WithExchange("MVM.EventExchange")
                                    .WithAddress("localhost", 5672)
                                    .WithCredentials(userName: "******", password: "******");



            var context = new TestBusContext();

            var builder = new MicroserviceHostBuilder()
                          .SetLoggerFactory(loggerFactory)
                          .RegisterDependencies((services) =>
            {
                services.AddTransient <IDataMapper, SinaasAppelDataMapper>();
                services.AddTransient <ICommandPublisher, CommandPublisher>();
                services.AddTransient <IEventPublisher, EventPublisher>();
                services.AddSingleton <IBusContext <IConnection> >(context);
            })
                          .WithContext(context)
                          .UseConventions();


            var host = builder.CreateHost();

            host.StartListeningInOtherThread();

            Console.WriteLine("ServiceHost is listening to incoming events...");
            Console.WriteLine("Press any key to quit.");

            var publisher        = new EventPublisher(context);
            var commandpublisher = new CommandPublisher(context);

            publisher.Publish(new PolisToegevoegdEvent("MVM.Polisbeheer.PolisToegevoegd")
            {
                Message = "Hey"
            });
            publisher.Publish(new HenkToegevoegdEvent("Test")
            {
                Test = "Oi"
            });
        }
Example #23
0
        // Run every 15 minutes in release mode
        public static void Run([TimerTrigger("0 1/15 * * * *")] TimerInfo myTimer, Microsoft.Extensions.Logging.ILogger _logger, ExecutionContext context)
#endif
        {
            if (CommandPublisher == null)
            {
                PreapreOnce(context);
            }

            CorrelationIdHelper.SetCorrelationId(Guid.NewGuid());
            CommandPublisher.Publish(new PublishTimeZonesCommand());
            Console.WriteLine($"Published.");
            Logger.LogInfo($"Published.");
        }
            public void WrapCommandInMessageEnvelope()
            {
                var command        = new FakeCommand() as Command;
                var messageFactory = new Mock <ICreateMessages>();
                var messageBus     = new Mock <ISendMessages <CommandEnvelope> >();
                var publisher      = new CommandPublisher(messageFactory.Object, messageBus.Object);
                var message        = new Message <CommandEnvelope>(GuidStrategy.NewGuid(), HeaderCollection.Empty, new CommandEnvelope(GuidStrategy.NewGuid(), command));

                messageFactory.Setup(mock => mock.Create(HeaderCollection.Empty, It.Is <CommandEnvelope>(envelope => ReferenceEquals(command, envelope.Command)))).Returns(message);

                publisher.Publish(GuidStrategy.NewGuid(), command, HeaderCollection.Empty);

                messageBus.Verify(mock => mock.Send(message), Times.Once());
            }
            public void WrapCommandInMessageEnvelope()
            {
                var command = new FakeCommand() as Command;
                var messageFactory = new Mock<ICreateMessages>();
                var messageBus = new Mock<ISendMessages<CommandEnvelope>>();
                var publisher = new CommandPublisher(messageFactory.Object, messageBus.Object);
                var message = new Message<CommandEnvelope>(GuidStrategy.NewGuid(), HeaderCollection.Empty, new CommandEnvelope(GuidStrategy.NewGuid(), command));

                messageFactory.Setup(mock => mock.Create(HeaderCollection.Empty, It.Is<CommandEnvelope>(envelope => ReferenceEquals(command, envelope.Command)))).Returns(message);

                publisher.Publish(GuidStrategy.NewGuid(), command, HeaderCollection.Empty);

                messageBus.Verify(mock => mock.Send(message), Times.Once());
            }
Example #26
0
        private static async Task Test(IBusContext <IConnection> context, int multiply)
        {
            CommandPublisher commandPublisher = new CommandPublisher(context);
            var testcommand = new TestCommand()
            {
                i = new Random().Next(99, 100) * multiply
            };

            Console.WriteLine($"{multiply} sending");


            var result1 = await commandPublisher.Publish <int>(testcommand, "TestjeAsync");

            Console.WriteLine($"{multiply} result:" + result1);
        }
Example #27
0
 public ActionResult Orders_Create([DataSourceRequest] DataSourceRequest request, [ModelBinder(typeof(NullableGuidBinder))] OrderViewModel order)
 {
     if (ModelState.IsValid)
     {
         // Cast the view model into a create command, and publish the command, waiting for an OrderCreated event
         // The Telerik Northwind dashboard website is synchronous not asynchronous.
         var          command           = (CreateOrderCommand)order;
         OrderCreated orderCreatedEvent = CommandPublisher.PublishAndWait <CreateOrderCommand, OrderCreated>(command);
         // Refresh server defined values from data store.
         OrderViewModel newOrder = GetOrders(orderCreatedEvent.Rsn).Single();
         order.OrderID = newOrder.OrderID;
         order.Rsn     = newOrder.Rsn;
     }
     return(Json(new[] { order }.ToDataSourceResult(request, ModelState)));
 }
Example #28
0
        public async Task WhenDeBestellingIsGeplaatst()
        {
            using (var context = new BeheerContext(options))
            {
                BestellingDatamapper bestellingDatamapper = new BestellingDatamapper(context);
                KlantDatamapper      klantDatamapper      = new KlantDatamapper(context);
                TestBusContext       testBusContext       = new TestBusContext();
                CommandPublisher     commandPublisher     = new CommandPublisher(testBusContext);
                EventPublisher       eventPublisher       = new EventPublisher(testBusContext);

                bestellingListener = new BestellingListener(bestellingDatamapper, klantDatamapper, commandPublisher, eventPublisher);

                id = await bestellingListener.PlaatsBestelling(bestelling);
            }
        }
Example #29
0
        private async static Task Test(IBusContext <IConnection> context)
        {
            CommandPublisher commandPublisher = new CommandPublisher(context);

            ReplayEventsCommand replayEventsCommand = new ReplayEventsCommand()
            {
                ToTimestamp  = DateTime.Now.Ticks,
                ExchangeName = "fddfgf",
            };

            var result = commandPublisher.Publish <bool>(replayEventsCommand, "AuditlogReplayService", "Minor.WSA.AuditLog.Commands.ReplayEventsCommand").Result;


            //Console.WriteLine($"{multiply} result:" + result1);
        }
Example #30
0
        static async Task Main(string[] args)
        {
            Console.Write("Enter RabbitMQ connection string: ");
            var connectionString = Console.ReadLine();

            Console.WriteLine($"Using RabbitMQ connection string: '{connectionString}'");
            Environment.SetEnvironmentVariable("BROKER_CONNECTION_STRING", connectionString);

            Console.WriteLine();

            Console.Write("Enter MSSQL connection string: ");
            connectionString = Console.ReadLine();
            Console.WriteLine($"Using MSSQL connection string: '{connectionString}'");
            Environment.SetEnvironmentVariable("DB_CONNECTION_STRING", connectionString);

            Console.WriteLine();

            using var loggerFactory = LoggerFactory.Create(configure =>
            {
                configure.AddConsole().SetMinimumLevel(LogLevel.Debug);
            });

            MiffyLoggerFactory.LoggerFactory    = loggerFactory;
            RabbitMqLoggerFactory.LoggerFactory = loggerFactory;

            using var context = new RabbitMqContextBuilder()
                                .ReadFromEnvironmentVariables()
                                .CreateContext();

            // using var host = new MicroserviceHostBuilder()
            //     .SetLoggerFactory(loggerFactory)
            //     .WithBusContext(context)
            //     .WithQueueName(QueueName)
            //     .UseConventions()
            //     .CreateHost();

            // host.Start();


            ICommandPublisher commandPublisher = new CommandPublisher(context);
            var klantId = new Guid("979F7437-F7F3-4662-7485-08D80D5821EA");

            // Export();
            await ImportDataIntoSystemFromFile(commandPublisher, klantId, @"C:\Users\Dirk-Jan\Dropbox\S6\prestaties beide.txt");
        }
Example #31
0
        public async Task KeurBestellingGoedChangesBestellingToGereedVoorBehandeling()
        {
            using (var context = new BeheerContext(options))
            {
                var bestelling = new Bestelling
                {
                    Id                = 1,
                    KlantId           = "1",
                    AdresRegel1       = "Laagstraat 11",
                    Plaats            = "Laaghoven",
                    Postcode          = "1234FG",
                    BestellingStatus  = BestellingStatus.TerControleVoorSales,
                    BesteldeArtikelen = new List <BestellingItem>
                    {
                        new BestellingItem(1, 3)
                        {
                            Id = 1
                        },
                        new BestellingItem(2, 5)
                        {
                            Id = 2
                        }
                    }
                };
                var datamapper = new BestellingDatamapper(context);
                await datamapper.Insert(bestelling);
            }

            var commandPublisher = new CommandPublisher(_context);
            await commandPublisher.Publish <int>(new BestellingGoedkeurenCommand { Id = 1 },
                                                 NameConstants.BestellingGoedKeurenCommandQueue);

            Thread.Sleep(1000);

            using (var context = new BeheerContext(options))
            {
                var datamapper = new BestellingDatamapper(context);
                var result     = await datamapper.GetBestelling(1);

                Assert.AreEqual(BestellingStatus.GereedVoorBehandeling, result.BestellingStatus);

                var klantmapper = new KlantDatamapper(context);
                var klant       = await klantmapper.GetKlant("1");
            }
        }
Example #32
0
        public virtual void Publish <TCommand>(TCommand command)
            where TCommand : ICommand <TAuthenticationToken>
        {
            RouteHandlerDelegate commandHandler;

            if (!PrepareAndValidateCommand(command, out commandHandler))
            {
                return;
            }

            // This could be null if Akka won't handle the command and something else will.
            if (commandHandler != null)
            {
                commandHandler.Delegate(command);
            }

            // Let everything else know about the command (usually double handling a command is bad... but sometimes it might be useful... like pushing from AWS to Azure so both systems handle it... although an event really is the proper pattern to use here.
            CommandPublisher.Publish(command);
        }
Example #33
0
        public async Task NieuweBestellingThatGoesAboveKredietLimitGoesToSale()
        {
            var bestelling = new NieuweBestellingCommand
            {
                KlantId           = "1",
                AdresRegel1       = "Laagstraat 11",
                Plaats            = "Laaghoven",
                Postcode          = "1234FG",
                BesteldeArtikelen = new List <BestellingItem>
                {
                    new BestellingItem(1, 3),
                    new BestellingItem(2, 3)
                }
            };


            var commandPublisher = new CommandPublisher(_context);
            await commandPublisher.Publish <bool>(bestelling, NameConstants.NieuweBestellingCommandQueue);

            Thread.Sleep(500);

            using (var context = new BeheerContext(options))
            {
                var datamapper = new BestellingDatamapper(context);
                var result     = await datamapper.GetBestelling(1);

                Assert.AreEqual("Hans", result.Klant.Voornaam);
                Assert.AreEqual("Van Huizen", result.Klant.Achternaam);
                Assert.AreEqual("1", result.KlantId);
                Assert.AreEqual("Laagstraat 11", result.AdresRegel1);
                Assert.AreEqual("Laaghoven", result.Plaats);
                Assert.AreEqual("1234FG", result.Postcode);
                Assert.AreEqual(2, result.BesteldeArtikelen.Count);
                Assert.AreEqual(BestellingStatus.TerControleVoorSales, result.BestellingStatus);
                Assert.IsTrue(result.BesteldeArtikelen.Any(b => b.Artikel.Naam == "Fiets" && b.Aantal == 3));

                var klantMapper = new KlantDatamapper(context);
                var klant       = await klantMapper.GetKlant("1");

                //Krediet should not be added yet
                Assert.AreEqual(508.2m, klant.KredietMetSales);
            }
        }
Example #34
0
        public void TestInitialize()
        {
            _busProviderMock
            .Setup(b => b.BasicConsume(It.IsAny <string>(), It.IsAny <EventReceivedCallback>(), It.IsAny <bool>()))
            .Callback <string, EventReceivedCallback, bool>((que, callback, ack) => _eventReceivedCallback = callback);

            _busProviderMock
            .Setup(b => b.EnsureConnection());

            _busProviderMock
            .Setup(b => b.BasicTopicBind(It.IsAny <string>(), It.IsAny <string>(), ExchangeName));

            _busProviderMock
            .Setup(b => b.BasicPublish(It.Is(CorrectEventMessage), ExchangeName))
            .Callback(BasicPublishCallback)
            .Verifiable();

            _sut = new CommandPublisher(_busProviderMock.Object);
        }
Example #35
0
        public async Task InsertNieuweBestellingUnder500EuroFromEventSetsStatusToGereed()
        {
            var bestelling = new NieuweBestellingCommand
            {
                KlantId           = "1",
                AdresRegel1       = "Laagstraat 11",
                Plaats            = "Laaghoven",
                Postcode          = "1234FG",
                BesteldeArtikelen = new List <BestellingItem>
                {
                    new BestellingItem(1, 1),
                    new BestellingItem(2, 1)
                }
            };


            var commandPublisher = new CommandPublisher(_context);
            await commandPublisher.Publish <bool>(bestelling, NameConstants.NieuweBestellingCommandQueue);

            Thread.Sleep(500);

            using (var context = new BeheerContext(options))
            {
                var datamapper = new BestellingDatamapper(context);
                var result     = await datamapper.GetBestelling(1);

                Assert.AreEqual("Hans", result.Klant.Voornaam);
                Assert.AreEqual("Van Huizen", result.Klant.Achternaam);
                Assert.AreEqual("1", result.KlantId);
                Assert.AreEqual("Laagstraat 11", result.AdresRegel1);
                Assert.AreEqual("Laaghoven", result.Plaats);
                Assert.AreEqual("1234FG", result.Postcode);
                Assert.AreEqual(2, result.BesteldeArtikelen.Count);
                Assert.AreEqual(BestellingStatus.GereedVoorBehandeling, result.BestellingStatus);
                Assert.IsTrue(result.BesteldeArtikelen.Any(b => b.Artikel.Naam == "Fiets" && b.Aantal == 1));

                var klantMapper = new KlantDatamapper(context);
                var klant       = await klantMapper.GetKlant("1");

                Assert.AreEqual(169.4m, klant.KredietMetSales);
            }
        }
Example #36
0
        static void Main(string[] args)
        {
            Console.WriteLine("Sleeping for 3 seconds..");

            IServiceBus serviceBus = ServiceBusFactory.New(cfg =>
            {
                cfg.ReceiveFrom("rabbitmq://localhost/cqrs-poc");
                cfg.UseRabbitMq(cf =>
                {
                    cf.ConfigureHost(new Uri("rabbitmq://localhost/cqrs-poc"), hc =>
                    {
                        hc.SetUsername("petcar");
                        hc.SetPassword("?!Krone2009");
                    });
                });
            });

            CommandPublisher commandPublisher = new CommandPublisher(serviceBus);

            NetworkDeviceService service = new NetworkDeviceService(commandPublisher);

            NetworkDeviceViewBuilder ndvb = new NetworkDeviceViewBuilder();

            serviceBus.SubscribeHandler<HandlerNotification>(service.Handle);

            service.ServiceResultRecieved += (sender, result) =>
                {
                    Console.WriteLine(
                        "CommandId: {0}, Result: {1}, Message: {2}, Exception: {3}",
                        result.CommandId != default(Guid) ? result.CommandId : Guid.Empty,
                    result.Success,
                    result.Message, result.ExceptionMessage);
                };

            Thread.Sleep(4000);
            //var id = Guid.NewGuid();
            //service.CreateDevice(id, "SESM-1");

            Random rnd = new Random();

            for (int i = 0; i < 100; i++)
            {
                var r = rnd.Next(1000, 6000);
                Thread.Sleep(r);
                var devices = ndvb.GetDevices();
                foreach (var device in devices)
                {
                    var online = r % 2 == 0;
                    service.SetDeviceStatus(device.Id, online);
                }

            }

            //Thread.Sleep(3000);
            //service.CreateDevice(id, "SESM-1");

            //for (int i = 0; i < 100; i++)
            //{
            //    Thread.Sleep(500);
            //    var id = Guid.NewGuid();
            //    service.CreateDevice(id, "SESM-" + i.ToString());
            //}

            //foreach (var device in ndvb.GetDevices())
            //{
            //    Console.WriteLine("{0}\t{1}\t{2}", device.Id, device.Hostname, device.Version);
            //}

            //Console.ReadKey();

            //var id = Guid.NewGuid();

            //service.CreateDevice(id, "SESM-1");
            //Thread.Sleep(2000);
            ////service.CreateDevice(id, "SESM-1");

            //foreach (var device in ndvb.GetDevices())
            //{
            //    Console.WriteLine("{0}\t{1}\t{2}", device.Id, device.Hostname, device.Version);
            //}

            ////Thread.Sleep(2000);

            //Random rnd = new Random();

            ////for (int i = 0; i < 2000; i++)
            ////{
            ////    Thread.Sleep(rnd.Next(1,20));
            ////    service.SetDeviceHostname(id, "SESM-" + i.ToString());
            ////}

            //for (int i = 0; i < 100; i++)
            //{
            //    Thread.Sleep(rnd.Next(1, 200));
            //    service.SetDeviceHostname(id, "SESM-" + i.ToString());
            //}

            //foreach (var device in ndvb.GetDevices())
            //{
            //    Console.WriteLine("{0}\t{1}\t{2}", device.Id, device.Hostname, device.Version);
            //}

            ////service.CreateDevice(id, "SESM-1");

            Console.ReadKey();
        }