Imports System.Data.SqlClient
Imports System.Globalization
Imports System.IO
Imports System.Reflection
Imports System.Text.RegularExpressions
Imports VERAG_PROG_ALLGEMEIN

Public Class cAsfinag

    Dim SQL As New VERAG_PROG_ALLGEMEIN.SQL

    Public Class CLFHeader

        Property PKFileName As Object = Nothing
        Property recordType As String
        Property fileVersion As Integer
        Property fileNumber As Integer
        Property indcator As Object = Nothing
        Property senderID As Object = Nothing
        Property receiverID As Object = Nothing
        Property fileCreationDate As DateTime
        Property fileCreationTime As DateTime
        Property ISOCountryCode As Object = Nothing
        Property creationName As Object = Nothing

        Public hasEntry = False

        Dim SQL As New VERAG_PROG_ALLGEMEIN.SQL

        Sub New(PKFileName, fileNumber)
            Me.PKFileName = PKFileName
            Me.fileNumber = fileNumber
            LOAD()
        End Sub

        Sub New()

        End Sub

        Function getParameterList() As List(Of VERAG_PROG_ALLGEMEIN.SQLVariable)
            Dim list As New List(Of VERAG_PROG_ALLGEMEIN.SQLVariable)
            list.Add(New VERAG_PROG_ALLGEMEIN.SQLVariable("PKFileName", PKFileName))
            list.Add(New VERAG_PROG_ALLGEMEIN.SQLVariable("fileNumber", fileNumber))
            list.Add(New VERAG_PROG_ALLGEMEIN.SQLVariable("recordType", recordType))
            list.Add(New VERAG_PROG_ALLGEMEIN.SQLVariable("fileVersion", fileVersion))
            list.Add(New VERAG_PROG_ALLGEMEIN.SQLVariable("indcator", indcator))
            list.Add(New VERAG_PROG_ALLGEMEIN.SQLVariable("senderID", senderID))
            list.Add(New VERAG_PROG_ALLGEMEIN.SQLVariable("receiverID", receiverID))
            list.Add(New VERAG_PROG_ALLGEMEIN.SQLVariable("fileCreationDate", fileCreationDate))
            list.Add(New VERAG_PROG_ALLGEMEIN.SQLVariable("fileCreationTime", fileCreationTime))
            list.Add(New VERAG_PROG_ALLGEMEIN.SQLVariable("ISOCountryCode", ISOCountryCode))
            list.Add(New VERAG_PROG_ALLGEMEIN.SQLVariable("creationName", creationName))

            Return list
        End Function

        Public Function SAVE() As Boolean
            Dim list As List(Of VERAG_PROG_ALLGEMEIN.SQLVariable) = getParameterList()

            Dim sqlstr = " BEGIN TRAN If EXISTS(Select * FROM CLFHeader  WHERE PKFileName=@PKFileName AND fileNumber = @fileNumber) " &
                       " BEGIN " & getUpdateCmd() & " End " &
                       " Else " &
                       " BEGIN " & getInsertCmd() & " End " &
                       " commit tran "

            Return SQL.doSQLVarList(sqlstr, "ASFINAG", , list)
        End Function

        Public Sub LOAD()
            Try
                hasEntry = False
                Using conn As SqlConnection = SQL.GetNewOpenConnectionAsfinag()
                    Using cmd As New SqlCommand("Select * FROM CLFHeader WHERE PKFileName=@PKFileName AND fileNumber = @fileNumber", conn)
                        cmd.Parameters.AddWithValue("@PKFileName", PKFileName)
                        cmd.Parameters.AddWithValue("@filenumber", fileNumber)
                        Dim dr = cmd.ExecuteReader()
                        If dr.Read Then
                            For Each li In getParameterList()
                                Dim propInfo As PropertyInfo = Me.GetType.GetProperty(li.Scalarvariable)

                                If dr.Item(li.Text) Is DBNull.Value Then
                                    propInfo.SetValue(Me, Nothing)
                                Else
                                    propInfo.SetValue(Me, dr.Item(li.Text))
                                End If

                            Next
                            hasEntry = True
                        End If
                        dr.Close()
                    End Using
                End Using
            Catch ex As Exception
                VERAG_PROG_ALLGEMEIN.cErrorHandler.ERR(ex.Message, ex.StackTrace, System.Reflection.MethodBase.GetCurrentMethod.Name)
            End Try
        End Sub



        Public Function getUpdateCmd() As String
            Try
                Dim list As List(Of VERAG_PROG_ALLGEMEIN.SQLVariable) = getParameterList()

                Dim str As String = ""
                For Each i In list
                    If Not i.isPrimaryParam Then
                        str &= "[" & i.Text & "] = @" & i.Scalarvariable & "," '.Replace("-", "").Replace(" ", "") & ","
                    End If
                Next
                str = str.Substring(0, str.Length - 1) 'wg. ','
                Return (" UPDATE [CLFHeader] SET " & str & " WHERE PKFileName=@PKFileName ")

            Catch ex As Exception
                VERAG_PROG_ALLGEMEIN.cErrorHandler.ERR(ex.Message, ex.StackTrace, System.Reflection.MethodBase.GetCurrentMethod.Name)
            End Try
            Return ""
        End Function


        Public Function getInsertCmd() As String
            Try
                Dim list As List(Of VERAG_PROG_ALLGEMEIN.SQLVariable) = getParameterList()
                Dim str As String = ""
                Dim values As String = ""
                For Each i In list
                    If Not i.isPrimaryParam Then
                        str &= "[" & i.Text & "],"
                        values &= "@" & i.Scalarvariable & "," '.Replace("-", "").Replace(" ", "") & ","
                    End If
                Next
                str = str.Substring(0, str.Length - 1) 'wg. ','
                values = values.Substring(0, values.Length - 1) 'wg. ','
                Return (" INSERT INTO CLFHeader  (" & str & ") VALUES(" & values & ")  ")
            Catch ex As Exception
                VERAG_PROG_ALLGEMEIN.cErrorHandler.ERR(ex.Message, ex.StackTrace, System.Reflection.MethodBase.GetCurrentMethod.Name)
            End Try
            Return ""
        End Function

    End Class

    Public Class CLFBody

        Property PKFileName As Object = Nothing
        Property RecordType As String
        Property fileVersion As Integer
        Property fileNumber As Integer
        Property cardNumber As String
        Property validTo As Integer
        Property OBUID As Object = Nothing
        Property vehicleLicensePlate As Object = Nothing
        Property nationality As Object = Nothing
        Property vehicleCategory As Object = Nothing
        Property emissionCategory As Object = Nothing
        Property status As Object = Nothing
        Property contractDate As Object = Nothing
        Property PKLine As Long
        Property engineCharacteristics As Integer
        Property CO2EmissionsClass As Integer
        Property contractType As Integer


        Public hasEntry = False

        Dim SQL As New VERAG_PROG_ALLGEMEIN.SQL

        Sub New(PKFileName, PKLine)
            Me.PKFileName = PKFileName
            Me.PKLine = PKLine
            LOAD()
        End Sub
        Function getParameterList() As List(Of VERAG_PROG_ALLGEMEIN.SQLVariable)
            Dim list As New List(Of VERAG_PROG_ALLGEMEIN.SQLVariable)
            list.Add(New VERAG_PROG_ALLGEMEIN.SQLVariable("PKFileName", PKFileName))
            list.Add(New VERAG_PROG_ALLGEMEIN.SQLVariable("PKLine", PKLine))
            list.Add(New VERAG_PROG_ALLGEMEIN.SQLVariable("RecordType", RecordType))
            list.Add(New VERAG_PROG_ALLGEMEIN.SQLVariable("fileVersion", fileVersion))
            list.Add(New VERAG_PROG_ALLGEMEIN.SQLVariable("fileNumber", fileNumber))
            list.Add(New VERAG_PROG_ALLGEMEIN.SQLVariable("cardNumber", cardNumber))
            list.Add(New VERAG_PROG_ALLGEMEIN.SQLVariable("validTo", validTo))
            list.Add(New VERAG_PROG_ALLGEMEIN.SQLVariable("OBUID", OBUID))
            list.Add(New VERAG_PROG_ALLGEMEIN.SQLVariable("vehicleLicensePlate", vehicleLicensePlate))
            list.Add(New VERAG_PROG_ALLGEMEIN.SQLVariable("nationality", nationality))
            list.Add(New VERAG_PROG_ALLGEMEIN.SQLVariable("vehicleCategory", vehicleCategory))
            list.Add(New VERAG_PROG_ALLGEMEIN.SQLVariable("emissionCategory", emissionCategory))
            list.Add(New VERAG_PROG_ALLGEMEIN.SQLVariable("status", status))
            list.Add(New VERAG_PROG_ALLGEMEIN.SQLVariable("contractDate", contractDate))
            list.Add(New VERAG_PROG_ALLGEMEIN.SQLVariable("engineCharacteristics", engineCharacteristics))
            list.Add(New VERAG_PROG_ALLGEMEIN.SQLVariable("CO2EmissionsClass", CO2EmissionsClass))
            list.Add(New VERAG_PROG_ALLGEMEIN.SQLVariable("contractType", contractType))

            Return list
        End Function

        Public Function SAVE() As Boolean
            Dim list As List(Of VERAG_PROG_ALLGEMEIN.SQLVariable) = getParameterList()

            Dim sqlstr = " BEGIN TRAN If EXISTS(Select * FROM CLFBody WHERE PKFileName=@PKFileName AND PKLine = @PKLine) " &
                       " BEGIN " & getUpdateCmd() & " End " &
                       " Else " &
                       " BEGIN " & getInsertCmd() & " End " &
                       " commit tran "

            Return SQL.doSQLVarList(sqlstr, "ASFINAG", , list)
        End Function

        Public Sub LOAD()
            Try
                hasEntry = False
                Using conn As SqlConnection = SQL.GetNewOpenConnectionAsfinag()
                    Using cmd As New SqlCommand("Select * FROM CLFBody WHERE PKFileName=@PKFileName AND PKLine = @PKLine  ", conn)
                        cmd.Parameters.AddWithValue("@PKFileName", PKFileName)
                        cmd.Parameters.AddWithValue("@PKLine", PKLine)
                        Dim dr = cmd.ExecuteReader()
                        If dr.Read Then
                            For Each li In getParameterList()
                                Dim propInfo As PropertyInfo = Me.GetType.GetProperty(li.Scalarvariable)

                                If dr.Item(li.Text) Is DBNull.Value Then
                                    propInfo.SetValue(Me, Nothing)
                                Else
                                    propInfo.SetValue(Me, dr.Item(li.Text))
                                End If

                            Next
                            hasEntry = True
                        End If
                        dr.Close()
                    End Using
                End Using
            Catch ex As Exception
                VERAG_PROG_ALLGEMEIN.cErrorHandler.ERR(ex.Message, ex.StackTrace, System.Reflection.MethodBase.GetCurrentMethod.Name)
            End Try
        End Sub



        Public Function getUpdateCmd() As String
            Try
                Dim list As List(Of VERAG_PROG_ALLGEMEIN.SQLVariable) = getParameterList()

                Dim str As String = ""
                For Each i In list
                    If Not i.isPrimaryParam Then
                        str &= "[" & i.Text & "] = @" & i.Scalarvariable & "," '.Replace("-", "").Replace(" ", "") & ","
                    End If
                Next
                str = str.Substring(0, str.Length - 1) 'wg. ','
                Return (" UPDATE [CLFBody] SET " & str & " WHERE PKFileName=@PKFileName AND PKLine  = @PKLine ")

            Catch ex As Exception
                VERAG_PROG_ALLGEMEIN.cErrorHandler.ERR(ex.Message, ex.StackTrace, System.Reflection.MethodBase.GetCurrentMethod.Name)
            End Try
            Return ""
        End Function


        Public Function getInsertCmd() As String
            Try
                Dim list As List(Of VERAG_PROG_ALLGEMEIN.SQLVariable) = getParameterList()
                Dim str As String = ""
                Dim values As String = ""
                For Each i In list
                    If Not i.isPrimaryParam Then
                        str &= "[" & i.Text & "],"
                        values &= "@" & i.Scalarvariable & "," '.Replace("-", "").Replace(" ", "") & ","
                    End If
                Next
                str = str.Substring(0, str.Length - 1) 'wg. ','
                values = values.Substring(0, values.Length - 1) 'wg. ','
                Return (" INSERT INTO CLFBody  (" & str & ") VALUES(" & values & ")  ")
            Catch ex As Exception
                VERAG_PROG_ALLGEMEIN.cErrorHandler.ERR(ex.Message, ex.StackTrace, System.Reflection.MethodBase.GetCurrentMethod.Name)
            End Try
            Return ""
        End Function





    End Class

    Public Class CLFArchiv

        Property PKFileName As Object = Nothing
        Property RecordType As String
        Property fileVersion As Integer
        Property fileNumber As Integer
        Property cardNumber As String
        Property validTo As Integer
        Property OBUID As Object = Nothing
        Property vehicleLicensePlate As Object = Nothing
        Property nationality As Object = Nothing
        Property vehicleCategory As Object = Nothing
        Property emissionCategory As Object = Nothing
        Property status As Object = Nothing
        Property contractDate As Object = Nothing
        Property PKLine As Long
        Property engineCharacteristics As Integer
        Property CO2EmissionsClass As Integer
        Property contractType As Integer


        Public hasEntry = False

        Dim SQL As New VERAG_PROG_ALLGEMEIN.SQL

        'Sub New(PKFileName, OBUID)
        '    Me.PKFileName = PKFileName
        '    Me.OBUID = OBUID
        '    LOAD()
        'End Sub

        Sub New(OBUID)
            Me.OBUID = OBUID
            LOAD()
        End Sub
        Function getParameterList() As List(Of VERAG_PROG_ALLGEMEIN.SQLVariable)
            Dim list As New List(Of VERAG_PROG_ALLGEMEIN.SQLVariable)
            list.Add(New VERAG_PROG_ALLGEMEIN.SQLVariable("PKFileName", PKFileName))
            list.Add(New VERAG_PROG_ALLGEMEIN.SQLVariable("PKLine", PKLine))
            list.Add(New VERAG_PROG_ALLGEMEIN.SQLVariable("RecordType", RecordType))
            list.Add(New VERAG_PROG_ALLGEMEIN.SQLVariable("fileVersion", fileVersion))
            list.Add(New VERAG_PROG_ALLGEMEIN.SQLVariable("fileNumber", fileNumber))
            list.Add(New VERAG_PROG_ALLGEMEIN.SQLVariable("cardNumber", cardNumber))
            list.Add(New VERAG_PROG_ALLGEMEIN.SQLVariable("validTo", validTo))
            list.Add(New VERAG_PROG_ALLGEMEIN.SQLVariable("OBUID", OBUID))
            list.Add(New VERAG_PROG_ALLGEMEIN.SQLVariable("vehicleLicensePlate", vehicleLicensePlate))
            list.Add(New VERAG_PROG_ALLGEMEIN.SQLVariable("nationality", nationality))
            list.Add(New VERAG_PROG_ALLGEMEIN.SQLVariable("vehicleCategory", vehicleCategory))
            list.Add(New VERAG_PROG_ALLGEMEIN.SQLVariable("emissionCategory", emissionCategory))
            list.Add(New VERAG_PROG_ALLGEMEIN.SQLVariable("status", status))
            list.Add(New VERAG_PROG_ALLGEMEIN.SQLVariable("contractDate", contractDate))
            list.Add(New VERAG_PROG_ALLGEMEIN.SQLVariable("engineCharacteristics", engineCharacteristics))
            list.Add(New VERAG_PROG_ALLGEMEIN.SQLVariable("CO2EmissionsClass", CO2EmissionsClass))
            list.Add(New VERAG_PROG_ALLGEMEIN.SQLVariable("contractType", contractType))

            Return list
        End Function

        Public Function SAVE() As Boolean
            Dim list As List(Of VERAG_PROG_ALLGEMEIN.SQLVariable) = getParameterList()

            'Dim sqlstr = " BEGIN TRAN If EXISTS(Select * FROM CLFArchiv WHERE PKFileName=@PKFileName AND OBUID = @OBUID) " &
            Dim sqlstr = " BEGIN TRAN If EXISTS(Select * FROM CLFArchiv WHERE OBUID = @OBUID) " &
                       " BEGIN " & getUpdateCmd() & " End " &
                       " Else " &
                       " BEGIN " & getInsertCmd() & " End " &
                       " commit tran "

            Return SQL.doSQLVarList(sqlstr, "ASFINAG", , list)
        End Function

        Public Sub LOAD()
            Try
                hasEntry = False
                Using conn As SqlConnection = SQL.GetNewOpenConnectionAsfinag()
                    Using cmd As New SqlCommand("Select * FROM CLFArchiv WHERE  OBUID = @OBUID  ", conn)
                        'Using cmd As New SqlCommand("Select * FROM CLFArchiv WHERE PKFileName=@PKFileName AND OBUID = @OBUID  ", conn)
                        'cmd.Parameters.AddWithValue("@PKFileName", PKFileName)
                        cmd.Parameters.AddWithValue("@OBUID", OBUID)
                        Dim dr = cmd.ExecuteReader()
                        If dr.Read Then
                            For Each li In getParameterList()
                                Dim propInfo As PropertyInfo = Me.GetType.GetProperty(li.Scalarvariable)

                                If dr.Item(li.Text) Is DBNull.Value Then
                                    propInfo.SetValue(Me, Nothing)
                                Else
                                    propInfo.SetValue(Me, dr.Item(li.Text))
                                End If

                            Next
                            hasEntry = True
                        End If
                        dr.Close()
                    End Using
                End Using
            Catch ex As Exception
                VERAG_PROG_ALLGEMEIN.cErrorHandler.ERR(ex.Message, ex.StackTrace, System.Reflection.MethodBase.GetCurrentMethod.Name)
            End Try
        End Sub



        Public Function getUpdateCmd() As String
            Try
                Dim list As List(Of VERAG_PROG_ALLGEMEIN.SQLVariable) = getParameterList()

                Dim str As String = ""
                For Each i In list
                    If Not i.isPrimaryParam Then
                        str &= "[" & i.Text & "] = @" & i.Scalarvariable & "," '.Replace("-", "").Replace(" ", "") & ","
                    End If
                Next
                str = str.Substring(0, str.Length - 1) 'wg. ','
                'Return (" UPDATE [CLFArchiv] SET " & str & " WHERE PKFileName=@PKFileName AND OBUID = @OBUID ")
                Return (" UPDATE [CLFArchiv] SET " & str & " WHERE OBUID = @OBUID ")

            Catch ex As Exception
                VERAG_PROG_ALLGEMEIN.cErrorHandler.ERR(ex.Message, ex.StackTrace, System.Reflection.MethodBase.GetCurrentMethod.Name)
            End Try
            Return ""
        End Function


        Public Function getInsertCmd() As String
            Try
                Dim list As List(Of VERAG_PROG_ALLGEMEIN.SQLVariable) = getParameterList()
                Dim str As String = ""
                Dim values As String = ""
                For Each i In list
                    If Not i.isPrimaryParam Then
                        str &= "[" & i.Text & "],"
                        values &= "@" & i.Scalarvariable & "," '.Replace("-", "").Replace(" ", "") & ","
                    End If
                Next
                str = str.Substring(0, str.Length - 1) 'wg. ','
                values = values.Substring(0, values.Length - 1) 'wg. ','
                Return (" INSERT INTO CLFArchiv  (" & str & ") VALUES(" & values & ")  ")
            Catch ex As Exception
                VERAG_PROG_ALLGEMEIN.cErrorHandler.ERR(ex.Message, ex.StackTrace, System.Reflection.MethodBase.GetCurrentMethod.Name)
            End Try
            Return ""
        End Function





    End Class

    Public Class CLFTrailer

        Property PKFileName As Object = Nothing
        Property recordType As String
        Property fileVersion As Integer
        Property fileNumber As Integer
        Property recordCount As Integer



        Public hasEntry = False

        Dim SQL As New VERAG_PROG_ALLGEMEIN.SQL

        Sub New(PKFileName)
            Me.PKFileName = PKFileName
            LOAD()
        End Sub
        Function getParameterList() As List(Of VERAG_PROG_ALLGEMEIN.SQLVariable)
            Dim list As New List(Of VERAG_PROG_ALLGEMEIN.SQLVariable)
            list.Add(New VERAG_PROG_ALLGEMEIN.SQLVariable("PKFileName", PKFileName))
            list.Add(New VERAG_PROG_ALLGEMEIN.SQLVariable("recordType", recordType))
            list.Add(New VERAG_PROG_ALLGEMEIN.SQLVariable("fileVersion", fileVersion))
            list.Add(New VERAG_PROG_ALLGEMEIN.SQLVariable("fileNumber", fileNumber))
            list.Add(New VERAG_PROG_ALLGEMEIN.SQLVariable("recordCount", recordCount))

            Return list
        End Function

        Public Function SAVE() As Boolean
            Dim list As List(Of VERAG_PROG_ALLGEMEIN.SQLVariable) = getParameterList()

            Dim sqlstr = " BEGIN TRAN If EXISTS(Select * FROM CLFTrailer  WHERE PKFileName=@PKFileName) " &
                       " BEGIN " & getUpdateCmd() & " End " &
                       " Else " &
                       " BEGIN " & getInsertCmd() & " End " &
                       " commit tran "

            Return SQL.doSQLVarList(sqlstr, "ASFINAG", , list)
        End Function

        Public Sub LOAD()
            Try
                hasEntry = False
                Using conn As SqlConnection = SQL.GetNewOpenConnectionAsfinag()
                    Using cmd As New SqlCommand("Select * FROM CLFTrailer WHERE PKFileName=@PKFileName", conn)
                        cmd.Parameters.AddWithValue("@PKFileName", PKFileName)
                        Dim dr = cmd.ExecuteReader()
                        If dr.Read Then
                            For Each li In getParameterList()
                                Dim propInfo As PropertyInfo = Me.GetType.GetProperty(li.Scalarvariable)

                                If dr.Item(li.Text) Is DBNull.Value Then
                                    propInfo.SetValue(Me, Nothing)
                                Else
                                    propInfo.SetValue(Me, dr.Item(li.Text))
                                End If

                            Next
                            hasEntry = True
                        End If
                        dr.Close()
                    End Using
                End Using
            Catch ex As Exception
                VERAG_PROG_ALLGEMEIN.cErrorHandler.ERR(ex.Message, ex.StackTrace, System.Reflection.MethodBase.GetCurrentMethod.Name)
            End Try
        End Sub



        Public Function getUpdateCmd() As String
            Try
                Dim list As List(Of VERAG_PROG_ALLGEMEIN.SQLVariable) = getParameterList()

                Dim str As String = ""
                For Each i In list
                    If Not i.isPrimaryParam Then
                        str &= "[" & i.Text & "] = @" & i.Scalarvariable & "," '.Replace("-", "").Replace(" ", "") & ","
                    End If
                Next
                str = str.Substring(0, str.Length - 1) 'wg. ','
                Return (" UPDATE [CLFTrailer] SET " & str & " WHERE PKFileName=@PKFileName")

            Catch ex As Exception
                VERAG_PROG_ALLGEMEIN.cErrorHandler.ERR(ex.Message, ex.StackTrace, System.Reflection.MethodBase.GetCurrentMethod.Name)
            End Try
            Return ""
        End Function


        Public Function getInsertCmd() As String
            Try
                Dim list As List(Of VERAG_PROG_ALLGEMEIN.SQLVariable) = getParameterList()
                Dim str As String = ""
                Dim values As String = ""
                For Each i In list
                    If Not i.isPrimaryParam Then
                        str &= "[" & i.Text & "],"
                        values &= "@" & i.Scalarvariable & "," '.Replace("-", "").Replace(" ", "") & ","
                    End If
                Next
                str = str.Substring(0, str.Length - 1) 'wg. ','
                values = values.Substring(0, values.Length - 1) 'wg. ','
                Return (" INSERT INTO CLFTrailer  (" & str & ") VALUES(" & values & ")  ")
            Catch ex As Exception
                VERAG_PROG_ALLGEMEIN.cErrorHandler.ERR(ex.Message, ex.StackTrace, System.Reflection.MethodBase.GetCurrentMethod.Name)
            End Try
            Return ""
        End Function



    End Class


    Public Class TTRHeader

        Property PKFileName As Object = Nothing
        Property PKHistory As Integer
        Property recordType As Integer
        Property fileVersion As Integer
        Property fileNumber As Integer
        Property senderID As Object = Nothing
        Property receiverID As Object = Nothing
        Property fileCreationDate As DateTime
        Property fileCreationTime As DateTime
        Property ISOCountryCode As Object = Nothing
        Property description As Object = Nothing
        Property currencyCode As Object = Nothing

        Public hasEntry = False

        Dim SQL As New VERAG_PROG_ALLGEMEIN.SQL

        Sub New(PKFileName, filenummer, PKHistory)
            Me.PKFileName = PKFileName
            Me.fileNumber = filenummer
            Me.PKHistory = PKHistory
            LOAD()
        End Sub
        Function getParameterList() As List(Of VERAG_PROG_ALLGEMEIN.SQLVariable)
            Dim list As New List(Of VERAG_PROG_ALLGEMEIN.SQLVariable)
            list.Add(New VERAG_PROG_ALLGEMEIN.SQLVariable("PKFileName", PKFileName))
            list.Add(New VERAG_PROG_ALLGEMEIN.SQLVariable("PKHistory", PKHistory))
            list.Add(New VERAG_PROG_ALLGEMEIN.SQLVariable("recordType", recordType))
            list.Add(New VERAG_PROG_ALLGEMEIN.SQLVariable("fileVersion", fileVersion))
            list.Add(New VERAG_PROG_ALLGEMEIN.SQLVariable("fileNumber", fileNumber))
            list.Add(New VERAG_PROG_ALLGEMEIN.SQLVariable("senderID", senderID))
            list.Add(New VERAG_PROG_ALLGEMEIN.SQLVariable("receiverID", receiverID))
            list.Add(New VERAG_PROG_ALLGEMEIN.SQLVariable("fileCreationDate", fileCreationDate))
            list.Add(New VERAG_PROG_ALLGEMEIN.SQLVariable("fileCreationTime", fileCreationTime))
            list.Add(New VERAG_PROG_ALLGEMEIN.SQLVariable("ISOCountryCode", ISOCountryCode))
            list.Add(New VERAG_PROG_ALLGEMEIN.SQLVariable("description", description))
            list.Add(New VERAG_PROG_ALLGEMEIN.SQLVariable("currencyCode", currencyCode))

            Return list
        End Function

        Public Function SAVE() As Boolean
            Dim list As List(Of VERAG_PROG_ALLGEMEIN.SQLVariable) = getParameterList()

            Dim sqlstr = " BEGIN TRAN If EXISTS(Select * FROM TTRHeader  WHERE PKFileName=@PKFileName AND fileNumber = @fileNumber AND PKHistory = @PKHistory) " &
                       " BEGIN " & getUpdateCmd() & " End " &
                       " Else " &
                       " BEGIN " & getInsertCmd() & " End " & " commit tran "

            Return SQL.doSQLVarList(sqlstr, "ASFINAG", , list)
        End Function


        Public Function UPDATE(OldKHistory As Integer) As Boolean
            Dim list As List(Of VERAG_PROG_ALLGEMEIN.SQLVariable) = getParameterList()

            Dim sqlstr = " BEGIN TRAN" & getUpdateCmd(OldKHistory) & " commit tran "

            Return SQL.doSQLVarList(sqlstr, "ASFINAG", , list)
        End Function


        Public Sub LOAD()
            Try
                hasEntry = False
                Using conn As SqlConnection = SQL.GetNewOpenConnectionAsfinag()
                    Using cmd As New SqlCommand("Select * FROM TTRHeader WHERE PKFileName=@PKFileName AND fileNumber = @fileNumber AND PKHistory = @PKHistory ", conn)
                        cmd.Parameters.AddWithValue("@PKFileName", PKFileName)
                        cmd.Parameters.AddWithValue("@fileNumber", fileNumber)
                        cmd.Parameters.AddWithValue("@PKHistory", PKHistory)
                        Dim dr = cmd.ExecuteReader()
                        If dr.Read Then
                            For Each li In getParameterList()
                                Dim propInfo As PropertyInfo = Me.GetType.GetProperty(li.Scalarvariable)

                                If dr.Item(li.Text) Is DBNull.Value Then
                                    propInfo.SetValue(Me, Nothing)
                                Else
                                    propInfo.SetValue(Me, dr.Item(li.Text))
                                End If

                            Next
                            hasEntry = True
                        End If
                        dr.Close()
                    End Using
                End Using
            Catch ex As Exception
                VERAG_PROG_ALLGEMEIN.cErrorHandler.ERR(ex.Message, ex.StackTrace, System.Reflection.MethodBase.GetCurrentMethod.Name)
            End Try
        End Sub



        Public Function getUpdateCmd(Optional OldKHistory As Integer = Nothing) As String
            Try
                Dim list As List(Of VERAG_PROG_ALLGEMEIN.SQLVariable) = getParameterList()

                Dim str As String = ""
                For Each i In list
                    If Not i.isPrimaryParam Then
                        str &= "[" & i.Text & "] = @" & i.Scalarvariable & "," '.Replace("-", "").Replace(" ", "") & ","
                    End If
                Next
                str = str.Substring(0, str.Length - 1) 'wg. ','
                If OldKHistory >= 0 Then
                    Return " UPDATE [TTRHeader] SET " & str & " WHERE PKFileName=@PKFileName AND filenumber = @filenumber AND PKHistory = " & OldKHistory
                Else
                    Return " UPDATE [TTRHeader] SET " & str & " WHERE PKFileName=@PKFileName AND filenumber = @filenumber"
                End If


            Catch ex As Exception
                VERAG_PROG_ALLGEMEIN.cErrorHandler.ERR(ex.Message, ex.StackTrace, System.Reflection.MethodBase.GetCurrentMethod.Name)
            End Try
            Return ""
        End Function


        Public Function getInsertCmd() As String
            Try
                Dim list As List(Of VERAG_PROG_ALLGEMEIN.SQLVariable) = getParameterList()
                Dim str As String = ""
                Dim values As String = ""
                For Each i In list
                    If Not i.isPrimaryParam Then
                        str &= "[" & i.Text & "],"
                        values &= "@" & i.Scalarvariable & "," '.Replace("-", "").Replace(" ", "") & ","
                    End If
                Next
                str = str.Substring(0, str.Length - 1) 'wg. ','
                values = values.Substring(0, values.Length - 1) 'wg. ','
                Return (" INSERT INTO TTRHeader  (" & str & ") VALUES(" & values & ")  ")
            Catch ex As Exception
                VERAG_PROG_ALLGEMEIN.cErrorHandler.ERR(ex.Message, ex.StackTrace, System.Reflection.MethodBase.GetCurrentMethod.Name)
            End Try
            Return ""
        End Function

    End Class

    Public Class TTRBody

        Property PKFileName As Object = Nothing
        Property recordType As Integer
        Property PKHistory As Integer
        Property fileVersion As Integer
        Property siteId As String
        Property fileNumber As Integer
        Property cardNumber As String
        Property fileCreationDate As Date
        Property deliveryNoteNumber As Integer
        Property deliveryDate As Date
        Property deliveryTime As Date
        Property transactionType As Integer
        Property productCode As Integer
        Property productQuantity As Double
        Property amountInclVAT As Double
        Property VATrate As Double
        Property VATamount As Double
        Property PKLine As Integer
        Property km As Integer
        Property driverId As Integer
        Property receiptNumber As String
        Property OBUID As String
        Property abrechnungsdatum As Object = Nothing

        Public hasEntry = False

        Dim SQL As New VERAG_PROG_ALLGEMEIN.SQL

        Sub New()

        End Sub

        Sub New(PKFileName, PKLine, PKHistory)
            Me.PKFileName = PKFileName
            Me.PKLine = PKLine
            Me.PKHistory = PKHistory
            LOAD()
        End Sub
        Function getParameterList() As List(Of VERAG_PROG_ALLGEMEIN.SQLVariable)
            Dim list As New List(Of VERAG_PROG_ALLGEMEIN.SQLVariable)
            list.Add(New VERAG_PROG_ALLGEMEIN.SQLVariable("PKFileName", PKFileName))
            list.Add(New VERAG_PROG_ALLGEMEIN.SQLVariable("PKHistory", PKHistory))
            list.Add(New VERAG_PROG_ALLGEMEIN.SQLVariable("PKLine", PKLine))
            list.Add(New VERAG_PROG_ALLGEMEIN.SQLVariable("fileVersion", fileVersion))
            list.Add(New VERAG_PROG_ALLGEMEIN.SQLVariable("recordType", recordType))
            list.Add(New VERAG_PROG_ALLGEMEIN.SQLVariable("siteId", siteId))
            list.Add(New VERAG_PROG_ALLGEMEIN.SQLVariable("fileNumber", fileNumber))
            list.Add(New VERAG_PROG_ALLGEMEIN.SQLVariable("fileCreationDate", fileCreationDate))
            list.Add(New VERAG_PROG_ALLGEMEIN.SQLVariable("deliveryNoteNumber", deliveryNoteNumber))
            list.Add(New VERAG_PROG_ALLGEMEIN.SQLVariable("cardNumber", cardNumber))
            list.Add(New VERAG_PROG_ALLGEMEIN.SQLVariable("deliveryDate", deliveryDate))
            list.Add(New VERAG_PROG_ALLGEMEIN.SQLVariable("deliveryTime", deliveryTime))
            list.Add(New VERAG_PROG_ALLGEMEIN.SQLVariable("transactionType", transactionType))
            list.Add(New VERAG_PROG_ALLGEMEIN.SQLVariable("productCode", productCode))
            list.Add(New VERAG_PROG_ALLGEMEIN.SQLVariable("km", km))
            list.Add(New VERAG_PROG_ALLGEMEIN.SQLVariable("driverId", driverId))
            list.Add(New VERAG_PROG_ALLGEMEIN.SQLVariable("productQuantity", productQuantity))
            list.Add(New VERAG_PROG_ALLGEMEIN.SQLVariable("amountInclVAT", amountInclVAT))
            list.Add(New VERAG_PROG_ALLGEMEIN.SQLVariable("VATrate", VATrate))
            list.Add(New VERAG_PROG_ALLGEMEIN.SQLVariable("VATamount", VATamount))
            list.Add(New VERAG_PROG_ALLGEMEIN.SQLVariable("receiptNumber", receiptNumber))
            list.Add(New VERAG_PROG_ALLGEMEIN.SQLVariable("OBUID", OBUID))
            list.Add(New VERAG_PROG_ALLGEMEIN.SQLVariable("abrechnungsdatum", abrechnungsdatum))

            Return list
        End Function

        Public Function SAVE() As Boolean
            Dim list As List(Of VERAG_PROG_ALLGEMEIN.SQLVariable) = getParameterList()

            Dim sqlstr = " BEGIN TRAN If EXISTS(Select * FROM TTRBody  WHERE PKFileName=@PKFileName AND  PKLine = @PKLine AND PKHistory = @PKHistory) " &
                       " BEGIN " & getUpdateCmd() & " End " &
                       " Else " &
                       " BEGIN " & getInsertCmd() & " End " & " commit tran "

            Return SQL.doSQLVarList(sqlstr, "ASFINAG", , list)
        End Function

        Public Sub LOAD()
            Try
                hasEntry = False
                Using conn As SqlConnection = SQL.GetNewOpenConnectionAsfinag()
                    Using cmd As New SqlCommand("Select * FROM TTRBody WHERE PKFileName=@PKFileName AND PKLine = @PKLine AND PKHistory = @PKHistory ", conn)
                        cmd.Parameters.AddWithValue("@PKFileName", PKFileName)
                        cmd.Parameters.AddWithValue("@PKLine", PKLine)
                        cmd.Parameters.AddWithValue("@PKHistory", PKHistory)
                        Dim dr = cmd.ExecuteReader()
                        If dr.Read Then
                            For Each li In getParameterList()
                                Dim propInfo As PropertyInfo = Me.GetType.GetProperty(li.Scalarvariable)

                                If dr.Item(li.Text) Is DBNull.Value Then
                                    propInfo.SetValue(Me, Nothing)
                                Else
                                    propInfo.SetValue(Me, dr.Item(li.Text))
                                End If

                            Next
                            hasEntry = True
                        End If
                        dr.Close()
                    End Using
                End Using
            Catch ex As Exception
                VERAG_PROG_ALLGEMEIN.cErrorHandler.ERR(ex.Message, ex.StackTrace, System.Reflection.MethodBase.GetCurrentMethod.Name)
            End Try
        End Sub



        Public Function getUpdateCmd() As String
            Try
                Dim list As List(Of VERAG_PROG_ALLGEMEIN.SQLVariable) = getParameterList()

                Dim str As String = ""
                For Each i In list
                    If Not i.isPrimaryParam Then
                        str &= "[" & i.Text & "] = @" & i.Scalarvariable & "," '.Replace("-", "").Replace(" ", "") & ","
                    End If
                Next
                str = str.Substring(0, str.Length - 1) 'wg. ','
                Return (" UPDATE [TTRBody] SET " & str & " WHERE PKFileName=@PKFileName AND PKLine = @PKLine AND PKHistory = @PKHistory")

            Catch ex As Exception
                VERAG_PROG_ALLGEMEIN.cErrorHandler.ERR(ex.Message, ex.StackTrace, System.Reflection.MethodBase.GetCurrentMethod.Name)
            End Try
            Return ""
        End Function


        Public Function getInsertCmd() As String
            Try
                Dim list As List(Of VERAG_PROG_ALLGEMEIN.SQLVariable) = getParameterList()
                Dim str As String = ""
                Dim values As String = ""
                For Each i In list
                    If Not i.isPrimaryParam Then
                        str &= "[" & i.Text & "],"
                        values &= "@" & i.Scalarvariable & "," '.Replace("-", "").Replace(" ", "") & ","
                    End If
                Next
                str = str.Substring(0, str.Length - 1) 'wg. ','
                values = values.Substring(0, values.Length - 1) 'wg. ','
                Return (" INSERT INTO TTRBody  (" & str & ") VALUES(" & values & ")  ")
            Catch ex As Exception
                VERAG_PROG_ALLGEMEIN.cErrorHandler.ERR(ex.Message, ex.StackTrace, System.Reflection.MethodBase.GetCurrentMethod.Name)
            End Try
            Return ""
        End Function





    End Class

    Public Class TTRTrailer

        Property PKFileName As Object = Nothing
        Property PKHistory As Integer
        Property recordType As Integer
        Property fileVersion As Integer
        Property recordCount As Integer
        Property checksumProductQuantity As Double
        Property checksumAmounntInclVAT As Double

        Public hasEntry = False

        Dim SQL As New VERAG_PROG_ALLGEMEIN.SQL

        Sub New(PKFileName, PKHistory)
            Me.PKFileName = PKFileName
            Me.PKHistory = PKHistory
            LOAD()
        End Sub
        Function getParameterList() As List(Of VERAG_PROG_ALLGEMEIN.SQLVariable)
            Dim list As New List(Of VERAG_PROG_ALLGEMEIN.SQLVariable)
            list.Add(New VERAG_PROG_ALLGEMEIN.SQLVariable("PKFileName", PKFileName))
            list.Add(New VERAG_PROG_ALLGEMEIN.SQLVariable("PKHistory", PKHistory))
            list.Add(New VERAG_PROG_ALLGEMEIN.SQLVariable("recordType", recordType))
            list.Add(New VERAG_PROG_ALLGEMEIN.SQLVariable("fileVersion", fileVersion))
            list.Add(New VERAG_PROG_ALLGEMEIN.SQLVariable("recordCount", recordCount))
            list.Add(New VERAG_PROG_ALLGEMEIN.SQLVariable("checksumProductQuantity", checksumProductQuantity))
            list.Add(New VERAG_PROG_ALLGEMEIN.SQLVariable("checksumAmounntInclVAT", checksumAmounntInclVAT))

            Return list
        End Function

        Public Function SAVE() As Boolean
            Dim list As List(Of VERAG_PROG_ALLGEMEIN.SQLVariable) = getParameterList()

            Dim sqlstr = " BEGIN TRAN If EXISTS(Select * FROM TTRTrailer WHERE PKFileName=@PKFileName AND PKHistory = @PKHistory) " &
                       " BEGIN " & getUpdateCmd() & " End " &
                       " Else " &
                       " BEGIN " & getInsertCmd() & " End " &
                       " commit tran "

            Return SQL.doSQLVarList(sqlstr, "ASFINAG", , list)
        End Function

        Public Sub LOAD()
            Try
                hasEntry = False
                Using conn As SqlConnection = SQL.GetNewOpenConnectionAsfinag()
                    Using cmd As New SqlCommand("Select * FROM TTRTrailer WHERE PKFileName=@PKFileName AND PKHistory = @PKHistory", conn)
                        cmd.Parameters.AddWithValue("@PKFileName", PKFileName)
                        cmd.Parameters.AddWithValue("@PKHistory", PKHistory)
                        Dim dr = cmd.ExecuteReader()
                        If dr.Read Then
                            For Each li In getParameterList()
                                Dim propInfo As PropertyInfo = Me.GetType.GetProperty(li.Scalarvariable)

                                If dr.Item(li.Text) Is DBNull.Value Then
                                    propInfo.SetValue(Me, Nothing)
                                Else
                                    propInfo.SetValue(Me, dr.Item(li.Text))
                                End If

                            Next
                            hasEntry = True
                        End If
                        dr.Close()
                    End Using
                End Using
            Catch ex As Exception
                VERAG_PROG_ALLGEMEIN.cErrorHandler.ERR(ex.Message, ex.StackTrace, System.Reflection.MethodBase.GetCurrentMethod.Name)
            End Try
        End Sub



        Public Function getUpdateCmd() As String
            Try
                Dim list As List(Of VERAG_PROG_ALLGEMEIN.SQLVariable) = getParameterList()

                Dim str As String = ""
                For Each i In list
                    If Not i.isPrimaryParam Then
                        str &= "[" & i.Text & "] = @" & i.Scalarvariable & "," '.Replace("-", "").Replace(" ", "") & ","
                    End If
                Next
                str = str.Substring(0, str.Length - 1) 'wg. ','
                Return (" UPDATE [TTRTrailer] SET " & str & " WHERE PKFileName=@PKFileName")

            Catch ex As Exception
                VERAG_PROG_ALLGEMEIN.cErrorHandler.ERR(ex.Message, ex.StackTrace, System.Reflection.MethodBase.GetCurrentMethod.Name)
            End Try
            Return ""
        End Function


        Public Function getInsertCmd() As String
            Try
                Dim list As List(Of VERAG_PROG_ALLGEMEIN.SQLVariable) = getParameterList()
                Dim str As String = ""
                Dim values As String = ""
                For Each i In list
                    If Not i.isPrimaryParam Then
                        str &= "[" & i.Text & "],"
                        values &= "@" & i.Scalarvariable & "," '.Replace("-", "").Replace(" ", "") & ","
                    End If
                Next
                str = str.Substring(0, str.Length - 1) 'wg. ','
                values = values.Substring(0, values.Length - 1) 'wg. ','
                Return (" INSERT INTO TTRTrailer  (" & str & ") VALUES(" & values & ")  ")
            Catch ex As Exception
                VERAG_PROG_ALLGEMEIN.cErrorHandler.ERR(ex.Message, ex.StackTrace, System.Reflection.MethodBase.GetCurrentMethod.Name)
            End Try
            Return ""
        End Function



    End Class

    Public Class Paramter
        Shared SQL As New VERAG_PROG_ALLGEMEIN.SQL

        Shared Function GET_PARAM_ByName(tcParam_name, TESTSYSTEM) As String
            Return SQL.getValueTxtBySql("SELECT TOP 1 [Param_value]  FROM [tblPartnersystem_Paramter] WHERE  Param_system='ASFINAG' AND [Param_name]='" & tcParam_name & "'", , , SQL.GetNewOpenConnectionFMZOLL_SYSTEM(TESTSYSTEM))
        End Function
    End Class


    Shared Function fktMod10Prüfziffer(strNummer As String) As String
        ' Der Funktion wird im Feld strNummer der Wert ohne Prüfziffer übergeben.
        ' Die Funktion berechnet und liefert die Prüfziffer zurück.

        Dim intIX As Integer
        Dim intZSum As Integer
        Dim intSum As Integer
        Dim boo1 As Boolean

        For intIX = Len(strNummer) To 1 Step -1
            intZSum = IIf(boo1, Mid(strNummer, intIX, 1) * 1, Mid(strNummer, intIX, 1) * 2)
            If intZSum < 10 Then
                intSum = intSum + intZSum
            Else
                intSum = intSum + ((intZSum Mod 10) + ((intZSum - (intZSum Mod 10)) / 10))
            End If
            boo1 = Not boo1
        Next intIX

        fktMod10Prüfziffer = CStr((10 - (intSum Mod 10)) Mod 10)

    End Function

    Public Class Exportist

        Dim blacklisteExported As Boolean = False
        Dim whiteListExported As Boolean = False

        Structure Header                  ' Format    Muss    von     bis     Kommentar
            Dim SortField As String             ' N3        Y       1       3       "000"
            Dim RecordID As String              ' N2        Y       4       5       "00"
            Dim FileName As String             ' C3        Y       6       8       "TBL"
            Dim LiveTestIndicator As String    ' C1        Y       9       9       "L" oder "T"
            Dim FileCreationDate As String ' N8        Y       10      17      YYYYMMDD
            Dim FileCreationTime As String       ' N4        Y       18      21      HHMM (24hr)
            Dim RunNumber As String         ' N3        Y       22      24      Laufende Nummer pro File-Type
            Dim SenderID As String ' C2        Y       25      26      "VG"
            Dim ReceiverID As String           ' C2        Y       27      28      "EP"
            Dim Filler As String                ' C3        Y       29      31      Leerzeichen
        End Structure

        Structure Body                    ' Format    Muss    von     bis     Kommentar
            Dim SortField As String             ' N3        Y       1       3       "000"
            Dim RecordID As String              ' N2        Y       4       5       "50"
            Dim ISOCountryCode As String        ' N3        Y       6       8       "040" (Österreich)
            Dim CardNumber As String            ' C22       Y       9       30      Komplette Tankkartennummer
            'onlyBlacklist
            Dim StopType As String               ' N1        Y       31      31      "3" Stopped for Post-Pay
            'only Whitelist
            Dim ValidFrom As String            ' N8        Y       31      38      YYYYMMDD
            Dim ValidTo As String                ' N8        Y       39      46      YYYYMMDD
            Dim NewCardNumber As String        ' N22       N       47      68      Tankkartennummer der Folge- oder Ersatzkarte
            Dim NewValidFrom As String           ' N8        N       69      76      YYYYMMDD der Folge- oder Ersatzkarte
            Dim NewValidTo As String
        End Structure

        Private Structure Trailer                 ' Format    Muss    von     bis     Kommentar
            Dim SortField As String             ' N3        Y       1       3       "999"
            Dim RecordID As String              ' N2        Y       4       5       "99"
            Dim FileName As String              ' C3        Y       6       8       "TBL"
            Dim RunNumber As String             ' N3        Y       9       11      Gleiche Nr. wie im Header
            Dim RecordCount As String            ' N7        Y       12      18      Anzahl der Sätze inkl. Header und Trailer
            Dim Filler As String                ' C13       Y       19      31      Leerzeichen
        End Structure


        Dim VERARBEITUNG_PFAD, ARCHIV_PFAD, BEREITSTELLUNG_PFAD, ERROR_PFAD, FTP_PFAD_TEST, FTP_PFAD
        Dim sw As StreamWriter
        Dim Dateiname = ""

        Public Function initExportPfade()

            ERROR_PFAD = cAsfinag.Paramter.GET_PARAM_ByName("ERROR_PFAD", VERAG_PROG_ALLGEMEIN.cAllgemein.TESTSYSTEM)
            BEREITSTELLUNG_PFAD = cAsfinag.Paramter.GET_PARAM_ByName("BEREITSTELLUNG_PFAD", VERAG_PROG_ALLGEMEIN.cAllgemein.TESTSYSTEM)
            ARCHIV_PFAD = cAsfinag.Paramter.GET_PARAM_ByName("ARCHIV_PFAD", VERAG_PROG_ALLGEMEIN.cAllgemein.TESTSYSTEM)
            VERARBEITUNG_PFAD = cAsfinag.Paramter.GET_PARAM_ByName("VERARBEITUNG_PFAD", VERAG_PROG_ALLGEMEIN.cAllgemein.TESTSYSTEM)
            FTP_PFAD_TEST = cAsfinag.Paramter.GET_PARAM_ByName("SERVER_Path_Out_Test", VERAG_PROG_ALLGEMEIN.cAllgemein.TESTSYSTEM)
            FTP_PFAD = cAsfinag.Paramter.GET_PARAM_ByName("SERVER_Path_Out", VERAG_PROG_ALLGEMEIN.cAllgemein.TESTSYSTEM)

            If Not System.IO.Directory.Exists(VERARBEITUNG_PFAD) Then System.IO.Directory.CreateDirectory(VERARBEITUNG_PFAD)
            'If Not IO.Directory.Exists(FTP_PFAD_TEST) Then IO.Directory.CreateDirectory(FTP_PFAD_TEST)

        End Function


        Public Function exportiereBlackList(Optional autoclose As Boolean = False) As Boolean

            Dim fileName = "TBL"
            Dim sucess = False
            Dim Header As Header
            Dim Body As Body
            Dim Trailer As Trailer
            Dim intRunNumber As Integer = 1
            Dim lngAnzahlSätze As Long


            Dim SQL As New VERAG_PROG_ALLGEMEIN.SQL
            'qryExportiereBlackList
            ' DO NOT WORK ON SQL2008 SERVER
            'Dim sqlstr As String = "
            'SELECT Kreditkarten.KartenNr AS CardNumber, Kreditkarten.Kartensperre AS StopType FROM Kreditkarten 
            'LEFT JOIN Kreditkarten AS Kreditkarten_1 ON Kreditkarten.NeueKartenNr = Kreditkarten_1.KartenNr 
            'WHERE Kreditkarten.Kartensperre > 0
            'AND ((Kreditkarten.Kartensperrdatum)<=GETDATE()) 
            'AND ((Left([Kreditkarten].[KartenNr],6))='990001') 
            'AND [Kreditkarten].[Kartenfreischaltungsdatum] <= GETDATE() 
            'And [Kreditkarten].[Kartenfreischaltungsdatum] <> '' 
            'AND DateAdd(DAY, -1, DateAdd(MONTH,1,DATEFROMPARTS(2000 + [Kreditkarten].[Kartenablaufjahr],[Kreditkarten].[Kartenablaufmonat],1))) >= GETDATE()
            'AND DateAdd(DAY, -1, DateAdd(MONTH,1,DATEFROMPARTS(2000 + [Kreditkarten].[Kartenablaufjahr],[Kreditkarten].[Kartenablaufmonat],1))) <> ''
            'AND (Kreditkarten_1.Kartenfreischaltungsdatum) Is Null Or (Kreditkarten_1.Kartenfreischaltungsdatum) > GETDATE() 
            'ORDER BY Kreditkarten.KartenNr"

            'WORK ON SQL 2008
            Dim sqlstr As String = "
            Select Kreditkarten.KartenNr As CardNumber, Kreditkarten.Kartensperre As StopType FROM Kreditkarten 
            Left Join Kreditkarten AS Kreditkarten_1 ON Kreditkarten.NeueKartenNr = Kreditkarten_1.KartenNr 
            WHERE Kreditkarten.Kartensperre > 0
            And ((Kreditkarten.Kartensperrdatum)<=GETDATE()) 
            And ((Left([Kreditkarten].[KartenNr],6))='990001') 
            And [Kreditkarten].[Kartenfreischaltungsdatum] <= GETDATE() 
            And [Kreditkarten].[Kartenfreischaltungsdatum] <> '' 
            And DateAdd(DAY, -1, DateAdd(MONTH,1,CAST(CONVERT(VARCHAR,2000 + [Kreditkarten].[Kartenablaufjahr])+ '-' + CONVERT(VARCHAR,[Kreditkarten].[Kartenablaufmonat]) + '-' + CONVERT(VARCHAR,1) AS DATETIME))) >= GETDATE()
            And DateAdd(DAY, -1, DateAdd(MONTH,1,CAST(CONVERT(VARCHAR,2000 + [Kreditkarten].[Kartenablaufjahr])+ '-' + CONVERT(VARCHAR,[Kreditkarten].[Kartenablaufmonat])+ '-' + CONVERT(VARCHAR,1) AS DATETIME))) <> ''
            And (Kreditkarten_1.Kartenfreischaltungsdatum) Is Null Or (Kreditkarten_1.Kartenfreischaltungsdatum) > GETDATE() 
            ORDER BY Kreditkarten.KartenNr"


            Dim dt As DataTable = SQL.loadDgvBySql_Param(sqlstr, "FMZOLL")
            'qry_ASFINAG_FileInfo_TBL
            Dim currentFileNr As Integer
            currentFileNr = SQL.getValueTxtBySql("SELECT fileVersion FROM [FileINfo]  where [filename]='" & fileName & "'", "ASFINAG")
            If currentFileNr = 999 Then currentFileNr = 0
            currentFileNr = currentFileNr + 1
            Dim preFilename As String = ""
            If Not VERAG_PROG_ALLGEMEIN.cAllgemein.TESTSYSTEM Then
                preFilename = "LVGEP"
            Else
                preFilename = "TVGEP"
            End If

            Dim strFile As String = BEREITSTELLUNG_PFAD & "\" & preFilename & fileName & "." & Format(currentFileNr, "000")

            Try


                'Dim fileExists As Boolean = File.Exists(ASFINAG_PFAD & "\" & strFile)

                Using sw As New StreamWriter(File.Open(strFile, FileMode.OpenOrCreate))

                    With Header
                        .SortField = "000"
                        .RecordID = "00"
                        .FileName = fileName
                        .LiveTestIndicator = IIf(VERAG_PROG_ALLGEMEIN.cAllgemein.TESTSYSTEM, "T", "L")  'T für Testfile, L Livesystem
                        .FileCreationDate = Today.ToString("yyyyMMdd", CultureInfo.CurrentCulture)
                        .FileCreationTime = Now().ToString("HHmm", CultureInfo.CurrentCulture)
                        .RunNumber = Format(currentFileNr, "000")
                        .SenderID = "VG"
                        .ReceiverID = "EP"
                        .Filler = New String(" ", 3)
                        sw.Write(Header.SortField)
                        sw.Write(Header.RecordID)
                        sw.Write(Header.FileName)
                        sw.Write(Header.LiveTestIndicator)
                        sw.Write(Header.FileCreationDate)
                        sw.Write(Header.FileCreationTime)
                        sw.Write(Header.RunNumber)
                        sw.Write(Header.SenderID)
                        sw.Write(Header.ReceiverID)
                        sw.Write(Header.Filler)
                        sw.WriteLine()
                    End With

                    lngAnzahlSätze = 1
                    For Each row As DataRow In dt.Rows

                        lngAnzahlSätze = lngAnzahlSätze + 1
                        With Body
                            .SortField = "000"
                            .RecordID = "50"
                            .ISOCountryCode = "040"
                            .CardNumber = row.Item("CardNumber") + New String(" ", 22 - Len(row.Item("CardNumber")))
                            .StopType = row.Item("StopType")
                            sw.Write(Body.SortField)
                            sw.Write(Body.RecordID)
                            sw.Write(Body.ISOCountryCode)
                            sw.Write(Body.CardNumber)
                            sw.Write(Body.StopType)
                            sw.WriteLine()
                        End With
                    Next

                    lngAnzahlSätze = lngAnzahlSätze + 1
                    With Trailer
                        .SortField = "999"
                        .RecordID = "99"
                        .FileName = fileName
                        .RunNumber = Format(currentFileNr, "000")
                        .RecordCount = Format(lngAnzahlSätze, "0000000")
                        .Filler = New String(" ", 13)
                        sw.Write(Trailer.SortField)
                        sw.Write(Trailer.RecordID)
                        sw.Write(Trailer.FileName)
                        sw.Write(Trailer.RunNumber)
                        sw.Write(Trailer.RecordCount)
                        sw.Write(Trailer.Filler)
                        sw.WriteLine()
                    End With
                    sw.Close()

                    SQL.doSQL("UPDATE [dbo].[FileINfo] SET FileVersion=" & currentFileNr & " WHERE [filename]='" & fileName & "'", "ASFINAG")
                    If autoclose Then
                        uploadListToFTP(fileName)
                    Else
                        MsgBox("Files uploaded: " & uploadListToFTP(fileName))
                    End If

                    Return True

                End Using
            Catch ex As Exception
                VERAG_PROG_ALLGEMEIN.cErrorHandler.ERR(ex.Message, ex.StackTrace & vbNewLine & "Datei: " & Dateiname, System.Reflection.MethodInfo.GetCurrentMethod.Name)
            End Try

        End Function

        Public Function exportiereWhiteList(Optional autoclose As Boolean = False) As Boolean

            Dim fileName = "TWL"
            Dim sucess = False
            Dim Header As Header
            Dim Body As Body
            Dim Trailer As Trailer
            Dim intRunNumber As Integer = 1
            Dim lngAnzahlSätze As Long


            Dim SQL As New VERAG_PROG_ALLGEMEIN.SQL
            'qryExportiereWhiteList

            ' DOES NOT WORK WITH SQL2008!!!!
            'Dim sqlstr As String = "
            '    SELECT Kreditkarten.KartenNr AS CardNumber, 
            '    CONVERT(varchar, [Kreditkarten].[Kartenfreischaltungsdatum],112) AS ValidFrom, 
            '    CONVERT(varchar,DateAdd(DAY, -1, DateAdd(MONTH,1,DATEFROMPARTS(2000 + [Kreditkarten].[Kartenablaufjahr],[Kreditkarten].[Kartenablaufmonat],1))),112) AS ValidTo, 
            '    Kreditkarten_1.KartenNr AS NewCardNumber, 
            '    IIf(Not IsNull(Kreditkarten_1.KartenNr,0) <> 0 ,CONVERT(varchar,[Kreditkarten_1].[Kartenfreischaltungsdatum],112),'') AS NewValidFrom, 
            '    IIf(Not IsNull(Kreditkarten_1.KartenNr,0) <> 0,CONVERT(varchar, DateAdd(DAY, -1, DateAdd(MONTH,1,DATEFROMPARTS(2000 + [Kreditkarten].[Kartenablaufjahr],[Kreditkarten].[Kartenablaufmonat],1))),112),'') AS NewValidTo,
            '     Kreditkarten.NeueKartenNrGemeldet
            '    FROM Kreditkarten AS Kreditkarten_1 
            '    RIGHT JOIN Kreditkarten ON Kreditkarten_1.KartenNr = Kreditkarten.NeueKartenNr
            '    WHERE (([Kreditkarten].[Kartenfreischaltungsdatum])<= GETDATE() And ([Kreditkarten].[Kartenfreischaltungsdatum] <>'') 
            '    AND DateAdd(DAY, -1, DateAdd(MONTH,1,DATEFROMPARTS(2000 + [Kreditkarten].[Kartenablaufjahr],[Kreditkarten].[Kartenablaufmonat],1))) >= GETDATE()
            '    AND ((Kreditkarten_1.KartenNr) Is Null)) OR (((Kreditkarten_1.KartenNr) Is Not Null) AND ((Kreditkarten.NeueKartenNrGemeldet)= 0))
            '    ORDER BY Kreditkarten.KartenNr, [Kreditkarten].[Kartenfreischaltungsdatum], CONVERT(varchar, DateAdd(DAY, -1, DateAdd(MONTH,1,DATEFROMPARTS(2000 + [Kreditkarten].[Kartenablaufjahr],[Kreditkarten].[Kartenablaufmonat],1))))
            '    "

            ' WORKS WITH SQL2008!!!!
            Dim sqlstr As String = "
            Select Kreditkarten.KartenNr As CardNumber, 
                Convert(varchar, [Kreditkarten].[Kartenfreischaltungsdatum], 112) As ValidFrom, 
                Convert(varchar, DateAdd(Day, -1, DateAdd(Month, 1, CAST(Convert(VARCHAR, 2000 + [Kreditkarten].[Kartenablaufjahr]) + '-' + CONVERT(VARCHAR,[Kreditkarten].[Kartenablaufmonat]) + '-' + CONVERT(VARCHAR,1) AS Datetime))),112) as ValidTo, 
                Kreditkarten_1.KartenNr As NewCardNumber, 
                Case when IsNull(Kreditkarten_1.KartenNr,0) = 0 THEN CONVERT(varchar,[Kreditkarten_1].[Kartenfreischaltungsdatum],112) ELSE '' END AS NewValidFrom,
				Case when IsNull(Kreditkarten_1.KartenNr,0) <> 0 THEN '' ELSE CONVERT(varchar, DateAdd(DAY, -1, DateAdd(MONTH,1,CAST(CONVERT(VARCHAR,2000 + [Kreditkarten].[Kartenablaufjahr]) + '-' + CONVERT(VARCHAR,[Kreditkarten].[Kartenablaufmonat]) + '-' + CONVERT(VARCHAR,1)AS DATETIME))), 112) END AS NewValidTo,
                 Kreditkarten.NeueKartenNrGemeldet
                    From Kreditkarten As Kreditkarten_1 
                Right Join Kreditkarten ON Kreditkarten_1.KartenNr = Kreditkarten.NeueKartenNr
                WHERE(([Kreditkarten].[Kartenfreischaltungsdatum]) <= GETDATE()) And ([Kreditkarten].[Kartenfreischaltungsdatum] <>'') 
                And DateAdd(DAY, -1, DateAdd(MONTH,1,CAST(CONVERT(VARCHAR,2000 + [Kreditkarten].[Kartenablaufjahr]) + '-' + CONVERT(VARCHAR,[Kreditkarten].[Kartenablaufmonat]) + '-' + CONVERT(VARCHAR,1) as datetime))) >= GETDATE()
                And (Kreditkarten_1.KartenNr Is Null) Or (Kreditkarten_1.KartenNr Is Not Null) And ((Kreditkarten.NeueKartenNrGemeldet)= 0)
                ORDER BY Kreditkarten.KartenNr, [Kreditkarten].[Kartenfreischaltungsdatum], Convert(varchar, DateAdd(Day, -1, DateAdd(Month, 1, CAST(Convert(VARCHAR, 2000 + [Kreditkarten].[Kartenablaufjahr]) + '-' + CONVERT(VARCHAR,[Kreditkarten].[Kartenablaufmonat]) + '-' + CONVERT(VARCHAR,1) AS datetime))), 112)"


            Dim dt As DataTable = SQL.loadDgvBySql_Param(sqlstr, "FMZOLL")
            'qry_ASFINAG_FileInfo_TWL
            Dim currentFileNr As Integer
            currentFileNr = SQL.getValueTxtBySql("SELECT fileVersion FROM [FileINfo]  where [filename]='" & fileName & "'", "ASFINAG")
            If currentFileNr = 999 Then currentFileNr = 0
            currentFileNr = currentFileNr + 1
            Dim preFilename As String = ""
            If Not VERAG_PROG_ALLGEMEIN.cAllgemein.TESTSYSTEM Then
                preFilename = "LVGEP"
            Else
                preFilename = "TVGEP"
            End If

            Dim strFile As String = BEREITSTELLUNG_PFAD & "\" & preFilename & fileName & "." & Format(currentFileNr, "000")

            Try


                Using sw As New StreamWriter(File.Open(strFile, FileMode.OpenOrCreate))


                    With Header
                        .SortField = "000"
                        .RecordID = "00"
                        .FileName = fileName
                        .LiveTestIndicator = IIf(VERAG_PROG_ALLGEMEIN.cAllgemein.TESTSYSTEM, "T", "L") 'T für Testfile, L Livesystem
                        .FileCreationDate = Today.ToString("yyyyMMdd", CultureInfo.CurrentCulture)
                        .FileCreationTime = Now().ToString("HHmm", CultureInfo.CurrentCulture)
                        .RunNumber = Format(currentFileNr, "000")
                        .SenderID = "VG"
                        .ReceiverID = "EP"
                        .Filler = New String(" ", 56)
                        sw.Write(Header.SortField)
                        sw.Write(Header.RecordID)
                        sw.Write(Header.FileName)
                        sw.Write(Header.LiveTestIndicator)
                        sw.Write(Header.FileCreationDate)
                        sw.Write(Header.FileCreationTime)
                        sw.Write(Header.RunNumber)
                        sw.Write(Header.SenderID)
                        sw.Write(Header.ReceiverID)
                        sw.Write(Header.Filler)
                        sw.WriteLine()
                    End With

                    lngAnzahlSätze = 1
                    For Each row As DataRow In dt.Rows
                        With Body
                            If Not IsDBNull(row.Item("NewCardNumber")) Then
                                If Not row.Item("NeueKartenNrGemeldet") Then
                                    lngAnzahlSätze = lngAnzahlSätze + 1
                                    .SortField = "000"
                                    .RecordID = "40"
                                    .ISOCountryCode = "040"
                                    .CardNumber = row.Item("CardNumber") + New String(" ", 22 - Len(row.Item("CardNumber")))
                                    .ValidFrom = row.Item("ValidFrom")
                                    .ValidTo = row.Item("ValidTo")
                                    .NewCardNumber = row.Item("NewCardNumber") + New String(" ", 22 - Len(row.Item("NewCardNumber")))
                                    .NewValidFrom = row.Item("NewValidFrom")
                                    .NewValidTo = row.Item("NewValidTo")
                                    sw.Write(.SortField)
                                    sw.Write(.RecordID)
                                    sw.Write(.ISOCountryCode)
                                    sw.Write(.CardNumber)
                                    sw.Write(.ValidFrom)
                                    sw.Write(.ValidTo)
                                    sw.Write(.NewCardNumber)
                                    sw.Write(.NewValidFrom)
                                    sw.Write(.NewValidTo)
                                    sw.WriteLine()
                                    row.Item("NeueKartenNrGemeldet") = True
                                End If
                            Else
                                lngAnzahlSätze = lngAnzahlSätze + 1
                                .SortField = "000"
                                .RecordID = "40"
                                .ISOCountryCode = "040"
                                .CardNumber = row.Item("CardNumber") + New String(" ", 22 - Len(row.Item("CardNumber")))
                                .ValidFrom = row.Item("ValidFrom")
                                .ValidTo = row.Item("ValidTo")
                                .NewCardNumber = "0000000000000000000000"
                                .NewValidFrom = "00000000"
                                .NewValidTo = "00000000"
                                sw.Write(.SortField)
                                sw.Write(.RecordID)
                                sw.Write(.ISOCountryCode)
                                sw.Write(.CardNumber)
                                sw.Write(.ValidFrom)
                                sw.Write(.ValidTo)
                                sw.Write(.NewCardNumber)
                                sw.Write(.NewValidFrom)
                                sw.Write(.NewValidTo)
                                sw.WriteLine()
                            End If
                        End With
                    Next

                    lngAnzahlSätze = lngAnzahlSätze + 1
                    With Trailer
                        .SortField = "999"
                        .RecordID = "99"
                        .FileName = fileName
                        .RunNumber = Format(currentFileNr, "000")
                        .RecordCount = Format(lngAnzahlSätze, "0000000")
                        .Filler = New String(" ", 66)
                        sw.Write(Trailer.SortField)
                        sw.Write(Trailer.RecordID)
                        sw.Write(Trailer.FileName)
                        sw.Write(Trailer.RunNumber)
                        sw.Write(Trailer.RecordCount)
                        sw.Write(Trailer.Filler)
                        sw.WriteLine()
                    End With
                    sw.Close()


                    SQL.doSQL("UPDATE [dbo].[FileINfo] SET FileVersion=" & currentFileNr & " WHERE [filename]='" & fileName & "'", "ASFINAG")

                    If autoclose Then
                        uploadListToFTP(fileName)
                    Else
                        MsgBox("Files uploaded: " & uploadListToFTP(fileName))
                    End If

                    Return True

                End Using
            Catch ex As Exception
                VERAG_PROG_ALLGEMEIN.cErrorHandler.ERR(ex.Message, ex.StackTrace & vbNewLine & "Datei: " & Dateiname, System.Reflection.MethodInfo.GetCurrentMethod.Name)
            End Try

        End Function

        Public Function uploadListToFTP(filename As String) As Integer

            Dim cnt = 0
            Try
                Dim SERVER_Path = ""

                If VERAG_PROG_ALLGEMEIN.cAllgemein.TESTSYSTEM Then

                    SERVER_Path = FTP_PFAD_TEST
                Else

                    SERVER_Path = FTP_PFAD
                End If

                For Each f In System.IO.Directory.GetFiles(BEREITSTELLUNG_PFAD)
                    Dim fi As New System.IO.FileInfo(f)

                    If Not fi.Name.StartsWith(".") AndAlso fi.Name.Contains(filename) Then
                        Dim zielPfad = SERVER_Path
                        'While IO.File.Exists(zielPfad)
                        '    zielPfad = SERVER_Path & "\" & Now.ToString("yyyyMMdd_HHmmss_") & fi.Name
                        'End While
                        System.IO.File.Copy(f, zielPfad & "\" & fi.Name, True)
                        If System.IO.File.Exists(zielPfad & "\" & fi.Name) Then

                            If Not System.IO.Directory.Exists(ARCHIV_PFAD & "\" & Now.Year & "\" & filename & "\") Then System.IO.Directory.CreateDirectory(ARCHIV_PFAD & "\" & Now.Year & "\" & filename & "\")
                            System.IO.File.Move(BEREITSTELLUNG_PFAD & "\" & fi.Name, ARCHIV_PFAD & "\" & Now.Year & "\" & filename & "\" & fi.Name)
                            If filename = "TWL" Then whiteListExported = True
                            If filename = "TBL" Then blacklisteExported = True
                        End If
                        cnt += 1
                    End If

                Next

                For Each f In System.IO.Directory.GetFiles(SERVER_Path)
                    Dim fi As New System.IO.FileInfo(f)
                    If fi.Name.ToUpper.Contains("DO_NOT_DELETE") AndAlso whiteListExported AndAlso blacklisteExported Then
                        System.IO.File.SetLastWriteTime(fi.FullName, Now())
                    End If
                Next


                Return cnt

            Catch ex As Exception
                VERAG_PROG_ALLGEMEIN.cErrorHandler.ERR(ex.Message, ex.StackTrace & vbNewLine & "Datei: " & Dateiname, System.Reflection.MethodInfo.GetCurrentMethod.Name)
            End Try

            Return cnt


        End Function



    End Class

    Public VERARBEITUNG_PFAD
    Public ARCHIV_PFAD
    Public BEREITSTELLUNG_PFAD
    Public ERROR_PFAD
    Public FTP_PFAD_TEST
    Public FTP_PFAD
    Dim Dateiname = ""

    Public Function initImportPfade()

        ERROR_PFAD = cAsfinag.Paramter.GET_PARAM_ByName("ERROR_PFAD", VERAG_PROG_ALLGEMEIN.cAllgemein.TESTSYSTEM)
        BEREITSTELLUNG_PFAD = cAsfinag.Paramter.GET_PARAM_ByName("BEREITSTELLUNG_PFAD", VERAG_PROG_ALLGEMEIN.cAllgemein.TESTSYSTEM)
        ARCHIV_PFAD = cAsfinag.Paramter.GET_PARAM_ByName("ARCHIV_PFAD", VERAG_PROG_ALLGEMEIN.cAllgemein.TESTSYSTEM)
        VERARBEITUNG_PFAD = cAsfinag.Paramter.GET_PARAM_ByName("VERARBEITUNG_PFAD", VERAG_PROG_ALLGEMEIN.cAllgemein.TESTSYSTEM)
        FTP_PFAD_TEST = cAsfinag.Paramter.GET_PARAM_ByName("SERVER_Path_In_Test", VERAG_PROG_ALLGEMEIN.cAllgemein.TESTSYSTEM)
        FTP_PFAD = cAsfinag.Paramter.GET_PARAM_ByName("SERVER_Path_In", VERAG_PROG_ALLGEMEIN.cAllgemein.TESTSYSTEM)

        If Not System.IO.Directory.Exists(VERARBEITUNG_PFAD) Then System.IO.Directory.CreateDirectory(VERARBEITUNG_PFAD)

    End Function

    Function getNachrichtenDatenFromFTP(ByRef filenameList As List(Of String), ByVal fileType As String, ByRef testFTP As Boolean) As Integer
        Dim cnt = 0
        Try
            Dim SERVERPath = ""

            If testFTP Then

                SERVERPath = Me.FTP_PFAD_TEST
            Else

                SERVERPath = Me.FTP_PFAD
            End If

            Dim catchedFiles As Boolean = False
            For Each f In System.IO.Directory.GetFiles(SERVERPath)
                Dim fi As New System.IO.FileInfo(f)
                If fi.Name.ToUpper.Contains(fileType) Then
                    If Not fi.Name.StartsWith(".") Then
                        Dim zielPfad = VERARBEITUNG_PFAD & "\" & fi.Name
                        While System.IO.File.Exists(zielPfad)
                            zielPfad = VERARBEITUNG_PFAD & "\" & "DOPPELT" & "\" & fi.Name.Replace(fi.Extension, "") & fi.Extension & Now.ToString("_yyyyMMdd_HHmmss")
                        End While
                        System.IO.File.Copy(f, zielPfad)

                        If System.IO.File.Exists(zielPfad) Then
                            System.IO.File.Delete(f)
                            catchedFiles = True
                        End If

                        Dim filename = frmStartOptions.cut_file((New FileInfo(zielPfad)).Name)
                        If filename.ToUpper.Contains(fileType) Then
                            filenameList.Add(filename)
                            cnt += 1
                        End If

                    End If
                End If

            Next

            ' zur prüfung ob Daten von uns abgeholt wurden bzw. ob Daten von Asfingag bereitgestellt wurden
            For Each f In System.IO.Directory.GetFiles(SERVERPath)
                Dim fi As New System.IO.FileInfo(f)
                If fi.Name.ToUpper.Contains("DO_NOT_DELETE") AndAlso catchedFiles Then
                    System.IO.File.SetLastWriteTime(fi.FullName, Now())
                End If
            Next


            Return cnt

        Catch ex As Exception
            VERAG_PROG_ALLGEMEIN.cErrorHandler.ERR(ex.Message, ex.StackTrace & vbNewLine & "Datei: " & Dateiname, System.Reflection.MethodInfo.GetCurrentMethod.Name)
        End Try

        Return cnt
    End Function

    Public Function readAndSaveCLF(objFileRead As StreamReader, fi As FileInfo) As Boolean



        Dim booHeaderVorhanden = False
        Dim booPrüfziffernfehler = False
        Dim booInTransaktion = False
        Dim booTrailerVorhanden = False

        Dim lngRecordCount As Long

        'Datei auf Fehler prüfen!
        Do While (objFileRead.Peek() > -1)
            Dim strZeile = objFileRead.ReadLine()
            lngRecordCount = lngRecordCount + 1

            Select Case Mid(strZeile, 1, 2)
                Case "10"
                    booHeaderVorhanden = True
                Case "20"
                    ' Meldung bei nicht vorhandenen Haeder.
                    If Not booHeaderVorhanden Then
                        MsgBox("Datei kann wegen fehlenden Header nicht verarbeitet werden.")
                        objFileRead.Close()
                        Return False
                    End If

                    'CardNumber prüfen.
                    If (Right(Trim(Mid(strZeile, 9, 22)), 1)) <> cAsfinag.fktMod10Prüfziffer(Left(Trim(Mid(strZeile, 9, 22)), Len(Trim(Mid(strZeile, 9, 22))) - 1)) Then
                        booPrüfziffernfehler = True
                    End If

                    ' Meldung bei Prüfziffernfehler.
                    If booPrüfziffernfehler Then
                        MsgBox("Prüfziffernfehler in Zeile " & CStr(lngRecordCount) & vbCrLf & "Datei kann nicht verarbeitet werden. " & vbNewLine & " " & fi.Name.ToString)
                        booInTransaktion = False
                        objFileRead.Close()
                        Return False

                    End If
                Case "90"
                    ' Meldung bei nicht vorhandenen Haeder.
                    If Not booHeaderVorhanden Then
                        MsgBox("Datei kann wegen fehlenden Header nicht verarbeitet werden.")
                        objFileRead.Close()
                        Return False
                    End If

                    booTrailerVorhanden = True
                    Dim clfTrailer As New cAsfinag.CLFTrailer(fi.Name)

                    ' Prüfsumme Anzahl der Sätze im File ohne Header und Trailer.
                    If Trim(Mid(strZeile, 9, 7)) <> (lngRecordCount) Then
                        MsgBox("Fehler: " & vbNewLine & "Prüfsumme in der Datei stimmt nicht mit der Zeilenanzahl der Datei überein! " & vbNewLine & "Record Count:  " & Trim(Mid(strZeile, 9, 7)) & vbCrLf & "Prüfsumme: " & (lngRecordCount) & vbCrLf)
                        objFileRead.Close()
                        Return False
                    End If


                    ' Meldung bei Prüfsummenfehler.
                    If booPrüfziffernfehler Then
                        MsgBox("Datei kann wegen Prüfsummenfehler nicht verarbeitet werden.")
                        objFileRead.Close()

                    End If
                Case Else

            End Select

        Loop


        Dim lngPKLine As Long = 0
        lngRecordCount = 0

        'gleicher PKFileName wird nun aus CLFHeader gelöscht. CASCADE löscht dann zugehörige CLFBody und CLFTrailer.
        If Not SQL.doSQL("delete FROM CLFHeader WHERE (PKHistory = 0) AND (PKFileName = N'" & fi.Name.ToString & "')", "ASFINAG") Then
            MsgBox("Fehler beim Löschen des CLF-Headers")
            objFileRead.Close()
            Return False
        End If

        If Not SQL.doSQL("UPDATE CLF SET PKFileName = '" & fi.Name.ToString & "'", "ASFINAG") Then
            MsgBox("Fehler beim Update der CLF-Nr")
            objFileRead.Close()
            Return False
        End If
        objFileRead.DiscardBufferedData()
        objFileRead.BaseStream.Seek(0, System.IO.SeekOrigin.Begin)

        Do While (objFileRead.Peek() > -1)
            Dim strZeile = objFileRead.ReadLine()
            lngRecordCount = lngRecordCount + 1

            Select Case Mid(strZeile, 1, 2)
                Case "10"
                    booHeaderVorhanden = True
                    Dim ext = CInt(fi.Extension.Remove(0, 1))
                    Dim clfHeader As New cAsfinag.CLFHeader(fi.Name.ToString, ext)
                    With clfHeader
                        .PKFileName = fi.Name
                        .recordType = Mid(strZeile, 1, 2)
                        .fileVersion = Mid(strZeile, 3, 2)
                        .indcator = Trim(Mid(strZeile, 9, 1))
                        .senderID = Trim(Mid(strZeile, 10, 6))
                        .receiverID = Trim(Mid(strZeile, 16, 6))
                        .fileCreationDate = DateSerial(Mid(strZeile, 22, 4), Mid(strZeile, 26, 2), Mid(strZeile, 28, 2))
                        .fileCreationTime = DateSerial(Mid(strZeile, 22, 4), Mid(strZeile, 26, 2), Mid(strZeile, 28, 2)) & " " & TimeSerial(Mid(strZeile, 30, 2), Mid(strZeile, 32, 2), 0)
                        '.fileCreationTime = DateSerial(Mid(strZeile, 22, 4), Mid(strZeile, 26, 2), Mid(strZeile, 28, 2)) & " " & TimeSerial(Mid(strZeile, 30, 2), Mid(strZeile, 32, 2), Mid(strZeile, 34, 2))
                        .ISOCountryCode = Trim(Mid(strZeile, 62, 3))
                        .SAVE()
                    End With

                Case "20"

                    Dim clfBody As New cAsfinag.CLFBody(fi.Name, lngPKLine)
                    With clfBody
                        .PKFileName = fi.Name
                        lngPKLine = lngPKLine + 1
                        .RecordType = Trim(Mid(strZeile, 1, 2))
                        .fileVersion = Trim(Mid(strZeile, 3, 2))
                        .fileNumber = Trim(Mid(strZeile, 5, 3))
                        .cardNumber = Trim(Mid(strZeile, 9, 22))
                        .validTo = Trim(Mid(strZeile, 31, 4))
                        .OBUID = Trim(Mid(strZeile, 35, 18))
                        .vehicleLicensePlate = Trim(Mid(strZeile, 53, 10))
                        .nationality = Trim(Mid(strZeile, 63, 3))
                        .vehicleCategory = Trim(Mid(strZeile, 66, 1))
                        .emissionCategory = Trim(Mid(strZeile, 67, 2))
                        .status = Trim(Mid(strZeile, 69, 2))
                        .contractDate = DateSerial(Mid(strZeile, 71, 4), Mid(strZeile, 75, 2), Mid(strZeile, 77, 2))
                        .engineCharacteristics = Trim(Mid(strZeile, 79, 3))
                        .CO2EmissionsClass = Trim(Mid(strZeile, 82, 1))
                        .contractType = Trim(Mid(strZeile, 83, 1))
                        .SAVE()
                    End With



                    Dim strSQLASFINAG = "SELECT * FROM CLFArchiv WHERE OBUID = N'" & Trim(Mid(strZeile, 35, 18)) & "'"

                    Dim dtAsfinag As DataTable = SQL.loadDgvBySql_Param(strSQLASFINAG, "ASFINAG")

                    Dim clfArchiv As New cAsfinag.CLFArchiv(Trim(Mid(strZeile, 35, 18)))

                    'Dim clfArchiv As New cAsfinag.CLFArchiv(fi.Name, Trim(Mid(strZeile, 35, 18)))

                    'If dtAsfinag.Rows.Count = 0 Then
                    With clfArchiv
                        .PKFileName = fi.Name
                        .RecordType = Trim(Mid(strZeile, 1, 2))
                        .fileVersion = Trim(Mid(strZeile, 3, 2))
                        .fileNumber = Trim(Mid(strZeile, 5, 3))
                        .cardNumber = Trim(Mid(strZeile, 9, 22))
                        .validTo = Trim(Mid(strZeile, 31, 4))
                        '.OBUID = Trim(Mid(strZeile, 35, 18))
                        .vehicleLicensePlate = Trim(Mid(strZeile, 53, 10))
                        .nationality = Trim(Mid(strZeile, 63, 3))
                        .vehicleCategory = Trim(Mid(strZeile, 66, 1))
                        .emissionCategory = Trim(Mid(strZeile, 67, 2))
                        .status = Trim(Mid(strZeile, 69, 2))
                        .contractDate = DateSerial(Mid(strZeile, 71, 4), Mid(strZeile, 75, 2), Mid(strZeile, 77, 2))
                        .engineCharacteristics = Trim(Mid(strZeile, 79, 3))
                        .CO2EmissionsClass = Trim(Mid(strZeile, 82, 1))
                        .contractType = Trim(Mid(strZeile, 83, 1))
                        .SAVE()
                    End With
                        'End If

                    '    For Each r As DataRow In dtAsfinag.Rows

                    '    clfArchiv = New cAsfinag.CLFArchiv(r.Item("PKFileName"), r.Item("OBUID"))

                    '    With clfArchiv
                    '        .PKFileName = fi.Name
                    '        .RecordType = Trim(Mid(strZeile, 1, 2))
                    '        .fileVersion = Trim(Mid(strZeile, 3, 2))
                    '        .fileNumber = Trim(Mid(strZeile, 5, 3))
                    '        .cardNumber = Trim(Mid(strZeile, 9, 22))
                    '        .validTo = Trim(Mid(strZeile, 31, 4))
                    '        .OBUID = Trim(Mid(strZeile, 35, 18))
                    '        .vehicleLicensePlate = Trim(Mid(strZeile, 53, 10))
                    '        .nationality = Trim(Mid(strZeile, 63, 3))
                    '        .vehicleCategory = Trim(Mid(strZeile, 66, 1))
                    '        .emissionCategory = Trim(Mid(strZeile, 67, 2))
                    '        .status = Trim(Mid(strZeile, 69, 2))
                    '        .contractDate = DateSerial(Mid(strZeile, 71, 4), Mid(strZeile, 75, 2), Mid(strZeile, 77, 2))
                    '        .engineCharacteristics = Trim(Mid(strZeile, 79, 3))
                    '        .CO2EmissionsClass = Trim(Mid(strZeile, 82, 1))
                    '        .contractType = Trim(Mid(strZeile, 83, 1))
                    '        .SAVE()
                    '    End With
                    'Next


                Case "90"

                    Dim clfTrailer As New cAsfinag.CLFTrailer(fi.Name)

                    With clfTrailer
                        .PKFileName = fi.Name
                        .recordType = Trim(Mid(strZeile, 1, 2))
                        .fileVersion = Trim(Mid(strZeile, 3, 2))
                        .fileNumber = Trim(Mid(strZeile, 5, 4))
                        .recordCount = Trim(Mid(strZeile, 9, 7))
                        .SAVE()
                    End With



                Case Else
                    ' Andere RecordNumber überlesen.
            End Select

        Loop

        objFileRead.Close()

        Return True

    End Function

    Public Function readAndSaveTTR(objFileRead As StreamReader, fi As FileInfo) As Boolean

        Dim booHeaderVorhanden = False
        Dim booPrüfziffernfehler = False
        Dim booInTransaktion = False
        Dim booTrailerVorhanden = False
        Dim dblCheckSumQuantity As Double
        Dim curCheckSumAmount As Double

        Dim lngPKLine As Long = 0
        Dim lngRecordCount As Long

        Dim counTrans As Integer = 0
        Dim savedTrans As Integer = 0
        Dim MDMEinarb As New cMDMEinarbeitung("ASFINAG", Now(), Now())
        MDMEinarb.setInvoicingDate(Now(), MDMEinarb)


        'Datei auf Fehler prüfen
        Do While (objFileRead.Peek() > -1)
            Dim strZeile = objFileRead.ReadLine()
            lngRecordCount = lngRecordCount + 1

            Select Case Mid(strZeile, 1, 2)
                Case "10"
                    booHeaderVorhanden = True
                Case "20"
                    ' Meldung bei nicht vorhandenen Haeder.
                    If Not booHeaderVorhanden Then
                        MsgBox("Datei kann wegen fehlenden Header nicht verarbeitet werden.")
                        objFileRead.Close()
                        Return False
                    End If


                    ' Bei den Checksummen wird unabhängig vom TransactionType immer der positive Betrag aufsummiert.
                    dblCheckSumQuantity = dblCheckSumQuantity + Trim(Mid(strZeile, 94, 6)) / 100
                    curCheckSumAmount = curCheckSumAmount + Trim(Mid(strZeile, 100, 10)) / 100
                    If (Right(Trim(Mid(strZeile, 43, 22)), 1)) <> (fktMod10Prüfziffer(Left(Trim(Mid(strZeile, 43, 22)), Len(Trim(Mid(strZeile, 43, 22))) - 1))) Then
                        booPrüfziffernfehler = True
                    End If

                    ' Meldung bei Prüfziffernfehler.
                    If booPrüfziffernfehler Then
                        MsgBox("Prüfziffernfehler in Zeile " & CStr(lngRecordCount) & vbCrLf & "Datei kann nicht verarbeitet werden. " & vbNewLine & " " & fi.Name.ToString)
                        booInTransaktion = False
                        objFileRead.Close()
                        Return False
                    End If


                Case "90"
                    ' Meldung bei nicht vorhandenen Haeder.
                    If Not booHeaderVorhanden Then
                        MsgBox("Datei kann wegen fehlenden Header nicht verarbeitet werden.")
                        objFileRead.Close()
                        Return False
                    End If

                    booTrailerVorhanden = True

                    Dim strPrompt
                    Dim recordCount = Trim(Mid(strZeile, 5, 9))
                    If recordCount <> lngRecordCount Then
                        strPrompt = strPrompt & "Record Count: " & recordCount & vbCrLf &
                                "Prüfsumme: " & lngRecordCount & vbCrLf
                    End If
                    ' Prüfsumme Menge.
                    Dim checksumProductQuantity = Trim(Mid(strZeile, 14, 15)) / 100
                    If checksumProductQuantity <> dblCheckSumQuantity Then
                        strPrompt = strPrompt & "Check Sum Quantity: " & checksumProductQuantity & vbCrLf &
                                "Prüfsumme: " & dblCheckSumQuantity & vbCrLf
                    End If
                    ' Prüfsumme Betrag.
                    Dim checksumAmounntInclVAT = Trim(Mid(strZeile, 29, 15)) / 100
                    If checksumAmounntInclVAT <> Math.Round(curCheckSumAmount, 2) Then
                        strPrompt = strPrompt & "Check Sum Amount: " & checksumAmounntInclVAT & vbCrLf &
                                "Prüfsumme: " & curCheckSumAmount & vbCrLf
                    End If

                    If strPrompt <> "" Then
                        MsgBox(strPrompt)
                        objFileRead.Close()
                        Return False
                    End If

                    ' Prüfsumme Anzahl der Sätze im File ohne Header und Trailer.
                    If recordCount <> (lngRecordCount) Then
                        MsgBox("Record Count: " & recordCount & vbCrLf & "Prüfsumme: " & (lngRecordCount) & vbCrLf)
                        objFileRead.Close()
                        Return False
                    End If


                    ' Meldung bei Prüfsummenfehler.
                    If booPrüfziffernfehler Then
                        MsgBox("Datei kann wegen Prüfsummenfehler nicht verarbeitet werden.")
                        objFileRead.Close()
                        Return False
                    End If
                Case Else
                    ' Andere RecordNumber überlesen.
            End Select

        Loop


        objFileRead.DiscardBufferedData()
        objFileRead.BaseStream.Seek(0, System.IO.SeekOrigin.Begin)

        lngPKLine = 0
        lngRecordCount = 0

        ' -----------------------------------------------------------------------------------
        ' Wenn der FileName schon in der Tabelle TTRHeader existiert, die Einträge in der History verschieben.
        ' Die Tabellen TTRBody und TTRTrailer werden über CASCADE aktualisiert.

        Dim SQLTTRHeader = "SELECT PKHistory, PKFileName, fileNumber FROM TTRHeader WHERE (PKHistory = 0) And (PKFileName = N'" & fi.Name.ToString & "') And (fileNumber = " & fi.Extension.Remove(0, 1) & ") "
        Dim dtTTRHeader As DataTable = SQL.loadDgvBySql_Param(SQLTTRHeader, "ASFINAG")

        If dtTTRHeader.Rows.Count > 0 Then
            Dim hisorty = SQL.getValueTxtBySql("SELECT PKHistory FROM TTRHeader WHERE (PKFileName = N'" & fi.Name.ToString & "') ORDER BY PKHistory DESC", "ASFINAG")
            hisorty = hisorty + 1
            For Each row As DataRow In dtTTRHeader.Rows
                Dim ttrHeaderArchiv As New cAsfinag.TTRHeader(row.Item("PKFileName"), row.Item("fileNumber"), "0")
                ttrHeaderArchiv.PKHistory = hisorty
                ttrHeaderArchiv.UPDATE("0")
            Next

        End If

        ' -----------------------------------------------------------------------------------

        Do While (objFileRead.Peek() > -1)
            Dim strZeile = objFileRead.ReadLine()
            lngRecordCount = lngRecordCount + 1

            Select Case Mid(strZeile, 1, 2)
                Case "10"
                    Dim ext = CInt(fi.Extension.Remove(0, 1))
                    Dim ttrHeader As New cAsfinag.TTRHeader(fi.Name.ToString, ext, "0")
                    With ttrHeader
                        .PKFileName = fi.Name
                        .recordType = Trim(Mid(strZeile, 1, 2))
                        .fileVersion = Trim(Mid(strZeile, 3, 2))
                        .senderID = Trim(Mid(strZeile, 5, 6))
                        .receiverID = Trim(Mid(strZeile, 11, 6))
                        .fileCreationDate = DateSerial(Mid(strZeile, 17, 4), Mid(strZeile, 21, 2), Mid(strZeile, 23, 2))
                        .fileCreationTime = DateSerial(Mid(strZeile, 17, 4), Mid(strZeile, 21, 2), Mid(strZeile, 23, 2)) & " " & TimeSerial(Mid(strZeile, 25, 2), Mid(strZeile, 27, 2), 0)
                        .fileNumber = Trim(Mid(strZeile, 29, 4))
                        .currencyCode = Trim(Mid(strZeile, 33, 3))
                        .description = IIf(Trim(Mid(strZeile, 36, 25)) = "", Nothing, Trim(Mid(strZeile, 36, 25)))
                        .ISOCountryCode = Trim(Mid(strZeile, 61, 3))
                        .SAVE()
                    End With

                Case "20"

                    Dim ttrBody As New cAsfinag.TTRBody(fi.Name, lngPKLine, "0")
                    With ttrBody
                        .PKFileName = fi.Name
                        .recordType = Trim(Mid(strZeile, 1, 2))
                        lngPKLine = lngPKLine + 1
                        .PKLine = lngPKLine
                        .fileVersion = Trim(Mid(strZeile, 3, 2))
                        .siteId = IIf(Trim(Mid(strZeile, 7, 15)) = "", Nothing, Trim(Mid(strZeile, 7, 15)))
                        .fileNumber = Trim(Mid(strZeile, 22, 4))
                        .fileCreationDate = DateSerial(Mid(strZeile, 26, 4), Mid(strZeile, 30, 2), Mid(strZeile, 32, 2))
                        .deliveryNoteNumber = IIf(Trim(Mid(strZeile, 35, 8)) = "", Nothing, Trim(Mid(strZeile, 35, 8)))
                        .cardNumber = Trim(Mid(strZeile, 43, 22))
                        .deliveryDate = DateSerial(Mid(strZeile, 65, 4), Mid(strZeile, 69, 2), Mid(strZeile, 71, 2))
                        .deliveryTime = IIf(Trim(Mid(strZeile, 73, 4)) = "", Nothing, DateSerial(Mid(strZeile, 65, 4), Mid(strZeile, 69, 2), Mid(strZeile, 71, 2)) & " " & TimeSerial(Mid(strZeile, 73, 2), Mid(strZeile, 75, 2), 0))
                        .transactionType = Trim(Mid(strZeile, 77, 2))
                        .productCode = Trim(Mid(strZeile, 79, 4))
                        .km = IIf(Trim(Mid(strZeile, 83, 7)) = "", Nothing, Trim(Mid(strZeile, 83, 7)))
                        .driverId = IIf(Trim(Mid(strZeile, 90, 4)) = "", Nothing, Trim(Mid(strZeile, 90, 4)))
                        .productQuantity = Trim(Mid(strZeile, 94, 6)) / 100
                        .amountInclVAT = Trim(Mid(strZeile, 100, 10)) / 100
                        .VATrate = Trim(Mid(strZeile, 155, 4)) / 100
                        .VATamount = Trim(Mid(strZeile, 159, 10)) / 100
                        .OBUID = Trim(Mid(strZeile, 130, 25))
                        .receiptNumber = Trim(Mid(strZeile, 110, 20))



                        If ttrBody.transactionType = 3 Then
                            ' Vorzeichenänderung
                            ttrBody.km = 0 - ttrBody.km
                            ttrBody.productQuantity = 0 - ttrBody.productQuantity
                            ttrBody.amountInclVAT = 0 - ttrBody.amountInclVAT
                            ttrBody.VATamount = 0 - ttrBody.VATamount
                        End If
                        If .SAVE() Then savedTrans += 1

                    End With


                Case "90"

                    Dim ttrTrailer As New cAsfinag.TTRTrailer(fi.Name, "0")
                    With ttrTrailer
                        .PKFileName = fi.Name
                        .recordType = Trim(Mid(strZeile, 1, 2))
                        .fileVersion = Trim(Mid(strZeile, 3, 2))
                        '.fileNumber = Trim(Mid(strZeile, 5, 4))
                        .recordCount = Trim(Mid(strZeile, 5, 9))
                        .checksumProductQuantity = Trim(Mid(strZeile, 14, 15)) / 100
                        .checksumAmounntInclVAT = Trim(Mid(strZeile, 29, 15)) / 100
                        .SAVE()

                        counTrans = .recordCount

                    End With

                Case Else
                    ' Andere RecordNumber überlesen.
            End Select

        Loop



        MDMEinarb.ds_total = counTrans - 2 'total - 2 (header + trailer)
        MDMEinarb.ds_count = savedTrans
        MDMEinarb.importfilename = fi.Name
        MDMEinarb.import_date = Now()

        If MDMEinarb.ds_total = MDMEinarb.ds_count Then
            MDMEinarb.completed = True
            MDMEinarb.completed_date = Now()
        End If

        MDMEinarb.SAVE()

        objFileRead.Close()

        Return True

    End Function

End Class
