Imports System.ComponentModel Imports System.IO Imports DigitalData.Modules.Logging Imports DigitalData.Modules.Database Imports DevExpress.DataAccess.Sql Imports GdPicture14 Imports System.Drawing Public Class MyService #Region "+++++ variables +++++" Private _threadRunner1 As BackgroundWorker Private _threadRunner2 As BackgroundWorker Private MyLogger As LogConfig Private Logger As Logger Private MyDatabase As MSSQLServer Dim MyStempel1 As String Dim MyStempel2 As String Private _licenseManager As New GdPicture14.LicenseManager() #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", "DD EBCreator") Logger = MyLogger.GetLogger Try Dim directory As New IO.DirectoryInfo(MyLogger.LogDirectory) For Each file As IO.FileInfo In directory.GetFiles If (Now - file.CreationTime).Days > 29 Then file.Delete() Else Exit For End If Next Catch ex As Exception End Try Logger.Info("## Service started ## ") If My.Settings.MyConnectionString = String.Empty Then Logger.Warn("NO CONNECTIONSTRING CONFIGURED.") Else If My.Settings.DEBUG = True Then Logger.Info("DEBUG ACTIVATED") MyLogger.Debug = True Else MyLogger.Debug = False End If MyDatabase = New MSSQLServer(MyLogger, My.Settings.MyConnectionString) If MyDatabase.DBInitialized = False Then Logger.Warn("ATTENTION: No Connection was established '" & My.Settings.MyConnectionString & "'!") Else Dim oSQL = "SELECT LICENSE FROM TBDD_3RD_PARTY_MODULES WHERE NAME = 'GDPICTURE' AND ACTIVE = 1" Dim oGDPICTURE_LIC_KEY As String oGDPICTURE_LIC_KEY = MyDatabase.GetScalarValue(oSQL) _licenseManager.RegisterKEY(oGDPICTURE_LIC_KEY) '### Thread 1 generieren _threadRunner1 = New BackgroundWorker() _threadRunner1.WorkerReportsProgress = True _threadRunner1.WorkerSupportsCancellation = True AddHandler _threadRunner1.DoWork, AddressOf RUN_THREAD1 AddHandler _threadRunner1.RunWorkerCompleted, AddressOf Thread1_Completed _threadRunner2 = New BackgroundWorker() _threadRunner2.WorkerReportsProgress = True _threadRunner2.WorkerSupportsCancellation = True AddHandler _threadRunner2.DoWork, AddressOf RUN_THREAD2 AddHandler _threadRunner2.RunWorkerCompleted, AddressOf Thread2_Completed '### Den Timer für Thread 1 generieren Dim Timer_Thread1 As New System.Timers.Timer() 'Das Event hinterlegen welches bei "Tick" ausgelöst wird AddHandler Timer_Thread1.Elapsed, AddressOf Thread_Run1 ' Set the Interval Timer_Thread1.Interval = (My.Settings.TIMER_INTERVALL * 60000) Timer_Thread1.Enabled = True Logger.Debug("...Timer 1 started.") ' Und den Durchlauf das erste Mal starten _threadRunner1.RunWorkerAsync() '### Den Timer für Thread 1 generieren Dim Timer_Thread2 As New System.Timers.Timer() 'Das Event hinterlegen welches bei "Tick" ausgelöst wird AddHandler Timer_Thread2.Elapsed, AddressOf Thread_Run2 ' Set the Interval Timer_Thread2.Interval = (My.Settings.TIMER_INTERVALL * 60000) Timer_Thread2.Enabled = True Logger.Debug("...Timer 2 started.") End If End If Catch ex As Exception EventLog.WriteEntry(Me.ServiceName, ex.ToString(), EventLogEntryType.Error) Logger.Error(ex) End Try End Sub Public Sub Thread_Run1() If Not _threadRunner1.IsBusy Then _threadRunner1.RunWorkerAsync() Else Logger.Info("##### THREAD 1 Is STILL RUNNING #####") End If End Sub Public Sub Thread_Run2() If Not _threadRunner2.IsBusy Then _threadRunner2.RunWorkerAsync() Else Logger.Info("##### THREAD 2 Is STILL RUNNING #####") End If End Sub Public Sub RUN_THREAD1(ByVal sender As Object, ByVal e As System.ComponentModel.DoWorkEventArgs) Try If My.Computer.Clock.LocalTime.Hour <> 4 And My.Computer.Clock.LocalTime.Hour <> 5 Then Generator_Run("01", My.Settings.oSQLThread1) Else Logger.Debug($"In Sleep Mode 04-05h: {Now.ToString}") End If Catch ex As Exception Logger.Error(ex) End Try End Sub Public Sub Generator_Run(GeneratorID As String, oGetDTSQL As String) Try Dim oSQLDelete = $"DELETE FROM TBCUST_PM_RPT_2BCREATED WHERE GEN_ID = '{GeneratorID}'" MyDatabase.ExecuteNonQuery(oSQLDelete) Dim oDTEB_Workload As DataTable = MyDatabase.GetDatatable(oGetDTSQL) If Not IsNothing(oDTEB_Workload) Then Dim oDocID As Long Dim oOutputfilename, OutputFolder As String Dim oReRun As Boolean If oDTEB_Workload.Rows.Count > 0 Then Logger.Info($"##### THREAD for Generator {GeneratorID} has [{oDTEB_Workload.Rows.Count}] results 2Bworked #####") For Each oRow As DataRow In oDTEB_Workload.Rows oDocID = oRow.Item(0).ToString Try oOutputfilename = oRow.Item("Outputfilename").ToString Catch ex As Exception oOutputfilename = "STANDARD" End Try Try OutputFolder = oRow.Item("OutputFolder").ToString Catch ex As Exception OutputFolder = "STANDARD" End Try Try oReRun = oRow.Item("ReRun") Catch ex As Exception oReRun = False End Try Dim oSQLCheck = $"SELECT * FROM TBCUST_PM_RPT_2BCREATED WHERE DocID = {oDocID}" Dim oDTRPT2BCreated As DataTable = MyDatabase.GetDatatable(oSQLCheck) If Not IsNothing(oDTRPT2BCreated) And (oDTRPT2BCreated.Rows.Count = 0 Or oReRun = True) Then oSQLCheck = $"select * From VWCUST_STAMP Where DocID = {oDocID}" Dim oCheckStamp As DataTable = MyDatabase.GetDatatable(oSQLCheck) If oCheckStamp.Rows.Count > 0 Then If oReRun = True Then Logger.Info($"## THIS IS A RERUN {oDocID}") Delete_EB2bCreated(oDocID) End If Dim oInsert = $"IF NOT EXISTS(SELECT DocID FROM TBCUST_PM_RPT_2BCREATED WHERE DocID = {oDocID}) INSERT INTO TBCUST_PM_RPT_2BCREATED (DocID,GEN_ID,Outputfilename) VALUES ({oDocID},'{GeneratorID}','{oOutputfilename}')" MyDatabase.ExecuteNonQuery(oInsert) Else Logger.Warn($"oCheckStamp = False [{oSQLCheck}]") End If Else Logger.Info($"DocID already worked (TBCUST_PM_RPT_2BCREATED) [{oSQLCheck}]") End If Next Dim oSQLWorkload2 = $"SELECT * FROM TBCUST_PM_RPT_2BCREATED WHERE GEN_ID = '{GeneratorID}'" oDTEB_Workload = MyDatabase.GetDatatable(oSQLWorkload2) For Each oRow As DataRow In oDTEB_Workload.Rows Dim oSQL As String oDocID = oRow.Item(0).ToString Try oOutputfilename = oRow.Item("Outputfilename").ToString Catch ex As Exception oOutputfilename = "STANDARD" End Try oSQL = $"EXEC PRCUST_CREATE_RPTERGEBNISBERICHT_POS {oDocID.ToString}" Logger.Debug($"Now executing [{oSQL}]") If MyDatabase.ExecuteNonQuery(oSQL, 500) = True Then oSQL = $"select * from VWCUST_RPTERGEBNISBERICHT where DocID = {oDocID}" Dim oDTEB = MyDatabase.GetDatatable(oSQL) If oDTEB.Rows.Count > 0 Then Create_EB_Report(oDocID.ToString, GeneratorID, oOutputfilename, OutputFolder, oReRun) Else Logger.Warn($"No EB-Rows [{oSQL}]") Delete_EB2bCreated(oDocID) End If End If Next End If End If Catch ex As Exception Logger.Warn($"Unexpected Error Generator_Run for GenID {GeneratorID}:") Logger.Error(ex) End Try End Sub Public Sub RUN_THREAD2(ByVal sender As Object, ByVal e As System.ComponentModel.DoWorkEventArgs) Try If My.Computer.Clock.LocalTime.Hour <> 4 And My.Computer.Clock.LocalTime.Hour <> 5 Then If My.Settings.oSQLThread2 <> String.Empty Then Generator_Run("02", My.Settings.oSQLThread2) End If Else Logger.Debug($"In Sleep Mode 04-05h: {Now.ToString}") End If Catch ex As Exception Logger.Error(ex) End Try End Sub Protected Overrides Sub OnStop() ' Hier Code zum Ausführen erforderlicher Löschvorgänge zum Beenden des Dienstes einfügen. Logger.Info("## Service has been 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 Logger.Warn("## Thread1 was cancelled.") ElseIf e.Error IsNot Nothing Then Logger.Warn("Unexpected error in thread 1: " & e.Error.Message) End If Catch ex As Exception Logger.Error(ex) End Try End Sub Private Sub Thread2_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("## Thread2 was cancelled.") ElseIf e.Error IsNot Nothing Then Logger.Warn("Unexpected error in thread 2: " & e.Error.Message) End If Catch ex As Exception Logger.Error(ex) End Try End Sub Sub Create_EB_Report(pDocID As String, GENID As String, Outputfilename As String, OutputFolder As String, pRerun As Boolean) Dim MyFreigabebericht As String If GENID = "01" Then MyStempel1 = "" Else MyStempel2 = "" End If Logger.Info($"#### Trying to Create_EB_Report (EB-Protokoll) for DocID: {pDocID} - GENID: {GENID}... ####") Dim errortext As String Try Dim oReport As New XtraReportEB() Dim oDatasource As SqlDataSource = oReport.DataSource Dim oSelectQuery As CustomSqlQuery = oDatasource.Queries(0) Dim oParameter As QueryParameter = oSelectQuery.Parameters(0) oParameter.Value = pDocID Try oReport.ReportPrintOptions.PrintOnEmptyDataSource = False oReport.FilterString = "DocID = " + pDocID 'report.ObjectDataSource1.Parameters(0).Value = Convert.ToInt64(TextBox1.Text) oReport.CreateDocument(False) Catch ex As Exception Delete_EB2bCreated(pDocID) Logger.Warn($"Unexpected Error in Create_EB_Report Create for DocID: {pDocID} - GENID: {GENID} - ERROR: {ex.Message}") Exit Sub End Try Dim oMyErgebnisbericht As String = Path.Combine(My.Settings.CONCAT_TEMPFolder, pDocID & "_ERPT.pdf") If File.Exists(oMyErgebnisbericht) Then Try File.Delete(oMyErgebnisbericht) Catch ex As Exception Logger.Info($"Could not delete existing Reportfile: {oMyErgebnisbericht}") Exit Sub End Try End If oReport.ExportToPdf(oMyErgebnisbericht) If File.Exists(oMyErgebnisbericht) Then MyFreigabebericht = oMyErgebnisbericht Dim oOriginFile As String Dim osql = $"select dbo.FNDD_GET_WINDREAM_FILE_PATH ({pDocID},{My.Settings.FNDD_GET_WM_FPATH_VARIANT})" oOriginFile = MyDatabase.GetScalarValue(osql) If File.Exists(oOriginFile) = False Then Logger.Warn($"File.Exists = false ### [{oOriginFile}] is not existing. Check Your security-permissions [{osql}]!") Delete_EB2bCreated(pDocID) Exit Sub End If If Not IsNothing(oOriginFile) Then If File.Exists(My.Settings.Path2PDFTK) Then If Create_MyStempel(pDocID, GENID) = True Then 'Jetzt Stempeln des OriginalBeleges mit dem Stamp-Report Dim oStampedResult = CreateStampedPDF(oOriginFile, pDocID, GENID) If oStampedResult <> "" Then If Concat_Files(pDocID, oOriginFile, GENID, Outputfilename, OutputFolder, oStampedResult, MyFreigabebericht) = True Then If pRerun = False Then Dim oInsert = $"INSERT INTO TBCUST_PM_RPT_CREATED (DocID,GEN_ID) VALUES ({Convert.ToInt64(pDocID)},'{GENID}')" MyDatabase.ExecuteNonQuery(oInsert) End If Logger.Info($"#### Created Ergebnisbericht for DocID: {pDocID} - GENID: {GENID}! #####") End If Else Logger.Info("ERROR: CreateStampedPDF = False or """) End If Else Logger.Warn("Create_MyStempel = False") Delete_EB2bCreated(pDocID) End If End If Else Logger.Warn("OriginFile is nothing!!") End If Else Logger.Warn($"Error in Create_EB_Report for DocID: {pDocID} - GENID: {GENID} - ERROR: EB_Reportfile {oMyErgebnisbericht} is not existing!!") Delete_EB2bCreated(pDocID) End If Catch ex As Exception Delete_EB2bCreated(pDocID) errortext = "ex.message: " & ex.Message & vbNewLine & "ex.StackTrace: " & ex.StackTrace.ToString & vbNewLine & "ex.InnerException: " & ex.InnerException.Message Logger.Warn($"Unexpected Error in Create_Report for DocID: {pDocID} - ERROR: {errortext}") End Try End Sub Private Function Create_MyStempel(pDocID As String, GENID As String) If GENID = "01" Then MyStempel1 = "" Else MyStempel2 = "" End If Dim errortext As String Try Dim oRptStampFirstPage As New RptStampIcon() Dim oDatasource As SqlDataSource = oRptStampFirstPage.DataSource Dim oSelectQuery As CustomSqlQuery = oDatasource.Queries(0) Dim oParameter As QueryParameter = oSelectQuery.Parameters(0) oParameter.Value = pDocID oRptStampFirstPage.ReportPrintOptions.PrintOnEmptyDataSource = False oRptStampFirstPage.FilterString = "DocID = " + pDocID 'report.ObjectDataSource1.Parameters(0).Value = Convert.ToInt64(TextBox1.Text) oRptStampFirstPage.CreateDocument(False) Dim oTempStempel As String = Path.Combine(My.Settings.CONCAT_TEMPFolder, pDocID & "_Stamp.jpg") If File.Exists(oTempStempel) Then Try File.Delete(oTempStempel) Catch ex As Exception Return False End Try End If 'myReport.ExportToPdf(oTempStempel) Dim oExportOptions As New DevExpress.XtraPrinting.ImageExportOptions oExportOptions.Resolution = 400 oExportOptions.Format = Imaging.ImageFormat.Jpeg oExportOptions.ExportMode = DevExpress.XtraPrinting.ImageExportMode.SingleFile oRptStampFirstPage.ExportToImage(oTempStempel, oExportOptions) If File.Exists(oTempStempel) Then If GENID = "02" Then MyStempel2 = oTempStempel Else MyStempel1 = oTempStempel End If Logger.Info($"...Stampreport created for DocID: {pDocID} - GENID {GENID}!") Return True Else If GENID = "02" Then MyStempel2 = "" Else MyStempel1 = "" End If Return False End If Catch ex As Exception errortext = "ex.message: " & ex.Message & vbNewLine & "ex.StackTrace: " & ex.StackTrace.ToString & vbNewLine & "ex.InnerException: " & ex.InnerException.Message Delete_EB2bCreated(pDocID) Logger.Error(ex) Return False End Try End Function Private Function CreateStampedPDF(oOriginFile As String, pDocID As Integer, GENID As String) Try Logger.Info($"Trying to CreateStampedPDF for DocID: {pDocID} - GENID {GENID}...") Dim MyLocalStempel As String If GENID = "01" Then MyLocalStempel = MyStempel1 Else MyLocalStempel = MyStempel2 End If Dim oStampedOriginWithPicture As String oStampedOriginWithPicture = Path.GetFileNameWithoutExtension(oOriginFile) & My.Settings.Concatted_File_Suffix oStampedOriginWithPicture = Path.Combine(My.Settings.CONCAT_TEMPFolder, oStampedOriginWithPicture + "_StampedOriginal.pdf") Dim oGdPicturePDF As New GdPicturePDF() Dim oGdPictureImaging As New GdPictureImaging() 'Creating a new empty PDF document. If oGdPicturePDF.LoadFromFile(oOriginFile, False) = GdPictureStatus.OK Then Logger.Debug($"{pDocID}..oGdPicturePDF Created") Dim oYDistance = oGdPicturePDF.GetPageHeight 'Just to remind you that units are set to points and the origin is set to bottom left by default. 'Loading an image from a file. Dim imageID As Integer = oGdPictureImaging.CreateGdPictureImageFromFile(MyLocalStempel) If oGdPictureImaging.GetStat() = GdPictureStatus.OK Then Logger.Debug($"{pDocID}..GdPictureImaging.GetStat") 'Adding an image as a resource into the PDF document - we decided not to draw the image in this moment. Dim imageResName As String = oGdPicturePDF.AddImageFromGdPictureImage(imageID, False, False) Logger.Debug($"{pDocID}..oGdPicturePDF.AddImageFromGdPictureImage") If System.IO.File.Exists(oStampedOriginWithPicture) Then System.IO.File.Delete(oStampedOriginWithPicture) End If Dim oStempelHEight = oGdPictureImaging.GetHeight(imageID) / 5 oYDistance = (oYDistance - oStempelHEight) - 10 'Drawing the image resource onto the current page and saving the PDF document. If (oGdPicturePDF.GetStat() <> GdPictureStatus.OK) OrElse (oGdPicturePDF.DrawImage(imageResName, My.Settings.XDistance, oYDistance, oGdPictureImaging.GetWidth(imageID) / 5, oGdPictureImaging.GetHeight(imageID) / 5) <> GdPictureStatus.OK) OrElse (oGdPicturePDF.SaveToFile(oStampedOriginWithPicture) <> GdPictureStatus.OK) Then Logger.Warn("The example has NOT been followed successfully. Error: " + oGdPicturePDF.GetStat().ToString()) 'MessageBox.Show("The example has NOT been followed successfully. Error: " + oGdPicturePDF.GetStat().ToString(), "Adding an image Example", MessageBoxButtons.OK, MessageBoxIcon.Error) Return "" End If Logger.Debug($"{pDocID}..oGdPicturePDF.SaveToFile") 'Releasing the image. oGdPictureImaging.ReleaseGdPictureImage(imageID) Else Logger.Warn($"The image [{MyLocalStempel}] can't be loaded. Error: " + oGdPictureImaging.GetStat().ToString()) Return "" 'MessageBox.Show("The image can't be loaded. Error: " + oGdPictureImaging.GetStat().ToString(), "Adding an image Example", MessageBoxButtons.OK, MessageBoxIcon.Error) End If oGdPicturePDF.CloseDocument() Else Logger.Warn("The new PDF document can't be created. Error: " + oGdPicturePDF.GetStat().ToString()) 'MessageBox.Show("The new PDF document can't be created. Error: " + oGdPicturePDF.GetStat().ToString(), "Adding an image Example", MessageBoxButtons.OK, MessageBoxIcon.Error) Return "" End If oGdPictureImaging.Dispose() oGdPicturePDF.Dispose() Dim sw As Stopwatch = New Stopwatch() Dim oSuccess As Boolean = True sw.Start() Logger.Debug("Waiting for file: " & oStampedOriginWithPicture) Do While File.Exists(oStampedOriginWithPicture) = False If sw.Elapsed.TotalSeconds = 30 Then Logger.Info("ATTENTION: Still waiting (30 sec) for file: " & oStampedOriginWithPicture) ElseIf sw.Elapsed.TotalMinutes = 1 Then Logger.Info("ATTENTION: Still waiting (60 sec) for file: " & oStampedOriginWithPicture) oSuccess = False Exit Do End If Loop sw.Stop() Try File.Delete(MyLocalStempel) Logger.Debug($"Deleted StempelFile [{MyLocalStempel}]!") Catch ex As Exception Logger.Warn($"Could not delete reportfile {MyLocalStempel} after creating concatted file: {ex.Message}") End Try If oSuccess = True Then Return oStampedOriginWithPicture Else Return "" End If Catch ex As Exception Logger.Error(ex) Return "" End Try End Function Private Function Concat_Files(DocID As String, oOriginFile As String, GENID As String, Outputfilename As String, pOutputFolder As String, MyOriginStamped As String, MyFreigabebericht As String) Dim oConcatSuccessfull As Boolean = True Dim MyFile2Concat As String Try If Outputfilename = "STANDARD" Then Outputfilename = Path.GetFileNameWithoutExtension(oOriginFile) & My.Settings.Concatted_File_Suffix + ".pdf" End If If pOutputFolder = "STANDARD" Then pOutputFolder = My.Settings.Path_ConcattedFile End If MyFile2Concat = Path.Combine(pOutputFolder, Outputfilename) If File.Exists(My.Settings.Path2PDFTK) Then If File.Exists(MyFile2Concat) Then Try File.Delete(MyFile2Concat) Catch ex As Exception Logger.Warn($"Could not delete ConcattedFile {MyFile2Concat}: {ex.Message}") Return False End Try End If Try Dim oPDFTKProcess As New Process Dim ProcID oPDFTKProcess.StartInfo.FileName = My.Settings.Path2PDFTK oPDFTKProcess.StartInfo.CreateNoWindow = True Dim _argument As String = """" & MyOriginStamped & """" & " " & """" & MyFreigabebericht & """" oPDFTKProcess.StartInfo.Arguments = _argument & " cat output " & MyFile2Concat Logger.Debug("Arguments: " & _argument & " cat output " & MyFile2Concat) oPDFTKProcess.Start() ProcID = oPDFTKProcess.Id Dim oProcID As Process oProcID = Process.GetProcessById(ProcID) Dim sw As Stopwatch = New Stopwatch() sw.Start() Do While oProcID.HasExited = False If sw.Elapsed.TotalSeconds = 30 Then Logger.Info("Still waiting (30 sec) for ending of process-id: " & ProcID.ToString) ElseIf sw.Elapsed.TotalMinutes = 1 Then Logger.Info("Still waiting (60 sec) for ending of process-id: " & ProcID.ToString & " - Exit now") Exit Do End If Loop Logger.Debug("...process has exited: ") sw.Stop() Logger.Debug("Waiting for file: " & MyFile2Concat) sw.Start() Do While File.Exists(MyFile2Concat) = False If sw.Elapsed.TotalSeconds = 30 Then Logger.Info("ATTENTION: Still waiting (30 sec) for file: " & MyFile2Concat) ElseIf sw.Elapsed.TotalMinutes = 1 Then Logger.Info("ATTENTION: Still waiting (60 sec) for file: " & MyFile2Concat) oConcatSuccessfull = False Exit Do End If Loop sw.Stop() Try File.Delete(MyOriginStamped) Logger.Debug($"Deleted file [{MyOriginStamped}]!") File.Delete(MyFreigabebericht) Logger.Debug($"Deleted file [{MyFreigabebericht}]!") Catch ex As Exception Logger.Warn($"Could not delete reportfile after creating concatted file: {ex.Message}") End Try Return oConcatSuccessfull Catch ex As Exception Logger.Error(ex) '("Unexpected error: " & ex.Message, "clsProfil.Profil_Durchlauf(Concat Files to one pdf)") Return False End Try Else Logger.Warn("pdftk is not existing") Return False End If Catch ex As Exception End Try End Function Sub Delete_EB2bCreated(pDocID As Long) Try Dim oDelete = $"DELETE FROM TBCUST_PM_RPT_2BCREATED WHERE DocID = {pDocID}" MyDatabase.ExecuteNonQuery(oDelete) Catch ex As Exception Logger.Error(ex) End Try End Sub End Class