public void CanCreateOutputFile() { var pricefileTxt = "pricefile.txt"; if (File.Exists(pricefileTxt)) File.Delete(pricefileTxt); var premiumSuppliers = new List<int> {219, 204}; var troubleSuppliers = new List<int> {32, 101}; var products = new Dictionary<string, Product> { {"Apples", new Product(1100, 1199, .40, 14)}, {"Bananas", new Product(1200, 1299, .35, 5)}, {"Berries", new Product(1300, 1399, .55, 7)} }; var productCollection = new ProductList( premiumSuppliers, troubleSuppliers, .1, 2, products ); var generator = new PriceFileGenerator(new ProduceFileParser(), productCollection); generator.CreatePriceFile(pricefileTxt, @".\Data\produce.csv"); assertFileContentsAreSame("..\..\pricefile.txt", pricefileTxt); }
public ProductList GetProducts() { string connectionString = Properties.Settings.Default.Store; SqlConnection con = new SqlConnection(connectionString); SqlCommand cmd = new SqlCommand("GetProducts", con); cmd.CommandType = CommandType.StoredProcedure; ProductList products = new ProductList(); try { con.Open(); SqlDataReader reader = cmd.ExecuteReader(); while (reader.Read()) { // Create a Product object that wraps the // current record. Product product = new Product((string)reader["ModelNumber"], (string)reader["ModelName"], (decimal)reader["UnitCost"], (string)reader["Description"]); // Add to collection products.Add(product); } } finally { con.Close(); } return products; }
/// <summary> /// The create. /// </summary> /// <returns> /// The <see cref="ActionResult" />. /// </returns> public ActionResult Create() { this.ViewBag.CompanyId = new SelectList(this.productService.Companies, "CompanyId", "CompanyName"); this.ViewBag.SubCategoryId = new SelectList(this.dataContext.Categories.Where(c => c.ParentCategory != null), "CategoryID", "CategoryName"); this.ViewBag.CatagoryId = new HashSet<Category>(this.dataContext.Categories.Where(c => c.ParentCategory == null)).Select( c => new SelectListItem { Text = c.CategoryName, Value = c.CategoryID.ToString(CultureInfo.InvariantCulture) }); var products = new ProductList(this.productService.GetProducts); return this.View(products); }
public void BusinessListBaaseFactory_Save_New_items() { ProductList list = new ProductList(); list.Add(new Product() { Name = "Test" }); list.Add(new Product() { Name = "Test1" }); list.Add(new Product() { Name = "Test2" }); ProductList products = _factory.Create(); products = _factory.Update(list); _repository.AssertWasCalled(x => x.Save(null), r => r.IgnoreArguments().Repeat.Times(3)); unitOfWorkStub.AssertWasCalled(x => x.TransactionalFlush()); }
public Company() { AllProducts = new ProductList();// new List<Product>(); AllProjects = new List<Project>(); AllEmployees = new StaffList(); CEO = new CEO(); AllEmployees.Add(CEO); Accounting = new Accounting(1500000); Office = new Office(); Office.PhysicalObjectsInOffice.Add(AllEmployees); //BusinessCycles.ProjectCreated += new ProjectCreatedEventHandler(BusinessCycles_ProjectCreated); Accounting.ProfitableItems.Add(AllProducts); Accounting.IndebtedItems.Add(AllEmployees); Accounting.IndebtedItems.Add(Office); Accounting.IndebtedItems.Add(AllProducts); }
public void BusinessListBaseFactory_Fetch_No_Criteria() { ProductList list = new ProductList(); list.Add(new Product() { Name = "Test" }); list.Add(new Product() { Name = "Test1" }); list.Add(new Product() { Name = "Test2" }); ProductList products = _factory.Create(); _repository.Expect(x => x.FindAll(DetachedCriteria.For(typeof (Product)))).IgnoreArguments().Return(list); _repository.Replay(); products = _factory.Fetch(); _repository.AssertWasCalled(x => x.FindAll(DetachedCriteria.For(typeof(Product))), r => r.IgnoreArguments()); Assert.AreEqual(3, products.Count); }
[WebMethod(EnableSession = true)] //啟用Session public static ProductList GetCurrentProducts() { //確認HttpContext.Current是否為空 if (HttpContext.Current != null) { //如果Session["Product"]不存在,就建一個空的Products物件 if (HttpContext.Current.Session["Products"] == null) { var order = new ProductList(); HttpContext.Current.Session["Products"] = order; } return((ProductList)HttpContext.Current.Session["Products"]); } else { throw new InvalidOperationException("System.web.HttpContext.Current為空,請檢查"); } }
protected void BindProductList() { try { ProductController sysmgr = new ProductController(); List <Product> datainfo = sysmgr.Product_List(); datainfo.Sort((x, y) => x.ProductName.CompareTo(y.ProductName)); ProductList.DataSource = datainfo; ProductList.DataTextField = nameof(Product.ProductName); ProductList.DataValueField = nameof(Product.ProductID); ProductList.DataBind(); ProductList.Items.Insert(0, "..select"); } catch (Exception ex) { errormsgs.Add(GetInnerException(ex).Message); LoadMessageDisplay(errormsgs, "alert alert-danger"); } }
public static async Task <IActionResult> GetProductList( [HttpTrigger(AuthorizationLevel.Anonymous, "get", "post", Route = null)] HttpRequest req, ILogger log) { string resource = "https://" + environmentId + ".cloudax.dynamics.com"; HttpClient client = new HttpClient(); AuthenticationHelper bearerToken = new AuthenticationHelper(); client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", bearerToken.GetBearerToken(environmentId).Result.AccessToken.ToString()); ProductList productList = new ProductList(); productList.GetProductList(client, resource); string responseMessage = JsonConvert.SerializeObject(productList); return(new OkObjectResult(responseMessage)); }
private async void ColorComboBox_SelectionChanged(object sender, SelectionChangedEventArgs e) { string select = e.AddedItems[0].ToString(); if (select.Equals("SortByName")) { ProductList productList = await _productServices.TodaySpecial(); var ProductSortByPrice = productList.data.OrderBy(P => P.name); ProductList.ItemsSource = ProductSortByPrice; } else { ProductList productList = await _productServices.TodaySpecial(); var ProductSortByPrice = productList.data.OrderBy(P => P.price); ProductList.ItemsSource = ProductSortByPrice; } }
public ProductList GetProductsByMultiType(SearchModel seach) //Advance search { ProductList productList = new ProductList(); List <SANPHAM> list = new List <SANPHAM>(); if (seach.KhuyenMai) { list = db.SANPHAMs.Where(sp => sp.DAXOA == false && sp.TEN.Contains(seach.Ten) && sp.NHASANXUAT1.TEN.Contains(seach.NhaSanSuat) && sp.LOAISANPHAM1.TEN.Contains(seach.LoaiSanPham) && sp.DONGIABAN >= seach.GiaToiThieu && sp.DONGIABAN < seach.GiaToiDa && sp.SANPHAMBANCHAY == seach.SPBanChay && sp.MAKHUYENMAI != 0).ToList(); } else { list = db.SANPHAMs.Where(sp => sp.DAXOA == false && sp.TEN.Contains(seach.Ten) && sp.NHASANXUAT1.TEN.Contains(seach.NhaSanSuat) && sp.LOAISANPHAM1.TEN.Contains(seach.LoaiSanPham) && sp.DONGIABAN >= seach.GiaToiThieu && sp.DONGIABAN < seach.GiaToiDa && sp.SANPHAMBANCHAY == seach.SPBanChay && sp.MAKHUYENMAI == 0).ToList(); } if (list.Count > 0) { productList.path = "Tìm kiếm nâng cao: có tất cả " + list.Count + " kết quả"; } else { productList.path = "Tìm kiếm nâng cao: không tìm thấy kết quả nào"; } for (int i = 0; i < list.Count; i++) { int makhuyenmai = list[i].MAKHUYENMAI.Value; if (makhuyenmai != 0) { var _mkm = db.KHUYENMAIs.Where(km => km.DAXOA.Value.Equals(false) && km.MA.Equals(makhuyenmai)).SingleOrDefault(); double dongiagiam = (double)(list[i].DONGIABAN * (100 - _mkm.NOIDUNG.Value)) / 100; productList.newListPromotion.Add(dongiagiam); } else { productList.newListPromotion.Add(0); } } Mapper.CreateMap <SANPHAM, SANPHAMModel>(); productList.newList = Mapper.Map <List <SANPHAM>, List <SANPHAMModel> >(list); return(productList); }
public void BindProductList() { try { ProductController sysmgr = new ProductController(); List <Product> info = sysmgr.Products_List(); info.Sort((x, y) => x.ProductName.CompareTo(y.ProductName)); ProductList.DataSource = info; ProductList.DataTextField = nameof(Product.ProductName); ProductList.DataValueField = nameof(Product.ProductID); ProductList.DataBind(); ProductList.Items.Insert(0, "select ..."); } catch (Exception ex) { errormsgs.Add("File Error: " + GetInnerException(ex).Message); LoadMessageDisplay(errormsgs, "alert alert-warning"); } }
protected override void Seed(MyTeletouch.DBContexts.ApplicationDbContext context) { // http://stackoverflow.com/questions/17169020/debug-code-first-entity-framework-migration-codes // Enable debugging for migrations if (System.Diagnostics.Debugger.IsAttached == false) { // System.Diagnostics.Debugger.Launch(); } // Migrate countries var countryList = new CountryList(); countryList.InsertCountries(); // Migrate products var productList = new ProductList(); productList.InsertProducts(); }
//Method will be called when reported is loaded public void OnReportLoaded(ReportViewerOptions reportOption) { //You can update report options here if (reportOption.SubReportModel != null) { //Set child subreport data source reportOption.SubReportModel.DataSources = new Syncfusion.Reporting.Web.ReportDataSourceCollection(); reportOption.SubReportModel.DataSources.Add(new Syncfusion.Reporting.Web.ReportDataSource { Name = "list", Value = ProductList.GetData() }); } else { reportOption.SubReportModel.DataSources = new Syncfusion.Reporting.Web.ReportDataSourceCollection(); reportOption.SubReportModel.DataSources.Add(new Syncfusion.Reporting.Web.ReportDataSource { Name = "list", Value = ProductList.GetData() }); } }
public int displayproduct() { int count = 0; try { ProductList p = new ProductList(); List <Product> list = p.products(); count = list.Count(); Console.WriteLine(list.ToStringTable( new[] { "Id", "Item Name", "Price" }, a => a.Id, a => a.Name, a => a.Price)); } catch (Exception ex) { Console.WriteLine("Error in displayproducts,display()," + ex.Message); } return(count); }
private async void Search(string searchString, int page, int size, string sort, int sequence, string priceGt, string priceLte) { IndicatorIsRunning = true; RestSharpService _restSharpService = new RestSharpService(); ProductListRD productListRD = await _restSharpService.FuzzySearch(searchString, sequence, page, size, sort, int.Parse(priceGt), int.Parse(priceLte)); TotalProductNum = productListRD.result.total; ProductNum += productListRD.result.data.Count; List <ProductListItem> tempList = new List <ProductListItem>(); foreach (var item in productListRD.result.data) { ProductList.Add(item); } ChangeButtonText(); IndicatorIsRunning = false; }
protected override void RefreshMainData() { PgMng.Grow(string.Empty, "Producto"); // Guardamos la configuración actual del listado _selectedOid = ActiveOID; switch (DataType) { case EntityMngFormTypeData.Default: List = ProductList.GetElaboradosList(false); break; case EntityMngFormTypeData.ByParameter: _sorted_list = List.GetSortedList(); break; } PgMng.Grow(string.Empty, "Lista de Productoes"); }
public ActionResult Create(ProductList pl) { //Total Price calculation and save data in Order table double totalPrice = 0; foreach (var item in pl.Products) { if (item.IsCheck) { totalPrice += item.UnitPrice; } } var value = pl.Customer.CustomerID; Order order = new Order() { CustomerID = pl.Customer.CustomerID, OrderStatus = "Ordered", TotalPrice = totalPrice }; //Save each item in OrderItem table List <OrderItem> orderItemList = new List <OrderItem>(); foreach (var item in pl.Products) { if (item.IsCheck) { OrderItem orderItem = new OrderItem() { OrderID = pl.OrderID, ProductID = item.ProductID }; orderItemList.Add(orderItem); } } db.Orders.Add(order); //Save Order entry db.OrderItems.AddRange(orderItemList); //save all products entry in one order db.SaveChanges(); return(RedirectToAction("Create")); }
public void Given() { var premiumSupplierMarkup = .1; var troubleSupplierDiscountInRands = 2; var sample = new Product(100, 200, .1, 14); _products = new ProductList( new List <int> { 1 }, new List <int> { 2 }, premiumSupplierMarkup, troubleSupplierDiscountInRands, new Dictionary <string, Product> { { "SampleProductName", sample } }); }
public async Task <IActionResult> Edit(int id, [Bind("Id,Title,Price,Image,Color,IsAvailable,ProductId,TagId")] ProductList productList, IFormFile image) { if (id != productList.Id) { return(NotFound()); } if (ModelState.IsValid) { try { if (image != null) { var name = Path.Combine(_he.WebRootPath + "/Images", Path.GetFileName(image.FileName)); await image.CopyToAsync(new FileStream(name, FileMode.Create)); productList.Image = "Images/" + image.FileName; } if (image == null) { productList.Image = "Images/noimage.PNG"; } _context.Update(productList); await _context.SaveChangesAsync(); } catch (DbUpdateConcurrencyException) { if (!ProductListExists(productList.Id)) { return(NotFound()); } else { throw; } } return(RedirectToAction(nameof(Index))); } ViewData["TagId"] = new SelectList(_context.TagProduct, "TagId", "TagId", productList.TagId); ViewData["ProductId"] = new SelectList(_context.PhotoProducts, "ProductId", "ProductId", productList.ProductId); return(View(productList)); }
private async void tbSearch_TextChanged(object sender, TextChangedEventArgs e) { List <Product> listSearch = new List <Product>(); ProductList productList = await _productServices.TodaySpecial(); if (productList != null) { foreach (var item in productList.data) { if (item.name.Contains(tbSearch.Text)) { listSearch.Add(item); } } // đổ dữ liệu lấy dc vào giao diện ProductList.ItemsSource = listSearch; } }
protected void Page_Load(object sender, EventArgs e) { IList <Product> products = ProductDataSource.GetNewProducts(this.UseDays, this.Days, this.MaxItems, 0, "CreatedDate DESC"); if (products != null && products.Count > 0) { if (!string.IsNullOrEmpty(this.Caption)) { CaptionLabel.Text = this.Caption; } ProductList.RepeatColumns = Columns; ProductList.DataSource = products; ProductList.DataBind(); } else { this.Visible = false; } }
// Method to fill the datagrid public void FillProductGrid() { if (ProductList.Count() > 0) { ProductList.Clear(); } using (var db = new DataSmartDBContext()) { var prod = db.Produits.ToList(); if (prod != null) { foreach (var d in prod) { ProductList.Add(d); } } } }
public static ProductList GetWTEProductsByCriteria(string searchBy, string searchString) { ProductList aList = null; MyDBConnection myConn = new MyDBConnection(); SqlConnection conn = new SqlConnection(); SqlDataReader dr; SqlCommand cmd = null; try { // Open the connection conn = myConn.OpenDB(); cmd = new SqlCommand(); cmd.Connection = conn; cmd.CommandType = CommandType.StoredProcedure; cmd.CommandText = "dbo.GetWTEProductsBySearchCriteria"; cmd.Parameters.Add("@SearchCriteria", SqlDbType.VarChar).Value = searchBy; cmd.Parameters.Add("@input", SqlDbType.VarChar).Value = searchString; dr = cmd.ExecuteReader(CommandBehavior.CloseConnection); if (dr.HasRows) { aList = new ProductList(); while (dr.Read()) { aList.Add(FillDataRecord(dr)); } } cmd.Dispose(); dr.Close(); } finally { myConn.CloseDB(conn); } return(aList); }
// This class manages s serializable file object by reading from and writing to a file // Write the Product List to file as a serialized binary object public static bool writeToFile(ProductList plist, string fn) { Stream thisFileStream; BinaryFormatter serializer = new BinaryFormatter(); if (plist.size() > 0) { try { thisFileStream = File.Create(fn); } catch (Exception ex) { MessageBox.Show("File open error: Owl Member List not written", "SFManager File Open"); MessageBox.Show(ex.ToString()); return(false); } // end Try try { serializer.Serialize(thisFileStream, plist); MessageBox.Show("File write: Owl Member List was written to serializable file."); } catch (Exception ex) { MessageBox.Show("File write error: Owl Member List not written", "SFManager File Write"); MessageBox.Show(ex.ToString()); return(false); } finally { thisFileStream.Close(); } // end Try } else { MessageBox.Show("No Product in List"); } // end if return(true); // The file write succeeded } // end WriteToFile
protected override void OnCreate(Bundle bundle) { base.OnCreate(bundle); SetContentView(Resource.Layout.BrowsingLayout1); mRecyclerView = FindViewById <RecyclerView>(Resource.Id.recyclerView1); if (this.Intent.Extras != null) { var category = (ProductCategory)Intent.Extras.GetInt("CategoryID"); var productlist = Intent.Extras.GetStringArray("lijst"); CategoryID = category; ListOfProducts = productlist.ToList(); } mProductList = new ProductList(CategoryID); //button = FindViewById<Button>(Resource.Id.button1); ButtonGroceries = FindViewById <ImageView>(Resource.Id.ListImageView); ButtonHelp = FindViewById <ImageView>(Resource.Id.HelpImageView); //---------------------------------------------------------------------------------------- // Layout Managing Set-up mLayoutManager = new GridLayoutManager(this, 2, GridLayoutManager.Vertical, false); mRecyclerView.SetLayoutManager(mLayoutManager); //---------------------------------------------------------------------------------------- // Adapter Set-up mAdapter = new BrowsingGroupAdapter(mProductList); mAdapter.ItemClick += OnItemClick; //button.Click += Button_Click; ; ButtonGroceries.Click += List_Click; ButtonHelp.Click += Help_Click; mRecyclerView.SetAdapter(mAdapter); }
// GET: Orders/Create public ActionResult Create(int id) { List <Product> pr = new List <Product> { new Product() { ProductID = 1, ProductName = "Coffee", IsCheck = false, UnitPrice = 3.5 }, new Product() { ProductID = 2, ProductName = "Pizza", IsCheck = false, UnitPrice = 20 }, new Product() { ProductID = 3, ProductName = "Salad", IsCheck = false, UnitPrice = 9.75 }, new Product() { ProductID = 4, ProductName = "Dumpling", IsCheck = false, UnitPrice = 13 }, new Product() { ProductID = 5, ProductName = "Donut", IsCheck = false, UnitPrice = 2.75 } }; ProductList prList = new ProductList { Products = pr }; var queryProductListinDB = db.Products; if (queryProductListinDB.Count() == 0) { db.Products.AddRange(pr); db.SaveChanges(); } prList.Customer = db.Customers.Find(id); return(View(prList)); }
public Product UpdateProductList(UserModel user, List <ProductList> productList, Product product) { if (!productList.IsNullOrZero()) { if (ProductList.IsNullOrZero()) { ProductList = new List <ProductList>(); } var savedProductItemList = productList.Select(p => p.SeperationFactorValue).ToList(); var removedImagesList = ProductList.Where(p => !savedProductItemList.Contains(p.SeperationFactorValue)).ToList(); var newProductItems = productList.Where(p => p.ProductId == 0).ToList(); removedImagesList.ForEach(item => { ProductList.Remove(item); }); productList.ForEach(item => { if (!item.Id.IsNullOrZero()) { var res = product.ProductList.FirstOrDefault(p => p.Id == item.Id); if (!res.IsNull()) { res.Update(user, item.AvailableQuantity, item.InvoicedPrice, item.PurchasedPrice, item.SeperationFactorValue, item.ReorderMargin); } } }); if (!newProductItems.IsNullOrZero()) { newProductItems.ForEach(obj => { ProductList.Add(new ProductList(_user).Create(Id, obj.AvailableQuantity, obj.InvoicedPrice, obj.PurchasedPrice, obj.SeperationFactorValue, obj.ReorderMargin)); }); } } return(this); }
protected void BindProductList() { //any time you leave the web page to // access another project, place your // code within a try catch try { //create an instance of the interface class // that exists in your BLL //you will need to have declared the namespace // of the class at the top of this file ProductController sysmger = new ProductController(); //call the method in the controller that will // return the data that you wish //you will need to have declared the namespace // of the entity class at the top of this file List <Product> info = sysmger.Products_List(); //sort the returned data info.Sort((x, y) => x.ProductName.CompareTo(y.ProductName)); //load the dropdownlist ProductList.DataSource = info; ProductList.DataTextField = nameof(Product.ProductName); ProductList.DataValueField = nameof(Product.ProductID); ProductList.DataBind(); //add a prompt line to the list ProductList.Items.Insert(0, new ListItem("select..", "0")); } catch (Exception ex) { //Sometimes, depending on the exception you will // simply get a message pointing you to the // Inner Exception which will hold the true error //Pass the exception to the GetInnerException() method // we have supplied. //This GetInnerException() returns the most inner // error message MessageLabel.Text = GetInnerException(ex).Message; } }
public int Bind() { SqlConnection cn = new SqlConnection(ConfigurationManager.ConnectionStrings["Test"].ToString()); cn.Open(); SqlDataAdapter da = new SqlDataAdapter("SELECT * FROM service", cn); DataTable dt = new DataTable(); da.Fill(dt); cn.Close(); PagedDataSource pgitems = new PagedDataSource(); DataView dv = new DataView(dt); pgitems.DataSource = dv; pgitems.AllowPaging = true; pgitems.PageSize = 5; pgitems.CurrentPageIndex = PageNumber; int total = pgitems.PageCount; if (pgitems.PageCount > 1) { rptPages.Visible = true; ArrayList pages = new ArrayList(); for (int i = 0; i < pgitems.PageCount; i++) { pages.Add((i + 1).ToString()); } rptPages.DataSource = pages; rptPages.DataBind(); } else { rptPages.Visible = false; } ProductList.DataSource = pgitems; ProductList.DataBind(); return(total); }
private void AddFunc() { ProductList pl = new ProductList(); pl.title = txt_title.Text; pl.img = txt_img.Text; pl.mainstyle = txt_mainstyle.Text; pl.memo = txt_memo.Text; pl.pagetype = ddl_pagetype.SelectedValue; pl.titlestyle = txt_titlestyle.Text; pl.typeid = int.Parse(ddl_type.SelectedValue); pl.url = txt_url.Text; string jpath = @"\json\ProductList.json"; List <ProductList> pll = GetJsonToObject <List <ProductList> >(jpath); pl.id = pll.Count + 1; pll.Add(pl); //保存修改 string s1 = JsonSerializer <List <ProductList> >(pll); Write(CurrentPath + "\\" + jpath, s1); Product product = new Product(); product.id = pll.Count; string jpath2 = @"\json\products\product" + product.id + ".json"; product.date = DateTime.Now.ToLongDateString(); product.content = txt_content.Text; string s2 = JsonSerializer <List <Product> >(new List <Product>() { product }); Write(CurrentPath + "\\" + jpath2, s2); ClientScript.RegisterStartupScript(ClientScript.GetType(), "myscript", "<script>successCallback('添加成功!');</script>"); // Alert("添加成功!"); }
public void RemoveProduct(product u) { bool x = true; foreach (product ur in ProductList) { if (ur.Description.Pcode == u.Description.Pcode) { x = false; ur.Description.Pstock = ur.Description.Pstock - u.Description.Miktar; } } if (x == true) { ProductList.Remove(u); x = true; } }
public ActionResult AddQun(Class2 p1) { ProductList product = new ProductList(); string s1 = Session["Product"].ToString(); product = db.ProductLists.Where(u => u.ProductName == s1).SingleOrDefault(); product.TotalQun = (p1.Quantity + product.TotalQun); product.CurrentQun = (p1.Quantity + product.CurrentQun); db.SaveChanges(); if (product != null) { return(Content("<script language='javascript' type='text/javascript'>alert('Quantity Update Successfully'); window.location.replace('Index');</script>")); } else { return(Content("<script language='javascript' type='text/javascript'>alert('Some Error occure Please Try again after some time'); window.location.replace('Logout');</script>")); } }
protected void Page_Load(object sender, EventArgs e) { ProductList.ItemStyle.Width = new System.Web.UI.WebControls.Unit(100 / this.Columns, System.Web.UI.WebControls.UnitType.Percentage); var products = ProductDataSource.GetProductSpecials(this.MaxItems, 0); if (products != null && products.Count > 0) { if (!string.IsNullOrEmpty(this.Caption)) { CaptionLabel.Text = this.Caption; } ProductList.RepeatColumns = this.Columns; ProductList.DataSource = products; ProductList.DataBind(); } else { this.Visible = false; } }
protected void Page_Load(object sender, EventArgs e) { var products = new List <Product>(); products.Add(new Product() { ProductID = 1, Name = "Bike", Price = 150.00 }); products.Add(new Product() { ProductID = 2, Name = "Helmet", Price = 19.99 }); products.Add(new Product() { ProductID = 3, Name = "Tire", Price = 10.00 }); ProductList.DataSource = products; ProductList.DataBind(); }
public DialogResult ShowDialog(IWin32Window owner, Project project, Product absorber) { this.products = project.Products; this.absorber = absorber; binder = new PhotoBinder(FileHelper.PathToProject(project)); picture.DataBindings.Clear(); picture.DataBindings.Add("Image", binder, "Img"); labelInfo.DataBindings.Clear(); labelInfo.DataBindings.Add("Text", binder, "InfoText"); foreach (Product prod in products) { if (prod != absorber) cbProducts.Items.Add(prod); } return base.ShowDialog(owner); }
public ActionResult Upload([FromServices] IHostingEnvironment env, ProductList pl, Product p) { var fileName = Path.Combine("upload", DateTime.Now.ToString("MMddHHmmss") + ".jpg"); using (var stream = new FileStream(Path.Combine(env.WebRootPath, fileName), FileMode.CreateNew)) { pl.PImg.CopyTo(stream); } Product c = db.Product.Add(new Product()).Entity; c.ProductName = p.ProductName; c.Feature = p.Feature; c.Description = p.Description; c.Price = p.Price; c.BigImg = fileName; c.ProductType = Request.Form["commission"]; c.TheCustomer = db.Customer.SingleOrDefault(u => u.Email == User.Identity.Name).ObjId; db.SaveChanges(); return(Index()); }
public int SaveProductList(string userId, string listName, List<long> productIds) { using (var sf = new SimplyFindEntities()) { var productList = new ProductList {Name = listName, UserId = userId }; foreach (var productId in productIds) { sf.ProductListToProduct.Add(new ProductListToProduct { ProductId = (int) productId, ProductList = productList }); } try { sf.SaveChanges(); return productList.ProductListId; } catch (System.Data.Entity.Validation.DbEntityValidationException dbEx) { Exception raise = dbEx; foreach (var validationErrors in dbEx.EntityValidationErrors) { foreach (var validationError in validationErrors.ValidationErrors) { string message = string.Format("{0}:{1}", validationErrors.Entry.Entity.ToString(), validationError.ErrorMessage); // raise a new exception nesting // the current instance as InnerException raise = new InvalidOperationException(message, raise); } } throw raise; } } }
public void TestInitialize() { this.productList = new ProductList(); }
private void AddFunc() { ProductList pl = new ProductList(); pl.title = txt_title.Text; pl.img = txt_img.Text; pl.mainstyle = txt_mainstyle.Text; pl.memo = txt_memo.Text; pl.pagetype = ddl_pagetype.SelectedValue; pl.titlestyle = txt_titlestyle.Text; pl.typeid = int.Parse(ddl_type.SelectedValue); pl.url = txt_url.Text; string jpath = @"\json\ProductList.json"; List<ProductList> pll = GetJsonToObject<List<ProductList>>(jpath); pl.id = pll.Count + 1; pll.Add(pl); //保存修改 string s1 = JsonSerializer<List<ProductList>>(pll); Write(CurrentPath + "\\" + jpath, s1); Product product = new Product(); product.id = pll.Count; string jpath2 = @"\json\products\product" + product.id + ".json"; product.date = DateTime.Now.ToLongDateString(); product.content = txt_content.Text; string s2 = JsonSerializer<List<Product>>(new List<Product>() { product }); Write(CurrentPath + "\\" + jpath2, s2); ClientScript.RegisterStartupScript(ClientScript.GetType(), "myscript", "<script>successCallback('添加成功!');</script>"); // Alert("添加成功!"); }
public static void AddProductList(Nullable<int> idMenu) { using (Model1Container db = new Model1Container()) { var prL = (from p in db.ProductList where p.MenuFK == idMenu select p.MenuFK).FirstOrDefault(); if (prL == 0) { var menuDay = (from md in db.MenuDay where md.MenuFK == idMenu select md).ToList<MenuDay>(); List<T> mealList = new List<T>(); foreach (var p in menuDay) { mealList.Add(new T() { quant = (double)(double)(p.QuantPortionsB / p.Meal.Portions), meal = p.Meal }); mealList.Add(new T() { quant = (double)((double)p.QuantPortionsD / p.Meal1.Portions), meal = p.Meal1 }); mealList.Add(new T() { quant = (double)((double)p.QuantPortionsD / p.Meal2.Portions), meal = p.Meal2 }); mealList.Add(new T() { quant = (double)((double)p.QuantPortionsD / p.Meal3.Portions), meal = p.Meal3 }); mealList.Add(new T() { quant = (double)((double)p.QuantPortionsS / p.Meal4.Portions), meal = p.Meal4 }); } foreach (var m in mealList) { var prList = (from mp in db.MealProducts where mp.MealFK == m.meal.MealPK select new { ProdID = mp.ProductFK, ProdQ = mp.Quantity * m.quant }).ToList(); foreach (var pl in prList) { ProductList prodList = (from p in db.ProductList where p.MenuFK == idMenu && p.ProductFK == pl.ProdID select p).FirstOrDefault(); if (prodList != null) prodList.Quantity += (Nullable<decimal>)pl.ProdQ; else { prodList = new ProductList() { MenuFK = (int)idMenu, ProductFK = pl.ProdID, Quantity = (Nullable<decimal>)pl.ProdQ }; db.ProductList.Add(prodList); } db.SaveChanges(); } } } } }
// GET: Product public ActionResult Index(string name , int id) { ProductList productList = new ProductList(); if (name.Equals("Default")) //hiển thị tất cả sản phẩm { productList.productList = db.SANPHAMs.Where(sp => sp.DAXOA.Value.Equals(false) && sp.SANPHAMBAN.Value.Equals(true)).ToList(); } if (name.Equals("Category")) //lấy theo category { var category = db.LOAISANPHAMs.Where(lsp => lsp.MA == id && lsp.DAXOA.Value.Equals(false)).SingleOrDefault(); productList.path = category.TEN; productList.productList = db.SANPHAMs.Where(sp => sp.DAXOA.Value.Equals(false) && sp.SANPHAMBAN.Value.Equals(true) && sp.LOAISANPHAM == id).ToList(); } if (name.Equals("Manufactory")) //lấy theo nhà sản xuất { var manufactory = db.NHASANXUATs.Where(nsx => nsx.MA == id && nsx.DAXOA.Value.Equals(false)).SingleOrDefault(); productList.path = manufactory.TEN; productList.productList = db.SANPHAMs.Where(sp => sp.DAXOA.Value.Equals(false) && sp.SANPHAMBAN.Value.Equals(true) && sp.NHASANXUAT == id).ToList(); } for (int i = 0; i < productList.productList.Count; i++) { int makhuyenmai = productList.productList[i].MAKHUYENMAI.Value; if (makhuyenmai != 0) { var _mkm = db.KHUYENMAIs.Where(km => km.DAXOA.Value.Equals(false) && km.MA.Equals(makhuyenmai)).SingleOrDefault(); float dongiagiam = (float)(productList.productList[i].DONGIABAN * (100 - _mkm.NOIDUNG.Value)) / 100; productList.productListPromotion.Add(dongiagiam); } else { productList.productListPromotion.Add(0); } } return View(productList); }
public ActionResult Create(ProductList product) { if (product.IsDuplicate(i => i.ProductName)) { this.ModelState.AddModelError(string.Empty, "Duplicate products"); } if (this.ModelState.IsValid) { this.productService.Add(product.Where(i => i.ProductId == 0)); this.dataContext.SaveChanges(); return this.RedirectToAction("Index"); } this.ViewBag.CompanyId = new SelectList(this.dataContext.Companies, "CompanyId", "CompanyName"); this.ViewBag.SubCategoryId = new SelectList(this.dataContext.Categories, "SubCategoryId", "SubCategoryName"); this.ViewBag.CatagoryId = new HashSet<Category>(this.dataContext.Categories).Select( c => new SelectListItem { Text = c.CategoryName, Value = c.CategoryID.ToString(CultureInfo.InvariantCulture) }); return this.View(product); }
public void Given() { var premiumSupplierMarkup = .1; var troubleSupplierDiscountInRands = 2; var sample = new Product(100, 200, .1, 14); _products = new ProductList( new List<int> { 1 }, new List<int> { 2 }, premiumSupplierMarkup, troubleSupplierDiscountInRands, new Dictionary<string, Product> { {"SampleProductName", sample} }); }
public void BusinessListBaseFactory_Fetch_WithCriteria_ReturnsObject() { _criteria = MockRepository.GenerateStub<NHibernate.ICriteria>(); ProductList list = new ProductList(); list.Add(new Product() { Name = "Test" }); list.Add(new Product() { Name = "Test1" }); list.Add(new Product() { Name = "Test2" }); NHibernate.Criterion.SimpleExpression expression = Restrictions.Eq("Name", "Test"); _criteria.Expect(c => c.Add(expression)).Return(_criteria); _repository.Expect(r => r.CreateCriteria()).Return(_criteria); _criteria.Expect(c => c.List<Product>()).Return(list); ProductList products = _factory.Fetch(new SingleCriteria<ProductList, string>("Test")); _repository.AssertWasCalled(r => r.CreateCriteria()); _criteria.AssertWasCalled(c => c.List<Product>()); Assert.AreEqual(3, products.Count); }
static void Main(string[] args) { var prods = new ProductList(); // 设置颜色 var oldBkColor = Console.BackgroundColor; var oldFrColor = Console.ForegroundColor; Console.BackgroundColor = ConsoleColor.Green; Console.ForegroundColor = ConsoleColor.Black; Console.Clear(); // 输出 List<string> texts = new List<string> { "*************************************************************", "* 本项目遵循 GNU-GPL v3 开源协议 *", "* 任何人可以从以下地址获取本程序源代码: *", "* https://github.com/ArphonePei/PDFConverter *", "*************************************************************", "", "", "*************************************************************", "请选择要安装PdfConverter的CAD版本:" }; int nLenth = 50; foreach (var prod in prods.ValidProducts) { texts.Add(prod.SelString(nLenth)); } texts.Add(Helper.FormatLine("退出", "Esc", nLenth)); texts.Add(Helper.FormatLine("安装所有版本", "回车", nLenth)); texts.AddRange(new string[] { "", Helper.FormatLine("访问中望CAD官方网站", '8', nLenth), Helper.FormatLine("访问本项目", '9', nLenth), "", "*************************************************************", "", "", }); foreach (var s in texts) { Console.WriteLine(Helper.FillLine(s)); } while (true) { Console.Write(("请输入要安装的版本:")); var keyInfo = Console.ReadKey(); if (keyInfo.Key == ConsoleKey.Escape) // esc { break; } else if (keyInfo.Key == ConsoleKey.Enter || keyInfo.Key == ConsoleKey.Spacebar) // Enter { foreach (var prod in prods.ValidProducts) { prod.DoInstall(); } Helper.ExitAnyKey(); break; } else if (keyInfo.Modifiers != 0) { continue; } switch (keyInfo.KeyChar) { case '8': Helper.OpenUrl("http://www.zwcad.com"); break; case '9': Helper.OpenUrl("https://github.com/ArphonePei/PDFConverter"); break; default: var sels = prods.ValidProducts.Where(prod => prod.Key == keyInfo.KeyChar); if (sels.Any()) { foreach (var prod in sels) { prod.DoInstall(); } } else { Console.WriteLine(); Console.WriteLine(Helper.FillLine("无效输入")); } break; } } Console.BackgroundColor = oldBkColor; Console.ForegroundColor = oldFrColor; }
/// <summary> /// Retrieves products of resturant using API responses /// </summary> /// <param name="restaurant"></param> /// <returns>List of products of resturant</returns> public ProductList GetRestaurantProducts(Restaurant restaurant) { string response = GetApiResponse("/restaurants/" + restaurant.Id + "/menus"); MenuList menus = JsonConvert.DeserializeObject<MenuList>(response); ProductList productsResult = new ProductList(); foreach (var menu in menus.Menus) { try { response = GetApiResponse("/menus/" + menu.Id + "/productcategories"); var categories = JsonConvert.DeserializeObject<CategoryList>(response); foreach (var category in categories.Categories) { var products = GetProductsByCategory(menu.Id, category.Id); productsResult.Products.AddRange(products.Products); } } catch { // handle NotFound pages for menus } } restaurant.ListOfProductsToSell = productsResult.Products; // finally set the list of products return productsResult; }