public CollectorState GetState(PingCollectorResult pingResult)
        {
            CollectorState result = CollectorState.Good;

            if (pingResult.PingTime > -1)
            {
                if (pingResult.PingTime > TimeOutMS)
                {
                    result = CollectorState.Error;
                    pingResult.ResponseDetails = string.Format("Operation timed out! Max time allowed: {0}ms, {1}", TimeOutMS, pingResult.ResponseDetails);
                }
                else if (pingResult.PingTime > MaxTimeMS)
                {
                    result = CollectorState.Warning;
                    pingResult.ResponseDetails = string.Format("Operation did not finished in allowed time! Excepted time: {0}ms, {1}", MaxTimeMS, pingResult.ResponseDetails);
                }
                else if (pingType == PingCollectorType.HTTP && HTMLContentContain != null && pingResult.ResponseContent.Trim().Length > 0 && HTMLContentContain.Trim().Length > 0 && !pingResult.ResponseContent.Contains(HTMLContentContain))
                {
                    result = CollectorState.Warning;
                    pingResult.ResponseDetails = string.Format("The returned HTML does not contain the specified string '{0}'", HTMLContentContain);
                }
                else
                {
                    result = CollectorState.Good;
                }
            }
            else
            {
                result = CollectorState.Error;
            }
            return(result);
        }
Beispiel #2
0
        public override List <System.Data.DataTable> GetDetailDataTables()
        {
            List <System.Data.DataTable> tables = new List <System.Data.DataTable>();

            System.Data.DataTable dt = new System.Data.DataTable();
            try
            {
                dt.Columns.Add(new System.Data.DataColumn("Host name", typeof(string)));
                dt.Columns.Add(new System.Data.DataColumn("Success", typeof(bool)));
                dt.Columns.Add(new System.Data.DataColumn("Ping time", typeof(int)));
                dt.Columns.Add(new System.Data.DataColumn("Response", typeof(string)));

                PingCollectorConfig currentConfig = (PingCollectorConfig)AgentConfig;
                foreach (PingCollectorHostEntry host in currentConfig.Entries) //.OrderBy(h => ((PingCollectorHostEntry)h).Address))
                {
                    PingCollectorResult pingResult = host.Ping();
                    dt.Rows.Add(host.Address, pingResult.Success, pingResult.PingTime, pingResult.ResponseDetails);
                }
            }
            catch (Exception ex)
            {
                dt = new System.Data.DataTable("Exception");
                dt.Columns.Add(new System.Data.DataColumn("Text", typeof(string)));
                dt.Rows.Add(ex.ToString());
            }
            tables.Add(dt);
            return(tables);
        }
 public override void RefreshDisplayData()
 {
     try
     {
         System.Windows.Forms.Cursor.Current = Cursors.WaitCursor;
         lvwEntries.BeginUpdate();
         foreach (ListViewItem itmX in lvwEntries.Items)
         {
             PingCollectorHostEntry host = (PingCollectorHostEntry)itmX.Tag;
             try
             {
                 PingCollectorResult pingResult = host.Ping();
                 CollectorState      result     = host.GetState(pingResult);
                 if (pingResult.Success)
                 {
                     itmX.SubItems[1].Text = pingResult.PingTime.ToString() + " ms";
                     itmX.SubItems[2].Text = pingResult.ResponseDetails;
                     if (result == CollectorState.Good)
                     {
                         itmX.ImageIndex = 0;
                         itmX.BackColor  = SystemColors.Window;
                     }
                     else if (result == CollectorState.Warning)
                     {
                         itmX.ImageIndex = 1;
                         itmX.BackColor  = Color.SandyBrown;
                     }
                     else
                     {
                         itmX.ImageIndex = 2;
                         itmX.BackColor  = Color.Salmon;
                     }
                 }
                 else
                 {
                     itmX.ImageIndex = 2;
                     itmX.BackColor  = Color.Salmon;
                     if (pingResult.PingTime < 0)
                     {
                         itmX.SubItems[1].Text = "Err";
                     }
                     itmX.SubItems[2].Text = pingResult.ResponseDetails;
                 }
             }
             catch (Exception ex)
             {
                 itmX.ImageIndex       = 2;
                 itmX.SubItems[1].Text = "Err";
                 itmX.SubItems[2].Text = ex.Message;
                 itmX.BackColor        = Color.Salmon;
             }
         }
         lvwEntries.EndUpdate();
         System.Windows.Forms.Cursor.Current = Cursors.Default;
         toolStripStatusLabelDetails.Text    = "Last updated " + DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss");
     }
     finally
     {
     }
 }
 private void cmdTestAddress_Click(object sender, EventArgs e)
 {
     try
     {
         PingCollectorResult result = RunPingTest();
         if (result.Success)
         {
             if (cboPingType.SelectedIndex == 1)
             {
                 try
                 {
                     string tempFileName = System.IO.Path.Combine(System.IO.Path.GetTempPath(), DateTime.Now.ToString("yyyyMMddHHmmss") + ".txt");
                     System.IO.File.WriteAllText(tempFileName, result.ResponseContent);
                     System.Diagnostics.Process p = new System.Diagnostics.Process();
                     p.StartInfo             = new System.Diagnostics.ProcessStartInfo("notepad.exe", tempFileName);
                     p.StartInfo.WindowStyle = System.Diagnostics.ProcessWindowStyle.Normal;
                     p.Start();
                     System.Threading.Thread.Sleep(1000);
                     System.IO.File.Delete(tempFileName);
                 }
                 catch { }
             }
             MessageBox.Show(string.Format("Test was successful\r\nPing time: {0}ms", result.PingTime), "Ping test", MessageBoxButtons.OK, MessageBoxIcon.Information);
         }
         else
         {
             MessageBox.Show("Test failed!\r\nResult: " + result.ResponseDetails, "Ping test", MessageBoxButtons.OK, MessageBoxIcon.Error);
         }
     }
     catch (Exception ex)
     {
         MessageBox.Show("Test failed!\r\nResult: " + ex.Message, "Ping test", MessageBoxButtons.OK, MessageBoxIcon.Error);
     }
 }
        public CollectorState GetState(PingCollectorResult pingResult)
        {
            CollectorState result = CollectorState.Good;

            if (pingResult.PingTime > -1)//  pingResult.Success)
            {
                if (pingResult.PingTime > TimeOutMS)
                {
                    result = CollectorState.Error;
                    pingResult.ResponseDetails = string.Format("Operation timed out! Max time allowed: {0}ms, {1}", TimeOutMS, pingResult.ResponseDetails);
                }
                else if (pingResult.PingTime > MaxTimeMS)
                {
                    result = CollectorState.Warning;
                    pingResult.ResponseDetails = string.Format("Operation did not finished in allowed time! Excepted time: {0}ms, {1}", MaxTimeMS, pingResult.ResponseDetails);
                }
                else
                {
                    result = CollectorState.Good;
                }
            }
            else
            {
                result = CollectorState.Error;
            }
            return(result);
        }
Beispiel #6
0
        public MonitorState GetCurrentState()
        {
            PingCollectorResult pingResult = Ping();

            CurrentAgentValue = pingResult;
            MonitorState currentState = new MonitorState()
            {
                ForAgent         = Address,
                CurrentValue     = pingResult.PingTime,
                CurrentValueUnit = "ms"
            };

            if (pingResult.PingTime > -1)
            {
                if (pingResult.PingTime > TimeOutMS)
                {
                    currentState.State      = CollectorState.Error;
                    currentState.RawDetails = string.Format("Operation timed out! Max time allowed: {0}ms, {1}", TimeOutMS, pingResult.ResponseDetails);
                }
                else if (pingResult.PingTime > MaxTimeMS)
                {
                    currentState.State      = CollectorState.Warning;
                    currentState.RawDetails = string.Format("Operation did not finished in allowed time! Excepted time: {0}ms, {1}", MaxTimeMS, pingResult.ResponseDetails);
                }
                else if (pingType == PingCollectorType.HTTP && HTMLContentContain != null && pingResult.ResponseContent.Trim().Length > 0 && HTMLContentContain.Trim().Length > 0 && !pingResult.ResponseContent.Contains(HTMLContentContain))
                {
                    currentState.State      = CollectorState.Warning;
                    currentState.RawDetails = string.Format("The returned HTML does not contain the specified string '{0}'", HTMLContentContain);
                }
                else
                {
                    currentState.State = CollectorState.Good;
                }
            }
            else
            {
                currentState.State = CollectorState.Error;
                if (pingResult.ResponseDetails == "No such host is known")
                {
                    currentState.CurrentValue     = "Host not found";
                    currentState.CurrentValueUnit = "";
                }
                currentState.RawDetails = pingResult.ResponseDetails;
            }

            return(currentState);
        }
Beispiel #7
0
 private void cmdTestAddress_Click(object sender, EventArgs e)
 {
     try
     {
         PingCollectorResult result = RunPingTest();
         if (result.Success)
         {
             MessageBox.Show(string.Format("Test was successful\r\nPing time: {0}ms", result.PingTime), "Ping test", MessageBoxButtons.OK, MessageBoxIcon.Information);
         }
         else
         {
             MessageBox.Show("Test failed!\r\nResult: " + result.ResponseDetails, "Ping test", MessageBoxButtons.OK, MessageBoxIcon.Error);
         }
     }
     catch (Exception ex)
     {
         MessageBox.Show("Test failed!\r\nResult: " + ex.Message, "Ping test", MessageBoxButtons.OK, MessageBoxIcon.Error);
     }
 }
Beispiel #8
0
        public PingCollectorResult Ping()
        {
            PingCollectorResult result = new PingCollectorResult();

            if (pingType == PingCollectorType.Ping)
            {
                result = PingICMP();
            }
            else if (pingType == PingCollectorType.HTTP)
            {
                result = PingHTTP();
            }
            else
            {
                result = PingSocket();
            }

            LastPingResult = result;
            return(result);
        }
        private PingCollectorResult RunPingTestWithPrompt()
        {
            PingCollectorResult result = new PingCollectorResult();

            try
            {
                result = RunPingTest();
                if (!result.Success)
                {
                    throw new Exception(result.ResponseDetails);
                }
            }
            catch (Exception ex)
            {
                if (MessageBox.Show(string.Format("Test failed!\r\nResult: {0}\r\nAccept anyway?", ex.Message), "Ping test", MessageBoxButtons.YesNo, MessageBoxIcon.Exclamation) == DialogResult.Yes)
                {
                    result.Success = true;
                }
            }
            return(result);
        }
Beispiel #10
0
        private PingCollectorResult PingSocket()
        {
            PingCollectorResult result = new PingCollectorResult();

            result.Success         = false;
            result.PingTime        = -1;
            result.ResponseDetails = "";
            try
            {
                TcpClient tcpSocket = new TcpClient();
                Stopwatch sw        = new Stopwatch();
                string    s         = "";

                tcpSocket.ReceiveTimeout = receiveTimeOutMS;
                tcpSocket.SendTimeout    = sendTimeOutMS;
                sw.Start();
                tcpSocket.Connect(address, socketPort);
                if (UseTelnetLogin)
                {
                    //the following is a Telnet protocol login so other protocals probably won't work with this.
                    s = Read(tcpSocket);
                    if (!s.TrimEnd().EndsWith(":"))
                    {
                        throw new Exception("Failed to connect : no login prompt");
                    }
                    WriteLine(tcpSocket, TelnetUserName);
                    s += Read(tcpSocket);
                    if (!s.TrimEnd().EndsWith(":"))
                    {
                        throw new Exception("Failed to connect : no password prompt");
                    }
                    WriteLine(tcpSocket, TelnetPassword);

                    s += Read(tcpSocket);
                }
                Write(tcpSocket, SocketPingMsgBody);
                s = Read(tcpSocket); // not doing anything with response
                sw.Stop();
                try
                {
                    if (tcpSocket != null)
                    {
                        tcpSocket.Close();
                    }
                    tcpSocket = null;
                }
                catch { }
                result.PingTime        = (int)sw.ElapsedMilliseconds;
                result.ResponseDetails = "Success";
                result.Success         = true;
            }
            catch (Exception ex)
            {
                result.Success  = false;
                result.PingTime = -1;
                if (ex.InnerException != null)
                {
                    result.ResponseDetails = ex.InnerException.Message;
                }
                else
                {
                    result.ResponseDetails = ex.Message;
                }
            }
            return(result);
        }
Beispiel #11
0
        private PingCollectorResult PingHTTP()
        {
            PingCollectorResult result = new PingCollectorResult();
            string lastStep            = "[Create WebClientEx]";

            result.Success         = false;
            result.PingTime        = -1;
            result.ResponseDetails = "";
            try
            {
                lastStep = "[HTTPSSetup]";
                if (Address.ToLower().StartsWith("https://"))
                {
                    System.Net.ServicePointManager.Expect100Continue = true;
                    if (HttpsSecurityProtocol == "Tls")
                    {
                        System.Net.ServicePointManager.SecurityProtocol = System.Net.SecurityProtocolType.Tls;
                    }
                    else if (HttpsSecurityProtocol == "Tls11")
                    {
                        System.Net.ServicePointManager.SecurityProtocol = System.Net.SecurityProtocolType.Tls11;
                    }
                    else if (HttpsSecurityProtocol == "Tls12")
                    {
                        System.Net.ServicePointManager.SecurityProtocol = System.Net.SecurityProtocolType.Tls12;
                    }
                    else
                    {
                        System.Net.ServicePointManager.SecurityProtocol = System.Net.SecurityProtocolType.Ssl3;
                    }
                    //System.Net.ServicePointManager.SecurityProtocol = System.Net.SecurityProtocolType.Tls12;
                    if (IgnoreInvalidHTTPSCerts)
                    {
                        System.Net.ServicePointManager.ServerCertificateValidationCallback = delegate { return(true); }
                    }
                    ;
                    else
                    {
                        System.Net.ServicePointManager.ServerCertificateValidationCallback += ValidateRemoteCertificate;
                    }
                }

                Stopwatch sw = new Stopwatch();
                using (WebClientEx wc = new WebClientEx())
                {
                    wc.Timeout = (TimeOutMS * 1000);
                    if (HttpProxyServer.Length > 0)
                    {
                        System.Net.WebProxy     proxy       = null;
                        System.Net.ICredentials credentials = null;
                        if (HttpProxyUserName.Length == 0)
                        {
                            credentials = System.Net.CredentialCache.DefaultNetworkCredentials;
                            proxy       = new System.Net.WebProxy(HttpProxyServer, true, null, credentials);
                            proxy.UseDefaultCredentials = true;
                        }
                        else
                        {
                            if (HttpProxyUserName.Contains('\\'))
                            {
                                string domain   = HttpProxyUserName.Split('\\')[0];
                                string userName = HttpProxyUserName.Split('\\')[1];
                                credentials = new System.Net.NetworkCredential(userName, HttpProxyPassword, domain);
                            }
                            else
                            {
                                credentials = new System.Net.NetworkCredential(HttpProxyUserName, HttpProxyPassword);
                            }
                            proxy = new System.Net.WebProxy(HttpProxyServer, true, null, credentials);
                            proxy.UseDefaultCredentials = false;
                            proxy.Credentials           = credentials;
                        }
                        wc.Proxy = proxy;
                    }
                    else
                    {
                        wc.Proxy = null;
                    }
                    wc.CachePolicy = new System.Net.Cache.RequestCachePolicy(System.Net.Cache.RequestCacheLevel.BypassCache);

                    if (HttpHeaderUserName.Trim().Length > 0)
                    {
                        wc.UseDefaultCredentials = false;
                        wc.Credentials           = new System.Net.NetworkCredential(HttpHeaderUserName, HttpHeaderPassword);
                    }
                    else
                    {
                        wc.UseDefaultCredentials = true;
                    }

                    sw.Start();
                    lastStep = "[OpenRead]";
                    using (System.IO.Stream webRequest = wc.OpenRead(Address))
                    {
                        int           chars       = 0;
                        StringBuilder docContents = new StringBuilder();
                        lastStep = "[CanRead]";
                        if (webRequest.CanRead)
                        {
                            lastStep = "[ReadByte]";
                            int readByte = webRequest.ReadByte();
                            while (readByte != -1) // && chars < 256)
                            {
                                chars++;
                                docContents.Append(Char.ConvertFromUtf32(readByte));
                                readByte = webRequest.ReadByte();

                                if (sw.ElapsedMilliseconds > TimeOutMS)
                                {
                                    break;
                                }
                            }
                            if (chars > 1)
                            {
                                result.ResponseContent = docContents.ToString();
                                result.ResponseDetails = "Characters returned:" + chars.ToString();
                            }
                        }
                        else
                        {
                            throw new Exception("Could not read web request stream");
                        }
                    }
                    sw.Stop();
                }
                result.PingTime = (int)sw.ElapsedMilliseconds;
                if (sw.ElapsedMilliseconds < TimeOutMS)
                {
                    result.Success = true;
                }
                else
                {
                    result.Success = false;
                }
            }
            catch (Exception ex)
            {
                result.Success  = false;
                result.PingTime = -1;

                if (ex is System.Net.WebException)
                {
                    if (((System.Net.WebException)ex).Response != null && ((System.Net.WebException)ex).Response is System.Net.HttpWebResponse)
                    {
                        System.Net.HttpWebResponse httpResp = ((System.Net.HttpWebResponse)((System.Net.WebException)ex).Response);
                        if (httpResp.StatusCode == System.Net.HttpStatusCode.Unauthorized)
                        {
                            result.ResponseDetails = string.Format("The URL '{0}' requires authorization to connect - i.e. Username/Password", Address);
                        }
                        else
                        {
                            result.ResponseDetails = string.Format("The URL '{0}' returned an HTTP error: {1}", httpResp);
                        }
                    }
                    else
                    {
                        result.ResponseDetails = lastStep + " " + ex.Message;
                    }
                }
                else
                {
                    if (ex.InnerException != null)
                    {
                        result.ResponseDetails = lastStep + " " + ex.InnerException.Message;
                    }
                    else
                    {
                        result.ResponseDetails = lastStep + " " + ex.Message;
                    }
                }
            }
            return(result);
        }
Beispiel #12
0
        private PingCollectorResult PingICMP()
        {
            PingCollectorResult result = new PingCollectorResult();

            result.Success         = false;
            result.PingTime        = -1;
            result.ResponseDetails = "";
            try
            {
                if (Address.ToLower() == "localhost" || Address.ToLower() == System.Net.Dns.GetHostName().ToLower())
                {
                    System.Net.IPHostEntry host;
                    host = System.Net.Dns.GetHostEntry(System.Net.Dns.GetHostName());
                    foreach (System.Net.IPAddress ip in host.AddressList)
                    {
                        if (ip.AddressFamily == AddressFamily.InterNetwork)
                        {
                            result.ResponseDetails = ip.ToString();
                            result.PingTime        = 0;
                            result.Success         = true;
                            break;
                        }
                    }
                }
                else
                {
                    using (System.Net.NetworkInformation.Ping ping = new System.Net.NetworkInformation.Ping())
                    {
                        System.Net.NetworkInformation.PingReply reply = ping.Send(Address, TimeOutMS);
                        if (reply.Status == System.Net.NetworkInformation.IPStatus.Success)
                        {
                            result.PingTime = Convert.ToInt32(reply.RoundtripTime);
                            result.Success  = true;
                            if (reply.Address != null)
                            {
                                result.ResponseDetails = reply.Address.ToString();
                            }
                        }
                        else // if (reply.Status == System.Net.NetworkInformation.IPStatus.TimedOut)
                        {
                            result.Success         = false;
                            result.PingTime        = -1;
                            result.ResponseDetails = reply.Status.ToString();
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                result.Success  = false;
                result.PingTime = -1;
                if (ex.InnerException != null)
                {
                    result.ResponseDetails = ex.InnerException.Message;
                }
                else
                {
                    result.ResponseDetails = ex.Message;
                }
            }

            return(result);
        }
Beispiel #13
0
        public override MonitorState RefreshState()
        {
            MonitorState returnState   = new MonitorState();
            string       lastAction    = "";
            long         pingTotalTime = 0;
            int          errors        = 0;
            int          warnings      = 0;
            int          success       = 0;

            try
            {
                PingCollectorConfig currentConfig = (PingCollectorConfig)AgentConfig;
                returnState.RawDetails  = string.Format("Pinging {0} entries", currentConfig.Entries.Count);
                returnState.HtmlDetails = string.Format("<b>Pinging {0} entries</b>", currentConfig.Entries.Count);
                foreach (PingCollectorHostEntry host in currentConfig.Entries)
                {
                    PingCollectorResult pingResult   = host.Ping();
                    CollectorState      currentState = host.GetState(pingResult);
                    if (pingResult.Success)
                    {
                        pingTotalTime += pingResult.PingTime;
                        if (currentState == CollectorState.Error)
                        {
                            errors++;
                            returnState.ChildStates.Add(
                                new MonitorState()
                            {
                                ForAgent     = host.Address,
                                State        = CollectorState.Error,
                                CurrentValue = pingResult.PingTime,
                                RawDetails   = string.Format("Response details : '{0}'", pingResult.ResponseDetails)
                            });
                        }
                        else if (currentState == CollectorState.Warning)
                        {
                            warnings++;
                            returnState.ChildStates.Add(
                                new MonitorState()
                            {
                                ForAgent     = host.Address,
                                State        = CollectorState.Warning,
                                CurrentValue = pingResult.PingTime,
                                RawDetails   = string.Format("Response details : '{0}'", pingResult.ResponseDetails)
                            });
                        }
                        else
                        {
                            success++;
                            returnState.ChildStates.Add(
                                new MonitorState()
                            {
                                ForAgent     = host.Address,
                                State        = CollectorState.Good,
                                CurrentValue = pingResult.PingTime,
                                RawDetails   = string.Format("Response details : '{0}'", pingResult.ResponseDetails)
                            });
                        }
                    }
                    else
                    {
                        errors++;
                        returnState.ChildStates.Add(
                            new MonitorState()
                        {
                            ForAgent     = host.Address,
                            State        = CollectorState.Error,
                            CurrentValue = "",
                            RawDetails   = string.Format("Response details : '{0}'", pingResult.ResponseDetails)
                        });
                    }
                }
                returnState.CurrentValue = pingTotalTime;

                if (errors > 0 && warnings == 0 && success == 0) // any errors
                {
                    returnState.State = CollectorState.Error;
                }
                else if (errors > 0 || warnings > 0) //any warnings
                {
                    returnState.State = CollectorState.Warning;
                }
                else
                {
                    returnState.State = CollectorState.Good;
                }
            }
            catch (Exception ex)
            {
                returnState.RawDetails  = ex.Message;
                returnState.HtmlDetails = string.Format("<p><b>Last action:</b> {0}</p><blockquote>{1}</blockquote>", lastAction, ex.Message);
                returnState.State       = CollectorState.Error;
            }
            return(returnState);
        }
        private PingCollectorResult PingHTTP()
        {
            PingCollectorResult result = new PingCollectorResult();
            string lastStep            = "[Create WebClientEx]";

            result.Success         = false;
            result.PingTime        = -1;
            result.ResponseDetails = "";
            try
            {
                lastStep = "[HTTPSSetup]";
                if (Address.ToLower().StartsWith("https://"))
                {
                    System.Net.ServicePointManager.Expect100Continue = true;
                    System.Net.ServicePointManager.SecurityProtocol  = System.Net.SecurityProtocolType.Ssl3;
                    if (IgnoreInvalidHTTPSCerts)
                    {
                        System.Net.ServicePointManager.ServerCertificateValidationCallback = delegate { return(true); }
                    }
                    ;
                    else
                    {
                        System.Net.ServicePointManager.ServerCertificateValidationCallback += ValidateRemoteCertificate; // = delegate { return true; };
                    }
                }

                Stopwatch sw = new Stopwatch();
                using (WebClientEx wc = new WebClientEx())
                {
                    wc.Timeout = (TimeOutMS * 1000);
                    wc.UseDefaultCredentials = true;
                    if (HttpProxyServer.Length > 0)
                    {
                        wc.Proxy             = new System.Net.WebProxy(HttpProxyServer);
                        wc.Proxy.Credentials = System.Net.CredentialCache.DefaultNetworkCredentials;
                    }
                    else
                    {
                        wc.Proxy = null;
                    }
                    wc.CachePolicy = new System.Net.Cache.RequestCachePolicy(System.Net.Cache.RequestCacheLevel.BypassCache);
                    sw.Start();

                    lastStep = "[OpenRead]";
                    using (System.IO.Stream webRequest = wc.OpenRead(Address))
                    {
                        int chars = 0;
                        lastStep = "[CanRead]";
                        if (webRequest.CanRead)
                        {
                            lastStep = "[ReadByte]";
                            int readByte = webRequest.ReadByte();
                            while (readByte != -1) // && chars < 256)
                            {
                                readByte = webRequest.ReadByte();
                                chars++;
                                if (sw.ElapsedMilliseconds > TimeOutMS)
                                {
                                    break;
                                }
                            }
                            result.ResponseDetails = "Characters returned:" + chars.ToString();
                        }
                        else
                        {
                            throw new Exception("Could not read web request stream");
                        }
                    }
                    sw.Stop();
                }
                result.PingTime = (int)sw.ElapsedMilliseconds;
                if (sw.ElapsedMilliseconds < TimeOutMS)
                {
                    result.Success = true;
                }
                else
                {
                    result.Success         = false;
                    result.ResponseDetails = "Operation timed out!\r\n" + result.ResponseDetails;
                }
            }
            catch (Exception ex)
            {
                result.Success  = false;
                result.PingTime = -1;
                if (ex.InnerException != null)
                {
                    result.ResponseDetails = lastStep + " " + ex.InnerException.Message;
                }
                else
                {
                    result.ResponseDetails = lastStep + " " + ex.Message;
                }
            }
            return(result);
        }
Beispiel #15
0
        public override MonitorState GetState()
        {
            MonitorState returnState = new MonitorState();
            StringBuilder plainTextDetails = new StringBuilder();
            StringBuilder htmlTextTextDetails = new StringBuilder();
            string lastAction = "";
            long pingTotalTime = 0;
            int errors = 0;
            int warnings = 0;
            int success = 0;            
            
            try
			{
                PingCollectorConfig currentConfig = (PingCollectorConfig)AgentConfig;
                plainTextDetails.AppendLine(string.Format("Pinging {0} entries", currentConfig.Entries.Count));
                htmlTextTextDetails.AppendLine(string.Format("<b>Pinging {0} entries</b>", currentConfig.Entries.Count));
                htmlTextTextDetails.AppendLine("<ul>");
				foreach (PingCollectorHostEntry host in currentConfig.Entries)
				{
                    PingCollectorResult pingResult = host.Ping();
                    CollectorState currentState = host.GetState(pingResult);
                    if (pingResult.Success)
                    {
                        pingTotalTime += pingResult.PingTime;
                        if (currentState == CollectorState.Error)
                        {
                            errors++;
                            plainTextDetails.AppendLine(string.Format("\t{0} (Error) - {1} ", host.Address, pingResult.ResponseDetails));
                            htmlTextTextDetails.AppendLine(string.Format("<li>{0} (<b>Error</b>) - {1}</li>", host.Address, pingResult.ResponseDetails));
                        }
                        else if (currentState == CollectorState.Warning)
                        {
                            warnings++;
                            plainTextDetails.AppendLine(string.Format("\t{0} (Warning) - {1}ms - {2}", host.Address, pingResult.PingTime, pingResult.ResponseDetails));
                            htmlTextTextDetails.AppendLine(string.Format("<li>{0} (<b>Warning</b>) - {1}ms - {2}</li>", host.Address, pingResult.PingTime, pingResult.ResponseDetails));
                        }
                        else
                        {
                            success++;
                            plainTextDetails.AppendLine(string.Format("\t{0} (Success) - {1}ms - {2}", host.Address, pingResult.PingTime, pingResult.ResponseDetails));
                            htmlTextTextDetails.AppendLine(string.Format("<li>{0} (<b>Success</b>) - {1}ms - {2}</li>", host.Address, pingResult.PingTime, pingResult.ResponseDetails));
                        }
                    }
                    else
                    {
                        errors++;
                        plainTextDetails.AppendLine(string.Format("\t{0} (Error)- {1}", host.Address, pingResult.ResponseDetails));
                        htmlTextTextDetails.AppendLine(string.Format("<li>{0} (<b>Error</b>) - {1}</li>", host.Address, pingResult.ResponseDetails));
                    }  
                }
                htmlTextTextDetails.AppendLine("</ul>");
                returnState.RawDetails = plainTextDetails.ToString().TrimEnd('\r', '\n');
                returnState.HtmlDetails = htmlTextTextDetails.ToString();
				returnState.CurrentValue = pingTotalTime;

                if (errors > 0) // any errors
                    returnState.State = CollectorState.Error;
                else if (warnings > 0) //any warnings
                    returnState.State = CollectorState.Warning;
                else
                    returnState.State = CollectorState.Good;
            }
            catch (Exception ex)
            {
                returnState.RawDetails = ex.Message;
                returnState.HtmlDetails = string.Format("<p><b>Last action:</b> {0}</p><blockquote>{1}</blockquote>", lastAction, ex.Message);
                returnState.State = CollectorState.Error;
            }	
            
            return returnState;
        }