Friday 8 January 2010

Stocks Displayer c#

I decided i wanted to be able to know what the stocks are for the yen to my local currency(shekel), but didn't like the bank`s graph(they put days that do not have trade on the graph), so i took the raw data, and made a graph.
Had to create a list for easy checking of the parsed data.

It might be interesting to someone that wants to know how to make a graph on c# or how to parse data without regex.
public partial class Form1 : Form
{
List<data> lst=new List<data>();

public Form1()
{

InitializeComponent();
string url="http://www.bankisrael.gov.il/eng.shearim/select_cur/cur4sdh.php?curname%5B%5D=_31%2B1977-10-31%2B%2BYen+-+Japan%A0&numselect=1&curfile=htm&fyear=2008&fmonth=12&fday=31&lyear=2009&lmonth=12&lday=31&cboday=01&cboyear_from=2008&cboyear_to=2009&lastwom=93&whosend=last";
string shitload;
System.Net.WebClient wc=new System.Net.WebClient();
shitload=wc.DownloadString(url);

//parsing
shitload=shitload.Remove(0,shitload.IndexOf("Exchange rates - Last 3 months"));
shitload=shitload.Remove(0,shitload.IndexOf("<TABLE width"));
shitload=shitload.Remove(shitload.IndexOf("</table>"));
string date;
try{
while (shitload.Length>100)
{
shitload=shitload.Remove(0,shitload.IndexOf("nowrap>")+7);
date=shitload.Substring(0,10);

shitload=shitload.Remove(0,shitload.IndexOf("nowrap>")+7);

lst.Add(new data(date,shitload.Substring(0,8)));

}
}
catch{}

label1.Text=shitload;

foreach (data dta in lst)
listBox1.Items.Add(dta.date+" "+dta.value);


this.Paint += new PaintEventHandler(paintgraph);


}
private void paintgraph(object sender,PaintEventArgs e)
{
Graphics g=e.Graphics;
g.Clear(Color.Wheat);
Pen pn=new Pen(new SolidBrush(Color.Red),2);
float min,max;
int mini=0,maxi=0;
min=100;max=0;
for (int i=0;i<lst.Count;i++)
{
if (lst[i].value<min) {min=lst[i].value;mini=i;}
if (lst[i].value>max) {max=lst[i].value;maxi=i;}
}
int inc=this.Width/lst.Count;
float dif=max-min;
float incy=(this.Height-40)/dif;
for(int i=0;i<lst.Count-1;i++)
{
g.DrawLine(pn,i*inc,(-lst[i].value+max)*incy,(i+1)*inc,(-lst[i+1].value+max)*incy);
Application.DoEvents();
}
if (lst.Count-1!=maxi)
g.DrawString(lst[maxi].date+" "+lst[maxi].value,new Font("Verdana",10),new SolidBrush(Color.Tomato),maxi*inc,(-lst[maxi].value+max)*incy);
else
g.DrawString(lst[lst.Count-1].date+" "+lst[lst.Count-1].value,new Font("Verdana",10),new SolidBrush(Color.Tomato),(lst.Count-1)*inc-130,(-lst[lst.Count-1].value+max)*incy);
if (lst.Count-1!=mini)
g.DrawString(lst[mini].date+" "+lst[mini].value,new Font("Verdana",10),new SolidBrush(Color.Tomato),mini*inc,(-lst[mini].value+max)*incy-20);
else
g.DrawString(lst[lst.Count-1].date+" "+lst[lst.Count-1].value,new Font("Verdana",10),new SolidBrush(Color.Tomato),(lst.Count-1)*inc-130,(-lst[lst.Count-1].value+max)*incy-20);
//if ((lst.Count-1!=maxi)&&(lst.Count-1!=mini))


}


void Form1ResizeEnd(object sender, EventArgs e)
{
this.Refresh();
}
}

public class data
{
public string date;
public float value;
public data(string d,string v)
{
date=d;
value=(float)System.Convert.ToDouble(v);
}
}

Wednesday 6 January 2010

PerformanceCounter c#

OK, after the last try to find some intresting data with the PerformanceCounter, i wanted to see what other counter it has, so i made a program to show me all the option, or at least the ones that are easy to find out, so i came up with this program:

Unlike the previous programs, this one is not a simple "throw everthing at the poor label", you will need:
-3 listboxs, each with a ListBox1SelectedIndexChanged(object sender, EventArgs e) event.
-and of course, one label to "throw everthing at"
Should look like this if you want:














Now, for the much more intresting code(not all that intersting, but the data you can get from the code is) :


void MainFormLoad(object sender, EventArgs e)
{
foreach (PerformanceCounterCategory pcc in PerformanceCounterCategory.GetCategories())
listBox1.Items.Add(pcc.CategoryName);
}

void ListBox1SelectedIndexChanged(object sender, EventArgs e)
{
int flag=1;
listBox2.Items.Clear();
listBox3.Items.Clear();
PerformanceCounterCategory pcc=new PerformanceCounterCategory(listBox1.SelectedItem.ToString());
foreach (string insname in pcc.GetInstanceNames())
{
flag=0;
listBox2.Items.Add(insname);
}
if (flag==1)
{
foreach (PerformanceCounter pc in pcc.GetCounters())
{
listBox3.Items.Add(pc.CounterName);
}
}
}

void ListBox2SelectedIndexChanged(object sender, EventArgs e)
{
listBox3.Items.Clear();
if (listBox2.SelectedItem==null) return;
PerformanceCounterCategory pcc=new PerformanceCounterCategory(listBox1.SelectedItem.ToString());
try{
foreach (PerformanceCounter pc in pcc.GetCounters(listBox2.SelectedItem.ToString()))
{
listBox3.Items.Add(pc.CounterName);
}
}
catch {label1.Text="instance invalid";}
}

void ListBox3SelectedIndexChanged(object sender, EventArgs e)
{
try{
PerformanceCounter pc;
if (listBox2.SelectedItem==null)
pc=new PerformanceCounter(listBox1.SelectedItem.ToString(),listBox3.SelectedItem.ToString());
else
pc=new PerformanceCounter(listBox1.SelectedItem.ToString(),
listBox3.SelectedItem.ToString(),listBox2.SelectedItem.ToString());
pc.NextValue();//for some, the first is always 0
label1.Text=pc.NextValue().ToString();
if ((label1.Text=="0")||(label1.Text=="100"))
{
float activity = 0;
int NormalDegree = 20;
for (int i = 0; i < NormalDegree; i++)
{
activity += pc.NextValue();
Application.DoEvents();
System.Threading.Thread.Sleep(20);
}
label1.Text=(activity/NormalDegree).ToString("g3");
if (listBox3.SelectedItem.ToString().StartsWith("%")) label1.Text+="%";
}
}
catch
{
label1.Text="counter invalid";
}
}

System Resources Monitor C#

As a continuation to the last program that monitor network stat, i created another one, now monitoring system resources such as cpu usage and memory usage.
I used PerformanceCounter for the current usage of both, and gotten the installed memory size from the windows management.
Also used threading to speed up and parrellize the proccess of getting the data.

Every 3 seconds:The system check the average cpu usage over the 3 seconds, and memory usage once(memory usage is far less dynamic compared to cpu usage).
Much like the previous example, the form is composed of a single Label named label1

public System.Diagnostics.PerformanceCounter pc=new System.Diagnostics.PerformanceCounter();
void getdata()
{
//using System.Threading;
//using System.Management;
//*IMPORTANT*also! you must add the management to the referances!!!!
System.Diagnostics.PerformanceCounter ram = new System.Diagnostics.PerformanceCounter("Memory", "Available MBytes");

label1.Text="";

int mem=0;

//check main memory size, it wont change during the running, thus only ran once.
ObjectQuery winQuery = new ObjectQuery("Select * from Win32_ComputerSystem");

ManagementObjectSearcher searcher = new ManagementObjectSearcher(winQuery);

foreach (ManagementObject item in searcher.Get())
{
mem=System.Convert.ToInt32(item["TotalPhysicalMemory"])/1024/1024;
}


while (this.Disposing==false)
{
//long tick=DateTime.Now.Ticks; //the ticks can be used to find out how much time each loop takes
Thread th=new Thread(new ThreadStart(setcpurate));
th.Start();
//lets get some more data, like free mem while he works, however, its best to make ones that wont sabotage the data

//to prevent corrupting the cpu data with these calculations, lets sleep while he works.
while (th.ThreadState==ThreadState.Running) Thread.Sleep(101);
label1.Text+="free memory="+ram.NextValue().ToString()+"MB of ";
label1.Text+=mem+" MB\n";
Application.DoEvents();

while (th.ThreadState!= ThreadState.Stopped) Thread.Sleep(100);
//now the cpu usage thread should be done.
label1.Text+="cpu usage="+str+"\n";
//tick=DateTime.Now.Ticks-tick;
//label1.Text+="time to calculate: "+tick/TimeSpan.TicksPerMillisecond+" ms\n";
Application.DoEvents();
}
}

void setcpurate()
{ //set the cpu rate to str, yea, i know i should have used a semaphor\mutex\we,
//but if you wait till thread is dead, the data is already in place
pc.CategoryName = "Processor";
pc.CounterName = "% Processor Time";
pc.InstanceName = "_Total";
pc.NextValue(); //always return 0 on first run
float activity = 0;
int NormalDegree = 15;
for (int i = 0; i < NormalDegree; i++) //averaging over 3 seconds
{
activity += pc.NextValue();
Application.DoEvents();
Thread.Sleep(200);
}
Thread.MemoryBarrier();
str=(activity/NormalDegree).ToString("g3")+"%";
}

Tuesday 5 January 2010

pinger in c#

I've been working on a program in c# that will let me monitor plenty of information about my system, a part of it the network stat, including mostly of internet speed, ping time and external ip.

This could also be used as an example for the ticks and timers in the system.
I'm using a big site in my country for the speeds, so you should fit the "www.ynet.co.il" to one the fit your needs better, and the ip is from a specific address at http://www.whatismyip.com
The form is composed of a single label named label1 to display the results.

void MainFormLoad(object sender, EventArgs e)
{
long tick;


//pinging
System.Net.NetworkInformation.Ping png=new System.Net.NetworkInformation.Ping();
png.Send("www.ynet.co.il");//static ping to create the classes
tick=DateTime.Now.Ticks;
for (int i=0;i<4;i++)
png.Send("www.ynet.co.il");
tick=(DateTime.Now.Ticks-tick)/4;
label1.Text="ping="+(((double)tick)/TimeSpan.TicksPerMillisecond).ToString()+"ms\n";


System.Net.WebClient wc=new System.Net.WebClient();

//getting speeds:
string site;
tick=DateTime.Now.Ticks; //these 3 lines must remain close to each
site=wc.DownloadString("http://www.ynet.co.il/"); //2
tick=DateTime.Now.Ticks-tick; //3
//label1.Text+="time="+((tick)/TimeSpan.TicksPerMillisecond).ToString()+" ms\n";
string tmp=((site.Length/1024)/((double)tick/TimeSpan.TicksPerSecond)).ToString("g4");
label1.Text+="speed="+tmp+" kb/s (for size="+(site.Length/1024).ToString()+" kb)\n";


//getting ip address
tmp=wc.DownloadString("http://www.whatismyip.com/automation/n09230945.asp"); //this address get ip directly
label1.Text+="external ip="+tmp;

}

If you want to know about a specific part of the program, feel free to ask.

this will probably be a blog about nothing

However, i will attempt to post some of the codes im working on.
In case you are wondering, who am i?
My name is omer and i live in israel, i'm a collage student for computer engineering, currently forth year.
If you really want to, my animeblog is at http://omerby.blogli.co.il , however, its in hebrew, so be warned.

Also, please forgive me for any spelling or grammer errors(especially capitailzation), i mostly write while being very tired