246 lines
12 KiB
VB.net

Imports DigitalData.Modules.Database
Imports DigitalData.Modules.Logging
Imports System.ComponentModel
Imports System.IO
Imports System.Security.Cryptography
Imports System.Text
Public Class MyService
#Region "+++++ variables +++++"
Private _threadRunner As BackgroundWorker
Private MyLogger As LogConfig
Private Logger As Logger
Private Database_ECM As MSSQLServer = Nothing
Private DT_CONFIG As DataTable
Private oENVELOPE_ID As Integer = 0
Private oENVELOPE_UUID As String = ""
Private Directory2Delete As String = ""
Private DOCUMENT_PATH_MOVE_AFTSEND As String = ""
Private DOCUMENT_PATH As String = ""
Private FILE_NAME As String = ""
#End Region
Protected Overrides Sub OnStart(ByVal args() As String)
Try
MyLogger = New LogConfig(LogConfig.PathType.CustomPath, Path.Combine(My.Application.Info.DirectoryPath, "Log"), Nothing, "Digital Data", "DDsignFLOWFolderSync")
Logger = MyLogger.GetLogger
MyLogger.Debug = My.Settings.DEBUG
Database_ECM = New MSSQLServer(MyLogger, My.Settings.DD_ECM_CS)
If Database_ECM.DBInitialized = False Then
Logger.Warn("ATTENTION: No Connection was established - Check Config")
Else
DT_CONFIG = Database_ECM.GetDatatable("SELECT * FROM TBSIG_CONFIG ")
DOCUMENT_PATH_MOVE_AFTSEND = DT_CONFIG.Rows(0).Item("DOCUMENT_PATH_MOVE_AFTSEND")
DOCUMENT_PATH = DT_CONFIG.Rows(0).Item("DOCUMENT_PATH")
'### Thread für das nachträgliche Setzen von Rechten generieren
_threadRunner = New BackgroundWorker()
_threadRunner.WorkerReportsProgress = True
_threadRunner.WorkerSupportsCancellation = True
AddHandler _threadRunner.DoWork, AddressOf RUN_THREAD
AddHandler _threadRunner.RunWorkerCompleted, AddressOf Thread1_Completed
'### Den Timer generieren
Dim Timer_Durchlauf As New System.Timers.Timer()
'Das Event hinterlegen welches bei "Tick" ausgelöst wird
AddHandler Timer_Durchlauf.Elapsed, AddressOf Thread_Run
' Set the Interval
Timer_Durchlauf.Interval = (My.Settings.TimerIntervall * 60000)
Timer_Durchlauf.Enabled = True
Logger.Debug("...Timer started.")
' Und den Durchlauf das erste Mal starten
_threadRunner.RunWorkerAsync()
End If
Catch ex As Exception
Logger.Error(ex)
End Try
End Sub
Public Sub Thread_Run()
If Not _threadRunner.IsBusy Then
_threadRunner.RunWorkerAsync()
End If
End Sub
Public Sub RUN_THREAD(ByVal sender As Object, ByVal e As System.ComponentModel.DoWorkEventArgs)
Try
Work_Envelopes()
Catch ex As Exception
Logger.Error(ex)
End Try
End Sub
Private Sub Work_Envelopes()
Try
Dim oDT_Envelopes As DataTable = Database_ECM.GetDatatable(My.Settings.Select_Status1_Send)
oENVELOPE_ID = 0
If Not IsNothing(oDT_Envelopes) Then
For Each oRow As DataRow In oDT_Envelopes.Rows
oENVELOPE_ID = 0
oENVELOPE_UUID = ""
oENVELOPE_UUID = oRow.Item("ENVELOPE_UUID")
oENVELOPE_ID = oRow.Item("GUID")
Logger.Info($"Working on Envelope-UUID [{oENVELOPE_UUID}] - ENVELOPE_ID: {oENVELOPE_ID}")
Dim oSourcePath As String
Dim oDestinationPath As String
Dim oDT_Files As DataTable = Database_ECM.GetDatatable("SELECT * FROM TBSIG_ENVELOPE_DOCUMENT where ENVELOPE_ID = " & oENVELOPE_ID)
If oDT_Files.Rows.Count > 0 Then
Logger.Debug("Working on [{0}] file(s) ", oDT_Files.Rows.Count)
For Each ofileRow As DataRow In oDT_Files.Rows
FILE_NAME = ""
FILE_NAME = ofileRow.Item("FILENAME")
oSourcePath = IO.Path.Combine(DOCUMENT_PATH, oENVELOPE_UUID, FILE_NAME)
oDestinationPath = IO.Path.Combine(DOCUMENT_PATH_MOVE_AFTSEND, oENVELOPE_UUID)
If CopyFileWithNetUse(oSourcePath, oDestinationPath) = True Then
Database_ECM.ExecuteNonQuery($"UPDATE TBSIG_ENVELOPE SET DMZ_MOVED = 1 WHERE GUID = {oENVELOPE_ID}")
If Directory2Delete <> String.Empty Then
Logger.Debug("Now Deleting SourcePath: {0} ...", Directory2Delete)
Try
System.IO.Directory.Delete(Directory2Delete, True)
Logger.Debug("Successfully deleted Sourcepath!")
Catch ex As Exception
Logger.Warn($"Unexpected Error while deleting SourcePath {Directory2Delete}")
Logger.Warn("ErrorMessage: {0}", ex.Message)
End Try
End If
End If
Next
End If
Next
End If
Catch ex As Exception
Logger.Error(ex)
End Try
End Sub
Private Shared key As String = "$xzBvyPETUS&amm8)D8x#)f;4%;?[BPd" ' Passwort-Schlüssel (16, 24, or 32 bytes)
Private Shared iv As String = "1wN&e[zrQ6_B7X/0" ' Initialisierungsvektor (16 bytes)
' Entschlüsselungsfunktion
Private Function Decrypt(cipherText As String) As String
'Logger.Debug("cipherText: {0}", cipherText)
' Logger.Debug("Aes.Create ...")
Dim aesAlg As Aes = Aes.Create()
' Logger.Debug("Encoding UTF8 GetBytes key ...")
aesAlg.Key = Encoding.UTF8.GetBytes(key)
'Logger.Debug("Encoding UTF8 GetBytes iv ...")
aesAlg.IV = Encoding.UTF8.GetBytes(iv)
'Logger.Debug("aesAlg.CreateDecryptor ...")
Dim decryptor As ICryptoTransform = aesAlg.CreateDecryptor(aesAlg.Key, aesAlg.IV)
'Logger.Debug("Convert.FromBase64String ...")
Dim cipherBytes As Byte() = Convert.FromBase64String(cipherText)
Dim msDecrypt As New IO.MemoryStream(cipherBytes)
Using csDecrypt As New CryptoStream(msDecrypt, decryptor, CryptoStreamMode.Read)
Using srDecrypt As New IO.StreamReader(csDecrypt)
Return srDecrypt.ReadToEnd()
End Using
End Using
End Function
Private Function CopyFileWithNetUse(pSourcePath As String, pDestinationPath As String) As Boolean
Logger.Debug("EXECUTING CopyFileWithNetUse for " & pDestinationPath)
Dim oDirectoryExists As Boolean = False
Try
If Directory.Exists(DOCUMENT_PATH_MOVE_AFTSEND) Then
Logger.Debug($"Access to [{DOCUMENT_PATH_MOVE_AFTSEND}] already succeeded!")
oDirectoryExists = True
End If
Catch ex As Exception
Logger.Warn("CopyFileWithNetUse - path not accessible or existing: {0}", ex.Message)
Logger.Error(ex)
End Try
Logger.Debug("CopyFileWithNetUse - Folder accessible [{0}]", oDirectoryExists.ToString)
If oDirectoryExists = False Then
Dim oDectryptedPW = Decrypt(My.Settings.NetUse_PW)
Logger.Debug("Successfully decrypted PW!")
Dim netUseCommand As String = $"net use {DOCUMENT_PATH_MOVE_AFTSEND} /user:{My.Settings.NetUse_Usr} {oDectryptedPW}"
Dim processInfo As New ProcessStartInfo("cmd.exe", $"/C {netUseCommand}")
processInfo.RedirectStandardOutput = True
processInfo.RedirectStandardInput = True
processInfo.UseShellExecute = False
processInfo.CreateNoWindow = True
Using oProcess As Process = Process.Start(processInfo)
oProcess.WaitForExit()
' Prüfe den Rückgabewert des net use Befehls
If oProcess.ExitCode = 0 Then
' Verschiebe die Datei
Try
Dim oReturn = COPY_TO_DMZ(pSourcePath, pDestinationPath)
oProcess.Close()
Return oReturn
Catch ex As Exception
oProcess.Close()
Logger.Warn($"Unexpected error in CopyFileWithNetUse [" & pDestinationPath + "]")
Logger.Warn(ex.Message)
Logger.Error(ex)
Return False
End Try
Else
Logger.Warn("Error while connecting to network-path: " & pDestinationPath)
Return False
End If
End Using
Else
Return COPY_TO_DMZ(pSourcePath, pDestinationPath)
End If
End Function
Private Function COPY_TO_DMZ(pSourcePath As String, pDestinationPath As String) As Boolean
Try
Logger.Debug("EXECUTING COPY_TO_DMZ {0} ...", pDestinationPath)
Dim oFilename = System.IO.Path.GetFileName(pSourcePath)
Dim oFilePath As String = pSourcePath
Dim oSourceDirectory As String = Path.GetDirectoryName(oFilePath)
Dim split As String() = oFilePath.Split("\")
Dim parentFolder As String = split(split.Length - 2)
If Not pDestinationPath.EndsWith(parentFolder) Then
pDestinationPath &= "\" + parentFolder
Logger.Debug("new oSourceDirectory = {0} ...", pDestinationPath)
End If
If Not System.IO.Directory.Exists(pDestinationPath) Then
Logger.Debug("Creating Folder {0} ...", pDestinationPath)
System.IO.Directory.CreateDirectory(pDestinationPath)
Logger.Debug("...Folder successfully created!")
End If
If Not System.IO.Directory.Exists(pDestinationPath) Then
Logger.Warn("Folder {0} could not be created!", pDestinationPath)
Return False
End If
pDestinationPath &= "\" + oFilename
If File.Exists(pDestinationPath) Then
File.Delete(pDestinationPath)
End If
Logger.Debug("Now copying file ...")
Logger.Debug("from [{0}] ", pSourcePath)
Logger.Debug("to [{0}]... ", pDestinationPath)
System.IO.File.Copy(pSourcePath, pDestinationPath)
Logger.Info($"Successfully copied file to DMZ [{pDestinationPath}]")
Directory2Delete = oSourceDirectory
Return True
Catch ex As Exception
Logger.Warn("COPY_TO_DMZ - Unexpected error {0}", ex.Message)
Logger.Error(ex)
Return False
End Try
End Function
Protected Overrides Sub OnStop()
' Hier Code zum Ausführen erforderlicher Löschvorgänge zum Beenden des Dienstes einfügen.
Logger.Info("## Service was stopped manually. ##")
End Sub
Private Sub Thread1_Completed(ByVal sender As Object, ByVal e As System.ComponentModel.RunWorkerCompletedEventArgs) 'Handles threadDateiimport.RunWorkerCompleted
'This event fires when the DoWork event completes
Try
Dim result As String = ""
If e.Cancelled Then
EventLog.WriteEntry("DDsignFLOWFolderSync", "The thread was cancelled!", EventLogEntryType.Error)
Logger.Warn("## The thread was cancelled.")
ElseIf e.Error IsNot Nothing Then
EventLog.WriteEntry("DDsignFLOWFolderSync", "Unexpected error in thread!", EventLogEntryType.Error)
Logger.Warn("Unexpected error in thread: " & e.Error.Message)
End If
Catch ex As Exception
Logger.Error(ex)
End Try
End Sub
End Class