From 1b8305c1bbd4e6480ac716c922100e5332790a86 Mon Sep 17 00:00:00 2001
From: "ankostis@host:STUW025" <ankostis@gmail.com>
Date: Fri, 30 May 2014 03:34:33 +0200
Subject: [PATCH] Rework logging routines

* Always write to file-log (even when sent to msg-box).
* file_v3: Completely hide close() method, leave Dispose() available only.
---
 CSE/Calculation/Minor_routines_calculate.vb |   2 +-
 CSE/Classes/cFile_v3.vb                     |  10 +-
 CSE/Classes/cJsonFile.vb                    |   3 +-
 CSE/Classes/cPreferences.vb                 |   2 +-
 CSE/GUI/Export_GUI.vb                       |  50 +++---
 CSE/GUI/F_Main.vb                           |  22 +--
 CSE/GUI/F_Preferences.designer.vb           |   2 +-
 CSE/GUI/minor_routines_GUI.vb               |  12 +-
 CSE/Minor_routines.vb                       | 163 ++++++++------------
 9 files changed, 121 insertions(+), 145 deletions(-)

diff --git a/CSE/Calculation/Minor_routines_calculate.vb b/CSE/Calculation/Minor_routines_calculate.vb
index 3dfdccb..cac6667 100644
--- a/CSE/Calculation/Minor_routines_calculate.vb
+++ b/CSE/Calculation/Minor_routines_calculate.vb
@@ -339,7 +339,7 @@
             Dim vline(), Line() As String
 
             ' Output on the GUI
-            fInfWarErrBW(4, False, "Read altitude file")
+            fInfWarErrBW(5, False, "Read altitude file")
 
             ' Open the MSC spezification file
             If Not FileInAlt.OpenRead(File) Then
diff --git a/CSE/Classes/cFile_v3.vb b/CSE/Classes/cFile_v3.vb
index 99aa0ec..aafdcf9 100644
--- a/CSE/Classes/cFile_v3.vb
+++ b/CSE/Classes/cFile_v3.vb
@@ -120,16 +120,18 @@ lb10:
 
     End Function
 
+    ' Close the file
     Public Sub Dispose() Implements IDisposable.Dispose
         Try
-            Close()
+            Me.Close()
         Catch ex As Exception
-            fInfWarErr(9, False, "Failed while closing file_v3 fue to: " & ex.Message)
+            fInfWarErr(9, False, format( _
+                       "Skipped exception while closing file_v3({0}) due to: {1}", Me.Path, ex.Message), ex)
         End Try
     End Sub
 
-    ' Close the file
-    Public Sub Close()
+    ' Use Dispose instead.
+    Private Sub Close()
         Select Case Mode
             Case FileMode.Read
                 If FileOpen Then TxtFldParser.Close()
diff --git a/CSE/Classes/cJsonFile.vb b/CSE/Classes/cJsonFile.vb
index 13a2b94..0eeced5 100644
--- a/CSE/Classes/cJsonFile.vb
+++ b/CSE/Classes/cJsonFile.vb
@@ -216,7 +216,7 @@ Public MustInherit Class cJsonFile
         End If
     End Function
 
-    ''' <summary>Used by sublasses to implement Propety-Get with defaults when non-existent</summary>
+    ''' <summary>Reads value found by XPath and if notinhg there, fetches default-value schema.</summary>
     ''' <param name="propPath">The JSON.net's XPath for a Body property, including the starting dot('.').
     ''' 
     ''' Examples:
@@ -225,6 +225,7 @@ Public MustInherit Class cJsonFile
     '''   /Body/SomeProp'                --> .SomeProp
     '''   /Body/someGroup/somePropName   --> .someGroup.somePropName'.  
     ''' </param>
+    ''' <remarks>Used by sublasses to implement Propety-Get with defaults when non-existent</remarks>
     Protected Function BodyGetter(ByVal propPath As String) As JToken
         Dim value As JToken = Me.Body.SelectToken(propPath)
         If value Is Nothing Then  '' No prop existed
diff --git a/CSE/Classes/cPreferences.vb b/CSE/Classes/cPreferences.vb
index ac80749..3c0d0b4 100644
--- a/CSE/Classes/cPreferences.vb
+++ b/CSE/Classes/cPreferences.vb
@@ -64,7 +64,7 @@ Public Class cPreferences
                     "minimum": 0,
                     "maximum": 10, "exclusiveMaximum": true,
                     "default": 5,
-                    "description": "Sets the threshold(Level) above from which log-messages to appear in the log-window.
+                    "description": "Sets the threshold(Level) below from which log-messages are skipped from the log-window.
     0     : All
     3-7   : No infos
     8     : No warnings
diff --git a/CSE/GUI/Export_GUI.vb b/CSE/GUI/Export_GUI.vb
index 0c6ccf7..1d6e1a3 100644
--- a/CSE/GUI/Export_GUI.vb
+++ b/CSE/GUI/Export_GUI.vb
@@ -101,24 +101,25 @@
     End Function
 
     ' Generation or upgrade from the log file
-    Function fWriteLog(ByVal BegHinEnd As Integer, Optional ByVal InfWarErrEls As Integer = 4, Optional ByVal text As String = "", _
+    Function fWriteLog(ByVal filePosition As Integer, Optional ByVal logLevel As Integer = 4, Optional ByVal text As String = "", _
                        Optional ByVal ex As Exception = Nothing) As Boolean
-        ' Style 1 ... Write beginning
-        ' Style 2 ... Add
-        ' Style 3 ... Write end
+        ' filePosition:
+        '   Write beginning
+        '   Add
+        '   Write end
 
-        ' Write Log only it is necessary
-        If AppPreferences.WriteLog Then
+        If Not AppPreferences.writeLog Then Return True
 
-            ' Declaration
-            Dim LogFilenam As String = MyPath & "Log.txt"
+        ' Declaration
+        Dim LogFilenam As String = joinPaths(MyPath, "log.txt")
 
+        Try
             ' Decision where should be write
-            Select Case BegHinEnd
+            Select Case filePosition
                 Case 1 ' At the beginning of VECTO
                     Dim fInf As New System.IO.FileInfo(LogFilenam)
                     If IO.File.Exists(LogFilenam) Then
-                        If fInf.Length > AppPreferences.LogSize * Math.Pow(10, 6) Then
+                        If fInf.Length > AppPreferences.logSize * Math.Pow(10, 6) Then
                             fLoeschZeilen(LogFilenam, System.IO.File.ReadAllLines(LogFilenam).Length / 2)
                         End If
                         FileOutLog.OpenWrite(LogFilenam, , True)
@@ -130,33 +131,34 @@
                     ' Write the start time into the Log
                     FileOutLog.WriteLine("Starting Session " & CDate(DateAndTime.Now))
                     FileOutLog.WriteLine(AppName & " " & AppVers)
-                    FileOutLog.Close()
 
                 Case 2 ' Add a message to the Log
-                    FileOutLog.OpenWrite(LogFilenam, , True)
-                    Select Case InfWarErrEls
-                        Case 1 ' Info
-                            FileOutLog.WriteLine("INFO     | " & text)
-                        Case 2 ' Warning
-                            FileOutLog.WriteLine("WARNING  | " & text)
-                        Case 3 ' Error
-                            FileOutLog.WriteLine("ERROR    | " & text)
-                        Case 4 ' Else
-                            FileOutLog.WriteLine(text)
+                    Dim slevel As String
+                    Select Case logLevel
+                        Case 1
+                            slevel = "INFO   | "
+                        Case 2
+                            slevel = "WARNING| "
+                        Case 3
+                            slevel = "ERROR  | "
+                        Case Else
+                            slevel = "DEBUG  | "
                     End Select
+                    FileOutLog.OpenWrite(LogFilenam, , True)
+                    FileOutLog.WriteLine(slevel & text)
                     If ex IsNot Nothing Then
                         FileOutLog.WriteLine(ex.StackTrace)
                     End If
 
-                    FileOutLog.Close()
                 Case 3 ' At the end
                     FileOutLog.OpenWrite(LogFilenam, , True)
                     ' Write the end to the Log
                     FileOutLog.WriteLine("Closing Session " & CDate(DateAndTime.Now))
                     FileOutLog.WriteLine("-----")
-                    FileOutLog.Close()
             End Select
-        End If
+        Finally
+            FileOutLog.Dispose()
+        End Try
 
         Return True
     End Function
diff --git a/CSE/GUI/F_Main.vb b/CSE/GUI/F_Main.vb
index d76731c..8adeadd 100644
--- a/CSE/GUI/F_Main.vb
+++ b/CSE/GUI/F_Main.vb
@@ -30,7 +30,8 @@ Public Class F_Main
         Try
             AppPreferences = New cPreferences(PreferencesPath)
         Catch ex As Exception
-            fInfWarErr(9, False, format("Failed loading Preferences({0}) due to: {1} \n\iThis is not a problem if it is the first time you launch the application.", _
+            fInfWarErr(9, False, format(<str>Failed loading Preferences({0}) due to: {1} 
+\iThis is normal the first time you launch the application.</str>, _
                                         PreferencesPath, ex.Message), ex)
             configL = False
         End Try
@@ -88,9 +89,9 @@ Public Class F_Main
     ' Open the vehiclefile in the Notepad
     Private Sub ButtonVeh_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles ButtonVeh.Click
         If IO.File.Exists(Me.TextBoxVeh1.Text) Then
-            System.Diagnostics.Process.Start(AppPreferences.Editor, Me.TextBoxVeh1.Text)
+            System.Diagnostics.Process.Start(AppPreferences.editor, Me.TextBoxVeh1.Text)
         Else
-            If Not fInfWarErr(9, True, "No such Inputfile: " & Me.TextBoxVeh1.Text) Then Exit Sub
+            fInfWarErr(9, True, "No such Inputfile: " & Me.TextBoxVeh1.Text)
         End If
     End Sub
 
@@ -107,9 +108,9 @@ Public Class F_Main
     ' Open the weatherfile in the Notepad
     Private Sub ButtonWeather_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles ButtonWeather.Click
         If IO.File.Exists(Me.TextBoxWeather.Text) Then
-            System.Diagnostics.Process.Start(AppPreferences.Editor, Me.TextBoxWeather.Text)
+            System.Diagnostics.Process.Start(AppPreferences.editor, Me.TextBoxWeather.Text)
         Else
-            If Not fInfWarErr(9, True, "No such Inputfile: " & Me.TextBoxWeather.Text) Then Exit Sub
+            fInfWarErr(9, True, "No such Inputfile: " & Me.TextBoxWeather.Text)
         End If
     End Sub
 
@@ -223,7 +224,7 @@ Public Class F_Main
         fClear_VECTO_Form(False, False)
 
         fInfWarErr(7, False, "Starting VECTO CSE calibration calculation...")
-        If AppPreferences.WriteLog Then fWriteLog(2, 4, "------------- Job: " & JobFile & " | Out: " & OutFolder & " | " & CDate(DateAndTime.Now) & "-------------")
+        If AppPreferences.writeLog Then fWriteLog(2, 4, "------------- Job: " & JobFile & " | Out: " & OutFolder & " | " & CDate(DateAndTime.Now) & "-------------")
 
         ' Start the calculation in the backgroundworker
         Me.BackgroundWorkerVECTO.RunWorkerAsync()
@@ -455,7 +456,7 @@ Public Class F_Main
 #Region "Tools"
     ' Menu open the Log
     Private Sub ToolStripMenuItemLog_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles ToolStripMenuItemLog.Click
-        System.Diagnostics.Process.Start(AppPreferences.Editor, MyPath & "Log.txt")
+        System.Diagnostics.Process.Start(AppPreferences.editor, joinPaths(MyPath, "log.txt"))
     End Sub
 
     ' Menu open the config file
@@ -565,8 +566,11 @@ Public Class F_Main
 
         '##### START THE CALCULATION #####
         '#################################
-
+        Try
             calculation(Cali)
+        Catch ex As Exception
+            fInfWarErrBW(9, True, format("Calculation Failed due to: {0}", ex.Message), ex)
+        End Try
 
         '#################################
 
@@ -589,7 +593,7 @@ Public Class F_Main
 
         Else
             ' Call the function for the depiction from the message on the GUI
-            MsgToForm(WorkerMsg.Styletext, WorkerMsg.Style, WorkerMsg.Text)
+            WorkerMsg.MsgToForm()
         End If
     End Sub
 
diff --git a/CSE/GUI/F_Preferences.designer.vb b/CSE/GUI/F_Preferences.designer.vb
index de9bb90..1a18919 100644
--- a/CSE/GUI/F_Preferences.designer.vb
+++ b/CSE/GUI/F_Preferences.designer.vb
@@ -282,7 +282,7 @@ Partial Class F_Preferences
         Me.CheckBox1.Name = "CheckBox1"
         Me.CheckBox1.Size = New System.Drawing.Size(129, 17)
         Me.CheckBox1.TabIndex = 5
-        Me.CheckBox1.Text = "Write log file (LOG.txt)"
+        Me.CheckBox1.Text = "Write log file (log.txt)"
         Me.CheckBox1.UseVisualStyleBackColor = True
         '
         'ButtonReload
diff --git a/CSE/GUI/minor_routines_GUI.vb b/CSE/GUI/minor_routines_GUI.vb
index 608e5e3..679dad9 100644
--- a/CSE/GUI/minor_routines_GUI.vb
+++ b/CSE/GUI/minor_routines_GUI.vb
@@ -52,10 +52,12 @@ Module minor_routines_GUI
     Function fControlPath(ByVal Line As String, ByVal position As Integer) As Boolean
         ' Polling if a path is available
         If (Line = Nothing) Then
-            If Not fInfWarErr(9, False, "No " & NameFK(position) & "-Inputfile") Then Return True
+            fInfWarErr(9, False, "No " & NameFK(position) & "-Inputfile")
+            Return True
             ' Polling if the path is an acceptable inputfile
         ElseIf IsNumeric(Line) Or (Mid(Line, 2, 1) <> ":") Or (Line = varOutStr) Then
-            If Not fInfWarErr(9, False, "No acceptably " & NameFK(position) & "-Inputfile: " & Line) Then Return True
+            fInfWarErr(9, False, "No acceptably " & NameFK(position) & "-Inputfile: " & Line)
+            Return True
         End If
 
         fWriteLog(2, 4, NameFK(position) & " File: " & Line)
@@ -370,10 +372,10 @@ Module minor_routines_GUI
     Function fControlInput(ByVal File As String, ByVal position As Integer, ByVal endung As String) As Boolean
         ' If no file, file with the wrong ending or the default is given then writes a warning
         If (File = Nothing) Then
-            If Not fInfWarErr(8, False, "The " & NameFK(position) & "-Inputfile is not a regular " & NameFK(position) & "-File") Then Return False
+            fInfWarErr(8, False, "The " & NameFK(position) & "-Inputfile is not a regular " & NameFK(position) & "-File")
             Return False
-        ElseIf (fEXT(File) <> endung) And Not (File = varOutStr) Then
-            If Not fInfWarErr(8, False, "The " & NameFK(position) & "-Inputfile is not a regular " & NameFK(position) & "-File") Then Return False
+        ElseIf (Not File.EndsWith(endung)) And Not (File = varOutStr) Then
+            fInfWarErr(8, False, "The " & NameFK(position) & "-Inputfile is not a regular " & NameFK(position) & "-File")
             Return False
         End If
         Return True
diff --git a/CSE/Minor_routines.vb b/CSE/Minor_routines.vb
index c614426..65a24b1 100644
--- a/CSE/Minor_routines.vb
+++ b/CSE/Minor_routines.vb
@@ -161,27 +161,63 @@ Module Minor_routines
 #End Region
 
     ' Functions for the information depiction on the GUI with the backgroundworker (Info, Warning, Error)
-#Region " Communication functions"
+#Region "Logging"
     ' Output from Informations\Warnings\Errors on the GUI
-    Function fInfWarErr(ByVal Style As Integer, ByVal MsgBoxOut As Boolean, ByVal text As String, Optional ByVal ex As Exception = Nothing) As Boolean
+    Function fInfWarErr(ByVal logLevel As Integer, ByVal MsgBoxOut As Boolean, _
+                   ByVal text As String, Optional ByVal ex As Exception = Nothing) As Boolean
 
         ' Declaration
-        Dim Styletext As String = ""
-        Dim StyleOut As String = ""
+        Dim Styletext = "Debug"
+        Dim logFileLevel As Integer = 0
+        Dim StyleOut = MsgBoxStyle.Information
 
         ' Identify the output style
-        Select Case Style
-            Case 0 To 7 ' Info
+        Select Case logLevel
+            Case 5 To 7 ' Info
+                logFileLevel = 1
                 Styletext = "Info"
-                StyleOut = MsgBoxStyle.Information
             Case 8 ' Warning
+                logFileLevel = 2
                 Styletext = "Warning"
                 StyleOut = MsgBoxStyle.Exclamation
             Case 9 ' Error
+                logFileLevel = 3
                 Styletext = "Error"
                 StyleOut = MsgBoxStyle.Critical
         End Select
 
+        ' Write to Log-file.
+        fWriteLog(2, logFileLevel, text, ex)
+
+        ' Polling the MSG if the message should shown
+        If logLevel >= AppPreferences.logLevel Then
+
+            ' Established the text wit the symbol from the style
+            text = AnzeigeMessage(logLevel) & text
+
+            ' Write to Log-windows
+            Select Case logFileLevel
+                Case 1 ' Info
+                    F_Main.ListBoxMSG.Items.Add(text)
+                Case 2 ' Warning
+                    F_Main.ListBoxMSG.Items.Add(text)
+                    F_Main.ListBoxWar.Items.Add(text)
+                    F_Main.TabPageWar.Text = Styletext & " (" & F_Main.ListBoxWar.Items.Count & ")"
+                Case 3 ' Error
+                    F_Main.ListBoxMSG.Items.Add(text)
+                    F_Main.ListBoxErr.Items.Add(text)
+                    F_Main.TabPageErr.Text = Styletext & " (" & F_Main.ListBoxErr.Items.Count & ")"
+                    F_Main.TabControlOutMsg.SelectTab(2)
+                Case Else
+                    '' ignored
+            End Select
+
+            ' Set the Scrollbars in the Listboxes at the end
+            F_Main.ListBoxMSG.TopIndex = F_Main.ListBoxMSG.Items.Count - 1
+            F_Main.ListBoxWar.TopIndex = F_Main.ListBoxWar.Items.Count - 1
+            F_Main.ListBoxErr.TopIndex = F_Main.ListBoxErr.Items.Count - 1
+        End If
+
         ' Output as an messagebox or on the tabcontrols
         If MsgBoxOut Then
             ' Output in a MsgBox
@@ -195,112 +231,41 @@ Module Minor_routines
             Else
                 MsgBox(text, StyleOut, Styletext)
             End If
-        Else
-            ' Polling the MSG if the message should shown
-            If Style <= AppPreferences.LogLevel Then Return True
-
-            ' Established the text wit the symbol from the style
-            text = AnzeigeMessage(Style) & text
-
-            ' Output in the Log
-            Select Case Style
-                Case 0 To 7 ' Message
-                    F_Main.ListBoxMSG.Items.Add(text)
-                    fWriteLog(2, 4, text, ex)
-                Case 8 ' Warning
-                    F_Main.ListBoxWar.Items.Add(text)
-                    F_Main.TabPageWar.Text = Styletext & " (" & F_Main.ListBoxWar.Items.Count & ")"
-                    fWriteLog(2, 2, text, ex)
-                Case 9 ' Error
-                    F_Main.ListBoxErr.Items.Add(text)
-                    F_Main.TabPageErr.Text = Styletext & " (" & F_Main.ListBoxErr.Items.Count & ")"
-                    F_Main.TabControlOutMsg.SelectTab(2)
-                    fWriteLog(2, 3, text, ex)
-            End Select
-        End If
-
-        ' Set the Scrollbars in the Listboxes at the end
-        F_Main.ListBoxMSG.TopIndex = F_Main.ListBoxMSG.Items.Count - 1
-        F_Main.ListBoxWar.TopIndex = F_Main.ListBoxWar.Items.Count - 1
-        F_Main.ListBoxErr.TopIndex = F_Main.ListBoxErr.Items.Count - 1
-
-        ' Return that the program have an error
-        If Style = 9 Then
-            Return False
-        Else
-            Return True
         End If
 
+        Return logLevel <> 9
     End Function
 
-    ' Definition for the Backgroundworker
-    Public Class CMsg
-        Public Styletext As String
-        Public Style As Integer
-        Public Text As String
-    End Class
-
-    ' Output from Informations\Warnings\Errors with the Backgoundworker
-    Function fInfWarErrBW(ByVal Style As Integer, ByVal MsgBoxOut As Boolean, ByVal text As String) As Boolean
-        ' Declaration
+    ''' <summary>Log from Informations\Warnings\Errors from within the Backgoundworker</summary>
+    Function fInfWarErrBW(ByVal logLevel As Integer, ByVal msgBoxOut As Boolean, _
+                     ByVal text As String, Optional ByVal ex As Exception = Nothing) As Boolean
         Dim WorkerMsg As New CMsg
 
-        WorkerMsg.Style = Style
+        WorkerMsg.LogLevel = logLevel
+        WorkerMsg.MsgBoxOut = msgBoxOut
         WorkerMsg.Text = text
-
-        ' Identify the output style
-        Select Case Style
-            Case 0 To 7 ' Info
-                WorkerMsg.Styletext = "Info"
-            Case 8 ' Warning
-                WorkerMsg.Styletext = "Warning"
-            Case 9 ' Error
-                WorkerMsg.Styletext = "Error"
-        End Select
-
-        ' Polling the MSG if the message should shown
-        If Style <= AppPreferences.LogLevel Then Return True
+        WorkerMsg.Ex = ex
 
         ' Output in the Tabcontrols (Call from Backgroundworker_ProgressChanged)
         BWorker.ReportProgress(0, WorkerMsg)
 
-        ' Return that the program have an error
-        If Style = 9 Then
-            Return (False)
-        Else
-            Return True
-        End If
-
+        Return logLevel <> 9
     End Function
 
-    ' Call for the output from Informations\Warnings\Errors with the backgoundworker
-    Sub MsgToForm(ByVal Styletext As String, ByVal Style As Integer, ByVal Text As String)
-        ' Established the text wit the symbol from the style
-        If Not Style = 10 Then Text = AnzeigeMessage(Style) & Text
-
-        ' Output in the Tabcontrols on the GUI
-        Select Case Style
-            Case 0 To 7 ' Message
-                F_Main.ListBoxMSG.Items.Add(Text)
-                fWriteLog(2, 4, Text)
-            Case 8 ' Warning
-                F_Main.ListBoxWar.Items.Add(Text)
-                F_Main.TabPageWar.Text = Styletext & " (" & F_Main.ListBoxWar.Items.Count & ")"
-                fWriteLog(2, 2, Text)
-            Case 9 ' Error
-                F_Main.ListBoxErr.Items.Add(Text)
-                F_Main.TabPageErr.Text = Styletext & " (" & F_Main.ListBoxErr.Items.Count & ")"
-                F_Main.TabControlOutMsg.SelectTab(2)
-                fWriteLog(2, 3, Text)
-        End Select
+    ' Definition for the Backgroundworker
+    Class CMsg
+        Public LogLevel As Integer
+        Public Text As String
+        Public Ex As Exception
+        Public MsgBoxOut As Boolean = False
 
-        ' Set the Scrollbars in the Listboxes at the end
-        F_Main.ListBoxMSG.TopIndex = F_Main.ListBoxMSG.Items.Count - 1
-        F_Main.ListBoxWar.TopIndex = F_Main.ListBoxWar.Items.Count - 1
-        F_Main.ListBoxErr.TopIndex = F_Main.ListBoxErr.Items.Count - 1
-    End Sub
+        ' Call for the output from Informations\Warnings\Errors with the backgoundworker
+        Public Sub MsgToForm()
+            fInfWarErr(LogLevel, MsgBoxOut, Text, Ex)
+        End Sub
+    End Class
 
-#End Region
+#End Region ' Logging
 
 
 #Region "Json"
@@ -370,7 +335,7 @@ Module Minor_routines
         Return value
     End Function
 
-#End Region ' "Json"
+#End Region ' Json
 
 
 #Region "Strings"
-- 
GitLab