view ServerMonitor/Objects/Checks/PingCheck.cs @ 23:3866c19535fd

Fix NullReferenceException when checks are executed on a brand new server.
author Brad Greco <brad@bgreco.net>
date Thu, 30 May 2019 21:40:27 -0400
parents 68d7834dc28e
children
line wrap: on
line source

using System.ComponentModel;
using System.Net.NetworkInformation;
using System.Threading;
using System.Threading.Tasks;

namespace ServerMonitorApp
{
    /// <summary>Checks that a server responds to ping.</summary>
    [DisplayName("Ping check"), Description("Check if the server responds to a ping request"), DisplayWeight(0)]
    public class PingCheck : Check
    {
        /// <summary>Sends a ping and waits for a response.</summary>
        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);
                }
            }
        }
    }
}