Ejemplo n.º 1
0
        public override MonitorStates GetState()
        {
            MonitorStates    returnState = MonitorStates.Good;
            CollectorMessage details     = new CollectorMessage();

            LastDetailMsg.HtmlText  = "";
            LastDetailMsg.PlainText = "Getting Ports and Orchestration states and counts";
            LastError    = 0;
            LastErrorMsg = "";
            try
            {
                LastDetailMsg.PlainText = "Getting Receive Location count";
                int receiveLocationCount = BizTalkGroup.AllReceiveLocations ? BizTalkGroup.GetTotalReceiveLocationCount() : BizTalkGroup.ReceiveLocations.Count;
                LastDetailMsg.PlainText = "Getting Disabled Receive Location count";
                int receiveLocationsDisabled = BizTalkGroup.AllReceiveLocations ? BizTalkGroup.GetDisabledReceiveLocationCount(new List <string>()) : BizTalkGroup.GetDisabledReceiveLocationCount(BizTalkGroup.ReceiveLocations);
                //Now check send ports
                LastDetailMsg.PlainText = "Getting Send Port count";
                int sendPortCount = BizTalkGroup.AllSendPorts ? BizTalkGroup.GetTotalSendPortCount() : BizTalkGroup.SendPorts.Count;
                LastDetailMsg.PlainText = "Getting Stopped Send Port count";
                int sendPortStoppedCount = BizTalkGroup.AllSendPorts ? BizTalkGroup.GetStoppedSendPortCount(new List <string>()) : BizTalkGroup.GetStoppedSendPortCount(BizTalkGroup.SendPorts);
                //Now check orchestrations
                LastDetailMsg.PlainText = "Getting Orchestration count";
                int orchestrationCount = BizTalkGroup.AllOrchestrations ? BizTalkGroup.GetTotalOrchestrationCount() : BizTalkGroup.Orchestrations.Count;
                LastDetailMsg.PlainText = "Getting Stopped Orchestration count";
                int orchestrationStoppedCount = BizTalkGroup.AllOrchestrations ? BizTalkGroup.GetStoppedOrchestrationCount(new List <string>()) : BizTalkGroup.GetStoppedOrchestrationCount(BizTalkGroup.Orchestrations);

                if (receiveLocationsDisabled == -1 || sendPortStoppedCount == -1 || orchestrationStoppedCount == -1)
                {
                    returnState       = MonitorStates.Error;
                    details.PlainText = "An error occured trying to query the BizTalk Management database!";
                    details.HtmlText  = "<blockquote>An error occured trying to query the BizTalk Management database!</blockquote>";
                }
                else
                {
                    if ((receiveLocationsDisabled >= receiveLocationCount && (receiveLocationCount > 0)) ||
                        (sendPortStoppedCount >= sendPortCount && (sendPortCount > 0)) ||
                        (orchestrationStoppedCount >= orchestrationCount && (orchestrationCount > 0)))
                    {
                        returnState = MonitorStates.Error;
                    }
                    else if (receiveLocationsDisabled > 0 || sendPortStoppedCount > 0 || orchestrationStoppedCount > 0)
                    {
                        returnState = MonitorStates.Warning;
                    }
                    details.PlainText = "Getting summary of current states";
                    details           = GetSummaryOfDisabledOrStopped();
                }
                LastDetailMsg = details;
            }
            catch (Exception ex)
            {
                LastError               = 1;
                LastErrorMsg            = ex.Message;
                LastDetailMsg.PlainText = string.Format("Last step: {0}\r\n{1}", LastDetailMsg.PlainText, ex.Message);
                LastDetailMsg.HtmlText  = string.Format("<blockquote>Last step: {0}<br />{1}</blockquote>", LastDetailMsg.PlainText, ex.Message);

                returnState = MonitorStates.Error;
            }
            return(returnState);
        }
Ejemplo n.º 2
0
        private void SendNotifierAlert(AlertLevel alertLevel, DetailLevel detailLevel,
                                       string collectorType, string collectorName, MonitorStates oldState, MonitorStates currentState, CollectorMessage details)
        {
            Stopwatch sw = new Stopwatch();

            sw.Start();
            foreach (NotifierEntry notifierEntry in (from n in Notifiers
                                                     where n.Enabled && (int)n.AlertLevel <= (int)alertLevel &&
                                                     (detailLevel == DetailLevel.All || detailLevel == n.DetailLevel) &&
                                                     (n.AlertForCollectors.Count == 0 || n.AlertForCollectors.Contains(collectorName))
                                                     select n))
            {
                try
                {
                    PCRaiseNotifiersCalled();
                    notifierEntry.Notifier.RecordMessage(alertLevel, collectorType, collectorName, oldState, currentState, details);
                }
                catch (Exception ex)
                {
                    RaiseRaiseNotifierError(notifierEntry, ex.ToString());
                }
            }
            sw.Stop();
            PCSetNotifiersSendTime(sw.ElapsedMilliseconds);
        }
Ejemplo n.º 3
0
        private void cmdTest_Click(object sender, EventArgs e)
        {
            if (DoValidate())
            {
                string lastStep = "Initialize values";
                try
                {
                    Cursor.Current = Cursors.WaitCursor;
                    RegistryQueryInstance testQueryInstance = new RegistryQueryInstance();
                    testQueryInstance.Name                   = txtName.Text;
                    testQueryInstance.UseRemoteServer        = chkUseRemoteServer.Checked;
                    testQueryInstance.Server                 = txtServer.Text;
                    testQueryInstance.Path                   = txtPath.Text;
                    testQueryInstance.KeyName                = txtKey.Text;
                    testQueryInstance.ExpandEnvironmentNames = chkExpandEnvNames.Checked;
                    testQueryInstance.RegistryHive           = RegistryQueryInstance.GetRegistryHiveFromString(cboRegistryHive.Text);

                    if (!chkValueIsANumber.Checked)
                    {
                        testQueryInstance.ReturnValueIsNumber = false;
                        testQueryInstance.ReturnValueInARange = false;
                        testQueryInstance.ReturnValueInverted = false;
                    }
                    else
                    {
                        testQueryInstance.ReturnValueIsNumber = true;
                        testQueryInstance.ReturnValueInARange = chkValueIsInARange.Checked;
                        testQueryInstance.ReturnValueInverted = !chkReturnValueNotInverted.Checked;
                    }

                    testQueryInstance.SuccessValue = cboSuccessValue.Text;
                    testQueryInstance.WarningValue = cboWarningValue.Text;
                    testQueryInstance.ErrorValue   = cboErrorValue.Text;

                    object returnValue = null;
                    returnValue = testQueryInstance.GetValue();
                    MonitorStates state = testQueryInstance.EvaluateValue(returnValue);
                    if (state == MonitorStates.Good)
                    {
                        MessageBox.Show(string.Format("Success!\r\nValue return: {0}", returnValue), "Test", MessageBoxButtons.OK, MessageBoxIcon.Information);
                    }
                    else if (state == MonitorStates.Warning)
                    {
                        MessageBox.Show(string.Format("Warning!\r\nValue return: {0}", returnValue), "Test", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                    }
                    else
                    {
                        MessageBox.Show(string.Format("Error!\r\nValue return: {0}", returnValue), "Test", MessageBoxButtons.OK, MessageBoxIcon.Error);
                    }
                }
                catch (Exception ex)
                {
                    MessageBox.Show(string.Format("Failed!\r\nLast step: {0}\r\n{1}", lastStep, ex.Message), "Test", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
                }
                finally
                {
                    Cursor.Current = Cursors.Default;
                }
            }
        }
Ejemplo n.º 4
0
 private void SetTreeNodeState(TreeNode treeNode, CollectorEntry collector, MonitorStates currentState)
 {
     if (currentState == MonitorStates.Disabled || currentState == MonitorStates.NotAvailable)
     {
         treeNode.ImageIndex         = 1;
         treeNode.SelectedImageIndex = 1;
     }
     else if (currentState == MonitorStates.Good)
     {
         treeNode.ImageIndex         = 2;
         treeNode.SelectedImageIndex = 2;
         PCRaiseCollectorSuccessState();
     }
     else if (currentState == MonitorStates.Warning)
     {
         treeNode.ImageIndex         = 3;
         treeNode.SelectedImageIndex = 3;
         PCRaiseCollectorWarningState();
     }
     else
     {
         treeNode.ImageIndex         = 4;
         treeNode.SelectedImageIndex = 4;
         PCRaiseCollectorErrorState();
     }
     if (collector.Enabled)
     {
         treeNode.ForeColor = SystemColors.WindowText;
     }
     else
     {
         treeNode.ForeColor = Color.Gray;
     }
 }
Ejemplo n.º 5
0
        public MonitorStates GetState(PingResult pingResult)
        {
            MonitorStates result = MonitorStates.Good;

            if (pingResult.Success)
            {
                if (pingResult.PingTime > TimeOut)
                {
                    result = MonitorStates.Error;
                }
                else if (pingResult.PingTime > MaxTime)
                {
                    result = MonitorStates.Warning;
                }
                else
                {
                    result = MonitorStates.Good;
                }
            }
            else
            {
                result = MonitorStates.Error;
            }
            return(result);
        }
Ejemplo n.º 6
0
        public MonitorStates GetState(float value)
        {
            MonitorStates state = MonitorStates.Good;

            if (!ReturnValueInverted)
            {
                if (ErrorValue <= value)
                {
                    state = MonitorStates.Error;
                }
                else if (WarningValue <= value)
                {
                    state = MonitorStates.Warning;
                }
            }
            else
            {
                if (ErrorValue >= value)
                {
                    state = MonitorStates.Error;
                }
                else if (WarningValue >= value)
                {
                    state = MonitorStates.Warning;
                }
            }
            return(state);
        }
Ejemplo n.º 7
0
        private string GetQIValue(ListViewItem lvi, WMIConfigEntry wmiConfigEntry)
        {
            string results = "";

            try
            {
                object        value        = wmiConfigEntry.RunQuery();
                MonitorStates currentstate = wmiConfigEntry.GetState(value);

                results = FormatUtils.N(value, "[null]");
                if (currentstate == MonitorStates.Error)
                {
                    lvi.ImageIndex = 3;
                }
                else if (currentstate == MonitorStates.Warning)
                {
                    lvi.ImageIndex = 2;
                }
                else
                {
                    lvi.ImageIndex = 1;
                }
            }
            catch (Exception ex)
            {
                results = ex.Message;
            }
            return(results);
        }
Ejemplo n.º 8
0
 private void disablePollingToolStripMenuItem_Click(object sender, EventArgs e)
 {
     monitorPack.Enabled = !monitorPack.Enabled;
     SetEnableDisablePolling();
     UpdateAppTitle();
     if (!monitorPack.Enabled)
     {
         globalState = MonitorStates.Disabled;
     }
     UpdateAppIcon();
 }
Ejemplo n.º 9
0
        public override MonitorStates GetState()
        {
            MonitorStates returnState = MonitorStates.Good;

            LastDetailMsg.PlainText = "";
            LastDetailMsg.HtmlText  = "";
            int instancesSuspended = 0;

            LastDetailMsg.PlainText = "Getting service states";
            LastError    = 0;
            LastErrorMsg = "";
            try
            {
                instancesSuspended = BizTalkGroup.GetSuspendedMsgsCount();
                if (instancesSuspended < BizTalkGroup.InstancesWarning)
                {
                    returnState = MonitorStates.Good;
                }
                else if (instancesSuspended >= BizTalkGroup.InstancesError)
                {
                    returnState = MonitorStates.Error;
                }
                else
                {
                    returnState = MonitorStates.Warning;
                }
                if (instancesSuspended > 0)
                {
                    LastDetailMsg.PlainText = string.Format("Total suspended count: {0}\r\n", instancesSuspended);
                    LastDetailMsg.HtmlText  = string.Format("<b>Total suspended count:</b> {0}<hr />\r\n", instancesSuspended);

                    if (returnState != MonitorStates.Good && BizTalkGroup.ShowLastXDetails > 0)
                    {
                        LastDetailMsg.AppendCollectorMessage(BizTalkGroup.GetLastXDetails());
                    }
                }
                else
                {
                    LastDetailMsg.PlainText = "No suspended instances";
                    LastDetailMsg.HtmlText  = "No suspended instances";
                }
            }
            catch (Exception ex)
            {
                LastError               = 1;
                LastErrorMsg            = ex.Message;
                LastDetailMsg.PlainText = ex.Message;
                LastDetailMsg.HtmlText  = string.Format("<blockquote>{0}</blockquote>", ex.Message);

                returnState = MonitorStates.Error;
            }
            return(returnState);
        }
Ejemplo n.º 10
0
 private void RefreshList()
 {
     System.Windows.Forms.Cursor.Current = Cursors.WaitCursor;
     lvwHosts.BeginUpdate();
     foreach (ListViewItem itmX in lvwHosts.Items)
     {
         HostEntry host = (HostEntry)itmX.Tag;
         try
         {
             PingResult    pingResult = host.Ping();
             MonitorStates result     = host.GetState(pingResult);
             if (pingResult.Success)
             {
                 itmX.SubItems[1].Text = pingResult.PingTime.ToString();
                 itmX.SubItems[2].Text = pingResult.LastErrorMsg;
                 if (result == MonitorStates.Good)
                 {
                     itmX.ImageIndex = 0;
                     itmX.BackColor  = SystemColors.Window;
                 }
                 else if (result == MonitorStates.Warning)
                 {
                     itmX.ImageIndex = 1;
                     itmX.BackColor  = Color.SandyBrown;
                 }
                 else
                 {
                     itmX.ImageIndex = 2;
                     itmX.BackColor  = Color.Salmon;
                 }
             }
             else
             {
                 itmX.ImageIndex       = 2;
                 itmX.BackColor        = Color.Salmon;
                 itmX.SubItems[1].Text = "Err";
                 itmX.SubItems[2].Text = pingResult.LastErrorMsg;
             }
         }
         catch (Exception ex)
         {
             itmX.ImageIndex       = 2;
             itmX.SubItems[1].Text = "Err";
             itmX.SubItems[2].Text = ex.Message;
             itmX.BackColor        = Color.Salmon;
         }
     }
     lvwHosts.EndUpdate();
     System.Windows.Forms.Cursor.Current = Cursors.Default;
     toolStripStatusLabel1.Text          = "Last updated " + DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss");
 }
Ejemplo n.º 11
0
 private void monitorPack_RaiseCurrentState(CollectorEntry collector, MonitorStates currentState)
 {
     if (this.InvokeRequired)
     {
         this.Invoke((MethodInvoker) delegate
         {
             UpdateTreeNodeStates(collector, currentState);
         });
     }
     else
     {
         UpdateTreeNodeStates(collector, currentState);
     }
 }
Ejemplo n.º 12
0
 private void RaiseRaiseCurrentStateDelegate(CollectorEntry collector, MonitorStates currentState)
 {
     try
     {
         if (RaiseCurrentState != null)
         {
             RaiseCurrentState(collector, currentState);
         }
     }
     catch (Exception ex)
     {
         System.Diagnostics.Trace.WriteLine(string.Format("Error in RaiseRaiseCurrentStateDelegate: {0}", ex.Message));
     }
 }
Ejemplo n.º 13
0
        public MonitorStates GetState(DirectoryFileInfo fileInfo)
        {
            MonitorStates returnState = MonitorStates.Good;

            LastErrorMsg = "";
            if (!fileInfo.Exists)
            {
                returnState  = MonitorStates.Error;
                LastErrorMsg = string.Format("Directory '{0}' not found or not accessible!", DirectoryPath);
            }
            else if (DirectoryExistOnly)
            {
                returnState = MonitorStates.Good;
            }
            else if (fileInfo.FileCount == -1)
            {
                returnState  = MonitorStates.Error;
                LastErrorMsg = string.Format("An error occured while accessing '{0}'\r\n\t{1}", FilterFullPath, LastErrorMsg);
            }
            else
            {
                if (
                    (CountErrorIndicator > 0 && CountErrorIndicator <= fileInfo.FileCount) ||
                    (SizeKBErrorIndicator > 0 && SizeKBErrorIndicator * 1024 <= fileInfo.FileSize)
                    )
                {
                    returnState  = MonitorStates.Error;
                    LastErrorMsg = string.Format("Error state reached for '{0}': {1} file(s), {2}", FilterFullPath, fileInfo.FileCount, FormatUtils.FormatFileSize(fileInfo.FileSize));
                }
                else if (
                    (CountWarningIndicator > 0 && CountWarningIndicator <= fileInfo.FileCount) ||
                    (SizeKBWarningIndicator > 0 && SizeKBWarningIndicator * 1024 <= fileInfo.FileSize)
                    )
                {
                    returnState  = MonitorStates.Warning;
                    LastErrorMsg = string.Format("Warning state reached for '{0}': {1} file(s), {2}", FilterFullPath, fileInfo.FileCount, FormatUtils.FormatFileSize(fileInfo.FileSize));
                }
                else
                {
                    returnState = MonitorStates.Good;
                }
            }
            return(returnState);
        }
Ejemplo n.º 14
0
 private void RefreshList()
 {
     Cursor.Current = Cursors.WaitCursor;
     try
     {
         lvwPerfCounters.BeginUpdate();
         foreach (ListViewItem lvi in lvwPerfCounters.Items)
         {
             try
             {
                 QMPerfCounterInstance pc = (QMPerfCounterInstance)lvi.Tag;
                 float currentValue       = pc.GetNextValue();
                 lvi.SubItems[1].Text = currentValue.ToString("F3");
                 MonitorStates currentState = pc.GetState(currentValue);
                 if (currentState == MonitorStates.Good)
                 {
                     lvi.ImageIndex = 0;
                     lvi.BackColor  = SystemColors.Window;
                 }
                 else if (currentState == MonitorStates.Warning)
                 {
                     lvi.ImageIndex = 1;
                     lvi.BackColor  = Color.SandyBrown;
                 }
                 else
                 {
                     lvi.ImageIndex = 2;
                     lvi.BackColor  = Color.Salmon;
                 }
             }
             catch (Exception ex)
             {
                 lvi.SubItems[1].Text = ex.Message;
             }
         }
         toolStripStatusLabel1.Text = "Last updated: " + DateTime.Now.ToString("yyyy-mm-dd HH:mm:ss");
     }
     catch (Exception ex)
     {
         MessageBox.Show(ex.Message, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
     }
     lvwPerfCounters.EndUpdate();
     Cursor.Current = Cursors.Default;
 }
Ejemplo n.º 15
0
 private void SetChildCollectorStates(CollectorEntry collector, MonitorStates childState)
 {
     try
     {
         foreach (CollectorEntry childCollector in (from c in Collectors
                                                    where c.ParentCollectorId == collector.UniqueId
                                                    select c))
         {
             RaiseRaiseCurrentStateDelegate(childCollector, childState);
             childCollector.LastMonitorState = childState;
             SetChildCollectorStates(childCollector, childState);
         }
     }
     catch (Exception ex)
     {
         if (!ex.Message.Contains("Collection was modified; enumeration operation may not execute"))
         {
             throw;
         }
     }
 }
Ejemplo n.º 16
0
 private void UpdateTreeNodeStates(CollectorEntry collector, MonitorStates currentState)
 {
     try
     {
         Cursor.Current = Cursors.WaitCursor;
         //tvwCollectors.BeginUpdate();
         if (collector.Tag != null && collector.Tag is TreeNode)
         {
             SetTreeNodeState((TreeNode)collector.Tag, collector, currentState);
         }
         else //scan for the node (old way)
         {
             UpdateCollectorNode(tvwCollectors.Nodes[0], collector, currentState);
         }
     }
     catch (Exception ex)
     {
         toolStripStatusLabelStatus.Text = ex.Message;
     }
     finally
     {
         //tvwCollectors.EndUpdate();
     }
 }
Ejemplo n.º 17
0
        public override MonitorStates GetState()
        {
            MonitorStates returnState         = MonitorStates.Good;
            StringBuilder plainTextDetails    = new StringBuilder();
            StringBuilder htmlTextTextDetails = new StringBuilder();

            LastDetailMsg.PlainText = "Querying web service";
            LastDetailMsg.HtmlText  = "";
            int errors  = 0;
            int success = 0;

            try
            {
                plainTextDetails.AppendLine(string.Format("Calling {0} web service(s)", SoapWebServicePingConfig.Entries.Count));
                htmlTextTextDetails.AppendLine(string.Format("<b>Calling {0} web service(s)</b>", SoapWebServicePingConfig.Entries.Count));

                htmlTextTextDetails.AppendLine("<ul>");
                foreach (SoapWebServicePingConfigEntry soapWebServicePingConfigEntry in SoapWebServicePingConfig.Entries)
                {
                    try
                    {
                        plainTextDetails.Append(string.Format("\t\t{0} - ", soapWebServicePingConfigEntry.ServiceBaseURL));
                        htmlTextTextDetails.Append(string.Format("<li>{0} - ", soapWebServicePingConfigEntry.ServiceBaseURL));

                        object val              = soapWebServicePingConfigEntry.ExecuteMethod();
                        string formattedVal     = "";
                        bool   checkResultMatch = soapWebServicePingConfigEntry.CheckResultMatch(val, soapWebServicePingConfigEntry.ResultType, soapWebServicePingConfigEntry.CustomValue1, soapWebServicePingConfigEntry.CustomValue2, out formattedVal);
                        LastDetailMsg.LastValue = formattedVal;
                        if (checkResultMatch)
                        //(checkResultMatch && soapWebServicePingConfigEntry.CheckType == SoapWebServicePingCheckType.Success)
                        //||
                        //(!checkResultMatch && soapWebServicePingConfigEntry.CheckType == SoapWebServicePingCheckType.Failure)
                        //)
                        {
                            success++;
                            plainTextDetails.Append("Success - ");
                            htmlTextTextDetails.Append("<b>Success</b> - ");
                        }
                        else
                        {
                            errors++;
                            plainTextDetails.Append("Failure - ");
                            htmlTextTextDetails.Append("<b>Failure</b> - ");
                        }
                        switch (soapWebServicePingConfigEntry.ResultType)
                        {
                        case SoapWebServicePingResultEnum.CheckAvailabilityOnly:
                            plainTextDetails.Append("Available");
                            htmlTextTextDetails.Append("Available");
                            break;

                        case SoapWebServicePingResultEnum.NoValueOnly:
                            plainTextDetails.Append("No value returned");
                            htmlTextTextDetails.Append("No value returned");
                            break;

                        default:
                            plainTextDetails.Append(string.Format("Value:{0}", formattedVal));
                            htmlTextTextDetails.Append(string.Format("Value:{0}", formattedVal));
                            break;
                        }

                        plainTextDetails.AppendLine();
                        htmlTextTextDetails.AppendLine("</li>");
                    }
                    catch (Exception innerEx)
                    {
                        errors++;
                        plainTextDetails.AppendLine(string.Format("{0}\r\n{1}", soapWebServicePingConfigEntry.LastError, innerEx.Message));
                        htmlTextTextDetails.AppendLine(string.Format("{0}\r\n{1}", soapWebServicePingConfigEntry.LastError, innerEx.Message));
                    }
                }
                htmlTextTextDetails.AppendLine("</ul>");

                if (errors > 0 && success == 0) //are all errors
                {
                    returnState = MonitorStates.Error;
                }
                else if (errors > 0 && success > 0) //mixture
                {
                    returnState = MonitorStates.Warning;
                }
                LastDetailMsg.PlainText = plainTextDetails.ToString().TrimEnd('\r', '\n');
                LastDetailMsg.HtmlText  = htmlTextTextDetails.ToString();
            }
            catch (Exception ex)
            {
                LastError               = 1;
                LastErrorMsg            = ex.Message;
                LastDetailMsg.PlainText = string.Format("Last step: '{0}\r\n{1}", LastDetailMsg.PlainText, ex.Message);
                LastDetailMsg.HtmlText  = string.Format("<blockquote>Last step: '{0}<br />{1}</blockquote>", LastDetailMsg.PlainText, ex.Message);
                returnState             = MonitorStates.Error;
            }
            return(returnState);
        }
Ejemplo n.º 18
0
        //internal List<DatabaseEntry> Databases = new List<DatabaseEntry>();

        public override MonitorStates GetState()
        {
            MonitorStates returnState         = MonitorStates.Good;
            StringBuilder plainTextDetails    = new StringBuilder();
            StringBuilder htmlTextTextDetails = new StringBuilder();

            LastDetailMsg.PlainText = "";
            LastDetailMsg.HtmlText  = "";

            LastError    = 0;
            LastErrorMsg = "";
            int  errorCount   = 0;
            int  warningCount = 0;
            int  okCount      = 0;
            long totalSize    = 0;

            try
            {
                DatabaseSizeInfo databaseSizeInfo = new DatabaseSizeInfo();
                databaseSizeInfo.OpenConnection(DatabaseSizeConfig.SqlServer, DatabaseSizeConfig.IntegratedSec, DatabaseSizeConfig.UserName, DatabaseSizeConfig.Password, DatabaseSizeConfig.CmndTimeOut);

                htmlTextTextDetails.AppendLine("<ul>");
                foreach (DatabaseEntry dbEntry in DatabaseSizeConfig.Databases)
                {
                    long size = databaseSizeInfo.GetDatabaseSize(dbEntry.Name);
                    totalSize += size;
                    if (size >= (long)dbEntry.ErrorSizeMB)
                    {
                        errorCount++;
                        plainTextDetails.AppendLine(string.Format("Database {0} - Size {1}MB - Error (trigger {2}MB)", dbEntry.Name, size, dbEntry.ErrorSizeMB));
                        htmlTextTextDetails.AppendLine(string.Format("<li>Database {0} - Size {1}MB - <b>Error</b> (trigger {2}MB)</li>", dbEntry.Name, size, dbEntry.ErrorSizeMB));
                    }
                    else if (size >= (long)dbEntry.WarningSizeMB)
                    {
                        warningCount++;
                        plainTextDetails.AppendLine(string.Format("Database {0} - Size {1}MB - Warning (trigger {2}MB", dbEntry.Name, size, dbEntry.WarningSizeMB));
                        htmlTextTextDetails.AppendLine(string.Format("<li>Database {0} - Size {1}MB - <b>Warning</b> (trigger {2}MB)</li>", dbEntry.Name, size, dbEntry.WarningSizeMB));
                    }
                    else
                    {
                        okCount++;
                        plainTextDetails.AppendLine(string.Format("Database {0} - Size {1}MB", dbEntry.Name, size));
                        htmlTextTextDetails.AppendLine(string.Format("<li>Database {0} - Size {1}MB</li>", dbEntry.Name, size));
                    }
                }
                LastDetailMsg.LastValue = totalSize;
                htmlTextTextDetails.AppendLine("</ul>");

                databaseSizeInfo.CloseConnection();

                if (errorCount > 0)
                {
                    returnState = MonitorStates.Error;
                }
                else if (warningCount > 0)
                {
                    returnState = MonitorStates.Warning;
                }
                else
                {
                    returnState = MonitorStates.Good;
                }
                LastDetailMsg.PlainText = plainTextDetails.ToString().TrimEnd('\r', '\n');
                LastDetailMsg.HtmlText  = htmlTextTextDetails.ToString();
            }
            catch (Exception ex)
            {
                LastError               = 1;
                LastErrorMsg            = ex.Message;
                LastDetailMsg.PlainText = ex.Message;
                LastDetailMsg.HtmlText  = string.Format("<blockquote>{0}</blockquote>", ex.Message);

                returnState = MonitorStates.Error;
            }

            return(returnState);
        }
Ejemplo n.º 19
0
        public override MonitorStates GetState()
        {
            MonitorStates returnState = MonitorStates.Good;
            Stopwatch     sw          = new Stopwatch();

            StringBuilder plainTextDetails    = new StringBuilder();
            StringBuilder htmlTextTextDetails = new StringBuilder();
            string        lastAction          = "Getting service states";
            int           errorCount          = 0;
            int           okCount             = 0;

            LastDetailMsg.PlainText = "Getting service states";
            LastError    = 0;
            LastErrorMsg = "";
            try
            {
                foreach (ServiceStateDefinition machine in Services)
                {
                    List <string> runningServices    = new List <string>();
                    List <string> notRunningServices = new List <string>();
                    sw.Restart();
                    lastAction = "Getting service states on " + machine.MachineName;
                    ServiceController[] allServices = ServiceController.GetServices(machine.MachineName);
                    foreach (ServiceController srvc in (from s in allServices
                                                        where machine.Services.Contains(s.DisplayName)
                                                        select s))
                    {
                        lastAction = string.Format("Getting service state for {0}\\{1}", machine.MachineName, srvc.DisplayName);
                        if (srvc.Status == ServiceControllerStatus.Running)
                        {
                            okCount++;
                            runningServices.Add(srvc.DisplayName);
                        }
                        else
                        {
                            errorCount++;
                            notRunningServices.Add(string.Format("{0} ({1})", srvc.DisplayName, srvc.Status));
                        }
                    }
                    sw.Stop();
                    LastDetailMsg.LastValue = okCount;
                    plainTextDetails.AppendLine(string.Format("{0}", machine.MachineName));
                    htmlTextTextDetails.AppendLine(string.Format("<b>{0}</b><br /><blockquote>", machine.MachineName));
                    if (notRunningServices.Count > 0)
                    {
                        plainTextDetails.AppendLine("\tServices not running");
                        htmlTextTextDetails.AppendLine("Services not running<br /><ul>");
                        foreach (string item in notRunningServices)
                        {
                            plainTextDetails.AppendLine(string.Format("\t\t{0}", item));
                            htmlTextTextDetails.AppendLine(string.Format("<li>{0}</li>", item));
                        }
                        htmlTextTextDetails.AppendLine("</ul>");
                    }
                    if (runningServices.Count > 0)
                    {
                        plainTextDetails.AppendLine("\tServices running");
                        htmlTextTextDetails.AppendLine("Services running<br /><ul>");
                        foreach (string item in runningServices)
                        {
                            plainTextDetails.AppendLine(string.Format("\t\t{0}", item));
                            htmlTextTextDetails.AppendLine(string.Format("<li>{0}</li>", item));
                        }
                        htmlTextTextDetails.AppendLine("</ul>");
                    }
                    htmlTextTextDetails.AppendLine("</blockquote>");

#if DEBUG
                    Trace.WriteLine(string.Format("GetState - ServiceStates: {0} - {1}ms", machine.MachineName, sw.ElapsedMilliseconds));
#endif
                }
                if (okCount == 0 && errorCount > 0)
                {
                    returnState = MonitorStates.Error;
                }
                else if (okCount > 0 && errorCount > 0)
                {
                    returnState = MonitorStates.Warning;
                }

                LastDetailMsg.PlainText = plainTextDetails.ToString().TrimEnd('\r', '\n');
                LastDetailMsg.HtmlText  = htmlTextTextDetails.ToString();
                LastDetailMsg.LastValue = okCount;
            }
            catch (Exception ex)
            {
                LastError               = 1;
                LastErrorMsg            = ex.Message;
                LastDetailMsg.PlainText = ex.Message;
                LastDetailMsg.HtmlText  = string.Format("<p><b>Last action:</b> {0}</p><blockquote>{1}</blockquote>", lastAction, ex.Message);
                returnState             = MonitorStates.Error;
            }

            return(returnState);
        }
Ejemplo n.º 20
0
        internal MonitorStates GetState(object value)
        {
            MonitorStates currentState = MonitorStates.Good;

            if (value == null)
            {
                if (ErrorValue == "[null]")
                {
                    currentState = MonitorStates.Error;
                }
                else if (WarningValue == "[null]")
                {
                    currentState = MonitorStates.Warning;
                }
            }
            else //non null value
            {
                if (!ReturnValueIsInt)
                {
                    if (value.ToString() == ErrorValue)
                    {
                        currentState = MonitorStates.Error;
                    }
                    else if (value.ToString() == WarningValue)
                    {
                        currentState = MonitorStates.Warning;
                    }
                    else if (value.ToString() == SuccessValue || SuccessValue == "[any]")
                    {
                        currentState = MonitorStates.Good; //just to flag condition
                    }
                    else if (WarningValue == "[any]")
                    {
                        currentState = MonitorStates.Warning;
                    }
                    else if (ErrorValue == "[any]")
                    {
                        currentState = MonitorStates.Error;
                    }
                }
                else //now we know the value is not null and must be in a range
                {
                    if (!value.IsIntegerTypeNumber()) //value must be a number!
                    {
                        currentState = MonitorStates.Error;
                    }
                    else if (ErrorValue != "[any]" && ErrorValue != "[null]" &&
                             (
                                 (!ReturnValueInverted && decimal.Parse(value.ToString()) >= decimal.Parse(ErrorValue)) ||
                                 (ReturnValueInverted && decimal.Parse(value.ToString()) <= decimal.Parse(ErrorValue))
                             )
                             )
                    {
                        currentState = MonitorStates.Error;
                    }
                    else if (WarningValue != "[any]" && WarningValue != "[null]" &&
                             (
                                 (!ReturnValueInverted && decimal.Parse(value.ToString()) >= decimal.Parse(WarningValue)) ||
                                 (ReturnValueInverted && decimal.Parse(value.ToString()) <= decimal.Parse(WarningValue))
                             )
                             )
                    {
                        currentState = MonitorStates.Warning;
                    }
                }
            }
            return(currentState);
        }
Ejemplo n.º 21
0
        public override MonitorStates GetState()
        {
            MonitorStates returnState         = MonitorStates.Good;
            StringBuilder plainTextDetails    = new StringBuilder();
            StringBuilder htmlTextTextDetails = new StringBuilder();

            LastDetailMsg.PlainText = "Getting file details";
            LastDetailMsg.HtmlText  = "Getting file details";
            LastError    = 0;
            LastErrorMsg = "";

            int errorCount     = 0;
            int warningCount   = 0;
            int okCount        = 0;
            int totalFileCount = 0;

            try
            {
                htmlTextTextDetails.AppendLine("<ul>");
                foreach (DirectoryFilterEntry directoryFilter in DirectorieFilters)
                {
                    DirectoryFileInfo directoryFileInfo = directoryFilter.GetDirFileInfo();
                    MonitorStates     currentState      = directoryFilter.GetState(directoryFileInfo);

                    if (directoryFilter.DirectoryExistOnly && currentState != MonitorStates.Good)
                    {
                        errorCount++;
                        plainTextDetails.AppendLine(directoryFilter.LastErrorMsg);
                        htmlTextTextDetails.AppendLine("<li>" + directoryFilter.LastErrorMsg + "</li>");
                    }
                    else if (!directoryFilter.DirectoryExistOnly)
                    {
                        if (directoryFileInfo.FileCount == -1)
                        {
                            errorCount++;
                            plainTextDetails.AppendLine(string.Format("An error occured while accessing '{0}'\r\n\t{1}", directoryFilter.FilterFullPath, directoryFilter.LastErrorMsg));
                            htmlTextTextDetails.AppendLine(string.Format("<li>'{0}' - Error accessing files<blockquote>{1}</blockquote></li>", directoryFilter.FilterFullPath, directoryFilter.LastErrorMsg));
                        }
                        else
                        {
                            totalFileCount += directoryFileInfo.FileCount;
                            if (directoryFileInfo.FileCount > 0)
                            {
                                htmlTextTextDetails.AppendLine("<li>");
                                if (directoryFilter.LastErrorMsg.Length > 0)
                                {
                                    plainTextDetails.AppendLine(directoryFilter.LastErrorMsg);
                                    htmlTextTextDetails.AppendLine(directoryFilter.LastErrorMsg);
                                }

                                plainTextDetails.AppendLine(GetTop10FileInfos(directoryFileInfo.FileInfos));
                                htmlTextTextDetails.AppendLine("<blockquote>");
                                htmlTextTextDetails.AppendLine(GetTop10FileInfos(directoryFileInfo.FileInfos).Replace("\r\n", "<br/>"));
                                htmlTextTextDetails.AppendLine("</blockquote></li>");
                            }
                            else
                            {
                                plainTextDetails.AppendLine(string.Format("No files found '{0}'", directoryFilter.FilterFullPath));
                                htmlTextTextDetails.AppendLine(string.Format("<li>'{0}' - No files found</li>", directoryFilter.FilterFullPath));
                            }
                            if (currentState == MonitorStates.Warning)
                            {
                                warningCount++;
                            }
                            else if (currentState == MonitorStates.Error)
                            {
                                errorCount++;
                            }
                            else
                            {
                                okCount++;
                            }
                        }
                    }
                    else
                    {
                        okCount++;
                    }
                }
                htmlTextTextDetails.AppendLine("</ul>");
                if (errorCount > 0)
                {
                    returnState = MonitorStates.Error;
                }
                else if (warningCount > 0)
                {
                    returnState = MonitorStates.Warning;
                }
                else
                {
                    returnState = MonitorStates.Good;
                }
                LastDetailMsg.PlainText = plainTextDetails.ToString().TrimEnd('\r', '\n');
                LastDetailMsg.HtmlText  = htmlTextTextDetails.ToString();
                LastDetailMsg.LastValue = totalFileCount;
            }
            catch (Exception ex)
            {
                LastError               = 1;
                LastErrorMsg            = ex.Message;
                LastDetailMsg.PlainText = ex.Message;
                LastDetailMsg.HtmlText  = ex.Message;
                returnState             = MonitorStates.Disabled;
            }

            return(returnState);
        }
Ejemplo n.º 22
0
        public override MonitorStates GetState()
        {
            MonitorStates returnState         = MonitorStates.Good;
            StringBuilder plainTextDetails    = new StringBuilder();
            StringBuilder htmlTextTextDetails = new StringBuilder();

            LastDetailMsg.PlainText = "Running SQL queries";
            LastDetailMsg.HtmlText  = "";
            int    errors     = 0;
            int    warnings   = 0;
            int    success    = 0;
            double totalValue = 0;

            try
            {
                plainTextDetails.AppendLine(string.Format("SQL Queries"));
                htmlTextTextDetails.AppendLine(string.Format("SQL Queries"));
                htmlTextTextDetails.AppendLine("<ul>");
                foreach (QueryInstance queryInstance in SqlQueryConfig.Queries)
                {
                    object value = null;
                    LastDetailMsg.PlainText = string.Format("Running SQL query '{0}' on '{1}\\{2}'", queryInstance.Name, queryInstance.SqlServer, queryInstance.Database);

                    value = queryInstance.RunQuery();
                    MonitorStates currentstate = queryInstance.GetState(value);
                    if (value != DBNull.Value && value.IsNumber())
                    {
                        totalValue += double.Parse(value.ToString());
                    }

                    if (currentstate == MonitorStates.Error)
                    {
                        errors++;
                        plainTextDetails.AppendLine(string.Format("\t'{0}' - value '{1}' - Error (trigger {2})", queryInstance.Name, FormatUtils.N(value, "[null]"), queryInstance.ErrorValue));
                        htmlTextTextDetails.AppendLine(string.Format("<li>Machine '{0}' - Value '{1}' - <b>Error</b> (trigger {2})</li>", queryInstance.Name, FormatUtils.N(value, "[null]"), queryInstance.ErrorValue));
                    }
                    else if (currentstate == MonitorStates.Warning)
                    {
                        warnings++;
                        plainTextDetails.AppendLine(string.Format("\t'{0}' - value '{1}' - Warning (trigger {2})", queryInstance.Name, FormatUtils.N(value, "[null]"), queryInstance.WarningValue));
                        htmlTextTextDetails.AppendLine(string.Format("<li>Machine '{0}' - Value '{1}' - <b>Warning</b> (trigger {2})</li>", queryInstance.Name, FormatUtils.N(value, "[null]"), queryInstance.WarningValue));
                    }
                    else
                    {
                        success++;
                        plainTextDetails.AppendLine(string.Format("\t'{0}' - value '{1}'", queryInstance.Name, value));
                        htmlTextTextDetails.AppendLine(string.Format("<li>Machine '{0}' - Value '{1}'</li>", queryInstance.Name, value));
                    }
                }
                htmlTextTextDetails.AppendLine("</ul>");
                if (errors > 0 && warnings == 0)
                {
                    returnState = MonitorStates.Error;
                }
                else if (warnings > 0)
                {
                    returnState = MonitorStates.Warning;
                }
                LastDetailMsg.PlainText = plainTextDetails.ToString().TrimEnd('\r', '\n');
                LastDetailMsg.HtmlText  = htmlTextTextDetails.ToString();
                LastDetailMsg.LastValue = totalValue;
            }
            catch (Exception ex)
            {
                LastError               = 1;
                LastErrorMsg            = ex.Message;
                LastDetailMsg.PlainText = string.Format("Last step: '{0}\r\n{1}", LastDetailMsg.PlainText, ex.Message);
                LastDetailMsg.HtmlText  = string.Format("<blockquote>Last step: '{0}<br />{1}</blockquote>", LastDetailMsg.PlainText, ex.Message);
                returnState             = MonitorStates.Error;
            }
            return(returnState);
        }
Ejemplo n.º 23
0
        public override void RecordMessage(AlertLevel alertLevel, string collectorType, string category, MonitorStates oldState, MonitorStates newState, CollectorMessage collectorMessage)
        {
            string lastStep = "";

            try
            {
                //eventLogWriteMutex.WaitOne();
                if (eventLogNotifierConfig.MachineName.Length == 0)
                {
                    throw new Exception("Computer name not specified!");
                }
                if (eventLogNotifierConfig.EventSource.Length == 0)
                {
                    throw new Exception("Event source not specified!");
                }
                string currentEventSource = eventLogNotifierConfig.EventSource
                                            .Replace("%CollectorName%", category)
                                            .Replace("%CollectorType%", collectorType);

                lastStep = "Test if source exists";
                if (!EventLog.SourceExists(currentEventSource))
                {
                    lastStep = "Attempt to create event source " + currentEventSource;
                    EventSourceCreationData escd = new EventSourceCreationData(currentEventSource, "Application");
                    escd.MachineName = eventLogNotifierConfig.MachineName;
                    EventLog.CreateEventSource(escd);
                }
                lastStep = "Opening event log on " + eventLogNotifierConfig.MachineName;
                EventLog          outputLog         = new EventLog("Application", eventLogNotifierConfig.MachineName, currentEventSource);
                EventLogEntryType eventLogEntryType = (alertLevel == AlertLevel.Info || alertLevel == AlertLevel.Debug) ?  EventLogEntryType.Information :
                                                      alertLevel == AlertLevel.Warning ? EventLogEntryType.Warning :EventLogEntryType.Error;

                lastStep = "Generate output stream";
                string outputStr = string.Format("Time: {0}\r\nAlert level: {1}\r\nCollector: {2}\r\nCategory: {3}\r\nOld state: {4}\r\nCurrent state: {5}\r\nDetails: {6}",
                                                 DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss"),
                                                 Enum.GetName(typeof(AlertLevel), alertLevel),
                                                 collectorType,
                                                 category,
                                                 Enum.GetName(typeof(MonitorStates), oldState),
                                                 Enum.GetName(typeof(MonitorStates), newState),
                                                 collectorMessage.PlainText);

                lastStep = "Write the event log entry";
                outputLog.WriteEntry(outputStr, eventLogEntryType);
            }
            catch (Exception ex)
            {
                throw new Exception("Error recording message in Event log notifier\r\nLast step: " + lastStep, ex);
            }
            finally
            {
                //eventLogWriteMutex.ReleaseMutex();
            }
        }
Ejemplo n.º 24
0
        private void LoadMonitorPack(string monitorPackPath)
        {
            if (System.IO.File.Exists(monitorPackPath))
            {
                mainRefreshTimer.Enabled = false;
                try
                {
                    monitorPack.RaiseCurrentState           -= new RaiseCurrentStateDelegate(monitorPack_RaiseCurrentState);
                    monitorPack.RaiseNotifierError          -= new RaiseNotifierErrorDelegare(monitorPack_RaiseNotifierError);
                    monitorPack.CollectorCalled             -= new RaiseCollectorCalledDelegate(monitorPack_CollectorCalled);
                    monitorPack.CollectorExecutionTimeEvent -= new CollectorExecutionTimeDelegate(monitorPack_CollectorExecutionTimeEvent);
                    monitorPack.ClosePerformanceCounters();
                    monitorPack = null;
                }
                catch { }
                TreeNode root = tvwCollectors.Nodes[0];
                root.Nodes.Clear();
                monitorPack = new MonitorPack();
                monitorPack.Load(monitorPackPath);
                monitorPack.ConcurrencyLevel = Properties.Settings.Default.ConcurrencyLevel;
                if (monitorPack.AgentLoadingErrors != null && monitorPack.AgentLoadingErrors.Length > 0)
                {
                    MessageBox.Show(monitorPack.AgentLoadingErrors, "Loading errors", MessageBoxButtons.OK, MessageBoxIcon.Error);
                }
                SetEnableDisablePolling();

                List <CollectorEntry> noDependantCollectors = (from c in monitorPack.Collectors
                                                               where c.ParentCollectorId.Length == 0
                                                               select c).ToList();
                foreach (CollectorEntry collector in noDependantCollectors)
                {
                    LoadCollectorNode(root, collector);
                }
                root.Expand();

                monitorPack.RaiseCurrentState                   += new RaiseCurrentStateDelegate(monitorPack_RaiseCurrentState);
                monitorPack.RaiseNotifierError                  += new RaiseNotifierErrorDelegare(monitorPack_RaiseNotifierError);
                monitorPack.CollectorCalled                     += new RaiseCollectorCalledDelegate(monitorPack_CollectorCalled);
                monitorPack.CollectorExecutionTimeEvent         += new CollectorExecutionTimeDelegate(monitorPack_CollectorExecutionTimeEvent);
                monitorPack.RunCollectorCorrectiveWarningScript += new RaiseCollectorCalledDelegate(monitorPack_RunCollectorCorrectiveWarningScript);
                monitorPack.RunCollectorCorrectiveErrorScript   += new RaiseCollectorCalledDelegate(monitorPack_RunCollectorCorrectiveErrorScript);
                monitorPack.MonitorPackPathChanged              += new MonitorPackPathChangedDelegate(monitorPack_MonitorPackPathChanged);
                globalState = MonitorStates.NotAvailable;

                UpdateAppTitle();
                try
                {
                    defaultNotifierViewerToolStripMenuItem.Enabled = false;
                    if (monitorPack != null)
                    {
                        toolStripStatusLabelStatus.Text = string.Format("{0} collectors, {1} notifiers",
                                                                        monitorPack.Collectors.Count,
                                                                        monitorPack.Notifiers.Count);
                        defaultNotifierViewerToolStripMenuItem.Enabled = monitorPack.DefaultViewerNotifier != null;
                    }
                }
                catch { }
                tvwCollectors.SelectedNode = root;
                root.EnsureVisible();
                AddMonitorPackFileToRecentList(monitorPackPath);
                mainRefreshTimer.Enabled = true;
            }
        }
Ejemplo n.º 25
0
        private void RefreshMonitorPack()
        {
            try
            {
                Cursor.Current = Cursors.WaitCursor;
                if (this.InvokeRequired)
                {
                    this.Invoke((MethodInvoker) delegate()
                    {
                        Cursor.Current           = Cursors.WaitCursor;
                        mainRefreshTimer.Enabled = false;
                    }
                                );
                }
                else
                {
                    Cursor.Current           = Cursors.WaitCursor;
                    mainRefreshTimer.Enabled = false;
                }
            }
            catch { }
            try
            {
                if (monitorPack.Enabled)
                {
                    if (monitorPack.BusyPolling) //still busy with previous polling instance
                    {
                        //Attempting to abort it.
                        monitorPack.AbortPolling = true;
                        DateTime abortStart = DateTime.Now;
                        while (monitorPack.BusyPolling && abortStart.AddSeconds(5) > DateTime.Now)
                        {
                            Application.DoEvents();
                        }
                        Cursor.Current = Cursors.WaitCursor;
                    }

                    Stopwatch sw = new Stopwatch();
                    sw.Start();
                    globalState = monitorPack.RefreshStates();
                    sw.Stop();
                    PCSetCollectorsQueryTime(sw.ElapsedMilliseconds);
                }
                else
                {
                    globalState = MonitorStates.Disabled;
                }

                UpdateAppIcon();
                if (this.InvokeRequired)
                {
                    this.Invoke((MethodInvoker) delegate()
                    {
                        lastUpdateToolStripStatusLabel.Text = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss");
                    }
                                );
                }
                else
                {
                    lastUpdateToolStripStatusLabel.Text = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss");
                }
            }
            catch (Exception ex)
            {
                if (!ex.Message.Contains("Collection was modified; enumeration operation may not execute."))
                {
                    if (Properties.Settings.Default.DisablePollingOnError)
                    {
                        monitorPack.Enabled = false;
                    }
                    MessageBox.Show(ex.Message, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
                }
            }
            finally
            {
                Cursor.Current           = Cursors.Default;
                mainRefreshTimer.Enabled = mainTimerEnabled;
            }
        }
Ejemplo n.º 26
0
 private bool UpdateCollectorNode(TreeNode treeNode, CollectorEntry collector, MonitorStates currentState)
 {
     foreach (TreeNode childNode in treeNode.Nodes)
     {
         if (childNode.Text == collector.Name)
         {
             SetTreeNodeState(childNode, collector, currentState);
             return(true);
         }
         if (UpdateCollectorNode(childNode, collector, currentState))
         {
             return(true);
         }
     }
     return(false);
 }
Ejemplo n.º 27
0
        public override void RecordMessage(AlertLevel alertLevel, string collectorType, string category, MonitorStates oldState, MonitorStates newState, CollectorMessage collectorMessage)
        {
            string lastStep = "";

            try
            {
                //rssWriteMutex.WaitOne();
                if (rssDocument == null)
                {
                    LoadRSSDocument();
                }
                string lineTitle = rssConfig.LineTitle
                                   .Replace("%DateTime%", DateTime.Now.ToString("F"))
                                   .Replace("%AlertLevel%", alertLevel.ToString())
                                   .Replace("%PreviousState%", oldState.ToString())
                                   .Replace("%CurrentState%", newState.ToString())
                                   .Replace("%CollectorName%", category)
                                   .Replace("%CollectorType%", collectorType);
                string lineCategory = rssConfig.LineCategory
                                      .Replace("%DateTime%", DateTime.Now.ToString("F"))
                                      .Replace("%AlertLevel%", alertLevel.ToString())
                                      .Replace("%PreviousState%", oldState.ToString())
                                      .Replace("%CurrentState%", newState.ToString())
                                      .Replace("%CollectorName%", category)
                                      .Replace("%CollectorType%", collectorType);
                string lineDetails = rssConfig.LineDescription
                                     .Replace("%Details%", collectorMessage.HtmlText)
                                     .Replace("%DateTime%", DateTime.Now.ToString("F"))
                                     .Replace("%AlertLevel%", alertLevel.ToString())
                                     .Replace("%PreviousState%", oldState.ToString())
                                     .Replace("%CurrentState%", newState.ToString())
                                     .Replace("%CollectorName%", category)
                                     .Replace("%CollectorType%", collectorType);

                rssDocument.Lines.Add(
                    new InMemoryRSSDocumentLine()
                {
                    Title   = lineTitle,
                    PubDate = DateTime.Now,
                    //GUID = Guid.NewGuid().ToString(),
                    Category    = lineCategory,
                    Description = lineDetails     //.Replace("\r\n", "<br/>")
                }
                    );
                rssDocument.SaveRssDocument();
            }
            catch (Exception ex)
            {
                throw new Exception("Error recording message in rss notifier\r\nLast step: " + lastStep, ex);
            }
            finally
            {
                //rssWriteMutex.ReleaseMutex();
            }
        }
Ejemplo n.º 28
0
        public override MonitorStates GetState()
        {
            MonitorStates returnState         = MonitorStates.Good;
            StringBuilder plainTextDetails    = new StringBuilder();
            StringBuilder htmlTextTextDetails = new StringBuilder();

            LastDetailMsg.PlainText = "Querying table sizes";
            LastDetailMsg.HtmlText  = "";
            int  errors        = 0;
            int  warnings      = 0;
            long pingTotalTime = 0;

            try
            {
                plainTextDetails.AppendLine(string.Format("Pinging {0} addresses", HttpPingConfig.Entries.Count));
                htmlTextTextDetails.AppendLine(string.Format("<b>Pinging {0} addresses</b>", HttpPingConfig.Entries.Count));

                htmlTextTextDetails.AppendLine("<ul>");
                foreach (HttpPingEntry httpPingEntry in HttpPingConfig.Entries)
                {
                    try
                    {
                        plainTextDetails.Append(string.Format("\t\t{0} - ", httpPingEntry.Url));
                        htmlTextTextDetails.Append(string.Format("<li>{0} - ", httpPingEntry.Url));

                        int pingTime = httpPingEntry.Ping();
                        pingTotalTime += pingTime;
                        if (pingTime == int.MaxValue)
                        {
                            errors++;
                            plainTextDetails.Append(string.Format("Error - {0}", httpPingEntry.LastError));
                            htmlTextTextDetails.Append(string.Format("<b>Error</b> - {0}", httpPingEntry.LastError));
                        }
                        else if (pingTime >= httpPingEntry.TimeOut)
                        {
                            errors++;
                            plainTextDetails.Append(string.Format("{0}ms - Error (Time-Out {1}ms)", pingTime, httpPingEntry.TimeOut));
                            htmlTextTextDetails.Append(string.Format("{0}ms - <b>Error</b> (Time-Out {1}ms)", pingTime, httpPingEntry.TimeOut));
                        }
                        else if (pingTime >= httpPingEntry.MaxTime)
                        {
                            warnings++;
                            plainTextDetails.Append(string.Format("{0}ms - Warning (Max allowed {1}ms)", pingTime, httpPingEntry.MaxTime));
                            htmlTextTextDetails.Append(string.Format("{0}ms - <b>Warning</b> (Max allowed {1}ms)", pingTime, httpPingEntry.MaxTime));
                        }
                        else
                        {
                            plainTextDetails.Append(string.Format("{0}ms", pingTime));
                            htmlTextTextDetails.Append(string.Format("{0}ms", pingTime));
                        }

                        plainTextDetails.AppendLine();
                        htmlTextTextDetails.AppendLine("</li>");
                    }
                    catch (Exception innerEx)
                    {
                        errors++;
                        plainTextDetails.AppendLine(string.Format("{0}", innerEx.Message));
                        htmlTextTextDetails.AppendLine(string.Format("{0}", innerEx.Message));
                    }
                }
                htmlTextTextDetails.AppendLine("</ul>");

                if (errors > 0 && warnings == 0) //are all errors
                {
                    returnState = MonitorStates.Error;
                }
                else if (errors > 0 || warnings > 0) //any errors or warnings
                {
                    returnState = MonitorStates.Warning;
                }
                LastDetailMsg.PlainText = plainTextDetails.ToString().TrimEnd('\r', '\n');
                LastDetailMsg.HtmlText  = htmlTextTextDetails.ToString();
                LastDetailMsg.LastValue = pingTotalTime;
            }
            catch (Exception ex)
            {
                LastError               = 1;
                LastErrorMsg            = ex.Message;
                LastDetailMsg.PlainText = string.Format("Last step: '{0}\r\n{1}", LastDetailMsg.PlainText, ex.Message);
                LastDetailMsg.HtmlText  = string.Format("<blockquote>Last step: '{0}<br />{1}</blockquote>", LastDetailMsg.PlainText, ex.Message);
                returnState             = MonitorStates.Error;
            }
            return(returnState);
        }
Ejemplo n.º 29
0
        public override void RecordMessage(AlertLevel alertLevel, string collectorType, string category, MonitorStates oldState, MonitorStates newState, CollectorMessage collectorMessage)
        {
            string lastStep = "";

            try
            {
                smtpWriteMutex.WaitOne();
                if (mailSettings.HostServer.Length == 0)
                {
                    throw new Exception("SMTP host server not specified!");
                }
                lastStep = "Setting up SMTP client details";
                using (SmtpClient smtpClient = new SmtpClient())
                {
                    smtpClient.Host = mailSettings.HostServer;
                    smtpClient.UseDefaultCredentials = mailSettings.UseDefaultCredentials;
                    smtpClient.Port = mailSettings.Port;

                    if (!mailSettings.UseDefaultCredentials)
                    {
                        lastStep = "Setting up non default credentials";
                        System.Net.NetworkCredential cr = new System.Net.NetworkCredential();
                        cr.Domain              = mailSettings.Domain;
                        cr.UserName            = mailSettings.UserName;
                        cr.Password            = mailSettings.Password;
                        smtpClient.Credentials = cr;
                    }
                    if (mailSettings.UseTLS)
                    {
                        smtpClient.EnableSsl = true;
                    }
                    MailMessage mailMessage = new MailMessage(mailSettings.FromAddress, mailSettings.ToAddress);

                    lastStep = "Setting up mail body";
                    string body = mailSettings.Body
                                  .Replace("%Details%", mailSettings.IsBodyHtml ? collectorMessage.HtmlText : collectorMessage.PlainText)
                                  .Replace("%DateTime%", DateTime.Now.ToString("F"))
                                  .Replace("%AlertLevel%", alertLevel.ToString())
                                  .Replace("%PreviousState%", oldState.ToString())
                                  .Replace("%CurrentState%", newState.ToString())
                                  .Replace("%CollectorName%", category)
                                  .Replace("%CollectorType%", collectorType);

                    string subject = mailSettings.Subject
                                     .Replace("%DateTime%", DateTime.Now.ToString("F"))
                                     .Replace("%AlertLevel%", alertLevel.ToString())
                                     .Replace("%PreviousState%", oldState.ToString())
                                     .Replace("%CurrentState%", newState.ToString())
                                     .Replace("%CollectorName%", category)
                                     .Replace("%CollectorType%", collectorType);

                    mailMessage.Priority = (MailPriority)mailSettings.MailPriority;
                    if (mailSettings.SenderAddress.Length > 0)
                    {
                        mailMessage.Sender = new MailAddress(mailSettings.SenderAddress);
                    }
                    if (mailSettings.ReplyToAddress.Length > 0)
                    {
                        mailMessage.ReplyToList.Add(mailSettings.ReplyToAddress);
                    }

                    mailMessage.Body       = body;
                    mailMessage.IsBodyHtml = mailSettings.IsBodyHtml;

                    mailMessage.Subject = subject;
                    lastStep            = "Sending SMTP mail";
                    smtpClient.Send(mailMessage);
                }
            }
            catch (Exception ex)
            {
                throw new Exception("Error recording message in SMTP notifier\r\nLast step: " + lastStep, ex);
            }
            finally
            {
                smtpWriteMutex.ReleaseMutex();
            }
        }
Ejemplo n.º 30
0
        public override MonitorStates GetState()
        {
            MonitorStates returnState = MonitorStates.Good;
            string        lastDetails = "";

            LastDetailMsg.PlainText = "Getting drive infos";
            LastError    = 0;
            LastErrorMsg = "";
            long totalFreeSpace = 0;

            try
            {
                foreach (DriveSpaceEntry dse in Drives)
                {
                    LastDetailMsg.PlainText = "Getting drive info for " + dse.DriveLetter;
                    DriveInfo di = new DriveInfo(dse.DriveLetter);
                    if (di.IsReady)
                    {
                        totalFreeSpace += di.TotalFreeSpace;
                        if (di.TotalFreeSpace < dse.ErrorSizeLeftMB * 1048576)
                        {
                            LastDetailMsg.PlainText = string.Format("Drive {0} has reached error level {1} MB left.", dse.DriveLetter, (di.TotalFreeSpace / 1048576));
                            LastErrorMsg            = LastDetailMsg.PlainText;
                            if (returnState == MonitorStates.Good || returnState == MonitorStates.Warning)
                            {
                                returnState = MonitorStates.Error;
                            }
                        }
                        else if (di.TotalFreeSpace < dse.WarningSizeLeftMB * 1048576)
                        {
                            lastDetails += string.Format("Drive {0} has {1} MB available space - Warning", dse.DriveLetter, (di.TotalFreeSpace / 1048576));
                            if (returnState == MonitorStates.Good)
                            {
                                returnState = MonitorStates.Warning;
                            }
                        }
                        else
                        {
                            lastDetails += string.Format("Drive {0} has {1} MB available space", dse.DriveLetter, (di.TotalFreeSpace / 1048576));
                        }
                    }
                    else
                    {
                        if (dse.WarnOnNotReady && returnState == MonitorStates.Good)
                        {
                            lastDetails += string.Format("Drive {0} is not available!", dse.DriveLetter);
                            returnState  = MonitorStates.Warning;
                        }
                        else
                        {
                            lastDetails += string.Format("Drive {0} is not available.", dse.DriveLetter);
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                LastError    = 1;
                LastErrorMsg = ex.Message;
                lastDetails  = ex.Message;
                returnState  = MonitorStates.Error;
            }
            LastDetailMsg.PlainText = lastDetails.TrimEnd('\r', '\n');
            LastDetailMsg.LastValue = totalFreeSpace;
            return(returnState);
        }