Ejemplo n.º 1
0
        public void given_a_product_when_persisting_then_successfully_persisted()
        {
            //given
            string name = "test_product_01";

            var client  = new RestClient(this.uri);
            var request = new RestRequest("products", Method.POST);

            AddNewProductCommand command = new AddNewProductCommand {
                Name = name
            };

            request.AddJsonBody(command);

            //when
            IRestResponse response = client.Execute(request);

            //then
            response.StatusCode.Should().Be(HttpStatusCode.OK, response.Content);

            List <Product> item = DBOperation.ReadAllProducts();

            item.Count.Should().Be(1, "item count !!!");
            item[0].Name.Should().Be(name, "product name !!!");
            item[0].Id.Should().Be(1, "product id !!!");
        }
Ejemplo n.º 2
0
        public void given_a_product_when_persisting_to_both_with_exception_at_the_end_then_successfully_rollback()
        {
            //given
            string name = "test_product_01";

            var client  = new RestClient(this.uri);
            var request = new RestRequest("products/bothexception", Method.POST);

            AddNewProductCommand command = new AddNewProductCommand {
                Name = name
            };

            request.AddJsonBody(command);

            //when
            IRestResponse response = client.Execute(request);

            //then
            response.StatusCode.Should().Be(HttpStatusCode.InternalServerError, response.ErrorMessage);


            List <Product>   products    = DBOperation.ReadAllProducts();
            List <Inventory> inventories = DBOperation.ReadAllInventories();

            products.Count.Should().Be(0, "products count !!!");
            inventories.Count.Should().Be(0, "inventories count !!!");
        }
Ejemplo n.º 3
0
        private void AddNewProduct(AddNewProductCommand c)
        {
            var product = new Product
            {
                Id    = c.Id,
                Name  = c.Name,
                Price = c.Price,
                Stock = c.Stock
            };

            try
            {
                _inventory.AddNewProduct(product);
            }
            catch (Exception e)
            {
                var result = CommandResult.Error(e.Message);
                Sender.Tell(result);
                return;
            }

            var ev = new NewProductAddedToInventory(c.Id, c.Name, c.Price, c.Stock);

            PersistEventAndSnapshot(ev);
            Sender.Tell(CommandResult.Success());
        }
Ejemplo n.º 4
0
        public Task <AddNewProductResponse> addNewProduct(AddNewProductRequest request)
        {
            AddNewProductCommand command = new AddNewProductCommand
                                           (
                request.Product.Name,
                request.Product.Note,
                request.Product.Code,
                request.Product.OtherUnitOfProduct,
                request.Product.UnitId,
                request.Product.WeightPerUnit,
                request.Product.Preservation.ID
                                           );
            Task <object> product = (Task <object>)Bus.SendCommand(command);
            //RabbitMQBus.Publish(command);
            AddNewProductResponse response = new AddNewProductResponse();

            response = Common <AddNewProductResponse> .checkHasNotification(_notifications, response);

            if (response.Success)
            {
                ProductModel ProductModel = (ProductModel)product.Result;
                response.Data = ProductModel.Id;
            }
            return(Task.FromResult(response));
        }
        public async Task <IActionResult> Post([FromBody] Product product)
        {
            try {
                //Log Information - Request
                _logger.LogInformation($"Received Request : HTTPPOST api/products");

                //Create command from Input
                AddNewProductCommand addCmd = new AddNewProductCommand {
                    Name         = product.Name,
                    Description  = product.Description,
                    UnitPrice    = product.UnitPrice,
                    UnitsInStock = product.UnitsInStock
                };

                //Send Command
                AddNewProductResult result = await _mediator.Send(addCmd);

                //Return result
                return(CreatedAtRoute("", new { id = result.ProductId }));
            } catch (Exception ex) {
                // Log the failure and return HTTP 500
                _logger.LogError($"Error at HTTPPOST api/products :{ex}");
                return(StatusCode(StatusCodes.Status500InternalServerError));
            }
        }
Ejemplo n.º 6
0
        public void given_a_product_when_persisting_to_both_then_successfully_persisted()
        {
            //given
            string name = "test_product_01";

            var client  = new RestClient(this.uri);
            var request = new RestRequest("products/both", Method.POST);

            AddNewProductCommand command = new AddNewProductCommand()
            {
                Name = name
            };

            request.AddJsonBody(command);

            //when
            IRestResponse response = client.Execute(request);

            //then
            response.StatusCode.Should().Be(HttpStatusCode.OK);

            List <Product>   products    = DBOperation.ReadAllProducts();
            List <Inventory> inventories = DBOperation.ReadAllInventories();

            products.Count.Should().Be(1, "products count !!!");
            products[0].Name.Should().Be(name, "product name !!!");
            products[0].Id.Should().Be(1, "product id !!!");

            inventories.Count.Should().Be(1, "inventories count !!!");
            inventories[0].Name.Should().Be(name, "inventory name !!!");
            inventories[0].Id.Should().Be(1, "inventory id !!!");
        }
Ejemplo n.º 7
0
        public async void Test_AddProductTo_ProductAPI_And_QueryProductPriceFrom_PricingAPI()
        {
            //Arrange
            //Both below servers and clients DO NOT talk to each other directly or via REST.
            //All communication is via EventBus - RabbitMQ over AMQP protocol
            using (var productClient = _servers.ProductCatalogAPIServer.CreateClient())
            {
                using (var priceClient = _servers.PricingAPIServer.CreateClient())
                {
                    //Act
                    var addNewProductCommand = new AddNewProductCommand(10, "Addedproduct", "", "", 100, new decimal(12.25), "");
                    var content = new StringContent(JsonConvert.SerializeObject(addNewProductCommand), Encoding.UTF8, "application/json");

                    //1. Add a new product to product catalog microservice
                    var productResponse = await productClient.PostAsync("api/v1/ProductCatalogue/new", content);

                    //2. Query for price from pricing microservice for added product
                    var priceResponse = await priceClient.GetAsync("api/v1/ProductPrice/" + addNewProductCommand.ProductId.ToString("D"));

                    //Assert
                    Assert.True(productResponse.StatusCode == System.Net.HttpStatusCode.OK);

                    var items = await priceResponse.Content.ReadAsStringAsync();

                    var price = JsonConvert.DeserializeObject <ProductPrice>(items);

                    //ProductId is equal, which shows that after adding to ProductCatalog microservice,
                    //this product is also avaliable within Pricing microservices over integration events via RabbitMQ Event Bus
                    Assert.True(price.ProductId == addNewProductCommand.ProductId);
                    Assert.True((price.Price - addNewProductCommand.UnitPrice) < new decimal(0.0000000000001)); //Prices are equal
                }
            }
        }
Ejemplo n.º 8
0
 //public AddProductViewModel(IDataRepository dataRepository, IDialogCoordinator dialogCoordinator)
 public AddProductViewModel(ProductsViewModel productsViewModel, IDataRepository dataRepository, IDialogCoordinator dialogCoordinator)
 {
     _dataRepository      = dataRepository;
     _dialogCoordinator   = dialogCoordinator;
     _productsViewModel   = productsViewModel;
     AddNewProductCommand = new AddNewProductCommand(this);
 }
        public async Task <IActionResult> AddNewProduct([FromBody] NewProductDTO dto)
        {
            var command = new AddNewProductCommand(dto.Name, dto.Price, dto.Stock);
            var result  = await CartSystem.AddNewProduct(command);

            if (result.IsSuccessful)
            {
                return(Ok());
            }
            return(BadRequest(result.Message));
        }
Ejemplo n.º 10
0
        static void RunCQRS()
        {
            var serviceProvider = BuildServiceProvider();

            try
            {
                var commandDispatcher = new CommandDispatcher(serviceProvider);
                var queryDispatcher   = new QueryDispatcher(serviceProvider);

                //Add new Product
                var product = new AddNewProductCommand {
                    Id = Guid.NewGuid(), Name = "iPhone 11", Description = "Apple iphone 11"
                };
                commandDispatcher.Send(product);

                //Update Product Unit Price
                commandDispatcher.Send(new UpdateProductUnitPriceCommand {
                    Id = product.Id, UnitPrice = 800
                });

                //Update Product Current Stock
                commandDispatcher.Send(new UpdateProductCurrentStockCommand {
                    Id = product.Id, CurrentStock = 500
                });


                //Fine Products By Name
                var productsByName = queryDispatcher.Send(new GetProductsByNameQuery {
                    Name = "iPhone"
                });
                foreach (var item in productsByName)
                {
                    Console.WriteLine(item.ToString());
                }

                //Fine Products By Name
                var outOfStockProducts = queryDispatcher.Send(new FindOutOfStockProductsQuery());
                foreach (var item in outOfStockProducts)
                {
                    Console.WriteLine(item.ToString());
                }

                //Delete Product
                commandDispatcher.Send(new DeleteProductCommand {
                    Id = product.Id
                });
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.Message);
            }
        }
        public async Task<IActionResult> AddNewProductAsync([FromBody]AddNewProductCommand command)
        {
            if(command == null)
            {
                return BadRequest();
            }

            _logger.LogInformation($"Sending command for adding product with name {command.Name}");

            var commandResult = await _mediator.Send(command);

            _logger.LogInformation($"Command handled successfuly for adding product with name {command.Name}");

            return Ok(commandResult);
        }
        public async void Test_API_AddNewProduct()
        {
            //Arrange
            var catalogController = CreateController();
            var newProductCommand = new AddNewProductCommand(10, "Something",
                                                             string.Empty, string.Empty, 10, 100, string.Empty);

            //Act
            var result = await catalogController.AddNewProductAsync(newProductCommand);

            //Assert
            var expectedResult = Assert.IsType <OkObjectResult>(result);

            Assert.True((bool)expectedResult.Value);

            Mock.VerifyAll();
        }
Ejemplo n.º 13
0
        public Task <bool> Handle(AddNewProductCommand message, CancellationToken cancellationToken)
        {
            if (!message.IsValid())
            {
                NotifyValidationErrors(message);
                return(Task.FromResult(false));
            }

            #region Get Category

            Category existingcategory = _categoryRepository.GetById(message.Id);

            if (existingcategory == null)
            {
                Bus.RaiseEvent(new DomainNotification(message.MessageType, "The Category does not exist."));
                return(Task.FromResult(false));
            }

            #endregion Get Category

            #region Add Product to Category

            Product product = new Product(Guid.NewGuid(), message.Name);

            if (existingcategory.Products != null && existingcategory.Products.Any(p => p.Name == product.Name))
            {
                Bus.RaiseEvent(new DomainNotification(message.MessageType, "The Product Name has already been taken."));
                return(Task.FromResult(false));
            }

            existingcategory.AddProduct(product);

            #endregion Add Product to Category

            _categoryRepository.Update(existingcategory);

            if (Commit())
            {
                Bus.RaiseEvent(new NewProductAddedEvent(existingcategory.Id, existingcategory.Name));
            }

            return(Task.FromResult(true));
        }
Ejemplo n.º 14
0
 public IActionResult Post(AddNewProductCommand command)
 {
     _commandDispatcher.Send(command);
     return(NoContent());
 }
Ejemplo n.º 15
0
 public async Task <int> Add(AddNewProductCommand command)
 {
     return(await Mediator.Send(command));
 }
Ejemplo n.º 16
0
 public async Task <CommandResult> AddNewProduct(AddNewProductCommand command)
 {
     return(await _commandActor.Ask <CommandResult>(command));
 }
Ejemplo n.º 17
0
        public void AddNewProduct(ProductViewModel productViewModel)
        {
            AddNewProductCommand addNewProductCommand = _mapper.Map <AddNewProductCommand>(productViewModel);

            _bus.SendCommand(addNewProductCommand);
        }
Ejemplo n.º 18
0
 public void Create([FromBody] AddNewProductCommand command)
 {
     _addNewProductCommandHandler.Execute(command);
 }
 public async Task <IActionResult> AddNewProduct([FromBody] AddNewProductCommand request)
 => Ok(await Mediator.Send(request));