diff ServerMonitor/Objects/PingCheck.cs @ 0:3e1a2131f897

Initial commit. Ping check, scheduling, UI working. SSH check mostly working.
author Brad Greco <brad@bgreco.net>
date Mon, 31 Dec 2018 18:32:14 -0500
parents
children
line wrap: on
line diff
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/ServerMonitor/Objects/PingCheck.cs	Mon Dec 31 18:32:14 2018 -0500
@@ -0,0 +1,56 @@
+using System;
+using System.Collections.Generic;
+using System.ComponentModel;
+using System.Linq;
+using System.Net.NetworkInformation;
+using System.Text;
+using System.Threading;
+using System.Threading.Tasks;
+
+namespace ServerMonitorApp
+{
+    [DisplayName("Ping check"), Description("Check if the server responds to a ping request"), DisplayWeight(0)]
+    public class PingCheck : Check
+    {
+        protected async override Task<CheckResult> ExecuteCheckAsync(CancellationToken token)
+        {
+            using (Ping ping = new Ping())
+            {
+                try
+                {
+                    PingReply reply = await ping.SendPingAsync(Server.Host, Timeout);
+                    if (reply.Status == IPStatus.Success)
+                        return Pass(string.Format("Reply received in {0} ms", reply.RoundtripTime));
+                    else
+                        return Fail("Ping result: " + reply.Status);
+                }
+                catch (PingException e)
+                {
+                    return Fail(e);
+                }
+            }
+
+            // Cancellable version that doesn't actulaly work
+            // might be useful as a TaskCompletionSource example though
+            //
+            //TaskCompletionSource<CheckResult> tcs = new TaskCompletionSource<CheckResult
+            //
+            //using (Ping ping = new Ping())
+            //{
+            //    token.Register(ping.SendAsyncCancel);
+            //    ping.PingCompleted += (sender, e) =>
+            //    {
+            //        if (e.Error != null)
+            //            tcs.SetResult(Fail("Ping failed: " + e.Error.GetBaseException().Message));
+            //        else if (e.Reply.Status != IPStatus.Success)
+            //            tcs.SetResult(Fail("Ping failed: " + e.Reply.Status.ToString()));
+            //        else
+            //            tcs.SetResult(Pass("Ping completed in " + e.Reply.RoundtripTime + "ms"));
+            //    };
+            //    ping.SendAsync(Server.Host, Timeout, null);
+            //}
+
+            //return tcs.Task;
+        }
+    }
+}