public HttpResponseMessage Post(AddProductCommand command) { commandBus.Send(command); HttpResponseMessage message = this.Request.CreateResponse(HttpStatusCode.Created); string link = Url.Link("DefaultApi", new { controller = "Product", Id = command.Id }); message.Headers.Location = new Uri(link); return message; }
public async Task <IActionResult> AddAsync([FromBody] AddProductCommand product, CancellationToken cancellationToken) => Ok(await _productApplication.AddAsync(product, cancellationToken));
public void AddProduct(AddProductCommand command) { _productCommandHandler.Handle(command); }
public async Task <AddProductValidationResult> Validate(AddProductCommand command, string subject) { if (command == null) { throw new ArgumentNullException(nameof(command)); } if (string.IsNullOrWhiteSpace(command.ShopId)) { return(new AddProductValidationResult(string.Format(ErrorDescriptions.TheParameterIsMandatory, Constants.DtoNames.Product.ShopId))); } if (string.IsNullOrWhiteSpace(command.UnitOfMeasure)) { return(new AddProductValidationResult(string.Format(ErrorDescriptions.TheParameterIsMandatory, Constants.DtoNames.Product.UnitOfMeasure))); } var shop = await _shopRepository.Get(command.ShopId); if (shop == null) { return(new AddProductValidationResult(ErrorDescriptions.TheShopDoesntExist)); } if (shop.Subject != subject) { return(new AddProductValidationResult(ErrorDescriptions.TheProductCannotBeAddedByYou)); } if (!IsValid(command.Name, 1, 50)) { return(new AddProductValidationResult(string.Format(ErrorDescriptions.TheParameterIsMandatoryAndShouldContainsBetween, Constants.DtoNames.Product.Name, 1, 15))); } if (!IsValid(command.Description, 1, 255)) { return(new AddProductValidationResult(string.Format(ErrorDescriptions.TheParameterIsMandatoryAndShouldContainsBetween, Constants.DtoNames.Product.Description, 1, 255))); } if (command.Price < 0) { return(new AddProductValidationResult(ErrorDescriptions.ThePriceCannotBeLessThanZero)); } if (command.Quantity < 0) { return(new AddProductValidationResult(ErrorDescriptions.TheQuantityCannotBeLessThanZero)); } if (command.AvailableInStock != null && command.AvailableInStock < 0) { return(new AddProductValidationResult(ErrorDescriptions.TheAvailableInStockCannotBeLessThanZero)); } var unitOfMeasure = _unitOfMeasures.FirstOrDefault(u => command.UnitOfMeasure.ToLowerInvariant().Equals(u, StringComparison.CurrentCultureIgnoreCase)); if (string.IsNullOrWhiteSpace(unitOfMeasure)) { return(new AddProductValidationResult(string.Format(ErrorDescriptions.TheUnitOfMeasureIsNotCorrect, string.Join(",", _unitOfMeasures)))); } if (command.Filters != null && command.Filters.Any()) { var filterValuesIds = command.Filters.Select(f => f.ValueId); var filters = await _filterRepository.Search(new SearchFilterValuesParameter { FilterValueIds = filterValuesIds }); if (filters.Filters.Count() != filterValuesIds.Count()) { return(new AddProductValidationResult(ErrorDescriptions.SomeFiltersAreNotValid)); } } return(new AddProductValidationResult()); }
public async Task <IActionResult> AddProductsAsync(AddProductCommand request) { return(await GenerateResponseAsync(async() => await MediatorService.Send(request), HttpStatusCode.Created)); }
public void Price_is_not_in_precision_too_long_fail() { var product = new AddProductCommand(string.Empty, string.Empty, (decimal)12500.99); validator.ShouldHaveValidationErrorFor(p => p.Price, product); }
public void Price_not_empty_success() { var product = new AddProductCommand(string.Empty, string.Empty, (decimal)10.99); validator.ShouldNotHaveValidationErrorFor(p => p.Price, product); }
public void Description_not_empty_success() { var product = new AddProductCommand(string.Empty, "Product Description", decimal.Zero); validator.ShouldNotHaveValidationErrorFor(p => p.Description, product); }
private void ProductsOnCollectionChanged(object sender, NotifyCollectionChangedEventArgs notifyCollectionChangedEventArgs) { AddProductCommand.RaiseCanExecuteChanged(); }
public void Create(AddProductCommand newProduct) { var repo = new ProductRepository(); repo.AddProduct(newProduct); }
public async Task <IActionResult> Post([FromBody] AddProductCommand request) { ApiResponse <string> response = await _mediator.Send(request); return(StatusCode(201, response)); }
static void Main() { var commandProcessor = new CommandQueueProcessor { Snapshots = new Queue <IMemento>() }; var order = new Order { List = new List <IProduct>() }; var addProductCommand = new AddProductCommand { Order = order, Product = new Product { Name = "First", Count = 10, Price = 100, Guid = Guid.NewGuid() } }; commandProcessor.AddCommandToExecute(addProductCommand); addProductCommand.Product = new Product { Count = 20, Price = 200, Guid = Guid.NewGuid(), Name = "Secon" }; commandProcessor.AddCommandToExecute(addProductCommand); addProductCommand.Product = new Product { Count = 30, Price = 300, Guid = Guid.NewGuid(), Name = "Third" }; commandProcessor.AddCommandToExecute(addProductCommand); commandProcessor.Run(); commandProcessor.Run(); commandProcessor.Run(); var getSumPriceCommand = new GetSumPriceCommand { Order = order }; commandProcessor.AddCommandToExecute(getSumPriceCommand); Console.Write(order.ToString()); Console.WriteLine(commandProcessor.Run()); Console.WriteLine("-----------------------------------------------------------------------"); commandProcessor.Undo(); commandProcessor.AddCommandToExecute(getSumPriceCommand); Console.Write(order.ToString()); Console.WriteLine(commandProcessor.Run()); Console.WriteLine("-----------------------------------------------------------------------"); commandProcessor.Undo(); commandProcessor.AddCommandToExecute(getSumPriceCommand); Console.Write(order.ToString()); Console.WriteLine(commandProcessor.Run()); Console.WriteLine("-----------------------------------------------------------------------"); }
public async Task <IActionResult> Create([FromBody] AddProductCommand command) { var result = await mediator.Send(command); return(ConvertToResponse(result)); }
public Task <AddProductResponse> Add([FromBody] AddProductCommand command) { return(_addProductCommandHandler.Handle(command)); }
private void CloseTrip_Click(object sender, RoutedEventArgs e) { if (NumberArea.Text != "") { try { int trip_id = Convert.ToInt32(NumberArea.Text); //Получить слоты Trip trip = controller.GetTrips().Where(t => t.Id == trip_id).FirstOrDefault(); if (trip == null) { throw new Exception("Не найден объект, с указанным Id. Проверьте правильность введенных данных"); } if (trip.Status.Equals("Завершён")) { throw new Exception("Нельзя завершить завершённый рейс"); } if (trip.Status.Equals("Ожидает отправки")) { throw new Exception("Нельзя завершить рейс, ожидающий отправки"); } if (trip.To.Id != employee.center.Id) { throw new Exception("Завершить рейс может только сотрудник центра назначения или администратор"); } ObservableCollection <TruckSlot> slots = controller.GetSlotsForTrip(trip); //Прибывить к наименованию на складе кол-во со слотов Center centerTo = trip.To; foreach (TruckSlot slot in slots) { ProductPosition position = controller.GetDBCenterProductsPosition(centerTo).Where(p => p.product.Id == slot.product.Id).FirstOrDefault(); if (position != null) { position.numberOfProduct += slot.total_umber; } else { ICommand command = new AddProductCommand( employee, Convert.ToString(slot.product.Name), Convert.ToString(slot.product.Length), Convert.ToString(slot.product.Height), Convert.ToString(slot.product.Height), Convert.ToString(slot.product.Weight), Convert.ToString(slot.product.Cost), slot.product.Unit_of_measurment, Convert.ToString(slot.product.Mominal_number), Convert.ToString(slot.total_umber) ); if (command.ifExecute()) { command.Execute(); } } } //Отнять с отбывшего склада Center centerFrom = trip.From; foreach (TruckSlot slot in slots) { ProductPosition position = controller.GetDBCenterProductsPosition(centerFrom).Where(p => p.product.Id == slot.product.Id).FirstOrDefault(); position.numberOfProduct -= slot.total_umber; } //Удалить заказы или отнять кол-во foreach (TruckSlot slot in slots) { Require require = controller.GetDBRequiers().Where(r => r.FromCenter.Id == centerFrom.Id && r.ToCenter.Id == centerTo.Id && r.product.Id == slot.product.Id).FirstOrDefault(); if (require != null) { if (require.Number == slot.total_umber) { controller.DelateRequier(require.Id); } else { require.Number -= slot.total_umber; } } } //Удалить слоты controller.DelateTripsSlots(trip_id); //Завершить рейс trip.CloseTrip(); trip.truck.closeTrip(centerTo); TripsWorkingArea.Content = EmployeeTripsTable.GetInstance(employee); } catch (Exception ex) { MessageBox.Show(ex.Message); } } else { MessageBox.Show("Укажите Id рейса, над которым хотите совершить операцию"); } }
public async Task <int> AddProduct(AddProductCommand command) { return(await this._mediator.Send(command)); }
public void Name_not_empty_success() { var product = new AddProductCommand("Product Name", string.Empty, decimal.Zero); validator.ShouldNotHaveValidationErrorFor(p => p.Name, product); }
public async Task <IActionResult> AddNewProduct([FromBody] AddProductCommand addProductCommand) => Ok(await _mediator.Send(addProductCommand));
public void Description_is_empty_fail() { var product = new AddProductCommand(string.Empty, "", decimal.Zero); validator.ShouldHaveValidationErrorFor(p => p.Description, product); }
public async Task <IActionResult> Post(AddProductCommand command) { var response = await _mediator.Send(command); return(Ok(response)); }
public void Price_is_empty_fail() { var product = new AddProductCommand(string.Empty, string.Empty, decimal.Zero); validator.ShouldHaveValidationErrorFor(p => p.Price, product); }
public async Task <IActionResult> Post([FromBody] AddProductCommand command, [FromServices] ProductHandler handler) { return(ResponseAsync(handler.Handle(command).Result as CommandResult)); }
public async Task <int> AddAsync(AddProductCommand product, CancellationToken cancellationToken) { return(await _productRepository.AddAsync(product, cancellationToken)); }
public async Task <Result <ProductResponse> > Post([FromBody] AddProductCommand fornecedor) => await _service.Add(fornecedor);
public async Task <IActionResult> Execute(JObject jObj, string subject, string commonId, HttpRequest request) { if (jObj == null) { throw new ArgumentNullException(nameof(jObj)); } if (string.IsNullOrWhiteSpace(subject)) { throw new ArgumentNullException(nameof(subject)); } if (request == null) { throw new ArgumentNullException(nameof(request)); } // 1. Check the request AddProductCommand command = null; try { command = _requestBuilder.GetAddProduct(jObj); } catch (ArgumentException ex) { var error = _responseBuilder.GetError(ErrorCodes.Request, ex.Message); return(_controllerHelper.BuildResponse(HttpStatusCode.BadRequest, error)); } var validationResult = await _validator.Validate(command, subject); if (!validationResult.IsValid) { var error = _responseBuilder.GetError(ErrorCodes.Request, validationResult.Message); return(_controllerHelper.BuildResponse(HttpStatusCode.BadRequest, error)); } // 2. Add images var images = new List <string>(); if (command.PartialImagesUrl != null) { foreach (var image in command.PartialImagesUrl) { string path; if (!AddImage(image, request, out path)) { continue; } images.Add(path); } } command.Id = Guid.NewGuid().ToString(); command.CreateDateTime = DateTime.UtcNow; command.UpdateDateTime = DateTime.UtcNow; command.CommonId = commonId; command.PartialImagesUrl = images; var res = new { id = command.Id }; _commandSender.Send(command); return(new OkObjectResult(res)); }
public AddProductCommandValidator(AddProductCommand command) : base(command) { }
public bool PostProduct(AddProductCommand addProductCommand) { return(_repo.PostProduct(addProductCommand)); }
public async Task <IActionResult> AddProduct(AddProductCommand command) { await mediator.Send(command); return(Ok()); }