public void tblProduct_insert(ProductDTO dt) { string sql = "INSERT INTO tblProduct(Title, AddedDate, AddedBy, LastModifyDate, LastModifyBy, Description, Excerpt, BodyContent, UnitPrice, UnitsInStock, Thumbnail, Category, Manufacture, PriorityOrder, IsDelete, Tag, Currency, Tax, Views, IsNew, Code, originalprice, DiscountPercentage, UnitPercent)" + " VALUES(@Title, @AddedDate, @AddedBy, @LastModifyDate, @LastModifyBy, @Description, @Excerpt, @BodyContent, @UnitPrice, @UnitsInStock, @Thumbnail, @Category, @Manufacture, @PriorityOrder, @IsDelete, @Tag, @Currency, @Tax, @Views, @IsNew, @Code, @originalprice, @DiscountPercentage, @UnitPercent)"; cmd = new SqlCommand(sql, ConnectionData._MyConnection); cmd.CommandType = CommandType.Text; cmd.Parameters.Add("@Title", SqlDbType.NVarChar).Value = dt.Title; cmd.Parameters.Add("@AddedDate", SqlDbType.DateTime).Value = dt.AddedDate; cmd.Parameters.Add("@AddedBy", SqlDbType.NVarChar).Value = dt.AddedBy; cmd.Parameters.Add("@LastModifyDate", SqlDbType.DateTime).Value = dt.LastModifyDate; cmd.Parameters.Add("@LastModifyBy", SqlDbType.NVarChar).Value = dt.LastModifyBy; cmd.Parameters.Add("@Description", SqlDbType.NVarChar).Value = dt.Description; cmd.Parameters.Add("@Excerpt", SqlDbType.NVarChar).Value = dt.Excerpt; cmd.Parameters.Add("@BodyContent", SqlDbType.NVarChar).Value = dt.BodyContent; cmd.Parameters.Add("@UnitPrice", SqlDbType.NVarChar).Value = dt.UnitPrice; cmd.Parameters.Add("@UnitsInStock", SqlDbType.Int).Value = dt.UnitsInStock; cmd.Parameters.Add("@Thumbnail", SqlDbType.NVarChar).Value = dt.Thumbnail; cmd.Parameters.Add("@Category", SqlDbType.Int).Value = dt.Category; cmd.Parameters.Add("@Manufacture", SqlDbType.Int).Value = dt.Manufacture; cmd.Parameters.Add("@PriorityOrder", SqlDbType.Int).Value = dt.PriorityOrder; cmd.Parameters.Add("@IsDelete", SqlDbType.Bit).Value = dt.IsDelete; cmd.Parameters.Add("@Tag", SqlDbType.NVarChar).Value = dt.Tag; cmd.Parameters.Add("@Currency", SqlDbType.Int).Value = dt.Currency; cmd.Parameters.Add("@Tax", SqlDbType.Int).Value = dt.Tax; cmd.Parameters.Add("@Views", SqlDbType.Int).Value = dt.Views; cmd.Parameters.Add("@IsNew", SqlDbType.Bit).Value = dt.IsNew; cmd.Parameters.Add("@Code", SqlDbType.NVarChar).Value = dt.Code; cmd.Parameters.Add("@originalprice", SqlDbType.Bit).Value = dt.originalprice; cmd.Parameters.Add("@DiscountPercentage", SqlDbType.Float).Value = dt.DiscountPercentage; cmd.Parameters.Add("@UnitPercent", SqlDbType.Bit).Value = dt.UnitPercent; cmd.ExecuteNonQuery(); cmd.Dispose(); }
public void IntegraProduto() { try { Console.WriteLine("Início do exemplo de integração de Produto"); int idProduct = 100; //Instanciando um objeto do tipo ProductDTO ProductDTO objProduct = this.vtexService.ProductGet(idProduct); if(objProduct != null) { //Instanciamos um objeto do tipo ProductDTO caso este Produto não exista na VTEX objProduct = new ProductDTO(); } objProduct.Id = idProduct; objProduct.CategoryId = 100; objProduct.BrandId = 100; objProduct.DepartmentId = 10; objProduct.Name = "Teste"; objProduct.Description = "Teste"; objProduct.LinkId = "URL_do_Produto";//URL do produto objProduct.RefId = "12344321";//Código de referencia objProduct.SupplierId = 1;//Id do fornecedor objProduct.TaxCode = "12345678";//Código fiscal objProduct.DescriptionShort = "Teste";//Descrição resumida(Vitrine) objProduct.KeyWords = "Teste,integração,produto"; objProduct.MetaTagDescription = ""; objProduct.ReleaseDate = DateTime.Now;//Data de lançamento objProduct.ShowWithoutStock = true;//Exibe Produto sem estoque objProduct.Title = "Teste";//Texto da tag title objProduct.IsVisible = true; objProduct.IsActive = true; //Enviando os dados para serem inseridos ou atualizados pelo WebService this.vtexService.ProductInsertUpdate(objProduct); //Mensagem de sucesso Console.WriteLine("Produto inserido com sucesso"); } catch (Exception ex) { //Mensagem de erro Console.WriteLine(ex.ToString()); } finally { Console.WriteLine("Fim do exemplo de integração de Produto"); Console.ReadKey(); } }
public static List<ProductDTO> CretateProductDto(List<Product> products) { List<ProductDTO> productsDto = new List<ProductDTO>(); ProductMapper mapper = new ProductMapper(); foreach (Product pr in products) { ProductDTO dto = new ProductDTO(); dto.Id = pr.ProductId; dto.ProductName = pr.ProductName; dto.ProductCategoryId = pr.ProductCategoryId; dto.ProductCategoryName = mapper.GetProductCategory(pr.ProductCategoryId).CategoryName; productsDto.Add(dto); } return productsDto; }
public async Task <IActionResult> AddNew(ProductDTO product) { await _product.Post(product); return(RedirectToAction("Index")); }
public AddProductVM() { Categories = new List <Category>(); Product = new ProductDTO(); }
public ActionResult AddProduct(ProductVM model, HttpPostedFileBase file) { //check model on validity if (!ModelState.IsValid) { using (Db db = new Db()) { model.Categories = new SelectList(db.Categories.ToList(), "Id", "Name"); return(View(model)); } } //check name product on unique using (Db db = new Db()) { if (db.Products.Any(x => x.Name == model.Name)) { model.Categories = new SelectList(db.Categories.ToList(), "Id", "Name"); ModelState.AddModelError("", "That product name is taken!"); return(View(model)); } } //announce variable ProductID int id; //initialization and save model on base ProductDTO using (Db db = new Db()) { ProductDTO product = new ProductDTO(); product.Name = model.Name; product.Slug = model.Name.Replace(" ", "-").ToLower(); product.Description = model.Description; product.Price = model.Price; product.CategoryId = model.CategoryId; CategoryDTO catDTO = db.Categories.FirstOrDefault(x => x.Id == model.CategoryId); product.CategoryName = catDTO.Name; db.Products.Add(product); db.SaveChanges(); id = product.Id; } //add messagein TempDate TempData["SM"] = "You have added a product!"; #region Upload Image // create needed link diretory var originalDirectory = new DirectoryInfo(string.Format($"{Server.MapPath(@"\")}Images\\Uploads")); var pathString1 = Path.Combine(originalDirectory.ToString(), "Products"); var pathString2 = Path.Combine(originalDirectory.ToString(), "Products\\" + id.ToString()); var pathString3 = Path.Combine(originalDirectory.ToString(), "Products\\" + id.ToString() + "\\Thumbs"); var pathString4 = Path.Combine(originalDirectory.ToString(), "Products\\" + id.ToString() + "\\Gallery"); var pathString5 = Path.Combine(originalDirectory.ToString(), "Products\\" + id.ToString() + "\\Gallery\\Thumbs"); // check is directories (if not, create) if (!Directory.Exists(pathString1)) { Directory.CreateDirectory(pathString1); } if (!Directory.Exists(pathString2)) { Directory.CreateDirectory(pathString2); } if (!Directory.Exists(pathString3)) { Directory.CreateDirectory(pathString3); } if (!Directory.Exists(pathString4)) { Directory.CreateDirectory(pathString4); } if (!Directory.Exists(pathString5)) { Directory.CreateDirectory(pathString5); } // check is file download if (file != null && file.ContentLength > 0) { //get extension file string ext = file.ContentType.ToLower(); //check extension file if (ext != "image/jpg" && ext != "image/jpeg" && ext != "image/pjpeg" && ext != "image/gif" && ext != "image/x-png" && ext != "image/png") { using (Db db = new Db()) { model.Categories = new SelectList(db.Categories.ToList(), "Id", "Name"); ModelState.AddModelError("", "The image was not uploaded - wrong image extension!"); return(View(model)); } } //announce variable with name image string imageName = file.FileName; //save name image in model DTO using (Db db = new Db()) { ProductDTO dto = db.Products.Find(id); dto.ImageName = imageName; db.SaveChanges(); } //assign path to original and reduce image var path = string.Format($"{pathString2}\\{imageName}"); var path2 = string.Format($"{pathString3}\\{imageName}"); //save original image file.SaveAs(path); //create and save reduce copy WebImage img = new WebImage(file.InputStream); img.Resize(200, 200).Crop(1, 1); img.Save(path2); } #endregion //readirect user return(RedirectToAction("AddProduct")); }
public void Save(ProductDTO productDTO, ProductSpecificationDTO productSpecificationDTO) { if (string.IsNullOrWhiteSpace(productDTO.Id)) { productDTO.Id = NewId.Next().ToString(); var productImages = new List <Image>(); if (productDTO.Images != null && productDTO.Images.Count > 0) { foreach (var image in productDTO.Images) { productImages.Add(new Image { ProductId = productDTO.Id, Path = image }); } } var metaTitle = productDTO.Name.GenerateSlug(); if (_context.Products.Any(p => p.MetaTitle == metaTitle)) { metaTitle += "-" + NewId.Next().ToString().Split('-').Last(); } productDTO.MetaTitle = metaTitle; productDTO.DateAdded = DateTime.Now; var product = _mapper.Map <ProductDTO, Product>(productDTO); productSpecificationDTO.ProductId = productDTO.Id; var productSepcification = _mapper.Map <ProductSpecificationDTO, ProductSpecification>(productSpecificationDTO); _context.Products.Add(product); _context.Images.AddRange(productImages); _context.ProductSpecifications.Add(productSepcification); } else { var product = _context.Products.First(p => p.Id == productDTO.Id); var dbEntryImages = GetImages(productDTO.Id); var newImages = productDTO.Images.ToList(); // Update metatitle if (product.Name != productDTO.Name) { var metaTitle = productDTO.Name.GenerateSlug(); if (_context.Products.Any(p => (p.MetaTitle != product.MetaTitle) && (p.MetaTitle == metaTitle))) { metaTitle += "-" + NewId.Next().ToString().Split('-').Last(); } productDTO.MetaTitle = metaTitle; } // Remove image foreach (var path in dbEntryImages) { if (!newImages.Any(i => i == path)) { var image = _context.Images.First(i => i.ProductId == productDTO.Id && i.Path == path); _context.Images.Remove(image); continue; } } // Add image foreach (var newImg in newImages) { if (!dbEntryImages.Any(path => path == newImg)) { var image = new Image { ProductId = product.Id, Path = newImg }; _context.Images.Add(image); } } // Update specification var productSpecification = _context.ProductSpecifications.First(ps => ps.ProductId == product.Id); productSpecification = _mapper.Map(productSpecificationDTO, productSpecification); product = _mapper.Map(productDTO, product); product.DateModified = DateTime.Now; } _context.SaveChanges(); }
public async Task <bool> ModifyProductAsync(ProductDTO productDTO) { return(await _products.ModifyProductAsync(_mapper.Map <ProductEntity>(productDTO))); }
public bool edit_product(ProductDTO a) { return(ProductDAO.Instance.Edit(a)); }
public ActionResult AddProduct(ProductVM model, HttpPostedFileBase file) { if (!ModelState.IsValid) { using (Db db = new Db()) { model.Categories = new SelectList(db.Categories.ToList(), "Id", "Name"); return(View(model)); } } using (Db db = new Db()) { if (db.Products.Any(x => x.Name == model.Name)) { model.Categories = new SelectList(db.Categories.ToList(), "Id", "Name"); ModelState.AddModelError("", "That product name is taken!"); return(View(model)); } } int id; using (Db db = new Db()) { ProductDTO product = new ProductDTO(); product.Name = model.Name; product.Slug = model.Name.Replace(" ", "-").ToLower(); product.Description = model.Description; product.Price = model.Price; product.CategoryId = model.CategoryId; CategoryDTO catDTO = db.Categories.FirstOrDefault(x => x.Id == model.CategoryId); product.CategoryName = catDTO.Name; db.Products.Add(product); db.SaveChanges(); id = product.Id; } TempData["SM"] = "You have added a product!"; #region Upload Image var originalDirectory = new DirectoryInfo(string.Format("{0}Images\\Uploads", Server.MapPath(@"\"))); var pathString1 = Path.Combine(originalDirectory.ToString(), "Products"); var pathString2 = Path.Combine(originalDirectory.ToString(), "Products\\" + id.ToString()); var pathString3 = Path.Combine(originalDirectory.ToString(), "Products\\" + id.ToString() + "\\Thumbs"); var pathString4 = Path.Combine(originalDirectory.ToString(), "Products\\" + id.ToString() + "\\Gallery"); var pathString5 = Path.Combine(originalDirectory.ToString(), "Products\\" + id.ToString() + "\\Gallery\\Thumbs"); if (!Directory.Exists(pathString1)) { Directory.CreateDirectory(pathString1); } if (!Directory.Exists(pathString2)) { Directory.CreateDirectory(pathString2); } if (!Directory.Exists(pathString3)) { Directory.CreateDirectory(pathString3); } if (!Directory.Exists(pathString4)) { Directory.CreateDirectory(pathString4); } if (!Directory.Exists(pathString5)) { Directory.CreateDirectory(pathString5); } if (file != null && file.ContentLength > 0) { string ext = file.ContentType.ToLower(); if (ext != "image/jpg" && ext != "image/jpeg" && ext != "image/pjpeg" && ext != "image/gif" && ext != "image/x-png" && ext != "image/png") { using (Db db = new Db()) { model.Categories = new SelectList(db.Categories.ToList(), "Id", "Name"); ModelState.AddModelError("", "The image was not uploaded - wrong image extension."); return(View(model)); } } string imageName = file.FileName; using (Db db = new Db()) { ProductDTO dto = db.Products.Find(id); dto.ImageName = imageName; db.SaveChanges(); } var path = string.Format("{0}\\{1}", pathString2, imageName); var path2 = string.Format("{0}\\{1}", pathString3, imageName); file.SaveAs(path); WebImage img = new WebImage(file.InputStream); img.Resize(200, 200); img.Save(path2); } #endregion return(RedirectToAction("AddProduct")); }
public ActionResult EditProduct(ProductVM model, HttpPostedFileBase file) { int id = model.Id; using (Db db = new Db()) { model.Categories = new SelectList(db.Categories.ToList(), "Id", "Name"); model.GalleryImages = Directory.EnumerateFiles(Server.MapPath("~/Images/Uploads/Products/" + id.ToString() + "/Gallery/Thumbs")) .Select(fn => Path.GetFileName(fn)); } if (!ModelState.IsValid) { return(View(model)); } using (Db db = new Db()) { if (db.Products.Where(x => x.Id != id).Any(x => x.Name == model.Name)) { ModelState.AddModelError("", "That product is taken."); return(View(model)); } } using (Db db = new Db()) { ProductDTO dto = db.Products.Find(id); dto.Name = model.Name; dto.Slug = model.Name.Replace(" ", "-").ToLower(); dto.Description = model.Description; dto.Price = model.Price; dto.CategoryId = model.CategoryId; dto.ImageName = model.ImageName; CategoryDTO catDTO = db.Categories.FirstOrDefault(x => x.Id == model.CategoryId); dto.CategoryName = catDTO.Name; db.SaveChanges(); } TempData["SM"] = "You have edited the product!"; #region Image Upload if (file != null && file.ContentLength > 0) { string ext = file.ContentType.ToLower(); if (ext != "image/jpg" && ext != "image/jpeg" && ext != "image/pjpeg" && ext != "image/gif" && ext != "image/x-png" && ext != "image/png") { using (Db db = new Db()) { ModelState.AddModelError("", "The image was not uploaded - wrong image extension."); return(View(model)); } } var originalDirectory = new DirectoryInfo(string.Format("{0}Images\\Uploads", Server.MapPath(@"\"))); var pathString1 = Path.Combine(originalDirectory.ToString(), "Products"); var pathString2 = Path.Combine(originalDirectory.ToString(), "Products\\" + id.ToString() + "\\Thumbs"); DirectoryInfo di1 = new DirectoryInfo(pathString1); DirectoryInfo di2 = new DirectoryInfo(pathString2); foreach (FileInfo file2 in di1.GetFiles()) { file2.Delete(); } foreach (FileInfo file3 in di2.GetFiles()) { file3.Delete(); } string imageName = file.FileName; using (Db db = new Db()) { ProductDTO dto = db.Products.Find(id); dto.ImageName = imageName; db.SaveChanges(); } var path = string.Format("{0}\\{1}", pathString1, imageName); var path2 = string.Format("{0}\\{1}", pathString2, imageName); file.SaveAs(path); WebImage img = new WebImage(file.InputStream); img.Resize(200, 200); img.Save(path2); } #endregion return(RedirectToAction("EditProduct")); }
protected double CalcPrice(ProductDTO item) { var re = item.Price - (item.Discount % 1 == 0 ? item.Discount : (item.Price * item.Discount)); return(re); }
public void Category_TestAssociationsUpdate() { //Create API Proxy. var proxy = CreateApiProxy(); //Find Category by Slug. var resParent = proxy.CategoriesFindBySlug(TestConstants.TestCategorySlug); CheckErrors(resParent); //Create test product and category. var category = new CategoryDTO { StoreId = 1, Name = "Test Category", ParentId = resParent.Content.Bvin }; var product = new ProductDTO { ProductName = "HCC Unit tests product", AllowReviews = true, ListPrice = 687, LongDescription = "This is test product", Sku = "TST100", StoreId = 1, TaxExempt = true }; var createCategoryResponse = proxy.CategoriesCreate(category); CheckErrors(createCategoryResponse); var createProductResponse = proxy.ProductsCreate(product, null); //CheckErrors(createProductResponse); //Create category and product association. category.Bvin = createCategoryResponse.Content.Bvin; product.Bvin = createProductResponse.Content.Bvin; var assoc = new CategoryProductAssociationDTO { ProductId = product.Bvin, CategoryId = category.Bvin }; var assocResponse = proxy.CategoryProductAssociationsCreate(assoc); CheckErrors(assocResponse); //Update category and product association. assocResponse.Content.SortOrder = 100; var assocUpdateResponse = proxy.CategoryProductAssociationsUpdate(assocResponse.Content); CheckErrors(assocUpdateResponse); var findAssociationResponse = proxy.CategoryProductAssociationsFind(assocResponse.Content.Id); CheckErrors(findAssociationResponse); Assert.AreEqual(assocUpdateResponse.Content.SortOrder, findAssociationResponse.Content.SortOrder); //Unrelate the category and product association. var unrelateResponse = proxy.CategoryProductAssociationsUnrelate(createProductResponse.Content.Bvin, createCategoryResponse.Content.Bvin); CheckErrors(unrelateResponse); Assert.IsTrue(unrelateResponse.Content); //Delete temporary product. var productDeleteResponse = proxy.ProductsDelete(product.Bvin); CheckErrors(productDeleteResponse); //Delete temporary category. var categoryDeleteResponse = proxy.CategoriesDelete(category.Bvin); CheckErrors(categoryDeleteResponse); }
public async Task <JsonResult> GetMonitoringsByUserEmailAndSecurityStamp(CheckModel model) { var results = new List <ValidationResult>(); var context = new ValidationContext(model); if (!Validator.TryValidateObject(model, context, results, true)) { return(Json("Bad data")); } ApplicationUserDTO checkUser = new ApplicationUserDTO { Email = model.Email, SecurityStamp = model.SecurityStamp }; try { ApplicationUserDTO user = await userService.GetUserByEmailAndSecurityStamp(checkUser); if (user.Role != "user") { return(Json("Only User can monitoring", JsonRequestBehavior.AllowGet)); } else { try { var monitorngs = monitoringService.GetMonitoringsByUserId(user.Id).ToList(); List <GetSensor> getSensors = new List <GetSensor>(); foreach (var monitoring in monitorngs) { try { SensorDTO sensor = sensorService.GetSensorById(monitoring.SensorId); try { ApplicationUserDTO ownerUser = await userService.GetUserById(sensor.ApplicationUserId); try { var mapper = new AutoMapper.MapperConfiguration(cfg => cfg.CreateMap <SensorDTO, GetSensor>()).CreateMapper(); GetSensor getSensor = mapper.Map <SensorDTO, GetSensor>(sensor); ProductDTO product = productService.GetProductById(sensor.ProductId); getSensor.ProductName = product.Name; getSensor.ObserverEmail = ownerUser.Email; getSensors.Add(getSensor); } catch { return(Json("Bad with get product", JsonRequestBehavior.AllowGet)); } } catch { return(Json("Bad with get owner user", JsonRequestBehavior.AllowGet)); } } catch { return(Json("Bad with get sensor", JsonRequestBehavior.AllowGet)); } } return(Json(getSensors, JsonRequestBehavior.AllowGet)); } catch { return(Json("Bad with monitorings", JsonRequestBehavior.AllowGet)); } } } catch { return(Json("Email or Token is wrong", JsonRequestBehavior.AllowGet)); } }
public async Task UpdateProductAsync(ProductDTO productDTO) { var product = mapper.Map <Product>(productDTO); await productService.UpdateProduct(product); }
public async Task <IActionResult> Edit(ProductDTO productDTO) { await _product.Put(productDTO); return(RedirectToAction("Index")); }
public ActionResult AddProduct(ProductVM model, HttpPostedFileBase uploadPDF, HttpPostedFileBase uploadPhoto) { string UserID = User.Identity.Name; HttpPostedFileBase photobase = uploadPhoto; HttpPostedFileBase pdfbase = uploadPDF; //Check model state if (!ModelState.IsValid) { using (TicketAppDB db = new TicketAppDB()) { model.Categories = new SelectList(db.Categories.ToList(), "Id", "Name"); return(View(model)); } } //Make sure product name is unique using (TicketAppDB db = new TicketAppDB()) { if (db.Products.Any(x => x.Name == model.Name)) { model.Categories = new SelectList(db.Categories.ToList(), "Id", "Name"); ModelState.AddModelError("", "That product name is taken!"); return(View(model)); } } // Declare product id int id; string pdfsName = null; string imagesName = null; //Init image name if (uploadPDF != null) { pdfsName = uploadPDF.FileName; } if (uploadPhoto != null) { imagesName = uploadPhoto.FileName; } string name = ""; using (TicketAppDB db = new TicketAppDB()) { //Init and save product DTO ProductDTO product = new ProductDTO(); var userId = from p in db.Users where p.Username == UserID select p.Id; product.Name = model.Name; name = model.Name; product.Slug = model.Name.Replace(" ", "-").ToLower(); product.Description = model.Description; product.Price = model.Price; product.ReservationDate = model.ReservationDate; product.Verified = model.Verified; product.PdfName = pdfsName; product.ImageName = imagesName; product.CategoryId = model.CategoryId; CategoryDTO catDTO = db.Categories.FirstOrDefault(x => x.Id == model.CategoryId); product.CategoryName = catDTO.Name; product.UserId = userId.First(); product.IsSold = false; db.Products.Add(product); db.SaveChanges(); //Get the id id = product.Id; } using (TicketAppDB db = new TicketAppDB()) { if (uploadPhoto != null && uploadPhoto.ContentLength > 0) { var photo = new PhotoDTO { Name = System.IO.Path.GetFileName(uploadPhoto.FileName), photoType = photoType.Picture, ContentType = uploadPhoto.ContentType, ProductId = id }; string photoext = Path.GetExtension(photo.Name); var strings = new List <string> { ".png", ".jpeg", ".gif", ".jpg" }; bool contains = strings.Contains(photoext, StringComparer.OrdinalIgnoreCase); if (!contains) { model.Categories = new SelectList(db.Categories.ToList(), "Id", "Name"); ModelState.AddModelError("", "That photo was not uploaded - wrong image extension."); return(View(model)); } using (var reader2 = new System.IO.BinaryReader(uploadPhoto.InputStream)) { photo.Data = reader2.ReadBytes(uploadPhoto.ContentLength); } model.Photos = new List <PhotoDTO> { photo }; db.Photos.Add(photo); db.SaveChanges(); } } using (TicketAppDB db = new TicketAppDB()) { if (uploadPDF != null && uploadPDF.ContentLength > 0) { var invoice = new PdfDTO { Name = System.IO.Path.GetFileName(uploadPDF.FileName), PdfType = PDFType.Invoice, ContentType = uploadPDF.ContentType, ProductId = id }; string pdfext = Path.GetExtension(invoice.Name); if (!pdfext.Equals(".pdf", StringComparison.OrdinalIgnoreCase)) { model.Categories = new SelectList(db.Categories.ToList(), "Id", "Name"); ModelState.AddModelError("", "That pdf was not uploaded - wrong Pdf extension."); return(View(model)); } using (var reader = new System.IO.BinaryReader(uploadPDF.InputStream)) { invoice.Data = reader.ReadBytes(uploadPDF.ContentLength); } model.Pdfs = new List <PdfDTO> { invoice }; db.Pdfs.Add(invoice); db.SaveChanges(); } } //Set TempData message TempData["SM"] = "You have added listing: '" + name + "'!"; //Redirect return(RedirectToAction("AddProduct")); }
public static void Main(string[] args) { var context = new AutoMappingDB(); #region Seed //string[] productName = new string[] { "Door", "Comp", "Hard", "Disc", "Mouse" }; //string[] prodDesc = new string[] { "Waww", "Maliiii", "Boje", "OMG" }; //string[] storageNames = new string[] { "Kafcha", "Golemakashta", "Warehouse", "SmallHouse" }; //string[] storageLocat = new string[] { "Sofia", "Rayovo", "Samokov", "Prodanovci" }; //List<Storage> storages = new List<Storage>(); //Random rand = new Random(); //for (int i = 0; i < 3; i++) //{ // int locIndex = rand.Next(0, 5); // var storage = new Storage() // { // Name = storageNames[i], // Location = storageLocat[locIndex] // }; // storages.Add(storage); //} //context.Storages.AddRange(storages); //context.SaveChanges(); //for (int i = 0; i < productName.Length; i++) //{ // int descIndex = rand.Next(0, 3); // int storageIndex = rand.Next(0, 3); // var entry = new Product() // { // Name = productName[i], // Description = prodDesc[descIndex], // ProductStocks = new List<ProductStock>() // { // new ProductStock() // { // Quantity = rand.Next(0, 101), // Storage = storages.ElementAt(storageIndex) // } // } // }; // context.Products.Add(entry); //} //context.SaveChanges(); #endregion Mapper.Initialize(cfg => { cfg.AddProfile <ProductProfile>(); cfg.AddProfile <StorageProfile>(); }); Product entity = context.Products.First(); ProductDTO dto = Mapper.Map <ProductDTO>(entity); //CollectionMapping List <ProductDTO> autoDtos = context.Products .ProjectTo <ProductDTO>() .ToList(); //using Expression in select List <ProductDTO> dtos = context.Products .Select(ProductMapping.ToProductDtoExpression()) .ToList(); }
public void Update(ProductDTO product) { _logic.Update(product); }
/// <summary> /// The CopyFromProductDTO /// </summary> /// <param name="productViewModel">The productViewModel<see cref="ProductViewModel"/></param> /// <param name="productDto">The productDto<see cref="ProductDTO"/></param> public static void CopyFromProductDTO(this ProductViewModel productViewModel, ProductDTO productDto) { productViewModel.Name = productDto.Name; productViewModel.Alias = productDto.Alias; productViewModel.Description = productDto.Description; productViewModel.Image = productDto.Image; productViewModel.MetaDescription = productDto.MetaDescription; productViewModel.MetaKeyword = productDto.MetaKeyword; productViewModel.Status = productDto.Status; productViewModel.HomeFlag = productDto.HomeFlag; productViewModel.CategoryID = productDto.CategoryID; productViewModel.Price = productDto.Price; productViewModel.PromotionPrice = productDto.PromotionPrice; productViewModel.Warranty = productDto.Warranty; productViewModel.Content = productDto.Content; productViewModel.MoreImages = productDto.MoreImages; productViewModel.ID = productDto.ID; productViewModel.CreatedBy = productDto.CreatedBy; productViewModel.CreatedDate = productDto.CreatedDate; productViewModel.UpdatedBy = productDto.UpdatedBy; productViewModel.UpdatedDate = productDto.UpdatedDate; productViewModel.CategoryName = productDto.CategoryName; }
public bool insert_product(ProductDTO a) { return(ProductDAO.Instance.insert(a)); }
public ActionResult AddProduct(ProductVM model, HttpPostedFileBase file) { if (!ModelState.Any()) { model.Categories = new SelectList(db.Categories.ToList(), "Id", "Name"); return(View(model)); } if (db.Products.Any(x => x.Name == model.Name)) { model.Categories = new SelectList(db.Categories.ToList(), "Id", "Name"); ModelState.AddModelError("", "The Product Name is already exisits"); return(View(model)); } var product = new ProductDTO(); product.Name = model.Name; product.Slug = model.Name.Replace(" ", "-").ToLower(); product.Description = model.Description; product.Price = model.Price; product.CategoryId = model.CategoryId; var catDTO = db.Categories.FirstOrDefault(x => x.Id == model.CategoryId); product.CategoryName = catDTO.Name; db.Products.Add(product); db.SaveChanges(); //FileUpload var id = product.Id; TempData["SM"] = "You have Added a Product Successfully"; var originalDirectory = new DirectoryInfo(string.Format("{0}Images\\Uploads", Server.MapPath(@"\"))); var pathString1 = Path.Combine(originalDirectory.ToString(), "Products"); var pathString2 = Path.Combine(originalDirectory.ToString(), "Products\\" + id.ToString()); var pathString3 = Path.Combine(originalDirectory.ToString(), "Products\\" + id.ToString() + "\\Thumbs"); var pathString4 = Path.Combine(originalDirectory.ToString(), "Products\\" + id.ToString() + "\\Gallary"); var pathString5 = Path.Combine(originalDirectory.ToString(), "Products\\" + id.ToString() + "\\Gallary\\Thumbs"); if (!Directory.Exists(pathString1)) { Directory.CreateDirectory(pathString1); } if (!Directory.Exists(pathString2)) { Directory.CreateDirectory(pathString2); } if (!Directory.Exists(pathString3)) { Directory.CreateDirectory(pathString3); } if (!Directory.Exists(pathString4)) { Directory.CreateDirectory(pathString4); } if (!Directory.Exists(pathString5)) { Directory.CreateDirectory(pathString5); } if (file != null && file.ContentLength > 0) { var ext = file.ContentType.ToLower(); if (ext != "image/jpg" && ext != "image/jpeg" && ext != "image/pjpeg" && ext != "image/gif" && ext != "image/x-png" && ext != "image/png") { model.Categories = new SelectList(db.Categories.ToList(), "Id", "Name"); ModelState.AddModelError("", "The image extension not supported upload jpeg,gif,png"); return(View(model)); } var imageName = file.FileName; var dto = db.Products.Find(id); dto.ImageName = imageName; db.SaveChanges(); var path = string.Format("{0}\\{1}", pathString2, imageName); var path2 = string.Format("{0}\\{1}", pathString3, imageName); file.SaveAs(path); var img = new WebImage(file.InputStream); img.Resize(200, 200); img.Save(path2); } return(RedirectToAction("AddProduct")); }
private async Task <IReadOnlyList <ProductDTO> > ExtractProducts(Page page) { var products = new List <ProductDTO>(); var productsInDom = await page.QuerySelectorAllAsync("div.product--box.box--minimal .image--media img"); var categoryName = await page.EvaluateExpressionAsync <string>("document.querySelector('li.is--active span.breadcrumb--title').innerText"); if (categoryName == null) { await _logger.ErrorAsync($"Category for page {page.Url} is null"); return(products); } foreach (var current in productsInDom) { try { await current.ClickAsync(); var nameTag = await page.WaitForSelectorAsync("div.product--details h1.product--title", new WaitForSelectorOptions { Visible = true }); if (nameTag == null) { await _logger.InformationAsync("Product name tag wasn't found!"); continue; } var parseResults = await page.EvaluateFunctionAsync(@"() => { return { 'Name': document.querySelector('div.product--details h1.product--title').innerText, 'SubCategory': Array.from(document.querySelectorAll('.product--buybox .entry--property')).map((n) => {return {'key': n.children[0].innerText, 'value': n.children[1].innerText}}).find((n) => n.key == 'Բաժին')?.value, 'Description': document.querySelector('div .product--description.im-collapse-content')?.innerText.replaceAll(/\s{2,}/ig, '\n').trim(), 'Price': document.querySelector('.price--content.content--default').children[0].attributes['content'].value, 'Code': Array.from(document.querySelectorAll('span.entry--content')).find((n) => 'itemprop' in n.attributes && n.attributes['itemprop'].value == 'sku').innerText, 'ImageUrl': document.querySelector('.image-slider--item span.image--element').attributes['data-img-original'].value } } "); var description = parseResults.Value <string>("Description") ?? string.Empty; var code = parseResults.Value <int>("Code"); var name = parseResults.Value <string>("Name"); var subCategory = parseResults.Value <string>("SubCategory") ?? string.Empty; var priceAsString = parseResults.Value <string>("Price"); int price = 0; var imageUrl = parseResults.Value <string>("ImageUrl"); if (name == null || priceAsString == null || !int.TryParse(priceAsString, System.Globalization.NumberStyles.AllowDecimalPoint, null, out price) || imageUrl == null) { await _logger.WarningAsync($"Field is missing from product. code={code}, description={description}, name={name}, subCategory={subCategory}, priceAsString={priceAsString}, imageUrl={imageUrl}"); continue; } var imageUrlParsed = new Uri(imageUrl); var product = new ProductDTO { Category = categoryName, Name = name, SubCategory = subCategory, ShortDescription = $"Code: {code}\n" + description.Substring(0, Math.Min(100, description.Length)), FullDescription = $"Code: {code}\n" + description, Price = price, Code = code, Image = await DownloadImage(imageUrl), ImageFileName = imageUrlParsed.Segments[imageUrlParsed.Segments.Length - 1] }; products.Add(product); await _logger.InformationAsync($"Parsed product, name: {product.Name}"); } catch (Exception exc) { await _logger.WarningAsync($"Exception thrown when parsing: URL={page.Url}", exc); continue; } finally { try { var closeButton = await page.QuerySelectorAsync(".quickview-close-btn"); await closeButton.ClickAsync(); await page.WaitForSelectorAsync(".quick-view.is--active", new WaitForSelectorOptions { Hidden = true }); await page.WaitForTimeoutAsync(1000); } catch {} } } return(products); }
public void Add(ProductDTO product) { var mapProduct = _mapper.Map <Product>(product); _productRepository.Add(mapProduct); }
public ActionResult EditProduct(ProductVM model, HttpPostedFileBase file) { //get id product int id = model.Id; //fill list categories and images using (Db db = new Db()) { model.Categories = new SelectList(db.Categories.ToList(), "Id", "Name"); } model.GalleryImages = Directory .EnumerateFiles(Server.MapPath("~/Images/Uploads/Products/" + id + "/Gallery/Thumbs")) .Select(fileName => Path.GetFileName(fileName)); //check model on validity if (!ModelState.IsValid) { return(View(model)); } //check name product on unique using (Db db = new Db()) { if (db.Products.Where(x => x.Id != id).Any(x => x.Name == model.Name)) { ModelState.AddModelError("", "That product name is taken!"); return(View(model)); } } //updqate product using (Db db = new Db()) { ProductDTO dto = db.Products.Find(id); dto.Name = model.Name; dto.Slug = model.Name.Replace(" ", "-").ToLower(); dto.Description = model.Description; dto.Price = model.Price; dto.CategoryId = model.CategoryId; dto.ImageName = model.ImageName; CategoryDTO catDto = db.Categories.FirstOrDefault(x => x.Id == model.CategoryId); dto.CategoryName = catDto.Name; db.SaveChanges(); } //message TempData TempData["SM"] = "You have edited the product!"; //logic processing images #region Image Upload //check download file if (file != null && file.ContentLength > 0) { //get extension file string ext = file.ContentType.ToLower(); //check extension if (ext != "image/jpg" && ext != "image/jpeg" && ext != "image/pjpeg" && ext != "image/gif" && ext != "image/x-png" && ext != "image/png") { using (Db db = new Db()) { ModelState.AddModelError("", "The image was not uploaded - wrong image extension!"); return(View(model)); } } //set path download var originalDirectory = new DirectoryInfo(string.Format($"{Server.MapPath(@"\")}Images\\Uploads")); var pathString1 = Path.Combine(originalDirectory.ToString(), "Products\\" + id.ToString()); var pathString2 = Path.Combine(originalDirectory.ToString(), "Products\\" + id.ToString() + "\\Thumbs"); //delete existing files and directories DirectoryInfo di1 = new DirectoryInfo(pathString1); DirectoryInfo di2 = new DirectoryInfo(pathString2); foreach (var file2 in di1.GetFiles()) { file2.Delete(); } foreach (var file3 in di2.GetFiles()) { file3.Delete(); } //save name of image string imageName = file.FileName; using (Db db = new Db()) { ProductDTO dto = db.Products.Find(id); dto.ImageName = imageName; db.SaveChanges(); } //save original and preview version var path = string.Format($"{pathString1}\\{imageName}"); var path2 = string.Format($"{pathString2}\\{imageName}"); //save original image file.SaveAs(path); //create and save reduce copy WebImage img = new WebImage(file.InputStream); img.Resize(200, 200).Crop(1, 1); img.Save(path2); } #endregion //redirect user return(RedirectToAction("EditProduct")); }
public void Update(ProductDTO product) { var mapProduct = _mapper.Map <Product>(product); _productRepository.Update(mapProduct); }
public async Task <ActionResult> UpdateProduct([FromForm] ProductDTO req) { var options = new JsonSerializerOptions { PropertyNameCaseInsensitive = true, }; //json으로 전송된 제품 정보를 객체로 역직렬화 var product = JsonSerializer.Deserialize <Product>(req.Product, options); long id = 0; if (!long.TryParse(req.Id, out id)) { return(BadRequest()); } //업로드된 이미지들을 /images/products로 옮기고 //옮긴 경로를 목록으로 가져오기 var pis = await GetProductImages(id, req.Photos); //기존 이미지 경로 목록에 업로드된 목록을 합친다 product.PhotoUrls.AddRange( pis.Select(pi => pi.PhotoUrl)); //DB에서 기존에 등록된 이미지 목록 가져오기 var productImages = _context.ProductImages .Where(pi => pi.ProductId == id); //기존에는 있었지만 없어진 이미지는 삭제 var toDeleteProductImageList = productImages .Where(pi => product.PhotoUrls.Contains(pi.PhotoUrl) == false); _context.ProductImages.RemoveRange(toDeleteProductImageList); foreach (var pu in product.PhotoUrls) { var _pi = await productImages .FirstOrDefaultAsync(pi => pi.PhotoUrl == pu); if (_pi == null) { //기존에 없던 항목들은 새로 추가 _pi = new ProductImage { PhotoUrl = pu, ProductId = product.Id }; await _context.ProductImages.AddAsync(_pi); } } //product 엔티티를 수정된 상태로 설정 //수정된 내용을 자동으로 체크해서 DB에 업데이트 해준다. _context.Entry(product).State = EntityState.Modified; //CreatedDate는 수정되지 않도록 설정 _context.Entry(product).Property(p => p.CreatedDate).IsModified = false; //DB에서 제품에 대한 기존의 Category목록 가져오기 var productCategories = _context.ProductCategories .Where(pc => pc.ProductId == id); //기존에는 있었지만 수정된 카테고리 목록에 없는 것들은 삭제 var toDeleteProductCategoryList = productCategories .Where(pc => product.CategoryIds.Contains(pc.CategoryId) == false); _context.ProductCategories.RemoveRange(toDeleteProductCategoryList); foreach (var cid in product.CategoryIds) { var _pc = await productCategories .FirstOrDefaultAsync(pc => pc.ProductId == id && pc.CategoryId == cid); if (_pc == null) { var sortOrder = await productCategories.Where(pc => pc.ProductId == id).CountAsync(); //기존에 없던 항목들은 새로 추가 _pc = new ProductCategory { CategoryId = cid, ProductId = product.Id, SortOrder = sortOrder }; await _context.ProductCategories.AddAsync(_pc); } } try { await _context.SaveChangesAsync(); } catch (DbUpdateConcurrencyException) { if (!ProductExists(id)) { return(NotFound()); } else { throw; } } return(Ok(new { Id = product.Id })); }
private void ShowProductDetails(object selectedProduct) { SelectedProduct = (ProductDTO)selectedProduct; Id = SelectedProduct.Id; Name = SelectedProduct.Name; Code = SelectedProduct.BarCode; Price = SelectedProduct.Retail_Price.HasValue ? SelectedProduct.Retail_Price.Value : 0; SelectedProduct.Quantity = Quantity = 0; Description = SelectedProduct.Description; }
public void Add(ProductDTO dto) { Repo.Add(Mapper.DeMap(dto)).Wait(); }
public ActionResult EditProduct(ProductVM model, HttpPostedFileBase file) { // Получаем ID продукта int id = model.Id; // Заполняем выпадающий список категориями и изображениями using (Db db = new Db()) { model.Categories = new SelectList(db.Categories.ToList(), "Id", "Name"); } model.GalleryImages = Directory .EnumerateFiles(Server.MapPath("~/Images/Uploads/Products/" + id + "/Gallery/Thumbs")) .Select(fn => Path.GetFileName(fn)); // Проверяем на валидность if (!ModelState.IsValid) { return(View(model)); } // Проверяем уникальность имени using (Db db = new Db()) { if (db.Products.Where(x => x.Id != id).Any(x => x.Name == model.Name)) { ModelState.AddModelError("", "That product name is taken."); return(View(model)); } } // Обновляем продукт using (Db db = new Db()) { ProductDTO dto = db.Products.Find(id); dto.Name = model.Name; dto.ShortDesc = model.Name.Replace(" ", "-").ToLower(); dto.Description = model.Description; dto.Price = model.Price; dto.CategoryId = model.CategoryId; dto.ImageName = model.ImageName; CategoryDTO categoryDTO = db.Categories.FirstOrDefault(x => x.Id == model.CategoryId); dto.CategoryName = categoryDTO.Name; db.SaveChanges(); } // Устанавливаем сообщение в TempData TempData["SM"] = "You have edited your product."; #region Image upload | Логика обработки изображений // Проверяем загружен ли файл if (file != null && file.ContentLength > 0) { // Получаем расширение файла string ext = file.ContentType.ToLower(); // Проверяем расширене файла if (ext != "image/jpg" && ext != "image/jpeg" && ext != "image/pjpeg" && ext != "image/gif" && ext != "image/x-png" && ext != "image/png") { using (Db db = new Db()) { ModelState.AddModelError("", "The image was not uploaded - wrong image extension."); return(View(model)); } } // Устанавливаем пути загрузки var originalDirectory = new DirectoryInfo(string.Format($"{Server.MapPath(@"\")}Images\\Uploads")); var pathStr1 = Path.Combine(originalDirectory.ToString(), "Products\\" + id.ToString()); var pathStr2 = Path.Combine(originalDirectory.ToString(), "Products\\" + id.ToString() + "\\Thumbs"); // Удаляем существующие файлы и директории DirectoryInfo di1 = new DirectoryInfo(pathStr1); DirectoryInfo di2 = new DirectoryInfo(pathStr2); foreach (var file2 in di1.GetFiles()) { file2.Delete(); } foreach (var file3 in di1.GetFiles()) { file3.Delete(); } // Сохранить изображение string imageName = file.FileName; using (Db db = new Db()) { ProductDTO dto = db.Products.Find(id); dto.ImageName = imageName; db.SaveChanges(); } // Сохраняем оригинал и миниатюрную версию var path = string.Format($"{pathStr1}\\{imageName}"); var path2 = string.Format($"{pathStr2}\\{imageName}"); // Уменьшенное изображение // Сохраняем оригинальное изображение file.SaveAs(path); // Создаем и сохраняем уменьшеную копию WebImage img = new WebImage(file.InputStream); img.Resize(200, 200).Crop(1, 1); img.Save(path2); } #endregion // Переадресация return(RedirectToAction("EditProduct")); }
public ActionResult AddProduct(ProductVM model, HttpPostedFileBase file) { // Проверяем модель на валидность if (!ModelState.IsValid) // Если не валидная модель то берем из БД и возвращаем представление { using (Db db = new Db()) { model.Categories = new SelectList(db.Categories.ToList(), "Id", "Name"); return(View(model)); } } // Проверяем имя продукта на уникальность using (Db db = new Db()) { if (db.Products.Any(x => x.Name == model.Name)) { model.Categories = new SelectList(db.Categories.ToList(), "Id", "Name"); ModelState.AddModelError("", "This product name is taken."); return(View(model)); } } // Объявляем переменную ProductID int id; // Сохраняем в БД модель на основе ProductDTO using (Db db = new Db()) { ProductDTO product = new ProductDTO(); product.Name = model.Name; product.ShortDesc = model.Name.Replace(" ", "-").ToLower(); product.Description = model.Description; product.Price = model.Price; product.CategoryId = model.CategoryId; CategoryDTO categoryDTO = db.Categories.FirstOrDefault(x => x.Id == model.CategoryId); product.CategoryName = categoryDTO.Name; db.Products.Add(product); db.SaveChanges(); id = product.Id; } // Добавляем сообщение в TempData TempData["SM"] = "You have added a product."; #region Upload img // Создаем необходимые ссылки на дериктории var originalDirectory = new DirectoryInfo(string.Format($"{Server.MapPath(@"\")}Images\\Uploads")); var pathStr1 = Path.Combine(originalDirectory.ToString(), "Products"); var pathStr2 = Path.Combine(originalDirectory.ToString(), "Products\\" + id.ToString()); var pathStr3 = Path.Combine(originalDirectory.ToString(), "Products\\" + id.ToString() + "\\Thumbs"); var pathStr4 = Path.Combine(originalDirectory.ToString(), "Products\\" + id.ToString() + "\\Gallery"); var pathStr5 = Path.Combine(originalDirectory.ToString(), "Products\\" + id.ToString() + "\\Gallery\\Thumbs"); // Проверка наличия директории, если нет дериктории, то создаем if (!Directory.Exists(pathStr1)) { Directory.CreateDirectory(pathStr1); } if (!Directory.Exists(pathStr2)) { Directory.CreateDirectory(pathStr2); } if (!Directory.Exists(pathStr3)) { Directory.CreateDirectory(pathStr3); } if (!Directory.Exists(pathStr4)) { Directory.CreateDirectory(pathStr4); } if (!Directory.Exists(pathStr5)) { Directory.CreateDirectory(pathStr5); } // Проверяем, был ли загружен файл if (file != null && file.ContentLength > 0) { // Получаем расширение файла string ext = file.ContentType.ToLower(); // Проверяем расширение файла if (ext != "image/jpg" && ext != "image/jpeg" && ext != "image/pjpeg" && ext != "image/gif" && ext != "image/x-png" && ext != "image/png") { using (Db db = new Db()) { model.Categories = new SelectList(db.Categories.ToList(), "Id", "Name"); ModelState.AddModelError("", "The image was not uploaded - wrong image extension."); return(View(model)); } } // Объявляем переменную с именем изображения string imageName = file.FileName; // Сохраняем имя изображения в модель DTO using (Db db = new Db()) { ProductDTO dto = db.Products.Find(id); dto.ImageName = imageName; db.SaveChanges(); } // Назначаем путь к оригинальному и уменьшеному изображению var path = string.Format($"{pathStr2}\\{imageName}"); var path2 = string.Format($"{pathStr3}\\{imageName}"); // Уменьшенное изображение // Сохраняем оригинальное изображение file.SaveAs(path); // Создаем и сохраняем уменьшеную копию WebImage img = new WebImage(file.InputStream); img.Resize(200, 200).Crop(1, 1); img.Save(path2); } #endregion // Переадресация return(RedirectToAction("AddProduct")); }
public ActionResult EditProduct(ProductVM model, HttpPostedFileBase uploadPhoto, HttpPostedFileBase uploadPDF, int id) { // Get product id id = model.Id; // Populate categories select list and gallery images using (TicketAppDB db = new TicketAppDB()) { model.Categories = new SelectList(db.Categories.ToList(), "Id", "Name"); } // Check model state if (!ModelState.IsValid) { return(View(model)); } // Make sure product name is unique using (TicketAppDB db = new TicketAppDB()) { if (db.Products.Where(x => x.Id != id).Any(x => x.Name == model.Name)) { ModelState.AddModelError("", "That product name is taken!"); return(View(model)); } } using (TicketAppDB db = new TicketAppDB()) { if (uploadPhoto != null && uploadPhoto.ContentLength > 0) { var deleteCommand = "DELETE FROM tblPhoto WHERE ProductId = " + id + ";"; DbConnection(); using (SqlCommand cmd = new SqlCommand(deleteCommand, con)) { con.Open(); cmd.ExecuteNonQuery(); con.Close(); } var photo = new PhotoDTO { Name = System.IO.Path.GetFileName(uploadPhoto.FileName), photoType = photoType.Picture, ContentType = uploadPhoto.ContentType, ProductId = id }; string photoext = Path.GetExtension(photo.Name); var strings = new List <string> { ".png", ".jpeg", ".gif", ".jpg" }; bool contains = strings.Contains(photoext, StringComparer.OrdinalIgnoreCase); if (!contains) { model.Categories = new SelectList(db.Categories.ToList(), "Id", "Name"); ModelState.AddModelError("", "That photo was not uploaded - wrong image extension."); return(View(model)); } using (var reader2 = new System.IO.BinaryReader(uploadPhoto.InputStream)) { photo.Data = reader2.ReadBytes(uploadPhoto.ContentLength); } model.Photos = new List <PhotoDTO> { photo }; db.Photos.Add(photo); db.SaveChanges(); } } using (TicketAppDB db = new TicketAppDB()) { if (uploadPDF != null && uploadPDF.ContentLength > 0) { var deleteCommand = "DELETE FROM tblPdf WHERE ProductId = " + id + ";"; DbConnection(); using (SqlCommand cmd = new SqlCommand(deleteCommand, con)) { con.Open(); cmd.ExecuteNonQuery(); con.Close(); } var invoice = new PdfDTO { Name = System.IO.Path.GetFileName(uploadPDF.FileName), PdfType = PDFType.Invoice, ContentType = uploadPDF.ContentType, ProductId = id }; string pdfext = Path.GetExtension(invoice.Name); if (!pdfext.Equals(".pdf", StringComparison.OrdinalIgnoreCase)) { model.Categories = new SelectList(db.Categories.ToList(), "Id", "Name"); ModelState.AddModelError("", "That pdf was not uploaded - wrong Pdf extension."); return(View(model)); } using (var reader = new System.IO.BinaryReader(uploadPDF.InputStream)) { invoice.Data = reader.ReadBytes(uploadPDF.ContentLength); } model.Pdfs = new List <PdfDTO> { invoice }; db.Pdfs.Add(invoice); db.SaveChanges(); } } PdfDTO pdfs = new PdfDTO(); PhotoDTO images = new PhotoDTO(); string pdfsName; string imagesName; using (TicketAppDB db = new TicketAppDB()) { pdfs = db.Pdfs.Where(x => x.ProductId == id).FirstOrDefault(); pdfsName = pdfs.Name; images = db.Photos.Where(x => x.ProductId == id).FirstOrDefault(); imagesName = images.Name; } if (uploadPDF != null) { pdfsName = uploadPDF.FileName; } if (uploadPhoto != null) { imagesName = uploadPhoto.FileName; } // Update product string product = ""; using (TicketAppDB db = new TicketAppDB()) { ProductDTO dto = db.Products.Find(id); UserDTO user = db.Users.Where(x => x.Username == User.Identity.Name).FirstOrDefault(); dto.Name = model.Name; product = model.Name; dto.Slug = model.Name.Replace(" ", "-").ToLower(); dto.Description = model.Description; dto.ReservationDate = model.ReservationDate; dto.Verified = model.Verified; dto.PdfName = pdfsName; dto.ImageName = imagesName; dto.Price = model.Price; dto.CategoryId = model.CategoryId; dto.UserId = user.Id; CategoryDTO catDTO = db.Categories.FirstOrDefault(x => x.Id == model.CategoryId); dto.CategoryName = catDTO.Name; db.SaveChanges(); } // Set TempData message TempData["SM"] = "You have edited " + product + "'!"; // Redirect return(RedirectToAction("Products", "Shop")); }
public void Create(ProductDTO product) { _logic.Create(product); }
public IEnumerable<string> GetImages(ProductDTO p) //gets image ofincoming product { IEnumerable<string> img = from prodImg in db.Images join prod in db.Products on prodImg.Product.ProductId equals prod.ProductId where prod.ProductId == p.ProductId where prodImg.Product.ProductId == p.ProductId select prodImg.ImageUrl; return img; }
public ProductDTO Add(ProductDTO productInput) { return(unitOfWork.ProductRepo.Add(productInput)); }
public void tblProduct_Update(ProductDTO dt) { string sql = "UPDATE tblProduct SET "+ "Title = @Title, " + "AddedDate = @AddedDate, "+ "AddedBy = @AddedBy, "+ "LastModifyDate = @LastModifyDate, "+ "LastModifyBy = @LastModifyBy, "+ "Description = @Description, "+ "Excerpt = @Excerpt, "+ "BodyContent = @BodyContent, "+ "UnitPrice = @UnitPrice, "+ "UnitsInStock = @UnitsInStock, "+ "Thumbnail = @Thumbnail, "+ "Category = @Category, "+ "Manufacture = @Manufacture, "+ "PriorityOrder = @PriorityOrder, "+ "IsDelete = @IsDelete, "+ "Tag = @Tag, "+ "Currency = @Currency, "+ "Tax = @Tax, "+ "Views = @Views, "+ "IsNew = @IsNew, "+ "Code = @Code, "+ "originalprice = @originalprice, "+ "DiscountPercentage = @DiscountPercentage, "+ "UnitPercent = @UnitPercent WHERE ID = @ID" ; cmd = new SqlCommand(sql, ConnectionData._MyConnection); cmd.CommandType = CommandType.Text; cmd.Parameters.Add("@Title", SqlDbType.NVarChar).Value = dt.Title; cmd.Parameters.Add("@AddedDate", SqlDbType.DateTime).Value = dt.AddedDate; cmd.Parameters.Add("@AddedBy", SqlDbType.NVarChar).Value = dt.AddedBy; cmd.Parameters.Add("@LastModifyDate", SqlDbType.DateTime).Value = dt.LastModifyDate; cmd.Parameters.Add("@LastModifyBy", SqlDbType.NVarChar).Value = dt.LastModifyBy; cmd.Parameters.Add("@Description", SqlDbType.NVarChar).Value = dt.Description; cmd.Parameters.Add("@Excerpt", SqlDbType.NVarChar).Value = dt.Excerpt; cmd.Parameters.Add("@BodyContent", SqlDbType.NVarChar).Value = dt.BodyContent; cmd.Parameters.Add("@UnitPrice", SqlDbType.NVarChar).Value = dt.UnitPrice; cmd.Parameters.Add("@UnitsInStock", SqlDbType.Int).Value = dt.UnitsInStock; cmd.Parameters.Add("@Thumbnail", SqlDbType.NVarChar).Value = dt.Thumbnail; cmd.Parameters.Add("@Category", SqlDbType.Int).Value = dt.Category; cmd.Parameters.Add("@Manufacture", SqlDbType.Int).Value = dt.Manufacture; cmd.Parameters.Add("@PriorityOrder", SqlDbType.Int).Value = dt.PriorityOrder; cmd.Parameters.Add("@IsDelete", SqlDbType.Bit).Value = dt.IsDelete; cmd.Parameters.Add("@Tag", SqlDbType.NVarChar).Value = dt.Tag; cmd.Parameters.Add("@Currency", SqlDbType.Int).Value = dt.Currency; cmd.Parameters.Add("@Tax", SqlDbType.Int).Value = dt.Tax; cmd.Parameters.Add("@Views", SqlDbType.Int).Value = dt.Views; cmd.Parameters.Add("@IsNew", SqlDbType.Bit).Value = dt.IsNew; cmd.Parameters.Add("@Code", SqlDbType.NVarChar).Value = dt.Code; cmd.Parameters.Add("@originalprice", SqlDbType.Bit).Value = dt.originalprice; cmd.Parameters.Add("@DiscountPercentage", SqlDbType.Float).Value = dt.DiscountPercentage; cmd.Parameters.Add("@UnitPercent", SqlDbType.Bit).Value = dt.UnitPercent; cmd.ExecuteNonQuery(); cmd.Dispose(); }