Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion WinNUT_V2/WinNUT-Client_Common/Common_Enums.vb
Original file line number Diff line number Diff line change
Expand Up @@ -100,7 +100,7 @@ Public Enum NUTResponse
End Enum

Public Enum Nut_Exception_Value
<StringValue("Unable to create connection :")>
<StringValue("Unable to create connection: ")>
CONNECT_ERROR
<StringValue("Invalid Username.")>
INVALID_USERNAME
Expand Down
104 changes: 80 additions & 24 deletions WinNUT_V2/WinNUT-Client_Common/Logger.vb
Original file line number Diff line number Diff line change
Expand Up @@ -7,16 +7,22 @@
'
' This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY

Imports System.IO

Public Class Logger
Private ReadOnly LogFile As New Microsoft.VisualBasic.Logging.FileLogTraceListener()
Private Const BaseFileName = "WinNUT-CLient"
' Logs will be stored in the program's appdata folder, in a Logs subdirectory.
Public Shared ReadOnly LogFolder = Path.Combine(ApplicationData, "Logs")

Private LogFile As Logging.FileLogTraceListener
Private ReadOnly TEventCache As New TraceEventCache()
' Enable writing to a log file.
Public WriteLogValue As Boolean
Public LogLevelValue As LogLvl
Private L_CurrentLogData As String
Private LastEventsList As New List(Of Object)
Public Event NewData(ByVal sender As Object)

#Region "Properties"

Public Property CurrentLogData() As String
Get
Dim Tmp_Data = Me.L_CurrentLogData
Expand All @@ -32,32 +38,38 @@ Public Class Logger
Return Me.LastEventsList
End Get
End Property
Public Sub New(ByVal WriteLog As Boolean, ByVal LogLevel As LogLvl)
Me.WriteLogValue = WriteLog
Me.LogLevelValue = LogLevel
Me.LogFile.TraceOutputOptions = TraceOptions.DateTime Or TraceOptions.ProcessId
Me.LogFile.Append = True
Me.LogFile.AutoFlush = True
Me.LogFile.BaseFileName = "WinNUT-CLient"
Me.LogFile.LogFileCreationSchedule = Logging.LogFileCreationScheduleOption.Daily
Me.LogFile.Location = Microsoft.VisualBasic.Logging.LogFileLocation.Custom
Me.LogFile.CustomLocation = Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData) & "\WinNUT-Client"
Me.LastEventsList.Capacity = 50
WinNUT_Globals.LogFilePath = Me.LogFile.FullLogFileName
End Sub

Public Property WriteLog() As Boolean
''' <summary>
''' Returns if data is being written to a file. Also allows for file logging to be setup or stopped.
''' </summary>
''' <returns>True when the <see cref="LogFile"/> object is instantiated, false if not.</returns>
Public Property IsWritingToFile() As Boolean
Get
Return Me.WriteLogValue
Return Not (LogFile Is Nothing)
End Get
Set(ByVal Value As Boolean)
Me.WriteLogValue = Value
If Not Me.WriteLogValue Then

Set(Value As Boolean)
If Value = False And LogFile IsNot Nothing Then
LogFile.Close()
LogFile.Dispose()
LogFile = Nothing
LogTracing("Logging to file has been disabled.", LogLvl.LOG_NOTICE, Me)
ElseIf Value Then
SetupLogfile()
End If
End Set
End Property

Public ReadOnly Property LogFileLocation() As String
Get
If IsWritingToFile Then
Return LogFile.FullLogFileName
Else
Return String.Empty
End If
End Get
End Property

Public Property LogLevel() As LogLvl
Get
Return Me.LogLevelValue
Expand All @@ -67,18 +79,62 @@ Public Class Logger
End Set
End Property

#End Region

Public Sub New(WriteLog As Boolean, LogLevel As LogLvl)
IsWritingToFile = WriteLog
LogLevelValue = LogLevel
LastEventsList.Capacity = 50
End Sub

Public Sub SetupLogfile()
LogFile = New Logging.FileLogTraceListener(BaseFileName) With {
.TraceOutputOptions = TraceOptions.DateTime Or TraceOptions.ProcessId,
.Append = True,
.AutoFlush = True,
.LogFileCreationSchedule = Logging.LogFileCreationScheduleOption.Daily,
.CustomLocation = LogFolder,
.Location = Logging.LogFileLocation.Custom
}

LogTracing("Log file is initialized at " & LogFile.FullLogFileName, LogLvl.LOG_NOTICE, Me)
End Sub

Public Function DeleteLogFile() As Boolean
Try
Dim fileLocation = LogFile.FullLogFileName
IsWritingToFile = False
File.Delete(fileLocation)
Return True
Catch ex As Exception
Return False
End Try
End Function

''' <summary>
''' Write the <paramref name="message"/> to the Debug tracer is debugging, into the <see cref="LastEventsList" />
''' for report generating, to the <see cref="LogFile"/> if appropriate, and notify any listeners if
''' <paramref name="LogToDisplay"/> is specified.
''' </summary>
''' <param name="message">The raw information that needs to be recorded.</param>
''' <param name="LvlError">How important the information is.</param>
''' <param name="sender"></param>
''' <param name="LogToDisplay">A user-friendly, translated string to be shown.</param>
Public Sub LogTracing(ByVal message As String, ByVal LvlError As Int16, sender As Object, Optional ByVal LogToDisplay As String = Nothing)
Dim Pid = TEventCache.ProcessId
Dim SenderName = sender.GetType.Name
Dim EventTime = Now.ToLocalTime
Dim FinalMsg = EventTime & " Pid: " & Pid & " " & SenderName & " : " & message

'Update LogFilePath to make sure it's still the correct path
WinNUT_Globals.LogFilePath = Me.LogFile.FullLogFileName
' gbakeman 31/7/2022: Disabling since the LogFilePath should never change throughout the lifetime of this
' object, unless proper initialization has occured.

' WinNUT_Globals.LogFilePath = Me.LogFile.FullLogFileName

' Always write log messages to the attached debug messages window.
#If DEBUG Then
Debug.WriteLine(FinalMsg)
Debug.WriteLine(FinalMsg)
#End If

'Create Event in EventList in case of crash for generate Report
Expand All @@ -88,7 +144,7 @@ Public Class Logger

Me.LastEventsList.Add(FinalMsg)

If Me.WriteLogValue AndAlso Me.LogLevel >= LvlError Then
If IsWritingToFile AndAlso Me.LogLevel >= LvlError Then
LogFile.WriteLine(FinalMsg)
End If
'If LvlError = LogLvl.LOG_NOTICE Then
Expand Down
19 changes: 14 additions & 5 deletions WinNUT_V2/WinNUT-Client_Common/Nut_Socket.vb
Original file line number Diff line number Diff line change
Expand Up @@ -38,6 +38,7 @@ Public Class Nut_Socket
Public Event OnNotice(Message As String, NoticeLvl As LogLvl, sender As Object)
'Public Event OnError(Excep As Exception, NoticeLvl As LogLvl, sender As Object, ReportToGui As Boolean)
Public Event OnError(Excep As Exception, NoticeLvl As LogLvl, sender As Object)
Public Event OnNUTException(ex As Nut_Exception, NoticeLvl As LogLvl, sender As Object)

Public Event Unknown_UPS()
Public Event Socket_Broken()
Expand Down Expand Up @@ -94,10 +95,11 @@ Public Class Nut_Socket
Dim Port = Me.Nut_Config.Port
Dim Login = Me.Nut_Config.Login
Dim Password = Me.Nut_Config.Password
Dim Response As Boolean = False

If Not String.IsNullOrEmpty(Host) And Not IsNothing(Port) Then
If Not Create_Socket(Host, Port) Then
Throw New Nut_Exception(Nut_Exception_Value.CONNECT_ERROR)
' Don't duplicate/override Create_Socket's error throwing functionality.
' Throw New Nut_Exception(Nut_Exception_Value.CONNECT_ERROR)
Disconnect()
Else
If Not AuthLogin(Login, Password) Then
Expand All @@ -113,15 +115,22 @@ Public Class Nut_Socket
If Nut_Query.Response = NUTResponse.OK Then
Me.Net_Ver = Nut_Query.Data
End If
Response = True
Return True
End If
End If
Return Response

Catch nutEx As Nut_Exception
' Handle NUT exceptions specifically, without variable boxing/unboxing
RaiseEvent OnNUTException(nutEx, LogLvl.LOG_ERROR, Me)
Return False
Catch Excep As Exception
RaiseEvent OnError(Excep, LogLvl.LOG_ERROR, Me)
Return False
Finally

End Try
End Function

Private Function Create_Socket(ByVal Host As String, ByVal Port As Integer) As Boolean
Try
Me.NutSocket = New Socket(AddressFamily.InterNetwork, ProtocolType.IP)
Expand All @@ -131,7 +140,7 @@ Public Class Nut_Socket
Me.WriterStream = New StreamWriter(NutStream)
Me.ConnectionStatus = True
Catch Excep As Exception
RaiseEvent OnError(New Nut_Exception(Nut_Exception_Value.CONNECT_ERROR, Excep.Message), LogLvl.LOG_ERROR, Me)
RaiseEvent OnNUTException(New Nut_Exception(Nut_Exception_Value.CONNECT_ERROR, Excep.Message), LogLvl.LOG_ERROR, Me)
Me.ConnectionStatus = False
End Try
Return Me.ConnectionStatus
Expand Down
8 changes: 6 additions & 2 deletions WinNUT_V2/WinNUT-Client_Common/UPS_Device.vb
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,7 @@
Imports System.Globalization
Public Class UPS_Device
'Private Nut_Conn As Nut_Comm
Private LogFile As Logger
' Private LogFile As Logger
Private Freq_Fallback As Double
Private ciClone As System.Globalization.CultureInfo
Private Const CosPhi As Double = 0.6
Expand Down Expand Up @@ -107,7 +107,7 @@ Public Class UPS_Device
End Sub

Public Sub New(ByVal Nut_Config As Nut_Parameter, ByRef LogFile As Logger)
Me.LogFile = LogFile
' Me.LogFile = LogFile
Me.Nut_Config = Nut_Config
Me.ciClone = CType(CultureInfo.InvariantCulture.Clone(), CultureInfo)
Me.ciClone.NumberFormat.NumberDecimalSeparator = "."
Expand Down Expand Up @@ -410,4 +410,8 @@ Public Class UPS_Device
RaiseEvent Deconnected()
End If
End Sub

Private Sub NUTSocketError(nutEx As Nut_Exception, NoticeLvl As LogLvl, sender As Object) Handles Nut_Socket.OnNUTException
LogFile.LogTracing("[" & Nut_Config.UPSName & "] " & nutEx.ToString(), LogLvl.LOG_WARNING, Nut_Socket)
End Sub
End Class
38 changes: 30 additions & 8 deletions WinNUT_V2/WinNUT-Client_Common/WinNUT_Globals.vb
Original file line number Diff line number Diff line change
Expand Up @@ -7,31 +7,43 @@
'
' This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY

Imports System.IO

Public Module WinNUT_Globals
#Region "Properties"
' The directory where volatile appdata is stored.
ReadOnly Property ApplicationData() As String
Get
#If DEBUG Then
' If debugging, keep any generated data next to the debug executable.
Return Path.Combine(Environment.CurrentDirectory, "Data")
#End If
Return Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData), "\WinNUT-Client")
End Get
End Property
#End Region

Public LongProgramName As String
Public ProgramName As String
Public ProgramVersion As String
Public ShortProgramVersion As String
Public GitHubURL As String
Public Copyright As String
Public Directory_AppData As String
Public IsConnected As Boolean
Public LogFile As String
' Public LogFile As String
' Handle application messages and debug events.
Public WithEvents LogFile As Logger ' As New Logger(False, 0)
Public AppIcon As Dictionary(Of Integer, System.Drawing.Icon)
Public StrLog As New List(Of String)
Public LogFilePath As String
' Public LogFilePath As String

Public Sub Init_Globals()
LongProgramName = My.Application.Info.Description
ProgramName = My.Application.Info.ProductName
ProgramVersion = System.Reflection.Assembly.GetEntryAssembly().GetName().Version.ToString
ShortProgramVersion = ProgramVersion.Substring(0, ProgramVersion.IndexOf(".", ProgramVersion.IndexOf(".") + 1))
GitHubURL = My.Application.Info.Trademark
Copyright = My.Application.Info.Copyright
Directory_AppData = Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData) & "\WinNUT-Client"

If Not System.IO.Directory.Exists(Directory_AppData) Then
My.Computer.FileSystem.CreateDirectory(Directory_AppData)
End If
IsConnected = False

'Add Main Gui's Strings
Expand Down Expand Up @@ -79,4 +91,14 @@ Public Module WinNUT_Globals
'StrLog.Insert(AppResxStr.STR_LOG_NUT_FSD, Resources.Log_Str_12)
End Sub

'Sub SetupAppDirectory()
' If Not Directory.Exists(ApplicationData) Then
' Try
' Directory.CreateDirectory(ApplicationData)
' Catch ex As Exception
' Logger.LogTracing("Could not create application directory! Operating with reduced functionality.\n\n" & ex.ToString(),
' LogLvl.LOG_ERROR, Nothing)
' End Try
' End If
'End Sub
End Module
2 changes: 1 addition & 1 deletion WinNUT_V2/WinNUT_GUI/About_Gui.vb
Original file line number Diff line number Diff line change
Expand Up @@ -19,7 +19,7 @@ Public Class About_Gui
Lbl_Copyright_2019.Text = Strings.Replace(WinNUT_Globals.Copyright, "©", vbNewLine & "©")
LkLbl_Github.Text = WinNUT_Globals.GitHubURL
Me.Icon = WinNUT.Icon
Me.LogFile = WinNUT.LogFile
' Me.LogFile = WinNUT.LogFile
LogFile.LogTracing("Load About Gui", LogLvl.LOG_DEBUG, Me)
End Sub

Expand Down
3 changes: 2 additions & 1 deletion WinNUT_V2/WinNUT_GUI/ApplicationEvents.vb
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@
'
' This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY

Imports WinNUT_Client_Common
Imports WinNUT_Params = WinNUT_Client_Common.WinNUT_Params

Namespace My
Expand Down Expand Up @@ -121,7 +122,7 @@ Namespace My
Crash_Report &= Msg_Error.Text & vbNewLine & vbNewLine
Crash_Report &= "Last Events :" & vbNewLine

For Each WinNUT_Event In WinNUT.LogFile.LastEvents
For Each WinNUT_Event In LogFile.LastEvents
Crash_Report &= WinNUT_Event & vbNewLine
Next
My.Computer.Clipboard.SetText(Crash_Report)
Expand Down
2 changes: 1 addition & 1 deletion WinNUT_V2/WinNUT_GUI/List_Var_Gui.vb
Original file line number Diff line number Diff line change
Expand Up @@ -16,7 +16,7 @@ Public Class List_Var_Gui
Private LogFile As Logger
Private UPS_Name = WinNUT.Nut_Config.UPSName
Private Sub List_Var_Gui_Load(sender As Object, e As EventArgs) Handles MyBase.Load
Me.LogFile = WinNUT.LogFile
' Me.LogFile = WinNUT.LogFile
LogFile.LogTracing("Load List Var Gui", LogLvl.LOG_DEBUG, Me)
Me.Icon = WinNUT.Icon
Me.Visible = False
Expand Down
Loading