public async Task Put_given_valid_id_and_valid_dto_returns_PendingCountDTO() { var userId = 1; var id = 1; var dto = new ProductUpdateDTO { UserId = userId }; var countDTO = new PendingApplicationsCountDTO { PendingApplications = 9000 }; var repository = new Mock <IProductRepository>(); repository.Setup(s => s.UpdateAsync(dto)).ReturnsAsync((true, countDTO.PendingApplications, (true, null))); var logger = new Mock <ILogger <ProductsController> >(); var controller = new ProductsController(repository.Object, logger.Object); // Needs HttpContext to mock it. controller.ControllerContext.HttpContext = new DefaultHttpContext(); var cp = MockClaimsSecurity(userId, UserRoleEnum.Producer.ToString()); //Update the HttpContext to use mocked claim controller.ControllerContext.HttpContext.User = cp.Object; var put = await controller.Put(id, dto); Assert.Equal(countDTO.PendingApplications, put.Value.PendingApplications); }
public async Task Put_given_dto_and_id_with_invalid_User_Role_in_Claim_returns_Unauthorized() { var dto = new ProductUpdateDTO(); var id = 1; var userRole = UserRoleEnum.Receiver.ToString(); var repository = new Mock <IProductRepository>(); var logger = new Mock <ILogger <ProductsController> >(); var controller = new ProductsController(repository.Object, logger.Object); // Needs HttpContext to mock it. controller.ControllerContext.HttpContext = new DefaultHttpContext(); var cp = MockClaimsSecurity(id, userRole); //Update the HttpContext to use mocked claim controller.ControllerContext.HttpContext.User = cp.Object; var put = await controller.Put(id, dto); Assert.IsType <UnauthorizedResult>(put.Result); }
public async Task <ActionResult> PartialUpdateProduct(int id, JsonPatchDocument <ProductUpdateDTO> patchDoc) { var productModelFromRepo = await _productService.GetProduct(id); if (productModelFromRepo == null) { return(NotFound()); } var productToPatch = new ProductUpdateDTO { Name = productModelFromRepo.Name, Price = productModelFromRepo.Price, Color = productModelFromRepo.Color, Description = productModelFromRepo.Description }; patchDoc.ApplyTo(productToPatch, ModelState); if (!TryValidateModel(productToPatch)) { return(ValidationProblem(ModelState)); } productModelFromRepo.SetName(productToPatch.Name); productModelFromRepo.SetPrice(productToPatch.Price); productModelFromRepo.SetColor(productToPatch.Color); productModelFromRepo.SetDescription(productToPatch.Description); await _productService.UpdateProduct(productModelFromRepo); return(NoContent()); }
public async Task Put_given_non_existing_returns_false_returns_NotFound() { var userId = 1; var id = 1; var dto = new ProductUpdateDTO { UserId = userId }; var repository = new Mock <IProductRepository>(); var logger = new Mock <ILogger <ProductsController> >(); var controller = new ProductsController(repository.Object, logger.Object); // Needs HttpContext to mock it. controller.ControllerContext.HttpContext = new DefaultHttpContext(); var cp = MockClaimsSecurity(userId, UserRoleEnum.Producer.ToString()); //Update the HttpContext to use mocked claim controller.ControllerContext.HttpContext.User = cp.Object; var put = await controller.Put(id, dto); Assert.IsType <NotFoundResult>(put.Result); }
public void Update(Guid id, ProductUpdateDTO item) { var product = _mapper.Map <Product>(item); _context.Update(product); _context.SaveChanges(); }
public async Task Put_given_dto_with_different_User_id_as_Claim_returns_Forbidden() { var userId = 1; var id = 1; var userRole = UserRoleEnum.Producer.ToString(); var dto = new ProductUpdateDTO { UserId = userId }; var repository = new Mock <IProductRepository>(); var logger = new Mock <ILogger <ProductsController> >(); var controller = new ProductsController(repository.Object, logger.Object); // Needs HttpContext to mock it. controller.ControllerContext.HttpContext = new DefaultHttpContext(); var cp = MockClaimsSecurity(42, userRole); //Update the HttpContext to use mocked claim controller.ControllerContext.HttpContext.User = cp.Object; var put = await controller.Put(id, dto); Assert.IsType <ForbidResult>(put.Result); }
public IActionResult Put(int id, [FromBody] ProductUpdateDTO DTO) { if (DTO == null) { return(BadRequest()); } if (!ModelState.IsValid) { return(BadRequest(ModelState)); } var entity = _rep.Get <Product>(id); if (entity == null) { return(NotFound()); } Mapper.Map(DTO, entity); if (!_rep.Save()) { return(StatusCode(500, "A problem happened while handling your request.")); } return(NoContent()); }
public async Task <IActionResult> Update(int id, [FromBody] ProductUpdateDTO productDTO) { var location = GetControllerActionNames(); try { _logger.LogInfo($"{location}: Update Attempted on record with id: {id} "); if (id < 1 || productDTO == null) { _logger.LogWarn($"{location}: Update failed with bad data - id: {id}"); return(BadRequest()); } if (!ModelState.IsValid) { _logger.LogWarn($"{location}: Data was Incomplete"); return(BadRequest(ModelState)); } var product = _mapper.Map <Product>(productDTO); var isSuccess = await _businessLogic.Update(id, product); if (!isSuccess.IsSuccess) { return(InternalError($"{location}: Update failed for record with id: {id}")); } _logger.LogInfo($"{location}: Record with id: {id} successfully updated"); return(NoContent()); } catch (Exception e) { return(InternalError($"{location}: {e.Message} - {e.InnerException}")); } }
public static Products ToUpdateEntity(this ProductUpdateDTO dto, Products dbdata) { dbdata.IsOnline = dto.IsOnline; dbdata.ProductCategory = dto.ProductCategory; dbdata.ProductName = dto.ProductName; return(dbdata); }
public async Task Put_given_dto_updates_product() { var id = 1; var userId = 1; var dto = new ProductUpdateDTO { UserId = userId }; var repository = new Mock <IProductRepository>(); var logger = new Mock <ILogger <ProductsController> >(); var controller = new ProductsController(repository.Object, logger.Object); // Needs HttpContext to mock it. controller.ControllerContext.HttpContext = new DefaultHttpContext(); var cp = MockClaimsSecurity(userId, UserRoleEnum.Producer.ToString()); //Update the HttpContext to use mocked claim controller.ControllerContext.HttpContext.User = cp.Object; await controller.Put(id, dto); repository.Verify(s => s.UpdateAsync(dto)); }
public async Task <IActionResult> UpdateProduct(int ProductId, ProductUpdateDTO productUpdateDTO) { try { //check product id matches requested id if (productUpdateDTO.ProductId != null) { if (ProductId != productUpdateDTO.ProductId) { return(BadRequest(new { ApiProblem = "Entity Id does not match requested Id." })); } } var productIdExists = _context.Products.Any(p => p.ProductId == productUpdateDTO.ProductId); //check if product id does not exist if (!productIdExists && productUpdateDTO.ProductId != null) { //add error message ModelState.AddModelError("ProductId", "No product found with given product id."); } //if model is not valid return error messages if (!ModelState.IsValid) { return(BadRequest(ModelState.ToDictionary(x => x.Key, x => x.Value.Errors.Select(e => e.ErrorMessage).ToArray()))); } //find product var product = await _context.Products.FindAsync(ProductId); //if product not found return error if (product == null) { return(NotFound()); } //update product product.VirtualSiteName = productUpdateDTO.VirtualSiteName; //put product try { await _context.SaveChangesAsync(); } catch (DbUpdateConcurrencyException) when(!ProductExists(ProductId)) { return(NotFound()); } return(NoContent()); } catch (NullReferenceException e) { //if exception is caught write to console and return error message Console.WriteLine("{0} Exception caught.", e); return(BadRequest(new { ApiProblem = "Invalid JSON format sent." })); } }
public ActionResult UpdateProduct(Guid id, ProductUpdateDTO product) { var productFromRepo = _repository.GetProduct(id); _mapper.Map(product, productFromRepo); _repository.save(); return(Ok()); }
public async Task Update(int id, ProductUpdateDTO model) { var entry = await _context.Products.SingleAsync(x => x.ProductId == id); entry.Description = model.Description; entry.Name = model.Name; entry.Price = model.Price; await _context.SaveChangesAsync(); }
public void Update(Guid id, ProductUpdateDTO item) { if (id != item.Id) { return; } var product = _mapper.Map <Product>(item); _context.Update(product); _context.SaveChanges(); }
public async Task <IActionResult> Put(int id, [FromBody] ProductUpdateDTO request) { if (id != request.Id) { return(BadRequest()); } var productUpdate = _mapper.Map <ProductUpdateDTO, Products>(request); await _productsService.Update(productUpdate); var ProductsDTO = _mapper.Map <Products, ProductsDTO>(productUpdate); return(Ok(ProductsDTO)); }
public ActionResult <ProductReadDto> Update(int id, ProductUpdateDTO productUpdateDTO) { var productToCreate = mapper.Map <Product>(productUpdateDTO); var result = productService.Update(id, productToCreate); if (!result.Success) { return(BadRequest(result.Message)); } var productReadDto = mapper.Map <ProductReadDto>(result.Product); return(Ok(productReadDto)); }
public void Update02(Guid id, ProductUpdateDTO item) { if (id != item.Id) { return; } var product = new Product(); product.Id = item.Id; product.Name = item.Name; _context.Update(product); _context.SaveChanges(); }
public ActionResult UpdateProduct(int id, ProductUpdateDTO productUpdate) { var product = _repo.GetById(id); if (product == null) { return(NotFound()); } _mapper.Map(productUpdate, product); product.ModifiedDate = DateTime.UtcNow; _repo.Update(product); _repo.SaveChanges(); return(NoContent()); }
public ActionResult Update(Guid id) { ProductUpdateDTO data = new ProductUpdateDTO(); Product p = service.ProductService.GetById(id); data.CategoryList = service.CategoryService.GetActive(); data.ProductID = p.Id; data.Name = p.Name; data.Price = p.Price; data.Quantity = p.Quantity; data.UnitsInStock = p.UnitsInStock; data.ImagePath = p.ImagePath; return(View(data)); }
public static bool Validate(this ProductUpdateDTO dto) { dto.IsValidated = true; if (string.IsNullOrEmpty(dto.ProductName)) { dto.IsValidated = false; dto.ValidationErrors.Add("Product Name Cannot Be Empty"); } if (string.IsNullOrEmpty(dto.ProductCategory)) { dto.IsValidated = false; dto.ValidationErrors.Add("Product Category Cannot Be Empty"); } return(dto.IsValidated); }
public async Task <IActionResult> AlternateUpdateProduct(int id, ProductUpdateDTO product) { if (!ModelState.IsValid) { return(BadRequest(ModelState)); } var currentProduct = await _repo.GetProduct(id); _mapper.Map(product, currentProduct); bool saved = await _repo.Save(); if (saved) { return(NoContent()); } return(BadRequest("Error saving changes")); }
public async Task <ProductDTO> UpdateProduct(ProductUpdateDTO updateDTO) { var product = await productRepository.GetProductById(updateDTO.Id); var team = await teamRepository.GetTeamById(updateDTO.DevTeam); if (team == null) { throw new ArgumentException("Team not found."); } product.Name = updateDTO.Name; product.DevTeam = updateDTO.DevTeam; await productRepository.UpdateProduct(product); return(await GetProductById(product.Id)); }
public JsonResult ProductEdit(ProductUpdateDTO entity) { try { if (_productService == null) { _productService = new ProductService(); } ProductListDTO productList = _productService.ProductEdit(entity); return(Json(productList, JsonRequestBehavior.AllowGet)); } catch (Exception) { return(null); throw; } }
public ActionResult Update(ProductUpdateDTO data, HttpPostedFileBase Image, ImagesForProducts ımageFor, HttpPostedFileBase Image1) { data.ImagePath = ImageUploader.UploadSingleImage("~/Uploads", Image); Product p = service.ProductService.GetById(data.ProductID); if (data.ImagePath == "0" || data.ImagePath == "1" || data.ImagePath == "2") { if (p.ImagePath == null || p.ImagePath == "~/Content/Images/avantaj.png") { data.ImagePath = "~/Content/Images/avantaj.png"; } else { data.ImagePath = p.ImagePath; } } data.ImagePath1 = ImageUploader.UploadSingleImage("~/Uploads/", Image1); if (data.ImagePath1 == "0" || data.ImagePath1 == "1" || data.ImagePath1 == "2") { data.ImageForProducts.ImagePath = "~/Content/Images/avantaj.png"; } ımageFor.ProductID = p.Id; ımageFor.ImagePath = data.ImagePath1; p.Name = data.Name; p.Price = data.Price; p.Quantity = data.Quantity; p.UnitsInStock = data.UnitsInStock; p.ImagePath = data.ImagePath; service.ImageForProductsService.Add(ımageFor); service.ProductService.Update(p); return(Redirect("/Member/Product/MemberProductList")); }
public async Task <ActionResult <PendingApplicationsCountDTO> > Put(int id, [FromBody] ProductUpdateDTO dto) { var claimRole = User.Claims.First(c => c.Type == ClaimTypes.Role); if (!claimRole.Value.Equals(UserRoleEnum.Producer.ToString())) { return(Unauthorized()); } var claimId = User.Claims.First(c => c.Type == ClaimTypes.NameIdentifier); // Identity check of current user // if id don't match, it is forbidden to update if (!claimId.Value.Equals(dto.UserId.ToString())) { return(Forbid()); } var(status, pendingApplications, (emailSent, emailError)) = await _productRepository.UpdateAsync(dto); if (!dto.Available) { _logger.LogInformation($"Email cancel application to receiver, sent to localhost:25. Status: {emailSent}"); if (!emailSent || emailError != null) { _logger.LogError($"Email error on cancel applications on productId: {dto.Id} with error message: {emailError}"); } } if (status) { return(new PendingApplicationsCountDTO { PendingApplications = pendingApplications }); } return(NotFound()); }
public async Task <IActionResult> Update(int id, [FromBody] ProductUpdateDTO productDTO) { var location = GetControllerActionName(); try { logger.LogInfo($"{location}: Update Product with id {id}"); if (id < 1 || productDTO == null || id != productDTO.Id) { logger.LogWarn($"{location}: Update Product with id {id} failed with bad data"); return(BadRequest()); } var isExists = await productRepository.IsExists(id); if (!isExists) { logger.LogWarn($"{location}: Product with id {id} not found"); return(NotFound()); } if (!ModelState.IsValid) { logger.LogWarn($"{location}: Product object is incomplete"); return(BadRequest(ModelState)); } var product = mapper.Map <Product>(productDTO); var isSuccess = await productRepository.Update(product); if (!isSuccess) { return(InternalError($"{location}: Update Product with id {id} failed")); } logger.LogInfo($"{location}: Update Product with id {id} successful"); return(NoContent()); } catch (Exception e) { return(InternalError($"{location}: {e.Message} - {e.InnerException}")); } }
public ProductListDTO ProductEdit(ProductUpdateDTO entity) { if (_productRepository == null) { _productRepository = new ProductRepository(); } try { Products product = _productRepository.GetDataById(entity.ProductID); product.ProductID = entity.ProductID; product.ProductName = entity.ProductName; product.CategoryID = entity.CategoryID; product.SupplierID = entity.SupplierID; product.Discontinued = entity.Discontinued; product.PhotoPath = entity.PhotoPath; product.QuantityPerUnit = entity.QuantityPerUnit; product.ReorderLevel = entity.ReorderLevel; product.UnitPrice = entity.UnitPrice; product.UnitsInStock = entity.UnitsInStock; product.UnitsOnOrder = entity.UnitsOnOrder; var item = _productRepository.Update(product); if (item != null) { return(GetProductByID(item.ProductID)); } else { return(null); } } catch (Exception) { return(null); } }
public async Task <IActionResult> PutTeam([FromRoute] int id, [FromBody] ProductUpdateDTO product) { if (!ModelState.IsValid) { return(BadRequest(ModelState)); } if (id != product.Id) { return(BadRequest()); } var userId = int.Parse(User.Claims.FirstOrDefault(c => c.Type == ClaimTypes.NameIdentifier).Value); var preUpdatedProduct = await productService.GetProductById(product.Id); if (preUpdatedProduct == null) { return(NotFound()); } if (preUpdatedProduct.Owner.Id != userId) { return(Forbid()); } try { await productService.UpdateProduct(product); return(NoContent()); } catch (ArgumentException e) { return(NotFound(new { error = "Team not found." })); } }
public void Update(ProductUpdateDTO productDTO) => throw new NotImplementedException();
public IActionResult Put(int id, [FromBody] ProductUpdateDTO product) { if (product == null) { return(BadRequest(new ErrorViewModel { ErrorCode = "400", ErrorMessage = "Thông tin cung cấp không chính xác." })); } if (!ModelState.IsValid) { var errorViewModel = new ErrorViewModel { ErrorCode = "400", ErrorMessage = ModelState.ToErrorMessages() }; return(BadRequest(errorViewModel)); } var productToUpdate = this._productRepository.GetById(id); if (productToUpdate == null) { return(NotFound(new ErrorViewModel { ErrorCode = "404", ErrorMessage = "Sản phẩm cần cập nhật không tìm thấy" })); } bool isExisting = this._productRepository.CheckExistingProduct( id, product.Serial, product.Name); if (isExisting) { return(BadRequest(new ErrorViewModel { ErrorCode = "400", ErrorMessage = "Mã sản phẩm hoặc Tên sản phẩm này đã tồn tại." })); } productToUpdate.Serial = product.Serial; productToUpdate.Name = product.Name; productToUpdate.Description = product.Description; productToUpdate.CategoryId = product.CategoryId; productToUpdate.SupplierId = product.SupplierId; productToUpdate.Price = product.Price; productToUpdate.ReOrder = product.ReOrder; productToUpdate.UpdatedBy = "admin"; productToUpdate.UpdatedDate = DateTime.Now; bool isSuccess = this._productRepository.Update(productToUpdate); if (isSuccess == false) { return(StatusCode(500, new ErrorViewModel { ErrorCode = "500", ErrorMessage = "Có lỗi trong quá trình cập nhật dữ liệu." })); } return(Ok(productToUpdate)); }