public IActionResult Update([FromBody] ProductUpdateDto productUpdateDto) { var oldProduct = _productService.GetByIdAsync(productUpdateDto.Id).Result; var productUpdate = _mapper.Map <ProductUpdateDto, Product>(productUpdateDto, oldProduct.Data); var result = _productService.Update(productUpdate); if (result.ResultStatus == ResultStatus.Error) { return(BadRequest(new ErrorDto { Message = ApiResultMessages.ResultMessage(false), ResultStatus = result.ResultStatus })); } return(Ok(new ProductDto { Product = result.Data, Message = ApiResultMessages.ResultMessage(true), ResultStatus = result.ResultStatus })); }
public ActionResult UpdateProduct(Guid brandId, Guid productId, ProductUpdateDto productUpdateDto) { Brand brand = _repository.GetBrandById(brandId); if (brand == null) { return(NotFound()); } Product productOfBrand = _repository.GetProductById(productId); //put upserting if (productOfBrand == null) { Product product = _mapper.Map <Product>(productUpdateDto); product.Id = productId; _repository.AddProduct(brandId, product); _repository.SaveChanges(); ProductReadDto productRead = _mapper.Map <ProductReadDto>(product); return(CreatedAtRoute("GetProduct", new { brandId, productId = productRead.Id }, productRead)); } _mapper.Map(productUpdateDto, productOfBrand); _repository.UpdateProduct(productOfBrand); _repository.SaveChanges(); return(NoContent()); }
public async Task <IActionResult> UpdateProduct(int id, ProductUpdateDto productUpdateDto) { var product = await _unitOfWork.Products.GetByIdAsync(id); if (product == null) { return(NotFound()); } var currentUserId = int.Parse(User.FindFirst(ClaimTypes.NameIdentifier)?.Value); if (currentUserId != product.UserId) { return(Unauthorized()); } _mapper.Map(productUpdateDto, product); _unitOfWork.Products.Update(product); if (await _unitOfWork.SaveAsync()) { return(NoContent()); } throw new Exception($"Updating product {id} failed to save"); }
public async Task <ServiceResponse <ProductGetDto> > UpdateProduct(ProductUpdateDto updatedProduct) { ServiceResponse <ProductGetDto> serviceResponse = new ServiceResponse <ProductGetDto>(); try{ Product product = await _context.Products.FirstOrDefaultAsync(u => u.id == updatedProduct.id); product.id = updatedProduct.id; product.code = updatedProduct.code; product.name = updatedProduct.name; product.description = updatedProduct.description; product.price = updatedProduct.price; product.stock = updatedProduct.stock; _context.Products.Update(product); await _context.SaveChangesAsync(); serviceResponse.Data = _mapper.Map <ProductGetDto>(product); } catch (Exception ex) { serviceResponse.Success = false; serviceResponse.Message = ex.Message; } return(serviceResponse); }
public async Task <IActionResult> UpdateProduct([FromBody] ProductUpdateDto productUpdateDto) { var product = _mapper.Map <Product>(productUpdateDto); await _productService.Update(product); return(NoContent()); }
public async Task <ActionResult> PutProduct(int id, [FromBody] /*[Bind("ProductID,ProductName,ProductDescription,ImageFile,SizeID,ProductQuantity,ProductPrice")] */ ProductUpdateDto product) { var getProduct = await _product.FindProduct(id); if (getProduct == null) { return(BadRequest()); } //No image will be updated only content _mapper.Map(product, getProduct); //no need for this, but when we don't need a mapper it's a good //practice to have the update method ready _product.ProductUpdate(getProduct); try { await _product.SaveProduct(); } catch (DbUpdateConcurrencyException) { if (!_product.ProductExists(id)) { return(NotFound()); } else { throw; } } return(NoContent()); }
public async Task ProductUpdate(ProductUpdateDto product) { using (var context = new ProductInformationContext()) { var entity = await context.Products.SingleOrDefaultAsync(x => x.Id == product.Id); if (product.ProductName != null) { entity.ProductName = product.ProductName; } if (product.Content != null) { entity.Content = product.Content; } if (product.Title != null) { entity.Title = product.Title; } if (product.ProductTypeId != null) { entity.ProductTypeId = product.ProductTypeId; } entity.Updated = DateTime.Now; await context.SaveChangesAsync(); } }
public async Task <IActionResult> UpdateProduct(ProductUpdateDto model, IFormFile Image) { if (ModelState.IsValid) { if (Image != null) { var images = Path.GetExtension(Image.FileName); string guid = Guid.NewGuid() + images; var addimages = Path.Combine(Directory.GetCurrentDirectory(), "wwwroot/image/" + guid); using (var stream = new FileStream(addimages, FileMode.Create)) { await Image.CopyToAsync(stream); } _productService.Update(_mapper.Map <Product>(model)); return(RedirectToAction("Index")); } } return(View(model)); }
public ResponseDto Update(ProductUpdateDto updateDto) { ResponseDto responseDto = new ResponseDto(); ProductUpdateBo updateBo = new ProductUpdateBo() { ProductId = updateDto.ProductId, ProductUpdateTypeId = updateDto.ProductUpdateTypeId, Name = updateDto.Name, OriginCountryId = updateDto.OriginCountryId, Notes = updateDto.Notes, CategoryId = updateDto.CategoryId, ImageUniqueId = updateDto.ImageUniqueId, ImageFileTypeId = updateDto.ImageFileTypeId, Session = Session }; ResponseBo responseBo = productBusiness.Update(updateBo); responseDto = responseBo.ToResponseDto(); return(responseDto); }
public void CanUpdateProduct() { _context.Users.Add(_testUser); var product = new Product { Id = 1, Name = "Test product 2", Description = "A description", AddedBy = _testUser, TimeEstimate = "5 hours", ProductImage = null, Requirements = "[]", Comments = new Collection <Comment>(), Instructions = new Collection <Instruction>() }; _context.Products.Add(product); _context.SaveChanges(); var updatedProduct = new ProductUpdateDto { Id = 1, Name = "Edited test product", Description = "A description", TimeEstimate = "5 hours", ProductImage = null, Requirements = new Collection <string>(), Instructions = new Collection <InstructionCreationDto>(), }; _productRepository.UpdateProduct(updatedProduct); var fromDb = _productRepository.GetProduct(1); Assert.AreEqual(fromDb.Name, "Edited test product"); }
public IActionResult Edit(Guid id, [FromBody] ProductUpdateDto product) { if (product == null) { return(BadRequest()); } var productFromRepo = _unitOfWork.Product.Get(id); if (productFromRepo == null) { return(NotFound()); } //Mapping the ProductUpdateDto to the product entity productFromRepo.Id = id; productFromRepo.CompanyName = product.CompanyName; productFromRepo.ImageUrl = product.ImageUrl; productFromRepo.Price = product.Price; productFromRepo.ProductName = product.ProductName; if (!(_unitOfWork.Complete() > 0)) { throw new Exception($"Updating the product with id: {id} has failed"); } return(NoContent()); }
public async Task <bool> UpdateProduct(int userId, ProductUpdateDto input) { var product = await _context.Products .Include(p => p.ProductionPrices) .FirstOrDefaultAsync(p => p.Id == input.Id && p.OwnerId == userId); if (product == null) { return(false); } product.Name = input.Name; product.Packaging = input.Packaging; product.StockCount = input.StockCount; product.ExpirationDate = input.ExpirationDate; product.ProductionDate = input.ProductionDate; product.SalePrice = input.SalePrice; product.ProductionPrices .OrderByDescending(p => p.AdditionDate) .ToList()[0].Value = input.ProductionPrice; var dbRes = await _context.SaveChangesAsync(); return(dbRes > 0); }
public ProductCode EditProduct(ProductUpdateDto Product) { var product = _context.Product.Include("Bids.User").FirstOrDefault(x => x.ProductId == Product.ProductId); if (product == null) { return(ProductCode.Null); } if (DateTime.UtcNow > Product.ExpiryDate) { return(ProductCode.InvalidDate); } if (product.Status == 1) { return(ProductCode.AlreadyAwarded); } if (Product.ImgFile != null) { var imgName = GetImgName(Product.ImgFile, product.ProductId); product.ImgUrl = GetImgUrl(imgName); _S3UploadeImage.UploadFileAsync(Product.ImgFile, imgName).Wait(); } product.ProductName = Product.ProductName; product.ProductDescription = Product.ProductDescription; product.ExpiryDate = Product.ExpiryDate; product.Bids = product.Bids.OrderByDescending(x => x.BidAmount); _productHub.Clients.All.SendAsync("ReceiveProduct", _mapper.Map <ProductReadDto>(product)); _context.SaveChanges(); return(ProductCode.Success); }
public ActionResult PartialProductUpdate(Guid brandId, Guid productId, JsonPatchDocument <ProductUpdateDto> patcher) { Brand brand = _repository.GetBrandById(brandId); if (brand == null) { return(NotFound()); } Product productOfBrand = _repository.GetProductById(productId); //patch upserting if (productOfBrand == null) { var newProduct = new ProductUpdateDto(); patcher.ApplyTo(newProduct, ModelState); var product = _mapper.Map <Product>(newProduct); product.Id = productId; _repository.AddProduct(brandId, product); _repository.SaveChanges(); var productReadDto = _mapper.Map <ProductReadDto>(product); return(CreatedAtRoute("GetProduct", new { brandId, productId = productReadDto.Id }, productReadDto)); } var productToPatch = _mapper.Map <ProductUpdateDto>(productOfBrand); patcher.ApplyTo(productToPatch, ModelState); _mapper.Map(productToPatch, productOfBrand); _repository.UpdateProduct(productOfBrand); _repository.SaveChanges(); return(NoContent()); }
public void Update_Products() { // Arrange var mapper = CreateMapperObject().CreateMapper(); var mockRepo = new Mock <IAppProductRepository>(); mockRepo.Setup(repo => repo.GetProductAsync(It.IsAny <Guid>())) .ReturnsAsync(GetSingleProduct()); var controller = new ProductController(mapper, mockRepo.Object); var inputDto = new ProductUpdateDto { Name = "updatedName", Price = 100 }; // Act var result = controller.UpdateProduct(It.IsAny <Guid>(), inputDto); // Assert var model = result.Result as CreatedAtRouteResult; var productToCheck = model?.Value as Product; Assert.Equal("updatedName", productToCheck?.Name); }
public async Task <IActionResult> CreateProduct(int userId, ProductUpdateDto productUpdateDto) { var user = await _userManager.FindByIdAsync(userId.ToString()); var userRoles = await _userManager.GetRolesAsync(user); var productToAdd = _mapper.Map <Product>(productUpdateDto); //by default product is publish if (userRoles.Contains("Admin")) { productToAdd.IsPublish = true; } else { productToAdd.IsPublish = false; } productToAdd.TimeStamp = DateTime.Now; await _repo.CreateProduct(productToAdd); var productToReturn = _mapper.Map <ProductIdDto>(productToAdd); await _repo.SaveAll(); return(CreatedAtRoute("GetProduct" , new { userId = userId, id = productToAdd.Id } , productToReturn)); }
public async Task <IActionResult> ProductUpdate(ProductUpdateDto model) { if (ModelState.IsValid) { Product product = await productService.GetByIdAsync(model.Id); if (product != null) { product.Transfer(model); product.UpdateUserId = appUserSessionService.Get().Id; await productService.UpdateAsync(product); return(Json(new { IsOk = true, Massage = "Ürün Guncellendi" })); } else { ModelState.AddModelError("", "Lütfen verilerı manipüle etmeyiniz"); string messages = ModelState.GetErrorsString(); return(Json(new { IsOk = false, Massage = messages })); } } else { ModelState.AddModelError("", "Lütfen gerekli tüm alanları doldurun."); string messages = ModelState.GetErrorsString(); return(Json(new { IsOk = false, Massage = messages })); } }
public ActionResult <Product> UpdateProduct([FromBody] ProductUpdateDto productUpdateDto, Guid productId, [FromHeader] Guid accountId, [FromHeader] string key) { try { if (!auth.AuthorizeUser(key)) { return(StatusCode(StatusCodes.Status401Unauthorized, "Authorization failed!")); } if (productUpdateDto.AccountId != accountId) { return(StatusCode(StatusCodes.Status403Forbidden, "Not allowed! User does not have permission!")); } var oldProduct = productRepository.GetProductById(productId); if (oldProduct == null) { return(NotFound()); } Product newProduct = mapper.Map <Product>(productUpdateDto); productRepository.UpdateProduct(oldProduct, newProduct); productRepository.SaveChanges(); logger.Log(LogLevel.Information, contextAccessor.HttpContext.TraceIdentifier, "", "Product updated", null); return(Ok(oldProduct)); } catch (Exception ex) { logger.Log(LogLevel.Error, contextAccessor.HttpContext.TraceIdentifier, "", "Update error", null); return(StatusCode(StatusCodes.Status500InternalServerError, ex.Message)); } }
public async Task <IActionResult> UpdateProduct(int userId, int id, ProductUpdateDto productUpdateDto) { if (await _repo.ProductExists(id)) { var productFromRepo = await _repo.GetProduct(id); try { if (productUpdateDto.Media.Count > 0) { ICollection <MediaDto> tempMediaList = new List <MediaDto>(productUpdateDto.Media); foreach (MediaDto m in tempMediaList) { if (m.Status == "Temp") { m.Status = "Saved"; } if (m.Status == "Delete") { if (m.IsMain) { return(BadRequest("You can not delete your main photo")); } if (m.Type == "image" || m.Type == "file") { if (m.Url != null) { var fileName = m.Url; var filePath = Path.Combine(Directory.GetCurrentDirectory(), @"wwwroot\images", fileName); if (System.IO.File.Exists(filePath)) { System.IO.File.Delete(filePath); } } } productUpdateDto.Media.Remove(m); } } } } catch { } productFromRepo.TimeStamp = DateTime.Now; _mapper.Map(productUpdateDto, productFromRepo); if (await _repo.SaveAll()) { return(NoContent()); } throw new Exception($"Updating product {id} failed on save"); } throw new Exception($"No product Id: {id}"); }
public async Task UpdateProduct(ProductUpdateDto input) { var product = await _productRepository.GetAllIncluding(p => p.Translations) .FirstOrDefaultAsync(p => p.Id == input.Id); product.Translations.Clear(); ObjectMapper.Map(input, product); }
public async Task <IViewComponentResult> InvokeAsync(UpdateModalViewModel model) { ViewBag.ModalModel = new ModalViewModel(model.Name, model.Submit); Product product = await productService.GetByIdAsync(model.Id); ProductUpdateDto vm = product != null?mapper.Map <ProductUpdateDto>(product) : new ProductUpdateDto(); return(View(vm)); }
public async Task UpdateProductAsync(Guid productId, [FromBody] ProductUpdateDto model, CancellationToken cancellationToken = default) { var command = _mapper.Map <ProductUpdateCommand>(model); command.ProductId = productId; await _mediator.Send(command, cancellationToken); Response.StatusCode = StatusCodes.Status204NoContent; }
public void Update(int id, ProductUpdateDto model) { var entry = _context.Products.Single(x => x.ProductId == id); entry.Name = model.Name; entry.Description = model.Description; entry.Price = model.Price; _context.SaveChanges(); }
private bool UpdateProduct(string productName, ProductUpdateDto updates) { if (productServices.UpdateProduct(productName, updates)) { return(true); } return(false); }
public async Task Update(int id, ProductUpdateDto model) { var entry = await _context.Products.SingleAsync(x => x.ProductId == id); entry.Name = model.Name; entry.Description = model.Description; entry.Price = model.Price; await _context.SaveChangesAsync(); }
public async Task UpdateProduct(string id, ProductUpdateDto productDto) { var product = _mapper.Map <Product>(productDto); var productDb = await _unitOfWork.Product.GetProductAsync(id, false); product.ID = id; product.AuctionID = productDb.AuctionID; _unitOfWork.Product.UpdateProduct(product); await _unitOfWork.SaveAsync(); }
public async Task <IActionResult> UpdateProduct(int Id, [FromBody] ProductUpdateDto productDto) { var productById = await _productService.UpdateProduct(Id, productDto); if (productById.Equals("oK")) { return(Ok()); } return(BadRequest()); }
public async Task <IHttpActionResult> Update(Guid id, ProductUpdateDto productUpdate) { var product = Mapper.Map <Product>(productUpdate); product.Id = id; var updatedProduct = await _productRepository.UpdateAsync(product); return(Ok(Mapper.Map <ProductDto>(updatedProduct))); }
public ActionResult UpdateProduct(int Id, ProductUpdateDto productUpdateDto) { var productModelFromRepo = productRepository.GetProductById(Id); mapper.Map(productUpdateDto, productModelFromRepo); productRepository.UpdateProduct(productModelFromRepo); productRepository.SaveChanges(); return(NoContent()); }
public async Task <IActionResult> UpdateProduct(ProductUpdateDto updatedProduct) { ServiceResponse <ProductGetDto> response = await _productService.UpdateProduct(updatedProduct); if (response.Data == null) { return(NotFound(response)); } return(Ok(response)); }