private async Task <FilePath> GetEmptyFilePath(ProductDBModel product) { FilePath oldFilePath = null; //just want to to get this to compile product.ImageFilePath; if (oldFilePath == null) //hitherto there was no image saved { FilePath ret = new FilePath() { ProductID = product.ID }; _context.Add(ret); return(ret); } //If there was an image, let's delete it and return the existing object string oldFileName = oldFilePath.FileName; if (!string.IsNullOrWhiteSpace(oldFileName)) { CloudBlockBlob blob = await GlobalCache.GetImageBlob(oldFileName); //delete the old file await blob.DeleteIfExistsAsync(); } return(oldFilePath); }
public ActionResult List() { var modelDB = new ProductDBModel(); var list = modelDB.getListProduct(); return(View(list)); }
public async Task <IActionResult> Create(ProductViewModel pvm) { if (!ModelState.IsValid) { return(ViewWithSupplierList()); } ; ProductDBModel product = null; try { product = await pvm.ToProductDB(); } catch (FileUploadFailedException e) { Expression <Func <ProductViewModel, IFormFileCollection> > expression = p => p.ImageFiles; string key = ExpressionHelper.GetExpressionText(expression); ModelState.AddModelError(key, e.Message); } if (ModelState.IsValid) { product.SupplierID = Utils.IsInternalUser(User) ? product.SupplierID : Utils.SupplierID(User); _context.Add(product); await _context.SaveChangesAsync(); return(RedirectToAction("Index")); } return(ViewWithSupplierList()); }
/// <summary> /// Create product attributes suited to fit in a product model from regular product attributes /// </summary> /// <param name="product">product from database</param> /// <returns>A list of products attributes, to fit in a product output model</returns> private IEnumerable <Attribute> CreateAttributes(ProductDBModel product) { var productAttributesByProduct = from attribute in _productAttributes where attribute.ProductID == product.ProductID select attribute; var unmappedCodes = new Dictionary <string, int>(); // used for development purposes var generatedAttributes = new List <Attribute>(); foreach (var attr in productAttributesByProduct) { if (_attributeFieldRouting.ContainsKey(attr.AttributeCode)) { switch (_attributeFieldRouting[attr.AttributeCode]) { case FieldRoutingType.TextValue: generatedAttributes.Add(new Attribute { Code = GetCustomizedAttributeCode(attr.AttributeCode, attr.Name).ToLower(), TextValue = new List <string> { attr.Value }, MultiValue = null }); break; case FieldRoutingType.MultiValue: // Note that when attribute value options are really supported, the processing underneath has to change! generatedAttributes.Add(new Attribute { Code = GetCustomizedAttributeCode(attr.AttributeCode, attr.Name).ToLower(), TextValue = null, MultiValue = Regex.Split(attr.Value, GetDelimiterByAttributeCode(attr.AttributeCode)).Select(p => p.Trim()).ToList() }); break; } // attributes to be duplicated here... // refactor this with a triple association like {"Color", "kleur", "hoofdkleur"}, lookup by attributeCode etc. if (attr.AttributeCode == "Color") { generatedAttributes.Add((from duplicatableAttribute in generatedAttributes where duplicatableAttribute.Code == "kleur" select new Attribute { Code = "hoofdkleur", MultiValue = duplicatableAttribute.MultiValue, TextValue = duplicatableAttribute.TextValue }).FirstOrDefault()); } } else { unmappedCodes[attr.AttributeCode] = 0; // see what is missing... } } return(generatedAttributes); }
public ActionResult UpdateStatusProduct(int n_id, string s_status) { var modelDB = new ProductDBModel(); s_status = s_status.Equals("Active") ? "InActive" : "Active"; modelDB.updateStatusProduct(n_id, s_status); return(RedirectToAction("List", "Product")); }
public async Task <IActionResult> OLDEditProbablyTrash(int id, IFormFile upload, [Bind("ID,Brand,SupplierID,SKU,PartNumber,AmazonASIN,Name,Inventory,Info,OurCost,Dealer,MAP,Dimensions,Weight,UPC,Website,PackageContents,Category")] ProductDBModel product) { ProductDBModel existingProduct = await _context.Products .Include(p => p.Supplier) .Include(p => p.ImageFilePaths) .SingleOrDefaultAsync(m => m.ID == id); _context.Entry(existingProduct).State = EntityState.Detached; //If all works well, the filepath will be tracked, but not the product if (id != product.ID || existingProduct == null) { return(NotFound()); } if (!User.IsOwnProduct(existingProduct)) { return(HiddenProductError()); } //EXP 9.28.17. Handle SupplierID if (!Utils.IsInternalUser(User)) { product.SupplierID = existingProduct.SupplierID; } string newFileName = null; //TODO EXP breaking everything! await ProductViewModel.UploadImageWrapper(upload); if (ModelState.IsValid) { try { if (newFileName != null) { FilePath filePath = await GetEmptyFilePath(existingProduct); filePath.FileName = newFileName; //then wire in the new file } _context.Update(product); await _context.SaveChangesAsync(); } catch (DbUpdateConcurrencyException) { if (!ProductExists(product.ID)) { return(NotFound()); } else { throw; } } return(RedirectToAction("Index")); } ViewData["SupplierID"] = new SelectList(_context.Companies, "ID", "ID", product.SupplierID); return(View(product)); }
public bool AddProduct(SalesProductModel data) { ProductDBModel datas = new ProductDBModel(); datas.GetConnectionString(connection.server(), connection.database(), connection.username(), connection.password()); //1 return(datas.AddProduct(data)); }
public SalesProductModel GetCurrentInformation(string id) { ProductDBModel datas = new ProductDBModel(); datas.GetConnectionString(connection.server(), connection.database(), connection.username(), connection.password()); //1 return(datas.GetProductByID(id)); }
private void AppendProduct(ProductDBModel product, ref StringBuilder sb) { foreach (PropertyInfo pi in product.GetType().GetProperties()) { var val = pi.GetValue(product) ?? string.Empty; AppendCell(sb, val.ToString()); } sb.Remove(sb.Length - 1, 1); }
/*public string Name { get; set; } * public int Price { get; set; } * public int Quantity { get; set; } * public string Cathegory { get; set; } * public int NrOfSeats { get; set; } * public int FlightRange { get; set; } * public int NrOfEngines { get; set; }*/ public Product(ProductDBModel dbModel) { Name = dbModel.Name; Price = dbModel.Price; Quantity = dbModel.Quantity; Cathegory = dbModel.Cathegory; NrOfSeats = dbModel.NrOfSeats; FlightRange = dbModel.FlightRange; NrOfEngines = dbModel.NrOfEngines; }
/// <summary> /// Create an arbitrary serializable product model, based on a product and connector /// </summary> /// <param name="product">product from database</param> /// <param name="connectorID">connector ID from context</param> /// <returns>serializable product model</returns> private ProductBizTalkModel CreateProductBizTalkModel(ProductDBModel product, int connectorID) { var productModel = MapSimpleProperties(product); DerivePropertiesFromProductAttributes(ref productModel, product); productModel.Attributes = new List <Attribute>(); productModel.Attributes.AddRange(DeriveArtificialAttributes(product, connectorID)); productModel.Attributes.AddRange(CreateAttributes(product)); productModel.Variants = CreateVariantSection(product).ToList(); return(productModel); }
// GET: ProductList public ActionResult Index() { InfoSession modelSession = new InfoSession(); modelSession = SessionHelper.GetInfoSession(); Session["infoSession"] = modelSession; var productModelDB = new ProductDBModel(); var planModelDB = new PlanDBModel(); IndexModel model = new IndexModel(); model.Products = productModelDB.getListProduct(); model.Plans = planModelDB.getListPlan(); return(View(model)); }
// GET: Admin/Store/Edit/5 public ActionResult Edit(int n_id) { var modelDB = new ProductDBModel(); var model = new ProductModel(); var result = modelDB.getProductById(n_id); model.id = result.N_ID; model.productName = result.S_NAME; model.price = result.N_PRICE; model.type = result.S_TYPE; model.detail = result.S_DETAIL; model.description = result.S_DESCRIPTION; model.status = result.S_STATUS; model.createdDate = result.D_CREATED; return(View(model)); }
//EXP 9.12.17. Making its own method public static void TrashInitialize(InventoryContext context) { //if (context.Products.Any()) return; var suppliers = new Company[] { new Company { /*ID=98,*/ Name = "First Supplier" }, //Comenting out the IDs, to see if that'll cause it to stop throwing errors new Company { /*ID=2,*/ Name = "Second Supplier" }, new Company { /*ID=3, */ Name = "Third Supplier" }, new Company { /*ID=4,*/ Name = "Fourth Supplier" }, }; foreach (Company m in suppliers) { context.Companies.Add(m); } context.SaveChanges(); var products = new ProductDBModel[] { new ProductDBModel { Name = "the first product", SupplierID = 1, Info = "this product, from producer 1, rocks the f*****g house" }, new ProductDBModel { Name = "the first product", SupplierID = 2, Info = "this product, from producer 2, rocks the f*****g house" }, new ProductDBModel { Name = "the first product", SupplierID = 3, Info = "this product, from producer 3, rocks the f*****g house" }, new ProductDBModel { Name = "the first product", SupplierID = 4, Info = "this product, from producer 4, rocks the f*****g house" }, }; foreach (ProductDBModel c in products) { context.Products.Add(c); } context.SaveChanges(); }
public HttpResponseMessage GetById(int id) { ProductData data = new ProductData(); ProductDBModel product = data.GetProductById(id); HttpResponseMessage response; if (product == null) { response = Request.CreateResponse(HttpStatusCode.NotFound, new { Message = "No data found matching given parameters values." }); } else { response = Request.CreateResponse(HttpStatusCode.OK, product); } return(response); }
public ActionResult Edit(ProductModel model) { try { var modelDB = new ProductDBModel(); TB_PRODUCT product = new TB_PRODUCT(); product.N_ID = model.id; product.S_NAME = model.productName; product.N_PRICE = model.price; product.S_TYPE = model.type; product.S_DESCRIPTION = model.description; modelDB.updateProductById(product); return(RedirectToAction("List")); } catch { return(View()); } }
public ActionResult Create(ProductModel model) { try { var modelDB = new ProductDBModel(); TB_PRODUCT product = new TB_PRODUCT(); product.S_NAME = model.productName; product.N_PRICE = model.price; product.S_TYPE = model.type; product.S_DETAIL = model.detail; product.S_DESCRIPTION = model.description; modelDB.createProduct(product); return(RedirectToAction("List")); } catch { return(View()); } }
/// <summary> /// Maps simple product properties into a product model /// </summary> /// <param name="product">product from database</param> /// <returns>Partially filled product model</returns> private static ProductBizTalkModel MapSimpleProperties(ProductDBModel product) { return(new ProductBizTalkModel { AttributeSet = "Default", Websites = new List <string> { "base" }, TaxClass = "high", Visibility = 4, Sku = product.VendorItemNumber, Name = product.ProductName, Description = product.LongContentDescription, ShortDescription = product.ShortContentDescription, LongSummary = product.LongSummaryDescription, ShortSummary = product.ShortSummaryDescription, Price = product.Price, Status = product.IsActive ? 1 : 0 }); }
/// <summary> /// Create a list of simple product data (called variants in the terminology of the product output model) /// </summary> /// <param name="product">product from database</param> /// <returns>A list of variant structures, to fit in a product output model</returns> private IEnumerable <Variant> CreateVariantSection(ProductDBModel product) { return(from variant in _relatedProducts where variant.ConfigurableProductID == product.ProductID select new Variant { Sku = variant.Barcode, Status = variant.IsActive ? 1 : 0, Visibility = 1, PriceCorrection = (int)(variant.Price - product.Price), Options = (from relatedProductAttribute in _productAttributes where relatedProductAttribute.ProductID == variant.SimpleProductID && _variantAttributes.Contains(relatedProductAttribute.AttributeCode) select new Option { Code = relatedProductAttribute.Name.ToLower(), Value = relatedProductAttribute.Value, }).ToList() }); }
public async Task <IActionResult> Index(string sku, string supplier, int num) { var products = await _context.Products.AsNoTracking() .Include(p => p.Supplier) .Include(p => p.ImageFilePaths) .Where(p => p.SKU.ToUpper() == sku.ToUpper()) .Where(p => p.Supplier.ID.ToString() == supplier || p.Supplier.Name.ToUpper() == supplier.ToUpper()) .ToListAsync(); if (products.Count() == 0) { return(Error($"No product was found whose SKU is <strong>{sku}</strong> and whose supplier is <strong>{supplier}</strong>.")); } else if (products.Count() == 1) { ProductDBModel product = products.First(); string fileName = string.Empty; try { fileName = product.ImageFilePaths.ElementAt(num - 1).FileName; //subtract one, because users are indexing from 1 instead of 0. } catch (ArgumentOutOfRangeException) { string message = $"It appears you were attempting to access product number <a href='/Products/Details/{product.ID}'>{product.ID}</a>. " + "However you did not specify a valid image number"; return(Error(message)); } string url = (await GlobalCache.GetImageBlob(fileName)).Uri.AbsoluteUri; return(Redirect(url)); } else { string message = $"The following products from supplier {supplier} all have sku {sku}. Clean up the data before attempting to access photos."; foreach (Product product in products) { message += $"<br/> <a href = '/Products/Details/{product.ID}' >{product.ID}</a>"; } return(Error(message)); } }
/// <summary> /// Derive artificial product attributes (in the sense that they're not part of the Concentrator product attribute datamodel) from other product properties /// The codes used here are not part of the product attribute set OR redefined to be sourced from another source! /// Note they are also localized! /// </summary> /// <param name="product">product from database</param> /// <param name="connectorID">connector ID from context</param> /// <returns>A list of products attributes, to fit in a product output model</returns> private IEnumerable <Attribute> DeriveArtificialAttributes(ProductDBModel product, int connectorID) { var generatedAttributes = new List <Attribute>(); generatedAttributes.Add(new Attribute { Code = "artikelcode", TextValue = new List <string> { product.VendorItemNumber.Split(" ").First() }, MultiValue = null }); generatedAttributes.Add(new Attribute { Code = "merk", TextValue = new List <string> { product.BrandName }, MultiValue = null }); #region Category processing var masterGroupMappingID = _currentProducts .Where(x => x.ProductID == product.ProductID) .Select(x => x.MasterGroupMappingID) .FirstOrDefault(); var categoryHierarchy = DeriveCategoryPath(masterGroupMappingID, connectorID); if (categoryHierarchy.Any()) { generatedAttributes.Add(ConvertHierarchyToCategoryAttribute(categoryHierarchy)); } #endregion return(generatedAttributes); }
// GET: Detail public ActionResult Index(int id, string type) { if (id < 1) { return(RedirectToAction("Index", "Home")); } else { InfoSession modelSession = new InfoSession(); modelSession = SessionHelper.GetInfoSession(); Session["infoSession"] = modelSession; DetailModel detailModel = new DetailModel(); if (type.Equals("PLAN")) { var planDBModel = new PlanDBModel(); var model = planDBModel.getPlanById(id); detailModel.id = model.N_ID; detailModel.name = model.S_NAME; detailModel.type = type; detailModel.detail = model.S_DETAIL; detailModel.description = model.S_DESCRIPTION; detailModel.total = 1; } else { var productDBModel = new ProductDBModel(); var model = productDBModel.getProductById(id); detailModel.id = model.N_ID; detailModel.name = model.S_NAME; detailModel.type = type; detailModel.detail = model.S_DETAIL; detailModel.description = model.S_DESCRIPTION; detailModel.price = model.N_PRICE; detailModel.total = 1; } return(View(detailModel)); } }
private void btnAdd_Click(object sender, EventArgs e) { ProductController controller = new ProductController(); SalesProductModel model = new SalesProductModel(); ProductDBModel db = new ProductDBModel(); model.Name = txtProductName.Text; model.Serialnumber = Convert.ToInt32(txtSerialnumber.Text); model.Quantity = Convert.ToInt32(txtQuantity.Text); model.Unitprice = Convert.ToInt32(txtPricePerUnit.Text); model.Description = txtDescription.Text; model.DateImport = dtpDateImport.Text; //true mean visible, have to use another if (db.CheckVisibleName(model.Name)) { MessageBox.Show("Name visible"); } else { if (db.CheckVisibleSerialnumber(model.Serialnumber.ToString())) { MessageBox.Show("Serialnumber visible"); } else { if (controller.AddProduct(model)) { MessageBox.Show("insert successful"); } else { MessageBox.Show("insert invalide"); } } } }
public async Task <IActionResult> Edit(int id, ProductViewModel product) { ProductDBModel existingProduct = await _context.Products.Include(p => p.ImageFilePaths).SingleOrDefaultAsync(m => m.ID == product.ID); if (id != product.ID || existingProduct == null) { return(NotFound()); } if (!User.IsOwnProduct(existingProduct)) { return(HiddenProductError()); } if (await FailsLockedProductPolicy(product)) { return(new ChallengeResult()); } if (ModelState.IsValid) { try { ProductDBModel pdb = await product.ToProductDB(existingProduct); DeleteOldImages(product, existingProduct.ImageFilePaths); //now merge pdb with existing product foreach (PropertyInfo pi in typeof(ProductDBModel).GetProperties()) { var attr = pi.GetCustomAttribute <RestrictedFieldAttribute>(true); if (attr == null || attr.CanUserEdit(User)) { var value = pi.GetValue(pdb); pi.SetValue(existingProduct, value); } } await _context.SaveChangesAsync(); /* handled more generically above * if (!Utils.IsInternalUser(User)) * { * pdb.SupplierID = existingProduct.SupplierID; * }*/ } catch (FileUploadFailedException e) { Expression <Func <ProductViewModel, IFormFileCollection> > expression = p => p.ImageFiles; string key = ExpressionHelper.GetExpressionText(expression); ModelState.AddModelError(key, e.Message); } catch (DbUpdateConcurrencyException) { if (!ProductExists(product.ID)) { return(NotFound()); } else { throw; } } return(RedirectToAction("Index")); } ViewData["SupplierID"] = new SelectList(_context.Companies, "ID", "ID", product.SupplierID); return(View(product)); }
/// <summary> /// These product attributes are promoted from the attribute list in the output to dedicated properties /// </summary> /// <param name="productModel">IN: a product output model, OUT: enriched product output model</param> /// <param name="product">product from database</param> private void DerivePropertiesFromProductAttributes(ref ProductBizTalkModel productModel, ProductDBModel product) { //try //{ // productModel.SpecialPriceStartDate = // DateTime.Parse(_productAttributes.Where(x => x.AttributeCode == "Special_From_Date").Select(x => x.Value).FirstOrDefault()); //} //catch (Exception ex) //{ // TraceError("Could not extract \"Special_From_Date\" for product \"{0}\". Error: {1}", product.ProductID, ex.Message); //} //try //{ // productModel.SpecialPriceEndDate = DateTime.Parse(_productAttributes.Where(x => x.AttributeCode == "Special_To_Date").Select(x => x.Value).FirstOrDefault()); //} //catch (Exception ex) //{ // TraceError("Could not extract \"Special_To_Date\" for product \"{0}\". Error: {1}", product.ProductID, ex.Message); //} try { productModel.Weight = _productAttributes.Where(x => x.AttributeCode == "weight").Select(x => x.Value).FirstOrDefault(); } catch (Exception ex) { TraceError("Could not extract \"weight\" for product \"{0}\". Error: {1}", product.ProductID, ex.Message); } }
public static bool IsOwnProduct(this ClaimsPrincipal user, ProductDBModel product) { return(Utils.IsInternalUser(user) || user.FindFirst(ClaimNames.EmployerID).Value == product.SupplierID.ToString()); }
private IActionResult ViewWithSupplierList(ProductDBModel currentProduct = null) { ViewData[KeyNames.SupplierID] = Utils.CompanyList(_context, currentProduct?.Supplier); return(View()); }
public async Task <ChangedInformationResultModel> AddProducts(AddNewProductRequest[] products) { int addedCount = 0; foreach (var product in products) { var existProduct = await _dataContext.Products.FirstOrDefaultAsync(x => x.Name == product.Name); if (existProduct == null) { var dbModel = new ProductDBModel { Name = product.Name, Count = product.Count, PrimaryPrice = product.PrimaryPrice, SecondaryPrice = product.SecondaryPrice, }; var category = await _dataContext.Categories.FirstOrDefaultAsync(x => x.Name == product.Category); if (category == null) { category = (await _dataContext.Categories.AddAsync(new CategoryDBModel { Name = product.Category })).Entity; await _dataContext.SaveChangesAsync(); } dbModel.CategoryId = category.CategoryID; var countType = await _dataContext.CountTypes.FirstOrDefaultAsync(x => x.Name == product.CountType); if (countType == null) { countType = (await _dataContext.CountTypes.AddAsync(new CountTypeDBModel { Name = product.CountType })).Entity; await _dataContext.SaveChangesAsync(); } dbModel.CounteTypeId = countType.CountTypeId; var productImage = await _dataContext.ProductImages.FirstOrDefaultAsync(x => x.ImageUrl == product.ImageProductUrl); if (productImage == null) { productImage = (await _dataContext.ProductImages.AddAsync(new ImageProductDBModel { ImageUrl = product.ImageProductUrl })).Entity; await _dataContext.SaveChangesAsync(); } dbModel.ImageId = productImage.ImageId; dbModel = (await _dataContext.Products.AddAsync(dbModel)).Entity; await _dataContext.SaveChangesAsync(); foreach (var shop in product.Shops) { var shopDB = await _dataContext.Shops.FirstOrDefaultAsync(x => x.Name == shop); if (shopDB == null) { shopDB = (await _dataContext.AddAsync(new ShopDBModel { Name = shop })).Entity; await _dataContext.SaveChangesAsync(); } await _dataContext.ProductsToShops.AddAsync(new ProductToShopDBModel { ProductId = dbModel.ProductId, ShopId = shopDB.ShopId }); await _dataContext.SaveChangesAsync(); } await _dataContext.SaveChangesAsync(); addedCount++; } } if (addedCount > 0) { return(new ChangedInformationResultModel { Success = true }); } else { return(new ChangedInformationResultModel { Success = false, ErrorsMessages = new[] { "Продукты не добавлены" } }); } }