private List <SSD> setAllSSD() { List <SSD> ssdList = new List <SSD>(6); DataTable dtbl = initializeDataTable("SELECT * FROM SSD"); foreach (DataRow row in dtbl.Rows) { SSD s = new SSD { ID = Convert.ToInt32(row[0]), Producator = Convert.ToString(row[1]), Model = Convert.ToString(row[2]), TipSSD = Convert.ToString(row[3]), FormFactor = Convert.ToString(row[4]), Interfata = Convert.ToString(row[5]), SuportNVMe = Convert.ToBoolean(row[6]), Capacitate = Convert.ToInt32(row[7]), CitireMax = Convert.ToInt32(row[8]), ScriereMax = Convert.ToInt32(row[9]), TotalBytesWritten = Convert.ToInt32(row[10]), CriptareDate = Convert.ToBoolean(row[11]), RecomandatGaming = Convert.ToBoolean(row[12]), Pret = Convert.ToDouble(row[13]), }; ssdList.Add(s); } return(ssdList); }
public async Task <IActionResult> Edit(int id, [Bind("Naziv,Proizvodjac,Cijena,Kapacitet,Brzina,Velicina,Id")] SSD sSD) { if (id != sSD.Id) { return(NotFound()); } if (ModelState.IsValid) { try { _context.Update(sSD); await _context.SaveChangesAsync(); } catch (DbUpdateConcurrencyException) { if (!SSDExists(sSD.Id)) { return(NotFound()); } else { throw; } } return(RedirectToAction(nameof(Index))); } return(View(sSD)); }
public ActionResult CreateSSD([Bind(Include = "ProductId,TypeID,Manufacturer,Name,Price,Speed,Capacity,Description")] SSDViewModel product, HttpPostedFileBase uploadImage) { if (product.Price < 1) { ModelState.AddModelError(string.Empty, "Цена не может быть негативной"); } if (ModelState.IsValid) { byte[] imageData = null; var pr = new Product { Manufacturer = product.Manufacturer, Name = product.Name, Price = product.Price, TypeID = ProductType.SSD, Description = product.Description }; if (uploadImage != null) { using (var binaryReader = new BinaryReader(uploadImage.InputStream)) { imageData = binaryReader.ReadBytes(uploadImage.ContentLength); pr.Image = imageData; } } db.Product.Add(pr); db.SaveChanges(); var ssd = new SSD { ProductId = pr.ProductId, Speed = product.Speed, Capacity = product.Capacity }; db.SSD.Add(ssd); db.SaveChanges(); return(RedirectToAction("Index")); } return(View(product)); }
void Start() { string path = Path.Combine(Application.streamingAssetsPath, fileName); ssd = new SSD(path); // Init camera string cameraName = WebCamUtil.FindName(); webcamTexture = new WebCamTexture(cameraName, 1280, 720, 30); cameraView.texture = webcamTexture; webcamTexture.Play(); Debug.Log($"Starting camera: {cameraName}"); // Init frames frames = new Text[10]; var parent = cameraView.transform; for (int i = 0; i < frames.Length; i++) { frames[i] = Instantiate(framePrefab, Vector3.zero, Quaternion.identity, parent); } // Labels labels = labelMap.text.Split('\n'); }
static Laptop CreateLaptop() { Battery battery = Config.GetBatteries().ElementAt(SelectComponent("Select Battery:", Config.GetBatteries())); CPU cpu = Config.GetCPUs().ElementAt(SelectComponent("Select CPU:", Config.GetCPUs())); RAM ram = Config.GetRAMs().ElementAt(SelectComponent("Select RAM:", Config.GetRAMs())); SSD ssd = Config.GetSSDs().ElementAt(SelectComponent("Select SSD:", Config.GetSSDs())); DOS.OperatingSystem os = Config.GetOperatingSystems().ElementAt(SelectComponent("Select OS:", Config.GetOperatingSystems())); bool electricity = SelectFlag("Will new laptop have an electricity connection?[y / n]: "); bool network = SelectFlag("Will new laptop have an network connection?[y / n]: "); Console.Write("Name of laptop: "); Laptop laptop = Laptop.Builder .Battery(battery) .Title(Console.ReadLine()) .CPU(cpu) .RAM(ram) .ExternalStorage(ssd) .OperatingSystem(os) .HasElectricityConnection(electricity) .HasNetworkConnection(network) .Build() as Laptop; foreach (DOS.Program program in Config.GetPrograms()) { laptop.OperatingSystem.Install(program); } return(laptop); }
public async Task <ActionResult <SSD> > PostSSD(SSD sSD) { _context.SSDs.Add(sSD); await _context.SaveChangesAsync(); return(CreatedAtAction("GetSSD", new { id = sSD.Id }, sSD)); }
public async Task <IActionResult> PutSSD(int id, SSD sSD) { if (id != sSD.Id) { return(BadRequest()); } _context.Entry(sSD).State = EntityState.Modified; try { await _context.SaveChangesAsync(); } catch (DbUpdateConcurrencyException) { if (!SSDExists(id)) { return(NotFound()); } else { throw; } } return(NoContent()); }
public OperationDetails CreateSSD(SSD ssd) { Database.SSDs.Create(ssd); Database.Save(); return(new OperationDetails(true, "Ok", "")); }
public ActionResult DeleteConfirmed(int id) { SSD sSD = db.SSDs.Find(id); db.SSDs.Remove(sSD); db.SaveChanges(); return(RedirectToAction("Index")); }
public ActionResult Edit([Bind(Include = "Id,Nome,Descricao,Marca,PrecoMedio,ConsumoWatts,Link")] SSD sSD) { if (ModelState.IsValid) { db.Entry(sSD).State = EntityState.Modified; db.SaveChanges(); return(RedirectToAction("Index")); } return(View(sSD)); }
public OperationDetails UpdateSSD(SSD ssd) { Database.SSDs.Update(ssd); Database.Save(); ssd = GetSSD(ssd.Id); _computerAssemblyService.OnSSDChange(ssd); Database.Save(); return(new OperationDetails(true, "Ok", "")); }
public async Task <IActionResult> Create([Bind("Naziv,Proizvodjac,Cijena,Kapacitet,Brzina,Velicina")] SSD sSD) { if (ModelState.IsValid) { _context.Add(sSD); await _context.SaveChangesAsync(); return(RedirectToAction(nameof(Index))); } return(View(sSD)); }
public async Task <IEnumerable <SSD> > PostSSD([FromBody] SSD value) { if (User.Identity.IsAuthenticated) { return(await _componentService.AddSSD(new AddSsdRequest(value))); } else { throw new UnauthorizedAccessException("Only admin can make changes. Have a nice day and f**k off ;)"); } }
public ActionResult Create([Bind(Include = "Id,Nome,Descricao,Marca,PrecoMedio,ConsumoWatts,Link")] SSD sSD) { if (ModelState.IsValid) { db.SSDs.Add(sSD); db.SaveChanges(); return(RedirectToAction("Index")); } return(View(sSD)); }
static void CallFacade() { CPU cpu = new CPU("Core i5 CPU"); MotherBoard motherBoard = new MotherBoard("ASUS ROG"); SSD ssd = new SSD("Kingston SSD"); Facade facade = new Facade(cpu, ssd, motherBoard); facade.StartPC(); facade.ShutDownPC(); }
public async Task <IEnumerable <SSD> > PutSSD(int id, [FromBody] SSD value) { if (User.Identity.IsAuthenticated) { value.ID = id; return(await _componentService.ReplaceSSD(new UpdateSSDRequest(value))); } else { throw new UnauthorizedAccessException("Only admin can make changes. Have a nice day and f**k off ;)"); } }
// GET: SSD/Delete/5 public ActionResult Delete(int?id) { if (id == null) { return(new HttpStatusCodeResult(HttpStatusCode.BadRequest)); } SSD sSD = db.SSDs.Find(id); if (sSD == null) { return(HttpNotFound()); } return(View(sSD)); }
protected void Page_Load(object sender, EventArgs e) { try { user = Session["user"].ToString(); userType = Session["userType"].ToString(); } catch { Response.Write("<script>window.top.location = '../';</script>"); } string where = string.Empty; if (userType == "Admin" || userType == "SC" || userType == "PMMerch") { where = "WHERE [Internal] = 1"; } else { where = "WHERE [" + userType + "] = 1"; } weSQL.SelectCommand = "SELECT 'SELECT' AS [WeekEnding], 'SELECT' AS [StartDate] UNION ALL SELECT DISTINCT CONVERT(NVARCHAR, CONVERT(DATE, [Week Ending]), 101) AS [WeekEnding], CONVERT(NVARCHAR, DATEADD(DAY, -13, CONVERT(DATE, [Week Ending]))) AS [StartDate] FROM [PAYOUTsummary] JOIN [PAYOUTwe] ON CONVERT(DATE, [PAYOUTwe].[WeekEnding]) = CONVERT(DATE, [PAYOUTsummary].[Week Ending]) " + where + " ORDER BY [WeekEnding] DESC"; if (!IsPostBack) { SSD.DataBind(); SSD.SelectedIndex = 0; hidSpan.Visible = false; } string WE = string.Empty; if (weDate.Text != "") { WE = " AND [StartDate] >= '" + weDate.Text + "'"; } else { WE = ""; } SqlDataSource1.SelectCommand = "SELECT * FROM [PAYOUTsubsidy] WHERE [Owner] LIKE '%" + ownerTXT.Text + "%' AND [StoreName] LIKE '" + storeDDLs.SelectedValue + "%' AND [StoreNumber] LIKE '%" + StoreNumberTXT.Text + "%' AND [Type] LIKE '%" + typeDDLs.SelectedValue + "%'" + WE + " ORDER BY [StartDate] DESC, [Owner], [StoreNumber]"; storeSQL.SelectCommand = "SELECT StoreName FROM PAYOUTschedule WHERE StoreName != '' OR StoreName IS NOT NULL GROUP BY StoreName ORDER BY StoreName"; programSQL.SelectCommand = "SELECT [Program] FROM [PAYOUTschedule] GROUP BY [Program] ORDER BY [Program]"; }
void Start() { ssd = new SSD(fileName); // Init frames frames = new Text[10]; var parent = cameraView.transform; for (int i = 0; i < frames.Length; i++) { frames[i] = Instantiate(framePrefab, Vector3.zero, Quaternion.identity, parent); frames[i].transform.localPosition = Vector3.zero; } // Labels labels = labelMap.text.Split('\n'); GetComponent <WebCamInput>().OnTextureUpdate.AddListener(Invoke); }
public IActionResult Create(SSDViewModel model) { if (ModelState.IsValid) { var helper = new ImageHelper(_webHostEnvironment); var image = helper.GetUploadedFile(model.Image, "SSD"); var ssd = new SSD() { Name = model.Name, OuterMemoryInterfaceId = model.OuterMemoryInterfaceId, MemorySize = model.MemorySize, Description = model.Description, OuterMemoryFormFactorId = model.OuterMemoryFormFactorId, ReadSpeed = model.ReadSpeed, WriteSpeed = model.WriteSpeed, ManufacturerId = model.ManufacturerId, Price = model.Price, Image = image }; var result = _ssdService.CreateSSD(ssd); model.Id = ssd.Id; model.Image = null; if (result.Succedeed) { return(View("../Catalog/Index", new { startView = "SSD" })); } return(NotFound(result)); } var outerMemoryInterfaces = _outerMemoryInterfaceService.GetOuterMemoryInterfaces(); ViewBag.OuterMemoryInterfaces = new SelectList(outerMemoryInterfaces, "Id", "Name"); var outerMemoryFormFactors = _outerMemoryFormFactorService.GetOuterMemoryFormFactors(); ViewBag.OuterMemoryFormFactors = new SelectList(outerMemoryFormFactors, "Id", "Name"); var manufacturers = _manufacturerService.GetManufacturers(); ViewBag.Manufacturers = new SelectList(manufacturers, "Id", "Name"); return(View(model)); }
/// <summary> /// /// </summary> /// <param name="element">Element to be added</param> public AddSsdRequest(SSD element) { _element = element; _parameters = new List <SqlParameter>(); if (Validate(_element.Title, "element.Title")) { _parameters.Add(new SqlParameter("@title", _element.Title)); } if (Validate(_element.Capacity, "element.Capacity")) { _parameters.Add(new SqlParameter("@volume", _element.Capacity)); } if (Validate(_element.Series, "element.Series")) { _parameters.Add(new SqlParameter("@series", _element.Series)); } if (Validate(_element.Company, "element.Company")) { _parameters.Add(new SqlParameter("@company", _element.Company)); } if (Validate(_element.Formfactor, "element.Formfactor")) { _parameters.Add(new SqlParameter("@formfactor", _element.Formfactor)); } if (Validate(_element.CellType, "element.CellType")) { _parameters.Add(new SqlParameter("@cellType", _element.CellType)); } for (int i = 0; i < _element.Interface.Count; i++) { Expression += $"INSERT INTO SSD_INTERFACE VALUES (SELECT TOP 1 ID FROM SSD WHERE TITLE = @title, @interface{i});"; _parameters.Add(new SqlParameter($"@interface{i}", _element.Interface[i])); } }
public ActionResult SSDEdit([Bind(Include = "ProductId,TypeID,Manufacturer,Name,Price,Speed,Capacity,Description,Image")] SSDViewModel product, HttpPostedFileBase uploadImage) { if (product.Price < 1) { ModelState.AddModelError(string.Empty, "Цена не может быть негативной"); } if (ModelState.IsValid) { byte[] imageData = null; if (uploadImage != null) { using (var binaryReader = new BinaryReader(uploadImage.InputStream)) { imageData = binaryReader.ReadBytes(uploadImage.ContentLength); product.Image = imageData; } } Product newP = new Product { ProductId = product.ProductId, Manufacturer = product.Manufacturer, Name = product.Name, Price = product.Price, TypeID = product.TypeID, Image = product.Image, Description = product.Description }; SSD newS = new SSD { ProductId = product.ProductId, Capacity = product.Capacity, Speed = product.Speed }; db.Entry(newP).State = EntityState.Modified; db.SaveChanges(); db.Entry(newS).State = EntityState.Modified; db.SaveChanges(); return(RedirectToAction("Index")); } return(View(product)); }
static Laptop CreateLaptop() { Battery battery = Config.GetBatteries().ElementAt(SelectComponent("Select Battery:", Config.GetBatteries())); CPU cpu = Config.GetCPUs().ElementAt(SelectComponent("Select CPU:", Config.GetCPUs())); RAM ram = Config.GetRAMs().ElementAt(SelectComponent("Select RAM:", Config.GetRAMs())); SSD ssd = Config.GetSSDs().ElementAt(SelectComponent("Select SSD:", Config.GetSSDs())); DOS.OperatingSystem os = Config.GetOperatingSystems().ElementAt(SelectComponent("Select OS:", Config.GetOperatingSystems())); bool electricity = SelectFlag("Will new laptop have an electricity connection?[y / n]: "); bool network = SelectFlag("Will new laptop have an network connection?[y / n]: "); Console.Write("Name of laptop: "); Laptop laptop = new Laptop(Console.ReadLine(), cpu, battery, ram, ssd, os, electricity, network); foreach (DOS.Program program in Config.GetPrograms()) { laptop.OperatingSystem.Install(program); } return(laptop); }
public void SSD_Add(List <string> list, int j, List <string> NamesSSD1, List <string> PricesSSD1) { int Price = 0; string Name = NamesSSD1[0]; bool fl = true; if (list.Count == 0) { fl = false; } foreach (var s in CSSD.listSSD) { if (s.Name == Name) { fl = false; } } if (fl) { string Volume = null; bool M_2 = true; if (PricesSSD1.Count != 0) { var prices1 = PricesSSD1[0].Split(); Price = Convert.ToInt32(prices1[1]) * 1000 + Convert.ToInt32(prices1[2]); foreach (string i in list) { if (i.Contains("ГБ")) { Volume = i; } } SSD ssd = new SSD(Price, Name, Volume, M_2); CSSD.Add(ssd); } } }
static void Main(string[] args) { while (true) { Console.WriteLine("1 - Вывести список компонентов"); Console.WriteLine("2 - Купить готовый набор"); Console.WriteLine("---Собрать свой ПК---"); Console.WriteLine("3 - Собрать свою комплектацию"); Console.WriteLine("4 - Выход"); int chouse = IntParser(1, 4); switch (chouse) { case 1: ShowComponentList(); Console.WriteLine("\nНажмите на любую клавишу..."); Console.Read(); Console.Read(); Console.Clear(); break; case 2: Console.WriteLine(); Console.WriteLine("\t1 - Купить базовую комплектацию"); Console.WriteLine("\t2 - Купить полную комплектацию"); Console.WriteLine("\t3 - Назад"); chouse = IntParser(1, 3); if (chouse == 1) { Director director = new Director(); ComputerComplectation computerComplectation = new ComputerComplectation(); director.Builder = computerComplectation; director.Basic(); Console.WriteLine("\tВ комплектацию входит:"); Console.WriteLine(computerComplectation.GetComplectation().ListParts()); Computer computer = new Processor(); Body body = new Body(computer); MainCard mainCard = new MainCard(body); AudioCard audioCard = new AudioCard(mainCard); NetworkCard networkCard = new NetworkCard(audioCard); HDD hdd = new HDD(networkCard); Console.WriteLine("\tОбщяя стоимость: " + hdd.GetCost()); Console.WriteLine("\n\t1 - Продолжить покупку"); Console.WriteLine("\t2 - В главное меню"); chouse = IntParser(1, 2); if (chouse == 1) { Console.WriteLine("\tТовар успешно куплен!"); Console.WriteLine("\nНажмите на любую клавишу..."); Console.Read(); return; } Console.Clear(); } else if (chouse == 2) { Director director = new Director(); ComputerComplectation computerComplectation = new ComputerComplectation(); director.Builder = computerComplectation; director.Full(); Console.WriteLine("\tВ комплектацию входит:"); Console.WriteLine(computerComplectation.GetComplectation().ListParts()); Computer computer = new Processor(); Body body = new Body(computer); MainCard mainCard = new MainCard(body); AudioCard audioCard = new AudioCard(mainCard); NetworkCard networkCard = new NetworkCard(audioCard); HDD hdd = new HDD(networkCard); VideoCard videoCard = new VideoCard(hdd); SSD ssd = new SSD(videoCard); Mouse mouse = new Mouse(ssd); Keyboard keyboard = new Keyboard(mouse); Console.WriteLine("\tОбщяя стоимость: " + keyboard.GetCost()); Console.WriteLine("\n\t1 - Продолжить покупку"); Console.WriteLine("\t2 - В главное меню"); chouse = IntParser(1, 2); if (chouse == 1) { Console.WriteLine("\tТовар успешно куплен!"); Console.WriteLine("\nНажмите на любую клавишу..."); Console.Read(); return; } Console.Clear(); } break; case 3: CollectComplectation(); break; case 4: return; } } }
//Adds the secelcted ssd the the reciept private void btnSSD_Click(object sender, EventArgs e) { //Sets the variables that will be used in the method int selected = 0; string name = ""; double price = 0; int quantity = Convert.ToInt32(numUpDownSSD.Value); //Clears the ssd object ssd.Clear(); //Satement that checks the value of the numeric up down is less than or equal to 4 if (numUpDownSSD.Value <= 4) { //Each item in the chekbox is checked to see if it is checked, if it is then it will be dispayed in the case recipt box for (int i = 0; i < cbxSSD.Items.Count; i++) { //Statement that checks is the checked item is i if (cbxSSD.GetItemChecked(i)) { selected = i; } } //Checks the index of the seleced SSD if (selected == 0) { name = "SSD A"; price = 10.00; } else if (selected == 1) { name = "SSD B"; price = 25.00; } else if (selected == 2) { name = "SSD C"; price = 15.00; } else if (selected == 3) { name = "SSD D"; price = 18.00; } //Calculates the price x quality and stores it in the ssdtotal variable double ssdtotal = price * quantity; //displays the name, total and quantity in the ssd reciept list box lstSSDReciept.Items.Add(name + " | £" + ssdtotal.ToString() + " | " + quantity); //Stores ssd SSD ss = new SSD { name = name, price = ssdtotal, quantity = quantity }; //Adds the value of ss to the ssd list ssd.Add(ss); } //displays if the previous statement didn't execute else { //Displays message box MessageBox.Show("A max of 4 SSD can be selected!"); } }
public SSDShortModel(SSD ssd) { SSDId = ssd.Id; SSDName = ssd.Name; SSDImage = "/Images/SSD/" + ssd.Image; }
private void timer1_Tick(object sender, EventArgs e) { foreach (var hardware in thisComputer.Hardware) { hardware.Update(); /*---------------------------------CPU---------------------------------*/ if (hardware.HardwareType == HardwareType.Cpu) { cpuName = hardware.Name; foreach (var sensor in hardware.Sensors) { if (sensor.SensorType == SensorType.Load && sensor.Name == "CPU Total") { cpuLoad = sensor.Value.Value; } if (sensor.SensorType == SensorType.Temperature && sensor.Name == "CPU Package") { cpuTemp = sensor.Value.GetValueOrDefault(); } } } /*---------------------------------GPU---------------------------------*/ if (hardware.HardwareType == HardwareType.GpuAmd || hardware.HardwareType == HardwareType.GpuNvidia) { gpuName = hardware.Name; foreach (var sensor in hardware.Sensors) { if (sensor.SensorType == SensorType.Load && sensor.Name == "GPU Core") { gpuLoad = sensor.Value.Value; } if (sensor.SensorType == SensorType.Temperature && sensor.Name == "GPU Core") { gpuTemp = sensor.Value.GetValueOrDefault(); } if (sensor.SensorType == SensorType.Fan && sensor.Name == "GPU Fan") { gpuFan = sensor.Value.GetValueOrDefault(); } if (sensor.SensorType == SensorType.Control && sensor.Name == "GPU Fan") { gpuFanLoad = sensor.Value.GetValueOrDefault(); } } } /*---------------------------------RAM---------------------------------*/ if (hardware.HardwareType == HardwareType.Memory) { foreach (var sensor in hardware.Sensors) { if (sensor.SensorType == SensorType.Load && sensor.Name == "Memory") { ramLoad = sensor.Value.Value; } if (sensor.SensorType == SensorType.Data && sensor.Name == "Memory Used") { ramUse = sensor.Value.GetValueOrDefault(); } if (sensor.SensorType == SensorType.Data && sensor.Name == "Memory Available") { float ramAva = sensor.Value.GetValueOrDefault(); totalRam = ramAva + ramUse; } } } /*---------------------------------Connection---------------------------------*/ if (hardware.HardwareType == HardwareType.Network) { foreach (var sensor in hardware.Sensors) { if (sensor.SensorType == SensorType.Throughput && sensor.Name == "Upload Speed") { upload = (sensor.Value.GetValueOrDefault()) * 8 / 1048576; } if (sensor.SensorType == SensorType.Throughput && sensor.Name == "Download Speed") { download = (sensor.Value.GetValueOrDefault()) * 8 / 1048576; } strNw = Math.Round(download, 2).ToString("F2") + "/" + Math.Round(upload, 2).ToString("F2"); if (strNw.Length > 10) { strNw = "Connecting..."; } } } /*---------------------------------Drive---------------------------------*/ if (hardware.Name == "WDC WD10EZEX-00WN4A0") { foreach (var sensor in hardware.Sensors) { hdd = hardware.Name; if (sensor.SensorType == SensorType.Load && sensor.Name == "Total Activity") { hddLoad = sensor.Value.Value; } if (sensor.SensorType == SensorType.Temperature && sensor.Name == "Temperature") { hddTemp = sensor.Value.GetValueOrDefault(); } if (sensor.SensorType == SensorType.Load && sensor.Name == "Used Space") { hddUse = sensor.Value.GetValueOrDefault(); } } } if (hardware.Name == "Samsung SSD 960 EVO 250GB") { foreach (var sensor in hardware.Sensors) { ssd = hardware.Name.Substring(0, 19); if (sensor.SensorType == SensorType.Load && sensor.Name == "Total Activity") { ssdLoad = sensor.Value.Value; } if (sensor.SensorType == SensorType.Temperature && sensor.Name == "Temperature") { ssdTemp = sensor.Value.GetValueOrDefault(); } if (sensor.SensorType == SensorType.Load && sensor.Name == "Used Space") { ssdUse = sensor.Value.GetValueOrDefault(); } } } if (hardware.HardwareType == HardwareType.Heatmaster) { foreach (var sensor in hardware.Sensors) { if (sensor.SensorType == SensorType.Load && sensor.Name == "CPU Total") { cpuLoad = sensor.Value.Value; } if (sensor.SensorType == SensorType.Temperature && sensor.Name == "CPU Package") { cpuTemp = sensor.Value.GetValueOrDefault(); } } } /*---------------------------------Display---------------------------------*/ grCPU.Text = cpuName; txtLoadCPU.Text = Math.Round(cpuLoad).ToString() + " %"; txtTempCPU.Text = Math.Round(cpuTemp).ToString() + " °C"; grGPU.Text = gpuName; txtLoadGPU.Text = Math.Round(gpuLoad).ToString() + " %"; txtTempGPU.Text = Math.Round(gpuTemp).ToString() + " °C"; txtFanGPU.Text = Math.Round(gpuFan).ToString() + " RPM"; txtTotalRam.Text = Math.Round(totalRam).ToString() + " GB"; txtRamUse.Text = Math.Round(ramUse).ToString() + " GB"; txtRamLoad.Text = Math.Round(ramLoad).ToString() + " %"; txtDown.Text = Math.Round(download, 2).ToString("F2") + " MB/s"; txtUp.Text = Math.Round(upload, 2).ToString("F2") + " MB/s"; grHDD.Text = hdd; txtHddLoad.Text = Math.Round(hddLoad).ToString() + " %"; txtHddUse.Text = Math.Round(hddUse).ToString() + " %"; txtHddTemp.Text = Math.Round(hddTemp).ToString() + " °C"; grSSD.Text = ssd; txtSsdLoad.Text = Math.Round(ssdLoad).ToString() + " %"; txtSsdUse.Text = Math.Round(ssdUse).ToString() + " %"; txtSsdTemp.Text = Math.Round(ssdTemp).ToString() + " °C"; /*---------------------------------Send DATA---------------------------------*/ } Processor dataCPU = new Processor { Name = cpuName, Load = Math.Round(cpuLoad, 1), Temp = Math.Round(cpuTemp, 1) }; Graphic dataGPU = new Graphic { Name = gpuName, Load = Math.Round(gpuLoad, 1), Temp = Math.Round(gpuTemp, 1), }; Ram dataRam = new Ram { Use = Math.Round(ramUse).ToString() + "/" + Math.Round(totalRam).ToString() }; Connection dataNet = new Connection { Speed = strNw }; HDD infoHDD = new HDD { Name = hdd, Use = Math.Round(hddUse), Load = Math.Round(hddLoad), Temp = Math.Round(hddTemp) }; SSD infoSSD = new SSD { Name = ssd, Use = Math.Round(ssdUse), Load = Math.Round(ssdLoad), Temp = Math.Round(ssdTemp) }; Infomation info = new Infomation { CPU = dataCPU, GPU = dataGPU, RAM = dataRam, Net = dataNet, hddDrive = infoHDD, ssdDrive = infoSSD }; string obj = JsonConvert.SerializeObject(info); if (lblWIFIStatus.Text == "Connected") { try { NetworkStream stream = client.GetStream(); byte[] data = Encoding.ASCII.GetBytes(obj + "\r\n"); stream.Write(data, 0, data.Length); } catch (Exception) { AppIcon.ShowBalloonTip(5000, "Mất kêt nối", "Kiểm tra lại server", ToolTipIcon.Warning); txtIP.Enabled = true; timer1.Enabled = false; btnConnectWIFI.Text = "Connect"; lblWIFIStatus.Text = "Disconnected"; lblWIFIStatus.ForeColor = Color.Red; client.Close(); client = new TcpClient(); } } if (lblStatusWired.Text == "Connected") { a = dataCPU.Name + "," + dataCPU.Load + "," + dataCPU.Temp + "," + dataGPU.Name + "," + dataGPU.Load + "," + dataGPU.Temp + "," + dataRam.Use + "," + dataNet.Speed + "," + infoHDD.Name + "," + infoHDD.Use + "," + infoHDD.Load + "," + infoHDD.Temp + "," + infoSSD.Name + "," + infoSSD.Use + "," + infoSSD.Load + "," + infoSSD.Temp + "*"; serialPort1.Write(a); } }
public async Task<string> ScrapeFromProductPageAsync(string productUrl) { if (productUrl.Contains("Combo")) { var message = "Invalid Product."; this.logger.LogWarning(message); return message; } var document = await this.Context.OpenAsync(productUrl); var ssdDataTableRows = this.GetAllTablesRows(document); var ssdDataTables = this.GetAllTables(document); var ssd = new SSD { Price = this.GetPrice(document), ImageUrl = this.GetImageUrl(document), Category = this.GetCategoryFromUrl(productUrl), }; this.logger.LogInformation(productUrl); foreach (var tableRow in ssdDataTableRows) { var rowName = tableRow.FirstChild.TextContent.Trim(); var rowValue = tableRow.LastElementChild.InnerHtml.Replace("<br><br>", "{n}").Replace("<br>", "{n}").Trim(); switch (rowName) { case "Model": if (this.ssdRepo.AllAsNoTracking().Any(x => x.Model == rowValue)) { var message = "Already exists."; this.logger.LogWarning(message); return message; } ssd.Model = rowValue; break; case "Brand": ssd.Brand = this.GetOrCreateBrand(this.brandRepo, rowValue); break; case "Series": ssd.Series = this.GetOrCreateSeries(this.seriesRepo, rowValue); break; case "Used For": var usage = this.usageRepo.All().FirstOrDefault(x => x.Name == rowValue); if (usage == null) { usage = new DiskForUsage { Name = rowValue, }; } ssd.Usage = usage; break; case "Form Factor": var formFactor = this.formFactorRepo.All().FirstOrDefault(x => x.Name == rowValue); if (formFactor == null) { formFactor = new FormFactor { Name = rowValue, }; } ssd.FormFactor = formFactor; break; case "Capacity": var capacityMatch = this.MatchOneOrMoreDigits.Match(rowValue); if (!capacityMatch.Success) { continue; } var capacity = short.Parse(capacityMatch.Value); if (rowValue.ToLower().Contains("tb")) { capacity *= 1024; } ssd.CapacityGb = capacity; break; case "Memory Components": var memoryComponent = this.memoryComponentRepo.All().FirstOrDefault(x => x.Name == rowValue); if (memoryComponent == null) { memoryComponent = new MemoryComponent { Name = rowValue, }; } ssd.MemoryComponent = memoryComponent; break; case "Interface": var ssdInterface = this.interfaceRepo.All().FirstOrDefault(x => x.Name == rowValue); if (ssdInterface == null) { ssdInterface = new Interface { Name = rowValue, }; } ssd.Interface = ssdInterface; break; case "Cache": var cacheMatch = this.MatchOneOrMoreDigits.Match(rowValue); if (!cacheMatch.Success) { continue; } var cache = int.Parse(cacheMatch.Value); if (rowValue.ToLower().Contains("mb")) { cache *= 1024; } else if (rowValue.ToLower().Contains("gb")) { cache *= 1024 * 1024; } ssd.CacheKb = cache; break; case "Max Sequential Read": var seqReadMatch = this.MatchOneOrMoreDigits.Match(rowValue); if (!seqReadMatch.Success) { continue; } ssd.MaxSequentialReadMBps = short.Parse(seqReadMatch.Value); break; case "Max Sequential Write": var seqWriteMatch = this.MatchOneOrMoreDigits.Match(rowValue); if (!seqWriteMatch.Success) { continue; } ssd.MaxSequentialWriteMBps = short.Parse(seqWriteMatch.Value); break; case "4KB Random Read": ssd.FourKBRandomRead = rowValue; break; case "4KB Random Write": ssd.FourKBRandomWrite = rowValue; break; case "MTBF": var mtbfMatch = this.MatchOneOrMoreDigits.Match(rowValue.Replace(",", string.Empty)); if (!mtbfMatch.Success) { continue; } ssd.MeanTimeBetweenFailures = int.Parse(mtbfMatch.Value); break; case "Features": ssd.Features = rowValue; break; case "Height": ssd.Height = this.MatchAndParseFloat(rowValue); break; case "Width": ssd.Width = this.MatchAndParseFloat(rowValue); break; case "Depth": ssd.Length = this.MatchAndParseFloat(rowValue); break; case "Date First Available": ssd.FirstAvailable = DateTime.Parse(rowValue); break; } } if (ssd.Model == null) { var message = "Invalid Model."; this.logger.LogWarning(message); return message; } await this.ssdRepo.AddAsync(ssd); await this.ssdRepo.SaveChangesAsync(); var successMessage = $"Successfully added {ssd.Model}."; this.logger.LogInformation(successMessage); return successMessage; }
// Load Items from CSV file or text using TextFieldParser private static void Load(string source, List <Part> list, StringReader sr = null) { dynamic tfpSource; if (sr != null) { tfpSource = sr; } else { tfpSource = source; } using (TextFieldParser tfp = new TextFieldParser(tfpSource)) { tfp.TextFieldType = FieldType.Delimited; tfp.SetDelimiters(","); list.Clear(); while (!tfp.EndOfData) { var currentItem = tfp.ReadFields(); Part currentItemObject = null; // Transform current CSV line to Part switch (currentItem[0]) { case "CPU": currentItemObject = new CPU( currentItem[1], currentItem[2], currentItem[3], decimal.Parse(currentItem[4]), currentItem[5], currentItem[6], double.Parse(currentItem[7]), currentItem[8], int.Parse(currentItem[9]), currentItem[10], currentItem[11], int.Parse(currentItem[12])); list.Add(currentItemObject); break; case "MotherBoard": currentItemObject = new MotherBoard( currentItem[1], currentItem[2], currentItem[3], decimal.Parse(currentItem[4]), currentItem[5], currentItem[6], currentItem[7], currentItem[8], currentItem[9], currentItem[10]); list.Add(currentItemObject); break; case "RAM": currentItemObject = new RAM( currentItem[1], currentItem[2], currentItem[3], decimal.Parse(currentItem[4]), currentItem[5], currentItem[6], int.Parse(currentItem[7]), currentItem[8], int.Parse(currentItem[9])); list.Add(currentItemObject); break; case "VideoCard": currentItemObject = new VideoCard( currentItem[1], currentItem[2], currentItem[3], decimal.Parse(currentItem[4]), currentItem[5], currentItem[6], currentItem[7], currentItem[8], currentItem[9], int.Parse(currentItem[10])); list.Add(currentItemObject); break; case "PSU": currentItemObject = new PSU( currentItem[1], currentItem[2], currentItem[3], decimal.Parse(currentItem[4]), currentItem[5], currentItem[6], int.Parse(currentItem[7]), Dimensions.Parse(currentItem[8]), currentItem[9], int.Parse(currentItem[10]), int.Parse(currentItem[11])); list.Add(currentItemObject); break; case "SSD": currentItemObject = new SSD( currentItem[1], currentItem[2], currentItem[3], decimal.Parse(currentItem[4]), currentItem[5], currentItem[6], int.Parse(currentItem[7]), currentItem[8], currentItem[9], double.Parse(currentItem[10]), bool.Parse(currentItem[11]), int.Parse(currentItem[12]), int.Parse(currentItem[13])); list.Add(currentItemObject); break; case "HDD": currentItemObject = new HDD( currentItem[1], currentItem[2], currentItem[3], decimal.Parse(currentItem[4]), currentItem[5], currentItem[6], int.Parse(currentItem[7]), currentItem[8], int.Parse(currentItem[9]), double.Parse(currentItem[10]), int.Parse(currentItem[11]), int.Parse(currentItem[12]), bool.Parse(currentItem[13])); list.Add(currentItemObject); break; case "Case": currentItemObject = new Case( currentItem[1], currentItem[2], currentItem[3], decimal.Parse(currentItem[4]), currentItem[5], currentItem[6], currentItem[7], Dimensions.Parse(currentItem[8]), int.Parse(currentItem[9]), int.Parse(currentItem[10]), int.Parse(currentItem[11]), bool.Parse(currentItem[12])); list.Add(currentItemObject); break; case "Monitor": currentItemObject = new Monitor( currentItem[1], currentItem[2], currentItem[3], decimal.Parse(currentItem[4]), currentItem[5], currentItem[6], double.Parse(currentItem[7]), currentItem[8], currentItem[9], currentItem[10], bool.Parse(currentItem[11]), (IO)int.Parse(currentItem[12]), Dimensions.Parse(currentItem[13]), double.Parse(currentItem[14]), (Color)int.Parse(currentItem[15])); list.Add(currentItemObject); break; case "Mouse": currentItemObject = new Mouse( currentItem[1], currentItem[2], currentItem[3], decimal.Parse(currentItem[4]), currentItem[5], currentItem[6], currentItem[7], int.Parse(currentItem[8]), int.Parse(currentItem[9]), double.Parse(currentItem[10]), currentItem[11], Dimensions.Parse(currentItem[12]), bool.Parse(currentItem[13]), (IO)int.Parse(currentItem[14]), (Color)int.Parse(currentItem[15])); list.Add(currentItemObject); break; case "Keyboard": currentItemObject = new Keyboard( currentItem[1], currentItem[2], currentItem[3], decimal.Parse(currentItem[4]), currentItem[5], currentItem[6], currentItem[7], currentItem[8], currentItem[9], currentItem[10], int.Parse(currentItem[11]), Dimensions.Parse(currentItem[12]), bool.Parse(currentItem[13]), double.Parse(currentItem[14]), (IO)int.Parse(currentItem[15]), (Color)int.Parse(currentItem[16])); list.Add(currentItemObject); break; case "Speakers": currentItemObject = new Speakers( currentItem[1], currentItem[2], currentItem[3], decimal.Parse(currentItem[4]), currentItem[5], currentItem[6], double.Parse(currentItem[7]), double.Parse(currentItem[8]), currentItem[9], bool.Parse(currentItem[10]), (IO)int.Parse(currentItem[11]), Dimensions.Parse(currentItem[12]), double.Parse(currentItem[13]), (Color)int.Parse(currentItem[14])); list.Add(currentItemObject); break; default: throw new Exception($"Unknown part: \"{currentItem[0]}\""); } } } }