public void One_to_one_foreign_key_value_is_obtained_from_reference_to_principal() { var model = BuildModel(); var principal = new Product { Id = 21 }; var dependent = new ProductDetail { Product = principal }; var dependentEntry = CreateContextConfiguration(model).StateManager.GetOrCreateEntry(dependent); Assert.Equal(21, CreateValueGenerator().Next(dependentEntry, model.GetEntityType(typeof(ProductDetail)).GetProperty("Id"))); }
public void One_to_one_foreign_key_value_is_obtained_from_reference_to_principal() { var model = BuildModel(); var principal = new Product { Id = 21 }; var dependent = new ProductDetail { Product = principal }; var contextServices = CreateContextServices(model); var dependentEntry = contextServices.GetRequiredService<IStateManager>().GetOrCreateEntry(dependent); var property = model.GetEntityType(typeof(ProductDetail)).GetProperty("Id"); PropagateValue(contextServices.GetRequiredService<IKeyPropagator>(), dependentEntry, property); Assert.Equal(21, dependentEntry[property]); }
private void button2_Click(object sender, EventArgs e) { ProductDetail productDetail = new ProductDetail(PID, Addcart); productDetail.ShowDialog(); }
private void UpdateProductDetail(StockTransfer transfer) { if (transfer.StockTransferDetails != null) { List <string> ids = transfer.StockTransferDetails.Select(x => x.ProductDetailId).ToList(); foreach (var id in ids) { ProductDetail productDetail = Repository.Db.Set <ProductDetail>().Find(id); var db = this.Repository.Db as BusinessDbContext; var sourceWarehouseProduct = db.WarehouseProducts.FirstOrDefault( x => x.ShopId == transfer.ShopId && x.ProductDetailId == id && x.WarehouseId == transfer.SourceWarehouseId); if (sourceWarehouseProduct == null) { sourceWarehouseProduct = new WarehouseProduct { ShopId = transfer.ShopId, WarehouseId = transfer.SourceWarehouseId, MinimumStockToNotify = productDetail.MinimumStockToNotify, ProductDetailId = productDetail.Id, }; this.AddCommonValues(transfer, sourceWarehouseProduct); db.WarehouseProducts.Add(sourceWarehouseProduct); Repository.Save(); } var decreasedByWh = db.StockTransferDetails.Include(x => x.StockTransfer) .Where(x => x.ShopId == transfer.ShopId && x.ProductDetailId == id && x.SourceWarehouseId == transfer.SourceWarehouseId && x.StockTransfer.TransferState == StockTransferState.Approved).Sum(y => (double?)y.Quantity) ?? 0; sourceWarehouseProduct.TransferredOut = decreasedByWh; sourceWarehouseProduct.OnHand = sourceWarehouseProduct.Purchased + sourceWarehouseProduct.TransferredIn + sourceWarehouseProduct.StartingInventory - sourceWarehouseProduct.Sold - sourceWarehouseProduct.TransferredOut; sourceWarehouseProduct.Modified = DateTime.Now; var destinationWarehouseProduct = db.WarehouseProducts.FirstOrDefault( x => x.ShopId == transfer.ShopId && x.ProductDetailId == id && x.WarehouseId == transfer.DestinationWarehouseId); if (destinationWarehouseProduct == null) { destinationWarehouseProduct = new WarehouseProduct { ShopId = transfer.ShopId, WarehouseId = transfer.DestinationWarehouseId, MinimumStockToNotify = productDetail.MinimumStockToNotify, ProductDetailId = productDetail.Id, }; this.AddCommonValues(transfer, destinationWarehouseProduct); db.WarehouseProducts.Add(destinationWarehouseProduct); Repository.Save(); } double increasedByWh = db.StockTransferDetails.Include(x => x.StockTransfer) .Where(x => x.ShopId == transfer.ShopId && x.StockTransfer.TransferState == StockTransferState.Approved && x.ProductDetailId == id && x.DestinationWarehouseId == transfer.DestinationWarehouseId) .Sum(x => (double?)x.Quantity) ?? 0; destinationWarehouseProduct.TransferredIn = increasedByWh; destinationWarehouseProduct.OnHand = destinationWarehouseProduct.Purchased + destinationWarehouseProduct.StartingInventory + destinationWarehouseProduct.TransferredIn - destinationWarehouseProduct.Sold - destinationWarehouseProduct.TransferredOut; destinationWarehouseProduct.Modified = DateTime.Now; Repository.Save(); } } }
/// <summary> /// Register a new Product /// </summary> /// <param name="sender"></param> /// <param name="e"></param> public void RegisterRadButton_RegisterNewProduct(object sender, EventArgs e) { try { //Validate a new product to register #region Validate ProductCodeRadTextBoxControl if (String.IsNullOrEmpty(ProductCodeRadTextBoxControl.Text)) { errorProductProvider.SetError(ProductCodeRadTextBoxControl, "Introduzca un código."); ProductCodeRadTextBoxControl.Focus(); return; } errorProductProvider.Clear(); if (isExitProductCode) { errorProductProvider.SetError(ProductCodeRadTextBoxControl, "Código existe en la base de datos"); return; } errorProductProvider.Clear(); #endregion #region Validate ProductNameRadTextBoxControl if (String.IsNullOrEmpty(ProductNameRadTextBoxControl.Text)) { errorProductProvider.SetError(ProductNameRadTextBoxControl, "Introduzca un nombre para el producto."); ProductNameRadTextBoxControl.Focus(); return; } errorProductProvider.Clear(); #endregion #region Validate ProductCostRadMaskedEditBox if (Convert.ToDouble(ProductCostRadMaskedEditBox.Value) == 0.00) { errorProductProvider.SetError(ProductCostRadMaskedEditBox, "Introduzca el costo por unidad."); ProductCostRadMaskedEditBox.Focus(); return; } errorProductProvider.Clear(); #endregion #region Validate InitialStockRadMaskedEditBox if (Convert.ToInt32(InitialStockRadMaskedEditBox.Value) == 0) { errorProductProvider.SetError(InitialStockRadMaskedEditBox, "Introduzca la cantidad Inicial."); InitialStockRadMaskedEditBox.Focus(); return; } errorProductProvider.Clear(); #endregion //Create Product Product _p = new Product() { ProductCode = ProductCodeRadTextBoxControl.Text, ProductName = ProductNameRadTextBoxControl.Text, Description = DescriptionRadTextBoxControl.Text != string.Empty ? DescriptionRadTextBoxControl.Text : null, State = StateRadCheckBox.Checked, InvoiceWithoutStock = InvoiceWithoutStockRadCheckBox.Checked, InvoiceWithPrice = GetInvoiceWithPrice(), }; if (CategoryIDComboBox.SelectedIndex != 0) { _p.CategoryID = (int)CategoryIDComboBox.SelectedValue; } if (UnitIDComboBox.SelectedIndex != 0) { _p.UnitID = (int)UnitIDComboBox.SelectedValue; } //Create Product Details ProductDetail _pd = new ProductDetail() { ProductCost = Convert.ToDecimal(ProductCostRadMaskedEditBox.Value), BodegaID = 1, }; if (Convert.ToDouble(UnitPrice1RadMaskedEditBox.Value) != 0.00) { _pd.UnitPrice1 = Convert.ToDecimal(UnitPrice1RadMaskedEditBox.Value); } if (Convert.ToDouble(UnitPrice2RadMaskedEditBox.Value) != 0.00) { _pd.UnitPrice2 = Convert.ToDecimal(UnitPrice2RadMaskedEditBox.Value); } if (Convert.ToDouble(UnitPrice3RadMaskedEditBox.Value) != 0.00) { _pd.UnitPrice3 = Convert.ToDecimal(UnitPrice3RadMaskedEditBox.Value); } if (TaxIDComboBox.SelectedIndex != 0) { _pd.TaxID = (int)TaxIDComboBox.SelectedValue; } var InitialStock = Convert.ToInt32(InitialStockRadMaskedEditBox.Value); _pd.Stock = InitialStock; //Create Kardex Kardex _k = new Kardex() { RegisterDate = DateTime.Now, TypeOfMove = "Inventario Inicial", KardexIn = InitialStock, KardexStock = InitialStock }; _pd.Kardexes.Add(_k); _p.ProductDetails.Add(_pd); this._serviceProductBL.Add(_p); this._currentParentForm.FillProductsRadGridView(); RadMessageBox.Show(null, "Producto registrado satisfactoriamente", "JOSIAS INDUSTRIAL SRL", MessageBoxButtons.OK, RadMessageIcon.Info); } catch (Exception ex) { RadMessageBox.Show(null, string.Format("Error : {0}", ex.InnerException), "JOSIAS INDUSTRIAL SRL", MessageBoxButtons.OK, RadMessageIcon.Error); return; } }
/// <summary> /// 构造函数 /// </summary> /// <param name="info">商品详细信息</param> public FrmProductDetail(ProductDetail info) : this() { this.detailInfo = info; ProductDetail2Control(info); }
public void Does_fixup_of_one_to_one_relationship() { var manager = CreateStateManager(); var principal1 = new Product { Id = 21 }; var principal2 = new Product { Id = 22 }; var principal3 = new Product { Id = 23 }; var dependent1 = new ProductDetail { Id = 21 }; var dependent2 = new ProductDetail { Id = 22 }; var dependent4 = new ProductDetail { Id = 24 }; var principalEntry1 = manager.GetOrCreateEntry(principal1); var principalEntry2 = manager.GetOrCreateEntry(principal2); var principalEntry3 = manager.GetOrCreateEntry(principal3); var dependentEntry1 = manager.GetOrCreateEntry(dependent1); var dependentEntry2 = manager.GetOrCreateEntry(dependent2); var dependentEntry4 = manager.GetOrCreateEntry(dependent4); manager.StartTracking(principalEntry1); manager.StartTracking(principalEntry2); manager.StartTracking(principalEntry3); manager.StartTracking(dependentEntry1); manager.StartTracking(dependentEntry2); manager.StartTracking(dependentEntry4); var fixer = new NavigationFixer(manager, CreateAccessorSource()); Assert.Null(principal1.Detail); Assert.Null(dependent1.Product); fixer.StateChanged(principalEntry1, EntityState.Unknown); Assert.Same(principal1, dependent1.Product); Assert.Same(dependent1, principal1.Detail); Assert.Null(principal2.Detail); Assert.Null(dependent2.Product); fixer.StateChanged(dependentEntry2, EntityState.Unknown); Assert.Same(principal2, dependent2.Product); Assert.Same(dependent2, principal2.Detail); Assert.Null(principal3.Detail); Assert.Null(dependent4.Product); fixer.StateChanged(principalEntry3, EntityState.Unknown); fixer.StateChanged(dependentEntry4, EntityState.Unknown); Assert.Null(principal3.Detail); Assert.Null(dependent4.Product); }
public void Binding_dgrDetailWH() { dgrvDetailWH.Refresh(); dgrvDetailWH.DataSource = null; var ID = Convert.ToInt32(dgrvWH.CurrentRow.Cells["ID"].Value.ToString()); List <Product> lpro = new List <Product>(); lpro = (from wh in db.WareHouses.Where(x => x.ID == ID).ToList() from ib in db.ImportBills.Where(x => x.IDWareHouse == wh.ID).ToList() from dt in db.ProductDetails.Where(x => x.IDImBill == ib.ID).ToList() from pr in db.Products.Where(x => x.ID == dt.IDProduct).ToList() from com in db.Companies.Where(x => x.ID == pr.IDCompany).ToList() select new Product { ID = pr.ID, Product1 = pr.Product1, IDCompany = pr.IDCompany, Price = pr.Price, OrdinaryPrice = pr.OrdinaryPrice } ).ToList(); List <Product> lpro2 = new List <Product>(); foreach (var item in lpro) { var search = lpro2.Find(x => x.ID == item.ID); if (search == null) { lpro2.Add(item); } } List <ProductDetail> ldt = new List <ProductDetail>(); ldt = (from wh in db.WareHouses.Where(x => x.ID == ID).ToList() from ib in db.ImportBills.Where(x => x.IDWareHouse == wh.ID).ToList() from dt in db.ProductDetails.Where(x => x.IDImBill == ib.ID).ToList() from pr in db.Products.Where(x => x.ID == dt.IDProduct).ToList() from com in db.Companies.Where(x => x.ID == pr.IDCompany).ToList() select new ProductDetail { IDProduct = dt.IDProduct, Quantity = dt.Quantity, } ).ToList(); List <ProductDetail> ldt2 = new List <ProductDetail>(); foreach (var item in lpro2) { var Quantity = ldt.Where(x => x.IDProduct == item.ID).Sum(x => x.Quantity); ProductDetail news = new ProductDetail(); news.IDProduct = item.ID; news.Quantity = Quantity; ldt2.Add(news); } var list = (from pr in lpro2.ToList() from dt in ldt2.Where(x => x.IDProduct == pr.ID).ToList() from com in db.Companies.Where(x => x.ID == pr.IDCompany).ToList() select new { ID = pr.ID, Product1 = pr.Product1, IDCompany = pr.IDCompany, Price = pr.Price, OrdinaryPrice = pr.OrdinaryPrice, Quantity = dt.Quantity, Company1 = com.Company1 } ).ToList(); dgrvDetailWH.AutoGenerateColumns = false; dgrvDetailWH.ColumnCount = 6; dgrvDetailWH.Columns[0].Name = "ID"; dgrvDetailWH.Columns[0].HeaderText = "ID"; dgrvDetailWH.Columns[0].DataPropertyName = "ID"; dgrvDetailWH.Columns[1].Name = "Product1"; dgrvDetailWH.Columns[1].HeaderText = "S?n ph?m"; dgrvDetailWH.Columns[1].DataPropertyName = "Product1"; dgrvDetailWH.Columns[2].Name = "Company1"; dgrvDetailWH.Columns[2].HeaderText = "Công ty"; dgrvDetailWH.Columns[2].DataPropertyName = "Company1"; dgrvDetailWH.Columns[3].Name = "Quantity"; dgrvDetailWH.Columns[3].HeaderText = "S? lu?ng"; dgrvDetailWH.Columns[3].DataPropertyName = "Quantity"; dgrvDetailWH.Columns[4].Name = "Price"; dgrvDetailWH.Columns[4].HeaderText = "Giá bán"; dgrvDetailWH.Columns[4].DataPropertyName = "Price"; dgrvDetailWH.Columns[5].Name = "OrdinaryPrice"; dgrvDetailWH.Columns[5].HeaderText = "Giá g?c"; dgrvDetailWH.Columns[5].DataPropertyName = "OrdinaryPrice"; dgrvDetailWH.DataSource = list; txtIDWH.Text = dgrvWH.CurrentRow.Cells["ID"].Value.ToString(); txtLocationWH.Text = dgrvWH.CurrentRow.Cells["Location"].Value.ToString(); txtWH.Text = dgrvWH.CurrentRow.Cells["Warehouse1"].Value.ToString(); txtCapacityWH.Text = dgrvWH.CurrentRow.Cells["Capacity"].Value.ToString(); txtQuantityWH.Text = dgrvWH.CurrentRow.Cells["Quantity"].Value.ToString(); }
private bool checkNewProduct(ProductDetail product) { bool bCheck = true; string strError1 = ""; string strError2 = ""; string strError3 = ""; string strError4 = ""; if (product.ID.Length < 5) strError1 = strError1 + "คุณกรอกรหัสสินค้าไม่ครบ 5 ตัวค่ะ"; if (product.Barcode.Length == 0) strError2 = strError2 + "Barcode "; if (product.Name.Length == 0) strError2 = strError2 + "ชื่อสินค้า "; if (product.UnitCode == ProductDetail.cstNotChooseUnit) strError3 = strError3 + "หน่วยนับ "; if (product.Cost <= 1) strError4 = strError4 + "ราคาต้นทุน "; if (product.Price <= 1) strError4 = strError4 + "ราคาขาย1 "; if (product.Price2 <= 1) strError4 = strError4 + "ราคาขาย2 "; if (product.ColorCode == ProductDetail.cstNotChooseColor) strError3 = strError3 + "สี "; if (product.SizeCode == ProductDetail.cstNotChooseSize) strError3 = strError3 + "ขนาด "; if (strError1 != "") strError1 = strError1 + "ค่ะ"; if (strError2 != "") { strError1 = strError1 + Environment.NewLine; strError1 = strError1 + "คุณยังไม่ได้กรอก" + strError2 + "ค่ะ"; } if (strError3 != "") { strError1 = strError1 + Environment.NewLine; strError1 = strError1 + "คุณยังไม่ได้เลือก" + strError3 + "ค่ะ"; } if (strError4 != "") { strError1 = strError1 + Environment.NewLine; strError1 = strError1 + "ราคา" + strError4 + "ต้องมีค่าอย่างน้อย 1 บาทค่ะ"; } if (strError1 != "") { bCheck = false; MessageBox.Show(strError1, cstWarning); } return bCheck; }
public static ProductDetail CreateProductDetail(int productId) { ProductDetail productDetail = new ProductDetail(); productDetail.ProductId = productId; return productDetail; }
private bool addDataToProduct(ProductDetail product) { bool bCheck = true; product.ID = tbProductID.Text.Trim(); product.Name = tbProductName.Text.Trim(); product.Barcode = tbBarcode.Text.Trim(); product.Name = tbProductName.Text.Trim(); product.UnitCode = ProductDetail.getUnitCode(cbUnitType.SelectedIndex, cbUnitType.SelectedItem.ToString()); try { product.Cost = Double.Parse(tbCost.Text.Trim()); } catch { MessageBox.Show("ราคาต้นทุนต้องเป็นตัวเลขเท่านั้นค่ะ เช่น 20.50 เป็นต้น", cstWarning); return false; } try { product.Price = Double.Parse(tbPrice1.Text.Trim()); } catch { MessageBox.Show("ราคาขายที่ 1 ต้องเป็นตัวเลขเท่านั้นค่ะ เช่น 20.50 เป็นต้น", cstWarning); return false; } try { product.Price2 = Double.Parse(tbPrice2.Text.Trim()); } catch { MessageBox.Show("ราคาขายที่ 2 ต้องเป็นตัวเลขเท่านั้นค่ะ เช่น 20.50 เป็นต้น", cstWarning); return false; } product.ColorCode = ProductDetail.getColorCode(cbColor.SelectedIndex, cbColor.SelectedItem.ToString()); product.SizeCode = ProductDetail.getSizeCode(cbSize.SelectedIndex, cbSize.SelectedItem.ToString()); product.Note = tbProductNote.Text.Trim(); return bCheck; }
private void buttonSave_Click(object sender, EventArgs e) { if (eCurrentPanel == EnumPanel.Customer) { bool bCheck = false; if (btnSearchEachMember.Enabled == false) bCheck = checkDuplicateCustomerID(tbCustomerID.Text.Trim()); if (bCheck == true) { MessageBox.Show("รหัสสมาชิกนี้มีอยู่แล้วในระบบค่ะ กรุณากรอกรหัสสมาชิกอีกครั้งนะคะ", cstWarning); tbCustomerID.Text = ""; tbCustomerID.Focus(); return; } Customer customer = new Customer(); addDataToCustomer(customer); bCheck = true; bCheck = checkNewCustomer(customer); if (bCheck == false) { return; } insertToCustomers(customer); btnSearchEachMember.Enabled = true; btnCancelCusCommand.Visible = false; setReadOnlyFieldCustomer(true); tbCustomerID.ReadOnly = false; } else if (eCurrentPanel == EnumPanel.Product) { bool bCheck = false; if (btnSearchEachProduct.Enabled == false) bCheck = checkDuplicateProductID(tbProductID.Text.Trim()); if (bCheck == true) { MessageBox.Show("รหัสสินค้านี้มีอยู่แล้วในระบบค่ะ กรุณากรอกรหัสสินค้าอีกครั้งนะคะ", cstWarning); tbProductID.Text = ""; tbProductID.Focus(); return; } bCheck = true; ProductDetail product = new ProductDetail(); bCheck = addDataToProduct(product); if (bCheck == false) return; bCheck = checkNewProduct(product); if (bCheck == false) return; insertToProducts(product); btnSearchEachProduct.Enabled = true; btnCancelProCommand.Visible = false; setReadOnlyFieldProduct(true); tbProductID.ReadOnly = false; } buttonSave.Enabled = false; buttonDelete.Enabled = false; }
private void updateToProduct(ProductDetail product) { StringBuilder sb = new StringBuilder(); sb.Append("Update Products"); sb.Append(" SET Barcode=@Barcode,"); sb.Append("ProductName=@ProductName,"); sb.Append("UnitCode=@UnitCode,"); sb.Append("Cost=@Cost,"); sb.Append("Price=@Price,"); sb.Append("Price2=@Price2,"); sb.Append("ColorCode=@ColorCode,"); sb.Append("SizeCode=@SizeCode,"); sb.Append("ProductNote=@ProductNote"); sb.Append(" WHERE ProductID=@ProductID"); string sqlUpdate = sb.ToString(); OpenConnection(); OleDbCommand com = new OleDbCommand(); OleDbTransaction tr = Conn.BeginTransaction(); com.CommandType = CommandType.Text; com.CommandText = sqlUpdate; com.Connection = Conn; com.Transaction = tr; com.Parameters.Add("@Barcode", OleDbType.VarChar).Value = product.Barcode; com.Parameters.Add("@ProductName", OleDbType.VarChar).Value = product.Name; com.Parameters.Add("@UnitCode", OleDbType.VarChar).Value = product.UnitCode; com.Parameters.Add("@Cost", OleDbType.Single).Value = product.Cost; com.Parameters.Add("@Price", OleDbType.Single).Value = product.Price; com.Parameters.Add("@Price2", OleDbType.Single).Value = product.Price2; com.Parameters.Add("@ColorCode", OleDbType.VarChar).Value = product.ColorCode; com.Parameters.Add("@SizeCode", OleDbType.VarChar).Value = product.SizeCode; com.Parameters.Add("@ProductNote", OleDbType.VarChar).Value = product.Note; com.Parameters.Add("@ProductID", OleDbType.VarChar).Value = product.ID; try { com.ExecuteNonQuery(); tr.Commit(); CloseConnection(); MessageBox.Show("แก้ไขข้อมูลสินค้านี้เรียบร้อยแล้วค่ะ", cstTitle); } catch (Exception ex) { tr.Rollback(); CloseConnection(); MessageBox.Show(ex.Message, cstWarning); } }
private void insertToProducts(ProductDetail product) { StringBuilder sb = new StringBuilder(); sb.Append("INSERT INTO Products(ProductID,Barcode,ProductName,UnitCode,"); sb.Append("Cost,Price,Price2,ColorCode,SizeCode,ProductNote)"); sb.Append(" VALUES(@ProductID,@BarCode,@ProductName,@UnitCode,"); sb.Append("@Cost,@Price,@Price2,@ColorCode,@SizeCode,@ProductNote)"); string sqlInsert = sb.ToString(); OpenConnection(); OleDbCommand com = new OleDbCommand(); OleDbTransaction tr = Conn.BeginTransaction(); com.CommandType = CommandType.Text; com.CommandText = sqlInsert; com.Connection = Conn; com.Transaction = tr; com.Parameters.Add("@ProductID", OleDbType.VarChar).Value = product.ID; com.Parameters.Add("@BarCode", OleDbType.VarChar).Value = product.Barcode; com.Parameters.Add("@ProductName", OleDbType.VarChar).Value = product.Name; com.Parameters.Add("@UnitCode", OleDbType.VarChar).Value = product.UnitCode; com.Parameters.Add("@Cost", OleDbType.Single).Value = product.Cost; com.Parameters.Add("@Price", OleDbType.Single).Value = product.Price; com.Parameters.Add("@Price2", OleDbType.Single).Value = product.Price2; com.Parameters.Add("@ColorCode", OleDbType.VarChar).Value = product.ColorCode; com.Parameters.Add("@SizeCode", OleDbType.VarChar).Value = product.SizeCode; com.Parameters.Add("@ProductNote", OleDbType.VarChar).Value = product.Note; try { com.ExecuteNonQuery(); tr.Commit(); CloseConnection(); MessageBox.Show("เพิ่มข้อมูลสินค้าเรียบร้อยแล้วค่ะ", cstTitle); } catch { tr.Rollback(); CloseConnection(); updateToProduct(product); } }
public void Save(ProductDetail productDetail) { _dbContext.ProductDetails.Add(productDetail); }
public bool isValidProductdetail(ProductDetail productDetail, string productType) { if (productDetail.GetType() == typeof()) { return(true); }
public bool Add(ProductDetail product) { var res = productDetailRepository.add(product); return(res != null); }
public ProductDetailDeleteDataParameters(ProductDetail val) { PDetail = val; Build(); }
public bool Update(ProductDetail product) { var res = productDetailRepository.update(product); return(res); }
public void Identifying_foreign_key_value_is_generated_if_principal_key_not_set() { var model = BuildModel(); var principal = new Product(); var dependent = new ProductDetail { Product = principal }; var contextServices = CreateContextServices(model); var dependentEntry = contextServices.GetRequiredService<IStateManager>().GetOrCreateEntry(dependent); var property = model.GetEntityType(typeof(ProductDetail)).GetProperty("Id"); PropagateValue(contextServices.GetRequiredService<IKeyPropagator>(), dependentEntry, property); Assert.Equal(1, dependentEntry[property]); }
public ProductDetailInsertDataParameters(ProductDetail proDe) { ProductDetail = proDe; Build(); }
public DbSeeder(DataContext dbcontext) { ScryptEncoder encoder = new ScryptEncoder(); //User DB User user = new User() { Id = Guid.NewGuid().ToString(), Name = "Daryl Kouk", Username = "******", Password = encoder.Encode("Password") }; dbcontext.Add(user); User user2 = new User() { Id = Guid.NewGuid().ToString(), Name = "Martin Ng", Username = "******", Password = encoder.Encode("Password") }; dbcontext.Add(user2); User user3 = new User() { Id = Guid.NewGuid().ToString(), Name = "Wutt Yee", Username = "******", Password = encoder.Encode("Password") }; dbcontext.Add(user3); User user4 = new User() { Id = Guid.NewGuid().ToString(), Name = "Bianca Cao", Username = "******", Password = encoder.Encode("Password") }; dbcontext.Add(user4); //Products //Shooter Games Product product1 = new Product() { Id = Guid.NewGuid().ToString(), Name = "Borderland 3", Genre = "Shooter", Description = "The original shooter-looter returns, packing bazillions of guns and a mayhem-fueled adventure! Blast through new worlds & enemies and save your home from the most ruthless cult leaders in the galaxy.", Price = 81.90, }; dbcontext.Add(product1); Product product2 = new Product() { Id = Guid.NewGuid().ToString(), Name = "Call of Duty® WWII", Genre = "Shooter", Description = "Call of Duty® returns to its roots with Call of Duty®: WWII - a breathtaking experience that redefines World War II for a new gaming generation.", Price = 85.00, }; dbcontext.Add(product2); Product product3 = new Product() { Id = Guid.NewGuid().ToString(), Name = "Far Cry® 5", Genre = "Shooter", Description = "Welcome to Hope County, Montana, home to a fanatical doomsday cult known as Eden’s Gate. Stand up to cult leader Joseph Seed & his siblings, the Heralds, to spark the fires of resistance & liberate the besieged community.", Price = 70.00, }; dbcontext.Add(product3); //Action Product product4 = new Product() { Id = Guid.NewGuid().ToString(), Name = "MONSTER HUNTER WORLD", Genre = "Action", Description = "Welcome to a new world! In Monster Hunter: World, the latest installment in the series, you can enjoy the ultimate hunting experience, using everything at your disposal to hunt monsters in a new world teeming with surprises and excitement.", Price = 41.00, }; dbcontext.Add(product4); Product product5 = new Product() { Id = Guid.NewGuid().ToString(), Name = "DARK SOULS™ III", Genre = "Action", Description = "Dark Souls continues to push the boundaries with the latest, ambitious chapter in the critically-acclaimed and genre-defining series. Prepare yourself and Embrace The Darkness!", Price = 59.90, }; dbcontext.Add(product5); Product product6 = new Product() { Id = Guid.NewGuid().ToString(), Name = "Sekiro™ Shadows Die Twice", Genre = "Action", Description = "Game of the Year - The Game Awards 2019, Best Action Game of 2019 - IGN. Carve your own clever path to vengeance in the award winning adventure from developer FromSoftware, creators of Bloodborne and the Dark Souls series. Take Revenge. Restore Your Honor. Kill Ingeniously.", Price = 69.90, }; dbcontext.Add(product6); //RPG Product product7 = new Product() { Id = Guid.NewGuid().ToString(), Name = "Divinity Original Sin 2 - Definitive Edition", Genre = "RPG", Description = "The eagerly anticipated sequel to the award-winning RPG. Gather your party. Master deep, tactical combat. Join up to 3 other players - but know that only one of you will have the chance to become a God.", Price = 49.00, }; dbcontext.Add(product7); Product product8 = new Product() { Id = Guid.NewGuid().ToString(), Name = "STAR WARS Jedi Fallen Order™", Genre = "RPG", Description = "A galaxy-spanning adventure awaits in Star Wars Jedi: Fallen Order, a 3rd person action-adventure title from Respawn. An abandoned Padawan must complete his training, develop new powerful Force abilities, and master the art of the lightsaber - all while staying one step ahead of the Empire.", Price = 69.90, }; dbcontext.Add(product8); Product product9 = new Product() { Id = Guid.NewGuid().ToString(), Name = "FINAL FANTASY XV WINDOWS EDITION", Genre = "RPG", Description = "Take the journey, now in ultimate quality. Boasting a wealth of bonus content and supporting ultra high-resolution graphical options and HDR 10, you can now enjoy the beautiful and carefully-crafted experience of FINAL FANTASY XV like never before.", Price = 69.90, }; dbcontext.Add(product9); //ProductDetails //Rating is out of 5 ProductDetail productDetail1 = new ProductDetail() { Id = Guid.NewGuid().ToString(), ProductId = product1.Id, UserId = user.Id, Comment = "Borderlands 3, on the whole is a solid game. The gunplay is much improved on previous entries as are the vehicles and most of the side missions are pretty fun, best bought on sale.", Rating = 4 }; dbcontext.productDetails.Add(productDetail1); ProductDetail productDetail2 = new ProductDetail() { Id = Guid.NewGuid().ToString(), ProductId = product1.Id, UserId = user.Id, Comment = "Apart from the janky story and the overload of terrible attempts at comedy it was a pretty good game, but since Randy Pitchford treats his employees like cattle I just can't recommend this game.", Rating = 2 }; dbcontext.productDetails.Add(productDetail2); //PurchaseDetails //Past purchase history of user Daryl PurchaseDetails purchaseDetails1 = new PurchaseDetails() { Id = Guid.NewGuid().ToString(), ActivationCode = Guid.NewGuid().ToString(), ProductId = product1.Id, UserId = user.Id, CreatedDate = new DateTime(2020, 04, 01, 10, 00, 00).ToUniversalTime() }; dbcontext.Add(purchaseDetails1); PurchaseDetails purchaseDetails2 = new PurchaseDetails() { Id = Guid.NewGuid().ToString(), ActivationCode = Guid.NewGuid().ToString(), ProductId = product1.Id, UserId = user.Id, CreatedDate = new DateTime(2020, 04, 01, 10, 00, 00).ToUniversalTime() }; dbcontext.Add(purchaseDetails2); PurchaseDetails purchaseDetails3 = new PurchaseDetails() { Id = Guid.NewGuid().ToString(), ActivationCode = Guid.NewGuid().ToString(), ProductId = product4.Id, UserId = user.Id, CreatedDate = new DateTime(2020, 04, 01, 10, 00, 00).ToUniversalTime() }; dbcontext.Add(purchaseDetails3); PurchaseDetails purchaseDetails4 = new PurchaseDetails() { Id = Guid.NewGuid().ToString(), ActivationCode = Guid.NewGuid().ToString(), ProductId = product2.Id, UserId = user.Id, CreatedDate = new DateTime(2020, 04, 01, 10, 00, 00).ToUniversalTime() }; dbcontext.Add(purchaseDetails4); //seeded by Martin 2020-04-10 PurchaseDetails purchaseDetails5 = new PurchaseDetails() { Id = Guid.NewGuid().ToString(), ActivationCode = Guid.NewGuid().ToString(), ProductId = product2.Id, UserId = user.Id, CreatedDate = new DateTime(2020, 03, 01, 10, 00, 00).ToUniversalTime() }; dbcontext.Add(purchaseDetails5); PurchaseDetails purchaseDetails6 = new PurchaseDetails() { Id = Guid.NewGuid().ToString(), ActivationCode = Guid.NewGuid().ToString(), ProductId = product2.Id, UserId = user.Id, CreatedDate = new DateTime(2020, 03, 01, 10, 00, 00).ToUniversalTime() }; dbcontext.Add(purchaseDetails6); PurchaseDetails purchaseDetails7 = new PurchaseDetails() { Id = Guid.NewGuid().ToString(), ActivationCode = Guid.NewGuid().ToString(), ProductId = product9.Id, UserId = user.Id, CreatedDate = new DateTime(2020, 03, 01, 10, 00, 00).ToUniversalTime() }; dbcontext.Add(purchaseDetails7); dbcontext.SaveChanges(); }
//取得商品詳細資料 public ActionResult GetProductDetail(int id = 1, int?colorid = 0) { //瀏覽過的紀錄 if (Session["recent"] != null) { List <int> recent = (List <int>)Session["recent"]; if (recent.Contains(id)) { } else { recent.Add(id); } Session["recent"] = recent; } else { List <int> recent = new List <int>(); recent.Add(id); Session.Add("recent", recent); } var product = db.Products.Find(id); ProductDetail prodcutDisplay; ViewBag.categorymid = product.CategorySmall.CategoryMID; ViewBag.categorymname = product.CategorySmall.CategoryMiddle.CategoryMName; ViewBag.categorysname = product.CategorySmall.CategorySName; prodcutDisplay = new ProductDetail() { ProductID = product.ProductID, ProductName = product.ProductName, Desctiption = product.Desctiption, CategorySID = product.CategorySID, UnitPrice = product.UnitPrice, WashingName = db.ProductWashings.Where(w => w.ProductID == id).Select(w => w.Washing.WashingName).ToArray(), Colors = db.ProductColors.Where(c => c.ProductID == id).AsEnumerable().Select(c => new Color { ColorID = c.ColorID, ColorName = c.Color.ColorName, R = c.Color.R, G = c.Color.G, B = c.Color.B }).ToList(), Sizes = db.ProductSizes.Where(s => s.ProductID == id).AsEnumerable().Select(s => new Size { SizeID = s.SizeID, SizeName = s.Size.SizeName }).ToList() }; var inactivity = db.ActivityProducts.Where(a => a.ProductID == id && a.Activity.EndDate >= DateTime.Now).ToList(); if (inactivity.Count() > 0) { ViewBag.activityname = inactivity.FirstOrDefault().Activity.ActivityName; prodcutDisplay.SUnitPrice = Convert.ToInt32(Math.Floor(inactivity.First().Activity.DiscountMethod.Discount *product.UnitPrice)); } ViewBag.colorid = (colorid == 0) ? db.ProductColors.Where(c => c.ProductID == id).Select(c => c.ColorID).First() : colorid; var images = db.ProductPhotoes.Where(p => p.ProductID == id).Take(10); List <string> imgs = new List <string>(); foreach (var image in images) { var img = Convert.ToBase64String(image.Photo.Photo1); imgs.Add(img); } ViewBag.images = imgs; if (Session["IsLogin"] != null || Request.Cookies["IsLogin"] != null) { int uid = int.Parse(Request.Cookies["upid"].Value); var fav = db.MyFavorites.Where(f => f.UserID == uid && f.ProductID == id).ToList(); ViewBag.fav = (fav.Count > 0) ? 1 : 0; } else { ViewBag.fav = 0; } var products = db.Products.Where(p => p.ProductID != id && p.CategorySID == prodcutDisplay.CategorySID).OrderBy(x => Guid.NewGuid()).Take(10).ToList(); List <CartItem> citems = new List <CartItem>(); CartItem citem; foreach (var pd in products) { decimal discountpercent = (db.ActivityProducts.Where(a => a.ProductID == pd.ProductID && a.Activity.EndDate >= DateTime.Now).Count() > 0) ? db.ActivityProducts.Where(a => a.ProductID == pd.ProductID && a.Activity.EndDate >= DateTime.Now).FirstOrDefault().Activity.DiscountMethod.Discount : 0; string activityname = (db.ActivityProducts.Where(a => a.ProductID == pd.ProductID && a.Activity.EndDate >= DateTime.Now).Count() > 0) ? db.ActivityProducts.Where(a => a.ProductID == pd.ProductID && a.Activity.EndDate >= DateTime.Now).FirstOrDefault().Activity.ActivityName : null; citem = new CartItem() { ProductID = pd.ProductID, ProductName = pd.ProductName, UnitPrice = pd.UnitPrice, SUnitPrice = Convert.ToInt32(Math.Floor(discountpercent * pd.UnitPrice)), ActivityName = activityname }; citems.Add(citem); } ViewBag.recommend = citems.ToList(); var evaluation = ProductMethod.LoadEvaluation(id); if (evaluation.Count > 0) { int score = evaluation.Sum(e => e.Grade) / evaluation.Count; ViewBag.score = score; } ViewBag.evaluation = evaluation.ToList(); return(View(prodcutDisplay)); }
public async Task <IActionResult> Payment(PaymentViewModel paymentViewModel) { if (ModelState.IsValid) { Dictionary <int, string> result = new Dictionary <int, string>(); int isReturn = 0; // Success or fail string message = string.Empty; // Message ProductDetail productDetailUpdate; // Update product detail List <ProductDetail> lstProductDetailUpdate = new List <ProductDetail>(); // Update product detail list CartDetail cartDetailUpdate; // Update cart detail List <CartDetail> lstCartDetailUpdate = new List <CartDetail>(); // Update cart detail list foreach (var item in paymentViewModel.Products.Cart) { productDetailUpdate = productDetailService.GetOne(item.ProductDetail.ID); if (productDetailUpdate != null) { if (productDetailUpdate.Quantity <= 0) { isReturn = 0; message = "outofstock"; goto Finish; } lstProductDetailUpdate.Add(productDetailUpdate); } } Order order = null; // Order Entity try { DataTranfer(out order, paymentViewModel); } catch (Exception e) { message = e.Message; goto Finish; } // Call Service => Execute #region --- Main Execute --- // Create new order result = orderService.Create(order); // Check create new order success or fail paymentViewModel.OrderId = result.Keys.FirstOrDefault(); if (paymentViewModel.OrderId <= 0) // Create fail { result.TryGetValue(isReturn, out message); // Get error message goto Finish; } else // Add new order successful { try { DataTranferOrderDetail(ref order, paymentViewModel); } catch (Exception e) { message = e.Message; goto Finish; } } result.Clear(); // Create new order detail result = orderDetailService.AddOrderDetail(order); // Check create new order detail success or fail isReturn = result.Keys.FirstOrDefault(); if (isReturn <= 0) // Create fail { result.TryGetValue(isReturn, out message); // Get error message goto Finish; } else // Create order detail successful, then update quantity of product { // Update quantity of product for (int i = 0; i < lstProductDetailUpdate.Count; i++) { lstProductDetailUpdate[i].Quantity -= paymentViewModel.Products.Cart[i].BuyedQuantity; } isReturn = productDetailService.Update(lstProductDetailUpdate); // Update if (isReturn <= 0) { message = "Cập nhật số lượng sản phẩm không thành công"; goto Finish; } // Update cart detail foreach (var item in paymentViewModel.Products.Cart) { cartDetailUpdate = cartDetailService.Get(item.CartDetailId); if (cartDetailUpdate != null) { cartDetailUpdate.State = 2; lstCartDetailUpdate.Add(cartDetailUpdate); } } isReturn = cartDetailService.Updates(lstCartDetailUpdate); // Update if (isReturn <= 0) { message = "Cập nhật trạng thái của sản phẩm trong giỏ hàng không thành công"; goto Finish; } } Finish: // isReturn = 0: Error || 1: Success // Giải thích: isReturn = dbContext.Commit = số dòng được thay đổi trong sql paymentViewModel.IsError = (isReturn == 0); paymentViewModel.Message = message; #endregion --- Main Execute --- if (paymentViewModel.IsError) // Error { return(View(paymentViewModel)); } List <ProductDetail> temp = new List <ProductDetail>(); foreach (var item in lstProductDetailUpdate) { productDetailUpdate = new ProductDetail() { Id = item.Id, Quantity = item.Quantity }; temp.Add(productDetailUpdate); } // Call SignalR update quantity await _hubContext.Clients.All.SendAsync("ReloadQuantity", temp); // Call SignalR update statistical await _hubContext.Clients.All.SendAsync("ReloadStatistical"); // Send email User user = await userManager.GetUserAsync(User); SendEmail(paymentViewModel, user.Email); // Call SignalR notification await _hubContext.Clients.All.SendAsync("OrderSuccess"); paymentViewModel.Email = user.Email; paymentViewModel.IsPaymentSuccess = true; return(View(paymentViewModel)); } // //string userIDProc = order.UserId; // //DataTable dataTable = new DataTable(); // //dataTable.Columns.Add(new DataColumn("ID", typeof(int))); // //dataTable.Columns.Add(new DataColumn("Quantity", typeof(int))); // //dataTable.Columns.Add(new DataColumn("Processed", typeof(int))); // //dataTable.Columns.Add(new DataColumn("UserIDProc", typeof(string))); // //foreach(var item in order.OrderDetail) // //{ // // dataTable.Rows.Add(item.ProductDetailId, item.Quantity, 0, userIDProc); // //} // //string query = "UpdateProductDetail @ListID"; // //orderDetailService.ExecStoreUpdate(query, new SqlParameter("@ListID", dataTable)); return(View(paymentViewModel)); }
public ActionResult Delete(int id) { ProductDetail productDetail = _entities.ProductDetails.SingleOrDefault(a => a.ID == id); return(View(productDetail)); }
/// <summary> /// Update a current Product /// </summary> /// <param name="sender"></param> /// <param name="e"></param> public void RegisterRadButton_UpdateCurrentProduct(object sender, EventArgs e) { //MessageBox.Show("Update Product"); try { #region Validate ProductNameRadTextBoxControl if (String.IsNullOrEmpty(ProductNameRadTextBoxControl.Text)) { errorProductProvider.SetError(ProductNameRadTextBoxControl, "Introduzca un nombre para el producto."); ProductNameRadTextBoxControl.Focus(); return; } errorProductProvider.Clear(); #endregion //Update Product //Create Product Product _p = new Product() { ProductID = this._currentProductToEdit.ProductID, ProductCode = ProductCodeRadTextBoxControl.Text, ProductName = ProductNameRadTextBoxControl.Text, Description = DescriptionRadTextBoxControl.Text != string.Empty ? DescriptionRadTextBoxControl.Text : null, State = StateRadCheckBox.Checked, InvoiceWithoutStock = InvoiceWithoutStockRadCheckBox.Checked, InvoiceWithPrice = GetInvoiceWithPrice(), }; if (CategoryIDComboBox.SelectedIndex != 0) { _p.CategoryID = (int)CategoryIDComboBox.SelectedValue; } if (UnitIDComboBox.SelectedIndex != 0) { _p.UnitID = (int)UnitIDComboBox.SelectedValue; } //Create Product Details ProductDetail _pd = new ProductDetail() { ProductID = _p.ProductID, ProductDetailsID = this._currentProductToEdit.ProductDetails.FirstOrDefault().ProductDetailsID, ProductCost = Convert.ToDecimal(ProductCostRadMaskedEditBox.Value), BodegaID = 1, Stock = this._currentProductToEdit.ProductDetails.FirstOrDefault().Stock, }; if (Convert.ToDouble(UnitPrice1RadMaskedEditBox.Value) != 0.00) { _pd.UnitPrice1 = Convert.ToDecimal(UnitPrice1RadMaskedEditBox.Value); } if (Convert.ToDouble(UnitPrice2RadMaskedEditBox.Value) != 0.00) { _pd.UnitPrice2 = Convert.ToDecimal(UnitPrice2RadMaskedEditBox.Value); } if (Convert.ToDouble(UnitPrice3RadMaskedEditBox.Value) != 0.00) { _pd.UnitPrice3 = Convert.ToDecimal(UnitPrice3RadMaskedEditBox.Value); } if (TaxIDComboBox.SelectedIndex != 0) { _pd.TaxID = (int)TaxIDComboBox.SelectedValue; } /* * var InitialStock = Convert.ToInt32(InitialStockRadMaskedEditBox.Value); * _pd.Stock = InitialStock; */ _p.ProductDetails.Add(_pd); this._serviceProductBL.Update(_p); RadMessageBox.Show(null, "Producto actualizado satisfactoriamente", "JOSIAS INDUSTRIAL SRL", MessageBoxButtons.OK, RadMessageIcon.Info); } catch (Exception ex) { RadMessageBox.Show(null, string.Format("Error : {0}", ex.Message), "JOSIAS INDUSTRIAL SRL", MessageBoxButtons.OK, RadMessageIcon.Error); return; } }
public ActionResult Edit(int id) { ProductDetail productDetail = _entities.ProductDetails.Single(a => a.ID == id); return(View(productDetail)); }
/// <summary> /// auto generate id for all entities in Asowell Database /// all id type is 10 character and the sign is depend on the type of entity /// </summary> /// <param name="entity"></param> /// <returns></returns> private TEntity AutoGeneteId_DBAsowell(TEntity entity) { string sign = ""; if (entity is Employee) { sign = "EMP"; // lấy số thứ tự mới nhất string numberWantToset = (this.Get().Count() + 1).ToString(); int blank = ID_SIZE_DBASOWELL - (sign.Length + numberWantToset.Length); string result = sign; for (int i = 0; i < blank; i++) { result += "0"; } result += numberWantToset; Employee emp = entity as Employee; emp.EmpId = result; } else if (entity is AdminRe) { sign = "AD"; // lấy số thứ tự mới nhất string numberWantToset = (this.Get().Count() + 1).ToString(); int blank = ID_SIZE_DBASOWELL - (sign.Length + numberWantToset.Length); string result = sign; for (int i = 0; i < blank; i++) { result += "0"; } result += numberWantToset; AdminRe admin = entity as AdminRe; admin.AdId = result; } else if (entity is Customer) { sign = "CUS"; // lấy số thứ tự mới nhất string numberWantToset = (this.Get().Count() + 1).ToString(); int blank = ID_SIZE_DBASOWELL - (sign.Length + numberWantToset.Length); string result = sign; for (int i = 0; i < blank; i++) { result += "0"; } result += numberWantToset; Customer cus = entity as Customer; cus.CusId = result; } else if (entity is WareHouse) { sign = "WAH"; // lấy số thứ tự mới nhất string numberWantToset = (this.Get().Count() + 1).ToString(); int blank = ID_SIZE_DBASOWELL - (sign.Length + numberWantToset.Length); string result = sign; for (int i = 0; i < blank; i++) { result += "0"; } result += numberWantToset; WareHouse wh = entity as WareHouse; wh.WarehouseId = result; } else if (entity is Ingredient) { sign = "IGD"; // lấy số thứ tự mới nhất string numberWantToset = (this.Get().Count() + 1).ToString(); int blank = ID_SIZE_DBASOWELL - (sign.Length + numberWantToset.Length); string result = sign; for (int i = 0; i < blank; i++) { result += "0"; } result += numberWantToset; Ingredient ign = entity as Ingredient; ign.IgdId = result; } else if (entity is Product) { sign = "P"; // lấy số thứ tự mới nhất string numberWantToset = (this.Get().Count() + 1).ToString(); int blank = ID_SIZE_DBASOWELL - (sign.Length + numberWantToset.Length); string result = sign; for (int i = 0; i < blank; i++) { result += "0"; } result += numberWantToset; Product p = entity as Product; p.ProductId = result; } else if (entity is ProductDetail) { sign = "PD"; // lấy số thứ tự mới nhất string numberWantToset = (this.Get().Count() + 1).ToString(); int blank = ID_SIZE_DBASOWELL - (sign.Length + numberWantToset.Length); string result = sign; for (int i = 0; i < blank; i++) { result += "0"; } result += numberWantToset; ProductDetail pd = entity as ProductDetail; pd.PdetailId = result; } else if (entity is OrderNote) { sign = "ORD"; // lấy số thứ tự mới nhất string numberWantToset = (this.Get().Count() + 1).ToString(); int blank = ID_SIZE_DBASOWELL - (sign.Length + numberWantToset.Length); string result = sign; for (int i = 0; i < blank; i++) { result += "0"; } result += numberWantToset; OrderNote ord = entity as OrderNote; ord.OrdernoteId = result; } else if (entity is ReceiptNote) { sign = "RN"; // lấy số thứ tự mới nhất string numberWantToset = (this.Get().Count() + 1).ToString(); int blank = ID_SIZE_DBASOWELL - (sign.Length + numberWantToset.Length); string result = sign; for (int i = 0; i < blank; i++) { result += "0"; } result += numberWantToset; ReceiptNote rcn = entity as ReceiptNote; rcn.RnId = result; } else if (entity is SalaryNote) { sign = "SAN"; // lấy số thứ tự mới nhất string numberWantToset = (this.Get().Count() + 1).ToString(); int blank = ID_SIZE_DBASOWELL - (sign.Length + numberWantToset.Length); string result = sign; for (int i = 0; i < blank; i++) { result += "0"; } result += numberWantToset; SalaryNote sln = entity as SalaryNote; sln.SnId = result; } else if (entity is WorkingHistory) { sign = "WOH"; // lấy số thứ tự mới nhất string numberWantToset = (this.Get().Count() + 1).ToString(); int blank = ID_SIZE_DBASOWELL - (sign.Length + numberWantToset.Length); string result = sign; for (int i = 0; i < blank; i++) { result += "0"; } result += numberWantToset; WorkingHistory wh = entity as WorkingHistory; wh.WhId = result; } return(entity); }
public PartialViewResult SP_cungLoai(int?type) { List <Product> list_spcungloai = ProductDetail.sp_cungloai(type); return(PartialView(list_spcungloai)); }
//end ConfigViewModel /// <summary> /// Chuyển đổi từ ViewModel => Entity /// </summary> /// <param name="product"></param> /// <param name="productDetails"></param> /// <param name="images"></param> /// <param name="viewModel"> ViewModel chứa Input</param> /// <history> /// [Lương Mỹ] Create [29/04/2019] /// </history> private void DataTranfer(out Product product, out History history, ProductUpdateViewModel viewModel) { bool deleteImage = false; bool deleteDetail = false; string userID = viewModel.UserID; string userName = viewModel.UserName; history = new History(); // ViewModel => Entity #region --- Tranfer --- #region --- Product --- // Product Entity => Product int productID = viewModel.ProductId; if (productID == 0) { product = new Product(); product.CreateByUser = userID; product.CreateDate = DateTime.Now; } else { product = productService.Get(productID); if (product == null) { return; // lỗi } } product.Name = viewModel.ProductName; //UserID product.CatalogId = viewModel.Catalog; product.Description = viewModel.Description; //History product.LastModifyByUser = userID; product.LastModifyDate = DateTime.Now; // product.State = 1; #endregion --- Product --- #region --- Details + Price --- // ProductDetail Entity => ProductDetails var productDetails = new List <ProductDetail>(); for (int i = 0; i < viewModel.ProductDetails.Count; i++) { var proDetailModel = viewModel.ProductDetails[i]; int detailID = proDetailModel.ID; ProductDetail detail = null; if (detailID == 0) { // Thêm mới detail = new ProductDetail(); detail.CreateByUser = userID; detail.CreateDate = DateTime.Now; } else { // Chỉnh sửa detail = detailService.GetOne(detailID); if (detail == null) { continue; } } // Info detail.Id = proDetailModel.ID; detail.Size = proDetailModel.Size; detail.Color = proDetailModel.Color; detail.Quantity = proDetailModel.Quantity; detail.Price = proDetailModel.PriceID; // History detail.LastModifyByUser = userID; detail.LastModifyDate = DateTime.Now; // State detail.State = 1; // ProductPrice int priceID = proDetailModel.PriceID.GetValueOrDefault(); ProductPrice productPrice = null; var newPrice = Double.Parse(viewModel.PriceText[i].Replace(".", ",")); if (priceID != 0) { productPrice = priceService.GetOne(priceID); //var newPrice = Double.Parse(viewModel.PriceText[i].Replace(".",",")); // Tạo mới Price nếu Thay đổi giá tiền if (productPrice.Price != newPrice) { productPrice = new ProductPrice(); productPrice.CreateDate = DateTime.Now; productPrice.CreateByUser = userID; } } else { productPrice = new ProductPrice(); productPrice.CreateDate = DateTime.Now; productPrice.CreateByUser = userID; } productPrice.Price = newPrice; // History productPrice.LastModifyByUser = userID; productPrice.LastModifyDate = DateTime.Now; // productPrice.State = 1; detail.PriceNavigation = productPrice; productDetails.Add(detail); }//end Entity ProductDetail // Delete ProductDetail if (viewModel.DeleteDetailID != null) { for (int i = 0; i < viewModel.DeleteDetailID.Count; i++) { deleteDetail = true; var proDetailID = viewModel.DeleteDetailID[i]; // ProductDetail ProductDetail detail = detailService.GetOne(proDetailID); if (detail == null) { continue; } detail.State = 0; // Xoa // Update history detail.LastModifyByUser = userID; detail.LastModifyDate = DateTime.Now; productDetails.Add(detail); } } #endregion --- Details + Price --- #region --- Image --- // Image Entity => List<Image> var images = new List <Image>(); for (int i = 0; i < viewModel.Images.Count; i++) { var imgModel = viewModel.Images[i]; Image img = new Image() { Url = imgModel.Url, CreateByUser = userID }; images.Add(img); } // Delete ProductDetail if (viewModel.DeleteImageID != null) { for (int i = 0; i < viewModel.DeleteImageID.Count; i++) { var imageDetailID = viewModel.DeleteImageID[i]; // ProductDetail Image img = imageService.GetOne(imageDetailID); if (img == null) { continue; } img.State = 0; // Xoa // Update history img.LastModifyByUser = userID; img.LastModifyDate = DateTime.Now; images.Add(img); } } #endregion --- Image --- #region --- History --- history.CreateDate = DateTime.Now; history.CreateByUser = userID; String changes = String.Empty; if (!viewModel.IsUpdate) // Thêm mới { changes = String.Format("</p> Tạo mới sản phảm </p>"); } else { if (viewModel.History != null) { for (int i = 0; i < viewModel.History.Count; i++) { var item = viewModel.History[i]; item = String.Format("<p> {0} </p>", item.ToString()); viewModel.History[i] = item; } changes = String.Join(" ", viewModel.History); } if (viewModel.DeleteImageID != null && viewModel.DeleteImageID.Count > 0) { changes += String.Format("</p> Xóa {0} hình ảnh </p>", viewModel.DeleteImageID.Count); } if (viewModel.Images != null && viewModel.Images.Count > 0) { changes += String.Format("</p> Thêm {0} hình ảnh </p>", viewModel.Images.Count); } } history.Content = changes; history.Table = "Product"; #endregion --- History --- if (viewModel.IsUpdate) { foreach (var img in images) { product.Images.Add(img); } foreach (var detail in productDetails) { product.ProductDetails.Add(detail); } } else { product.Images = images; product.ProductDetails = productDetails; } #endregion --- Tranfer --- }
public SecondDetailPage(ProductDetail productDetail) { InitializeComponent(); BindingContext = _ViewModel = new SecondDetailPageViewModel(productDetail); }
public async Task <IActionResult> ProductDetail(long id) { var product = _productRepository.Query() .Include(x => x.OptionValues) .Include(x => x.Categories).ThenInclude(c => c.Category) .Include(x => x.AttributeValues).ThenInclude(a => a.Attribute) .Include(x => x.ProductLinks).ThenInclude(p => p.LinkedProduct).ThenInclude(m => m.ThumbnailImage) .Include(x => x.ThumbnailImage) .Include(x => x.Medias).ThenInclude(m => m.Media) .FirstOrDefault(x => x.Id == id && x.IsPublished); if (product == null) { return(Redirect("~/Error/FindNotFound")); } var model = new ProductDetail { Id = product.Id, Name = product.Name, CalculatedProductPrice = _productPricingService.CalculateProductPrice(product), IsCallForPricing = product.IsCallForPricing, IsAllowToOrder = product.IsAllowToOrder, StockQuantity = product.StockQuantity, ShortDescription = product.ShortDescription, MetaTitle = product.MetaTitle, MetaKeywords = product.MetaKeywords, MetaDescription = product.MetaDescription, Description = product.Description, Specification = product.Specification, ReviewsCount = product.ReviewsCount, RatingAverage = product.RatingAverage, Attributes = product.AttributeValues.Select(x => new ProductDetailAttribute { Name = x.Attribute.Name, Value = x.Value }).ToList(), Categories = product.Categories.Select(x => new ProductDetailCategory { Id = x.CategoryId, Name = x.Category.Name, Slug = x.Category.Slug }).ToList() }; MapProductVariantToProductVm(product, model); MapRelatedProductToProductVm(product, model); foreach (var item in product.OptionValues) { var optionValues = JsonConvert.DeserializeObject <IList <ProductOptionValueVm> >(item.Value); foreach (var value in optionValues) { if (!model.OptionDisplayValues.ContainsKey(value.Key)) { model.OptionDisplayValues.Add(value.Key, new ProductOptionDisplay { DisplayType = item.DisplayType, Value = value.Display }); } } } model.Images = product.Medias.Where(x => x.Media.MediaType == Core.Models.MediaType.Image).Select(productMedia => new MediaViewModel { Url = _mediaService.GetMediaUrl(productMedia.Media), ThumbnailUrl = _mediaService.GetThumbnailUrl(productMedia.Media) }).ToList(); await _mediator.Publish(new EntityViewed { EntityId = product.Id, EntityTypeId = "Product" }); _productRepository.SaveChanges(); return(View(model)); }
public async Task <ActionResult> AddNewProduct(NewProductModel product, List <HttpPostedFileBase> files) { var UserId = User.Identity.GetUserId(); Product dbProduct = new Product() { Id = Guid.NewGuid().ToString(), Amount = product.Amount, Description = product.Description, ProductName = product.Name, ProductBrandId = product.ProductBrandId, CreatedByUserId = UserId, DateCreated = DateTime.UtcNow }; //many to many insert mapping List <string> tmpint = product.Categories .Where(i => i.IsSelected).Select(i => i.Id).ToList(); var tmp = await(from p in data.ProductCategories where tmpint.Contains(p.Id.ToString()) select p).ToListAsync(); foreach (var o in tmp) { dbProduct.ProductCategories.Add(o); } ProductDetail dbProductDetail = new ProductDetail() { Id = Guid.NewGuid().ToString(), ProductMeasurementId = product.MeasurementId, ProductColorId = product.ColordId, Length = product.Lenght, Width = product.Width, Height = product.Height, Weight = product.Weight }; if (files.Count() >= 1 && files[0] != null) { foreach (var x in files) { var id = Guid.NewGuid().ToString(); NewIMageModel img = new Models.NewIMageModel() { Id = id, FileExtention = x.ContentType, File = x, }; var res = await azureBlob.UploadImageAsync(img); ProductDetailImage dbProductImage = new ProductDetailImage() { Id = img.Id, ImageUrl = res.URL, FileName = res.FileName }; dbProductDetail.ProductDetailImages.Add(dbProductImage); } } foreach (var o in product.Genders) { if (o.IsSelected) { ProductsInGender dbProdcutsInGender = new ProductsInGender() { Gender = o.Id, Product = dbProduct }; data.ProductsInGenders.Add(dbProdcutsInGender); } } dbProduct.ProductDetails.Add(dbProductDetail); data.Products.Add(dbProduct); await data.SaveChangesAsync(); return(RedirectToAction("Products")); }
public JsonResult Crear(List <EDEntryDetails> DetalleEntrada, EDEntry Entradas, List <int> IdABorrar) { bool Probar = true; string Mensaje = ""; EDEntry EDEntry = new EDEntry(); EDEntry.EntryId = Entradas.EntryId; EDEntry.FechaIngreso = Entradas.FechaIngreso; EDEntry.Aprobado = Entradas.Aprobado; EDEntry.TerceroId = Entradas.TerceroId; List <EDEntryDetails> EDEntryDetails = new List <EDEntryDetails>(); foreach (var item in DetalleEntrada) { EDEntryDetails EDEntryDetail = new EDEntryDetails(); EDEntryDetail.EntryDetailId = item.EntryDetailId; EDEntryDetail.Cantidad = item.Cantidad; EDEntryDetail.Lote = item.Lote; EDEntryDetail.FechaVence = item.FechaVence; EDEntryDetail.ProductDetailId = item.ProductDetailId; EDEntryDetails.Add(EDEntryDetail); } try { Entry Entry = new Entry(); if (EDEntry.EntryId > 0) { Entry entrada = db.Entries.Find(EDEntry.EntryId); Entry = entrada; } Entry.FechaIngreso = DateTime.Parse(EDEntry.FechaIngreso); Entry.TerceroId = EDEntry.TerceroId; Entry.Aprobado = EDEntry.Aprobado = Entradas.Aprobado; if (EDEntry.EntryId > 0) { db.Entry(Entry).State = EntityState.Modified; db.SaveChanges(); } else { db.Entries.Add(Entry); db.SaveChanges(); } int IdEntrada = Entry.EntradaId; if (IdABorrar != null) { foreach (var detalle in IdABorrar) { EntryDetail EntradaDetalle = db.EntryDetails.Find(detalle); db.EntryDetails.Remove(EntradaDetalle); db.SaveChanges(); } } foreach (var item1 in EDEntryDetails) { EntryDetail EntryDetail = new EntryDetail(); if (item1.EntryDetailId > 0) { EntryDetail entradaDetalle = db.EntryDetails.Find(item1.EntryDetailId); EntryDetail = entradaDetalle; } EntryDetail.Cantidad = item1.Cantidad; EntryDetail.Lote = item1.Lote; EntryDetail.FechaVence = DateTime.Parse(item1.FechaVence); EntryDetail.EntradaId = IdEntrada; EntryDetail.ProductDetailId = item1.ProductDetailId; if (EntryDetail.EntryDetailId > 0) { db.Entry(EntryDetail).State = EntityState.Modified; db.SaveChanges(); } else { db.EntryDetails.Add(EntryDetail); db.SaveChanges(); } if (Entry.Aprobado == "S") { ProductDetail ProductDetail = db.ProductDetails.Find(EntryDetail.ProductDetailId); ProductDetail.Existencias += EntryDetail.Cantidad; db.Entry(ProductDetail).State = EntityState.Modified; db.SaveChanges(); } } Mensaje = " Registro Agregado con exito."; } catch (Exception) { Probar = false; Mensaje = " Se produjo un error al agregar el registro."; } return(Json(new { Probar, Mensaje }, JsonRequestBehavior.AllowGet)); }
public bool Add(ProductDetail obj) { throw new System.NotImplementedException(); }
public void One_to_one_foreign_key_value_is_obtained_from_tracked_principal() { var model = BuildModel(); var contextServices = CreateContextServices(model); var manager = contextServices.GetRequiredService<IStateManager>(); var dependent = new ProductDetail(); var principal = new Product { Id = 21, Detail = dependent }; manager.GetOrCreateEntry(principal).SetEntityState(EntityState.Unchanged); var dependentEntry = manager.GetOrCreateEntry(dependent); var property = model.FindEntityType(typeof(ProductDetail)).FindProperty("Id"); PropagateValue(contextServices.GetRequiredService<IKeyPropagator>(), dependentEntry, property); Assert.Equal(21, dependentEntry[property]); }
public void Create(ProductDetail productDetail) { UnitOfWork.Context.Add(productDetail); }
public void AddToProductDetail(ProductDetail productDetail) { base.AddObject("ProductDetail", productDetail); }
public void Update(ProductDetail productDetail) { _productRepository.Update(productDetail); }
public ProductDetail Add(ProductDetail productDetail) { return(_productRepository.Add(productDetail)); }
public void Update(ProductDetail productDetail) { UnitOfWork.Context.Attach(productDetail); }