Alright, Hello everybody.
First here is my code:
My problem is written bellow the code.
public partial class Form1 : Form
{
Decimal startCoins;
string winlossstr;
int TotalRolls;
int TotalWins;
int TotalLost;
int winloss = 0;
int CountError;
private void timerGetData_Tick(object sender, EventArgs e)
{
if (this.webBrowser1.ReadyState == WebBrowserReadyState.Complete)
{
string u = webBrowser1.DocumentText;
u = u.Substring(u.IndexOf("<span id=\"goCoins\" class=\"coins\""));
u = u.Substring(u.IndexOf(">") + 1);
u = u.Substring(0, u.IndexOf("</span>"));
textBoxCoins.Text = u;
//newCount = Convert.ToDecimal(u);
label5.Text = u;
decimal Pstart = Convert.ToDecimal(startCoins);
decimal Pnew = Convert.ToDecimal(u.Replace('.', ','));
decimal p = Convert.ToDecimal(Pnew) - Convert.ToDecimal(Pstart);
labelProfit.Text = p.ToString();
labelToltalRols.Text = TotalRolls.ToString();
//if (newCount >= oldCount)
if (Convert.ToDecimal(label5.Text) >= Convert.ToDecimal(label11.Text))
{
textBoxWinLoose.Text = "Won!";
textBoxWinLoose.BackColor = System.Drawing.Color.Green;
textBoxWinLossCounter.BackColor = System.Drawing.Color.Green;
textBoxBetAmount.Text = textBoxAmount.Text;
winlossstr = "won";
TotalWins++;
labelRollsWon.Text = TotalWins.ToString();
var cl = labelCoinsWon.Text;
var clbet = textBoxBetAmount.Text;
decimal clbet1 = Convert.ToDecimal(clbet.Replace('.', ','));
if (cl == "0")
{
labelCoinsWon.Text = clbet;
}
else
{
decimal clc = Convert.ToDecimal(cl.Replace('.', ',')) + clbet1;
labelCoinsWon.Text = clc.ToString();
}
//DEBUGGER
richTextBoxDebugger.AppendText(Environment.NewLine + DateTime.Now.ToString("HH:mm:ss") + " Roll Number #" + labelToltalRols.Text + " Bet Amount: " + textBoxBetAmount.Text + " Won!");
richTextBoxHistorik.AppendText(Environment.NewLine + DateTime.Now.ToString("HH:mm:ss") + " Roll Number #" + labelToltalRols.Text + " Bet Amount: " + textBoxBetAmount.Text + " Won!");
}
else
{
textBoxWinLoose.Text = "Loss!";
textBoxWinLoose.BackColor = System.Drawing.Color.Red;
textBoxWinLossCounter.BackColor = System.Drawing.Color.Red;
winlossstr = "loss";
TotalLost++;
labelRollsLost.Text = TotalLost.ToString();
var cl = labelCoinsLost.Text;
var clbet = textBoxBetAmount.Text;
decimal clbet1 = Convert.ToDecimal(clbet.Replace('.', ','));
if (cl == "0")
{
labelCoinsLost.Text = clbet;
}
else
{
decimal clc = Convert.ToDecimal(cl.Replace('.', ',')) + clbet1;
labelCoinsLost.Text = clc.ToString();
}
//DEBUGGER
richTextBoxDebugger.AppendText(Environment.NewLine + DateTime.Now.ToString("HH:mm:ss") + " Roll Number #" + labelToltalRols.Text + " Bet Amount: " + textBoxBetAmount.Text + " Tabt");
richTextBoxHistorik.AppendText(Environment.NewLine + DateTime.Now.ToString("HH:mm:ss") + " Roll Number #" + labelToltalRols.Text + " Bet Amount: " + textBoxBetAmount.Text + " Tabt");
}
// TIMER
var r = new Random();
var r2 = r.Next(3000, 5000);
timerLoop.Interval = r2;
decimal t = Convert.ToDecimal(r2) / 1000;
////DEBUGGER
richTextBoxDebugger.AppendText(Environment.NewLine + DateTime.Now.ToString("HH:mm:ss") + " Loop starts in " + t + " secs.");
timerLoop.Start();
//oldCount = newCount;
label11.Text = label5.Text;
timerGetData.Stop();
}
else
{
CountError++;
label18.Text = CountError.ToString();
////DEBUGGER
richTextBoxDebugger.AppendText(Environment.NewLine + DateTime.Now.ToString("HH:mm:ss") + " Website not found. #" + CountError.ToString());
webBrowser1.Navigate(url);
////DEBUGGER
richTextBoxDebugger.AppendText(Environment.NewLine + DateTime.Now.ToString("HH:mm:ss") + " Reloader data in 10 secs.");
timerGetData.Interval = 10000;
timerGetData.Start();
}
}
private void timerLoop_Tick(object sender, EventArgs e)
{
if (winlossstr == "won")
{
HtmlDocument doc = this.webBrowser1.Document;
doc.GetElementById("bet").SetAttribute("Value", textBoxAmount.Text);
richTextBoxDebugger.AppendText(Environment.NewLine + DateTime.Now.ToString("HH:mm:ss") + " Setting start bet!");
}
if (winlossstr == "loss")
{
var h = textBoxBetAmount.Text;
decimal n = Convert.ToDecimal(h.Replace('.', ',')) * 2;
textBoxBetAmount.Text = n.ToString();
var j = n.ToString();
HtmlDocument doc = this.webBrowser1.Document;
doc.GetElementById("bet").SetAttribute("Value", j.Replace(',', '.'));
richTextBoxDebugger.AppendText(Environment.NewLine + DateTime.Now.ToString("HH:mm:ss") + " Setting loss bet to: " + j.Replace(',', '.'));
}
timerClick.Interval = 1000;
timerClick.Start();
timerLoop.Dispose();
}
private void timerClick_Tick(object sender, EventArgs e)
{
TotalRolls++;
HtmlElementCollection elc = this.webBrowser1.Document.GetElementsByTagName("input");
foreach (HtmlElement el in elc)
{
if (el.GetAttribute("id").Equals("roll"))
{
el.InvokeMember("Click");
}
}
timerClick.Dispose();
////DEBUGGER
richTextBoxDebugger.AppendText(Environment.NewLine + DateTime.Now.ToString("HH:mm:ss") + " Rolled");
timerRefreshPage.Interval = 2000;
timerRefreshPage.Start();
}
private void timerRefreshPage_Tick(object sender, EventArgs e)
{
webBrowser1.Refresh(WebBrowserRefreshOption.Completely);
timerRefreshPage.Stop();
////DEBUGGER
richTextBoxDebugger.AppendText(Environment.NewLine + DateTime.Now.ToString("HH:mm:ss") + " Website loades." + Environment.NewLine + DateTime.Now.ToString("HH:mm:ss") + " Getting data in 1 sec");
GC.Collect();
GC.WaitForPendingFinalizers();
timerGetData.Interval = 2000;
timerGetData.Start();
}
Alright, i have an huge problem with my Memory in this program.
In about an hour running this program my Memory will get fully loaded by this program.
I have tryed to dispose all my timers without any help.
So i have come to that its maybe my Webbrowser there is filling up my memory, my webbrowser is refressing in every 5-10 secs.
I have tried google and on this Stackoverflow to dispose the webbrowser, i found a way where i was creating a new webbrowser for every refresh, but i didnt help on my Memory usage.
I have also worked on to clear my webbrowser cache, but i have to be signed in on the website with a user and a password, so that can't help me either.
So now i want to show you my code and hope someone can tell me what i need to do, so it don't fill up my ram.
And, then i have another thing in this code i cant figure it out why its goes wrong.
Alright, as you can see in the code its finds out if my new data from the website is higher or lower then it was before in this:
if (Convert.ToDecimal(label5.Text) >= Convert.ToDecimal(label11.Text))
But I have seen a few times if it gets lower more then 13 times it's just "reset" the counter so the program thinks that it's not lower anymore, and sets my winlossstr string to "won", even if it's still gets an loss result on the website.
Fyi the data this program gets from the website is a number ex. like this: 125.578
I hope you understand my and my question, otherwise please tell me what you need to know.
Best regards
-- Edit --
Alright, now i have found this:
[DllImport("KERNEL32.DLL", EntryPoint = "SetProcessWorkingSetSize", SetLastError = true, CallingConvention = CallingConvention.StdCall)]
internal static extern bool SetProcessWorkingSetSize(IntPtr pProcess, int dwMinimumWorkingSetSize, int dwMaximumWorkingSetSize);
[DllImport("KERNEL32.DLL", EntryPoint = "GetCurrentProcess", SetLastError = true, CallingConvention = CallingConvention.StdCall)]
internal static extern IntPtr GetCurrentProcess();
in my timer:
IntPtr pHandle = GetCurrentProcess();
SetProcessWorkingSetSize(pHandle, -1, -1);
But that's doesn't help me either, my memory keeps going up. and it won't stop.
In your tick methods you always seem to append text to some kind of textbox (richTextBoxDebugger), which might take up more and more memory space as you go on. Try to comment out these calls (or at least limit the maximum amount of text tored in that box), to avoid filling up the memory space.
Related
I have a list made by user input which is bound to a datasource class, I also have a datagridview where the data is supposed to be put into the datagrid.
private void ViewMemo_Load(object sender, EventArgs e)
{
dgvMemo.DataSource = Datasources.memorecorders;
}
this is the AddMemo class
private void btAdd_Click(object sender, EventArgs e)
{
int SerialId;
SerialId = int.Parse(txtSerialId.Text);
decimal price;
price = decimal.Parse(txtPrijs.Text);
MemoRecorder m1 = new MemoRecorder(SerialId);
m1.make = txtMerk.Text;
m1.model = txtModel.Text;
m1.priceExBtw = price;
m1.creationDate = dtProductie.Value;
foreach (MemoCartridgeType mem in Enum.GetValues(typeof(MemoCartridgeType)))
{
if (cbCartridge.SelectedValue.ToString() == mem.ToString())
{
m1.maxCartridgeType = mem;
}
}
Datasources.memorecorders.Add(m1);
MessageBox.Show("uitkomst: Merk: " + m1.make + "model: " + m1.model + " ,prijs Ex btw: "+ m1.priceExBtw + " ,CartridgeType: "+ m1.maxCartridgeType
+ " ,Creatie Datum: " + m1.creationDate);
txtMerk.Text = String.Empty;
txtModel.Text = String.Empty;
txtPrijs.Text = String.Empty;
}
but when I view the datagridview the data is not in there, what did I do wrong?
Datasources.memorecorders.Add(m1);
dgvMemo.DataSource = Datasources.memorecorders;
MessageBox.Show("uitkomst: Merk: " + m1.make + "model: " + m1.model + " ,prijs Ex btw: "+ m1.priceExBtw + " ,CartridgeType: "+ m1.maxCartridgeType
+ " ,Creatie Datum: " + m1.creationDate);
I've always wondered, are there ways to shorten this kind of code?
private void Update01()
{
item01.text = item01n + "\nCost: " + Math.Round(cost01, 2) + "\nYou have: " + n01;
}
private void Update02()
{
item02.text = item02n + "\nCost: " + Math.Round(cost02, 2) + "\nYou have: " + n02;
}
private void Update03()
{
item03.text = item03n + "\nCost: " + Math.Round(cost03, 2) + "\nYou have: " + n03;
}
.
.
.
Thanks for the help.
As 12seconds said, just return a string and pass in 3 variables:
private string GetUpdate(item, cost, n)
{
return item + "\nCost: " + Math.Round(cost, 2) + "\nYou have: " + n;
}
And then simply do:
item01.text = GetUpdate(item01n, cost01, n01);
item02.text = GetUpdate(item02n, cost02, n02);
item03.text = GetUpdate(item03n, cost03, n03);
I'm working on an app that extracts content from a game page (example), displays it to the user in a textbox and if the user wishes to do so, he/she can save it as a .txt file or .xsl (excel spreadsheet format).
But the main problem I'm facing right now is that you have to manually change the code to "extract" data about another in-game unit.
If you open the link you'll see that I'm currently extracting the "Weapons", "Used", "Survived" and "Casualties" from the Defender side (as for now), but only 1 type of unit (more like only 1 row of that table) is being "extracted", I'm looking for a way to search "tr[1]/td[2]/span[1]" through "tr[45]/td[2]/span[1]" (even if the example page only goes until tr[16]), or maybe a way to automate it to search until it finds no data (nothing) then it would stop.
Sorry for any text mistakes, I'm not a native speaker
private void btnStart_Click(object sender, RoutedEventArgs e)
{
HtmlDocument brPage = new HtmlWeb().Load("http://us.desert-operations.com/world2/battleReport.php?code=f8d77b1328c8ce09ec398a78505fc465");
HtmlNodeCollection nodes = brPage.DocumentNode.SelectNodes("/html[1]/body[1]/div[1]/div[1]/div[3]/div[1]/div[1]/div[1]/div[2]/table[2]");
string result = "";
List<brContentSaver> ContentList = new List<brContentSaver>();
foreach (var item in nodes)
{
brContentSaver cL = new brContentSaver();
/* Here comes the junk handler, replaces all junk for nothing, essentially deleting it
I wish I knew a way to do this efficiently */
cL.Weapons = item.SelectSingleNode("tr[16]/td[1]").InnerText
.Replace(" * ", " ")
.Replace("  ; *  ;", " ");
cL.Used = item.SelectSingleNode("tr[16]/td[2]/span[1]").InnerText
.Replace(" * ", " ")
.Replace("  ; *  ;", " ");
cL.Survived = item.SelectSingleNode("tr[16]/td[3]").InnerText
.Replace(" * ", " ")
.Replace("  ; *  ;", " ");
if (cL.Survived == "0")
{
cL.Casualties = cL.Used;
} else
{
/* int Casualties = int.Parse(cL.Casualties);
* int Used = int.Parse(cL.Used);
* int Survived = int.Parse(cL.Survived);
* Casualties = Used - Survived; */
cL.Casualties = item.SelectSingleNode("tr[16]/td[4]").InnerText
.Replace(" * ", " ")
.Replace("  ; *  ;", " ");
}
ContentList.Add(cL);
}
foreach (var item in ContentList)
{
result += item.Weapons + " " + item.Used + " " + item.Survived + " " + item.Casualties + Environment.NewLine;
}
brContent.Text = result;
}
Sorry if this sounds silly, but I'm new to programming, especially in C#.
Edit 1: I noticed that "if (cL.Survived == "0")", I was just testing stuff some stuff way earlier and I forgot to change it, but hey, it works
Edit 2: If you are wondering I'm also using this:
public class brContentSaver
{
public string Weapons
{
get;
set;
}
public string Used
{
get;
set;
}
public string Survived
{
get;
set;
}
public string Casualties
{
get;
set;
}
}
I don't have much time to write this but hope it will help if you still need. I find Linq is more handy:
private static void Run()
{
HtmlDocument brPage = new HtmlWeb().Load("http://us.desert-operations.com/world2/battleReport.php?code=f8d77b1328c8ce09ec398a78505fc465");
var nodes = brPage.DocumentNode.Descendants("table").Where(_ => _.Attributes["class"] != null && _.Attributes["class"].Value != null && _.Attributes["class"].Value.Contains("battleReport"));
string result = "";
List<brContentSaver> ContentList = new List<brContentSaver>();
foreach (var item in nodes)
{
if (item.Descendants("th").Any(_ => _.InnerText.Equals("Weapons")))
{
//get all tr nodes except first one (header)
var trNodes = item.Descendants("tr").Skip(1);
foreach (var node in trNodes)
{
brContentSaver cL = new brContentSaver();
var tds = node.Descendants("td").ToArray();
/* Here comes the junk handler, replaces all junk for nothing, essentially deleting it
I wish I knew a way to do this efficiently */
cL.Weapons = tds[0].InnerText
.Replace(" * ", " ")
.Replace("  ; *  ;", " ");
cL.Used = tds[1].Descendants("span").FirstOrDefault()?.InnerText
.Replace(" * ", " ")
.Replace("  ; *  ;", " ");
if (string.IsNullOrEmpty(cL.Used))
{
cL.Used = tds[1].InnerText;
}
cL.Survived = tds[2].Descendants("span").FirstOrDefault()?.InnerText
.Replace(" * ", " ")
.Replace("  ; *  ;", " ");
if (string.IsNullOrEmpty(cL.Survived))
{
cL.Casualties = cL.Used;
}
else
{
/* int Casualties = int.Parse(cL.Casualties);
* int Used = int.Parse(cL.Used);
* int Survived = int.Parse(cL.Survived);
* Casualties = Used - Survived; */
cL.Casualties = tds[3].Descendants("span").FirstOrDefault()?.InnerText
.Replace(" * ", " ")
.Replace("  ; *  ;", " ");
if (string.IsNullOrEmpty(cL.Casualties))
{
cL.Casualties = tds[3].InnerText;
}
}
ContentList.Add(cL);
}
}
}
foreach (var item in ContentList)
{
result += item.Weapons + " " + item.Used + " " + item.Survived + " " + item.Casualties + Environment.NewLine;
}
var text = result;
}
I have been creating a winform application using perfmon. I have found out that the battery status will not work because its part of windows management. So I decide to go the wmi route.
So my question is when I put the battery status in a label as shown below:
private void BatteryStatus()
{
System.Management.ManagementClass wmi = new System.Management.ManagementClass("Win32_Battery");
var allBatteries = wmi.GetInstances();
foreach (var battery in allBatteries)
{
int estimatedChargeRemaining = Convert.ToInt32(battery["EstimatedChargeRemaining"]);
if (estimatedChargeRemaining == 100)
{
label13.Text = "Remaining:" + " " + estimatedChargeRemaining + " " + "%";
}
}
}
The charge remaining is shown perfectly. My question is, is there a way that I can have just one if statement to call the battery status from 100 to 1
or the way I am doing it will I have to do 99 more if statements?
this is part of my performance monitor I am custom building. It would be easier if perfmon would allow the counter. This is the only way I can think of to get the battery stats such as:
Charge Rate
Discharge Rate
Remaining Capacity
Voltage
I have always did if statements with the labels on battery status. Before I go into doing 99 more if statements I want to be sure there is not an easier way?
*********** Update ************
I figured it out. Thanks for the help for the ones who helped.
I thing that what you want to do is this:
private void BatteryStatus()
{
System.Management.ManagementClass wmi = new System.Management.ManagementClass("Win32_Battery");
var allBatteries = wmi.GetInstances();
foreach (var battery in allBatteries)
{
int estimatedChargeRemaining = Convert.ToInt32(battery["EstimatedChargeRemaining"]);
label13.Text = "Remaining:" + " " + estimatedChargeRemaining + " " + "%";
}
}
No need for and if statment, the label will be updated no matter what the percentage is.
On the second part of the question you say that you want to show the "battery status", you can then use if like this:
private void BatteryStatus()
{
System.Management.ManagementClass wmi = new System.Management.ManagementClass("Win32_Battery");
var allBatteries = wmi.GetInstances();
foreach (var battery in allBatteries)
{
int estimatedChargeRemaining = Convert.ToInt32(battery["EstimatedChargeRemaining"]);
string Status = "";
if(estimatedChargeRemaining < 15) Status = "Critical";
else if(estimatedChargeRemaining < 35) Status = "Low";
else if(estimatedChargeRemaining < 60) Status = "Regular";
else if(estimatedChargeRemaining < 90) Status = "High";
else Status = "Complete";
label13.Text = "Remaining:" + " " + estimatedChargeRemaining + " " + "% | Status: " + Status;
}
}
private void BatteryStatus()
{
System.Management.ManagementClass wmi = new System.Management.ManagementClass("Win32_Battery");
var allBatteries = wmi.GetInstances();
foreach (var battery in allBatteries)
{
int estimatedChargeRemaining = Convert.ToInt32(battery["EstimatedChargeRemaining"]);
label13.Text = "Remaining" + " " + estimatedChargeRemaining.ToString() + " " + "%";
if (estimatedChargeRemaining < 15 )
{
label13.ForeColor = Color.Red;
}
}
}
I know this is a very stupid and elementary question, but I really have no idea on other ways to accomplish this.
Now I know I can insert spaces within the text like my example below.
int num = some numerical value;
status.Text = "Successfully Deleted"+ " " + num + " " + "Files";
However, I'm wondering is there a neater way to do this. I always done it this way, but I'm wondering whether there's an easier/neater way to it. Thanks.
Using String class:
int num = 5;
status.Text = String.Format("Successfully Deleted {0} Files", num);
Using StringBuilder class:
int num = 5;
StringBuilder sb = new StringBuilder();
sb.AppendFormat("Successfully Deleted {0} Files", num);
status.Text = sb.ToString();
More options:
status.Text = "Successfully Deleted " + num + " Files";
Or:
public static string SurroundWithSpaces(this object o)
{
return " " + o + " ";
}
status.Text = "Successfully Deleted" + num.SurroundWithSpaces() + "Files";