public static async Task Run(IEndpointInstance endpointInstance) { Console.WriteLine("Press 's' to send a valid message"); Console.WriteLine("Press 'e' to send a failed message"); Console.WriteLine("Press any key to exit"); while (true) { var key = Console.ReadKey(); Console.WriteLine(); Console.WriteLine(); switch (key.Key) { case ConsoleKey.S: #region SendingSmall var createProductCommand = new CreateProductCommand { ProductId = "XJ128", ProductName = "Milk", ListPrice = 4, // 7MB. MSMQ should throw an exception, but it will not since the buffer will be compressed // before it reaches MSMQ. Image = new byte[1024 * 1024 * 7] }; await endpointInstance.SendLocal(createProductCommand) .ConfigureAwait(false); #endregion break; case ConsoleKey.E: try { #region SendingLarge var productCommand = new CreateProductCommand { ProductId = "XJ128", ProductName = "Really long product name", ListPrice = 15, // 7MB. MSMQ should throw an exception, but it will not since the buffer will be compressed // before it reaches MSMQ. Image = new byte[1024 * 1024 * 7] }; await endpointInstance.SendLocal(productCommand) .ConfigureAwait(false); #endregion } catch { //so the console keeps on running } break; default: { return; } } } }
public void Execution_should_fail_when_all_required_params_are_not_set_behavior_based() { var product = new Product(); var command = new CreateProductCommand(product, Mock.Of<IProductDataProxy>(), Mock.Of<IInventoryItemService>(), new TransactionContextStub()); var result = command.Execute(); result.Success.ShouldBe(false); result.Errors.Count().ShouldBe(3); }
public void Product_and_inventory_item_should_be_created() { var product = CreateValidProduct(); var productDataProxy = new ProductRepository(); var inventoryDataProxy = new InventoryItemRepository(); var inventoryService = new InventoryItemService(inventoryDataProxy); var command = new CreateProductCommand(product, productDataProxy, inventoryService, new TransactionContextStub()); var newProduct = command.Execute().Value; productDataProxy.GetByID(newProduct.ID).ShouldNotBeNull(); inventoryDataProxy.GetByProduct(newProduct.ID).ShouldNotBeNull(); }
public async Task<CreateProductResponse> CreateProductAsync(CreateProductCommand cmd) { using (var client = new HttpClient()) { var url = new Uri(string.Format("{0}/products", BaseServiceUrl)); var response = await client.PostAsync<CreateProductCommand>(url, cmd, new JsonMediaTypeFormatter()); if (response.StatusCode != HttpStatusCode.Created) { throw new ApplicationException("There was an error creating a new Product"); } var result = await response.Content.ReadAsStringAsync(); var dto = JsonConvert.DeserializeObject<CreateProductResponse>(result); return dto; } }
public Product(CreateProductCommand command) : base(command.Id) { ValidatePrice(command.Price); ValidateDiscount(command.Discount); Id = command.Id; Price = command.Price; Color = command.Color; Brand = command.Brand; ProductType = command.ProductType; Weight = command.Weight; Name = command.Name; Description = command.Description; Gender = command.Gender; ForBaby = command.ForBaby; Size = command.Size; Discount = command.Discount; CreateTime = command.CreateTime; Expiration = command.Expiration; Images = command.Images; ApplyChange(new CreatedProductEvent(Price, Color, Brand, ProductType, Weight, Name, Description, Gender, ForBaby, Size, Discount, CreateTime, Images, Expiration, this, command )); }
public async Task ShouldDeleteProduct() { // Arrange // Create product brand var brand = await CreateAsync <Brand, ProductCatalogContext>(new Brand("Test Brand Delete Brand")); // Create product category var productCategory = await CreateAsync <ProductCategory, ProductCatalogContext>(new ProductCategory("Test ProductCategory Delete Product category")); var createProductCommand = new CreateProductCommand { AvailableToSell = true, // created brand id BrandId = brand.Id.ToString(), // created product category id ProductCategoryId = productCategory.Id.ToString(), Name = "Test Product", PhotoUrl = "Test Product", Barcode = "Test Product" }; var productToAddId = await SendAsync(createProductCommand); var deleteProductCommand = new DeleteProductCommand { ProductId = productToAddId }; // Act await SendAsync(deleteProductCommand); var results = FluentActions.Invoking(() => SendAsync(deleteProductCommand)); // Assert results.Should().Throw <ProductNotFoundException>(); }
public async Task <CommandResult <Product> > Handle(CreateProductCommand request, CancellationToken cancellationToken) { var product = await _repository.FindOneAsync(x => x.Name.ToLower().Equals(request.Name.ToLower())); if (product != null) { return(CommandResult <Product> .Fail(product, "Product already exists")); } product = new Product(request.Name, request.Description, request.UnityPrice, request.QuantityInStock, request.Image, request.CategoryId, request.SubCategoryId, request.NoveltyId, request.Images); _repository.Create(product); //var productEvent = new ProductIntegrationEvent(product.Name, // product.Description, // product.UnityPrice, // product.QuantityInStock, // product.Image, // product.CategoryId, // product.SubCategoryId, // product.NoveltyId, // product.Images.Select(s => ProductImage.CreateModel(s)).ToList(), // product.Status, // product.CreatedAt, // product.UpdatedAt); PublishEvents(product); return(CommandResult <Product> .Success(product)); }
public async Task ShouldThrowProductCategoryNotFoundException() { // Arrange var brand = await CreateAsync <Brand, ProductCatalogContext>(new Brand("Test Brand")); // Create product category var productCategory = await CreateAsync <ProductCategory, ProductCatalogContext>(new ProductCategory("Test ProductCategory")); var createProductCommand = new CreateProductCommand { AvailableToSell = true, // created brand id BrandId = brand.Id.ToString(), // created product category id ProductCategoryId = Guid.NewGuid().ToString(), Name = "Test Product", PhotoUrl = "Test Product", Barcode = "Test Product" }; // Act FluentActions.Invoking(() => SendAsync(createProductCommand)).Should().Throw <ProductCategoryNotFoundException>(); }
public async Task <CreateProductResponse> HandleAsync(CreateProductCommand command, CancellationToken cancellationToken) { requestValidator.ValidateAndThrow(command); using (var context = dbContextFactory.CreateDbContext()) { var product = new Product { Name = command.Name, PointsCost = command.PointsCost }; context.Products.Add(product); await context.SaveChangesAsync(cancellationToken).ConfigureAwait(false); return(new CreateProductResponse { PointsCost = product.PointsCost, ProductId = product.Id, Name = product.Name }); } }
public async Task <ProductModel> CreateProduct(CreateProductCommand command) { _httpClient.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", BearerToken); var result = await _httpClient.PostAsJsonAsync <CreateProductCommand>("https://api-m.sandbox.paypal.com/v1/catalogs/products", command); ProductModel productModel = null; if (result.IsSuccessStatusCode) { string content = await result.Content.ReadAsStringAsync(); //All properties are getting null except name and description productModel = Newtonsoft.Json.JsonConvert.DeserializeObject <ProductModel>(content); //objects are getting null, properties are filled var productModell = await result.Content.ReadFromJsonAsync <ProductModel>(); } else { string content = await result.Content.ReadAsStringAsync(); } return(productModel); }
public async Task <BaseResponse <ProductDto> > Handle(CreateProductCommand request, CancellationToken cancellationToken) { var response = new BaseResponse <ProductDto>(); var category = await _categoryRepository.GetByIdAsync(request.CategoryId); if (category == null) { response.AddError("Category not found.", "404"); return(response); } var product = _mapper.Map <Product>(request); product.Category = category; product.CreatedAt = DateTime.Now; product.IsActive = true; product.IsDeleted = false; await _productRespository.AddAsync(product); response.Data = _mapper.Map <ProductDto>(product); return(response); }
public CommandEvent When(CreateProductCommand cmd) { var productCatalog = _factory.Load <ProductCatalogAggregate>(cmd.RootId); productCatalog.CreateProduct(cmd); try { _eventStore.AppendToStream <ProductCatalogAggregate>(cmd.RootId, productCatalog.Version, productCatalog.Changes, productCatalog.DomainEvents.ToArray()); //_publisher.Publish(arry<IDomainEvent> event) return(new CommandEvent(OperationStatus.Success)); } catch (EventStoreConcurrencyException ex) { HandleConcurrencyException(ex, productCatalog); return(new CommandEvent(OperationStatus.Success)); } catch (Exception) { throw; } }
public async Task <IActionResult> Post([FromBody] CreateProductCommand command) { var result = _productHandler.Handle(command); return(await CreateResponse(result, _productHandler.Notifications)); }
public async Task <ActionResult <Guid> > Create(CreateProductCommand command) { return(await Mediator.Send(command)); }
public async Task <ActionResult> Create([FromBody] CreateProductCommand command) { var productId = await Mediator.Send(command); return(Created($"products/{productId}", new { code = productId })); }
public static async Task Run(IEndpointInstance endpointInstance) { Console.WriteLine("Press 's' to send a valid message"); Console.WriteLine("Press 'e' to send a failed message"); Console.WriteLine("Press any key to exit"); while (true) { var key = Console.ReadKey(); Console.WriteLine(); Console.WriteLine(); switch (key.Key) { case ConsoleKey.S: #region SendingSmall var createProductCommand = new CreateProductCommand { ProductId = "XJ128", ProductName = "Milk", ListPrice = 4, // 7MB. MSMQ should throw an exception, but it will not since the buffer will be compressed // before it reaches MSMQ. Image = new byte[1024 * 1024 * 7] }; await endpointInstance.SendLocal(createProductCommand) .ConfigureAwait(false); #endregion break; case ConsoleKey.E: try { #region SendingLarge var productCommand = new CreateProductCommand { ProductId = "XJ128", ProductName = "Really long product name", ListPrice = 15, // 7MB. MSMQ should throw an exception, but it will not since the buffer will be compressed // before it reaches MSMQ. Image = new byte[1024 * 1024 * 7] }; await endpointInstance.SendLocal(productCommand) .ConfigureAwait(false); #endregion } catch { // so the console keeps on running } break; default: { return; } } } }
public async Task <IActionResult> Add([FromBody] CreateProductCommand createProduct) { await _mediator.Send(createProduct); return(StatusCode(201)); }
public async Task <IActionResult> Post([FromBody] CreateProductCommand command) { return(Ok(await mediator.Send(command))); }
public void Execution_should_succeed_when_all_required_params_are_set_behavior_based() { var product = CreateValidProduct(); var productDataProxy = new Mock<IProductDataProxy>(); productDataProxy.Setup(p => p.Insert(product)) .Returns(product) .Callback<Product>(p => product.ID = 10); var inventoryDataProxy = new Mock<IInventoryItemDataProxy>(); inventoryDataProxy.Setup(dp => dp.Insert(It.IsAny<InventoryItem>())); var command = new CreateProductCommand(product, productDataProxy.Object, new InventoryItemService(inventoryDataProxy.Object), new TransactionContextStub()); var result = command.Execute(); result.Success.ShouldBe(true); }
public async Task ShouldThrowCancelConfirmedOrderException() { // Arrange var accountId = await RunAsDefaultUserAsync(); var createCustomerCommand = new CreateCustomerCommand { AccountId = accountId, ShopName = "Test Shop Name", ShopAddress = "Test Shop address", LocationOnMap = "Test LocationOnMap" }; await SendAsync(createCustomerCommand); // Create product brand var brandCommand = new CreateBrandCommand { Name = "Test Brand" }; var brandId = await SendAsync(brandCommand); // Create product category var productCategoryCommand = new CreateProductCategoryCommand { Name = "Test Product Category" }; var productCategoryId = await SendAsync(productCategoryCommand); // Create product var createProductCommand = new CreateProductCommand { AvailableToSell = true, // created brand id BrandId = brandId, // created product category id ProductCategoryId = productCategoryId, Name = "Test Product", PhotoUrl = "Test Product", Barcode = "Test Product" }; var productId = await SendAsync(createProductCommand); // Add unit to product var addUnitToCommand = new AddUnitCommand { ProductId = productId, SellingPrice = 92, ContentCount = 2, Price = 33, Count = 6, IsAvailable = true, Name = "Test Unit", Weight = 44 }; var unitId = await SendAsync(addUnitToCommand); // AddItem To Shopping Van var addItemToVanCommand = new AddItemToVanCommand { ProductId = productId, UnitId = unitId }; await SendAsync(addItemToVanCommand); await SendAsync(addItemToVanCommand); // Place Order Command var placeOrderCommand = new PlaceOrderCommand(); var orderId = await SendAsync(placeOrderCommand); // Act var confirmOrderCommand = new ConfirmOrderCommand { OrderId = orderId }; await SendAsync(confirmOrderCommand); var cancelOrderCommand = new CancelOrderCommand { OrderId = orderId }; // Assert // Cancel Order Command FluentActions.Invoking(() => SendAsync(cancelOrderCommand)).Should().Throw <CancelConfirmedOrderException>(); }
public async Task <IActionResult> CreateProduct(CreateProductCommand model) { var response = await _mediator.Send(model); return(Ok(response)); }
public void Product_and_inventory_item_should_be_created_behavior_based() { var product = CreateValidProduct(); var productDataProxy = new Mock<IProductDataProxy>(); productDataProxy.Setup(p => p.Insert(product)) .Callback<Product>(p => product.ID = 10) .Returns(product); var inventoryDataProxy = new Mock<IInventoryItemDataProxy>(); inventoryDataProxy.Setup(dp => dp.Insert(It.IsAny<InventoryItem>())); var command = new CreateProductCommand(product, productDataProxy.Object, new InventoryItemService(inventoryDataProxy.Object), new TransactionContextStub()); command.Execute(); //productDataProxy.Verify(p => p.Insert(It.Is<Product>(pr => pr.ProductID == product.ProductID)),Times.Once()); inventoryDataProxy.Verify(p => p.Insert(It.Is<InventoryItem>(i => i.ProductID == 10)), Times.Once()); }
//Ideally should be productDTO public async Task <IActionResult> CreateProduct([FromBody] CreateProductCommand command) { var response = await _mediator.Send(command); return(Ok(response)); }
public ICommandResult Post([FromBody] CreateProductCommand command) { var result = _handler.Handler(command); return(result); }
public async Task <ActionResult <bool> > Post(CreateProductCommand command) { return(await Mediator.Send(command)); }
public async Task <ActionResult <int> > Create([FromBody] CreateProductCommand command) { var productId = await Mediator.Send(command); return(Ok(productId)); }
public async Task <IActionResult> PostProduct([FromBody] CreateProductCommand command) { var viewModel = await Mediator.Send(command); return(CreatedAtAction("GetProduct", new { id = viewModel.Product.ProductId }, viewModel)); }
public async Task <ActionResult <CreateProductCommandDto> > PostProduct([FromBody] CreateProductCommand payload) { return(Ok(await _mediatr.Send(payload))); }
public async Task <IActionResult> CreateProductAsync([FromBody] CreateProductCommand createProductCommand) => base.Ok(await mediator.Send <bool>(createProductCommand));
public async Task ShouldListAllOrders() { // Arrange var accountId = await RunAsDefaultUserAsync(); var createCustomerCommand = new CreateCustomerCommand { AccountId = accountId, ShopName = "Test Shop Name", ShopAddress = "Test Shop address", LocationOnMap = "Test LocationOnMap" }; await SendAsync(createCustomerCommand); // Create product brand var brandCommand = new CreateBrandCommand { Name = "Test Brand" }; var brandId = await SendAsync(brandCommand); // Create product category var productCategoryCommand = new CreateProductCategoryCommand { Name = "Test Product Category" }; var productCategoryId = await SendAsync(productCategoryCommand); // Create product var createProductCommand = new CreateProductCommand { AvailableToSell = true, // created brand id BrandId = brandId, // created product category id ProductCategoryId = productCategoryId, Name = "Test Product", PhotoUrl = "Test Product", Barcode = "Test Product" }; var productId = await SendAsync(createProductCommand); // Add unit to product var addUnitToCommand = new AddUnitCommand { ProductId = productId, SellingPrice = 92, ContentCount = 2, Price = 33, Count = 6, IsAvailable = true, Name = "Test Unit", Weight = 44 }; var unitId = await SendAsync(addUnitToCommand); // AddItem To Shopping Van var addItemToVanCommand = new AddItemToVanCommand { ProductId = productId, UnitId = unitId }; await SendAsync(addItemToVanCommand); await SendAsync(addItemToVanCommand); // Place Order Command var placeOrderCommand = new PlaceOrderCommand(); await SendAsync(placeOrderCommand); // Act // Get Order By Id Query var listOrdersQuery = new ListOrdersQuery { OrderStatuses = new List <OrderStatus> { OrderStatus.Placed } }; var listOrders = await SendAsync(listOrdersQuery); // Assert listOrders.Data.Should().NotBeNull(); listOrders.Data.Count.Should().Be(1); }
/// <summary> /// Trata comando de criação do produto /// </summary> /// <param name="command">Comando de criação</param> public void Handle(CreateProductCommand command) { var aggregate = new Product(command.Id, command.Name, command.Value, command.Image); _repository.Create(aggregate); }
public async Task <ActionResult <int> > Post([FromBody] CreateProductCommand command) { int id = await mediator.Send(command); return(Ok(id)); }
public async Task <IActionResult> CreateProduct([FromBody] CreateProductCommand command) { var productDto = await Mediator.Send(command); return(CreatedAtAction("GetProduct", new { id = productDto.Id }, productDto)); }
public async Task <IActionResult> Create(CreateProductCommand command) { return(Ok(await Mediator.Send(command))); }
public async Task Create(CreateProductCommand command) { await CommandBus.Execute(command); }
public async Task <ActionResult> Create([FromBody] CreateProductCommand command) { await _dispatcher.SendAsync(command); return(Ok()); }
public async Task<IHttpActionResult> Post(CreateProductCommand cmd) { var result = await productsService.CreateProductAsync(cmd); return CreatedAtRoute("GetProductById", new { id = result.Id }, result); }