public async Task <IHttpActionResult> PutProduct(int id, ProductVm model) { if (!ModelState.IsValid) { return(BadRequest(ModelState)); } if (id != model.ProductId) { return(BadRequest()); } _db.Entry(model).State = EntityState.Modified; try { await _db.SaveChangesAsync(); } catch (DbUpdateConcurrencyException) { if (!ProductExists(id)) { return(NotFound()); } throw; } return(StatusCode(HttpStatusCode.NoContent)); }
public async Task <IActionResult> Get(long id) { var product = _productRepository.Query() .Include(x => x.ThumbnailImage) .Include(x => x.Medias).ThenInclude(m => m.Media) .FirstOrDefault(x => x.Id == id); var currentUser = await _workContext.GetCurrentUser(); if (!User.IsInRole("admin")) { return(BadRequest(new { error = "You don't have permission to manage this product" })); } var productVm = new ProductVm { Id = product.Id, Name = product.Name, Slug = product.Slug, MetaTitle = product.MetaTitle, MetaKeywords = product.MetaKeywords, MetaDescription = product.MetaDescription, ShortDescription = product.ShortDescription, Description = product.Description, Specification = product.Specification, OldPrice = product.OldPrice, Price = product.Price, SpecialPrice = product.SpecialPrice, SpecialPriceStart = product.SpecialPriceStart, SpecialPriceEnd = product.SpecialPriceEnd, IsPublished = product.IsPublished, CategoryId = product.CategoryId, ThumbnailImageUrl = _mediaService.GetThumbnailUrl(product.ThumbnailImage), BrandId = product.BrandId, TyreWidthId = product.TyreWidthId, TyreProfileId = product.TyreProfileId, TyreRimSizeId = product.TyreRimSizeId }; foreach (var productMedia in product.Medias.Where(x => x.Media.MediaType == MediaType.Image)) { productVm.ProductImages.Add(new ProductMediaVm { Id = productMedia.Id, MediaUrl = _mediaService.GetThumbnailUrl(productMedia.Media) }); } foreach (var productMedia in product.Medias.Where(x => x.Media.MediaType == MediaType.File)) { productVm.ProductDocuments.Add(new ProductMediaVm { Id = productMedia.Id, Caption = productMedia.Media.Caption, MediaUrl = _mediaService.GetMediaUrl(productMedia.Media) }); } return(Json(productVm)); }
public async Task <ProductVm> GetById(string productId) { var product = await _context.products.FindAsync(productId); var categories = await(from c in _context.products join ct in _context.productCategories on c.idCategory equals ct.idCategory where c.idCategory == productId select ct.categoryName).ToListAsync(); var image = await _context.productPhotos.Where(x => x.idProduct == productId).FirstOrDefaultAsync(); var productViewModel = new ProductVm() { idProduct = product.idProduct, idSize = product.idSize, idBrand = product.idBrand, idColor = product.idColor, idType = product.idType, idCategory = product.idCategory, price = product.price, salePrice = product.salePrice, detail = product.detail, dateAdded = DateTime.Now, photoReview = "a", ThumbnailImage = image != null?image.link:"no-image.jpg" }; return(productViewModel); }
private async Task <CategoryAssignRequest> GetCategoryAssignRequest(int id) { var languageId = HttpContext.Session.GetString(SystemConstants.AppSettings.DefaultLanguageId); ProductVm productObj = null; if (id > 0) { productObj = await _productApiClient.GetById(id, languageId); } var categories = await _categoryApiClient.GetAll(languageId); var categoryAssignRequest = new CategoryAssignRequest(); foreach (var role in categories) { categoryAssignRequest.Categories.Add(new SelectItem() { Id = role.Id.ToString(), Name = role.Name, Selected = productObj != null && productObj.Categories.Contains(role.Name) }); } return(categoryAssignRequest); }
private void OnControlPanelInvoked(ProductVm product) { foreach (var productTypePanelControl in ProductTypesPanelsContainer.Children.OfType <ProductTypePanelControl>()) { productTypePanelControl.HideControlPanels(product); } }
public IActionResult Index() { var products = _productService.GetProducts().ToList(); if (products == null) { return(NotFound()); } var model = new ProductListVm(); foreach (var product in products) { var productVm = new ProductVm() { Id = product.Id, Name = product.Name, Description = product.Description, Price = product.Price, MediaId = product.MediaId }; model.ProductList.Add(productVm); } return(View(model)); }
public async Task <ProductVm> GetById(int productId, string languageId) { var product = await _context.Products.FindAsync(productId); var productTranslation = await _context.ProductTranslations.FirstOrDefaultAsync(x => x.ProductId == productId && x.LanguageId == languageId); var categories = await(from c in _context.Categories join ct in _context.CategoryTranslations on c.Id equals ct.CategoryId join pic in _context.ProductInCategories on c.Id equals pic.CategoryId where pic.ProductId == productId && ct.LanguageId == languageId select ct.Name).ToListAsync(); var productViewModel = new ProductVm() { Id = product.Id, DateCreated = product.DateCreated, Description = productTranslation != null ? productTranslation.Description : null, LanguageId = productTranslation.LanguageId, Details = productTranslation != null ? productTranslation.Details : null, Name = productTranslation != null ? productTranslation.Name : null, OriginalPrice = product.OriginalPrice, Price = product.Price, SeoAlias = productTranslation != null ? productTranslation.SeoAlias : null, SeoDescription = productTranslation != null ? productTranslation.SeoDescription : null, SeoTitle = productTranslation != null ? productTranslation.SeoTitle : null, Stock = product.Stock, ViewCount = product.ViewCount, Categories = categories }; return(productViewModel); }
public HttpResponseMessage PutProduct([FromUri] int id, ProductVm model) { if (!ModelState.IsValid) { IEnumerable <string> errors = ModelState.Values.SelectMany(e => e.Errors).Select(e => e.ErrorMessage); return(Request.CreateResponse(HttpStatusCode.BadRequest, String.Join(",", errors))); } Product product = uow.ProductManager.GetEntity(id); if (product == null) { return(Request.CreateResponse(HttpStatusCode.BadRequest, "product not found")); } Product prod = Mapper.Map <ProductVm, t>(model); prod.Id = product.Id; uow.UpdateProduct(prod); var response = Request.CreateResponse(HttpStatusCode.OK, new { status = true, message = "product updated successfully" }); string uri = Url.Link("GetProduct", new { id = prod.Id }); response.Headers.Location = new Uri(uri); return(response); // return Ok(new { status = true, message = "product updated successfully" }); }
public void CreateUser_ThowsException(ProductVm product) { _mediator.Setup(m => m.Send(It.IsAny <AddProductCommand>(), default)) .Throws(new Exception()); Assert.That(() => _controller.Post(product), Throws.TypeOf <Exception>()); }
public async Task <IActionResult> Edit(int id, [Bind("ProductId,Article,SupplierName,CategoryId,Price,VatProduct,AdvancePaymentTax,Notes")] ProductVm Product) { if (id != Product.ProductId) { return(NotFound()); } if (ModelState.IsValid) { try { await _ProductMapper.BlUpdateAsync(Product); } catch (DbUpdateConcurrencyException) { var Exists = _ProductMapper.ProductExists((Product.ProductId)); if (!Exists) { return(NotFound()); } else { throw; } } return(RedirectToAction(nameof(Index))); } var company = _categorymapper.BlGetAllCategory(); ViewData["CategoryId"] = new SelectList(company, "CategoryId", "CategoryName"); return(View(Product)); }
// GET: Products/Details/5 public ActionResult Details(int?id) { if (id == null) { return(new HttpStatusCodeResult(HttpStatusCode.BadRequest)); } Product product = db.Products.Find(id); if (product == null) { return(HttpNotFound()); } ProductVm productvm = new ProductVm { Brand = product.Brand.Name, Category = product.Category.Name, Description = product.Description, Price = product.Price, StockLevel = product.StockLevel, Name = product.Name, Id = product.Id }; return(View(productvm)); }
public IActionResult Upsert(int?id) { ProductVm productVm = new ProductVm() { Product = new Product(), CategoryList = _unitOfWork.Catagory.GetAll().Select(i => new SelectListItem { Text = i.Name, Value = i.Id.ToString() }), CoverTypeList = _unitOfWork.coverType.GetAll().Select(i => new SelectListItem { Text = i.Name, Value = i.Id.ToString() }) }; if (id == null) { //this is for create return(View(productVm)); } //this is for edit productVm.Product = _unitOfWork.Product.Get(id.GetValueOrDefault()); if (productVm.Product == null) { return(NotFound()); } return(View(productVm)); }
public async Task <ActionResult <IEnumerable <ProductVm> > > GetProductByCategory(int idCate) { var productList = await _context.Products .Where(p => p.CategoryId == idCate) .ToListAsync(); List <ProductVm> productVmList = new List <ProductVm>(); foreach (var x in productList) { ProductVm get = new ProductVm(); get.ProductId = x.ProductId; get.ProductName = x.ProductName; get.Description = x.Description; get.Price = x.Price; get.CreatedDate = x.CreatedDate; get.UpdatedDate = x.UpdatedDate; get.BrandId = x.BrandId; get.Images = _storageService.GetFileUrl(x.Images); //for (int i = 0; i < x.ImageFiles.Count; i++) //{ // get.ImageLocation.Add(x.ImageFiles.ElementAt(i).ImageLocation); //} productVmList.Add(get); } return(productVmList); }
public async Task <ProductVm> GetById(int id, string LanguageId) { var sessions = _httpContextAccessor .HttpContext .Session .GetString(SystemConstants.AppSettings.Token); var client = _httpClientFactory.CreateClient(); client.BaseAddress = new Uri(_configuration[SystemConstants.AppSettings.BaseAddress]); client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", sessions); var response = await client.GetAsync($"/api/products/{id}/{LanguageId}"); // đúng đương dẫn đấy var body = await response.Content.ReadAsStringAsync(); // đọc nội dung chuỗi lấy từ response về if (response.IsSuccessStatusCode) { //response sẽ là một chuỗi json trả về chúng ta cần giải nó // Và phương thức tôi đang sử dụng để giải tuần tự hóa một phản hồi JSON thành một TResponse đối tượng ProductVm myDeserializedObjList = (ProductVm)JsonConvert.DeserializeObject(body, typeof(ProductVm));// muốn trả về kiểu TResponse nên ép sang nó return(myDeserializedObjList); } return(JsonConvert.DeserializeObject <ProductVm>(body)); // trả về một sản phẩm }
public IActionResult ViewProducts() { if (!_currentUser.IsAdmin || !_currentUser.IsAuthenticated) { return(RedirectToAction("Login", "Account")); } var products = _productService.GetProducts().ToList(); if (products == null) { return(NotFound()); } var model = new ProductListVm(); foreach (var product in products) { var productVm = new ProductVm() { Id = product.Id, Name = product.Name, Description = product.Description, Price = product.Price, MediaId = product.MediaId, StockNumber = product.StockNumber }; model.ProductList.Add(productVm); } return(View(model)); }
public void CreateUser_ThowsException(ProductVm product) { _mediator.Setup(m => m.Send(It.IsAny <GetProductByIdQuery>(), default)) .Throws(new Exception()); Assert.That(() => _controller.Get(product.Id), Throws.TypeOf <Exception>()); }
public void DeleteProductFromView(ProductVm product) { // Products.Remove(product); // var productView = ProductsContainer.Children.OfType<ProductViewControl>().FirstOrDefault(x=>x.Product.Id == product.Id); // // ProductsContainer.Children.Remove(productView); }
public ProductVm GetProductById(int?id) { Product model = this.Context.Products.Find(id); ProductVm vm = Mapper.Instance.Map <Product, ProductVm>(model); return(vm); }
private void OnControlPanelInvoked(ProductVm product) { foreach (var productViewControl in ProductsContainer.Children.OfType <ProductViewControl>().Where(x => x.Product.Id != product.Id)) { productViewControl.HideControlPanel(); } }
public void HideControlPanels(ProductVm product) { // foreach (var productViewControl in ProductsContainer.Children.OfType<ProductViewControl>().Where(x => x.Product.Id != product.Id)) // { // productViewControl.HideControlPanel(); // } }
public ActionResult EditProduct(int id) { //declare productvm ProductVm model; using (Db db = new Db()) { //get product ProductDTO dto = db.Products.Find(id); //confirm product exists if (dto == null) { return(Content("The product does not exist")); } //init model model = new ProductVm(dto); //make a select list model.Categories = new SelectList(db.Categories.ToList(), "Id", "Name"); //get all gallery images model.GalleryImages = Directory.EnumerateFiles(Server.MapPath("~/Images/Uploads/Products/" + id + "/Gallery/Thumbs")) .Select(fn => Path.GetFileName(fn)); } //return product view with model return(View(model)); }
public async Task <ActionResult <ProductVm> > GetProduct(int id) { var product = await _applicationDbContext.Products.Include("Images").Include("Comments").Where(x => x.ProductID == id).FirstAsync(); if (product == null) { return(NotFound()); } var prodVM = new ProductVm(); prodVM.ProductId = product.ProductID; prodVM.Name = product.Name; prodVM.Price = product.Price; prodVM.CPU = product.CPU; prodVM.Quantity = product.Quantity; prodVM.Screen = product.Screen; prodVM.HardDrive = product.HardDrive; prodVM.Card = product.Card; prodVM.GateWay = product.GateWay; prodVM.Size = product.Size; prodVM.BrandID = product.BrandID; prodVM.Images = product.Images.Select(x => x.ImageName).ToList(); prodVM.Commentings = product.Comments.Select(x => new CommentingVm { star = x.Star, date = x.Date, content = x.Content, userName = x.UserName }).ToList(); return(prodVM); }
private void AddOrDeleteProductVariation(ProductVm productVm, Product product) { var childProducts = product.GetLinkedProducts(ProductLinkType.Super); foreach (var productVariationVm in productVm.Variations) { if (productVariationVm.Id == 0) // New variation added { var productVariation = product.Clone(); productVariation.Name = productVariationVm.Name; productVariation.SeoTitle = StringHelper.ToUrlFriendly(productVariationVm.Name); productVariation.Price = productVariationVm.Price; productVariation.OldPrice = productVariationVm.OldPrice; productVariation.NormalizedName = productVariationVm.NormalizedName; productVariation.HasOptions = false; productVariation.IsVisibleIndividually = false; productVariation.ThumbnailImage = product.ThumbnailImage; foreach (var combinationVm in productVariationVm.OptionCombinations) { productVariation.AddOptionCombination(new ProductOptionCombination { OptionId = combinationVm.OptionId, Value = combinationVm.Value, SortIndex = combinationVm.SortIndex }); } product.AddProductLinks(new ProductLink { LinkType = ProductLinkType.Super, Product = product, LinkedProduct = productVariation }); } else { var productVariation = childProducts.FirstOrDefault(x => x.Id == productVariationVm.Id); productVariation.Price = productVariationVm.Price; productVariation.OldPrice = productVariationVm.OldPrice; productVariation.IsDeleted = false; // Main product is renamed => Rename child products based on the new name if (product.Name != productVm.Name) { productVariation.Name = productVariation.Name.Replace(product.Name, productVm.Name); productVariation.SeoTitle = StringHelper.ToUrlFriendly(productVariation.Name); } } } var removedVariations = product.ProductLinks .Where(item => item.LinkType == ProductLinkType.Super && !productVm.Variations.Any(v => v.Id == item.LinkedProduct.Id)); foreach (var productLink in removedVariations) { _productLinkRepository.Remove(productLink); productLink.LinkedProduct.IsDeleted = true; } }
/// <summary> /// This method will accept the Product details and save it into the database. /// </summary> /// <param name="objProduct">Object containing the details of Product</param> /// <returns>Returns the same Object</returns> public ResultStatus SaveProduct(ProductVm objProduct) { if (!IsProductExist(objProduct)) { try { using (Data.Model.LicenseManagementMVCEntities DbContext = new LicenseManagementMVCEntities()) { try { Data.Model.Product objProductData = new Data.Model.Product(); objProductData.ProductName = objProduct.ProductName; DbContext.Products.Add(objProductData); DbContext.SaveChanges(); } catch (Exception) { return(ResultStatus.QueryNotExecuted); } } } catch (Exception) { return(ResultStatus.ConnectionError); } } else { return(ResultStatus.AlreadyExist); } return(ResultStatus.Success); }
public ActionResult UpdateProduct(ProductVm model, HttpPostedFileBase avatar, string returnUrl) { ProductImage avatarka = null; if (avatar != null) { var fileName = Guid.NewGuid() + "_" + avatar.FileName; var filePath = Server.MapPath("/Content/img/goods/UploadsImages"); var fullPath = Path.Combine(filePath, fileName); avatar.SaveAs(fullPath); avatarka = new ProductImage { Path = "/Content/img/goods/UploadsImages/" + fileName, PhotoType = PhotoType.Avatar }; } if (model.Product.Id > 0) { _admin.EditProductHead(model.Product, avatarka); } else { var resalt = _admin.CreateProduct(model.Product, avatarka); return(RedirectToAction("CatItemDetails", new { id = resalt })); } return(Redirect(returnUrl)); }
public ActionResult Product(ProductVm model) { if (ModelState.IsValid) { Entity.EntityModels.Product product = Mapper.Map <Entity.EntityModels.Product>(model); if (product.Id == 0) { var extension = Path.GetExtension(model.Image1.FileName); var path = Path.Combine(Server.MapPath("~/Content/Student/Photo/")); if (!Directory.Exists(path)) { Directory.CreateDirectory(path); } model.Image1.SaveAs(path + model.Id + extension); ViewBag.message = productManager.Save(product); } else { ViewBag.message = productManager.Update(product); } model = new ProductVm(); ModelState.Clear(); } ViewBag.Items = GetItemDropdownList(); ViewBag.Brand = GetItemForBrandDropdownList(); ViewBag.Category = GetItemForCategoryDropdownList(); List <Product> products = productManager.GetAllProduct(); ViewBag.Product = products; return(View(model)); }
public async Task <ProductVm> GetById(int productId, string languageId) { var product = await _context.products.FindAsync(productId); var productTranslation = await _context.productDetails.FirstOrDefaultAsync(x => x.ProductId == productId && x.LanguageId == languageId); var categories = await(from c in _context.Categories join ct in _context.CategoryTranslations on c.idCategory equals ct.CategoryId join pic in _context.ProductInCategories on c.idCategory equals pic.idCategory where pic.ProductId == productId && ct.LanguageId == languageId select ct.Name).ToListAsync(); var productViewModel = new ProductVm() { Id = product.ProductId, ProductName = productTranslation.ProductName, price = productTranslation.price, salePrice = productTranslation.salePrice, ViewCount = product.ViewCount, detail = productTranslation.detail, dateAdded = productTranslation.dateAdded, LanguageId = productTranslation.LanguageId, Categories = categories }; return(productViewModel); }
public ActionResult AddProduct() { ProductVm model = new ProductVm { Categories = new SelectList(db.Categories.ToList(), "Id", "Name") }; return(View(model)); }
public ActionResult ViewDetails(int Id) { ProductVm ViewDetails = new ProductVm(); var SingleItem = ProductHolder.FetchProduct().Where(p => p.ItemId == Id).ToList(); ViewDetails.MyProduct = SingleItem; return(View(ViewDetails)); }
public IActionResult UpdateProduct(ProductVm model) { if (!_currentUser.IsAdmin || !_currentUser.IsAuthenticated) { return(RedirectToAction("Login", "Account")); } if (_currentUser.IsAdmin) { if (!ModelState.IsValid) { return(View(model)); } if (_productService.GetProductById(model.Id) == null) { return(View(model)); } var productToBeUpdated = _mapper.Map <Product>(model); var existingProduct = _productService.GetProductById(model.Id); if (model.MediaVm != null) { model.MediaVm.Content = FileToByteArray(model.MediaVm.File); var media = _mapper.Map <Media>(model.MediaVm); productToBeUpdated.Media = media; } if (existingProduct != null) { existingProduct.Description = productToBeUpdated.Description; existingProduct.Media = productToBeUpdated.Media; existingProduct.MediaId = productToBeUpdated.MediaId; existingProduct.Name = productToBeUpdated.Name; existingProduct.OrderItems = productToBeUpdated.OrderItems; existingProduct.Price = productToBeUpdated.Price; existingProduct.StockNumber = productToBeUpdated.StockNumber; if (_productService.UpdateProduct(existingProduct)) { model.DisplayMessage = "Successfuly saved"; model.IsOkay = true; } else { model.DisplayMessage = "Error"; model.IsOkay = false; } } return(View(model)); } else { return(ForbiddenView()); } }
public PPEditorJob(Model.Job model, DataServices.JobDataService jobDataService) { _jobDataService = jobDataService; Replications.Add(model); Deadline = model.Deadline; ReleaseDT = model.ReleaseTime; Code = model.Code; Quantity = model.Quantity; Weight = model.Weight; Description = model.Description; FpcId = model.FPC.Id; Product = new ProductVm(model.ProductRework.Product, null); ProductRework = new ProductReworkVm(model.ProductRework, Product); initializeCommands(); }