sltSync/sltSync/frmMain.vb
2023-06-30 13:44:18 +02:00

274 lines
9.6 KiB
VB.net

Imports System.ComponentModel
Imports System.Configuration
Imports System.Data.SqlClient
Imports System.IO
Imports System.Text
Imports DigitalData.Modules.Base
Imports DigitalData.Modules.Base.IDB
Imports DigitalData.Modules.Config
Imports DigitalData.Modules.Database
Imports DigitalData.Modules.Logging
Imports Microsoft.Win32
Partial Public Class frmMain
Private LogConfig As LogConfig
Private Logger As Logger
Private ConfigManager As ConfigManager(Of Config)
Private Database As MSSQLServer
Private Sync As sltSync
Private FileEx As FileEx
Public Sub New()
InitializeComponent()
End Sub
Private Async Sub frmMain_Load(sender As Object, e As EventArgs) Handles Me.Load
Try
LogConfig = New LogConfig(LogConfig.PathType.CustomPath, Application.LocalUserAppDataPath, CompanyName:="Digital Data", ProductName:="sltSync")
Logger = LogConfig.GetLogger()
ConfigManager = New ConfigManager(Of Config)(LogConfig, Application.UserAppDataPath)
FileEx = New FileEx()
LogConfig.Debug = ConfigManager.Config.Debug
SyncTimer.Interval = ConfigManager.Config.TimerIntervalMin * 60 * 1_000
AddInfoEntry("Application started.")
AddInfoEntry("Version: {0}", Application.ProductVersion)
AddInfoEntry("Timer Interval: {0} min", ConfigManager.Config.TimerIntervalMin.ToString)
AddDivider()
Database = New MSSQLServer(LogConfig, ConfigManager.Config.ConnectionString)
Sync = New sltSync(LogConfig, ConfigManager.Config)
If Database.DBInitialized = False Then
AddWarnEntry("Database could not be initialized. Please check connection string.")
Else
If ConfigManager.Config.Autostart Then
Await RunSync()
End If
StartTimer()
End If
Catch ex As Exception
Logger.Error(ex)
AddWarnEntry($"Error while loading the application: {ex.Message}")
End Try
End Sub
Private Async Function frmMain_Closing(sender As Object, e As CancelEventArgs) As Threading.Tasks.Task Handles Me.Closing
Try
If Sync IsNot Nothing AndAlso Sync.IsLoggedIn Then
AddInfoEntry("Logging out..")
Await Sync.Logout()
End If
Catch ex As Exception
Logger.Error(ex)
AddWarnEntry($"Error while closing the application: {ex.Message}")
End Try
End Function
Private Sub StartTimer()
If TestConfigurationIsComplete() = False Then
AddInfoEntry("Configuration is incomplete. Stopping.")
AddDivider()
Else
AddInfoEntry("Starting timer..")
btnStopSync.Enabled = True
btnSyncStart.Enabled = False
SyncTimer.Enabled = True
End If
End Sub
Private Sub StopTimer()
AddInfoEntry("Stopping timer..")
btnStopSync.Enabled = False
btnSyncStart.Enabled = True
SyncTimer.Enabled = False
End Sub
Private Async Function Timer_Elapsed(sender As Object, e As System.EventArgs) As Threading.Tasks.Task Handles SyncTimer.Tick
Await RunSync()
End Function
Private Async Function RunSync() As Threading.Tasks.Task
Try
AddInfoEntry("Starting Sync.")
AddDivider()
Dim oOutputDirectory As String = ConfigManager.Config.OutputDirectory
If Directory.Exists(oOutputDirectory) = False Then
Throw New DirectoryNotFoundException($"Directory '{oOutputDirectory}' does not exist.")
End If
Dim oTable As DataTable = Await Database.GetDatatableAsync(ConfigManager.Config.SQLQueryFetch)
Dim oExtDocIds = oTable.Rows.Cast(Of DataRow).Select(Function(r) r.Item(0).ToString()).ToList()
AddInfoEntry("Found [{0}] files.", oExtDocIds.Count.ToString)
AddInfoEntry("Logging in..")
Await Sync.GetAvailableSystems()
Await Sync.Login(ConfigManager.Config.SystemId)
For Each oDocId As String In oExtDocIds
Try
Logger.Debug("Fetching document from API..")
Dim oDocument = Await Sync.GetDocumentContent(oDocId)
Logger.Debug("Document fetched!")
AddInfoEntry("Document: [{0}]", oDocument.Name)
Logger.Info("ExtDocId: [{0}]", oDocument.ExtDocId)
Dim oFileName = GetFilenameWithExtension(oDocument.Name, oDocument.DocMimeType)
Dim oFilePath = Path.Combine(oOutputDirectory, oFileName)
Using oStream As New MemoryStream(oDocument.Data)
Using oWriter As New FileStream(oFilePath, FileMode.Create)
oStream.CopyTo(oWriter)
End Using
End Using
Dim oSQL = String.Format(ConfigManager.Config.SQLQueryExport, oDocument.ExtDocId, oFileName)
Await Database.ExecuteNonQueryAsync(oSQL)
Catch ex As Exception
Logger.Error(ex)
AddWarnEntry("Error while running Sync: " & ex.Message)
End Try
Next
Catch ex As Exception
Logger.Error(ex)
AddWarnEntry("Error while running Sync: " & ex.Message)
End Try
Try
AddInfoEntry("Finished Sync.")
AddInfoEntry("Logging Out..")
AddDivider()
Await Sync.Logout()
Catch ex As Exception
Logger.Error(ex)
AddWarnEntry("Error while logging out: " & ex.Message)
End Try
End Function
Private Function GetFilenameWithExtension(pFilename As String, pMimetype As String) As String
Try
If pMimetype = "application/outlook" Then
pMimetype = "application/vnd.ms-outlook"
End If
Dim oExtension = FileEx.GetExtension(pMimetype)
Return StringEx.ConvertTextToSlug(pFilename) & oExtension
Catch ex As Exception
AddWarnEntry("File [{0}] does not have a valid mimetype [{1}]. Returning original filename.", pFilename, pMimetype)
Return pFilename
End Try
End Function
Private Sub AddInfoEntry(pMessage As String, ParamArray pArgs As Object())
Logger.Info(pMessage, pArgs)
ListBoxControl1.Items.Add(Now & " " & String.Format(pMessage, pArgs))
End Sub
Private Sub AddWarnEntry(pMessage As String, ParamArray pArgs As Object())
Logger.Info(pMessage, pArgs)
ListBoxControl1.Items.Add(String.Format(pMessage, pArgs))
End Sub
Private Sub AddDivider()
ListBoxControl1.Items.Add("=====================================")
End Sub
Private Function TestConfigurationIsComplete() As Boolean
Dim oComplete = True
If ConfigManager.Config.Hostname = String.Empty Then
AddWarnEntry("Configuration for 'Hostname' is empty.")
oComplete = False
End If
If ConfigManager.Config.Port = String.Empty Then
AddWarnEntry("Configuration for 'Port' is empty.")
oComplete = False
End If
If ConfigManager.Config.Username = String.Empty Then
AddWarnEntry("Configuration for 'Username' is empty.")
oComplete = False
End If
If ConfigManager.Config.Password = String.Empty Then
AddWarnEntry("Configuration for 'Password' is empty.")
oComplete = False
End If
If ConfigManager.Config.ConnectionString = String.Empty Then
AddWarnEntry("Configuration for 'ConnectionString' is empty.")
oComplete = False
End If
If ConfigManager.Config.SQLQueryFetch = String.Empty Then
AddWarnEntry("Configuration for 'SQLQueryFetch' is empty.")
oComplete = False
End If
If ConfigManager.Config.SQLQueryExport = String.Empty Then
AddWarnEntry("Configuration for 'SQLQueryExport' is empty.")
oComplete = False
End If
If ConfigManager.Config.OutputDirectory = String.Empty Then
AddWarnEntry("Configuration for 'OutputDirectory' is empty.")
oComplete = False
End If
Return oComplete
End Function
Private Sub BarButtonItem1_ItemClick(sender As Object, e As DevExpress.XtraBars.ItemClickEventArgs) Handles BarButtonItem1.ItemClick
Try
Dim oPath = LogConfig.LogDirectory
Process.Start("explorer.exe", oPath)
Catch ex As Exception
Logger.Error(ex)
End Try
End Sub
Private Sub btnSyncStart_ItemClick(sender As Object, e As DevExpress.XtraBars.ItemClickEventArgs) Handles btnSyncStart.ItemClick
StartTimer()
End Sub
Private Sub btnStopSync_ItemClick(sender As Object, e As DevExpress.XtraBars.ItemClickEventArgs) Handles btnStopSync.ItemClick
StopTimer()
End Sub
Private Sub btnToggleWindow_Click(sender As Object, e As EventArgs) Handles btnToggleWindow.Click
ToggleWindow()
End Sub
Private Sub btnExit_Click(sender As Object, e As EventArgs) Handles btnExit.Click
Close()
End Sub
Private Sub TrayIcon_MouseDoubleClick(sender As Object, e As MouseEventArgs) Handles TrayIcon.MouseDoubleClick
ToggleWindow()
End Sub
Private Sub ToggleWindow()
If Visible = True Then
Hide()
Else
WindowState = FormWindowState.Minimized
Show()
WindowState = FormWindowState.Normal
End If
End Sub
End Class