From fa63a57f90c5e3537b4dde76d761704f209b8623 Mon Sep 17 00:00:00 2001
From: Markus Quaritsch <markus.quaritsch@tugraz.at>
Date: Thu, 21 Feb 2019 11:05:03 +0100
Subject: [PATCH] reading config file if VECTO should run in 'installed' mode
 and change path to %APPDATA% and %LOCALAPPDATA% if so change all access to
 config files and use path .combine for creating file and directory paths

---
 VECTO/ApplicationEvents.vb                | 73 +++++++++++++++++++----
 VECTO/File Browser/FileBrowserDialog.vb   | 12 ++--
 VECTO/GUI/MainForm.vb                     |  4 +-
 VECTO/VECTO_Global.vb                     | 39 ++++++++----
 VECTOAux/VectoAuxiliaries/UI/FB_Dialog.vb | 12 ++--
 5 files changed, 104 insertions(+), 36 deletions(-)

diff --git a/VECTO/ApplicationEvents.vb b/VECTO/ApplicationEvents.vb
index d9f9810ace..ec52e9a5ee 100644
--- a/VECTO/ApplicationEvents.vb
+++ b/VECTO/ApplicationEvents.vb
@@ -10,7 +10,10 @@
 ' See the LICENSE.txt for the specific language governing permissions and limitations.
 Imports System.Collections.Generic
 Imports System.IO
+Imports System.Linq
 Imports System.Text
+Imports TUGraz.VectoCommon.Utils
+Imports TUGraz.VectoCore.Utils
 
 Namespace My
 	' The following events are available for MyApplication:
@@ -22,6 +25,14 @@ Namespace My
 	' NetworkAvailabilityChanged: Occurs when connecting or disconnecting to the network.
 	' ReSharper disable once ClassNeverInstantiated.Global
 	Partial Friend Class MyApplication
+
+		Const INSTALL_SETTINGS_FILE As String = "install.ini"
+		Const CONFIG_FOLDER As string = "Config"
+		Const CONFIG_FILE_HISTORY_FOLDER As string = "FileHistory"
+		
+
+		Const APP_DATA_VENDOR_PATH As String = "VECTO"
+
 		'Initialization
 		Private Sub MyApplication_Startup(sender As Object, e As Microsoft.VisualBasic.ApplicationServices.StartupEventArgs) _
 			Handles Me.Startup
@@ -30,19 +41,38 @@ Namespace My
 			Dim i As Integer
 
 			'Paths
-			MyAppPath = Application.Info.DirectoryPath & "\"
-			MyConfPath = MyAppPath & "Config\"
+			MyAppPath = Application.Info.DirectoryPath
 
-			FileHistoryPath = MyConfPath & "FileHistory\"
+			ReadInstallMode()
 
-			'Log
-			LogFile = New FileLogger
-			If Not LogFile.StartLog() Then
-				MsgBox("Error! Can't access log file. Application folder needs read/write permissions!")
-				e.Cancel = True
+			MyConfPath = path.Combine(MyAppPath, CONFIG_FOLDER)
+			if (InstallModeInstalled) Then
+				MyConfPath = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData), APP_DATA_VENDOR_PATH, VectoSimulationCore.VersionNumber, CONFIG_FOLDER)
+				MyLogPath = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData), APP_DATA_VENDOR_PATH, VectoSimulationCore.VersionNumber)
 			End If
 
+			FileHistoryPath = path.Combine(MyConfPath, CONFIG_FILE_HISTORY_FOLDER)
+
+			
+
 			'If folder does not exist: Create!
+		    If Not Directory.Exists(MyLogPath) Then
+		        Try
+		            Directory.CreateDirectory(MyLogPath)
+		        Catch ex As Exception
+		            MsgBox("Failed to create directory '" & MyLogPath & "'!", MsgBoxStyle.Critical)
+		            'LogFile.WriteToLog(MessageType.Err, "Failed to create directory '" & MyLogPath & "'!")
+		            e.Cancel = True
+		        End Try
+		    End If
+
+		    'Log
+		    LogFile = New FileLogger
+		    If Not LogFile.StartLog() Then
+		        MsgBox("Error! Can't access log file. Application folder needs read/write permissions!")
+		        e.Cancel = True
+		    End If
+
 			If Not Directory.Exists(MyConfPath) Then
 				Try
 					Directory.CreateDirectory(MyConfPath)
@@ -51,9 +81,10 @@ Namespace My
 					LogFile.WriteToLog(MessageType.Err, "Failed to create directory '" & MyConfPath & "'!")
 					e.Cancel = True
 				End Try
-				File.Create(MyConfPath & "joblist.txt").Close()
-				File.Create(MyConfPath & "cyclelist.txt").Close()
+				File.Create(path.Combine(MyConfPath, CONFIG_JOBLIST_FILE)).Close()
+				File.Create(path.Combine(MyConfPath, CONFIG_CYCLELIST_FILE)).Close()
 			End If
+			
 			If Not Directory.Exists(FileHistoryPath) Then
 				Try
 					Directory.CreateDirectory(FileHistoryPath)
@@ -66,7 +97,7 @@ Namespace My
 					End Try
 					Try
 
-						Dim file As StreamWriter = Computer.FileSystem.OpenTextFileWriter(FileHistoryPath & "Directories.txt", True,
+						Dim file As StreamWriter = Computer.FileSystem.OpenTextFileWriter(Path.Combine(FileHistoryPath, FILE_HISTORY_DIR_FILE), True,
 																						Encoding.UTF8)
 						file.WriteLine(s)
 						For i = 2 To 20
@@ -103,7 +134,7 @@ Namespace My
 
 			Cfg = New Configuration _
 			'ACHTUNG: Configuration.New löst Configuration.SetDefault aus welches sKey benötigt dehalb muss sKey schon vorher initialisiert werden!!
-			Cfg.FilePath = MyConfPath & "settings.json"
+			Cfg.FilePath = Path.Combine(MyConfPath, "settings.json")
 
 			ProgBarCtrl = New ProgressbarControl
 
@@ -114,6 +145,24 @@ Namespace My
 			LogFile.SizeCheck()
 		End Sub
 
+		Private Sub ReadInstallMode()
+
+			if (file.Exists(path.Combine(MyAppPath, INSTALL_SETTINGS_FILE))) Then
+				Try 
+					Dim lines As List(Of String) = file.readlines(path.Combine(MyAppPath, INSTALL_SETTINGS_FILE)).Where(function(s1) Not(s1.RemoveWhitespace().StartsWith("#"))).toList()
+					Dim installSetting as String = lines.LastOrDefault(function(s1) s1.StartsWith("ExecutionMode", StringComparison.InvariantCultureIgnoreCase))
+					if (Not(string.IsNullOrWhiteSpace(installSetting))) then
+						Dim parts As String() = installSetting.split("="c)
+						if (parts.Length > 1 AndAlso "install".Equals(parts(1).RemoveWhitespace(), StringComparison.InvariantCultureIgnoreCase)) then
+							InstallModeInstalled = True
+						End If
+					End If
+				Catch ex As Exception
+					'do nothing...
+				End Try
+			End If
+		End Sub
+
 		Private Sub MyApplication_UnhandledException(ByVal sender As Object,
 													ByVal e As Microsoft.VisualBasic.ApplicationServices.UnhandledExceptionEventArgs) _
 			Handles Me.UnhandledException
diff --git a/VECTO/File Browser/FileBrowserDialog.vb b/VECTO/File Browser/FileBrowserDialog.vb
index d16a69c22d..dbc210f44c 100644
--- a/VECTO/File Browser/FileBrowserDialog.vb	
+++ b/VECTO/File Browser/FileBrowserDialog.vb	
@@ -300,7 +300,7 @@ Public Class FileBrowserDialog
 		'Folder History
 		If FileBrowserFolderHistoryIninialized Then
 			Try
-				Dim f = My.Computer.FileSystem.OpenTextFileWriter(FileHistoryPath & "Directories.txt", False, Encoding.UTF8)
+				Dim f = My.Computer.FileSystem.OpenTextFileWriter(path.Combine(FileHistoryPath, FILE_HISTORY_DIR_FILE), False, Encoding.UTF8)
 				For x = 0 To 19
 					f.WriteLine(FileBrowserFolderHistory(x))
 				Next
@@ -314,7 +314,7 @@ Public Class FileBrowserDialog
 		If _initialized And Not _bLightMode Then
 			If Not _bBrowseFolder Then
 				Try
-					Dim f = My.Computer.FileSystem.OpenTextFileWriter(FileHistoryPath & _myId & ".txt", False, Encoding.UTF8)
+					Dim f = My.Computer.FileSystem.OpenTextFileWriter(Path.Combine(FileHistoryPath,  _myId & ".txt"), False, Encoding.UTF8)
 					For x = 0 To 9
 						f.WriteLine(ContextMenuHisFile.Items(x).Text)
 					Next
@@ -374,8 +374,8 @@ Public Class FileBrowserDialog
 			For x = 0 To 9
 				ContextMenuHisFile.Items.Add("")
 			Next
-			If File.Exists(FileHistoryPath & _myId & ".txt") Then
-				Dim f = New StreamReader(FileHistoryPath & _myId & ".txt")
+			If File.Exists(path.Combine(FileHistoryPath, _myId & ".txt")) Then
+				Dim f = New StreamReader(path.Combine(FileHistoryPath, _myId & ".txt"))
 				Dim x = -1
 				Do While Not f.EndOfStream And x < 9
 					x += 1
@@ -420,8 +420,8 @@ Public Class FileBrowserDialog
 		For x = 0 To 19
 			FileBrowserFolderHistory(x) = EmptyText
 		Next
-		If File.Exists(FileHistoryPath & "Directories.txt") Then
-			Dim f = New StreamReader(FileHistoryPath & "Directories.txt")
+		If File.Exists(path.Combine(FileHistoryPath, FILE_HISTORY_DIR_FILE)) Then
+			Dim f = New StreamReader(path.Combine(FileHistoryPath, FILE_HISTORY_DIR_FILE))
 			x = -1
 			Do While Not f.EndOfStream And x < 19
 				x += 1
diff --git a/VECTO/GUI/MainForm.vb b/VECTO/GUI/MainForm.vb
index 1f35cdf962..2105f1a79b 100644
--- a/VECTO/GUI/MainForm.vb
+++ b/VECTO/GUI/MainForm.vb
@@ -234,9 +234,9 @@ Imports TUGraz.VectoCore.Utils
 
 
         'FileLists
-        _jobListView = New FileListView(MyConfPath & "joblist.txt")
+        _jobListView = New FileListView(path.Combine(MyConfPath, CONFIG_JOBLIST_FILE))
         _jobListView.LVbox = LvGEN
-        _cycleListView = New FileListView(MyConfPath & "cyclelist.txt")
+        _cycleListView = New FileListView(path.Combine(MyConfPath, CONFIG_CYCLELIST_FILE))
 
         _jobListView.LoadList()
 
diff --git a/VECTO/VECTO_Global.vb b/VECTO/VECTO_Global.vb
index 7adb29fa6b..74bbb8eedf 100644
--- a/VECTO/VECTO_Global.vb
+++ b/VECTO/VECTO_Global.vb
@@ -17,8 +17,14 @@ Public Module VECTO_Global
 	Public COREvers As String = "NOT FOUND"
 
 	Public Const LicSigAppCode As String = "VECTO-Release-0093C61E0A2E4BFA9A7ED7E729C56AE4"
+	public InstallModeInstalled As Boolean = False
 	Public MyAppPath As String
 	Public MyConfPath As String
+	public MyLogPath As String
+
+	public Const CONFIG_JOBLIST_FILE As string =  "joblist.txt"
+	public const CONFIG_CYCLELIST_FILE As string = "cyclelist.txt"
+    public Const FILE_HISTORY_DIR_FILE As string = "Directories.txt"
 
 
 	Public LogFile As FileLogger
@@ -37,9 +43,24 @@ Public Module VECTO_Global
 	Public Class FileLogger
 		Private _logStream As StreamWriter
 
+		Const LOG_FILENAME As string = "LOG.txt"
+		Const BACKUP_LOG_FILENAME As String = "LOG_backup.txt"
+
+		Private logPath as string
+		Private logFile As string
+
+		public sub New()
+			logPath = MyAppPath
+			If (InstallModeInstalled) Then
+				logPath = MyLogPath
+			End If
+			logFile = path.Combine(logPath, LOG_FILENAME)
+		End sub
+
+
 		Public Function StartLog() As Boolean
 			Try
-				_logStream = My.Computer.FileSystem.OpenTextFileWriter(MyAppPath & "LOG.txt", True, FileFormat)
+				_logStream = My.Computer.FileSystem.OpenTextFileWriter(logFile, True, FileFormat)
 				_logStream.AutoFlush = True
 				WriteToLog(MessageType.Normal, "Starting Session " & Now)
 				WriteToLog(MessageType.Normal, "VECTO " & VECTOvers)
@@ -51,14 +72,12 @@ Public Module VECTO_Global
 		End Function
 
 		Public Function SizeCheck() As Boolean
-			Dim logfDetail As FileInfo
-			Dim backUpError As Boolean
 
 			'Start new log if file size limit reached
-			If File.Exists(MyAppPath & "LOG.txt") Then
+			If File.Exists(logFile) Then
 
 				'File size check
-				logfDetail = My.Computer.FileSystem.GetFileInfo(MyAppPath & "LOG.txt")
+				Dim logfDetail As FileInfo = My.Computer.FileSystem.GetFileInfo(logFile)
 
 				'If Log too large: Delete
 				If logfDetail.Length / (2 ^ 20) > Cfg.LogSize Then
@@ -66,11 +85,11 @@ Public Module VECTO_Global
 					WriteToLog(MessageType.Normal, "Starting new logfile")
 					_logStream.Close()
 
-					backUpError = False
+					Dim backUpError As Boolean = False
 
 					Try
-						If File.Exists(MyAppPath & "LOG_backup.txt") Then File.Delete(MyAppPath & "LOG_backup.txt")
-						File.Move(MyAppPath & "LOG.txt", MyAppPath & "LOG_backup.txt")
+						If File.Exists(path.Combine(logPath, BACKUP_LOG_FILENAME)) Then File.Delete(path.Combine(logPath, BACKUP_LOG_FILENAME))
+						File.Move(logFile, path.Combine(logPath, BACKUP_LOG_FILENAME))
 					Catch ex As Exception
 						backUpError = True
 					End Try
@@ -78,9 +97,9 @@ Public Module VECTO_Global
 					If Not StartLog() Then Return False
 
 					If backUpError Then
-						WriteToLog(MessageType.Err, "Failed to backup logfile! (" & MyAppPath & "LOG_backup.txt)")
+						WriteToLog(MessageType.Err, "Failed to backup logfile! (" & Path.Combine(logPath, BACKUP_LOG_FILENAME) & ")")
 					Else
-						WriteToLog(MessageType.Normal, "Logfile restarted. Old log saved to LOG_backup.txt")
+						WriteToLog(MessageType.Normal, "Logfile restarted. Old log saved to " & BACKUP_LOG_FILENAME)
 					End If
 
 				End If
diff --git a/VECTOAux/VectoAuxiliaries/UI/FB_Dialog.vb b/VECTOAux/VectoAuxiliaries/UI/FB_Dialog.vb
index 3256310fbb..0a795f3275 100644
--- a/VECTOAux/VectoAuxiliaries/UI/FB_Dialog.vb
+++ b/VECTOAux/VectoAuxiliaries/UI/FB_Dialog.vb
@@ -300,7 +300,7 @@ Public Class FB_Dialog
 		'Folder History
 		If FB_Init Then
 			Try
-				Dim f = My.Computer.FileSystem.OpenTextFileWriter(FB_FilHisDir & "Directories.txt", False, Encoding.UTF8)
+				Dim f = My.Computer.FileSystem.OpenTextFileWriter(Path.Combine(FB_FilHisDir, "Directories.txt"), False, Encoding.UTF8)
 				For x = 0 To 19
 					f.WriteLine(FB_FolderHistory(x))
 				Next
@@ -314,7 +314,7 @@ Public Class FB_Dialog
 		If _initialized And Not _bLightMode Then
 			If Not _bBrowseFolder Then
 				Try
-					Dim f = My.Computer.FileSystem.OpenTextFileWriter(FB_FilHisDir & _myId & ".txt", False, Encoding.UTF8)
+					Dim f = My.Computer.FileSystem.OpenTextFileWriter(Path.Combine(FB_FilHisDir,  _myId & ".txt"), False, Encoding.UTF8)
 					For x = 0 To 9
 						f.WriteLine(ContextMenuHisFile.Items(x).Text)
 					Next
@@ -374,8 +374,8 @@ Public Class FB_Dialog
 			For x = 0 To 9
 				ContextMenuHisFile.Items.Add("")
 			Next
-			If File.Exists(FB_FilHisDir & _myId & ".txt") Then
-				Dim f = New StreamReader(FB_FilHisDir & _myId & ".txt")
+			If File.Exists(path.Combine(FB_FilHisDir,  _myId & ".txt")) Then
+				Dim f = New StreamReader(path.Combine(FB_FilHisDir, _myId & ".txt"))
 				Dim x = -1
 				Do While Not f.EndOfStream And x < 9
 					x += 1
@@ -418,8 +418,8 @@ Public Class FB_Dialog
 		For x = 0 To 19
 			FB_FolderHistory(x) = EmptyText
 		Next
-		If File.Exists(FB_FilHisDir & "Directories.txt") Then
-			Dim f = New StreamReader(FB_FilHisDir & "Directories.txt")
+		If File.Exists(path.Combine(FB_FilHisDir, "Directories.txt")) Then
+			Dim f = New StreamReader(path.Combine(FB_FilHisDir,"Directories.txt"))
 			x = -1
 			Do While Not f.EndOfStream And x < 19
 				x += 1
-- 
GitLab