Esempio n. 1
0
        public async Task Put_ShouldReturnOk_WhenUserIsAdminAndDataIsValid()
        {
            await AuthenticateAdminAsync();

            var addProduct = new AddProduct
            {
                Name          = "testProduct",
                Calories      = 100,
                Proteins      = 10,
                Carbohydrates = 15,
                Fats          = 10,
                CategoryName  = "Meat"
            };

            var createdProduct = await _client.CreatePostAsync("/api/products", addProduct);

            var updateProduct = new UpdateProduct
            {
                ProductId     = createdProduct.Id,
                Name          = createdProduct.Name,
                Calories      = createdProduct.Calories + 20,
                Proteins      = createdProduct.Proteins,
                Carbohydrates = createdProduct.Carbohydrates,
                Fats          = createdProduct.Fats,
                CategoryName  = createdProduct.CategoryName
            };

            var response = await _client.PutAsJsonAsync("/api/products", updateProduct);

            response.EnsureSuccessStatusCode();
            response.StatusCode.ShouldBe(HttpStatusCode.OK);
        }
Esempio n. 2
0
        public HttpResponseMessage isUpdateProduct(UpdateProduct product)
        {
            //string result = "";
            BooleanMessage bm = new BooleanMessage();

            Business business = new Business();

            try
            {
                bm = business.isUpdateProduct(product);
            }
            catch (Exception ex)
            {
                business.addErrorLog("WebApi", "isUpdateProduct", ex.Message);
                //Utility.ErrorMessageToLogFile(ex);
                //throw;
            }

            string result = JsonConvert.SerializeObject(bm);

            return(new HttpResponseMessage()
            {
                Content = new StringContent(result)
            });
        }
Esempio n. 3
0
        public IActionResult Put(UpdateProduct model)
        {
            var product = _mapper.Map <Product>(model);

            _productService.UpdateProduct(product);
            return(Ok());
        }
Esempio n. 4
0
        public void Test_UpdateStock(int id)
        {
            var fakeContext = new FakeContext("UpdateProduct_Helper");

            fakeContext.FillWithAll();

            using (var context = new MainContext(fakeContext.FakeOptions, fakeContext.FakeConfiguration().Object))
            {
                var productRepository = new ProductRepository(context);
                var repository        = new SaleRepository(context);
                var productService    = new Mock <IProductService>();
                productService.Setup(x => x.GetById(It.IsAny <int>())).Returns(productRepository.GetById(id));
                productService.Setup(x => x.Update(It.IsAny <int>(), It.IsAny <Product>()))
                .Returns <int, Product>((productId, product) => "{ Message = Produto alterado com sucesso. }");
                var update = new UpdateProduct(productService.Object);

                var oldSale = repository.GetById(id);
                var newSale = new Sale();
                newSale.ProductId = id;
                newSale.Quantity  = 15;
                update.UpdateStock(newSale, oldSale);

                Assert.Equal(115, productRepository.GetById(id).Quantity);
            }
        }
Esempio n. 5
0
 public void Any(UpdateProduct request)
 {
     using (var db = DbFactory.OpenDbConnection())
     {
         db.Update(request.Product);
     }
 }
Esempio n. 6
0
        public void WithEmptyCode_ShouldThrowException()
        {
            var product = ProductFactory.Create();
            var command = new UpdateProduct("", product.Name, product.Price);

            Assert.That(() => product.Update(command), Throws.TypeOf <ProductCodeEmpty>());
        }
Esempio n. 7
0
        public async Task <IActionResult> PutAsync(string id, [FromBody] UpdateProduct command)
        {
            if (!ModelState.IsValid)
            {
                return(BadRequest(ModelState));
            }

            var toBeUpdatedProduct = _productRepository.GetAsync(id);

            if (toBeUpdatedProduct == null)
            {
                return(NotFound());
            }
            else if (command.Id == null)
            {
                command.Id = id;
            }

            Product product = Mapper.Map <Product>(command);
            await _productRepository.UpdateAsync(product);

            // send event
            ProductUpdated e = Mapper.Map <ProductUpdated>(product);
            await _messagePublisher.PublishMessageAsync(e.MessageType, e, "");

            return(NoContent());
        }
        public async Task <IActionResult> UpdateProductAsync(int id, UpdateProduct command)
        {
            command.Id = id;
            var result = await _mediator.Send(command);

            return(Ok(result));
        }
Esempio n. 9
0
        public void UpdateProduct_ReturnsUpdatedObject()
        {
            //ARRANGE --- 
            HttpStatusCode statusCode = 0;
            const string PRODUCT_NAME = "White Wine";
            const string SITE = "http://localhost:50712";
            const string PRODUCT_LINK = "/products/2";

            var client = new JsonServiceClient(SITE)
            {
                //grabbing the header once the call is ended.
                LocalHttpWebResponseFilter =
                    httpRes =>
                    {
                        statusCode = httpRes.StatusCode;
                    }
            };

            var updateProduct = new UpdateProduct
            {
                Name = PRODUCT_NAME,
                Status = new Status { Id = 2 } // Id = 2 means inactive.
            };

            //ACT  ------ 
            var product = client.Put<ProductResponse>(PRODUCT_LINK, updateProduct);

            //ASSERT ---- 
            Assert.IsTrue(statusCode == HttpStatusCode.OK);
            Assert.IsTrue(product.Name == PRODUCT_NAME);
            Assert.IsTrue(product.Status.Id == 2);
        }
Esempio n. 10
0
        public async Task <ServiceResponse <Product> > Update(Guid id, UpdateProduct request)
        {
            try
            {
                var result = await _baseRepository.GetById(id);

                if (result == null)
                {
                    return(new ServiceResponse <Product>($"The requested Product could not be found"));
                }

                result.Name            = request.Name;
                result.Description     = request.Description;
                result.Manufacturer    = request.Manufacturer;
                result.ReOrderLevel    = request.ReOrderLevel;
                result.StockType       = request.StockType;
                result.FactoryPrice    = request.FactoryPrice;
                result.SubBrandId      = request.SubBrandId;
                result.SubCategoryId   = request.SubCategoryId;
                result.ImageUrl        = request.ImageUrl;
                result.VatId           = request.VatId;
                result.UnitOfMeasureId = request.UnitOfMeasureId;
                result.LastUpdated     = DateTime.Now;

                await _baseRepository.Update(id, result);

                return(new ServiceResponse <Product>(result));
            }
            catch (Exception ex)
            {
                return(new ServiceResponse <Product>($"An Error Occured While Updating The Product. {ex.Message}"));
            }
        }
        private void BtnUpdateProduct_Click(object sender, EventArgs e)
        {
            UpdateProduct updateProduct = new UpdateProduct();

            this.Hide();
            updateProduct.Show();
        }
Esempio n. 12
0
        public async Task <ActionResult> UpdateProduct(string updateProductCustomizeID = "", string productTypeID = "", string productCustomizeID = "", string productName = "", string productUnitName = "", string updateMemberID = "")
        {
            BooleanMessage bm = new BooleanMessage();

            try
            {
                UpdateProduct updateProduct = new UpdateProduct();

                updateProduct.UpdateProductCustomizeID = updateProductCustomizeID;
                updateProduct.ProductTypeID            = productTypeID;
                updateProduct.ProductCustomizeID       = productCustomizeID;
                updateProduct.ProductName     = productName;
                updateProduct.ProductUnitName = productUnitName;
                updateProduct.UpdateMemberID  = updateMemberID;



                bm = await isUpdateProduct(updateProduct);
            }
            catch (Exception ex)
            {
                bm.Message = ex.Message;
            }

            if (bm.Result == true)
            {
                return(RedirectToAction("Index"));
            }
            else
            {
                return(HttpNotFound());
            }
        }
Esempio n. 13
0
        public async Task <IActionResult> Update([FromBody] UpdateProduct data, [FromHeader] string CompanyId)
        {
            if (ModelState.IsValid)
            {
                var idsHasPermission = await _productRepository.HasPermission(new List <string>() { data.Id });

                if (idsHasPermission.Count == 0)
                {
                    return(Unauthorized());
                }
                data.UpdatedBy = User.Claims.FirstOrDefault(s => s.Type == "userName").Value;
                data.CompanyId = CompanyId;
                var result = await _updateProductRequestClient.Request(data);

                if (result.Id != "-1")
                {
                    return(Ok(result));
                }
                else
                {
                    return(BadRequest("productCodeExisted"));
                }
            }
            return(BadRequest(ModelState));
        }
        public static void updateProduct(Dictionary <String, TextBox> productValueLabels, BindingNavigator bindingNavigatorProducts,
                                         UpdateProduct updateProductForm, int productId)
        {
            if (!validateFields(productValueLabels))
            {
                return;
            }

            try
            {
                int currentPage = bindingNavigatorProducts.BindingSource.Position;

                UpdateProductDAO.updateProduct(productValueLabels["LABEL"].Text, productValueLabels["CATEGORY"].Text, int.Parse(productValueLabels["RESERVE"].Text),
                                               float.Parse(productValueLabels["SELLING_PRICE"].Text), productValueLabels["MANUFACTURER"].Text, productId);


                foreach (KeyValuePair <string, Label> entry in App.GetProductLabels())
                {
                    entry.Value.DataBindings.Clear();
                }

                db.BindProductsData(App.GetProductLabels(), bindingNavigatorProducts);

                bindingNavigatorProducts.BindingSource.Position = currentPage;

                // Updated!
                updateProductForm.Close();
            }
            catch (SqlException e)
            {
                ViewMessages.ExceptionOccured(e);
            }
        }
        public async Task <Result <Product> > Handle(UpdateProduct command)
        {
            if (command == null)
            {
                throw Error.ArgumentNull(nameof(command));
            }

            var validationResult = await Validate(command);

            if (validationResult.IsFailure)
            {
                return(validationResult.As <Product>());
            }

            var productResult = await repository.GetById(command.Id);

            if (productResult.IsFailure)
            {
                return(productResult);
            }

            var product = productResult.Value;

            product.Apply(command);

            await auditService.RegisterUpdate(product);

            await repository.Update(product);

            return(Result.Ok(product));
        }
Esempio n. 16
0
        public ActionResult <Product> UpdateProduct([FromRoute] int id, [FromBody] UpdateProduct model)
        {
            var storeProduct = Store.Products.FirstOrDefault(p => p.Id == id);

            if (storeProduct == null)
            {
                return(NotFound("Ürün bulunamadı!"));
            }

            if (string.IsNullOrEmpty(model.Name))
            {
                return(BadRequest("Ürün adı boş olamaz!"));
            }

            if (model.Price <= 0)
            {
                return(BadRequest("Ürün fiyatı 0'dan büyük olmalı!"));
            }

            //todo db üzerinde güncelleme yapılır.

            storeProduct.Name  = model.Name;
            storeProduct.Price = model.Price;

            return(Ok(storeProduct));
        }
Esempio n. 17
0
        public ProductDto PatchProduct(int id, [FromBody] JsonPatchDocument <UpdateProduct> requests)
        {
            if (requests == null)
            {
                throw new Exception("参数不能为空");
            }

            var model = ProductService.Current.Products.SingleOrDefault(s => s.Id == id);

            if (model == null)
            {
                throw new Exception("找不到对应的产品");
            }

            var toPatch = new UpdateProduct
            {
                Name        = model.Name,
                Description = model.Description,
                Price       = model.Price
            };

            requests.ApplyTo(toPatch, ModelState);

            model.Name        = toPatch.Name;
            model.Price       = toPatch.Price;
            model.Description = toPatch.Description;

            return(model);
        }
        /// <summary>
        ///
        /// </summary>
        /// <param name="updateProduct"></param>
        /// <param name="username"></param>
        /// <returns></returns>
        public async Task <Product> UpdateProduct(UpdateProduct updateProduct, string username)
        {
            try
            {
                _Logger.LogInformation("Validation Success");
                Product Product = await productService.GetProduct(updateProduct.ProductId);

                if (Product == null)
                {
                    throw new Exception($"No Product with Id {updateProduct.ProductId} exists in the DB");
                }
                Product.UpdatedDate = DateTimeOffset.Now;
                Product.UpdatedBy   = username;

                _Logger.LogDebug($"The Object which gets Updated into the DB :- {JsonConvert.SerializeObject(Product) }");
                Product ProductfromDB = await productService.UpdateProduct(Product);

                return(ProductfromDB);
            }
            catch (Exception ex)
            {
                _Logger.LogError($"Error Occured while processing the Add Request. {ex.Message}");
                throw;
            }
        }
Esempio n. 19
0
        public async Task <IActionResult> UpdateProduct(
            [FromForm] ProductForm form,
            [FromServices] GetProduct getProduct,
            [FromServices] UpdateProduct updateProduct,
            [FromServices] S3Client s3Client)
        {
            var product = getProduct.Do(form.Id);

            product.Description      = form.Description;
            product.Series           = form.Series;
            product.StockDescription = form.StockDescription;

            if (form.Images != null && form.Images.Any())
            {
                product.Images = new List <Image>();
                var results = await Task.WhenAll(UploadFiles(s3Client, form.Images));

                product.Images.AddRange(results.Select((path, index) => new Image
                {
                    Index = index,
                    Url   = path,
                }));
            }

            await updateProduct.Update(product);

            return(Ok());
        }
Esempio n. 20
0
        public async Task <IActionResult> Update(Guid id, [FromBody] UpdateProduct request)
        {
            request.Id = id;
            var response = await _whenUpdateProduct.Handle(request);

            return(Ok(response));
        }
Esempio n. 21
0
 public Product Update(UpdateProduct dto)
 {
     Name          = dto.Name;
     Description   = dto.Description;
     Price         = dto.Price;
     DeliveryPrice = dto.DeliveryPrice;
     return(this);
 }
Esempio n. 22
0
        public async Task <IActionResult> UpdateProduct(Guid id, UpdateProduct request)
        {
            _logger.LogInformation($"[PUT] /products/{id}");

            var result = await _productService.UpdateProductAsync(id, request);

            return(Ok(result));
        }
Esempio n. 23
0
        public void WithNegativePrice_ShouldThrowException()
        {
            var updatedPrice = -10;
            var product      = ProductFactory.Create();
            var command      = new UpdateProduct(product.Code, product.Name, updatedPrice);

            Assert.That(() => product.Update(command), Throws.TypeOf <PriceInvalid>());
        }
Esempio n. 24
0
        public async Task <IActionResult> Update([FromBody] UpdateProduct command, int id)
        {
            command.Id = id;

            Result <Product> result = await Mediator.Send(command);

            return(As(result, MapTo <ProductDto>));
        }
Esempio n. 25
0
        private void editToolStripMenuItem_Click(object sender, EventArgs e)
        {
            AddProduct p = new AddProduct(MyProduct);

            p.ShowDialog();
            UpdateProduct?.Invoke(this, EventArgs.Empty);
            //button1.BackColor = Color.Aqua;
        }
Esempio n. 26
0
 public void Apply(UpdateProduct command)
 {
     DepartamentId    = command.DepartamentId;
     Price            = command.Price;
     Quantity         = command.Quantity;
     ShortDescription = command.ShortDescription;
     Title            = command.Title;
 }
 public AdminProductsBlazorService(GetProducts getProducts, GetProduct getProduct, CreateProduct createProduct, DeleteProduct deleteProduct, UpdateProduct updateProduct)
 {
     _getProducts   = getProducts;
     _getProduct    = getProduct;
     _createProduct = createProduct;
     _deleteProduct = deleteProduct;
     _updateProduct = updateProduct;
 }
Esempio n. 28
0
        public async Task <IActionResult> CreateProduct(Guid productId, UpdateProduct command)
        {
            command.Id = productId;

            await _productCommandsHandler.Handle(command);

            return(NoContent());
        }
Esempio n. 29
0
        //PUT: /api/products
        public async Task <ActionResult> Put([FromBody] UpdateProduct command)
        {
            await DispatchAsync(command);

            _logger.LogInfo($"Product with id: {command.ProductId} updated.");

            return(Ok());
        }
Esempio n. 30
0
        public ResultBase UpdateProduct(UpdateProduct item)
        {
            var jsonTest = Newtonsoft.Json.JsonConvert.SerializeObject(item);
            var obj      = Newtonsoft.Json.JsonConvert.DeserializeObject <Product>(jsonTest);

            var result = productRepository.ReplaceOne(obj);

            return(result);
        }
Esempio n. 31
0
        public void UpdateProductName()
        {
            using (IDbConnection dbConnection = new SqliteConnectionFactory().Create())
            {
                var insertProduct = new InsertProduct();
                var product = new ProductDto {Name = "Product Name"};
                product.Id = (int) dbConnection.Query<Int64>(insertProduct.Query(product)).Single();

                var updateProduct = new UpdateProduct();
                dbConnection.Execute(updateProduct.NameForAllProducts("new name"));

                var selectProduct = new SelectProduct();
                ProductDto result = dbConnection.Query<ProductDto>(selectProduct.ById(product.Id)).Single();

                StringAssert.AreEqualIgnoringCase("new name", result.Name);
            }
        }
Esempio n. 32
0
 private void update_Click(object sender, EventArgs e)
 {
     UpdateProduct updateproduct = new UpdateProduct();
     updateproduct.Owner = this;
     string goodsid = textBox1.Text;
     string SQLString = "select * from goodsInfo where goodsid=" + goodsid;
     SqlDataReader reader = goods_methods.ExecuteReader(SQLString);
     reader.Read();
     string goodsid1 = reader.GetString(0);
     string goodsname = reader.GetString(1);
     string goodsprice = reader.GetSqlMoney(2).ToString();
     string goodsphotoid = reader.GetString(3);
     reader.Close();
     string SQLString1 = "select * from goodsphoto where goodsphotoid=" + goodsphotoid;
     SqlDataReader reader1 = goods_methods.ExecuteReader(SQLString1);
     reader1.Read();
     string photourl = reader1.GetString(1);
     reader1.Close();
     updateproduct.setValue(goodsid1, goodsname, goodsprice, goodsphotoid, photourl);
     updateproduct.ShowDialog();
 }
Esempio n. 33
0
 private void insert_Click(object sender, EventArgs e)
 {
     UpdateProduct updateproduct = new UpdateProduct();
     updateproduct.Owner = this;
     updateproduct.ShowDialog();
 }
Esempio n. 34
0
        public object Delete(UpdateProduct request)
        {
            var product = documentSession.Load<Product>(request.Id);
            if (product == null)
                HttpError.NotFound("Product not found!");

            documentSession.Delete(product);
            documentSession.SaveChanges();

            return
                new HttpResult
                    {
                        StatusCode = HttpStatusCode.NoContent,
                    };
        }
Esempio n. 35
0
        public object Put(UpdateProduct request)
        {
            var product = documentSession.Load<Product>(request.Id);
            if (product == null)
                HttpError.NotFound("Product not found!");

            product.PopulateWith(request);

            documentSession.Store(product);
            documentSession.SaveChanges();

            return new ProductDto().PopulateWith(product);
        }