Ejemplo n.º 1
1
        public async Task CheckThatEventsAreProperlyRecorded()
        {
            var bus = new FakeBus();

            var commandMessage = new { Text = "hej med dig min ven!!!!" };
            await bus.Send(commandMessage);

            var messageSentEvents = bus.Events.OfType<MessageSent>().ToList();

            Assert.That(messageSentEvents.Count, Is.EqualTo(1));
            Assert.That(messageSentEvents[0].CommandMessage, Is.EqualTo(commandMessage));
        }
Ejemplo n.º 2
0
        public void Debe_actualizar_pedidoEngine_cuando_cancela_pedidoCommand_es_enviado()
        {
            var pedidoEngine = new PedidoYClientesRepository();
            var bus          = new FakeBus();

            CompositionRootHelper.BuildTheWriteModelHexagon(pedidoEngine, pedidoEngine, bus, bus);

            var pizzeriaId    = 1;
            var cantidad      = 1;
            var clienteId     = "*****@*****.**";
            var pedidoCommand = new PedidoCommand(
                clienteId: clienteId,
                pizzaNombre: "Malcriada",
                pizzeriaId: pizzeriaId,
                cantidad: cantidad,
                fechaDeEntrega: Constants.MyFavoriteSaturdayIn2019);

            bus.Send(pedidoCommand);

            Check.That(pedidoEngine.GetPedidoDe(clienteId)).HasSize(1);
            var deliveryGuid = pedidoEngine.GetPedidoDe(clienteId).First().PedidoId;

            var cancelDeliveryCommand = new CancelarPedidoCommand(deliveryGuid, clienteId);

            bus.Send(cancelDeliveryCommand);

            // Pedido is still there, but canceled
            Check.That(pedidoEngine.GetPedidoDe(clienteId)).HasSize(1);
            Check.That(pedidoEngine.GetPedidoDe(clienteId).First().EsCancelado).IsTrue();
        }
Ejemplo n.º 3
0
        public IActionResult Add([FromForm] AddModel add)
        {
            Console.WriteLine(" 输出:  " + add.Name);
            _bus.Send(new CreateInventoryItem(Guid.NewGuid(), add.Name));

            return(RedirectToAction("Index"));
        }
Ejemplo n.º 4
0
        public ActionResult Add(string name)
        {
            var command = new CreateInventoryItem(Guid.NewGuid(), name);

            _bus.Send(command);
            return(RedirectToAction("Index"));
        }
Ejemplo n.º 5
0
        public HttpResponseMessage Post(CreateInventoryItemCommand createInventoryItem)
        {
            if (!createInventoryItem.Id.HasValue)
            {
                createInventoryItem.Id = Guid.NewGuid();
            }

            _bus.Send(new CreateInventoryItem(createInventoryItem.Id.Value, createInventoryItem.Name));
            var response = Request.CreateResponse(HttpStatusCode.Accepted);

            response.Headers.Location = new Uri(
                new Uri(Request.RequestUri.ToString().TrimEnd('/') + "/"),
                createInventoryItem.Id.ToString());
            return(response);
        }
        public IHttpActionResult Post()
        {
            var createMedicalProcedureApprovalRequest = new CreateMedicalProcedureApprovalRequest(Guid.NewGuid(), 1, "1", "Henry", DateTime.UtcNow);

            _bus.Send(createMedicalProcedureApprovalRequest);
            return(this.Ok("Request Created"));
        }
Ejemplo n.º 7
0
        public void TryClaimsInBus()
        {
            var bus     = new FakeBus();
            var command = new ClaimFileCommand("C001", 10, DateTime.Now);

            bus.Send(command);
        }
Ejemplo n.º 8
0
        private static void Main()
        {
            IBus bus = new FakeBus();
            IApplicationLogger applicationLogger = new ConsoleApplicationLogger();

            const int orderId    = 100;
            const int customerId = 200;
            const int paymentId  = 300;

            // Place order
            PlaceOrderV1 placeOrderV1 = new PlaceOrderV1(orderId, customerId);

            placeOrderV1.OrderDetails.OrderItems.Add(new OrderItem(400, "desc", 9.99m, 2));
            applicationLogger.SendMessage(placeOrderV1);
            bus.Send(placeOrderV1);

            // Choose delivery options
            SubmitDeliveryOptionsV1 submitDeliveryOptionsV1 = new SubmitDeliveryOptionsV1(orderId);

            submitDeliveryOptionsV1.DeliveryOptions.DeliveryMethod   = "method";
            submitDeliveryOptionsV1.DeliveryOptions.Address.Line1    = "Line 1";
            submitDeliveryOptionsV1.DeliveryOptions.Address.Line2    = "Line 2";
            submitDeliveryOptionsV1.DeliveryOptions.Address.City     = "City";
            submitDeliveryOptionsV1.DeliveryOptions.Address.PostCode = "A1 1AB";
            applicationLogger.SendMessage(submitDeliveryOptionsV1);
            bus.Send(submitDeliveryOptionsV1);

            // Submit payment info
            SubmitPaymentDetailsV1 submitPaymentDetailsV1 = new SubmitPaymentDetailsV1(orderId);

            submitPaymentDetailsV1.PaymentDetails.Amount     = 9.99m;
            submitPaymentDetailsV1.PaymentDetails.CardNumber = "1234123412341234";
            submitPaymentDetailsV1.PaymentDetails.Ccv        = "111";
            submitPaymentDetailsV1.PaymentDetails.Expiry     = "01/01";
            submitPaymentDetailsV1.PaymentDetails.PaymentId  = paymentId;
            applicationLogger.SendMessage(submitPaymentDetailsV1);
            bus.Send(submitPaymentDetailsV1);

            // Confirm order
            ConfirmOrderV1 confirmOrderV1 = new ConfirmOrderV1(orderId, customerId);

            applicationLogger.SendMessage(confirmOrderV1);
            bus.Send(confirmOrderV1);

            Console.ReadLine();
        }
Ejemplo n.º 9
0
        public void CanClearEventsFromFakeBus()
        {
            var bus = new FakeBus();
            var commandMessage = new { Text = "hej med dig min ven!!!!" };
            bus.Send(commandMessage).Wait();

            bus.Clear();

            Assert.That(bus.Events.Count(), Is.EqualTo(0));
        }
Ejemplo n.º 10
0
    public void CanInvokeCallback()
    {
        var fakeBus   = new FakeBus();
        var callbacks = new List <string>();

        fakeBus.On <MessageSent>(e => callbacks.Add($"message sent: {e.CommandMessage}"));

        fakeBus.Send("whatever").Wait();

        Assert.That(callbacks, Is.EqualTo(new[] { "message sent: whatever" }));
    }
Ejemplo n.º 11
0
    public void CanClearEventsFromFakeBus()
    {
        var bus            = new FakeBus();
        var commandMessage = new { Text = "hej med dig min ven!!!!" };

        bus.Send(commandMessage).Wait();

        bus.Clear();

        Assert.That(bus.Events.Count(), Is.EqualTo(0));
    }
Ejemplo n.º 12
0
        public void CanDoItAll()
        {
            var fakeBus = new FakeBus();

            fakeBus.Send(new MyMessage("send")).Wait();
            fakeBus.SendLocal(new MyMessage("send")).Wait();
            fakeBus.Publish(new MyMessage("send")).Wait();
            fakeBus.Defer(TimeSpan.FromSeconds(10), new MyMessage("send")).Wait();
            fakeBus.Subscribe<MyMessage>().Wait();
            fakeBus.Unsubscribe<MyMessage>().Wait();
        }
Ejemplo n.º 13
0
        public void CanInvokeCallback()
        {
            var fakeBus = new FakeBus();
            var callbacks = new List<string>();

            fakeBus.On<MessageSent>(e => callbacks.Add($"message sent: {e.CommandMessage}"));

            fakeBus.Send("whatever").Wait();

            Assert.That(callbacks, Is.EqualTo(new[] {"message sent: whatever"}));
        }
Ejemplo n.º 14
0
    public void CanDoItAll()
    {
        var fakeBus = new FakeBus();

        fakeBus.Send(new MyMessage("send")).Wait();
        fakeBus.SendLocal(new MyMessage("send")).Wait();
        fakeBus.Publish(new MyMessage("send")).Wait();
        fakeBus.Defer(TimeSpan.FromSeconds(10), new MyMessage("send")).Wait();
        fakeBus.Subscribe <MyMessage>().Wait();
        fakeBus.Unsubscribe <MyMessage>().Wait();
    }
Ejemplo n.º 15
0
    public void CodeSampleForComment()
    {
        var fakeBus = new FakeBus();

        fakeBus.Send(new MyMessage("woohoo!")).Wait();

        var sentMessagesWithMyGreeting = fakeBus.Events
                                         .OfType <MessageSent <MyMessage> >()
                                         .Count(m => m.CommandMessage.Text == "woohoo!");

        Assert.That(sentMessagesWithMyGreeting, Is.EqualTo(1));
    }
Ejemplo n.º 16
0
    public async Task CheckThatEventsAreProperlyRecorded()
    {
        var bus = new FakeBus();

        var commandMessage = new { Text = "hej med dig min ven!!!!" };
        await bus.Send(commandMessage);

        var messageSentEvents = bus.Events.OfType <MessageSent>().ToList();

        Assert.That(messageSentEvents.Count, Is.EqualTo(1));
        Assert.That(messageSentEvents[0].CommandMessage, Is.EqualTo(commandMessage));
    }
Ejemplo n.º 17
0
        public void CodeSampleForComment()
        {
            var fakeBus = new FakeBus();

            fakeBus.Send(new MyMessage("woohoo!")).Wait();

            var sentMessagesWithMyGreeting = fakeBus.Events
                .OfType<MessageSent<MyMessage>>()
                .Count(m => m.CommandMessage.Text == "woohoo!");

            Assert.That(sentMessagesWithMyGreeting, Is.EqualTo(1));
        }
Ejemplo n.º 18
0
        public void DebeActualizar_readmodel_usuario_reservacion_cuando_CancelarPedidoCommand_is_enviadot()
        {
            var pedidoEngine = new PedidoYClientesRepository();
            var bus          = new FakeBus(synchronousPublication: true);

            CompositionRootHelper.BuildTheWriteModelHexagon(pedidoEngine, pedidoEngine, bus, bus);

            var pizzeriasYPizzasAdapter = new PizzeriasYPizzasAdapter(Constants.RelativePathForPizzaIntegrationFiles, bus);

            pizzeriasYPizzasAdapter.LoadAllPizzaFiles();
            var reservationAdapter = new ReservaAdapter(bus);

            CompositionRootHelper.BuildTheReadModelHexagon(pizzeriasYPizzasAdapter, pizzeriasYPizzasAdapter, reservationAdapter, bus);

            var clienteId = "*****@*****.**";

            Check.That(reservationAdapter.GetReservacionesDe(clienteId)).IsEmpty();

            var pizzeriaId    = 2;
            var cantidad      = 2;
            var pedidoCommand = new PedidoCommand(clienteId: clienteId, pizzeriaId: pizzeriaId, pizzaNombre: "Peperoni", cantidad: 2, fechaDeEntrega: Constants.MyFavoriteSaturdayIn2019);

            bus.Send(pedidoCommand);

            var pedidoGuid = pedidoEngine.GetPedidoDe(clienteId).First().PedidoId;

            Check.That(reservationAdapter.GetReservacionesDe(clienteId)).HasSize(1);

            var reservation = reservationAdapter.GetReservacionesDe(clienteId).First();

            Check.That(reservation.Cantidad).IsEqualTo(cantidad);
            Check.That(reservation.PizzeriaId).IsEqualTo(pizzeriaId);

            var cancelCommand = new CancelarPedidoCommand(pedidoGuid, clienteId);

            bus.Send(cancelCommand);

            Check.That(reservationAdapter.GetReservacionesDe(pedidoGuid, clienteId)).HasSize(0);
        }
Ejemplo n.º 19
0
        public void Should_impact_booking_repository_when_sending_a_booking_command()
        {
            var bus = new FakeBus(synchronousPublication: true);
            var bookingRepository = new Mock <ISaveBooking>();
            var clientRepository  = new Mock <IHandleClients>();

            CompositionRootHelper.BuildTheWriteModelHexagon(bookingRepository.Object, clientRepository.Object, bus, bus);

            bookingRepository.Verify(x => x.Save(It.IsAny <Booking>()), Times.Never);

            var bookingCommand = new BookingCommand(clientId: "*****@*****.**", hotelName: "Super Hotel", hotelId: 1, roomNumber: "2", checkInDate: DateTime.Parse("2016-09-17"), checkOutDate: DateTime.Parse("2016-09-18"));

            bus.Send(bookingCommand);

            bookingRepository.Verify(x => x.Save(It.Is <Booking>(y => y.ClientId == "*****@*****.**")), Times.Once);
        }
Ejemplo n.º 20
0
        public void Debe_actualizar_buscar_pizza_cuando_cancelaPedidoCommand_es_enviado()
        {
            // Initialize Read-model side
            var bus = new FakeBus(synchronousPublication: true);
            var pizzeriasAdapter = new PizzeriasYPizzasAdapter(Constants.RelativePathForPizzaIntegrationFiles, bus);
            var pedidoAdapter    = new ReservaAdapter(bus);

            pizzeriasAdapter.LoadPizzaFile("Malcriada-availabilities.json");

            // Initialize Write-model side
            var bookingRepository = new PedidoYClientesRepository();

            CompositionRootHelper.BuildTheWriteModelHexagon(bookingRepository, bookingRepository, bus, bus);

            var readFacade = CompositionRootHelper.BuildTheReadModelHexagon(pizzeriasAdapter, pizzeriasAdapter, pedidoAdapter, bus);

            // Search Pizzas availabilities
            var fechaEntrega = Constants.MyFavoriteSaturdayIn2019;

            var searchQuery    = new BuscarPedidoOpciones(fechaEntrega, direccion: "Cercado", nombrePizza: "peperoni", cantidad: 2);
            var pedidoOpciones = readFacade.BuscarPedidoOpciones(searchQuery);

            // We should get 1 pedido option with 13 available pizzas in it.
            Check.That(pedidoOpciones).HasSize(1);

            var pedidoOpcion        = pedidoOpciones.First();
            var initialPizzaNumbers = 13;

            Check.That(pedidoOpcion.DisponiblesPizzasConPrecios).HasSize(initialPizzaNumbers);

            // Now, let's request that pizza!
            var firstPizzaOfThisPedidoOption = pedidoOpcion.DisponiblesPizzasConPrecios.First();
            var clientId      = "*****@*****.**";
            var pedidoCommand = new PedidoCommand(clienteId: clientId, pizzeriaId: pedidoOpcion.Pizzeria.Identificador, pizzaNombre: "MalcriadaC", cantidad: firstPizzaOfThisPedidoOption.Cantidad, fechaDeEntrega: fechaEntrega);

            // We send the PedirPizza command
            bus.Send(pedidoCommand);

            // We check that both the PedidoRepository (Write model) and the available pizzas (Read model) have been updated.
            Check.That(bookingRepository.GetPedidoDe(clientId).Count()).IsEqualTo(1);
            var pedidoId = bookingRepository.GetPedidoDe(clientId).First().PedidoId;

            // Fetch pizzas availabilities now. One pizza should have disappeared from the search result
            pedidoOpciones = readFacade.BuscarPedidoOpciones(searchQuery);
            Check.That(pedidoOpciones).HasSize(1);
            Check.That(pedidoOpcion.DisponiblesPizzasConPrecios).As("available matching pizzas").HasSize(initialPizzaNumbers - 1);
        }
Ejemplo n.º 21
0
        public void Should_impact_both_write_and_read_models_when_sending_a_booking_command()
        {
            // Initialize Read-model side
            var bus                 = new FakeBus(synchronousPublication: true);
            var hotelsAdapter       = new HotelsAndRoomsAdapter(Constants.RelativePathForHotelIntegrationFiles, bus);
            var reservationsAdapter = new ReservationAdapter(bus);

            hotelsAdapter.LoadHotelFile("New York Sofitel-availabilities.json");

            var readFacade = CompositionRootHelper.BuildTheReadModelHexagon(hotelsAdapter, hotelsAdapter, reservationsAdapter, bus);

            // Search Rooms availabilities
            var checkInDate  = Constants.MyFavoriteSaturdayIn2017;
            var checkOutDate = checkInDate.AddDays(1);

            var searchQuery    = new SearchBookingOptions(checkInDate, checkOutDate, location: "New York", numberOfAdults: 2);
            var bookingOptions = readFacade.SearchBookingOptions(searchQuery);

            // We should get 1 booking option with 13 available rooms in it.
            Check.That(bookingOptions).HasSize(1);

            var bookingOption       = bookingOptions.First();
            var initialRoomsNumbers = 13;

            Check.That(bookingOption.AvailableRoomsWithPrices).HasSize(initialRoomsNumbers);

            // Now, let's book that room!
            var firstRoomOfThisBookingOption = bookingOption.AvailableRoomsWithPrices.First();
            var bookingCommand = new BookingCommand(clientId: "*****@*****.**", hotelName: "New York Sofitel", hotelId: bookingOption.Hotel.Identifier, roomNumber: firstRoomOfThisBookingOption.RoomIdentifier, checkInDate: checkInDate, checkOutDate: checkOutDate);

            // Initialize Write-model side
            var bookingRepository = new BookingAndClientsRepository();

            CompositionRootHelper.BuildTheWriteModelHexagon(bookingRepository, bookingRepository, bus, bus);

            // We send the BookARoom command
            bus.Send(bookingCommand);

            // We check that both the BookingRepository (Write model) and the available rooms (Read model) have been updated.
            Check.That(bookingRepository.GetBookingsFrom("*****@*****.**").Count()).IsEqualTo(1);

            // Fetch rooms availabilities now. One room should have disappeared from the search result
            bookingOptions = readFacade.SearchBookingOptions(searchQuery);
            Check.That(bookingOptions).HasSize(1);
            Check.That(bookingOption.AvailableRoomsWithPrices).As("available matching rooms").HasSize(initialRoomsNumbers - 1);
        }
Ejemplo n.º 22
0
        public void TestUnitOfWorkWithCommit()
        {
            var bus     = new FakeBus();
            var events  = new ClaimsEventHandler(bus);
            var storage = new EventStore(bus);

            var eventStoreRepository = new Repository <Claim>(storage, @"c:\shibutemp\eventstore.txt");
            var emailProvider        = new TextEmailProvider(@"c:\shibutemp\emaillog.txt");

            var connectionString = @"Data Source=(localdb)\MSSQLLocalDB;Initial Catalog=MyTest;Integrated Security=True;Connect Timeout=30;Encrypt=False;TrustServerCertificate=False;ApplicationIntent=ReadWrite;MultiSubnetFailover=False";

            using (var connection = new System.Data.SqlClient.SqlConnection(connectionString))
            {
                connection.Open();
                var unitOfWork = new UnitOfWork(connection).WithTransaction();
                //var unitOfWork = new UnitOfWork(connection);

                var queryService   = new MyCqrs.Persistent.ClaimsQueryService(unitOfWork);
                var commandService = new MyCqrs.Persistent.ClaimsCommandService(unitOfWork);

                var commands = new ClaimsCommandHandler(bus, queryService, commandService, eventStoreRepository, emailProvider);
                RegisterCommandHandles(bus, commands);
                RegisterEventHandles(bus, events);


                var claimNo = "C009";
                var command = new ClaimFileCommand(claimNo, 10, DateTime.Now);
                // bus.Send(command);

                var claimRejectedCommand = new ClaimRejectedCommand(claimNo, "r_user1", DateTime.Now);
                bus.Send(claimRejectedCommand);

                //var claimApprovedCommand = new ClaimApprovedCommand(claimNo, "a_user1", DateTime.Now);
                //bus.Send(claimApprovedCommand);

                unitOfWork.Commit();
                //unitOfWork.Rollback();
            }

            var eventDatas = TextEventStoreProvider.GetEventData("4eba9d9f-d64b-4d98-9fa6-2bced2695143");



            Assert.Pass();
        }
Ejemplo n.º 23
0
        public void BookRoom_WithEmptyStore_ShouldBeSuccessful()
        {
            var store = new InMemoryStore();

            Assert.Empty(store.AllBookings());

            var bus     = new FakeBus();
            var handler = new BookingHandler(new BookingService(store, bus));

            bus.Subscribe <BookRoom>(handler.Handle);

            bus.Send(new BookRoom("Room1", DateTime.Now, DateTime.Now.AddDays(2)));

            var bookings = store.AllBookings();

            Assert.NotEmpty(bookings);
            Assert.Single(bookings);
            Assert.Equal("Room1", bookings.Single().RoomName);
        }
Ejemplo n.º 24
0
        public void Should_retrieve_updated_list_of_reservations()
        {
            var bus     = new FakeBus();
            var adapter = new HotelsAndRoomsAdapter(Constants.RelativePathForHotelIntegrationFiles, bus);

            adapter.LoadHotelFile("New York Sofitel-availabilities.json");
            var reservationAdapter = new ReservationAdapter(bus);
            var readFacade         = CompositionRootHelper.BuildTheReadModelHexagon(adapter, adapter, reservationAdapter, bus);

            var clientId = "*****@*****.**";
            IEnumerable <Reservation> reservations = readFacade.GetReservationsFor(clientId);

            Check.That(reservations).IsEmpty();

            var bookingAndClientsRepository = new BookingAndClientsRepository();

            CompositionRootHelper.BuildTheWriteModelHexagon(bookingAndClientsRepository, bookingAndClientsRepository, bus, bus);

            var hotelId      = 1;
            var hotelName    = "New York Sofitel";
            var roomNumber   = "101";
            var checkInDate  = Constants.MyFavoriteSaturdayIn2017;
            var checkOutDate = checkInDate.AddDays(1);

            bus.Send(new BookingCommand(clientId, hotelName, hotelId, roomNumber, checkInDate, checkOutDate));

            reservations = readFacade.GetReservationsFor(clientId);
            Check.That(reservations).HasSize(1);
            var reservation = reservations.First();

            Check.That(reservation.ClientId).IsEqualTo(clientId);
            Check.That(reservation.HotelId).IsEqualTo(hotelId.ToString()); // TODO: make the hotelId a string and not an int.
            Check.That(reservation.RoomNumber).IsEqualTo(roomNumber);
            Check.That(reservation.CheckInDate).IsEqualTo(checkInDate);
            Check.That(reservation.CheckOutDate).IsEqualTo(checkOutDate);
        }
Ejemplo n.º 25
0
        public ActionResult Add(string name)
        {
            _bus.Send(new InventoryItemCreateCommand(Guid.NewGuid(), name));

            return(RedirectToAction("Index"));
        }
Ejemplo n.º 26
0
        public IActionResult Create(string name)
        {
            _bus.Send(new CreateInventoryItem(Guid.NewGuid(), name));

            return(RedirectToAction("Index"));
        }
Ejemplo n.º 27
0
 public ActionResult Add(string name)
 {
     _bus.Send(new CreateInventoryItem(Guid.NewGuid(), name));
     return(View());
 }