ResulHandlerMSSQL/app/DDWDResultHandler/DDWDResultHandler.vb
Digital Data - Marlon Schreiber 24f052f5b5 MS
2018-11-07 15:11:52 +01:00

490 lines
29 KiB
VB.net

Imports System.IO
'Imports System.Collections.ObjectModel
Imports System.ComponentModel
Imports DigitalData.Modules.Logging
Imports DD_WMResulthandler
Public Class DDWDResultHandler
#Region "+++++ Variablen +++++"
Private _windream As DD_WMResulthandler.clsWindream_allgemein
Private _windreamPMR As DD_WMResulthandler.clsWindream_allgemein
Private _database As DD_WMResulthandler.clsDatabase
Private _databasePMR As DD_WMResulthandler.clsDatabase
Private _profil As clsProfil
Public Shared threadRunner As BackgroundWorker
Public Shared threadPMRefresh As BackgroundWorker
Private Logger As Logger
Private Shared MyLogger As LogConfig
Private LoggerPMR As Logger
Private Shared MyLoggerPMR As LogConfig
Public Shared _PROFIL_ID As Integer
Dim _INTERVALL As Integer
Dim oFirstRun As Boolean = False
'Variablen für Dateiimporter
#End Region
Public Sub New()
MyBase.New()
InitializeComponent()
End Sub
Protected Overrides Sub OnStart(ByVal args() As String)
' Code zum Starten des Dienstes hier einfügen. Diese Methode sollte Vorgänge
' ausführen, damit der Dienst gestartet werden kann.
'EventLog1.WriteEntry("Dienst 'DD windream Result Handler' gestartet")
Try
If Not System.Diagnostics.EventLog.SourceExists("DDWMResultHandler") Then
System.Diagnostics.EventLog.CreateEventSource("DDWMResultHandler", "DigitalData Log")
End If
Catch ex As Exception
EventLog.WriteEntry("DDWMResultHandler", "ERROR in Creating source:" & ex.ToString(), EventLogEntryType.Error)
End Try
Try
Try
MyLogger = New LogConfig(LogConfig.PathType.CustomPath, Path.Combine(My.Application.Info.DirectoryPath, "Log"))
Logger = MyLogger.GetLogger()
_database = New clsDatabase(MyLogger, My.Settings.SQLSERVER_CS)
Catch ex As Exception
EventLog.WriteEntry("DDWMResultHandler", "ERROR in CREATING-LOG:" & ex.ToString(), EventLogEntryType.Error)
End Try
If My.Settings.SQLSERVER_CS = String.Empty Then
Logger.Warn("Achtung: Es wurde noch kein Datenbank-ConnectionString hinterlegt.")
Else
If _database.Init(My.Settings.SQLSERVER_CS) = False Then
Logger.Warn("Achtung: Es konnte keine Verbindung zur Datenbank '" & My.Settings.SQLSERVER_CS & "' hergestellt werden!")
Else
If clsCURRENT.LOG_ERRORS_ONLY = False Then
MyLogger.Debug = True
Else
MyLogger.Debug = False
End If
oFirstRun = True
' '#Thread für Durchlauf generieren
DDWDResultHandler.threadRunner = New BackgroundWorker()
DDWDResultHandler.threadRunner.WorkerReportsProgress = True
DDWDResultHandler.threadRunner.WorkerSupportsCancellation = True
AddHandler threadRunner.DoWork, AddressOf RUN_THREAD
AddHandler threadRunner.RunWorkerCompleted, AddressOf Thread_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 = 60000
'ClassLogger.Add("Timer - Intervall: " & clsSQLITE.konf_intervall & " Minuten", False)
Timer_Durchlauf.Enabled = True
Logger.Debug("Timer gestartet")
' Und den Durchlauf das erste Mal starten
DDWDResultHandler.threadPMRefresh = New BackgroundWorker()
DDWDResultHandler.threadPMRefresh.WorkerReportsProgress = True
DDWDResultHandler.threadPMRefresh.WorkerSupportsCancellation = True
AddHandler threadPMRefresh.DoWork, AddressOf RUNPMRefresh
AddHandler threadPMRefresh.RunWorkerCompleted, AddressOf ThreadPMRefresh_Completed
' '### Den Timer generieren
Dim TimerPMRefresh As New System.Timers.Timer()
'Das Event hinterlegen welches bei "Tick" ausgelöst wird
AddHandler TimerPMRefresh.Elapsed, AddressOf ThreadPMRefreshRun
' Set the Interval
TimerPMRefresh.Interval = 353000
'ClassLogger.Add("Timer - Intervall: " & clsSQLITE.konf_intervall & " Minuten", False)
TimerPMRefresh.Enabled = True
' Und den Durchlauf das erste Mal starten
threadRunner.RunWorkerAsync()
End If
End If
Catch ex As Exception
EventLog.WriteEntry("DDWMResultHandler", "Unexpected error in OnStart: " & ex.ToString(), EventLogEntryType.Error)
Logger.Error(ex)
End Try
End Sub
Public Sub Thread_Run()
If Not threadRunner.IsBusy Then
threadRunner.RunWorkerAsync()
End If
End Sub
Public Sub ThreadPMRefreshRun()
Logger.Info("In Tick of ThreadPMRefreshRun")
If Not threadPMRefresh.IsBusy Then
threadPMRefresh.RunWorkerAsync()
Else
Logger.Warn("threadPMRefresh IsBusy")
End If
End Sub
Protected Overrides Sub OnStop()
Try
' Hier Code zum Ausführen erforderlicher Löschvorgänge zum Beenden des Dienstes einfügen.
Logger.Warn("WindreamResultHandler wurde gestoppt - " & Now)
_database.Execute_non_Query("Update TBWMRH_PROFIL SET Running = 1 WHERE GUID = " & _PROFIL_ID)
Catch ex As Exception
EventLog.WriteEntry("DDWMResultHandler", "Unexpected error in OnStop: " & ex.ToString(), EventLogEntryType.Error)
End Try
End Sub
Public Sub RUN_THREAD(ByVal sender As Object, ByVal e As System.ComponentModel.DoWorkEventArgs)
Try
MyLogger = New LogConfig(LogConfig.PathType.CustomPath, Path.Combine(My.Application.Info.DirectoryPath, "Log"))
Logger = MyLogger.GetLogger()
_database = New clsDatabase(MyLogger, My.Settings.SQLSERVER_CS)
Dim notcompleted As Boolean = False
'clsLogger.Init(My.Application.Info.DirectoryPath & "\Log", "_SERVICEResultHandler")
Logger.Info("RUN_THREAD WMResulthandler started..")
' Windream instanziieren
_windream = New clsWindream_allgemein(MyLogger)
'windream initialisieren
If _windream.Init() = True Then
Logger.Debug("windream vollumfänglich initialisiert!")
'Zur sicherheit die DB nochmal initialiseren
If _database.Init(My.Settings.SQLSERVER_CS) = True Then
Dim DT As DataTable = _database.Return_Datatable("select * from TBWMRH_KONFIGURATION where GUID = 1")
If DT.Rows.Count = 1 Then
clsCURRENT.DT_TBWMRH_KONFIGURATION = DT
clsCURRENT.WDLAUFWERK = clsCURRENT.DT_TBWMRH_KONFIGURATION.Rows(0).Item("WD_LAUFWERK")
DD_WMResulthandler.clsCURRENT.LOG_ERRORS_ONLY = DT.Rows(0).Item("LOG_ERRORS_ONLY")
MyLogger.Debug = DT.Rows(0).Item("LOG_ERRORS_ONLY")
If DD_WMResulthandler.clsCURRENT.LOG_ERRORS_ONLY = False Then
Logger.Debug("Detaillog is ON!")
End If
DD_WMResulthandler.clsCURRENT.WDLAUFWERK = DT.Rows(0).Item("WD_LAUFWERK")
End If
DT = _database.Return_Datatable("SELECT GUID FROM TBWMRH_PROFIL WHERE AKTIV = 1 order by REIHENFOLGE")
If DT.Rows.Count > 0 Then
Logger.Debug("Anzahl der aktiven Profile: " & DT.Rows.Count.ToString)
For Each DR As DataRow In DT.Rows
_PROFIL_ID = CInt(DR.Item("GUID"))
_profil = New clsProfil(MyLogger, _PROFIL_ID)
'Und nun das Profil durchlaufen
Dim initresult = _profil.Init(_PROFIL_ID)
If initresult = True Then
'##### Profildurchlauf ########
_profil.Profil_Durchlauf(False)
ElseIf initresult = False Then
Logger.Warn("clsProfil konnte nicht initialisiert werden")
notcompleted = True
ElseIf initresult = 0 Then
Logger.Debug("initresult: 0")
notcompleted = True
ElseIf initresult = 1 Then
Logger.Debug("initresult: 1")
notcompleted = True
End If
Next
Else
Logger.Warn("Keine aktiven Profile WMResulthandler vorhanden")
notcompleted = True
End If
_database.Execute_non_Query("UPDATE TBWMRH_KONFIGURATION SET LAST_TICK = GETDATE() WHERE GUID = 1")
If oFirstRun = True Then
oFirstRun = False
threadPMRefresh.RunWorkerAsync()
End If
Else
Logger.Warn("clsDatabase konnte nicht initialisiert werden!")
notcompleted = True
End If
Else
Logger.Warn("# Achtung: Windream-Init mit Fehlern beendet")
notcompleted = True
End If
If notcompleted = True Then
End If
Catch ex As Exception
Logger.Error(ex)
End Try
End Sub
Public Sub RUNPMRefresh(ByVal sender As Object, ByVal e As System.ComponentModel.DoWorkEventArgs)
Try
MyLoggerPMR = New LogConfig(LogConfig.PathType.CustomPath, Path.Combine(My.Application.Info.DirectoryPath, "Log_PMRefresh"))
LoggerPMR = MyLoggerPMR.GetLogger()
_databasePMR = New clsDatabase(MyLoggerPMR, My.Settings.SQLSERVER_CS_PMRefresh)
_windreamPMR = New clsWindream_allgemein(MyLoggerPMR)
If _windreamPMR.Init() = True Then
If _databasePMR.Init(My.Settings.SQLSERVER_CS_PMRefresh) = True Then
Dim oDTPM_CONFIG As DataTable = _databasePMR.Return_Datatable("select * from TBPM_KONFIGURATION where GUID = 1")
If oDTPM_CONFIG.Rows.Count = 1 Then
Dim oConfigschedule = oDTPM_CONFIG.Rows(0).Item("SERVICE_SCHEDULE").ToString
Dim oConfigIDXName_DocID = oDTPM_CONFIG.Rows(0).Item("SERVICE_IDXNAME_DOCID").ToString
Dim oConfigIDXName_Created = oDTPM_CONFIG.Rows(0).Item("SERVICE_IDXNAME_CREATED").ToString
Dim oConfigWMDrive = oDTPM_CONFIG.Rows(0).Item("SERVICE_WMDRIVE_LETTER").ToString
Dim oConfigLOGERRONLY As Boolean = oDTPM_CONFIG.Rows(0).Item("SERVICE_LOG_ERRORS_ONLY")
Dim oSplit As String()
oSplit = oConfigschedule.Split(";")
Dim oTimespan = oSplit(0)
Dim oDays = oSplit(1)
If oConfigLOGERRONLY = False Then
MyLoggerPMR.Debug = True
LoggerPMR.Info("Detaillog Service PMRefresh is ON!")
Else
MyLoggerPMR.Debug = False
End If
Dim oDayofweek As Integer = My.Computer.Clock.LocalTime.DayOfWeek
Dim oSubstringInteger As Integer = 0
Dim oRunToday As Integer = 0
Select Case oDayofweek
Case 6 'Saturday
Case 5 'Friday
Case 4 'Thursday
Case 3 'Wednesday
Case 2 'Tuesday
Case 1 'Monday
Case 0 'Sunday
End Select
If oDayofweek = 0 Then
oSubstringInteger = 6
Else
oSubstringInteger = oDayofweek - 1
End If
oRunToday = oDays.Substring(oSubstringInteger, 1)
Dim oStep As String
If oRunToday = 1 Then
Dim oHourSplit As String() = oTimespan.Split("-")
Dim oMinHour As Integer = oHourSplit(0)
Dim oMaxHour As Integer = oHourSplit(1)
If CInt(Now.Hour) >= oMinHour And CInt(Now.Hour) < oMaxHour Then
LoggerPMR.Info($"Now running PM-Refresh ({oMinHour.ToString}#{oMaxHour.ToString})")
Try
LoggerPMR.Debug("Check_Profiles gestartet", False)
Dim WD_Search As String
Dim oSQLCommand As String
oSQLCommand = "SELECT GUID,NAME,WD_OBJECTTYPE,WD_SEARCH FROM TBPM_PROFILE WHERE ACTIVE = 1"
oStep = 1
Dim oDTPROFILES As DataTable = _databasePMR.Return_Datatable(oSQLCommand)
oStep = 2
Console.WriteLine(">> Evtl alte nicht aktualisierte PROFILE-FILE Daten werden gelöscht")
'---------------------- Evtl alte nicht aktualisierte PROFILE-FILE Daten werden gelöscht ------------------------
Dim oDelete As String = "DELETE FROM TBPM_PROFILE_FILES WHERE ACTIVE = 0 AND IN_WORK = 0"
_databasePMR.Execute_non_Query(oDelete)
oSQLCommand = "select * from TBPM_PROFILE_FILES"
Dim oDTPROFILE_FILES As DataTable = _databasePMR.Return_Datatable(oSQLCommand)
If oDTPROFILE_FILES.Rows.Count = 0 Then
LoggerPMR.Info("TBPM_PROFILE_FILES is completely empty...")
End If
'delete = "DELETE FROM TBPM_PROFILE_FILES_TEMP"
'ClassDatabase.Execute_MSSQL(delete)
oStep = 3
If oDTPROFILES.Rows.Count > 0 Then
Dim Profile_Row As System.Data.DataRow
'---------------------- für jedes Profil die Dateien überprüfen ------------------------
For Each Profile_Row In oDTPROFILES.Rows
oStep = "4a"
Console.WriteLine(">> Dateien für Profil '" & Profile_Row.Item("NAME") & "' eintragen")
LoggerPMR.Debug("Add info for profile '" & Profile_Row.Item("NAME") & "'")
Dim oPROFILE_ID As Integer = Profile_Row.Item("GUID")
WD_Search = Nothing
WD_Search = Profile_Row.Item("WD_SEARCH")
oStep = "4b"
If WD_Search Is Nothing = False Then
'---------------------- Die Dateien auslesen ------------------------
Dim oDTWM_Results As DataTable
oStep = "4c"
oDTWM_Results = _windreamPMR.GetSearchDocumentsDT(WD_Search, oConfigIDXName_DocID, oConfigIDXName_Created)
oStep = "4d"
Dim oDocCount As Integer = 0
If IsNothing(oDTWM_Results) Then
Continue For
End If
'Die aktuellen Files auf refreshed = 0 setzten
oSQLCommand = "UPDATE TBPM_PROFILE_FILES SET REFRESHED = 0 WHERE PROFIL_ID = " & oPROFILE_ID
If _databasePMR.Execute_non_Query(oSQLCommand) = True Then
If oDTWM_Results Is Nothing = False Then
If oDTWM_Results.Rows.Count > 0 Then
oStep = "4e"
'Ein Array mit Dateiinformationen anlegen
Dim Profil_Docs(oDTWM_Results.Rows.Count - 1, 2) As String
For Each oRow As DataRow In oDTWM_Results.Rows
Dim oDOC_ID = oRow.Item(0)
Dim oWMFilePath As String = oConfigWMDrive & ":" & oRow.Item(1)
Profil_Docs(oDocCount, 0) = oRow.Item(0)
Profil_Docs(oDocCount, 1) = oWMFilePath
'------DMS Erstell-Datum holen --------
Dim oDMSErstellt = oRow.Item(2)
'ClassLogger.Add(">> DMSErstellt: '" & DMSErstellt.ToString, False)
Dim date_EN As String
If oConfigIDXName_Created.EndsWith("reated") Then
Dim arr() = oDMSErstellt.ToString.Split(".")
If arr.Length = 3 Then
date_EN = arr(2).Replace(" 00:00:00", "") & "-" & arr(1) & "-" & arr(0)
LoggerPMR.Debug("date_EN: '" & date_EN)
oDMSErstellt = date_EN
End If
End If
'-------------------- Überprüfen ob das Dokument bereits enthalten ist? Kann nur passieren wenn das Dok gerade in Bearbeitung ist ----------
oSQLCommand = $"SELECT GUID FROM TBPM_PROFILE_FILES WHERE PROFIL_ID = {oPROFILE_ID} AND FILE_PATH = '{oWMFilePath}'"
Dim oCheck = _databasePMR.Execute_Scalar(oSQLCommand)
'---------------------- Das Dokument inserten ------------------------
Try
If oCheck Is Nothing Or oDTPROFILE_FILES.Rows.Count = 0 Then
Dim oInsert As String = $"INSERT INTO TBPM_PROFILE_FILES (PROFIL_ID, FILE_PATH, ACTIVE, DMS_ERSTELLT_DATE,DOC_ID) VALUES ({oPROFILE_ID}, '{oWMFilePath}',1, CONVERT(DATE,'{oDMSErstellt}'),{oDOC_ID})"
If _databasePMR.Execute_non_Query(oInsert) = False Then
LoggerPMR.Info($"Unexpected Error while Inserting File-Record {oDOC_ID}")
End If
' aktuelles Dokument der Klasse mitteilen
Else
If CInt(oCheck) > 0 Then
oSQLCommand = $"UPDATE TBPM_PROFILE_FILES SET REFRESHED = 1, EDIT = 0 WHERE GUID = {CInt(oCheck)}"
_databasePMR.Execute_non_Query(oSQLCommand)
End If
End If
Catch ex As Exception
LoggerPMR.Error(ex)
End Try
oDocCount += 1
Next
LoggerPMR.Info($"Profile '{Profile_Row.Item("NAME")} refreshed - FileCount {oDocCount.ToString}")
Else
oStep = "4g"
LoggerPMR.Info($"No Data for profile '{Profile_Row.Item("NAME")}'!")
End If
Else
LoggerPMR.Warn("oDTWM_Results IS NOTHING")
End If
oStep = "Step: vor Delete Refreshed = 0"
Dim oSQLDEL As String = "DELETE FROM TBPM_PROFILE_FILES WHERE PROFIL_ID = " & oPROFILE_ID & " AND REFRESHED = 0"
_databasePMR.Execute_non_Query(oSQLDEL)
'---------------------- Aktuelle Anzahl in Profiltabelle updaten ------------------------
oSQLCommand = $"UPDATE TBPM_PROFILE SET NO_OF_DOCUMENTS = {oDocCount} WHERE GUID = {oPROFILE_ID}"
oStep = "Step 4h AnzahlDocs: - " & oDocCount.ToString
_databasePMR.Execute_non_Query(oSQLCommand)
Else
LoggerPMR.Warn("ATTENTION: Refresh could not be executed " & oSQLCommand)
End If
End If
Next
oStep = "4i"
''------------------------------- Bearbeitete Daten löschen ------------------------
If _databasePMR.Execute_non_Query("DELETE FROM TBPM_PROFILE_FILES WHERE EDIT = 1") = True Then
' oStep = "i"
' Console.WriteLine(">> Alte PROFILE-FILE Daten geleert")
' '---------------------- DIE NEUEN DATEN AUF ACTIVE SETZEN ------------------------
' Dim update As String = "UPDATE TBPM_PROFILE_FILES SET ACTIVE = 1 WHERE ACTIVE = 0"
' ClassDatabase.Execute_MSSQL(update)
' oStep = "j"
' Console.WriteLine(">> Neue PROFILE-FILE Daten aktiv gesetzt")
End If
oStep = "4j"
_databasePMR.Execute_non_Query("EXEC PRPM_REMOVE_NE_FILES")
oStep = "4k"
Else
LoggerPMR.Debug("oDTPROFILES has no rows!")
End If
Catch ex As Exception
LoggerPMR.Info("Unexpected Error in RUNJob")
LoggerPMR.Warn("Error in RunJob- laststep: " & oStep)
LoggerPMR.Error(ex)
End Try
Else
LoggerPMR.Info($"No run of PMRefresh as hour is not in timespan ({CInt(Now.Hour)} >= {oMinHour} And {CInt(Now.Hour)} < {oMaxHour})")
End If
Else
LoggerPMR.Info($"No run of PMRefresh as today Is Not configured as RUN")
End If
End If
Else
LoggerPMR.Warn("Could not initialize the database of PMRefresh.")
End If
End If
Catch ex As Exception
LoggerPMR.Error(ex)
End Try
End Sub
#Region "*** BackgroundWorker beenden und Abbrechen ***"
Private Sub Thread_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
Logger.Warn("Der Process wurde durch den Anwender abgebrochen")
ElseIf e.Error IsNot Nothing Then
Logger.Warn("Fehler bei Durchlauf. Der Vorgang wird abgebrochen: " & e.Error.Message)
End If
'If DI_Verzeichnisloeschen Then
' Try
' My.Computer.FileSystem.DeleteDirectory(DI_Quellordner, FileIO.DeleteDirectoryOption.ThrowIfDirectoryNonEmpty)
' Catch ex As Exception
' ClassLogger.Add("ACHTUNG: Der Vorgang wurde abgeschlossen. Das Quellverzeichnis konnte jedoch nicht gelöscht werden, da sich in dem Ordner noch Dateien/Verzeichnisse befinden.", False)
' End Try
'End If
Catch ex As Exception
EventLog.WriteEntry("DDWMResultHandler", "Unexpected error in Thread_Completed: " & ex.ToString(), EventLogEntryType.Error)
End Try
End Sub
Private Sub ThreadPMRefresh_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
Logger.Warn("Der Process PMRefresh wurde durch den Anwender abgebrochen")
ElseIf e.Error IsNot Nothing Then
Logger.Warn("Fehler bei Durchlauf PMRefresh. Der Vorgang wird abgebrochen: " & e.Error.Message)
End If
'If DI_Verzeichnisloeschen Then
' Try
' My.Computer.FileSystem.DeleteDirectory(DI_Quellordner, FileIO.DeleteDirectoryOption.ThrowIfDirectoryNonEmpty)
' Catch ex As Exception
' ClassLogger.Add("ACHTUNG: Der Vorgang wurde abgeschlossen. Das Quellverzeichnis konnte jedoch nicht gelöscht werden, da sich in dem Ordner noch Dateien/Verzeichnisse befinden.", False)
' End Try
'End If
Catch ex As Exception
Logger.Error(ex, "Unexpected error in ThreadPMRefresh_Completed: ")
End Try
End Sub
Public Function Thread_Abbrechen()
Try
If DDWDResultHandler.threadRunner.IsBusy Then
DDWDResultHandler.threadRunner.CancelAsync()
End If
Return True
Catch ex As Exception
EventLog.WriteEntry("DDWMResultHandler", "Unexpected error in Thread_Abbrechen: " & ex.ToString(), EventLogEntryType.Error)
Logger.Error(ex)
Return False
End Try
End Function
#End Region
End Class