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";
Related
I'm trying to search for a certain number(object) in a listbox which comes together with a string in order to highlight it. In the following bit of code i override a ToString() method to contain all my objects.
public override string ToString()
{
string reservatiestring;
reservatiestring = "Kamer: " + roomNumber + "" + " Op datum: " + datum + " Aantal personen: " + personen.Count + " Naam: " + reservatienaam;
return reservatiestring;
}
Following this I add it to my listbox in the following bit of code:
listBox1.Items.Add(reservatie.ToString());
I now want to search for all the items in my listbox containing the same roomNumber object. To do this i tried the Contains() method with the text before it: "Kamer: " and the object which I'm looking for +comboBox1.SelectedItem. This however always fails and my code goes to the else option giving me the error message.
private void buttonSearch_Click(object sender, EventArgs e)
{
listBox1.SelectionMode = SelectionMode.MultiExtended;
Reservations reservaties = new Reservations();
reservaties.roomnumberstring = "Kamer: " + comboBox1.SelectedValue;
for (int i = listBox1.Items.Count - 1; i >= 0; i--)
{
if (listBox1.Items[i].ToString().ToLower().Contains(("Kamer: " + comboBox1.SelectedValue)))
{
listBox1.SetSelected(i, true);
}
else
{
MessageBox.Show("error");
}
Please note: All my roomNumber objects are stored in the combobox, so whenever i select for example roomNumber 3 in my combobox and hit search all the items in the listbox containing "Kamer: 3" should be selected.
The roomnumberstring is a option I tried which did not work unfortunately.
reservaties.roomnumberstring = "Kamer: " + comboBox1.SelectedValue;
Your override of the ToString method is wrong and won't modify anything. Try this :
public override string ToString(this string reservatiestring)
{
reservatiestring = "Kamer: " + roomNumber + "" + " Op datum: " + datum + " Aantal personen: " + personen.Count + " Naam: " + reservatienaam;
return reservatiestring;
}
I can see one thing that might make your code fail. you are comparing
.ToLower()
with "Kamer", where the "K" isn´t in lowercase
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;
}
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.
I was wondering if there is a way to reach the logs under the section named Application and Service Logs in the Event viewer utility in Windows. The thing is, I can read the entries under Windows Logs with the code below. I read the whole entry, and get the items with the necessary id, getting top 20 results. But I couldn't find anything on accessing the Application and Service logs section. Should I change the LogType in the EventLog constructor? Or is there a different method or class to access Application and Service logs? Trying "Application" as the logType variable doesnt work.
string str = "";
EventLog ev = new EventLog(logType, System.Environment.MachineName);
int LastLogToShow = ev.Entries.Count;
if (LastLogToShow <= 0)
Console.WriteLine("No Event Logs in the Log :" + logType);
int i;
int k = 0;
for (i = ev.Entries.Count - 1; i >= 0; i--)
{
EventLogEntry CurrentEntry = ev.Entries[i];
if (CurrentEntry.EventID == id)
{
if (id == 1)
{
str += "Son Açılma \n";
str += "Olay Zamanı: " + CurrentEntry.TimeGenerated.ToLongDateString() + " " + CurrentEntry.TimeGenerated.ToShortTimeString() + "\n";
}
else if (id == 42)
{
str += "Son Kapatılma \n";
str += "Olay Zamanı: " + CurrentEntry.TimeGenerated.ToLongDateString() + " " + CurrentEntry.TimeGenerated.ToShortTimeString() + "\n";
}
else
{
str += "Event type: " + CurrentEntry.EntryType.ToString() + "\n";
str += "Event Message: " + CurrentEntry.Message + CurrentEntry + "\n";
str += "Event : " + CurrentEntry.UserName + "\n" + "\n";
str += "Olay Zamanı: " + CurrentEntry.TimeGenerated.ToLongDateString() + " " + CurrentEntry.TimeGenerated.ToShortTimeString() + "\n";
}
k++;
}
if (k > 20)
break;
}
ev.Close();
return str;
What I am looking for is under
Application and Service Logs/
Microsoft/
Windows/
TerminalServices-RemoteConnectionManager/
Operational/
Event ID 1149
I'm not sure you can access them using the EventLog class, or at least I couldn't figure out how. I did it using the EventLogQuery class instead.
I've provided an example below which I adapted from this post (C#: How to Query for an event log details with a given event id?), and should work for what you need:
using System.Diagnostics.Eventing.Reader;
string logType = "Microsoft-Windows-TerminalServices-RemoteConnectionManager/Operational";
string query = "*[System/EventID=1149]";
var elQuery = new EventLogQuery(logType, PathType.LogName, query);
var elReader = new EventLogReader(elQuery);
for (EventRecord eventInstance = elReader.ReadEvent(); eventInstance != null; eventInstance = elReader.ReadEvent())
{
// .. do stuff here
}
So I want to put certain lines into a text box, say I use the "Search Function" to search transaction ID, it would look through the transactions.txt file and find the transaction ID and Read the 6 lines under it which show the transactions Details, once found this would then go to a the listbox which then you could edit the transaction.
I was wondering would you use loops and arrays to do this, and could someone show me how, Thank you!
Heres my current code:
//Creates a textfile with details of the transaction
public void CreateFile()
{
StreamWriter outputFile;
outputFile = File.AppendText("Transactions.txt");
outputFile.WriteLine("Investor :" +" " + InvestorNameLabel.Text);
outputFile.WriteLine("Initial Amount" + " " +AmountLabel.Text);
outputFile.WriteLine("Date Invested" +" " +DateLabel.Text);
outputFile.WriteLine("Period Chosen" + " "+DaysInvestedLabel.Text);
outputFile.WriteLine("Rate Chosen" + " " + RateLabel.Text);
outputFile.WriteLine("Total Interest" + " " +InterestAmountLabel.Text);
outputFile.WriteLine("Transaction Number :" + " " + TransactionIDLabel.Text);
outputFile.Close();
MessageBox.Show("Transaction file for Transaction: " + TransactionIDLabel.Text + " " +"Was Created", "Transaction File");
}
//puts all transactions in listbox
//needs to be able to find certain transactions
private void button1_Click(object sender, EventArgs e)
{
using (StreamReader sr = new StreamReader("transactions.txt"))
{
string line;
while ((line = sr.ReadLine()) != null)
{
listBox1.Items.Add(line);
}
}
}
Try This:
string ID = "23";
bool idFound=false;
int count = 0;
foreach (var line in File.ReadLines("transactions.txt"))
{
if (idFound && count < 6)
{
listBox1.Items.Add(line);
count++;
}
if(line.Contains(ID))//if you wantto match exactly use if(line.Equals(ID))
{
idFound = true;
}
}