changeset 9:7127d5b5ac75

Code cleanup and comments
author Brad Greco <brad@bgreco.net>
date Mon, 08 Apr 2019 21:29:54 -0400
parents 052aa62cb42a
children 9e77c0dccb66
files ServerMonitor/Controls/CheckControl.cs ServerMonitor/Controls/DiskSpaceCheckControl.cs ServerMonitor/Controls/FileCheckControl.cs ServerMonitor/Controls/HttpCheckControl.cs ServerMonitor/Controls/MatchComboBox.cs ServerMonitor/Controls/ServerSummaryControl.cs ServerMonitor/Controls/SizeUnitsComboBox.cs ServerMonitor/Controls/SshCheckControl.cs ServerMonitor/Controls/TimeUnitsComboBox.cs ServerMonitor/Forms/CheckBoxDialog.cs ServerMonitor/Forms/CheckForm.cs ServerMonitor/Forms/InputDialog.cs ServerMonitor/Objects/Checks/FileCheck.cs ServerMonitor/Objects/Logger.cs
diffstat 14 files changed, 91 insertions(+), 145 deletions(-) [+]
line wrap: on
line diff
--- a/ServerMonitor/Controls/CheckControl.cs	Sat Mar 09 20:14:03 2019 -0500
+++ b/ServerMonitor/Controls/CheckControl.cs	Mon Apr 08 21:29:54 2019 -0400
@@ -1,18 +1,16 @@
 using System;
 using System.Collections.Generic;
-using System.ComponentModel;
-using System.Drawing;
 using System.Data;
 using System.Linq;
-using System.Text;
 using System.Windows.Forms;
 
 namespace ServerMonitorApp
 {
-    /// <summary>Base class for check controls</summary>
+    /// <summary>Base class for check controls.</summary>
     /// <remarks>This control should never be used directly, but marking it abstract causes problems with the designer.</remarks>
     public partial class CheckControl : UserControl
     {
+        /// <summary>Type of the check this control can edit.</summary>
         public Type CheckType => GetCheckType(GetType());
 
         public CheckControl()
@@ -24,6 +22,8 @@
         {
             CheckGroupBox.Text = Helpers.GetDisplayName(CheckType);
 
+            // Bind change listeners to checkboxes to enable or disable a panel of controls.
+            // The leftmost checkbox is assumed to be the "master switch" for the panel.
             IEnumerable<Panel> panels = CheckGroupBox.Controls.OfType<Panel>();
             foreach (Panel panel in panels)
             {
@@ -41,6 +41,8 @@
             DisablePanelByCheckBox((CheckBox)sender);
         }
 
+        /// <summary>Enables or disables all sibling controls of a checkbox.</summary>
+        /// <param name="checkBox">The checkbox to disable or enable the sibling controls of.</param>
         private void DisablePanelByCheckBox(CheckBox checkBox)
         {
             foreach (Control control in checkBox.Parent.Controls)
@@ -50,16 +52,24 @@
             }
         }
 
+        /// <summary>Sets the values of the controls from a check's properties.</summary>
+        /// <remarks>Subclasses should implement this method. Marking as abstract causes problems with the designer.</remarks>
         public virtual void LoadCheck(Check check) { }
 
+        /// <summary>Updates the properties of a check from user input.</summary>
+        /// <remarks>Subclasses should implement this method. Marking as abstract causes problems with the designer.</remarks>
         public virtual void UpdateCheck(Check check) { }
 
+        /// <summary>Creates an instance of a check control based on a check type.</summary>
         public static CheckControl Create(Type CheckType)
         {
+            // Use reflection to find a check control that declares it handles the given type.
             Type checkControlType = typeof(CheckControl).Assembly.GetTypes().FirstOrDefault(t => GetCheckType(t) == CheckType);
+            // If one was found, instantiate it.
             return checkControlType == null ? null : (CheckControl)Activator.CreateInstance(checkControlType);
         }
 
+        /// <summary>Gets the value of the CheckTypeAttribute for a type.</summary>
         private static Type GetCheckType(Type type)
         {
             return type.GetAttribute<CheckTypeAttribute>()?.CheckType;
--- a/ServerMonitor/Controls/DiskSpaceCheckControl.cs	Sat Mar 09 20:14:03 2019 -0500
+++ b/ServerMonitor/Controls/DiskSpaceCheckControl.cs	Mon Apr 08 21:29:54 2019 -0400
@@ -1,14 +1,8 @@
 using System;
-using System.Collections.Generic;
-using System.ComponentModel;
-using System.Drawing;
-using System.Data;
-using System.Linq;
-using System.Text;
-using System.Windows.Forms;
 
 namespace ServerMonitorApp
 {
+    /// <summary>Control for editing a disk space check.</summary>
     [CheckType(typeof(DiskSpaceCheck))]
     public partial class DiskSpaceCheckControl : CheckControl
     {
@@ -19,9 +13,11 @@
 
         private void DiskSpaceCheckControl_Load(object sender, EventArgs e)
         {
+            // Initialize the free space units to a non-empty value.
             FreeSpaceUnitsComboBox.SelectedIndex = 1;
         }
 
+        /// <summary>Sets the values of the controls from a check's properties.</summary>
         public override void LoadCheck(Check check1)
         {
             DiskSpaceCheck check = (DiskSpaceCheck)check1;
@@ -30,6 +26,7 @@
             FreeSpaceUnitsComboBox.SelectedIndex = (int)check.FreeSpaceUnits;
         }
 
+        /// <summary>Updates the properties of a check from user input.</summary>
         public override void UpdateCheck(Check check1)
         {
             DiskSpaceCheck check = (DiskSpaceCheck)check1;
@@ -46,4 +43,4 @@
             }
         }
     }
-}
\ No newline at end of file
+}
--- a/ServerMonitor/Controls/FileCheckControl.cs	Sat Mar 09 20:14:03 2019 -0500
+++ b/ServerMonitor/Controls/FileCheckControl.cs	Mon Apr 08 21:29:54 2019 -0400
@@ -1,14 +1,8 @@
 using System;
-using System.Collections.Generic;
-using System.ComponentModel;
-using System.Drawing;
-using System.Data;
-using System.Linq;
-using System.Text;
-using System.Windows.Forms;
 
 namespace ServerMonitorApp
 {
+    /// <summary>Control for editing a file check.</summary>
     [CheckType(typeof(FileCheck))]
     public partial class FileCheckControl : CheckControl
     {
@@ -19,10 +13,12 @@
 
         private void DiskSpaceCheckControl_Load(object sender, EventArgs e)
         {
+            // Initialize the combo boxes to non-empty values.
             FileSizeComparisonComboBox.SelectedIndex = 0;
             DateModifiedComparisonComboBox.SelectedIndex = 0;
         }
 
+        /// <summary>Sets the values of the controls from a check's properties.</summary>
         public override void LoadCheck(Check check1)
         {
             FileCheck check = (FileCheck)check1;
@@ -36,12 +32,14 @@
             DateModifiedTextBox.Text = check.DateModified.ToString();
             DateModifiedUnitsComboBox.SelectedIndex = (int)check.DateModifiedUnits;
 
-            if (FileSizeTextBox.Text == "0")
+            // Blank out text boxes that are disabled and have a blank-looking value.
+            if (FileSizeTextBox.Text == "0" && !check.CheckFileSize)
                 FileSizeTextBox.Clear();
-            if (DateModifiedTextBox.Text == "0")
+            if (DateModifiedTextBox.Text == "0" && !check.CheckDateModified)
                 DateModifiedTextBox.Clear();
         }
 
+        /// <summary>Updates the properties of a check from user input.</summary>
         public override void UpdateCheck(Check check1)
         {
             FileCheck check = (FileCheck)check1;
--- a/ServerMonitor/Controls/HttpCheckControl.cs	Sat Mar 09 20:14:03 2019 -0500
+++ b/ServerMonitor/Controls/HttpCheckControl.cs	Mon Apr 08 21:29:54 2019 -0400
@@ -1,14 +1,6 @@
-using System;
-using System.Collections.Generic;
-using System.ComponentModel;
-using System.Drawing;
-using System.Data;
-using System.Linq;
-using System.Text;
-using System.Windows.Forms;
-
-namespace ServerMonitorApp
+namespace ServerMonitorApp
 {
+    /// <summary>Control for editing an HTTP check.</summary>
     [CheckType(typeof(HttpCheck))]
     public partial class HttpCheckControl : CheckControl
     {
@@ -17,6 +9,7 @@
             InitializeComponent();
         }
 
+        /// <summary>Sets the values of the controls from a check's properties.</summary>
         public override void LoadCheck(Check check1)
         {
             HttpCheck check = (HttpCheck)check1;
@@ -32,6 +25,7 @@
             ResponseBodyRegexCheckBox.Checked = check.ResponseBodyUseRegex;
         }
 
+        /// <summary>Updates the properties of a check from user input.</summary>
         public override void UpdateCheck(Check check1)
         {
             HttpCheck check = (HttpCheck)check1;
--- a/ServerMonitor/Controls/MatchComboBox.cs	Sat Mar 09 20:14:03 2019 -0500
+++ b/ServerMonitor/Controls/MatchComboBox.cs	Mon Apr 08 21:29:54 2019 -0400
@@ -1,16 +1,14 @@
-using System;
-using System.Collections.Generic;
-using System.Linq;
-using System.Text;
-using System.Windows.Forms;
+using System.Windows.Forms;
 
 namespace ServerMonitorApp
 {
+    /// <summary>Combo box containing options for matching text against a response string.</summary>
     class MatchComboBox : ComboBox
     {
         protected override void OnCreateControl()
         {
             base.OnCreateControl();
+            // Clear the items to prevent duplicates added at design time and run time.
             Items.Clear();
             Items.Add("equals");
             Items.Add("does not equal");
@@ -22,5 +20,6 @@
         }
     }
 
+    /// <summary>Types of matches that can be run against a response string.</summary>
     public enum MatchType { Equals = 0, NotEquals = 1, Contains = 2, NotContains = 3, GreaterThan = 4, LessThan = 5 }
 }
--- a/ServerMonitor/Controls/ServerSummaryControl.cs	Sat Mar 09 20:14:03 2019 -0500
+++ b/ServerMonitor/Controls/ServerSummaryControl.cs	Mon Apr 08 21:29:54 2019 -0400
@@ -1,10 +1,4 @@
 using System;
-using System.Collections.Generic;
-using System.ComponentModel;
-using System.Drawing;
-using System.Data;
-using System.Linq;
-using System.Text;
 using System.Windows.Forms;
 
 namespace ServerMonitorApp
--- a/ServerMonitor/Controls/SizeUnitsComboBox.cs	Sat Mar 09 20:14:03 2019 -0500
+++ b/ServerMonitor/Controls/SizeUnitsComboBox.cs	Mon Apr 08 21:29:54 2019 -0400
@@ -1,16 +1,14 @@
-using System;
-using System.Collections.Generic;
-using System.Linq;
-using System.Text;
-using System.Windows.Forms;
+using System.Windows.Forms;
 
 namespace ServerMonitorApp
 {
+    /// <summary>Combo box containing options for size units.</summary>
     class SizeUnitsComboBox : ComboBox
     {
         protected override void OnCreateControl()
         {
             base.OnCreateControl();
+            // Clear the items to prevent duplicates added at design time and run time.
             Items.Clear();
             Items.Add("B");
             Items.Add("KB");
@@ -20,5 +18,6 @@
         }
     }
 
+    /// <summary>Size units.</summary>
     public enum SizeUnits { B = 0, KB = 1, MB = 2, GB = 3 }
 }
--- a/ServerMonitor/Controls/SshCheckControl.cs	Sat Mar 09 20:14:03 2019 -0500
+++ b/ServerMonitor/Controls/SshCheckControl.cs	Mon Apr 08 21:29:54 2019 -0400
@@ -1,14 +1,8 @@
 using System;
-using System.Collections.Generic;
-using System.ComponentModel;
-using System.Drawing;
-using System.Data;
-using System.Linq;
-using System.Text;
-using System.Windows.Forms;
 
 namespace ServerMonitorApp
 {
+    /// <summary>Control for editing an SSH space check.</summary>
     [CheckType(typeof(SshCheck))]
     public partial class SshCheckControl : CheckControl
     {
@@ -17,6 +11,7 @@
             InitializeComponent();
         }
 
+        /// <summary>Sets the values of the controls from a check's properties.</summary>
         public override void LoadCheck(Check check1)
         {
             SshCheck check = (SshCheck)check1;
@@ -29,6 +24,7 @@
             CommandOutputRegexCheckBox.Checked = check.CommandOutputUseRegex;
         }
 
+        /// <summary>Updates the properties of a check from user input.</summary>
         public override void UpdateCheck(Check check1)
         {
             SshCheck check = (SshCheck)check1;
@@ -55,6 +51,7 @@
             check.CommandOutputUseRegex = CommandOutputRegexCheckBox.Checked;
         }
 
+        /// <summary>Disables the regex checkbox if a numeric comparison is selected.</summary>
         private void CommandOutputComboBox_SelectedIndexChanged(object sender, EventArgs e)
         {
             bool numeric = ((MatchType)CommandOutputComboBox.SelectedIndex).In(MatchType.GreaterThan, MatchType.LessThan);
--- a/ServerMonitor/Controls/TimeUnitsComboBox.cs	Sat Mar 09 20:14:03 2019 -0500
+++ b/ServerMonitor/Controls/TimeUnitsComboBox.cs	Mon Apr 08 21:29:54 2019 -0400
@@ -1,16 +1,14 @@
-using System;
-using System.Collections.Generic;
-using System.Linq;
-using System.Text;
-using System.Windows.Forms;
+using System.Windows.Forms;
 
 namespace ServerMonitorApp
 {
+    /// <summary>Combo box containing options for time units.</summary>
     class TimeUnitsComboBox : ComboBox
     {
         protected override void OnCreateControl()
         {
             base.OnCreateControl();
+            // Clear the items to prevent duplicates added at design time and run time.
             Items.Clear();
             Items.Add("minutes");
             Items.Add("hours");
@@ -19,5 +17,6 @@
         }
     }
 
+    /// <summary>Time units.</summary>
     public enum TimeUnits { Minute = 0, Hour = 1, Day = 2 }
 }
--- a/ServerMonitor/Forms/CheckBoxDialog.cs	Sat Mar 09 20:14:03 2019 -0500
+++ b/ServerMonitor/Forms/CheckBoxDialog.cs	Mon Apr 08 21:29:54 2019 -0400
@@ -1,18 +1,16 @@
 using System;
-using System.Collections.Generic;
-using System.ComponentModel;
-using System.Data;
 using System.Drawing;
-using System.Linq;
-using System.Text;
 using System.Windows.Forms;
 
 namespace ServerMonitorApp
 {
+    /// <summary>Message dialog with an additional checkbox.</summary>
     public partial class CheckBoxDialog : Form
     {
+        /// <summary>Message to show.</summary>
         public string Message { get; set; }
 
+        /// <summary>Check state of the checkbox.</summary>
         public bool Checked { get; private set; }
 
         public CheckBoxDialog()
@@ -26,6 +24,7 @@
             MessageLabel.Text = Message;
         }
 
+        /// <summary>Updates the public property with the checked state so it can be read by the dialog owner.</summary>
         private void PromptCheckBox_CheckedChanged(object sender, EventArgs e)
         {
             Checked = PromptCheckBox.Checked;
--- a/ServerMonitor/Forms/CheckForm.cs	Sat Mar 09 20:14:03 2019 -0500
+++ b/ServerMonitor/Forms/CheckForm.cs	Mon Apr 08 21:29:54 2019 -0400
@@ -1,19 +1,17 @@
-using ServerMonitorApp.Properties;
-using System;
+using System;
 using System.Collections.Generic;
 using System.ComponentModel;
-using System.Data;
 using System.Drawing;
 using System.Linq;
 using System.Text;
 using System.Threading;
 using System.Windows.Forms;
+using ServerMonitorApp.Properties;
 
 namespace ServerMonitorApp
 {
     public partial class CheckForm : Form
     {
-        //private static readonly Dictionary<Type, CheckInfo> checkInfo = new Dictionary<Type, CheckInfo>();
         private readonly List<CheckControl> checkControls = new List<CheckControl>();
         private bool helpShown;
         private CancellationTokenSource cancellationTokenSource;
@@ -86,16 +84,6 @@
             e.Value = Helpers.GetDisplayName((Type)e.ListItem);
         }
 
-        /*private void showGroupBox(GroupBox groupBox)
-        {
-
-        }*/
-
-        /*private Type GetCheckType()
-        {
-            return (Type)CheckTypeComboBox.SelectedItem;
-        }*/
-
         private void ShowCheckControl()
         {
             IEnumerable<CheckControl> checkControls = CheckSettingsPanel.Controls.OfType<CheckControl>();
@@ -115,8 +103,6 @@
             }
             if (checkControl != null)
             {
-                //CheckSettingsPanel.Height = checkControl.Height;
-                //Height = 230 + checkControl.Height;
                 checkControl.Show();
             }
         }
@@ -210,30 +196,6 @@
             localCancellationTokenSource = null;
         }
 
-        //private void RunButton_Click(object sender, EventArgs e)
-        //{
-        //    if (!Check.Server.SshClient.IsConnected)
-        //        Check.Server.SshClient.Connect();
-        //    using (Renci.SshNet.SshCommand command = Check.Server.SshClient.CreateCommand("ls"))
-        //    {
-        //        //token.Register(command.CancelAsync);
-        //        //command.BeginExecute(asyncResult =>
-        //        //{
-        //        //    string result = command.EndExecute(asyncResult);
-        //        //    //tcs.SetResult(new CheckResult(this, CheckStatus.Success, result));
-        //        //});
-        //        IAsyncResult iar = command.BeginExecute(z);
-        //        command.EndExecute(iar);
-        //        //string result = command.Execute();
-        //        //System.Console.Write(result);
-        //    }
-        //}
-
-        //private void z(IAsyncResult ar)
-        //{
-        //    throw new NotImplementedException();
-        //}
-
         private void CancelRunButton_Click(object sender, EventArgs e)
         {
             cancellationTokenSource.Cancel();
@@ -250,25 +212,11 @@
             if (result != null)
             {
                 ResultLabel.Text = result.Message;
-                //ResultLabel.ForeColor = result.CheckStatus == CheckStatus.Success ? Color.Green : Color.Red;
                 ResultIconPictureBox.Image = result.CheckStatus.GetImage();
                 ResultLabel.Visible = ResultIconPictureBox.Visible = true;
             }
         }
 
-        /*private class CheckInfo
-        {
-            public GroupBox GroupBox { get; private set; }
-
-            public Func<string> ValidateFunction { get; private set; }
-
-            public CheckInfo(GroupBox groupBox, Func<string> validateFunction)
-            {
-                GroupBox = groupBox;
-                ValidateFunction = validateFunction;
-            }
-        }*/
-
         private string BuildHelpText()
         {
             StringBuilder rtf = new StringBuilder(@"{\rtf1\ansi ");
--- a/ServerMonitor/Forms/InputDialog.cs	Sat Mar 09 20:14:03 2019 -0500
+++ b/ServerMonitor/Forms/InputDialog.cs	Mon Apr 08 21:29:54 2019 -0400
@@ -1,21 +1,19 @@
 using System;
-using System.Collections.Generic;
-using System.ComponentModel;
-using System.Data;
 using System.Drawing;
-using System.Linq;
-using System.Text;
-using System.Threading.Tasks;
 using System.Windows.Forms;
 
 namespace ServerMonitorApp
 {
+    /// <summary>Message dialog with an input box.</summary>
     public partial class InputDialog : Form
     {
+        /// <summary>Message to show.</summary>
         public string Message { get; set; }
 
+        /// <summary>Icon to show.</summary>
         public Icon MessageIcon { get; set; }
 
+        /// <summary>The text entered by the user.</summary>
         public string Input { get; private set; } = "";
 
         public InputDialog()
@@ -29,6 +27,17 @@
             MessageLabel.Text = Message;
         }
 
+        /// <summary>Updates the public property with the checked state so it can be read by the dialog owner.</summary>
+        private void InputTextBox_TextChanged(object sender, EventArgs e)
+        {
+            Input = InputTextBox.Text;
+        }
+
+        /// <summary>Creates and shows an input box dialog.</summary>
+        /// <param name="message">The message to display.</param>
+        /// <param name="icon">The icon to display.</param>
+        /// <param name="owner">The dialog owner.</param>
+        /// <returns>The string entered by the user, or null if the dialog was cancelled.</returns>
         public static string ShowDialog(string message, Icon icon = null, IWin32Window owner = null)
         {
             using (InputDialog dialog = new InputDialog() { Message = message, MessageIcon = icon })
@@ -36,10 +45,5 @@
                 return dialog.ShowDialog(owner) == DialogResult.OK ? dialog.Input : null;
             }
         }
-
-        private void InputTextBox_TextChanged(object sender, EventArgs e)
-        {
-            Input = InputTextBox.Text;
-        }
     }
 }
--- a/ServerMonitor/Objects/Checks/FileCheck.cs	Sat Mar 09 20:14:03 2019 -0500
+++ b/ServerMonitor/Objects/Checks/FileCheck.cs	Mon Apr 08 21:29:54 2019 -0400
@@ -75,6 +75,7 @@
                 }
                 if (CheckDateModified)
                 {
+                    // TODO use the server time instead
                     string dateString = tokens[5] + " " + tokens[6];
                     if (DateTime.TryParse(dateString, out DateTime modified))
                     {
@@ -104,8 +105,8 @@
                 message += "File is required." + Environment.NewLine;
             if (!CheckFileSize && !CheckDateModified)
                 message += "At least one check must be enabled." + Environment.NewLine;
-            if (CheckFileSize && FileSize <= 0)
-                message += "File size must be greater than 0." + Environment.NewLine;
+            if (CheckFileSize && FileSize < 0)
+                message += "File size must be at least 0." + Environment.NewLine;
             if (CheckDateModified && DateModified <= 0)
                 message += "Date modified must be greater than 0." + Environment.NewLine;
             return message;
--- a/ServerMonitor/Objects/Logger.cs	Sat Mar 09 20:14:03 2019 -0500
+++ b/ServerMonitor/Objects/Logger.cs	Mon Apr 08 21:29:54 2019 -0400
@@ -65,28 +65,35 @@
         {
             DateTime maxAge = DateTime.Now.AddDays(-1 * Settings.Default.KeepLogDays);
             string tempFile = logFile + ".tmp";
-            using (FileStream stream = new FileStream(logFile, FileMode.Open, FileAccess.Read, FileShare.Read))
-            using (StreamReader reader = new StreamReader(stream, Encoding.UTF8))
-            using (FileStream outStream = new FileStream(tempFile, FileMode.Create, FileAccess.Write, FileShare.None))
-            using (StreamWriter writer = new StreamWriter(outStream, Encoding.UTF8))
+            try
             {
-                while (true)
+                using (FileStream stream = new FileStream(logFile, FileMode.Open, FileAccess.Read, FileShare.Read))
+                using (StreamReader reader = new StreamReader(stream, Encoding.UTF8))
+                using (FileStream outStream = new FileStream(tempFile, FileMode.Create, FileAccess.Write, FileShare.None))
+                using (StreamWriter writer = new StreamWriter(outStream, Encoding.UTF8))
                 {
-                    try
+                    while (true)
                     {
-                        string line = reader.ReadLine();
-                        if (line == null)
-                            break;
-                        if (DateTime.TryParse(line.Substring(6, 10), out DateTime date) && date > maxAge)
+                        try
                         {
-                            await writer.WriteLineAsync(line);
+                            string line = reader.ReadLine();
+                            if (line == null)
+                                break;
+                            if (DateTime.TryParse(line.Substring(6, 10), out DateTime date) && date > maxAge)
+                            {
+                                await writer.WriteLineAsync(line);
+                            }
                         }
+                        catch (Exception) { }
                     }
-                    catch (Exception) { }
                 }
+                File.Delete(logFile);
+                File.Move(tempFile, logFile);
             }
-            File.Delete(logFile);
-            File.Move(tempFile, logFile);
+            catch (FileNotFoundException)
+            {
+                // Do nothing if the log file does not exist yet.
+            }
         }
     }
 }