public void TestProductServiceAfterUpdated() { var dbcontext = new MemoryDbContext { Products = new MemDbSet <Product>() }; var productService = new ProductService(dbcontext); var productToCheck = new Product { Id = 1, Name = "123", Price = 100 }; productService.Add(productToCheck); productService.Add(new Product { Id = 2, Name = "123", Price = 350 }); var productToCheck2 = new Product { Id = 1, Name = "333", Price = 0 }; productService.Update(productToCheck2); productToCheck2 = new Product { Id = 2, Name = "333", Price = 10 }; productService.Update(productToCheck2); Assert.AreEqual(productService.Sum, 10); }
public void Product_TestService_AddProduct_ShouldBeOk() { _mockRepository.Setup(pr => pr.Save(_product)).Returns(_product); Product resultadoEncontrado = _servico.Add(_product); _mockRepository.Verify(pr => pr.Save(_product)); resultadoEncontrado.Id.Should().BeGreaterThan(0); }
public void Should_Add_New_Product() { var result = service.Add(new AddProductCommand() { Name = "NEW PRODUCT", Price = 3, Stock = 3 }).Result; result.Success.Should().BeTrue(); result.Value.Name.Should().Be("NEW PRODUCT"); }
public void ProductInegration_Add_ShouldBeOk() { _product = ObjectMother.GetProductSql(); var id = 2; _expectedProduct = _service.Add(_product); _expectedProduct.Should().NotBeNull(); _expectedProduct.Name.Should().Be(_product.Name); _expectedProduct.Id.Should().Be(id); }
public void VerifyAddProductAndInventoryWarehouses() { Product.Inventory.Warehouses = new List <Warehouse> { new Warehouse("MOEMA", 3, "PHYSICAL_STORE") }; var result = _productServices.Add(Product); Assert.AreEqual(result.Sku, 43265); Assert.GreaterOrEqual(result.Inventory.Quantity, 1); }
public void Product_Service_Add_Sucessfully() { //Cenário var product = ObjectMother.ProductValidWithoutId(); var productCmd = ObjectMother.ProductCommandToRegister(); _mockProductRepository.Setup(pr => pr.Add(It.IsAny <Product>())).Returns(product); //Ação var addProduct = _productService.Add(productCmd); //Verificar _mockProductRepository.Verify(pr => pr.Add(It.IsAny <Product>()), Times.Once); addProduct.Should().Be(product.Id); }
public void TestIfCreatedProductIsTheSameAsTheInsertedProduct(int id, int uid, string name, string desc, string pic, double price, DateTime experation, Category category) { //ARRANGE experation = DateTime.Now.AddDays(1); var insertedProduct = new Product() { Category = category, ProductId = id, Name = name, Description = desc, PictureUrl = pic, CurrentPrice = price, Expiration = experation, UserId = uid }; ProductService ps = new ProductService(_repoMock.Object); _repoMock.Setup(repo => repo.Add(insertedProduct)).Returns(() => insertedProduct); //ACT var createdProduct = ps.Add(insertedProduct); //ASSERT Assert.Equal(insertedProduct, createdProduct); }
public async Task AddWithInvalidCategory() { //Arrange var cloudinaryService = new Mock <ICloudinaryService>().Object; var mapperConfig = new MapperConfiguration(x => x.AddProfile(new MappingProfile())); var mapper = mapperConfig.CreateMapper(); var categoryService = new CategoryService(this.context, cloudinaryService, mapper); var userService = new Mock <IUserService>().Object; var productService = new ProductService(this.context, cloudinaryService, mapper, categoryService, userService); var productDto = new ProductDto() { Name = "Product", CategoryName = "InvalidCategory" }; //Act var result = await productService.Add(productDto); //Assert Assert.False(result); }
public void AddProductWhoExists_ExpectInvalidArgumentException() { // ARRANGE Product product = new Product() { Category = new Category() { Name = "Test Category " }, ProductId = 1, Name = "Blikspand", Description = "Lavet af ler", PictureUrl = "URLISGONE.PNG", CurrentPrice = 1000.00, Expiration = DateTime.Now.AddDays(1), UserId = 1 }; _repoMock.Setup(repo => repo.Get(It.Is <int>(x => x == product.ProductId))).Returns(() => product); ProductService us = new ProductService(_repoMock.Object); // ACT var ex = Assert.Throws <InvalidOperationException>(() => us.Add(product)); // ASSERT Assert.Equal("Product already exists", ex.Message); _repoMock.Verify(repo => repo.Add(It.Is <Product>(p => p == product)), Times.Never); }
public ActionResult ProductAdd(Product product) //Parameter: HttpPostedFileBase file ... Sildim { ViewBag.categoryservice = categoryservice.GetAll(); ViewBag.brandservice = brandservice.GetAll(); ViewBag.pictureservice = pictureservice.GetAll(); var producr = productservice.Add(product); productservice.SaveChanges(); //string pic = System.IO.Path.GetFileName(file.FileName); //string path = System.IO.Path.Combine(Server.MapPath("~/Content/NiceAdmin/img"), pic); //// file is uploaded //file.SaveAs(path); //string picturepath = "Content/NiceAdmin/img/" + pic; //product.Resim = picturepath; //productservice.Add(product); //productservice.SaveChanges(); return(RedirectToAction("UrunDetayi", "Product", new { @id = producr.Id })); return(RedirectToAction("UrunDetayi")); }
public ActionResult Create(product product) { //ProductService ps = new ProductService(); //ps.Add(product); //ps.Commit(); //return RedirectToAction("Index"); product p = new product { name = product.name, idProduct = product.idProduct, isAvailable = product.isAvailable, price = product.price, quantity = product.quantity, idCategory = product.idCategory, // category = product.c, // product.category.idCategory. = category.idCategory, }; if (ModelState.IsValid) { ps.Add(p); ps.Commit(); } return(RedirectToAction("Index")); }
public void ReviewAlreadyReviewedProductTest() { ReviewService reviewService = getService(); OrderService orderService = getOrderService(); ProductService productService = getProductService(); User u = registerUser(); Product p = generateProduct(); Product p2 = new Product(); p2.Code = "1235"; p2.Description = "Desc"; p2.Manufacturer = "Manu"; p2.Name = "Name2"; p2.Price = 120; p2.Category = p.Category; productService.Add(p2); Guid orderId = orderService.GetActiveOrderFromUser(u).Id; orderService.AddProduct(u, p.Id); orderService.AddProduct(u, p2.Id); orderService.SetAddress(u, u.Address.Id); orderService.Ship(orderId); orderService.Pay(orderId); string reviewText = "Muy bueno"; reviewService.Evaluate(u, p.Id, orderId, reviewText); reviewService.Evaluate(u, p.Id, orderId, reviewText); }
public HttpResponseMessage Add(Product product) { try { if (product.ItemName.StartsWith("!,@,#,$,%,^,&,*,(,)._.+,=,-,],[,',;,/,.,>,<,?,|,`.~")) { throw new HttpResponseException(HttpStatusCode.NotModified); } else if (product.ItemPrice < 0) { throw new HttpResponseException(HttpStatusCode.NotModified); } else { var newproduct = new Product() { ItemName = product.ItemName, ItemPrice = product.ItemPrice, Description = product.Description, Quantity = product.Quantity }; productService.Add(newproduct); uow.Complete(); var message = Request.CreateResponse(HttpStatusCode.Created, product); message.Headers.Location = new Uri(Request.RequestUri + product.ID.ToString()); return(message); } } catch (Exception ex) { return(Request.CreateErrorResponse(HttpStatusCode.BadRequest, ex)); } }
public void Call_UnitOfWork_SaveChangesMethod_AfterAddInQuerable() { // Arange var expected = new List <int>() { 1, 2 }; var actual = new List <int>(); var productDto = ProductGenerator.GetProductDtos(1).First(); var product = ProductGenerator.GetProducts(1).First(); var mockedQuerable = new Mock <IEfQuerable <Product> >(); mockedQuerable.Setup(x => x.Add(product)).Callback(() => actual.Add(1)); var mockedUnitOfWork = new Mock <IEfUnitOfWork>(); mockedUnitOfWork.Setup(x => x.SaveChanges()).Callback(() => actual.Add(2)); var mockedMapperService = new Mock <IMapperService>(); mockedMapperService.Setup(x => x.Map(productDto)).Returns(product); var obj = new ProductService(mockedQuerable.Object, mockedUnitOfWork.Object, mockedMapperService.Object); // Act obj.Add(productDto); // Assert CollectionAssert.AreEqual(expected, actual); }
public ActionResult AddProduct(Product product) { EmptyInfo(); productService.Add(product); Saved(); return(RedirectToAction("AddProduct")); }
public object InsertProduct() { var model = new ProductInfo(); //model.Id = Convert.ToInt32(HttpContext.Current.Request.Params["id"]); model.Title = (string)HttpContext.Current.Request.Params["title"]; model.CategoryId = Convert.ToInt32(HttpContext.Current.Request.Params["productCategory"]); //model.Price = Convert.ToDouble(HttpContext.Current.Request.Params["price"]); model.Content = (string)HttpContext.Current.Request.Params["Content"]; model.Desc = (string)HttpContext.Current.Request.Params["Desc"];//产品简介 //model.IsOnline = HttpContext.Current.Request.Params["isonline"]; model.BigPicture = HttpContext.Current.Request.Params["bigpicture"]; model.SmallPicture = HttpContext.Current.Request.Params["smallpicture"]; model.MediumPicture = (string)HttpContext.Current.Request.Params["mediumpicture"]; model.Specifications = (string)HttpContext.Current.Request.Params["specifications"]; model.AfterService = (string)HttpContext.Current.Request.Params["afterservice"]; model.InDate = DateTime.Now; model.FileUrl = HttpContext.Current.Request.Params["filedown"]; model.Keywords = HttpContext.Current.Request.Params["Keywords"]; model.MetaDesc = HttpContext.Current.Request.Params["Description"]; model.DisplayOrder = OrderGenerator.NewOrder(); IProductService productService = new ProductService(); return(productService.Add(model) > 0); }
protected void Button1_Click(object sender, EventArgs e) { if (productService.IsExistProduct(TextBox1.Text.Trim())) { Label1.Text = "商品已经存在"; } else { string fileName; string fileFolder; string dateTime = ""; fileName = Path.GetFileName(FileUpload1.PostedFile.FileName); dateTime += DateTime.Now.Year.ToString(); dateTime += DateTime.Now.Month.ToString(); dateTime += DateTime.Now.Day.ToString(); dateTime += DateTime.Now.Hour.ToString(); dateTime += DateTime.Now.Minute.ToString(); dateTime += DateTime.Now.Second.ToString(); fileName = dateTime + fileName; fileFolder = Server.MapPath("~/") + "Prod_Images\\" + DropDownList1.SelectedItem.Text + "\\"; fileFolder = fileFolder + fileName; FileUpload1.PostedFile.SaveAs(fileFolder); productService.Add("~\\Prod_Images\\" + DropDownList1.SelectedItem.Text + "\\" + fileName, TextBox1.Text.Trim(), int.Parse(DropDownList1.SelectedValue), int.Parse(DropDownList2.SelectedValue), decimal.Parse(TextBox2.Text.Trim()), decimal.Parse(TextBox3.Text.Trim()), TextBox4.Text.Trim(), int.Parse(TextBox5.Text.Trim())); Response.Redirect("ProductMaster.aspx"); } }
public void TestIfDateOnBidIsOlderThanCurrentDateWhenCreated(string time) { //ARRANGE _products = new List <Product>(); ProductService ps = new ProductService(_repoMock.Object); Product p = new Product() { ProductId = 1, Name = "something", CurrentPrice = 200, IsSold = false, Expiration = DateTime.Parse(time), Description = "something", UserId = 1, CategoryId = 1, Category = null, Bids = null, PictureUrl = "no" }; //ACT var ex = Assert.Throws <ArgumentException>(() => ps.Add(p)); //ASSERT Assert.Equal("Auction end date must be after today", ex.Message); }
public void ScenarioA_Test() { //Initialize List <Product> product = new List <Product>(); ProductService.Add(new Product() { Id = "A" }); ProductService.Add(new Product() { Id = "B" }); ProductService.Add(new Product() { Id = "C" }); //Action ProductService productService = new ProductService(); int totalPrice = productService.GetTotalPrice(products); //Assert Assert.AreEqual <int>(100, totalPrice); }
public void Call_UnitOfWork_SaveChangesMethod_WhenProductIsValid() { // Arange var productDto = ProductGenerator.GetProductDtos(1).First(); var product = ProductGenerator.GetProducts(1).First(); var mockedQuerable = new Mock <IEfQuerable <Product> >(); mockedQuerable.Setup(x => x.Add(product)); var mockedUnitOfWork = new Mock <IEfUnitOfWork>(); mockedUnitOfWork.Setup(x => x.SaveChanges()).Verifiable(); var mockedMapperService = new Mock <IMapperService>(); mockedMapperService.Setup(x => x.Map(productDto)).Returns(product); var obj = new ProductService(mockedQuerable.Object, mockedUnitOfWork.Object, mockedMapperService.Object); // Act obj.Add(productDto); // Assert mockedUnitOfWork.Verify(x => x.SaveChanges(), Times.Once); }
public void ServiceLayer_Prod_Test() { //Arrange var options = new DbContextOptionsBuilder <EfstoreContext>() .UseInMemoryDatabase(databaseName: "WebstoreDB").Options; //ACT using (var op = new EfstoreContext(options)) { Products p = new Products(); p.ClothingID = 1; p.name = "Adiddas A1 Running"; p.Description = "Running Shoe with special Gel"; p.price = 300; p.status = "Instock"; var op1 = new ProductService(op); op1.Add(p); //Assert // Use a separate instance of the context to verify correct data was saved to database using (var context = new EfstoreContext(options)) { // Assert.AreEqual(1, context.Products.Count()); Assert.AreEqual(1, context.Products.Single().ClothingID); Assert.AreNotEqual(0, context.Products.Single().ClothingID); } { } } }
public ActionResult Create(ProductViewModel pvm, HttpPostedFileBase Image) { pvm.ImageUrl = Image.FileName; Product t = new Product { IdCategory = pvm.CategoryId, CreationDate = DateTime.Now, CurrentPrice = pvm.CurrentPrice, //IdUser = pvm.IdUser, Name = pvm.Name, reference = pvm.reference, status = false, UpdateDate = DateTime.Now, ImageUrl = pvm.ImageUrl }; ps.Add(t); ps.Commit(); // Sauvgarde de l'image var path = Path.Combine(Server.MapPath("~/Content/Upload/"), Image.FileName); Image.SaveAs(path); return(RedirectToAction("Index")); }
private void btnAddProduct_Click(object sender, EventArgs e) { if (txtProductName.Text.Trim() == "" || txtProductPrice.Text.Trim() == "" || cmbProductType.SelectedValue == null) { MessageBox.Show("اطلاعات وارد شده صحیح نیست."); return; } double d = 0; if (!double.TryParse(txtProductPrice.Text, out d)) { MessageBox.Show("مشکلی رخ داد. دوباره تلاش کنید."); return; } if (_productService.HasNameExists(txtProductName.Text)) { MessageBox.Show("محصولی با این نام وجود دارد. نام دیگری را وارد نمایید."); return; } _productService.Add(new Product() { Available = true, Description = txtProductDesc.Text, Name = txtProductName.Text, Price = d, Type = (ProductType)cmbProductType.SelectedValue }); _uow.SaveChanges(); ShowProducts(); ClearTextBoxes(); }
protected void btnSubmit_Click(object sender, EventArgs e) { var id = Guid.Parse(this.ddlLoanType.SelectedValue); int res = 0; var data = proSvc.GetProductByLoanTypeId(id); if (data == null) { data = new Model.Product() { LoanType_Id = Guid.Parse(this.ddlLoanType.SelectedValue), Product_Detail = this.txtProductContent.Value }; res = proSvc.Add(data); } else { data.LoanType_Id = Guid.Parse(this.ddlLoanType.SelectedValue); data.Product_Detail = this.txtProductContent.Value; res = proSvc.Edit(data); } var rm = res > 0 ? new ReturnMsg { Code = StatusCode.Ok, Message = "编辑产品介绍成功", Data = null } : new ReturnMsg { Code = StatusCode.Error, Message = "编辑产品介绍失败", Data = null }; Session["Msg"] = rm; Response.Redirect("Product_Info.aspx"); }
public ActionResult Add(Product data, HttpPostedFileBase Image) { List <string> UploadedImagePaths = new List <string>(); UploadedImagePaths = ImageUploader.UploadSingleImage(ImageUploader.OriginalProfileImagePath, Image, 1); data.ImagePath = UploadedImagePaths[0]; if (data.ImagePath == "0" || data.ImagePath == "1" || data.ImagePath == "2") { data.ImagePath = ImageUploader.DefaultProfileImagePath; data.ImagePath = ImageUploader.DefaultXSmallProfileImage; data.ImagePath = ImageUploader.DefaulCruptedProfileImage; } else { data.ImagePath = UploadedImagePaths[1]; data.ImagePath = UploadedImagePaths[2]; } data.Status = MaterialManagemenetProject.Core.Enum.Status.Active; _productService.Add(data); return(Redirect("/Admin/Product/List")); }
public ActionResult Add(Product product, HttpPostedFileBase ImagePath) { if (ModelState.IsValid) { product.ImagePath = ImageUploader.UploadImage("~/Content/images", ImagePath); if (product.ImagePath == "0") { ViewBag.Error = "Dosya Boş"; } else if (product.ImagePath == "1") { ViewBag.Error = "Zaten bu isimde dosya bulunmaktadır"; } else if (product.ImagePath == "2") { ViewBag.Error = "Dosya uzantısı belirtilenlere uymuyor"; } else { ViewBag.Produts = productService.GetAll(); productService.Add(product); return(RedirectToAction("Index")); } } return(View()); }
public IHttpActionResult Add([FromBody] ProductDTO productDTO) { var product = productDTO.ToProduct(); _productService.Add(product); return(Created(string.Format("{0}/{1}", Request.RequestUri, product.Id), product)); }
public void ProductService_Add_Message_LessThan4_ShouldBeFail() { // Inicio Cenário //Modelo Product modelo = new Product() { Id = 1, Name = "Ric", SalePrice = 6, CostPrice = 4, Disponibility = true, FabricationDate = DateTime.Now, ExpirationDate = DateTime.Now.AddMonths(4) }; //Serviço ProductService service = new ProductService(_mockRepository.Object); // Fim Cenário //Executa Action comparison = () => service.Add(modelo); //Saída comparison.Should().Throw <ProductNameLessThan4Exception>(); _mockRepository.VerifyNoOtherCalls(); }
public void ProductService_Add_ShouldBeOK() { // Inicio Cenário //Modelo Product modelo = new Product() { Id = 1, Name = "Rice", SalePrice = 6, CostPrice = 4, Disponibility = true, FabricationDate = DateTime.Now, ExpirationDate = DateTime.Now.AddMonths(4) }; //Mock _mockRepository.Setup(m => m.Save(modelo)).Returns(new Product() { Id = 1 }); //Serviço ProductService service = new ProductService(_mockRepository.Object); // Fim Cenário //Executa Product resultado = service.Add(modelo); //Saída resultado.Should().NotBeNull(); resultado.Id.Should().BeGreaterThan(0); _mockRepository.Verify(repository => repository.Save(modelo)); }
public JsonResult AddPost() { var id = Guid.NewGuid().ToString("n"); var name = RequestHelper.GetValue("name"); var des = RequestHelper.GetValue("des"); var traffic = RequestHelper.GetInt("traffic"); var expirationday = RequestHelper.GetInt("expirationday"); var price = RequestHelper.GetDecimal("price"); var isrest = RequestHelper.GetInt("isrest"); var sortnum = RequestHelper.GetInt("sortnum"); if (string.IsNullOrEmpty(name) || traffic <= 0 || expirationday <= 0 || price <= 0) { return(Json(new { result = false, info = "缺少必要参数。" }, JsonRequestBehavior.DenyGet)); } var dto = new ProductDto() { Id = id, Name = name, Description = des, Traffic = traffic, ExpirationDay = expirationday, Price = price, IsRest = (sbyte)isrest, SortNum = sortnum }; var result = ProductService.Add(dto); LogService.Info($"ProductService.Add >>> {result} --- {id}:{name}"); return(Json(new { result = result }, JsonRequestBehavior.DenyGet)); }
public void HtmlAgilityPack_Demo01() { var list = new List<string>(); list.Add("2"); list.Add("3"); list.Add("4"); list.Add("5"); list.Add("7"); list.Add("8"); list.Add("9"); list.Add("10"); list.Add("11"); list.Add("12"); list.Add("13"); list.Add("14"); list.Add("15"); list.Add("16"); list.Add("17"); list.Add("18"); list.Add("19"); list.Add("20"); list.Add("21"); list.Add("22"); list.Add("23"); list.Add("24"); list.Add("25"); list.Add("26"); list.Add("27"); list.Add("28"); list.Add("29"); list.Add("31"); foreach (string s in list) { var webGet = new HtmlWeb(); HttpClient httpClient1 = new HttpClient("http://www.yihui-lighting.com/productshow.asp?id="+s); HtmlAgilityPack.HtmlDocument htmlDocument1 = new HtmlAgilityPack.HtmlDocument(); htmlDocument1.LoadHtml(httpClient1.Request()); var document = htmlDocument1; var data = document.DocumentNode.SelectNodes("//*[@id=\"mitte2\"]"); StringBuilder sb = new StringBuilder(); int i = 0; foreach (HtmlNode htmlNode in data) { var images = document.DocumentNode.SelectNodes("//img"); if (images != null && images.Count > 0) { int j = 0; foreach (HtmlNode imageNode in images) { j++; WebClient webClient = new WebClient(); var dir = "images\\content"; string filepath = "z:\\upload\\" + dir; if (!Directory.Exists(filepath)) { Directory.CreateDirectory("z:\\upload\\" + dir); } if (imageNode.Attributes["src"].Value != null) { try { string url = "http://www.yihui-lighting.com/UpProduct"; downloadfile(url + "//" + imageNode.Attributes["src"].Value.Substring(imageNode.Attributes["src"].Value.LastIndexOf('/') + 1), imageNode.Attributes["src"].Value.Substring(imageNode.Attributes["src"].Value.LastIndexOf('/') + 1)); } catch { } } } } if (!string.IsNullOrEmpty(htmlNode.InnerText)) { // var titleNode = document.DocumentNode.SelectSingleNode( "/html/body/div/div[3]/div[3]/div[2]/div/h2/font"); var title = titleNode.InnerText??""; var body = htmlNode.InnerHtml.Replace("UpProduct/", "upload/images/content/")??""; var model = new ProductInfo(); model.Title = title; model.CategoryId = 2; model.Content = body; model.InDate = DateTime.Now; model.DisplayOrder = OrderGenerator.NewOrder(); IProductService productService = new ProductService(); try { productService.Add(model); } catch { } } } } }
public object InsertProduct() { var model = new ProductInfo(); //model.Id = Convert.ToInt32(HttpContext.Current.Request.Params["id"]); model.Title = (string)HttpContext.Current.Request.Params["title"]; model.CategoryId = Convert.ToInt32(HttpContext.Current.Request.Params["productCategory"]); //model.Price = Convert.ToDouble(HttpContext.Current.Request.Params["price"]); model.Content = (string)HttpContext.Current.Request.Params["Content"]; model.Desc = (string)HttpContext.Current.Request.Params["Desc"];//产品简介 //model.IsOnline = HttpContext.Current.Request.Params["isonline"]; model.BigPicture = HttpContext.Current.Request.Params["bigpicture"]; model.SmallPicture = HttpContext.Current.Request.Params["smallpicture"]; model.MediumPicture = (string)HttpContext.Current.Request.Params["mediumpicture"]; model.Specifications = (string)HttpContext.Current.Request.Params["specifications"]; model.AfterService = (string)HttpContext.Current.Request.Params["afterservice"]; model.InDate = DateTime.Now; model.FileUrl = HttpContext.Current.Request.Params["filedown"]; model.Keywords = HttpContext.Current.Request.Params["Keywords"]; model.MetaDesc = HttpContext.Current.Request.Params["Description"]; model.DisplayOrder = OrderGenerator.NewOrder(); IProductService productService = new ProductService(); return productService.Add(model) > 0; }
protected void btnSave_Click(object sender, EventArgs e) { var obj = new PRODUCT(); obj.PRODUCT_CODE = popTxtProductCode.Text; obj.PRODUCT_NAME = poptxtProductName.Text; obj.PRODUCT_PACKING_QTY = Convert.ToInt32(txtPacking.Text); if (ddlPakUDesc.SelectedValue != "กรุณาเลือก") obj.PRODUCT_PACKING_PER_UDESC = ddlPakUDesc.SelectedValue; if (ddlPakPDesc.SelectedValue != "กรุณาเลือก") obj.PRODUCT_PACKING_PER_PDESC = ddlPakPDesc.SelectedValue; obj.PRODUCT_PACKING_DESC = "(" + obj.PRODUCT_PACKING_QTY + " " + obj.PRODUCT_PACKING_PER_UDESC + "/" + obj.PRODUCT_PACKING_PER_PDESC + ")"; obj.PRODUCT_WEIGHT = Convert.ToDecimal(txtWeight.Text); obj.PRODUCT_WEIGHT_DEFINE = txtUnit.Text; obj.CATEGORY_ID = Convert.ToInt32(ddlCategory.SelectedValue); obj.PRODUCT_TYPE_CODE = Convert.ToInt32(ddlkind.SelectedValue); var cmd = new ProductService(obj); if (flag.Text.Equals("Add")) { obj.Action = ActionEnum.Create; obj.CREATE_DATE = DateTime.Now; obj.CREATE_EMPLOYEE_ID = 0; obj.UPDATE_DATE = DateTime.Now; obj.UPDATE_EMPLOYEE_ID = 0; obj.SYE_DEL = true; cmd.Add(); } else { obj.Action = ActionEnum.Update; obj.PRODUCT_ID = Convert.ToInt32(ViewState["proId"].ToString()); obj.UPDATE_DATE = DateTime.Now; obj.UPDATE_EMPLOYEE_ID = 0; obj.SYE_DEL = true; cmd.Edit(); } if (FileUpload1.HasFile) { Stream fs = FileUpload1.PostedFile.InputStream; if (!System.IO.Directory.Exists(HttpContext.Current.Server.MapPath("~") + "ImageProduct")) System.IO.Directory.CreateDirectory(HttpContext.Current.Server.MapPath("~") + "ImageProduct"); obj.PRODUCT_IMAGE_PATH = "~/ImageProduct/" + obj.PRODUCT_ID + "." + FileUpload1.FileName.Split('.').ToArray()[1]; FileUpload1.PostedFile.SaveAs(HttpContext.Current.Server.MapPath("~") + "ImageProduct\\" + obj.PRODUCT_ID + "." + FileUpload1.FileName.Split('.').ToArray()[1]); } cmd = new ProductService(obj); cmd.Edit(); var listDetail = new List<PRODUCT_PRICELIST>(); int i = 0; foreach (var item in DataSouceList) { var objDetail = new PRODUCT_PRICELIST(); objDetail.ZONE_ID = item.ZONE_ID; objDetail.PRODUCT_PRICE = Convert.ToDecimal(((TextBox)(gridProductDetail.Rows[i++].Cells[2].FindControl("txtPrice"))).Text); objDetail.SYE_DEL = true; objDetail.UPDATE_DATE = DateTime.Now; objDetail.UPDATE_EMPLOYEE_ID = 0; if (item.PRODUCT_ID == 0) { objDetail.Action = ActionEnum.Create; objDetail.PRODUCT_ID = obj.PRODUCT_ID; objDetail.CREATE_DATE = DateTime.Now; objDetail.CREATE_EMPLOYEE_ID = 0; } else { objDetail.Action = ActionEnum.Update; objDetail.PRODUCT_ID = item.PRODUCT_ID; } listDetail.Add(objDetail); } if (listPromotion.Count > 0) { foreach (PRODUCT_PROMOTION item in listPromotion) { item.PRODUCT_ID = obj.PRODUCT_ID; } var cmdPromotion = new ProductPromotionService(listPromotion); cmdPromotion.AddList(); } var cmdDetail = new ProductPriceListService(listDetail); cmdDetail.AddUpdateList(); ViewState["proId"] = null; Response.Redirect("SearchProduct.aspx"); }