C# system.timers.timer weird behavior - c#

I am trying to implement Bully Coordinator election algorithm. In this algorithm, Coordinator sends the alive message every 10 seconds and all the processes wait for at least 14 seconds to receive alive, if they don't receive the message within that time, they will initiate dead coordinator election.
The problem is AliveTimer (Timer3_Count) is increasing exponentially and active processes are also affecting it. I don't know why it is behaving weirdly.
When the initial coordinator is sending the Alive message then counter works perfectly but after dead coordinator election, it behaves weirdly.
else if (Received_Text.Contains("Alive:"))
{
SetText(Received_Text + "\n");
Coordinator_Alive = true;
Timer3_Counter = 0;
if (Alive_Count == 0)
{
Alive_Count++;
AliveTimer.Interval = (1 * 1000);
AliveTimer.Enabled = true;
AliveTimer.Elapsed += new System.Timers.ElapsedEventHandler(AliveTimer_Elapsed);
AliveTimer.Start();
}
}
The elapsed function is here
I think there is something wrong with my program, I tried everything.
private void AliveTimer_Elapsed(object sender, EventArgs e)
{
Timer3_Counter++;
SetTimer(Timer3_Counter.ToString());
Random rnd = new Random();
int rand_time = rnd.Next(14, 18);
if (Timer3_Counter == 14)
{
AliveTimer.Stop();
Timer3_Counter = 0;
Alive_Count = 0;
if (Coordinator_Alive == false)
{
byte[] buffer = Encoding.ASCII.GetBytes("Dead Coordinator Election: " + txName.Text);
_clientSocket.Send(buffer);
Timer4_Counter = 0;
DeadTimer.Interval = (1 * 1000);
DeadTimer.Elapsed += new System.Timers.ElapsedEventHandler(DeadTimer_Elapsed);
DeadTimer.Enabled = true;
DeadTimer.Start();
}
}
if (Coordinator_Alive == true)
Coordinator_Alive = false;
}
and the dead Coordinator election code is here
else if (Received_Text.Contains("Dead Coordinator Election:"))
{
SetCPID("");
Coordinator_Alive = false;
Alive_Count = 0;
Timer3_Counter = 0;
AliveTimer.Stop();
AliveTimer.Enabled = false;
string output = Regex.Match(Received_Text, #"\d+").Value;
SetText("Dead Coordinator Election Received from Process ID: " + output + "\n");
if (Convert.ToInt32(txName.Text) > Convert.ToInt32(output))
{
byte[] buffer = Encoding.ASCII.GetBytes("Greater Process No: " + txName.Text + " found than " + output + "\n");
_clientSocket.Send(buffer);
SetText("Our Process No: " + txName.Text + " is Greater than " + output + "\n");
Lower_Count++;
byte[] buffer1 = Encoding.ASCII.GetBytes("Dead Coordinator Election: " + txName.Text);
_clientSocket.Send(buffer1);
}
else
{
byte[] Txt_Send = Encoding.ASCII.GetBytes("Our Process No: " + txName.Text + " is less than " + output);
_clientSocket.Send(Txt_Send);
Greater_Count++;
}
}
The full code can be found here
Bully Algorithm
Note: I am using passive server just to broadcast messages from each process

I don't know what causes the problem, but I think you will be able to figure the cause quickly if you log start and stop all all methods and analyse the output.
This would help establish if:
1. As #Idle_Mind suggested, that you are adding more and more handlers
2. The time taken to execute each method creeps up
and more...
I don't know how you app is built but you can even start with Console.WriteLine or Debug.WriteLine.

Related

C# Managing threads in console application

Good day everyone,
I need to say firstly, that I am not a C# developer in anyway, I have been tasked from my boss to "Make it work".
What I want is to have a thread that will spin off, not interrupt main(), call a function CcnDirSearch() and re perform this action after a certain amount of time.
My code currently runs in console about 1 time (sometimes 6 times) and then stops. I think the threads(or something like this) are ending before the function is completing.
Here is my code:
public int Run()
{
Task.Factory.StartNew(() => CcnDirFireAway());
...
...
//continues main();
>
public void CcnDirFireAway()
{
if (ScanDir != "")
{
Console.WriteLine("Starting Initial Scan on Directory: " + ScanDir + "\n\n\n");
TimerCallback tmCallback = CheckEffectExpiry;
Timer timer = new Timer(tmCallback, "test", 1000, 1000);
}
}
>
public void CheckEffectExpiry(object objectInfo)
{
//TODO put your code
Console.ForegroundColor = ConsoleColor.Green;
Console.Write(DateTime.Now + " Starting Scan.....\n");
Console.ForegroundColor = ConsoleColor.White;
//Here is a call to my function that I want to call.
// I noticed that If I don't call it the programs continues to run harmoniously
Searcher.CcnDirSearch(ScanDir);
Console.ForegroundColor = ConsoleColor.Red;
Console.Write(DateTime.Now + " Finished Scan.....\n");
Console.ForegroundColor = ConsoleColor.White;
}
>
Here is the code of the function I need to call off .
public static void CcnDirSearch(string sDir)
{
try
{
foreach (string file in Directory.EnumerateFiles(sDir, "*.*", SearchOption.AllDirectories))
{
using (var stream = File.OpenRead(file))
{
// Console.WriteLine(DateTime.Now + " Checking File : " + file);
bool Mcard = Searcher.CCNSearch(file, De.Thekid.INotify.Runner.MASTERCARD, false);
bool VCARD = Searcher.CCNSearch(file, De.Thekid.INotify.Runner.VISA, false);
bool ACARD = Searcher.CCNSearch(file, De.Thekid.INotify.Runner.AMEX, false);
if (Mcard)
{
Console.WriteLine(DateTime.Now + " MasterCard Number Found In File >> " + file);
//Inotifywatch.EventForward.UDPSend(512, RServer, ("<30>" + DateTime.Now + " MasterCard Number Found In File >> " + fullpath+ "\n"));
Logger.WriteEvent(DateTime.Now + " MasterCard Number Found In File >> " + file + "\n");
}
else if (VCARD)
{
Console.WriteLine(DateTime.Now + " Visa Card Number Found In File >> " + file);
//Inotifywatch.EventForward.UDPSend(512, RServer, ("<30>" + DateTime.Now + " Visa Card Number Found In File >> " + fullpath+ "\n"));
Logger.WriteEvent(DateTime.Now + " Visa Card Number Found In File >> " + file + "\n");
}
else if (ACARD)
{
Console.WriteLine(DateTime.Now + " AMEX Card Number Found In File >> " + file);
//Inotifywatch.EventForward.UDPSend(512, RServer, ("<30>" + DateTime.Now + " AMEX Card Number Found In File >> " + fullpath+ "\n"));
Logger.WriteEvent(DateTime.Now + " Amex Card Number Found In File >> " + file + "\n");
}
}
}
}
catch (System.Exception excpt)
{
Console.WriteLine(excpt.Message);
}
Console.Write("Finished the Search\n");
}
You could use a DispatcherTimer to call a function on a given time interval, then in that function create and start a new Thread in which you execute your function.
public static void Main(string[] args)
{
DispatcherTimer timer = new DispatcherTimer();
timer.Interval = TimeSpan.FromMilliseconds(5000);;
timer.IsEnabled = true;
timer.Tick += OnTimerTick;
}
private void OnTimerTick(object sender, EventArgs e)
{
var thread = new Thread(new ThreadStart(()=>yourMethodToCall()));
thread.Start();
}
I want to Thanks everyone for all your help. I found a work around that worked for me.
As I said before , I am not a C# developer (I play one on T.V) so I am certain there are somethings where this code base can be improved .
If someone can write a better answer, I will happily accept it.
I just decided to launch the code differntly .
Timer x = new Timer(state => CheckEffectExpiry(1), null, 5000 /* When to start*/, 300000 /* when to retry */);
>
public void CheckEffectExpiry(object objectInfo)
{
//I hate C#'s way of accessing variables and such .
//So I am doing this...
Console.Write(DateTime.Now + " I was hit\n");
if (lockf == 1)
{
Console.ForegroundColor = ConsoleColor.Green;
Console.Write(DateTime.Now + " Starting Scan.....\n");
Console.ForegroundColor = ConsoleColor.White;
lockf = 0;
Searcher.CcnDirSearch(ScanDir);
lockf = 1;
Console.ForegroundColor = ConsoleColor.Red;
Console.Write(DateTime.Now + " Finished Scan.....\n");
Console.ForegroundColor = ConsoleColor.White;
}
}

C# Console application pause working until right click on Console

I'm building a c# console application which read messages from MSMQ(Microsoft Message Queuing), I expected it to run forever but after a day running it stop reading message from MSMQ until I right click on its Console, my problem seems to be alittle bit similar to this: "Console Application "pausing" c#". Bellow is the function that I'm using:
private static void downloadHandler(object args)
{
while (true)
{
while (CURRENT_ACTIVE_THREAD < MAX_THREAD)
{
DownloadController.WriteLog("Current active Thread = " + CURRENT_ACTIVE_THREAD);
Console.WriteLine("Current active Thread = " + CURRENT_ACTIVE_THREAD);
Thread.Sleep(1000);
MessageQueue messageQueue;
if (MessageQueue.Exists(messageQueuePath))
{
messageQueue = new MessageQueue(messageQueuePath);
Message requestMessage = messageQueue.Receive();
try
{
requestMessage.Formatter = new BinaryMessageFormatter();
string msg = requestMessage.Body.ToString();
if (!string.IsNullOrEmpty(msg))
{
DownloadController.WriteLog("received message with message = " + msg);
CURRENT_ACTIVE_THREAD += 1;
RequestDownload request = new RequestDownload();
request = JsonConvert.DeserializeObject<RequestDownload>(msg);
DownloadController.WriteLog("received message with contentId = " + request.contentId + "from message queue | title= " + request.contentTitle + " | url = " + request.baseURL);
DownloadController downloader = new DownloadController();
Thread t = new Thread(new ParameterizedThreadStart(downloader.findURLandDownload));
object[] objs = new object[2];
objs[0] = request;
objs[1] = "1";
t.Start(objs);
Console.WriteLine("received message with contentId = " + request.contentId);
}
}
catch (Exception ex)
{
CURRENT_ACTIVE_THREAD -= 1;
Console.WriteLine("Exception: " + ex.Message);
DownloadController.WriteLog("There is exception while trying to read message from message queue, Exception = " + ex.Message);
}
}
}
}
}
So,could anyone please tell me what the problem is? Why this happening?
It might be you're while loop. I had while loops freeze or break my applications before. Might i suggest using timers instead ? I have some links you could use for reference:
c# wait for a while without blocking
https://msdn.microsoft.com/en-us/library/system.timers.timer(v=vs.110).aspx
I do hope this fixes the problem you're having !
greatings,
Ramon.

Battery Status in winforms

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;
}
}
}

Memory getting full by timers or Webbrowser? c#

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.

Why does a method that calls Ping.Send() on an invalid URL die with an unhandled exception?

The following method calls Ping.Send(). When I pass an invalid URL, Send() dies and an unhandled exception happens. What is the cause of this?
private void ping()
{
comboBox3.Visible = false;
listBox2.Items.Clear();
// check the url if it is null
if (string.IsNullOrEmpty(textBox1.Text) || textBox1.Text == "")
{
listBox2.Items.Add("Please use valid IP or web address!!");
comboBox3.Visible = false;
coloring_red_tab4();
}
else
{
// do the ping
coloring_green_tab4();
for (int i = 0; i < numericUpDown1.Value; i++)
{
string s;
s = textBox1.Text;
string data = "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa";
byte[] buffer = Encoding.ASCII.GetBytes(data);
int timeout = 120;
Ping p = new Ping();
PingOptions options = new PingOptions();
options.DontFragment = true;
//pingexception was unhalded (if the url wrong here is the error)
PingReply r = p.Send(s, timeout, buffer, options);
// if it's true url
if (r.Status == IPStatus.Success)
{
listBox2.Items.Add("Ping to " + s.ToString() + "[" + r.Address.ToString() + "]" + " (Successful) "
+ "Bytes =" + r.Buffer.Length + " TTL=" + r.Options.Ttl + " Response delay = " + r.RoundtripTime.ToString() + " ms " + "\n");
label91.Text = r.Address.ToString();
}
else
{
// just to know the ip for the website if they block the icmp protocol
listBox2.Items.Add(r.Status);
IPAddress[] ips;
ips = Dns.GetHostAddresses(textBox1.Text);
foreach (IPAddress ip in ips)
{
label91.Text = ip.ToString();
}
}
}
}
}
The exception is unhandled because you do not handle it. Whenever you call a .Net library method, you need to check its documentation to see what exceptions it throws, and decide which, if any, you want to handle at that level of code. Here is the relevant portion of the documentation for Ping.Send(), which I am including as an image so you will be able to recognize these sections going forward:
Notice that the documentation states that a PingException can occur if
An exception was thrown while sending or receiving the ICMP messages. See the inner exception for the exact exception that was thrown.
Thus it's clear from the documentation that many errors from Ping() will be reported as thrown exceptions rather than reported by setting PingReply.Status != IPStatus.Success. So you need to modify your code to be something like the following:
public static bool TryPing(string hostNameOrAddress, out string pingStatusMessage, out string pingAddressMessage)
{
if (String.IsNullOrWhiteSpace(hostNameOrAddress))
{
pingStatusMessage = "Missing host name";
pingAddressMessage = "";
return false;
}
var data = "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa";
var buffer = Encoding.ASCII.GetBytes(data);
var timeout = 120;
using (var p = new Ping())
{
var options = new PingOptions();
options.DontFragment = true;
try
{
var r = p.Send(hostNameOrAddress, timeout, buffer, options);
if (r.Status == IPStatus.Success)
{
pingStatusMessage = "Ping to " + hostNameOrAddress.ToString() + "[" + r.Address.ToString() + "]" + " (Successful) "
+ "Bytes =" + r.Buffer.Length + " TTL=" + r.Options.Ttl + " Response delay = " + r.RoundtripTime.ToString() + " ms " + "\n";
pingAddressMessage = r.Address.ToString();
return true;
}
else
{
// just to know the ip for the website if they block the icmp protocol
pingStatusMessage = r.Status.ToString();
var ips = Dns.GetHostAddresses(hostNameOrAddress);
pingAddressMessage = String.Join(",", ips.Select(ip => ip.ToString()));
return false;
}
}
catch (PingException ex)
{
pingStatusMessage = string.Format("Error pinging {0}: {1}", hostNameOrAddress, (ex.InnerException ?? ex).Message);
pingAddressMessage = hostNameOrAddress;
return false;
}
}
}
Here I have extracted a utility method from the user interface code and also properly disposed of the Ping instance after it is no longer needed.
Then
TryPing(#"www.google.com", out pingStatusMessage, out pingAddressMessage);
Gives
Ping to www.google.com[146.115.8.83] (Successful) Bytes =32 TTL=62 Response delay = 8 ms
While
TryPing(#"www.kdjf98rglkfgjldkfjgdl;fge8org.com", out pingStatusMessage, out pingAddressMessage);
Gives
Error pinging www.kdjf98rglkfgjldkfjgdl;fge8org.com: No such host is known

Categories

Resources