Imports System.ServiceProcess
Imports System.Threading
Imports System.IO

Imports System.Collections.Generic
Imports Syncfusion.Pdf
Imports Syncfusion.Pdf.Parsing
Imports Syncfusion.Pdf.Graphics
Imports Syncfusion.Pdf.Grid
Imports System.Drawing
Imports Newtonsoft
Imports Microsoft.Office.Interop
Imports System.Text
Imports System.Net
Imports Newtonsoft.Json
Imports System.Runtime.InteropServices
Imports System.Diagnostics.Eventing.Reader

'''<summary></summary>
Public Class EDKB02DMSIL
    Inherits System.ServiceProcess.ServiceBase

#Region " Vom Component Designer generierter Code "

    Public Sub New()
        MyBase.New()

        ' Dieser Aufruf wird vom Komponenten-Designer benötigt.
        InitializeComponent()


        ' Fügen Sie Initialisierungscode hinter dem InitializeComponent()-Aufruf ein

    End Sub

    'UserService überschreibt den Löschvorgang zum Bereinigen der Komponentenliste.
    Protected Overloads Overrides Sub Dispose(ByVal disposing As Boolean)
        If disposing Then
            If Not (components Is Nothing) Then
                components.Dispose()
            End If
        End If
        MyBase.Dispose(disposing)
    End Sub

    ' Der Haupteinstiegspunkt für den Vorgang
    <MTAThread()>
    Shared Sub Main()

#If CONFIG = "Release" Then
        Dim ServicesToRun() As System.ServiceProcess.ServiceBase
        ServicesToRun = New System.ServiceProcess.ServiceBase() {New EDKB02DMSIL()}
        System.ServiceProcess.ServiceBase.Run(ServicesToRun)
#Else

        Dim myServ As New EDKB02DMSIL
        myServ.OnStart({""})
        While (True)
            System.Threading.Thread.Sleep(2000)
        End While
#End If



    End Sub

    ' Für Komponenten-Designer erforderlich
    Private components As System.ComponentModel.IContainer

    ' HINWEIS: Die folgende Prozedur wird vom Komponenten-Designer benötigt.
    ' Sie kann mit dem Komponenten-Designer modifiziert werden. Verwenden Sie nicht
    ' den Code-Editor zur Bearbeitung.
    'Friend WithEvents ServiceIcon As System.Windows.Forms.NotifyIcon

    <System.Diagnostics.DebuggerStepThrough()> Private Sub InitializeComponent()
        Me.components = New System.ComponentModel.Container()
        Dim resources As System.ComponentModel.ComponentResourceManager = New System.ComponentModel.ComponentResourceManager(GetType(EDKB02DMSIL))

        '

        '
        'EDKB02DMSIL
        '
        Me.ServiceName = "EDKB02DMSIL"

    End Sub

#End Region

#Region "Deklarationen"
    Private StopThread As Boolean = False
    Dim WithEvents BCK_Timer As New Timers.Timer()
    Dim WithEvents Dokument_Timer As New Timers.Timer
    Dim Watch_Directory As String
    Dim FileWatch As New FileSystemWatcher()
    Dim EventStopped As Boolean = False
    Dim db As New clsdb
    Dim Base64_File As String
    Dim JsonString As String
    Dim mimetype As String
    Dim OutputFile As String
    Dim SendError As String = ""

    Dim debug As Boolean = False
    Dim logfile As String = ""
    Dim sendtoonbase As Boolean = False
    Dim updateedoka As Boolean = False
    Dim OnBaseFiletype As String = ""



    'Dim w As New Microsoft.Office.Interop.Word.Application
    'Dim x As New Microsoft.Office.Interop.Excel.Application

    Dim w As Microsoft.Office.Interop.Word.Application
    Dim x As Microsoft.Office.Interop.Excel.Application
#End Region

#Region "Hauptverarbeitung"

    Dim Parameters As New clsParams

    Protected Overrides Sub OnStart(ByVal args() As String)
        Try
            Parameters.get_params()
            Me.BCK_Timer.Interval = Parameters.BCK_TimerInterval * 1000
            Me.Dokument_Timer.Interval = Parameters.Document_Timerinterval * 1000
            Me.BCK_Timer.Enabled = True
            Me.BCK_Timer.Start()
            Me.Dokument_Timer.Enabled = True
            Me.Dokument_Timer.Start()
            Me.debug = Parameters.Debug = "1"
            Me.logfile = Parameters.LogFilename
            Me.sendtoonbase = Parameters.SendToOnBase = "1"
            Me.updateedoka = Parameters.updateedoka = "1"
            db.Connectionstring = Parameters.Connectionstring_EDOKA
            db.Connectionstring_DokTypMapping = Parameters.Connectionstring_DokTypMapping
            db.Debug = Parameters.Debug
            db.Logfile = Parameters.LogFilename


            Syncfusion.Licensing.SyncfusionLicenseProvider.RegisterLicense("OTU3NTQ3QDMyMzAyZTM0MmUzMFhyMnhJK1JNSCtETllyc1k5d0lyYzBBR1NQK2JDQlhpamFLdTN4UjNnenc9 ")
            'Convert_Doc("1234")
            ' test_excel_csv()
        Catch ex As Exception
        End Try
    End Sub

    Protected Overrides Sub OnStop()
        'w.Quit(SaveChanges:=False)
        'w = Nothing
        'x.Quit()
        'x = Nothing
    End Sub

#End Region

#Region "TimerHandling"
    Public Sub BCKTimer_Elapsed(ByVal sender As Object, ByVal e As System.Timers.ElapsedEventArgs) Handles BCK_Timer.Elapsed
        If EventStopped = True Then Exit Sub
        Parameters.Loglevel = My.Settings.LogLevel
        Parameters.Debug = My.Settings.Debug
        EventStopped = True
        BCK_Verarbeitung()
        EventStopped = False
    End Sub

    Public Sub DokumentTimer_Elapsed(ByVal sender As Object, ByVal e As System.Timers.ElapsedEventArgs) Handles Dokument_Timer.Elapsed
        If EventStopped = True Then Exit Sub
        Parameters.Loglevel = My.Settings.LogLevel
        Parameters.Debug = My.Settings.Debug
        EventStopped = True
        Archivierung_Verarbeitung()
        EventStopped = False
    End Sub

#End Region

#Region "SendMail"
    Public Function send_mail(ByVal ErrorText As String)
        Dim s As String = My.Settings.SendMail_PS
        s = s.Replace("&sender&", My.Settings.Sender)
        s = s.Replace("&recipient&", My.Settings.Recipient)
        s = s.Replace("&body&", ErrorText)
        Dim write As IO.StreamWriter
        write = New IO.StreamWriter(My.Settings.SendMailPath & "" & My.Settings.SendMailFile)
        write.Write(s)
        write.Close()
        s = My.Settings.SendMailCmd
        s = s + My.Settings.SendMailPath + "" + My.Settings.SendMailFile

        PDebug("Mailversand: " + s, 1)
        Process.Start("powershell.exe", s)
    End Function
#End Region

#Region "FileWatcher"

#Region "Verarbeitungen"
    Public Sub deleteTempFiles()
        If Parameters.DeleteTempFiles = True Then
            Dim directoryName As String = Parameters.TempDir
            For Each deleteFile As String In Directory.GetFiles(directoryName, "*.*", SearchOption.TopDirectoryOnly)
                Try
                    File.Delete(deleteFile)
                Catch
                End Try

            Next

            directoryName = Parameters.TempDirOffice
            For Each deleteFile As String In Directory.GetFiles(directoryName, "*.*", SearchOption.TopDirectoryOnly)
                Try
                    File.Delete(deleteFile)
                Catch
                End Try
            Next

        End If

    End Sub
    Public Sub BCK_Verarbeitung()
        Try
            PDebug("BCK verarbeiten", 1)
            deleteTempFiles()
            Dim dt As New DataTable
            OnBaseFiletype = "PDF"
            dt = db.Get_Pendente_BCK()
            For Each r As DataRow In dt.Rows
                OutputFile = Parameters.TempDir + "\" + r("dokumentid") + ".pdf"
                PDebug("Generiertes PDF: " + OutputFile, 1)
                If Create_BCK_Dummy(r("dokumentid"), r("barcodenr")) Then
                    PDebug("Base-64 Convert", 2)
                    Base64_File = ConvertFileToBase64(OutputFile)
                    JsonString = ""
                    PDebug("Create OnBase-Daten", 2)
                    Create_OnBase_Datastream(r("dokumentid"))
                    PDebug(JsonString, 3)
                    If JsonString <> "" Then
                        If Transfer_Onbase(r("dokumentid")) = True Then
                            Dim stnr As Integer
                            If updateedoka Then
                                PDebug("Update EDOKA-Datenbank", 2)
                                stnr = update_status(r("dokumentid"))
                                db.update_dokument(stnr, r("dokumentid"))
                            End If
                        Else
                            send_mail("Dokument nicht nach OnBase übergeben: " + r("dokumentid"))
                        End If
                    End If
                End If
            Next
            PDebug("BCK verarbeiten ende", 1)
        Catch ex As Exception
            PDebug(ex.Message, 1)
            send_mail(ex.Message)
        End Try

    End Sub

    Public Sub Archivierung_Verarbeitung()
        w = New Microsoft.Office.Interop.Word.Application
        x = New Microsoft.Office.Interop.Excel.Application
        ' 2012-12-16 DisplayAlert ausschalten
        w.DisplayAlerts = False
        x.DisplayAlerts = False
        'Ende  2012-12-16 DisplayAlert ausschalten

        PDebug("Standard verarbeiten", 1)
        deleteTempFiles()
        Dim dt As New DataTable
        Dim dd As New DataTable
        dt = db.Get_Archivdokumente

        For Each r As DataRow In dt.Rows
            Try
                Dim ofile As String
                dd = db.Get_Dokument(r("dokumentid"))
                If dd.Rows(0).Item("dokumenttypnr") = Parameters.ExcelDokTyp Then
                    Dim excellib As New clsexcel(Parameters.ExcelCSV)
                    excellib.Connectionstring = Parameters.Connectionstring_EDOKA
                    excellib.dokumenttypnr = Parameters.ExcelDokTyp
                    excellib.CSVPath = Parameters.ExcelCSV
                    mimetype = GetDocType(dd.Rows(0).Item("dokumentname"))
                    PDebug(mimetype, 2)
                    Dim filename As String
                    filename = Parameters.TempDirOffice + "\" + r("dokumentid") + "." + mimetype
                    If File.Exists(filename) Then
                        File.Delete(filename)
                        Thread.Sleep(500)
                    End If
                    db.Get_From_DB(r("dokumentid"), filename)
                    excellib.Excelfile = filename
                    excellib.Get_Excel_Values(r("dokumentid"))
                End If

                ofile = Convert_Doc(r("dokumentid"))
                If ofile <> "" Then
                    PDebug("Base-64 Convert", 2)
                    Base64_File = ConvertFileToBase64(ofile)

                    JsonString = ""
                    PDebug("Create OnBase-Daten", 2)
                    Create_OnBase_Datastream(r("dokumentid"))
                    If JsonString <> "" Then
                        PDebug(JsonString, 3)
                        If Transfer_Onbase(r("dokumentid")) = True Then
                            Dim stnr As Integer

                            If updateedoka = True Then
                                PDebug("Update EDOKA-Datenbank", 2)
                                stnr = update_status(r("dokumentid"))
                                db.update_dokument(stnr, r("dokumentid"))
                            End If
                        Else
                            send_mail("Dokument nicht nach OnBase übergeben: " + r("dokumentid"))
                        End If

                    End If
                End If

            Catch ex As Exception
                send_mail(ex.Message)
            End Try

        Next

        w.Quit(SaveChanges:=False)
        'w = Nothing
        x.Quit()

        '2023-12-16 Anpassungen ReleaseComObject
        Try
            If w IsNot Nothing Then
                System.Runtime.InteropServices.Marshal.ReleaseComObject(2)
            End If
            w = Nothing
        Catch ex As Exception
            'PDebug("Word ReleasecomObjekt Fehler: " + ex.Message, 1)
        End Try

        Try
            If x IsNot Nothing Then
                System.Runtime.InteropServices.Marshal.ReleaseComObject(2)
            End If
            x = Nothing
        Catch ex As Exception
            'PDebug("Excel ReleasecomObjekt Fehler: " + ex.Message, 1)
        End Try

        Try
            GC.Collect()
        Catch ex As Exception
            PDebug("GC.Collect: " + ex.Message, 1)

        End Try
        ' 2023-16-16 ende

        '2023-12-16 urpsürnglich
        'Marshal.ReleaseComObject(w)
        'Marshal.ReleaseComObject(x)
        'x = Nothing
        'w = Nothing
        '2023-12-16 ursprünglich Ende

        If Parameters.KillCmd <> "" Then
            Process.Start(Parameters.KillCmd)
        End If

        PDebug("Standard verarbeiten ende", 1)
    End Sub

    Public Function Create_BCK_Dummy(ByVal Dokumentid As String, ByVal barcodenr As String) As Boolean
        Try
            Dim document As New PdfDocument()
            Dim page As PdfPage = document.Pages.Add()
            Dim graphics As PdfGraphics = page.Graphics
            Dim font As PdfFont = New PdfStandardFont(PdfFontFamily.Helvetica, 20)
            If barcodenr = "" Then
                graphics.DrawString("Bedingt retournierbares-Dokument - nicht eingescannt", font, PdfBrushes.Black, New PointF(0, 0))
                graphics.DrawString("Dokument-ID: " + Dokumentid, font, PdfBrushes.Black, New PointF(0, 50))

            Else
                graphics.DrawString("EDOKA-Barcode-Dokument - noch nicht eingescannt", font, PdfBrushes.Black, New PointF(0, 0))
                graphics.DrawString("Dokument-ID: " + Dokumentid, font, PdfBrushes.Black, New PointF(0, 50))
                graphics.DrawString("Barcode-Kleber: " + barcodenr, font, PdfBrushes.Black, New PointF(0, 75))
            End If

            document.Save(Parameters.TempDir + "\" + Dokumentid + ".pdf")
            document.Close(True)
            PDebug("Dummy-PDF erfolgreich erstellt: " + Parameters.TempDir + "\" + Dokumentid + ".pdf", 3)
            Return True
        Catch
            PDebug("Dummy-PDF konnte nicht erstellt werden", 1)
            Return False
        End Try


    End Function

    Public Function update_status(ByVal dokumentid As String) As Integer
        Dim da As New DataTable
        da = db.Get_Status(dokumentid)
        For i As Integer = 0 To da.Rows.Count - 1
            If da.Rows(i).Item("status_bezeichnungnr") = 3 Then
                For i1 As Integer = 0 To da.Rows.Count - 1
                    If da.Rows(i1).Item("status_bezeichnungnr") = 4 Or
                       da.Rows(i1).Item("status_bezeichnungnr") = 5 Then
                        db.insert_history_status(da.Rows(i1).Item("dokument_statusnr"), dokumentid)
                        Return da.Rows(i1).Item("dokument_statusnr")
                    End If
                Next
            End If
            If da.Rows(i).Item("status_bezeichnungnr") = 11 Then
                For i1 As Integer = 0 To da.Rows.Count - 1
                    If da.Rows(i1).Item("status_bezeichnungnr") = 6 Then
                        db.insert_history_status(da.Rows(i1).Item("dokument_statusnr"), dokumentid)
                        Return da.Rows(i1).Item("dokument_statusnr")
                    End If
                Next
            End If
        Next
    End Function

    Private Sub Create_OnBase_Datastream(ByVal dokumentid As String)
        Dim ds As New DataSet
        ds = db.Get_OnBase_Datastream(dokumentid)
        Dim od As New OnBaseDokument
        od.dokumentTyp = ds.Tables(0).Rows(0).Item("Dokumenttyp")
        od.bpNummer = ds.Tables(0).Rows(0).Item("BPNummer")
        od.personNummer = ds.Tables(0).Rows(0).Item("PersonNummer")
        od.dokumentDatei = Base64_File
        od.dokumentDatum = ds.Tables(0).Rows(0).Item("Dokumentdatum")
        od.dateiTyp = UCase(OnBaseFiletype)

        Dim Attribute As New List(Of attribute)
        For Each rw As DataRow In ds.Tables(1).Rows
            Dim p As New attribute With
        {
          .fieldname = rw("fieldname"),
          .fieldvalue = rw("fieldvalue")
        }
            Attribute.Add(p)
        Next
        od.attributes = Attribute
        JsonString = ""
        JsonString = Newtonsoft.Json.JsonConvert.SerializeObject(od, Newtonsoft.Json.Formatting.Indented)
    End Sub

    Public Function ConvertFileToBase64(ByVal fileName As String) As String

        Dim ReturnValue As String = ""

        If My.Computer.FileSystem.FileExists(fileName) Then
            Using BinaryFile As FileStream = New FileStream(fileName, FileMode.Open)
                Dim BinRead As BinaryReader = New BinaryReader(BinaryFile)
                Dim BinBytes As Byte() = BinRead.ReadBytes(CInt(BinaryFile.Length))
                ReturnValue = Convert.ToBase64String(BinBytes)
                BinaryFile.Close()
            End Using
        End If
        Return ReturnValue
    End Function

    Public Function Transfer_Onbase(ByVal dokumentid As String) As Boolean
        Try
            PDebug("Transfer OnBase", 2)
            If sendtoonbase = True Then
                PDebug("OnBase", 3)
                Dim myUri As New Uri(Parameters.EntryPoint_IL)
                Dim data = Encoding.UTF8.GetBytes(JsonString)
                Dim response As String
                response = SendRequest_A(myUri, data, "application/json", "POST")
                PDebug("IL-Response", 3)
                PDebug(response, 1)
                'Dim db As New clsdb
                PDebug("JSON-Datei: " + Parameters.TempDir & "\" + dokumentid + ".json", 2)
                File.WriteAllText(Parameters.TempDir & "\" + dokumentid + ".json", JsonString)
                PDebug("Status in EDOKA-Journal nachführen", 2)
                db.Update_EDOKA_IL_Status(dokumentid, response, SendError)
                If SendError = "1" Then Return False Else Return True
            Else
                PDebug("Kein OnBase-Transfer", 1)
                PDebug("JSON-Datei: " + Parameters.TempDir & "\" + dokumentid + ".json", 1)

                File.WriteAllText(Parameters.TempDir & "\" + dokumentid + ".json", JsonString)
                db.Update_EDOKA_IL_Status(dokumentid, "DEMO:" + dokumentid, "0")
            End If
            PDebug("Ende Transfer OnBase", 1)
        Catch
            Return False
        End Try

    End Function

    Private Function SendRequest_A(uri As Uri, jsonDataBytes As Byte(), contentType As String, method As String) As String
        Dim response As String
        Dim request As WebRequest

        request = WebRequest.Create(uri)
        request.ContentLength = jsonDataBytes.Length
        request.ContentType = contentType
        request.Method = method
        Try

            Using requestStream As Stream = request.GetRequestStream
                requestStream.Write(jsonDataBytes, 0, jsonDataBytes.Length)
                requestStream.Close()

                Using responseStream As Stream = request.GetResponse.GetResponseStream
                    Using reader As New StreamReader(responseStream)
                        response = reader.ReadToEnd()
                    End Using
                End Using
            End Using
            SendError = "0"
            Return response
        Catch ex As Exception
            SendError = "1"
            Return ex.Message

        End Try


    End Function

#End Region

    '''<summary>Initialisierung des Filewacher-Objektes</summary>
    '''<remarks>Das Filewacher-Objekt wird mit den entpsrechenden Pfad- sowie
    '''Dateifilter-Angaben initialisiert.</remarks>
    Private Function Init_Filewatcher() As Boolean
        Try
            FileWatch.Path = Watch_Directory
            FileWatch.IncludeSubdirectories = False
            FileWatch.Filter = "*.*"
            Return True
        Catch ex As Exception
            'Printout("Fehler bei der Initialisierung des Filewacherobjekts auf " + Watch_Directory + ex.Message, EventLogEntryType.Error)
            Return False
        End Try
    End Function

    '''<summary>Eventhandler des FileWatching-Objektes aktivieren</summary>
    Private Function Start_Watching() As Boolean
        Try
            AddHandler FileWatch.Created, New FileSystemEventHandler(AddressOf OnFileEvent)
            AddHandler FileWatch.Renamed, AddressOf OnFileEventRename
            FileWatch.EnableRaisingEvents = True
            'PrintOut("Filewatch Event-Handler initialisiert: " + Me.Watch_Directory)
            Return True
        Catch ex As Exception
            'Printout("Fehler bei der Event-Initialisierung " + ex.Message, EventLogEntryType.Error)
            Return False
        End Try
    End Function


    '''<summary>Aktivitäten im Inputverzeichnis verarbeiten</summary>
    '''<remarks>Wird eine Datei mit der Endung .IND angeliefert, wird der Eventhandler
    '''gestoppt und die anstehenden Dokumente verarbeitet.
    '''
    '''Nach abgeschlossener Verarbeitung wird der Eventhandler wieder
    '''eingeschaltet</remarks>
    '''<param name="source"></param>
    '''<param name="e"></param>
    Private Sub OnFileEvent(ByVal source As Object, ByVal e As FileSystemEventArgs)
        If EventStopped = True Then Exit Sub


        If UCase(Microsoft.VisualBasic.Right(e.FullPath, 4)) = ".IND" Or UCase(Microsoft.VisualBasic.Right(e.FullPath, 4)) = ".XML" Then
            FileWatch.EnableRaisingEvents = False
            EventStopped = True

            'IntSleep(Params.WaitAfterFileevent)
            'If UCase(Microsoft.VisualBasic.Right(e.FullPath, 4)) = ".XML" Then
            '    IntSleep(Params.Wait_before_xmlind_ren)
            '    Rename(e.FullPath, e.FullPath + ".ind")
            '    PrintTempJournal("Fileevent Rename XML: " + e.FullPath + " -> " + e.FullPath + ".ind")
            'End If
            'PrintOut("Neue Datei " + e.FullPath)

            FileWatch.EnableRaisingEvents = True
        End If
    End Sub

    Private Sub OnFileEventRename(ByVal source As Object, ByVal e As RenamedEventArgs)
        'If Params.UseFileEventRename = False Then Exit Sub
        'If EventStopped = True Then Exit Sub
        'If UCase(Microsoft.VisualBasic.Right(e.FullPath, 4)) = ".IND" Then
        '    FileWatch.EnableRaisingEvents = False
        '    EventStopped = True
        '    PrintOut("Neue Datei " + e.FullPath)
        '    '20130131 - Sleep von 1000 auf 3000 geändert, damit bei FinFox-Dokumente die Verarbeitung nicht aussteigt, sofern die Datei noch nicht angeliefert wurde

        '    FileWatch.EnableRaisingEvents = True
        'End If
    End Sub



#End Region
#Region "Converter"
    Public Function Convert_Doc(ByVal dokumentid As String) As String
        Try
            PDebug("Start Convert Doc", 2)
            Dim dok As New DataTable
            dok = db.Get_Dokument(dokumentid)
            PDebug("Dok Read OK", 2)
            mimetype = GetDocType(dok.Rows(0).Item("dokumentname"))
            'mimetype = UCase(mimetype)


            PDebug(mimetype, 2)
            Dim filename As String
            filename = Parameters.TempDirOffice + "\" + dokumentid + "." + mimetype
            If File.Exists(filename) Then
                File.Delete(filename)
                Thread.Sleep(500)
            End If
            db.Get_From_DB(dokumentid, filename)
            OutputFile = ""
            Select Case UCase(mimetype)
                Case "DOC", "DOCX", "DOCM", "DOT", "DOTX", "DOTM"
                    OutputFile = Parameters.TempDir + "\" + dokumentid + ".pdf"
                    If Parameters.AsOffice.IndexOf(";" & dok.Rows(0).Item("dokumenttypnr").ToString & ";") > -1 Then
                        OutputFile = Parameters.TempDir + "\" + dokumentid + "." + mimetype
                        OnBaseFiletype = mimetype
                        FileCopy(filename, OutputFile)
                        PDebug("Datei kopieren: " + filename + " nach " + OutputFile, 2)
                        Return OutputFile
                    End If
                    'filename = "K:\EDOKA\__OnBase\dok1.docm"
                    PDebug("Word-Dokument konvertieren: " + filename + " nach " + OutputFile, 2)
                    OnBaseFiletype = "PDF"
                    If Convert_Word(filename, OutputFile) Then Return OutputFile Else Return ""

                Case "XLS", "XLSX", "XLSM", "XLT", "XLTX", "XLTM"
                    OutputFile = Parameters.TempDir + "\" + dokumentid + ".pdf"
                    If Parameters.AsOffice.IndexOf(";" & dok.Rows(0).Item("dokumenttypnr").ToString & ";") > -1 Then
                        OutputFile = Parameters.TempDir + "\" + dokumentid + "." + mimetype
                        OnBaseFiletype = mimetype
                        FileCopy(filename, OutputFile)
                        PDebug("Datei kopieren: " + filename + " nach " + OutputFile, 2)
                        Return OutputFile
                    End If
                    PDebug("Excel-Dokument konvertieren: " + filename + " nach " + OutputFile, 2)
                    If Convert_Excel(filename, OutputFile) Then Return OutputFile Else Return ""
                    OnBaseFiletype = "PDF"
                Case "PDF", "JPG", "TIF"
                    OutputFile = Parameters.TempDir + "\" + dokumentid + "." + mimetype
                    OnBaseFiletype = mimetype
                    FileCopy(filename, OutputFile)
                    PDebug("Datei kopieren: " + filename + " nach " + OutputFile, 2)
                    Return OutputFile
                Case Else
                    OutputFile = Parameters.TempDir + "\" + dokumentid + "." + mimetype
                    OnBaseFiletype = mimetype
                    FileCopy(filename, OutputFile)
                    PDebug("Datei kopieren: " + filename + " nach " + OutputFile, 2)
                    Return OutputFile
            End Select


        Catch ex As Exception
            PDebug(ex.Message, 1)
        End Try
    End Function

    Dim WithEvents WordTimer As New Timers.Timer
    Dim WithEvents ExcelTimer As New Timers.Timer
    Public Function Convert_Word(ByVal filename As String, ByVal outputfile As String) As Boolean

        WordTimer.Interval = 20000
        WordTimer.Enabled = True
        Try
            If w.Documents.Count > 0 Then
                For i As Integer = 1 To w.Documents.Count
                    w.Documents(i).Saved = True
                    w.Documents(i).Close(SaveChanges:=False)
                Next
            End If
        Catch ex As Exception
            w = Nothing
            w = New Microsoft.Office.Interop.Word.Application
        End Try
        Try
            w.Documents.Open(FileName:=filename.ToString, ReadOnly:=True)
            w.ActiveDocument.ExportAsFixedFormat(outputfile.ToString, Word.WdExportFormat.wdExportFormatPDF, , Word.WdExportOptimizeFor.wdExportOptimizeForPrint, Word.WdExportRange.wdExportAllDocument, , , Word.WdExportItem.wdExportDocumentContent, True, True, Word.WdExportCreateBookmarks.wdExportCreateNoBookmarks, True, False, False)
            w.ActiveDocument.Saved = True
            w.ActiveDocument.Close(SaveChanges:=False)
            WordTimer.Enabled = False
            Thread.Sleep(100)
            Return True
        Catch ex As Exception
            Try
                w.Quit(SaveChanges:=False)
            Catch
            End Try
            Try
                w = Nothing
            Catch
            End Try
            Try
                w = New Microsoft.Office.Interop.Word.Application
            Catch
            End Try
            Return False
        End Try
        WordTimer.Enabled = False
    End Function
    Public Sub WordTimer_Elapsed(ByVal sender As Object, ByVal e As System.Timers.ElapsedEventArgs) Handles WordTimer.Elapsed
        Dim processArray As Process() = Process.GetProcessesByName("winword")
        For Each p As Process In processArray
            p.Kill()
        Next
        WordTimer.Enabled = False
    End Sub
    Public Sub ExcelTimer_Elapsed(ByVal sender As Object, ByVal e As System.Timers.ElapsedEventArgs) Handles WordTimer.Elapsed
        Dim processArray As Process() = Process.GetProcessesByName("excel")
        For Each p As Process In processArray
            p.Kill()
        Next
        ExcelTimer.Enabled = False
    End Sub
    Public Function Convert_Excel(ByVal filename As String, ByVal outputfile As String) As Boolean
        ExcelTimer.Interval = 40000
        ExcelTimer.Enabled = True
        Try
            If x.Workbooks.Count > 0 Then
                For i As Integer = 1 To x.Workbooks.Count
                    x.Workbooks(i).Close(SaveChanges:=False)
                Next
            End If
            x.Workbooks.Open(filename.ToString)
            x.ActiveWorkbook.ExportAsFixedFormat(Microsoft.Office.Interop.Excel.XlFixedFormatType.xlTypePDF, outputfile.ToString, Microsoft.Office.Interop.Excel.XlFixedFormatQuality.xlQualityStandard)
            x.ActiveWorkbook.Close(SaveChanges:=False)
            ExcelTimer.Enabled = False
            Thread.Sleep(1000)
            Return True
        Catch ex As Exception
            PDebug("Fehler::Convert Excel: " + ex.Message, 1)

            Try
                x = Nothing
            Catch
            End Try
            Try
                x = New Microsoft.Office.Interop.Excel.Application
            Catch
            End Try

            Return False
        End Try
        ExcelTimer.Enabled = False
    End Function

    Public Function GetDocType(ByVal Filename As String) As String
        Dim NoDot() As String
        NoDot = Split(Filename, ".")
        GetDocType = NoDot(UBound(NoDot))
    End Function

    Public Sub PDebug(ByVal istring As String, ByVal loglevel As Integer)
        Dim s As String
        s = Now.ToString("u")
        istring = s + " - " + istring
        If debug = True Then
            Console.WriteLine(istring)
            If logfile <> "" Then
                Try
                    If loglevel <= Parameters.Loglevel Then
                        FileOpen(1, logfile, OpenMode.Append)
                        WriteLine(1, istring)
                        FileClose(1)
                    End If
                Catch
                End Try
            End If
        End If
    End Sub


#End Region



End Class
