public decimal CalculateBasketTotalPrice(product[] basket) { decimal totalPrice = 0; for (int i = 0; i < basket.Length; i++ ) totalPrice = totalPrice + basket[i].price; return totalPrice; }
public void CalculateMediumProductPriceInBasket() { product a = new product { name = "shorts", price = 50 }; product b = new product { name = "tshirt", price = 100 }; product c = new product { name = "shoes", price = 150 }; product[] productList1 = new product[] { a, b, c }; Assert.AreEqual(100, CalculateMediumProductPrice(productList1)); }
public static string InsertProduct(product p) { dataContext.products.Add(p); dataContext.SaveChanges(); return "success"; }
public void AddNewProductPriceInBasket() { product a = new product { name = "shorts", price = 50 }; product b = new product { name = "tshirt", price = 100 }; product c = new product { name = "shoes", price = 150 }; product d = new product { name = "bag", price = 1 }; product[] productList1 = new product[] { a, b, c }; product[] productList2 = new product[] { a, b, c, d }; CollectionAssert.AreEqual(productList2, AddNewProductPrice(productList1, d)); }
public void EliminateMosteExpensiveProductFromFirstPositionInBasket() { product a = new product { name = "shoes", price = 150 }; product b = new product { name = "bag", price = 1 }; product c = new product { name = "tshirt", price = 100 }; product d = new product { name = "shorts", price = 50 }; product[] listProduct1 = new product[] { b, c, d }; product[] listProduct2 = new product[] { a, b, c, d }; CollectionAssert.AreEqual(listProduct1, EliminateMostExpensiveProduct(listProduct2)); }
public product[] AddNewProductPrice(product[] basket, product p) { product[] newBasketProducts = new product[basket.Length + 1]; for (int i = 0; i < newBasketProducts.Length; i++) { if (i == newBasketProducts.Length - 1) newBasketProducts[i] = p; else newBasketProducts[i] = basket[i]; } return newBasketProducts; }
public static int getProductID(product p) { var userResults = from u in dataContext.products where u.username == p.username && u.productName == p.productName && u.productInfo == p.productInfo && u.price == p.price select u; var j1 = dataContext.products.First(a => a.productID == p.productID).productID; return j1; }
public static string updateProduct(product p) { product pro = dataContext.products.First(i => i.productID == p.productID); var p1 = dataContext.products.First(a => a.productID == p.productID).photo1; if (p1 == null) { pro.photo1 = p.photo1; } else { pro.photo2 = p.photo1; } dataContext.SaveChanges(); return "success"; }
protected product[] select; // выбранные пункты меню #endregion Fields #region Constructors public Automat() { menu = new product[3]; menu[0] = new product("Кекс", 50, 4); menu[1] = new product("Печенье", 10, 3); menu[2] = new product("Вафли", 30, 10); select = new product[3]; select[0] = new product("Кекс", 50, 0); select[1] = new product("Печенье", 10, 0); select[2] = new product("Вафли", 30, 0); account = new bank(100, 100, 100, 100); balance = 0; }
public Task<IEnumerable<string>> Post(int productid) { var session = HttpContext.Current.Session; try { if (session["username"] != null) { if (Request.Content.IsMimeMultipartContent()) { string fullPath = HttpContext.Current.Server.MapPath("~/uploads"); MultipartFormDataStreamProvider streamProvider = new MultipartFormDataStreamProvider(fullPath); var task = Request.Content.ReadAsMultipartAsync(streamProvider).ContinueWith(t => { if (t.IsFaulted || t.IsCanceled) throw new HttpResponseException(HttpStatusCode.InternalServerError); var fileInfo = streamProvider.FileData.Select(i => { var info = new FileInfo(i.LocalFileName); product img = new product(); byte[] a = File.ReadAllBytes(info.FullName); img.productID = productid; img.photo1 = a; ProductRepository.updateProduct(img); return "File uploaded successfully!"; }); return fileInfo; }); return task; } else { throw new HttpResponseException(Request.CreateResponse(HttpStatusCode.NotAcceptable, "Invalid Request!")); } } else { throw new HttpResponseException(Request.CreateResponse(HttpStatusCode.BadRequest, "Bad Request")); } } catch (Exception e) { System.Diagnostics.Debug.WriteLine(e); return null; } }
public bool AddProduct(product product) { try { using (QLBH_PHONE_ENTITY data = new QLBH_PHONE_ENTITY()) { data.products.Add(product); data.SaveChanges(); return true; } } catch (Exception e) { Debug.WriteLine(e); return false; } }
// copy constructor public product(product x, bool copyVersion) { if (copyVersion == true) { _versionInfo = x._versionInfo; } else { _versionInfo = null; } ProductKey = x.ProductKey; ProductName = x.ProductName; Color = x.Color; Cost = x.Cost; Description = x.Description; ModelName = x.ModelName; }
private List<product> GetProducts(out int total) { List<product> products = new List<product>(); for (int i = 1; i <= Total; i++) { product p = new product() {id = i, name = "name" + i, price = i + 1}; products.Add(p); } var productEnum = products.AsEnumerable(); if (!string.IsNullOrEmpty(Sort)) { if (Sort == "id") { if (Order == "asc") { productEnum = productEnum.OrderBy(p => p.id); } else { productEnum = productEnum.OrderByDescending(p => p.id); } } else if (Sort == "price") { if (Order == "asc") { productEnum = productEnum.OrderBy(p => p.price); } else { productEnum = productEnum.OrderByDescending(p => p.price); } } } if (!string.IsNullOrEmpty(SearchWord)) { //search productEnum = productEnum.Where(p => p.name.Contains(SearchWord.Trim())); } IEnumerable<product> enumerable = productEnum as IList<product> ?? productEnum.ToList(); total = enumerable.Count(); productEnum = enumerable.Skip(Offset).Take(Limit); return productEnum.ToList(); }
private void createButton_Click(object sender, EventArgs e) { int typeId = 0; var query = from prodType in db.productType where prodType.typeName == Resources.productType_Изделие select prodType.typeID; foreach (var id in query) { typeId = id; } var product = new product() { name = createProductName.Text, typeID = typeId }; db.product.Add(product); db.SaveChanges(); treeOfProduct.Nodes[0].Nodes.Add(createProductName.Text); createProductName.Text = null; }
public RedirectResult AddaProduct(HttpPostedFileBase file, product p, string edit) { p.imgpath = null; if (file != null && file.ContentLength > 0) { string time = (DateTime.UtcNow - new DateTime(1970, 1, 1)).TotalSeconds.ToString(); string file_time = time + ".jpg"; /////////////////////////////////////////////////////////////////// // check the algo // path is the small image string product_page_url = Server.MapPath("~/Product"); string server_path_map = Server.MapPath("~/Scripts/uploads"); var path = Path.Combine(server_path_map, "small_" + file_time); string htmlfilename = p.name.Replace(' ', '_') + p.model.Replace(' ', '-') + ".html"; var product_page_path = Path.Combine(product_page_url, htmlfilename); Bitmap original_image = (Bitmap)Image.FromStream(file.InputStream); int height = original_image.Height, width = original_image.Width; int size = (width * 205 / height); //Reducing size of image Bitmap upBmp = new Bitmap(original_image, new Size(size, 205)); upBmp.Save(path, ImageFormat.Jpeg); string tweetID = null; //tweeting about the product //posting image using (var stream = new FileStream(path, FileMode.Open)) { var result = service.SendTweetWithMedia(new SendTweetWithMediaOptions { Status = p.name + " " + p.model + " enorbit.co.uk/Product/" + htmlfilename, Images = new Dictionary <string, Stream> { { "Norbit", stream } } }); tweetID = result.IdStr; } /*string start = "<!DOCTYPE html><html lang=\"en\" xmlns=\"http://www.w3.org/1999/xhtml\"><head><meta charset=\"utf-8\" /><title>"+ p.name +"</title></head><body style=\"background-color: #E2E1DD\">" + "<div style=\"width:100%; height:100px; background-color:white\"><img src=\"/Scripts/images/NORBIT.jpg\" height=\"100px\" /></div><br />" +"<a href=\"/Home/Index\"><div style=\"margin-left:5%; margin-top:5%\">BACK to HOME</div></a><div style=\"margin-left:5%; border:ridge; margin-right:5%; background-color:white; border-radius:5px\"><br /><br /><div style=\"margin-left:10px\">"; + string end = "</div><br /><br /><br /></div><div style=\"margin-left:5%\"><a href=\"https://twitter.com/bitf13m006/status/"+tweetID+"\">Twitter</a></div></body></html>";*/ string end2 = "</div><div class=\"clear\"> </div></div><div class=\"clear\"> </div></div><div class=\"clear\"> </div></div></body></html>"; string title = "<!DOCTYPE html><html><head><title>" + p.name + "</title>"; //server.mappath dont froget to string filepath = Server.MapPath("~/Views/Home/page.txt"); string start2 = System.IO.File.ReadAllText(filepath); string completeHtmlText = title + start2 + edit + end2; //Saving HTML Page System.IO.File.WriteAllText(product_page_path, completeHtmlText); //var result = service.SendTweet(new SendTweetOptions{Status = @"enorbit.co.uk/Product/"+htmlfilename}); //ViewBag.Txt = result.Text.ToString(); p.pagepath = "/Product/" + htmlfilename; p.imgpath = "/Scripts/uploads/small_" + file_time; db.saveProduct(p); } return(Redirect("/dskfj3k4adsfDF23cnv34fOAdmin2mcbue767bnmn326568/AddProduct")); }
/// <summary> /// Invoked when <see cref="ToEntity"/> operation is about to return. /// </summary> /// <param name="entity"><see cref="product"/> converted from <see cref="productDto"/>.</param> static partial void OnEntity(this productDto dto, product entity);
public ActionResult Order(string name, string email, string phone, string address, string province, string district) { var objOrder = new order(); objOrder.order_name = name; objOrder.order_email = email; objOrder.order_phone = phone; objOrder.order_address = address; objOrder.order_province = province; objOrder.order_district = district; // objOrder.order_ward = ward; objOrder.order_date = DateTime.Now; // Get user infor try { var orderId = new OrderADO().Insert(objOrder); var cart = (List <CartModel>)Session[SessionConst.CART_SESSION]; var orderDetailADO = new OrderDetailADO(); decimal total = 0; var orderDetail = new order_detail(); foreach (var item in cart) { orderDetail.product_id = item.Product.product_id; orderDetail.order_id = orderId; orderDetail.price = item.Product.price; orderDetail.quantity = item.Quantity; orderDetailADO.Insert(orderDetail); total += (item.Product.price.GetValueOrDefault(0) * item.Quantity); } var productInfo = new product(); foreach (var item in cart) { productInfo.prod_code = item.Product.prod_code; productInfo.product_name = item.Product.product_name; productInfo.quantity = item.Product.quantity; productInfo.price = item.Product.price; } string content = System.IO.File.ReadAllText(Server.MapPath("~/Contents/EmailTemplate/neworder.html")); content = content.Replace("{{CustomerName}}", name); content = content.Replace("{{CustomerPhone}}", phone); content = content.Replace("{{CustomerEmail}}", email); content = content.Replace("{{CustomerAddress}}", address); content = content.Replace("{{CustomerProvince}}", province); content = content.Replace("{{CustomerDistrict}}", district); // content = content.Replace("{{CustomerWard}}", ward); content = content.Replace("{{CustomerProdCode}}", productInfo.prod_code); content = content.Replace("{{CustomerProdName}}", productInfo.product_name); content = content.Replace("{{CustomerQuantity}}", productInfo.quantity.ToString()); content = content.Replace("{{CustomerPrice}}", productInfo.price.ToString()); content = content.Replace("{{CustomerTotal}}", total.ToString("N0")); var toEmailAddress = ConfigurationManager.AppSettings["ToEmailAddress"].ToString(); new MailHelper().SendMail(email, "FashionShop - Xác nhận đơn hàng", content); // Send Email to Customer new MailHelper().SendMail(toEmailAddress, "FashionShop - Đơn hàng mới", content); // Send Email to Admin } catch (Exception) { return(Redirect("/dat-hang-khong-thanh-cong")); } Session[SessionConst.CART_SESSION] = null; return(Redirect("/dat-hang-thanh-cong")); }
public ActionResult NewMovie() { var product = new product(); return(View(product)); }
public static StringBuilder getPostDataStr(INodeContext ctx, product prod, LoggerMemory log, Action<StringBuilder> finishScriptData = null) { StringBuilder scriptData = buildLib.getServerScript(getPostDataFiles(ctx, prod, log)); if (finishScriptData != null) finishScriptData(scriptData); return scriptData; }
public void updateCategory(int id, [FromBody] product value) { value.CategoryId = id; db.SaveChanges(); }
public product[] EliminateMostExpensiveProduct(product[] basket) { decimal highestPrice; int counter = 0, index = 0; product[] newBasketProducts = new product[basket.Length]; highestPrice = IndicateMostExpensiveProductInBasket(basket); for (int i = 0; i < basket.Length; i++) if (basket[i].price == highestPrice) counter = counter + 1; Array.Resize<product>(ref newBasketProducts, newBasketProducts.Length - counter); for (int i = 0; i < basket.Length; i++) if (basket[i].price != highestPrice) newBasketProducts[i - index] = basket[i]; else index = index + 1; return newBasketProducts; }
public string IndicateCheapestProductInBasket(product[] basket) { product lowestPrice; lowestPrice.price = basket[0].price; lowestPrice.name = basket[0].name; for (int i = 1; i < basket.Length; i++) if (basket[i].price < lowestPrice.price) { lowestPrice.price = basket[i].price; lowestPrice.name = basket[i].name; } return lowestPrice.name; }
private void TestSimple() { product p = new product(); List<product> products = new List<product>(); for (int i = 1; i <= 33; i++) { products.Add(new product() {id = i,name = "p" + i, price = i}); } string json = Newtonsoft.Json.JsonConvert.SerializeObject(products); Response.Write(json); Response.End(); }
public decimal IndicateMostExpensiveProductInBasket(product[] basket) { product mostExpensiveProduct = basket[0]; for (int i = 1; i < basket.Length; i++) if (basket[i].price > mostExpensiveProduct.price) mostExpensiveProduct = basket[i]; return mostExpensiveProduct.price ; }
public static void getPublishProduct(Stream str, fileContext actCtx, string prodUrl, string globalPublisherDir, IEnumerable<Packager.Consts.file> files = null) { vsNetServer.log.clear(); vsNetServer.log.vsNetGlobalPublisherDir = globalPublisherDir; //var log = new LoggerMemory(true) { isVsNet = true, vsNetGlobalPublisherDir = globalPublisherDir }; var prod = new product { url = prodUrl, styleSheet = ex.stdStyle, line = actCtx.line, //defaultDictType = dictTypes.no, //defaultLocs = new Langs[] {Langs.en_gb}, title = actCtx.actNode.title, type = actCtx.actNode.isType(runtimeType.test) ? runtimeType.product | runtimeType.test : runtimeType.product, Items = new data[] { new ptr(true, actCtx.url) { takeChilds = childMode.selfChild } } }; getPostDataFilesZip(str, actCtx, prod, vsNetServer.log, files); }
public static IEnumerable<Packager.Consts.file> getPostDataFiles(INodeContext ctx, product prod, LoggerMemory log) { var isModule = ctx.url.EndsWith("/"); return isModule ? vsNetServer.getModuleFiles(ctx, prod, log) : vsNetServer.buildExFiles(ctx.url, log); }
public decimal CalculateMediumProductPrice(product[] basket) { decimal mediumPrice = 0; mediumPrice = CalculateBasketTotalPrice(basket) / basket.Length; return mediumPrice; }
/// <summary> /// 新增需求單 /// </summary> /// <param name="sender"></param> /// <param name="e"></param> protected void btn_ADD_Click(object sender, EventArgs e) { try { //抓取目前儲位清單 List <product> producttemp = new List <product>(); foreach (GridViewRow row in gv_FList.Rows) { var one = new product(); one.productid = GetCellByName(row, "產品編號").Text; TextBox 調出數 = GetCellByName(row, "調出數").FindControl("txt_num") as TextBox; one.quantity = (調出數 != null) ? int.Parse(調出數.Text) : 0; //數量防呆 if (one.quantity <= 0) { lblMsg.Text = one.productid + " 調出數量不正確!"; return; } producttemp.Add(one); } //統計總數 var temp = (from i in producttemp group i by new { i.productid } into g select new product { productid = g.Key.productid, quantity = g.Sum(x => x.quantity), }).ToList(); //轉成List<string> List <string> ProductList = new List <string>(); foreach (var item in temp) { ProductList.Add(item.productid + "," + item.quantity); } //分為 一般調出 /瑕疵 /問題件 var requireType = 0; if (DDL_SearchType.SelectedItem.Text == "瑕疵") { requireType = 1; } else if (DDL_SearchType.SelectedItem.Text == "問題件") { requireType = 2; } //新增需求單 var result = RequireDA.SetRequireProduct(ProductList, requireType, account, _areaId); lblMsg.Text = result.Reason; if (result.Result == "1") { btn_ADD.Enabled = false; } } catch (Exception ex) { Response.Write("系統發生錯誤 " + ex.Message); } }
public void DeleteRecord(product record) { myRecords.Remove(record); context.products.Remove(record); context.SaveChanges(); }
public ActionResult Edit(int id, FormCollection frm) { if (user == null) { return(RedirectToAction("Login", "Account")); } product blg = datas.products.Where(a => a.Id == id).FirstOrDefault(); blg.name = frm["prod.name"].ToString(); blg.price = Convert.ToDecimal(frm["prod.price"]); blg.desciption = frm["prod.desciption"].ToString(); blg.smdesc = frm["prod.smdesc"].ToString(); blg.cId = Convert.ToInt32(frm["basliksec"]); int r = blg.Id; datas.SaveChanges(); if (Request.Files.Count > 0) { image img = new image(); if (datas.images.Where(d => d.id == r).FirstOrDefault() == null) { img = new image(); } else { img = datas.images.Where(d => d.id == r).FirstOrDefault(); } string path = Server.MapPath("/"); if (Directory.Exists(path + "/productImg") == false) { Directory.CreateDirectory(path + "productImg/"); } if (!string.IsNullOrEmpty(Request.Files["pic"].FileName)) { Request.Files["pic"].SaveAs(path + "productImg/" + Request.Files["pic"].FileName); img.folderName = string.IsNullOrEmpty(Request.Files["pic"].FileName) == true ? "" : "productImg/" + Request.Files["pic"].FileName; } if (Request.Files["pic2"].FileName != null) { if (!string.IsNullOrEmpty(Request.Files["pic2"].FileName)) { Request.Files["pic2"].SaveAs(path + "productImg/" + Request.Files["pic2"].FileName); img.folderName1 = string.IsNullOrEmpty(Request.Files["pic2"].FileName) == true ? "" : "productImg/" + Request.Files["pic2"].FileName; } } if (Request.Files["pic3"].FileName != null) { if (!string.IsNullOrEmpty(Request.Files["pic3"].FileName)) { Request.Files["pic3"].SaveAs(path + "productImg/" + Request.Files["pic3"].FileName); img.folderName2 = string.IsNullOrEmpty(Request.Files["pic3"].FileName) == true ? "" : "productImg/" + Request.Files["pic3"].FileName; } } img.pid = r; if (datas.images.Where(d => d.id == r).FirstOrDefault() == null) { datas.images.Add(img); datas.SaveChanges(); } else { datas.SaveChanges(); } } return(RedirectToAction("Index")); }
public bool AddProduct([FromBody] product Product) { return(ProductService.AddProduct(Product)); }
public bool UpdateProduct(product product) { try { using (QLBH_PHONE_ENTITY data = new QLBH_PHONE_ENTITY()) { //data.products.Attach(product); //data.Entry(product).State = EntityState.Modified; //getItem.id = product.id; var getItem = data.products.Single(p => p.id == product.id);//get the specific product getItem.id_manufacturer = product.id_manufacturer; getItem.id_save = product.id_save; getItem.name = product.name; getItem.sale_price = product.sale_price; getItem.number = product.number; getItem.image = product.image; getItem.product_info = product.product_info; data.SaveChanges(); return true; } } catch (Exception e) { Debug.WriteLine(e); return false; } }
public static void getPostDataFilesZip(Stream str, INodeContext ctx, product prod, LoggerMemory log, IEnumerable<Packager.Consts.file> files = null) { buildLib.zipVirtualFiles(str, getPostDataFiles(ctx, prod, log).Concat(files == null ? Enumerable.Empty<Packager.Consts.file>() : files), log); }
public product GetProductByID(int productID) { record = context.products.FirstOrDefault(e => e.productID == productID); return(record); }
public void export() { int cost = 0; try { cost = int.Parse(Request.Form["cost"]); } catch (Exception e) { return; } int id = 0; try { id = int.Parse(Request.Form["id"]); } catch (Exception e) { } string name = Request.Form["name"]; if (name == "" || name == null) { return; } string type = Request.Form["type"]; teethLabEntities db = new teethLabEntities(); int dayId = 0; DateTime day; CultureInfo enUS = new CultureInfo("en-US"); DateTime.TryParseExact(Request.Form["day"], "yyyy-MM-dd", enUS, DateTimeStyles.None, out day); moneyDay md = new moneyDay(); if (db.moneyDays.Where(o => o.day.Year == day.Year && o.day.Month == day.Month && o.day.Day == day.Day).Count() > 0) { md = db.moneyDays.Where(o => o.day.Year == day.Year && o.day.Month == day.Month && o.day.Day == day.Day ).First(); md.credit -= cost; db.Entry(md).State = System.Data.EntityState.Modified; } else { return; } db.SaveChanges(); dayId = md.id; db = new teethLabEntities(); money m = new money(); m.dayId = dayId; m.fromTo = name; m.type = "export"; m.value = cost; m.recieveDate = DateTime.Now; if (type == "new") { } else if (type == "Doctor") { m.doctorId = id; } else if (type == "Company") { m.companyId = id; } else if (type == "Employee") { m.employeeId = id; } db.Entry(m).State = System.Data.EntityState.Added; db.moneys.Add(m); db.SaveChanges(); db = new teethLabEntities(); if (type == "Company") { product p = new product(); p.companyId = id; p.enterDate = day; p.name = name;// p.isFinished = false; p.price = cost; db.Entry(p).State = System.Data.EntityState.Added; } else if (type == "Doctor") { doctor doc = db.doctors.Find(id); db.Entry(doc).State = System.Data.EntityState.Modified; doc.depit += cost; } db.SaveChanges(); Response.Write("success"); }
public static string ToLiquidProductUrl(this product p) { return(String.Concat("/products/", p.id, "/", p.title.ToSafeUrl())); }
public void add(product product) { product_list.Add(product); }
public ProductInCart(product product, int quantityInCart) { this.Product = product; this.QuantityInCart = quantityInCart; }
public void add(string name, double price) { product p = new product(); p.name = name; p.price = price; }
public ActionResult AddProduct(product AddData) { var Flag = new ProductBll().Add(AddData) != 0; return(Content(Flag.ToString())); }
private void DelSale_Click(object sender, RoutedEventArgs e) { var btn = sender as Button; DelSaleButtonTag dt = btn.Tag as DelSaleButtonTag; try { DGSaleItems sale = new DGSaleItems(); var sales = lst.Where(w => w.SaleNumber == dt.SaleNumber).ToList(); foreach (var item in sales) { var prod = new product(); if (dt.ProdId != null) { sale = lst.First(s => s.ProductId == dt.ProdId && s.SaleNumber == dt.SaleNumber); } if (dt.ServId != null) { sale = lst.First(s => s.ServiceId == dt.ServId && s.SaleNumber == dt.SaleNumber); } lst.Remove(sale); using (u0324292_tyreshopEntities db = new u0324292_tyreshopEntities()) { prod = db.products.Single(s => s.ProductId == item.ProductId); var oper = db.operations.First(s => (s.ProductId == dt.ProdId && s.SaleNumber == dt.SaleNumber) || (s.ServiceId == dt.ServId && s.SaleNumber == dt.SaleNumber)); var res = MessageBox.Show("Вы действительно хотите полностью удалить данную операцию? Действие необратимо.", "Информация", MessageBoxButton.OKCancel); if (res == MessageBoxResult.OK) { if (oper.ProductId != null && oper.ProductId != 0) { int store = db.storehouses.First(s => s.StorehouseName == oper.Storehouse).StorehouseId; int quant = oper.Count; var pq = db.productquantities.First(s => s.StorehouseId == store && s.ProductId == oper.ProductId); pq.Quantity += quant; db.Entry(pq).Property(x => x.Quantity).IsModified = true; var prodsQ = db.productquantities.Where(w => w.ProductId == item.ProductId).ToList(); foreach (var innerItem in prodsQ) { quant += (int)innerItem.Quantity; } var product = db.products.Single(s => s.ProductId == item.ProductId); if (quant > 0) { product.ProdStatus = true; } else { product.ProdStatus = false; } db.Entry(product).Property(p => p.ProdStatus).IsModified = true; using (u0324292_mainEntities db2 = new u0324292_mainEntities()) { //var prod = db.products.Single(s => s.ProductId == prodId); var id = int.Parse(prod.ProdNumber); if (db2.shop_product.Any(a => a.product_id == id)) { var siteProd = db2.shop_product.Single(a => a.product_id == id); siteProd.quantity += quant; db2.Entry(siteProd).Property(p => p.quantity).IsModified = true; if (siteProd.quantity >= 0) { db2.SaveChanges(); } if (siteProd.quantity >= 0 && siteProd.stock_status_id == 8) { siteProd.stock_status_id = 7; db2.Entry(siteProd).Property(p => p.stock_status_id).IsModified = true; db2.SaveChangesAsync(); } } } } db.operations.Remove(oper); db.SaveChanges(); } } } Report.Items.Refresh(); } catch (Exception ex) { int point = 0; } }
private bool IsRecommended(product p) { return(null != MainScreen.RecomedationsFromAgent.Find(x => x.product_id == p.product_id)); }
public product Create(product produit) { _produits.InsertOne(produit); return(produit); }
public HttpResponseMessage Post([FromBody] Models.product product) { try { if (productRepository.CheckDuplicateProductName(product.product_name)) { var formatter = RequestFormat.JsonFormaterString(); return(Request.CreateResponse(HttpStatusCode.OK, new Confirmation { output = "warning", msg = "Product Name Already Exists" }, formatter)); } if (string.IsNullOrEmpty(product.product_name)) { var formatter = RequestFormat.JsonFormaterString(); return(Request.CreateResponse(HttpStatusCode.OK, new Confirmation { output = "error", msg = "Product Name is Empty" }, formatter)); } if (string.IsNullOrEmpty(product.supplier_id.ToString())) { var formatter = RequestFormat.JsonFormaterString(); return(Request.CreateResponse(HttpStatusCode.OK, new Confirmation { output = "error", msg = "Select supplier for this product" }, formatter)); } if (string.IsNullOrEmpty(product.brand_id.ToString())) { var formatter = RequestFormat.JsonFormaterString(); return(Request.CreateResponse(HttpStatusCode.OK, new Confirmation { output = "error", msg = "Select Brand" }, formatter)); } if (string.IsNullOrEmpty(product.product_category_id.ToString())) { var formatter = RequestFormat.JsonFormaterString(); return(Request.CreateResponse(HttpStatusCode.OK, new Confirmation { output = "error", msg = "Select Product Category" }, formatter)); } if (string.IsNullOrEmpty(product.mrp_price.ToString())) { var formatter = RequestFormat.JsonFormaterString(); return(Request.CreateResponse(HttpStatusCode.OK, new Confirmation { output = "error", msg = "Select MRP Price" }, formatter)); } if (string.IsNullOrEmpty(product.md_price.ToString())) { var formatter = RequestFormat.JsonFormaterString(); return(Request.CreateResponse(HttpStatusCode.OK, new Confirmation { output = "error", msg = "Select Master Dealer Price" }, formatter)); } if (string.IsNullOrEmpty(product.rp_price.ToString())) { var formatter = RequestFormat.JsonFormaterString(); return(Request.CreateResponse(HttpStatusCode.OK, new Confirmation { output = "error", msg = "Select Retailer Shop Price" }, formatter)); } if (string.IsNullOrEmpty(product.bs_price.ToString())) { var formatter = RequestFormat.JsonFormaterString(); return(Request.CreateResponse(HttpStatusCode.OK, new Confirmation { output = "error", msg = "Select Brand Shop Price" }, formatter)); } else { product insert_product = new product { product_name = product.product_name, product_code = product.product_code, unit_id = product.unit_id, brand_id = product.brand_id, product_category_id = product.product_category_id, current_balance = product.current_balance, product_image_url = product.product_image_url, has_serial = product.has_serial, has_warrenty = product.has_warrenty, warrenty_type = product.warrenty_type, warrenty_value = product.warrenty_value, vat_percentage = product.vat_percentage, tax_percentage = product.tax_percentage, rp_price = product.rp_price, md_price = product.md_price, mrp_price = product.mrp_price, bs_price = product.bs_price, specification = product.specification, remarks = product.remarks, eol_date = product.eol_date, launce_date = product.launce_date, supplier_id = product.supplier_id, accessories_category_id = product.accessories_category_id, is_active = product.is_active }; productRepository.AddProduct(insert_product); var formatter = RequestFormat.JsonFormaterString(); return(Request.CreateResponse(HttpStatusCode.OK, new Confirmation { output = "success", msg = "Product Saved successfully" }, formatter)); } } catch (Exception ex) { var formatter = RequestFormat.JsonFormaterString(); return(Request.CreateResponse(HttpStatusCode.OK, new Confirmation { output = "error", msg = ex.ToString() }, formatter)); } }
public void Update(int id, product produitIn) => _produits.ReplaceOne(product => product.idProduit == id, produitIn);
/// <summary> /// Invoked when <see cref="ToDTO"/> operation is about to return. /// </summary> /// <param name="dto"><see cref="productDto"/> converted from <see cref="product"/>.</param> static partial void OnDTO(this product entity, productDto dto);
// Создает дочерний объект к выбранному объекту дерева private void createButton_Click(object sender, EventArgs e) { if (createTypeChose.Text == String.Empty) { MessageBox.Show(Resources.AdministrationWindows_createNewButton_Click_Тип_элемента_не_выбран, Resources.error_operation_msg); return; } if (createNameBox.Text == String.Empty) { MessageBox.Show(Resources.AdministrationWindows_createNewButton_Click_Не_указано_имя_объекта, Resources.error_operation_msg); return; } var newProduct = new product(); using (var context = new ProductTrackerEntities()) { try { var query = from type in context.productType where type.typeName == createTypeChose.Text select type.typeID; foreach (var type in query.Take(1)) { newProduct.name = createNameBox.Text; newProduct.typeID = type; foreach (TreeNode node in addTarget.Nodes) { if (node.Text.Equals(createNameBox.Text) && node.Tag.Equals(newProduct.typeID)) { MessageBox.Show(Resources.AdministrationWindows_createNewButton_Click_Такой_элемент_уже_создан_в_структуре_); return; } } } context.product.Add(newProduct); context.SaveChanges(); var queryProd = from pr in context.product where pr.name == addTarget.Text select pr; var parent = new product(); foreach (var p in queryProd.Take(1)) { parent = p; } var pt = new productTree { productID = newProduct.id, parentID = parent.id, product = newProduct }; context.productTree.Add(pt); context.SaveChanges(); } catch (Exception mes) { MessageBox.Show(mes.Message); } } aw.ExpandTree(); Close(); AddProduct.Text = newProduct.name; AddProduct.Tag = newProduct.typeID; }
/// <summary> /// 保存 /// </summary> /// <param name="theData">保存的数据</param> public ActionResult SaveData(product theData, List <product_date> listProductDate, List <product_Introduction> datalistIntroduction) { //校验价格是否亏本 if (!_productBusiness.PaymentAmount(theData)) { return(Error("价格异常!请检查产品价格及营销价格")); } var supplier = _dictionaryBusiness.GetTheData(theData.supplier); if (supplier == null)//创建供应商 { var su = new dictionary() { Id = Guid.NewGuid().ToSequentialGuid(), code = "supplier", name = theData.supplier, sort = 0, enable_flag = "1" }; _dictionaryBusiness.AddData(su); theData.supplier = su.Id; } if (theData.Id == 0) { theData.enable_flag = "1"; theData.special_status = 0; theData.create_by = Operator.UserId; theData.create_time = DateTime.Now.ToCstTime(); _productBusiness.AddData(theData); } else { theData.update_by = Operator.UserId; theData.update_time = DateTime.Now.ToCstTime(); _productBusiness.UpdateData(theData); } var addIntroductions = new List <product_Introduction>(); foreach (var item in datalistIntroduction) { if (item.Id.IsNullOrEmpty()) { addIntroductions.Add(new product_Introduction() { Id = Guid.NewGuid().ToSequentialGuid(), productId = theData.Id, days = item.days, title = item.title, scheduling = item.scheduling, stay = item.stay, food = item.food, create_by = Operator.UserId, create_time = DateTime.Now.ToCstTime() }); } else { var introduction = new product_Introduction() { Id = item.Id, days = item.days, title = item.title, scheduling = item.scheduling, stay = item.stay, food = item.food, update_by = Operator.UserId, update_time = DateTime.Now.ToCstTime() }; _product_IntroductionBusiness.UpdateAny(introduction, new List <string>() { "days", "title", "scheduling", "stay", "food", "update_by", "update_time" }); } } _product_IntroductionBusiness.Insert(addIntroductions); var addProductDate = new List <product_date>(); var updateProductDate = new List <product_date>(); var teamlist = new List <team>(); //保存或更新开团日期 foreach (var item in listProductDate) { item.product_id = theData.Id; if (item.product_date_id == 0) { addProductDate.Add(item); teamlist.Add(new team() { product_id = theData.Id, start_time = item.open_date, status = 1 }); } else { updateProductDate.Add(item); } } _product_dateBusiness.Insert(addProductDate); _product_dateBusiness.Update(updateProductDate); _teamBusiness.Insert(teamlist); return(Success()); }
public IActionResult DeleteForm(int id) { product prod = db.Get <product>(id); return(View(prod)); }
private void btnRemoveProduct_Click(object sender, EventArgs e) { if (cbRemoveProducts.SelectedIndex == -1) { MessageBox.Show("You must fill in the required fields!"); return; } product p = new product(); var result = productList.Find(x => x.productName == cbRemoveProducts.SelectedItem.ToString()); try { using (var context2 = new STOK_TAKIPEntities()) { //Delete Product from stored procedure var productID = new SqlParameter("@productID", result.productID); context2.Database.ExecuteSqlCommand("exec removeProduct @productID", productID); MessageBox.Show("The transaction was successful!"); getData(); gridRegistered.Visible = false; //Refresh related instance ucProduct.Instance = null; ucLoantoUser.Instance = null; ucUnusedProducts.Instance = null; cbRemoveProducts.SelectedIndex = -1; } } catch (SqlException err) { formLogin.Instance = null; switch (err.Number) { //If the product registered before case 35100: { MessageBox.Show("There are users associated with this product!"); STOK_TAKIPEntities db = new STOK_TAKIPEntities(); var model = from l in db.loanDetails join pr in db.products on l.productID equals pr.productID join u in db.users on l.userID equals u.id where l.loanPieces >= 1 where pr.productID == result.productID select new { pr.productName, pr.productFeatures, Who = u.name + " " + u.lastName, l.loanDate, How_Many = l.loanPieces }; gridRegistered.Visible = true; gridRegistered.DataSource = model.ToList(); } break; default: MessageBox.Show("This product is not deleting!"); throw; } } }
public IActionResult Add(product prod) { db.Insert(prod); return(RedirectToAction("Index")); }
public ActionResult Create(FormCollection frm) { if (user == null) { return(RedirectToAction("Login", "Account")); } product blg = new product(); blg.name = frm["prod.name"].ToString(); blg.price = Convert.ToDecimal(frm["prod.price"]); blg.desciption = frm["prod.desciption"].ToString(); blg.smdesc = frm["prod.smdesc"].ToString(); blg.cId = Convert.ToInt32(frm["basliksec"]); datas.products.Add(blg); datas.SaveChanges(); if (Request.Files.Count > 0) { image img = new image(); string path = Server.MapPath("/"); if (Directory.Exists(path + "/productImg") == false) { Directory.CreateDirectory(path + "productImg/"); } if (!string.IsNullOrEmpty(Request.Files["pic"].FileName)) { Request.Files["pic"].SaveAs(path + "productImg/" + Request.Files["pic"].FileName); } img.folderName = string.IsNullOrEmpty(Request.Files["pic"].FileName) == true ? "" : "productImg/" + Request.Files["pic"].FileName; if (Request.Files["pic2"].FileName != null) { if (!string.IsNullOrEmpty(Request.Files["pic2"].FileName)) { Request.Files["pic2"].SaveAs(path + "productImg/" + Request.Files["pic2"].FileName); } img.folderName1 = string.IsNullOrEmpty(Request.Files["pic2"].FileName) == true ? "" : "productImg/" + Request.Files["pic2"].FileName; } if (Request.Files["pic3"].FileName != null) { if (!string.IsNullOrEmpty(Request.Files["pic3"].FileName)) { Request.Files["pic3"].SaveAs(path + "productImg/" + Request.Files["pic3"].FileName); } img.folderName2 = string.IsNullOrEmpty(Request.Files["pic3"].FileName) == true ? "" : "productImg/" + Request.Files["pic3"].FileName; } img.pid = datas.products.Max(q => q.Id); datas.images.Add(img); stockStatu abc = new stockStatu(); abc.pId = datas.products.Max(q => q.Id); datas.stockStatus.Add(abc); datas.SaveChanges(); } return(RedirectToAction("Index")); }
public static void shop_open(bool auto = true) { header(); if (auto) { int customers = ran.Next(3, 10); for (int i = 0; i < customers; i++) { int bought = ran.Next(1, 3); product[] _products = new product[bought]; for (int n = 0; n < bought; n++) { product _product = products[ran.Next(products.Length - 1)]; if (_product.inventory <= 0) { continue; } products[_product._id].inventory -= 1; _products[n] = _product; } shop_transaction(_products, ConsoleColor.Yellow); Console.WriteLine("---"); } } else { while (true) { product[] _products = new product[3]; for (int n = 0; n < 3; n++) { header(); Console.WriteLine("¡LA TIENDA ESTÁ ABIERTA!"); Console.WriteLine("========================"); Console.ForegroundColor = ConsoleColor.Yellow; Console.WriteLine("Bienvenido al cliente de la tienda de videojuegos!"); error("¡EL ÚNICO LUGAR EN EL QUE SOLO COMPRAS TRES JUEGOS DE VIDEO DIFERENTES UNA VEZ!", ConsoleColor.Yellow); Console.WriteLine("¿Qué te gustaría comprar? (nombre)"); string name = Console.ReadLine(); product _product = products.Single(product => product.name.Contains(name)); if (_product.inventory <= 0) { error("¡Lo sentimos, no tenemos ese juego en stock!"); continue; } Console.WriteLine(""); product_view(_product, ConsoleColor.Yellow); Console.WriteLine(""); Console.WriteLine("¿Te gustaría comprar? (1 : si, 2 : no)"); if (Console.ReadLine() != "2") { products[_product._id].inventory -= 1; _products[n] = _product; Console.WriteLine("Genial, voy a agregar eso a tu carrito de compras..."); } if (_products.Length < 3) { Console.WriteLine("¿Seguir comprando? (1 : si, 2 : no)"); if (Console.ReadLine() == "1") { continue; } } break; } shop_transaction(_products, ConsoleColor.Yellow); Console.WriteLine("¡Muy bien, esperamos que vuelvas!"); Console.ReadKey(); header(); Console.WriteLine("¿Cerrar la tienda? (1 : si, 2 : no)"); if (Console.ReadLine() == "1") { break; } } } }
private product ParseModel(ProductVM vm) { product model; if (vm.Id == null || vm.Id == 0) { model = new product(); } else { model = dbContext.products.SingleOrDefault(p=> p.id == vm.Id); } model.name = vm.Name; model.description = vm.Description; model.img_url = vm.ImgUrl; model.is_active = vm.IsActive; model.location_id = vm.LocationId; model.category_id = vm.CategoryId; model.created_date = vm.CreatedDate; model.currency = vm.Currency; model.price = vm.Price; model.quantity = vm.Quantity; model.unit_measure = vm.UnitMeasure; return model; }
public void AddRecord(product Record) { myRecords.Add(record); }
public void Remove(product produitIn) => _produits.DeleteOne(product => product.Id == produitIn.Id);
public static IEnumerable<Packager.Consts.file> getModuleFiles(INodeContext ctx, product prod, LoggerMemory logger) { try { //var ctx = new serverContext(url, logger); if (ctx.line == LineIds.no) { logger.ErrorLine("?", "Unknown product Line"); return Enumerable.Empty<Packager.Consts.file>(); } if (prod == null) prod = new product { url = vsNetProductId, styleSheet = ex.stdStyle, line = ctx.line, title = ctx.actNode.title, //Items = new data[] { new ptr(ctx.actNode.type == runtimeType.no ? new taskCourse() : null, ctx.url) { takeChilds = childMode.selfChild } } Items = new data[] { new ptr(true, ctx.url) { takeChilds = childMode.selfChild } } }; var sm = ctx.getSiteMap(logger); prod = (product)prodDef.expand(prod, sm, logger); prodDef.addInstructions(prod, logger); var bldProd = new buildProduct { prod = prod, natLangs = new Langs[] { Langs.cs_cz }, dictType = dictTypes.L }; Cache cache = new Cache(logger, new Langs[] { Langs.cs_cz }); return bldProd.getFiles(cache, logger, sm).ToArray(); } catch (Exception exp) { logger.ErrorLineFmt("?", ">>>> Compiling Error {0}", LowUtils.ExceptionToString(exp)); return Enumerable.Empty<Packager.Consts.file>(); } }
public IActionResult Edit(product prod) { db.Update(prod); return(RedirectToAction("Index")); }
//done button to insert values in database protected void Btndone_Click(object sender, EventArgs e) { //here we are getting follow people values(asptokeninput) from ItemList.aspx page,it can be multiple so we are entering multiple values by '/' for (int i = 0; i <= lbList2.Items.Count - 1; i++) { listid = lbList2.Items[i].Value.Split('-'); string name = listid[0]; eco += listid[0] + "/"; } if (eco != "") { eco = eco.Remove(eco.Length - 1); } namesplit = LblFLName.Text.Split(' '); if (p) { var pp = new product { FirstName = namesplit[0], LastName=namesplit[1], Password = Hiddpass.Value, University = LblUni.Text, Course = LblCourse.Text, Year = LblYear.Text, Location = LblCity.Text, SuaveID = Label2.Text + TxtSuaveid.Text, About = TxtAbout.Text, FollowPpl = eco, Project = TxtCreateproj.Text, Emailid=TxtEmailid.Text }; //inserting user details in table admin var hh = a1.GetCollection<product>("admin"); hh.Insert(pp); //here we are creating projectid,it is a combination of suaveid+first 3 letters of project name proid = TxtCreateproj.Text.Substring(0,3); var pp2 = new project { Project = TxtCreateproj.Text, ProjectId=Label2.Text + TxtSuaveid.Text+proid, SuaveID = Label2.Text + TxtSuaveid.Text }; //inserting project details in table ProjectDet var hh2 = a1.GetCollection<project>("ProjectDet"); hh2.Insert(pp2); ScriptManager.RegisterStartupScript(this.Page, this.GetType(), "Alert", "alert('Inserted ');", true); //here we move forward for dash board page by passing suaveid as a parameter string su=Label2.Text + TxtSuaveid.Text; Session["SuaveID"] = su; Response.Redirect("Default.aspx"); TxtFirstname.Text = ""; Txtlastname.Text = ""; txtPwd.Text = ""; txtRePwd.Text = ""; TxtUniversity.Text = ""; TxtCourse.Text = ""; DdlYear.Items.Clear(); TxtLocation.Text = ""; TxtSuaveid.Text = ""; TxtAbout.Text = ""; tiTest2.Items.Clear(); TxtCreateproj.Text = ""; } }