private async Task <TResponse <bool> > CanUpdate(UpdateProductModel request)
        {
            try
            {
                var product = await ReadOnlyRepository.QueryFirstOrDefaultAsync <ProductModel>(SqlQuery.PRODUCT_FIND_BY_NAME_AND_ID,
                                                                                               new
                {
                    request.Name,
                    request.Id
                });

                if (product.IsSuccess)
                {
                    if (product.Data != null)
                    {
                        return(await Fail <bool>(ErrorEnum.PRODUCT_HAS_EXIST.GetStringValue()));
                    }

                    return(await Ok(true));
                }

                return(await Fail <bool>(product.Message));
            }
            catch (Exception exception)
            {
                return(await Fail <bool>(exception));
            }
        }
Beispiel #2
0
 public async Task <ActionResult <int> > UpdateProduct([FromBody] UpdateProductModel value)
 {
     return(Ok(await _mediator.Send(new UpdateProductRequest()
     {
         Model = value
     })));
 }
        public IActionResult UpdateProduct([FromBody] UpdateProductModel model)
        {
            try
            {
                var getProductResponse = _productRepository.GetById(model.ProductId);

                if (!getProductResponse.isStatusCodeSuccess() || getProductResponse.Data == null)
                {
                    return(NotFound());
                }

                var updateResponse = _productRepository.Update(model.ToEntity(getProductResponse.Data));

                if (updateResponse.isStatusCodeSuccess() && updateResponse.Data != null)
                {
                    return(StatusCode(updateResponse.StatusCode, ProductModel.ToModel(updateResponse.Data)));
                }
                else
                {
                    return(StatusCode(updateResponse.StatusCode));
                }
            }
            catch (Exception e)
            {
                return(InternalServerError());
            }
        }
Beispiel #4
0
        public async Task <Guid> UpdateProduct(UpdateProductModel product)
        {
            _logger.LogInformation(Resources.UpdatingProductLogMessage, product.ProductId);
            Guid updateProduct = await _dal.UpdateProduct(product);

            return(updateProduct);
        }
        internal async Task <Guid> UpdateProduct(UpdateProductModel product)
        {
            var tIdParam      = GetParameter(Resources.ProductIdParameterName, product.ProductId);
            var productReader = GetDataReader(Resources.GetProductByIdProc, new List <DbParameter> {
                tIdParam
            });

            if (!productReader.HasRows)
            {
                await productReader.CloseAsync();

                throw new Exception(string.Format(Resources.ProductDoesNotExistsErrorMessage, product.ProductId));
            }

            await productReader.CloseAsync();

            var idParam = GetParameter(Resources.IdParameter, product.ProductId);
            var descriptionParameter = GetParameter(Resources.ProductDescriptionParameterName, product.Description);
            var priceParameter       = GetParameter(Resources.ProductPriceParameterName, product.Price);
            var reader = GetDataReader(Resources.UpdateProductProc, new List <DbParameter> {
                idParam, descriptionParameter, priceParameter
            });

            if (reader.HasRows)
            {
                await reader.ReadAsync();
            }

            var resultantId = reader.GetGuid(0);
            await reader.CloseAsync();

            return(resultantId);
        }
        public UpdateProductResultModel Update(long id, UpdateProductModel model)
        {
            BaseClient client = new BaseClient();
            string     url    = "products/Update/" + id;

            return(client.Post <UpdateProductResultModel, UpdateProductModel>(url, model));
        }
Beispiel #7
0
 public async Task <ActionResult <ProductModel> > UpdateAsync(
     Guid id,
     [FromBody] UpdateProductModel model,
     CancellationToken cancellationToken
     )
 {
     return(Ok(await mediator.Send(new UpdateProduct(id, model), cancellationToken)));
 }
        public async Task <TResponse <bool> > Update(int userId,
                                                     UpdateProductModel request,
                                                     int permissionId)
        {
            try
            {
                var checkValid = await _userService.CheckPermission(userId,
                                                                    permissionId);

                if (checkValid.IsSuccess)
                {
                    var canUpdate = await CanUpdate(request);

                    if (canUpdate.IsSuccess)
                    {
                        var result = await WriteRepository.ExecuteAsync(SqlQuery.PRODUCT_UPDATE,
                                                                        new
                        {
                            request.Id,
                            request.Name,
                            request.ImportPrice,
                            request.SellPrice,
                            request.MinCount,
                            request.MaxCount,
                            request.WarrantyMonth,
                            request.ProductUnitId,
                            request.ProductGroupId,
                            request.ProductStatusId,
                            request.ManufacturerId,
                            request.CountryId,
                            request.Description,
                            UserUpdated = userId,
                            DateUpdated = DateTime.Now
                        });

                        if (result.IsSuccess)
                        {
                            if (result.Data > 0)
                            {
                                return(await Ok(true));
                            }

                            return(await Fail <bool>(ErrorEnum.BAD_REQUEST.GetStringValue()));
                        }

                        return(await Fail <bool>(result.Message));
                    }

                    return(await Fail <bool>(canUpdate.Message));
                }

                return(await Fail <bool>(checkValid.Message));
            }
            catch (Exception exception)
            {
                return(await Fail <bool>(exception));
            }
        }
        public async Task <UpdateProductModel> Update(string id, UpdateProductModel p)
        {
            var product = await GetById(id);

            _mapper.Map(p, product);
            await _products.ReplaceOneAsync(p => p.Id == id, product);

            return(p);
        }
        public async Task UpdateAsync(UpdateProductModel product)
        {
            var existingProduct = await _db.Products.SingleOrDefaultAsync(x => x.Id == product.Id);

            existingProduct.Name  = product.Name;
            existingProduct.Price = product.Price;

            await _db.SaveChangesAsync();
        }
Beispiel #11
0
        public ProductModel Update(UpdateProductModel product)
        {
            var apiClient  = new RestClient("http://localhost:2534/api");
            var apiRequest = new RestRequest($"products/{product.Id}", Method.PUT, DataFormat.Json);

            apiRequest.AddJsonBody(product);
            var apiResponse = apiClient.Execute <ProductModel>(apiRequest);

            return(apiResponse.Data);
        }
Beispiel #12
0
        public IActionResult Edit(UpdateProductModel product)
        {
            if (!ModelState.IsValid)
            {
                return(View(product));
            }

            _productService.Update(product);
            return(RedirectToAction("Index"));
        }
Beispiel #13
0
        public async Task <ActionResult <ProductDto> > UpdateProduct([FromForm] UpdateProductModel productModel)
        {
            var result = await _mediator.Send(new UpdateProductCommand
            {
                ProductDto = _mapper.Map <ProductDto>(productModel),
                Photo      = productModel.Photo != null ? new FileAdapter(productModel.Photo) : null
            });

            return(Ok(result));
        }
Beispiel #14
0
 public void UpdateProduct(UpdateProductModel model)
 {
     if (ModelState.IsValid)
     {
         //
     }
     else
     {
         BadRequest();
     }
 }
        public ActionResult UpdateProduct([FromBody] UpdateProductModel model)
        {
            var result = _productService.UpdateProduct(
                new Product
            {
                ProductName        = model.ProductName,
                ProductDescription = model.ProductDescription,
                Amount             = model.Amount
            });

            return(Ok(result));
        }
Beispiel #16
0
        public IActionResult Edit(string id)
        {
            var product = _productService.Get(id);
            var model   = new UpdateProductModel()
            {
                Id       = product.Id,
                Category = product.Category,
                Name     = product.Name
            };

            return(View(model));
        }
 public IHttpActionResult UpdateProduct(int productId, UpdateProductModel model)
 {
     if (model == null)
     {
         return(NotFound());
     }
     if (model.ProductId != productId)
     {
         return(NotFound());
     }
     return(Ok());
 }
        //[ValidateInput(false)]
        public ActionResult UpdateProduct(UpdateProductModel Model)
        {
            try
            {
                _UserName = System.Web.HttpContext.Current.User.Identity.Name + " - DataEntryApp";
                SearchHelper.DecodeModel(Model);

                _db.UpdateProduct(Model.ProductID,
                                  Model.ItemNumber,
                                  Model.ShortDescription ?? "",
                                  Model.Categories.Where(c => c != null).DefaultIfEmpty().Last(),
                                  Model.InfoTemplate,
                                  Model.AvailableInKitSetAsst,
                                  Model.MetaDescription ?? "",
                                  Model.AdditionalSpecs,
                                  Model.PleaseNote,
                                  Model.MetaKeyword ?? "",
                                  Model.KitSetincludes,
                                  Model.NewItemMeetingDate,
                                  Model.PrintGridDesc,
                                  Model.ProdCatSection,
                                  Model.ProdPageNmbr,
                                  Model.ProductnamePrint,
                                  Model.ProductPrintDesc,
                                  (!Model.ItemNumber.ToUpper().Contains("GP") ? Model.StyleClass : null), //don't add variant parents to GP items
                                  _UserName);

                _db.UpdateProductAttributes(Model.ProductID, string.Join(",", Model.Attributes?.Where(c => c != null)));
                _db.UpdateProductChemicals(Model.ProductID, string.Join(",", Model.Chemicals?.Where(c => c != null)));

                // don't add variants to GP items
                if (!Model.ItemNumber.ToUpper().Contains("GP"))
                {
                    _db.UpdateStyleTraitValueProducts(Model.ProductID, (Model.StyleTraitValues != null ? string.Join(",", Model.StyleTraitValues?.Where(c => c != null)) : ""));
                }

                return(Json(new
                {
                    Status = "Successful"
                }));
            }
            catch (Exception ex)
            {
                LoggingHelper.LogError(ex);

                return(Json(new
                {
                    Status = "Error",
                    Message = ex.Message
                }));
            }
        }
        public ActionResult Update(HttpPostedFileBase fileBase, UpdateProductModel updateProduct)
        {
            var    find = new ProductDAO().FindProduct(updateProduct.Id);
            string images;

            if (fileBase.ContentLength > 0)
            {
                string fileName = Path.GetFileNameWithoutExtension(fileBase.FileName);
                fileName += "_" + updateProduct.Id;
                fileName += Path.GetExtension(fileBase.FileName);

                string folderPath = Server.MapPath("~") + @"Images\product";

                if (!Directory.Exists(folderPath))
                {
                    Directory.CreateDirectory(folderPath);
                }

                string path = Path.Combine(folderPath, fileName);

                fileBase.SaveAs(path);
                images = fileName;
            }
            else
            {
                images = find.images;
            }
            var product = new Product()
            {
                prId        = updateProduct.Id,
                prName      = updateProduct.Name,
                images      = images,
                cateId      = updateProduct.Category,
                prodId      = find.prodId,
                description = updateProduct.Description,
                price       = updateProduct.Price,
                amount      = updateProduct.Amounts
            };
            var dao = new ProductDAO().UpdateProduct(product);

            if (dao != null)
            {
                ViewBag.ProductId    = dao;
                ViewBag.Category     = new CategoryDAO().FindCategory(dao.cateId);
                ViewBag.Producer     = new ProducerDAO().FindProducer(dao.prodId);
                ViewBag.CaletedPr    = new ProductDAO().ProductCategoryDifferent(dao.prId);
                ViewBag.CategoryList = new CategoryDAO().ListAll();

                return(RedirectToAction("Update", new { id = dao.prId }));
            }
            return(RedirectToAction("NotFound", "Error"));
        }
Beispiel #20
0
        public async Task <IActionResult> UpdateProduct(UpdateProductModel model)
        {
            var productRequest = model.MapToFullRequest();

            HttpResponseMessage response = await PutAsync("products", productRequest);

            if (!response.IsSuccessStatusCode)
            {
                TempData["ProductErrorMessage"] = await response.Content.ReadAsStringAsync();
            }

            return(RedirectToAction(nameof(Index)));
        }
Beispiel #21
0
        public Products UpdateProduct(int id, UpdateProductModel updateProductModel)
        {
            var product = _context.Products.FirstOrDefault(x => x.ProductId == id);

            if (product != null)
            {
                product.ProductName = updateProductModel.Name;
                product.UnitPrice   = updateProductModel.UnitPrice;
                _context.SaveChanges();
            }

            return(product);
        }
 public ActionResult UpdataProductDescription(int id, UpdateProductModel model)
 {
     if (!model.IsValid())
     {
         return(BadRequest(ErrorModel.GetErrorModel(model.GetValidationResults())));
     }
     if (_productService.ProductByKey(id) is ProductDataModel p)
     {
         p.Description = model.Description;
         _productService.UpdateProduct(p);
         return(Ok());
     }
     return(NotFound(ErrorModel.GetErrorModel("Not found.", "Id", "Id does not exist.", HttpStatusCode.NotFound)));
 }
Beispiel #23
0
        public async Task <UpdateProductModel> Update(string id, UpdateProductModel p, IFormFile picture)
        {
            var product = await GetById(id);

            _mapper.Map(p, product);
            if (picture != null)
            {
                var imgId = UploadedFile(1, picture);
                product.ThumbnailId = imgId;
            }
            await _products.ReplaceOneAsync(p => p.Id == id, product);

            return(p);
        }
        public IActionResult Edit(IFormCollection valueCollection)
        {
            string code        = valueCollection["i_code"];
            string name        = valueCollection["i_name"];
            string description = valueCollection["i_description"];
            string priceStr    = valueCollection["i_price"];
            string idStr       = valueCollection["i_id"];
            string stock       = valueCollection["i_stock"];
            string versionStr  = valueCollection["i_version"];

            Decimal price = 0;

            Decimal.TryParse(priceStr, out price);

            long id = 0;

            long.TryParse(idStr, out id);

            Guid version = Guid.Empty;

            Guid.TryParse(versionStr, out version);

            ProductManagement  pm    = new ProductManagement();
            UpdateProductModel model = new UpdateProductModel()
            {
                Code        = code,
                Name        = name,
                Description = description,
                Price       = price,
                Version     = version
            };

            try{
                UpdateProductResultModel result = pm.Update(id, model);
            }
            catch (Exception ex)
            {
                return(new ContentResult()
                {
                    Content = "An error has occurred: " + Environment.NewLine + ex.Message
                });
            }

            // pm.Update(id,model);


            //FIX ME
            return(RedirectToAction("Search", null));
        }
Beispiel #25
0
        public async Task <IActionResult> Post([FromBody] UpdateProductModel model)
        {
            if (!ModelState.IsValid)
            {
                return(BadRequest(ModelState));
            }

            var product = _mapper.Map <Product>(model);

            product = await _productyService.Create(product);

            var view = _mapper.Map <ProductModel>(product);

            return(Ok(view));
        }
    public async Task Attribute_Routing_Values_In_Url_Should_Bind_Parameter_FromBody()
    {
        var config = new HttpConfiguration();

        config.MapHttpAttributeRoutes();
        using (var server = new HttpTestServer(config)) {
            var    client = server.CreateClient();
            string url    = "http://localhost/api/Products/5";
            var    data   = new UpdateProductModel {
                Name = "New Name"     // NB: No ProductId in data
            };
            using (var response = await client.PostAsJsonAsync(url, data)) {
                Assert.AreEqual(HttpStatusCode.OK, response.StatusCode);
            }
        }
    }
Beispiel #27
0
        public async Task <IActionResult> UpdateProduct(int productId, UpdateProductModel updateProductModel, Guid?cartToken)
        {
            var cart = GetOrCreateCart(cartToken);

            var product = await GetProduct(productId);

            if (product == null)
            {
                return(NotFound("Product not found"));
            }

            cart.UpdateProduct(product, updateProductModel.Quantity);
            _cartContext.SaveChanges();

            return(Ok(MapToApiModel(cart)));
        }
Beispiel #28
0
        public async Task <IActionResult> Update([FromBody] UpdateProductModel updateProductModel)
        {
            try
            {
                if (String.IsNullOrWhiteSpace(updateProductModel.Name) ||
                    String.IsNullOrWhiteSpace(updateProductModel.Description) ||
                    String.IsNullOrWhiteSpace(updateProductModel.StoreId) ||
                    String.IsNullOrWhiteSpace(updateProductModel.QuantityUnit))
                {
                    return(BadRequest("At least one of required fields are empty!"));
                }

                if (updateProductModel.Price <= 0)
                {
                    return(BadRequest("Price must be greater than 0!"));
                }

                if (updateProductModel.Quantity < 0)
                {
                    return(BadRequest("Quantity cannot be less than 0!"));
                }

                var product = Uow.ProductRepository.Get(updateProductModel.Id);
                if (product == null)
                {
                    return(NotFound("Product with given Id was not found!"));
                }

                var store = Uow.StoreRepository.Get(updateProductModel.StoreId);
                if (store == null)
                {
                    return(NotFound("Store with given Id was not found!"));
                }

                var entity         = Mapper.Map(updateProductModel, product);
                var updatedProduct = Uow.ProductRepository.Update(entity);

                await Uow.CompleteAsync();

                return(Ok(Mapper.Map <ProductModel>(Mapper.Map <ProductModel>(updatedProduct))));
            }
            catch (Exception e)
            {
                Console.WriteLine(e);
                return(InternalServerError());
            }
        }
        public async Task <IActionResult> Update(string productId, UpdateProductModel product)
        {
            var apiRep = new APIResponse();

            if (!(await _productService.IsExisting(productId)))
            {
                apiRep.Data  = null;
                apiRep.Error = false;

                return(Ok(apiRep));
            }
            var p = await _productService.Update(productId, product);

            apiRep.Data  = p;
            apiRep.Error = false;
            return(Ok(apiRep));
        }
Beispiel #30
0
        public IActionResult AddProduct([FromBody] UpdateProductModel product)
        {
            if (product == null)
            {
                return(BadRequest());
            }
            var productDto = new ProductDto()
            {
                Category    = product.Category,
                Collection  = product.Collection,
                Description = product.Description,
                LusId       = product.LusId,
                Name        = product.Name,
                Provider    = product.Provider,
                Type        = product.Type
            };

            //_productService.AddProduct(productDto);
            return(Ok());
        }