view ServerMonitor/Objects/PingCheck.cs @ 1:9e92780ebc0f

Additional validation for SSH check
author Brad Greco <brad@bgreco.net>
date Tue, 01 Jan 2019 21:14:47 -0500
parents 3e1a2131f897
children
line wrap: on
line source

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