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;
}
}
}
Related
I am trying to print a bill of sale, it works fine for me. But I have a problem, I don't know how to make the product description appear aligned, under the cut I make to print the rest of the description on a new line.
The full description is: "Aloe Vera Coco 12 x 1500 ml"
I leave the image and the code that prints the detail.
Someone who knows iText well and tell me how to solve this detail.
Thank you all
private void SetDetalles()
{
// 1 2 3 4 5
// 12345678901234567890123456789012345678901234567890
// "Cant Descripcion 000000000 000000000"
// --------------------------------------------------
SetLineaDivisora();
string linea = "Cant Descripcion Precio Total";
SetTextoNormal(linea);
SetLineaDivisora();
int maxLenLine = 25;
string descpart = "";
foreach (DetallesPDF det in detalles)
{
string descripcion = det.Descripcion;
if (maxLenLine > descripcion.Length)
{
descpart = descripcion.PadRight(25);
descripcion = "";
linea = det.Cantidad.ToString().PadRight(4) + " " +
descpart + " " +
det.Precio.ToString("N0").PadLeft(9) + " " +
det.TotalItem.ToString("N0").PadLeft(9);
SetTextoNormal(linea);
}
else
{
bool lflag = true;
descpart = descripcion.Substring(0, maxLenLine);
do
{
if (lflag)
{
linea = det.Cantidad.ToString().PadRight(4) + " " +
descpart + " " +
det.Precio.ToString("N0").PadLeft(9) + " " +
det.TotalItem.ToString("N0").PadLeft(9);
descripcion = descripcion.Substring(maxLenLine);
lflag = false;
}
else
{
descpart = descripcion.Substring(0);
linea = $" {descpart}"; // --> Add 5 blanks so it will be aligned, but the line break shows it on the left side.
descripcion = descripcion.Replace(descpart, "");
}
SetTextoNormal(linea);
}
while (descripcion.Trim().Length > 0);
}
}
SetLineaDivisora();
}
Function that generates the sale detail item
private void SetTextoNormal(string linea, float separacion = 0.2f, bool centrado = false)
{
Paragraph header = new Paragraph(linea)
//.SetTextAlignment(TextAlignment.LEFT)
.SetMultipliedLeading(separacion)
.SetFontSize(7)
.SetFont(currierNew);
if (centrado)
header.SetTextAlignment(TextAlignment.CENTER);
miDocumento.Add(header);
}
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'm working on a speech recognition program in C# and I'v compiled a few lines of code that speaks back the current battery level when I say "battery Level". Only problem is, It doesn't work.
Debugging stage it builds fine, no errors or warnings yet when I say "battery level" I get no response.
if (e.Result.Text == "battery level")
{
System.Management.ManagementClass wmi = new System.Management.ManagementClass("Win32_Battery");
var allBatteries = wmi.GetInstances();
String estimatedChargeRemaining = String.Empty;
foreach (var battery in allBatteries)
{
estimatedChargeRemaining = Convert.ToString(battery["EstimatedChargeRemaining"]);
}
JARVIS.Speak("Estimated Charge Remaining: " + estimatedChargeRemaining + "%");
return;
}
Does anyone notice any obvious mistakes in the code that could prevent it from working?
Thanks.
There are couple of mistakes in your code that may or may not be affecting your application
if (e.Result.Text.ToLower() == "battery level") //First Change
{
System.Management.ManagementClass wmi = new System.Management.ManagementClass("Win32_Battery");
var allBatteries = wmi.GetInstances();
String estimatedChargeRemaining = String.Empty;
foreach (var battery in allBatteries)
{
estimatedChargeRemaining = Convert.ToString(battery["EstimatedChargeRemaining"]);
JARVIS.Speak("Estimated Charge Remaining: " + estimatedChargeRemaining + "%"); //second change as you may have more than one batteries.
}
return;
}