Imports System.Net
Imports Excel = Microsoft.Office.Interop.Excel
Imports System.ComponentModel
Imports System.Data.SqlClient
Imports System.IO
Imports System.Data.OleDb

Public Class FMMain
    Dim FormLoaded As Boolean = False
    Dim Anzahl_Dateien As Integer = 0
    Dim Gesamtfiles As Integer = 0
    Dim _GID As Integer = 0
    Dim marker, Resultdatei As String
    Dim ListeInsert As New ArrayList
    Dim Geraet_inserted As Boolean = False
    Dim pathImport, pathImportArchiv, pathBestellungen As String
    Dim ATRDATATABLE As DataTable
    Dim SelSupplyID As Integer
    Dim vGeraete_Bez, vIP, vPORT_DISPLAY, vSerienNrGeraet, vPagecount, vModelNr, vWert As String

    Private bwXMLverarbeiten As New BackgroundWorker
    Private bwBestellungen_verarbeiten As New BackgroundWorker
    ' entspricht dem EmailProfil und enthält alle relevanten Informationen darüber
    Private _EmailProfile As ClassBWProfilExport
    Private xlsApp As Excel.Application
    Public Sub New()
        ' Dieser Aufruf ist für den Designer erforderlich.
        InitializeComponent()
        ' Fügen Sie Initialisierungen nach dem InitializeComponent()-Aufruf hinzu.
        AddHandler bwXMLverarbeiten.DoWork, AddressOf bwXMLverarbeiten_DoWork
        AddHandler bwXMLverarbeiten.RunWorkerCompleted, AddressOf bwXMLverarbeiten_RunWorkerCompleted
        AddHandler bwXMLverarbeiten.ProgressChanged, AddressOf bwXMLverarbeiten_ProgressChanged

        bwXMLverarbeiten.WorkerReportsProgress = True
        bwXMLverarbeiten.WorkerSupportsCancellation = True
        AddHandler bwBestellungen_verarbeiten.DoWork, AddressOf bwBestellungen_verarbeiten_DoWork
        AddHandler bwBestellungen_verarbeiten.RunWorkerCompleted, AddressOf bwBestellungenverarbeiten_RunWorkerCompleted
        AddHandler bwBestellungen_verarbeiten.ProgressChanged, AddressOf bwXLSverarbeiten_ProgressChanged

        bwBestellungen_verarbeiten.WorkerReportsProgress = True
        bwBestellungen_verarbeiten.WorkerSupportsCancellation = True
    End Sub
    Private Sub Form1_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
        Try
            Me.tscmbaktiv.SelectedIndex = 0
            'IP-Adresse-Auslesen
            Dim Addresslist() As IPAddress =
            Dns.GetHostEntry(Dns.GetHostName()).AddressList
            Dim IPs As IPAddress
            For Each IPs In Addresslist
                'Aktuelle Machine
                Me.Status_Machine.Text = My.Computer.Name & " - IP: " & IPs.ToString
            Next IPs
            'Beschriftung des Formulares
            Me.Text = Application.ProductName
            'Timer für Uhrzeit wird festgelegt
            Me.Timer_Uhrzeit.Interval = 1000 'Tick-Intervall des Timers festlegen
            Me.Timer_Uhrzeit.Start()  'Und diesen starten
            'Aktueller Benutzer
            Me.StatusUser.Text = Environment.UserName 'My.User.Name
            If My.Settings.ConfigConnectionString <> String.Empty Then
                CS_uebergeben()
                'Me.Status_Connection.Text = "Angemeldet an: " & Application.ProductName & " mit ConnectionString: " & My.Settings.ConfigConnectionString.ToString()
            End If
            Me.KeyPreview = True
            SPCOrder.Panel2Collapsed = True
        Catch ex As Exception
            MsgBox("Fehlerbeschreibung: " & ex.Message.ToString, MsgBoxStyle.Critical, "Fehler beim Laden des Startformulares:")
        End Try
        LoadDatagrid_layouts()
    End Sub
    Private Sub CS_uebergeben()
        Try
            Me.TBMANDANTENTableAdapter.Connection.ConnectionString = My.Settings.ConfigConnectionString
            Me.TBGERAETE_VERFOLGUNGTableAdapter.Connection.ConnectionString = My.Settings.ConfigConnectionString
            Me.TBGERAETTableAdapter.Connection.ConnectionString = My.Settings.ConfigConnectionString
            Me.TBKONFIGURATIONTableAdapter.Connection.ConnectionString = My.Settings.ConfigConnectionString
            Me.TBSTATUSTableAdapter.Connection.ConnectionString = My.Settings.ConfigConnectionString
            Me.TBSUPPLIESTableAdapter.Connection.ConnectionString = My.Settings.ConfigConnectionString
            Me.TBSUPPLY_VERFOLGUNGTableAdapter.Connection.ConnectionString = My.Settings.ConfigConnectionString
            Me.TBWH_MARKTTableAdapter.Connection.ConnectionString = My.Settings.ConfigConnectionString
            Me.TBWH_STATUS1TableAdapter.Connection.ConnectionString = My.Settings.ConfigConnectionString
            Me.TBWH_STATUS2TableAdapter.Connection.ConnectionString = My.Settings.ConfigConnectionString
            Me.TBWH_STATUS3TableAdapter.Connection.ConnectionString = My.Settings.ConfigConnectionString
            Me.TBWH_STATUS4TableAdapter.Connection.ConnectionString = My.Settings.ConfigConnectionString
            Me.TBWH_STATUS5TableAdapter.Connection.ConnectionString = My.Settings.ConfigConnectionString
            Me.TBWH_STATUSFILTERTableAdapter.Connection.ConnectionString = My.Settings.ConfigConnectionString
            Me.TBVERTRAEGETableAdapter.Connection.ConnectionString = My.Settings.ConfigConnectionString
            Me.TBGERAETE_NOTINLISTTableAdapter.Connection.ConnectionString = My.Settings.ConfigConnectionString
            Me.TBMELDEDATUMTableAdapter.Connection.ConnectionString = My.Settings.ConfigConnectionString

            Me.TBSUPPLY_DEFINITIONTableAdapter.Connection.ConnectionString = My.Settings.ConfigConnectionString
            Me.TBWH_MODELLTableAdapter.Connection.ConnectionString = My.Settings.ConfigConnectionString
            Me.TBGERAET_SUPPLY_ZUORDNUNGTableAdapter.Connection.ConnectionString = My.Settings.ConfigConnectionString
            Me.TBVERTRAG_NOTEXISTTableAdapter.Connection.ConnectionString = My.Settings.ConfigConnectionString

            Me.VWGERAET_ORDERTableAdapter.Connection.ConnectionString = My.Settings.ConfigConnectionString
            Me.VWSUPPLIES_2_ORDERTableAdapter.Connection.ConnectionString = My.Settings.ConfigConnectionString
            Me.VWRPT_SUPPLIES_TOORDERTableAdapter.Connection.ConnectionString = My.Settings.ConfigConnectionString
            Me.VWSUPPLIES_GERAETTableAdapter.Connection.ConnectionString = My.Settings.ConfigConnectionString
            Me.VWSUPPLIES_TO_ORDERTableAdapter.Connection.ConnectionString = My.Settings.ConfigConnectionString
            Me.VWSUPPLIESTableAdapter.Connection.ConnectionString = My.Settings.ConfigConnectionString
            Me.TBSUPPLY_BESTELLUNGViewTableAdapter.Connection.ConnectionString = My.Settings.ConfigConnectionString
            Me.TBSUPPLY_BESTELLUNGTableAdapter.Connection.ConnectionString = My.Settings.ConfigConnectionString
            Me.TBPRODUKT_VERTRAGTableAdapter.Connection.ConnectionString = My.Settings.ConfigConnectionString
            TBWH_MARKTTableAdapter.Connection.ConnectionString = My.Settings.ConfigConnectionString
            TBGERAETByMarktTableAdapter.Connection.ConnectionString = My.Settings.ConfigConnectionString
            Me.VWGERAETE_VERFOLGUNGTableAdapter.Connection.ConnectionString = My.Settings.ConfigConnectionString
            Me.VWSUPPLY_VERFOLGUNGTableAdapter.Connection.ConnectionString = My.Settings.ConfigConnectionString
            Me.VWGeraet_Supply_ZuordnungTableAdapter.Connection.ConnectionString = My.Settings.ConfigConnectionString
            ViewSUPPLY_STATUS_VERFOLGUNGTableAdapter.Connection.ConnectionString = My.Settings.ConfigConnectionString
        Catch ex As Exception
            MsgBox("Fehler beim Hinterlegen der ConnectionStrings: " & vbNewLine & ex.Message, MsgBoxStyle.Exclamation)
        End Try
    End Sub
    Private Sub Load_Config()
        Try
            Me.TBKONFIGURATIONTableAdapter.Fill(Me.MyDataset.TBKONFIGURATION)
            Dim DT As DataTable = Me.MyDataset.TBKONFIGURATION
            For Each dr As DataRow In DT.Rows
                pathImport = dr.Item("IMPORT_XML")
                pathImportArchiv = dr.Item("IMPORT_XMLARCHIV")
                pathBestellungen = dr.Item("IMPORT_BESTELLUNGEN")
            Next
            Try
                Dim f As New IO.DirectoryInfo(pathBestellungen & "\Archiv")
                If f.Exists = False Then
                    IO.Directory.CreateDirectory(pathBestellungen & "\Archiv")
                End If
            Catch ex As Exception
                MsgBox("Fehler beim Anlegen des Verzeichnisses '" & pathBestellungen & "\Archiv" & vbNewLine & ex.Message.ToString, MsgBoxStyle.Critical)
            End Try


        Catch ex As Exception
            MsgBox("Fehlerbeschreibung: " & ex.Message.ToString, MsgBoxStyle.Critical, "Fehler beim Laden der Konfiguration:")
        End Try
    End Sub
    Private Sub LoadDatagrid_layouts()
        Try
            txtConfigPath.Text = Application.UserAppDataPath.ToString & "\config\"
            Load_Datagrid(TBSTATUSDataGridView, "TBSTATUSDataGridView")
            Load_Datagrid(VWSUPPLIES_AKTUELLDataGridView, "VWSUPPLIES_AKTUELLDataGridView")
            Load_Datagrid(TBWH_STATUSFILTERDataGridView, "TBWH_STATUSFILTERDataGridView")

            Load_Datagrid(TBSUPPLY_DEFINITIONDataGridView, "TBSUPPLY_DEFINITIONDataGridView")
            Load_GridLayout_BestGesendet()
            Load_GridLayout_Bestuebersicht()
            Load_GridLayout_Geraete()
            Load_GridLayoutSupplies()
            Load_GridLayout_Supllies2Order()
            Load_GridLayout_SupplyZuordnung()
            Load_GridLayout_ProduktVertrag()
            If Not IO.Directory.Exists(Application.UserAppDataPath.ToString & "\config\Datagrid\") Then
                ' Nein! Jetzt erstellen...
                Try
                    IO.Directory.CreateDirectory(Application.UserAppDataPath.ToString & "\config\Datagrid\")
                    ' Ordner wurde korrekt erstellt!
                Catch ex As Exception
                    ' Ordner wurde nich erstellt
                End Try
            End If
        Catch ex As Exception
            MsgBox("Fehlerbeschreibung: " & ex.Message.ToString, MsgBoxStyle.Critical, "Fehler beim Laden der Datagrid-Layouts:")
        End Try
    End Sub
    Private Sub Form1_FormClosing(ByVal sender As Object, ByVal e As System.Windows.Forms.FormClosingEventArgs) Handles Me.FormClosing
        Try
            Me.Cursor = Cursors.WaitCursor
            Dim Path As String = Application.UserAppDataPath.ToString & "\config\Datagrid\"

            ' _Datagrid.SaveC1_DG(DGTBSUPPLY_BESTELLUNG, Path, "DGTBSUPPLY_BESTELLUNG.xml")

            Save_Datagrid(VWSUPPLIES_AKTUELLDataGridView, "VWSUPPLIES_AKTUELLDataGridView")
            Save_Datagrid(TBSTATUSDataGridView, "TBSTATUSDataGridView")
            Save_Datagrid(TBWH_STATUSFILTERDataGridView, "TBWH_STATUSFILTERDataGridView")

            Save_Datagrid(TBSUPPLY_DEFINITIONDataGridView, "TBSUPPLY_DEFINITIONDataGridView")
            Save_GridLayout_BestGesendet()
            Save_GridLayout_Bestuebersicht()
            Save_GridLayout_Geraete()
            Save_GridLayout_Supplies2Order()
            Save_GridLayout_Supplies()
            Save_GridLayout_SupplyZuordnung()
            Save_GridLayout_ProduktVertrag()
        Catch ex As Exception
            MsgBox(ex.Message, MsgBoxStyle.Critical, "Fehler beim Speichern der Datagrids:")
        End Try
    End Sub
    Sub Load_Datagrid(ByVal _Datagrid As DataGridView, ByVal _settings_String As String)
        Dim settings() As String
        If My.Settings(_settings_String) <> String.Empty Then
            settings = My.Settings(_settings_String).Split("$"c)
            For idx As Integer = 0 To _Datagrid.Columns.Count - 1
                Dim sv() As String = settings(idx).Split("/"c)
                _Datagrid.Columns(idx).DisplayIndex = CInt(sv(0))
                _Datagrid.Columns(idx).Width = CInt(sv(1))
            Next
        End If
    End Sub
    Sub Save_Datagrid(ByVal _Datagrid As DataGridView, ByVal _settings_String As String)
        Dim settings As String = String.Empty
        For idx As Integer = 0 To _Datagrid.Columns.Count - 1
            settings += _Datagrid.Columns(idx).DisplayIndex.ToString()
            settings += "/"
            settings += _Datagrid.Columns(idx).Width.ToString
            settings += "$"
        Next
        My.Settings(_settings_String) = settings
    End Sub
    Private Sub TextBoxen_GotFocus(ByVal sender As Object, ByVal e As System.EventArgs) Handles _
      txtConfigPath.GotFocus, txtPartnumber.GotFocus, txtPasswort.GotFocus, txtSchwellenwert.GotFocus, txtServer.GotFocus, txtUser.GotFocus, txtPartnumerORDER.GotFocus
        CType(sender, TextBox).BackColor = Color.Lime
    End Sub
    Private Sub TextBoxen_LostFocus(ByVal sender As Object, ByVal e As System.EventArgs) Handles _
         txtConfigPath.LostFocus, txtPartnumber.LostFocus, txtPasswort.LostFocus, txtSchwellenwert.LostFocus, txtServer.LostFocus, txtUser.LostFocus, txtPartnumerORDER.LostFocus
        CType(sender, TextBox).BackColor = Color.White
        Dim text As TextBox = sender
    End Sub
    Private Sub Form1_Shown(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Shown
        FormLoaded = True
        If My.Settings.ConfigConnectionString = "" Then
            Me.TCMain.SelectedIndex = 1
            TabControlEinstellungen.SelectedIndex = 1
            MsgBox("Bitte konfigurieren Sie die Datenbankverbindung!", MsgBoxStyle.Exclamation, "Achtung Konfiguration erforderlich!")
            txtServer.Focus()
        Else
            Status_Refresh()
            Refresh_Mandanten()
        End If
        Dim DT As DataTable = MyDataset.TBKONFIGURATION
        For Each dr As DataRow In DT.Rows
            If dr.Item("IMPORT_XML").ToString Is Nothing Then
                Me.TCMain.SelectedIndex = 1

                MsgBox("Bitte geben Sie den zu überwachenden XML-Ordner an!", MsgBoxStyle.Exclamation, "Achtung Konfiguration erforderlich!")
                Watch_Ordner()
            End If
            If dr.Item("IMPORT_XMLARCHIV").ToString Is Nothing Then
                Me.TCMain.SelectedIndex = 1
                MsgBox("Bitte geben Sie den Archivordner für eingelesene XML-Files an!", MsgBoxStyle.Exclamation, "Achtung Konfiguration erforderlich!")
                Archiv_Ordner()
            End If
            If dr.Item("IMPORT_BESTELLUNGEN").ToString Is Nothing Then
                Me.TCMain.SelectedIndex = 1
                MsgBox("Bitte geben Sie den Ordner für Bestellungen an!", MsgBoxStyle.Exclamation, "Achtung Konfiguration erforderlich!")
                Bestellungen_Ordner()
            End If
        Next
    End Sub

    Private Sub BtnConnect_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles BtnConnect.Click
        ' Dim csb As New SqlClient.SqlConnectionStringBuilder
        Try
            Dim con As String = "Server=" & Me.txtServer.Text & ";Database=" & Me.cmbDatenbank.Text & ";User Id=" & Me.txtUser.Text & ";Password=" & Me.txtPasswort.Text & ";"
            'csb.DataSource = Me.txtServer.Text
            'csb.InitialCatalog = Me.cmbDatenbank.Text
            'csb.IntegratedSecurity = False

            'csb.UserID = Me.txtUser.Text
            'csb.Password = Me.txtPasswort.Text
            'If txtTimeout.Text <> String.Empty Then
            '    csb.ConnectTimeout = CInt(txtTimeout.Text)
            'End If

            Dim connection As New SqlClient.SqlConnection(con)
            'während Verbindungsaufbau Sanduhr-Mauszeiger
            Cursor = Cursors.WaitCursor
            connection.Open()
            Cursor = Cursors.Default
            'DialogResult = Windows.Forms.DialogResult.OK
            Dim result As MsgBoxResult
            result = MessageBox.Show("Die Verbindung wurde erfolgreich aufgebaut!" & vbNewLine & "Möchten Sie diese Verbindung nun in der Anwendung speichern?", "Erfolgsmeldung:", MessageBoxButtons.YesNo, MessageBoxIcon.Question)
            If result = MsgBoxResult.Yes Then
                'Set the construction string
                My.Settings.ConfigConnectionString = con

                My.Settings.Save()
                CS_uebergeben()

                Load_Config()
                Refresh_Mandanten()
                Status_Refresh()
                Refresh_Supply_Typen()
            End If
        Catch ex As Exception
            Cursor = Cursors.Default
            MsgBox("Fehler beim Verbindungsaufbau: " & vbNewLine & ex.Message, MsgBoxStyle.Exclamation)
        End Try
    End Sub
    Private Sub TCMain_SelectedIndexChanged(ByVal sender As Object, ByVal e As System.EventArgs) Handles TCMain.SelectedIndexChanged
        Select Case Me.TCMain.SelectedIndex
            Case 0
            Case 1
                If My.Settings.ConfigConnectionString <> String.Empty Then
                    Refresh_Supply_Typen()
                End If
            Case 2
                If My.Settings.ConfigConnectionString <> String.Empty Then
                    Refresh_WH_Modell()
                    Refresh_Vertrag_Produkt()
                    Refresh_Geraete_Supply()
                    Refresh_Supply_Typen()
                End If
        End Select
    End Sub
    Private Function Konfiguration_save()
        Try
            Me.Validate()
            Me.TBKONFIGURATIONBindingSource.EndEdit()
            If Me.MyDataset.TBKONFIGURATION.GetChanges Is Nothing = False Then
                Me.GEAENDERTWERTextBox.Text = Environment.UserName
                Me.TBKONFIGURATIONBindingSource.EndEdit()
                Me.TBKONFIGURATIONTableAdapter.Update(MyDataset.TBKONFIGURATION)
                MsgBox("Konfiguration wurde erfolgreich gespeichert!", MsgBoxStyle.Information, "Erfolgsmeldung:")

            End If
            Return True
        Catch ex As Exception
            MsgBox(ex.Message, MsgBoxStyle.Critical, "Fehler bei Update der Konfiguration:")
            Return False
        End Try
    End Function
    Private Sub Status_Save()
        Try
            Me.Validate()
            Me.TBSTATUSBindingSource.EndEdit()
            If MyDataset.TBSTATUS.GetChanges Is Nothing = False Then
                TBSTATUSBindingSource.EndEdit()
                Me.TBSTATUSTableAdapter.Update(Me.MyDataset.TBSTATUS)
                MsgBox("Status-Daten wurden erfolgreich gespeichert!", MsgBoxStyle.Information, "Erfolgsmeldung:")
            End If
        Catch ex As Exception
            MsgBox(ex.Message, MsgBoxStyle.Critical, "Fehler bei Speichern der Modelle:")
        End Try
    End Sub
    Private Sub Status_Refresh()
        Try
            Me.TBSTATUSTableAdapter.Fill(Me.MyDataset.TBSTATUS)
        Catch ex As Exception
            MsgBox(ex.Message, MsgBoxStyle.Critical, "Fehler beim Laden der StatusDaten:")
        End Try
        Wertehilfen_fuellen()
        Load_Config()
    End Sub
    Private Sub Refresh_Supplies()
        Try
            Dim Row As Integer
            If VWSUPPLIESBindingSource.Count > 0 Then

            Else
                Row = 0
            End If
            If Me.chbFilterStatus.Checked = True Then
                Dim Status As String = TBWH_STATUSFILTERDataGridView.CurrentCell.Value()
                Me.VWSUPPLIESTableAdapter.FillByStatusname(Me.MyDataset.VWSUPPLIES, Status)
            Else
                Me.VWSUPPLIESTableAdapter.Fill(Me.MyDataset.VWSUPPLIES)
            End If
        Catch ex As System.Exception
            MsgBox(ex.Message, MsgBoxStyle.Critical, "Fehler beim Abfragen der Supply-Daten:")
        End Try
        'Wertehilfen_fuellen()
    End Sub
    Private Sub Wertehilfen_fuellen()
        Try
            Me.TBWH_STATUS5TableAdapter.Fill(Me.MyDataset.TBWH_STATUS5)
            Me.TBWH_STATUS4TableAdapter.Fill(Me.MyDataset.TBWH_STATUS4)
            Me.TBWH_STATUS3TableAdapter.Fill(Me.MyDataset.TBWH_STATUS3)
            Me.TBWH_STATUS2TableAdapter.Fill(Me.MyDataset.TBWH_STATUS2)
            Me.TBWH_STATUS1TableAdapter.Fill(Me.MyDataset.TBWH_STATUS1)
            Me.TBWH_STATUSFILTERTableAdapter.Fill(Me.MyDataset.TBWH_STATUSFILTER)
        Catch ex As Exception
            MsgBox(ex.Message, MsgBoxStyle.Critical, "Fehler bei Zuweisen der Stati zu Comboboxen:")
        End Try
    End Sub
    Sub Refresh_WH_Modell()
        Try
            Me.TBWH_MODELLTableAdapter.Fill(Me.MyDataset.TBWH_MODELL)
        Catch ex As Exception
            MsgBox(ex.Message, MsgBoxStyle.Critical, "Fehler beim Laden Refresh_WH_Modell:")
        End Try
    End Sub
    Sub Refresh_Mandanten()
        Try
            Me.TBMANDANTENTableAdapter.Fill(Me.MyDataset.TBMANDANTEN)
            cmbMandanten.Items.Clear()
            Dim DT As DataTable = MyDataset.TBMANDANTEN
            cmbMandanten.Items.Add("")
            For Each row As DataRow In DT.Rows
                cmbMandanten.Items.Add(row.Item("NAME"))
            Next
            cmbMandanten.SelectedIndex = 1
        Catch ex As Exception
            MsgBox(ex.Message, MsgBoxStyle.Critical, "Fehler beim Laden Mandanten:")
        End Try
    End Sub
    Private Sub Refresh_Geraete(mandant As String)
        Try
            If FormLoaded = True Then
                If mandant <> String.Empty Then
                    Dim mandant_id As Integer = TBMANDANTENTableAdapter.cmdGetMandID(mandant)

                    cmbMandanten.BackColor = Color.White
                    Me.Cursor = Cursors.WaitCursor
                    If Me.tscmbaktiv.SelectedIndex = 0 Then
                        FILTER_DEVICE = ""

                    Else
                        FILTER_DEVICE = tscmbaktiv.Text

                    End If
                    Select Case Me.tscmbaktiv.Text
                        Case "Nur aktive Geräte"
                            Me.TBGERAETTableAdapter.Fill(Me.MyDataset.TBGERAET, True, mandant_id)
                        Case "Inaktive Geräte"
                            Me.TBGERAETTableAdapter.Fill(Me.MyDataset.TBGERAET, False, mandant_id)
                        Case "Abgebaute Geräte"
                            Me.TBGERAETTableAdapter.FillByAbgebaut1(Me.MyDataset.TBGERAET, mandant_id)
                    End Select







                    Me.MyDataset.VWSUPPLIES_AKTUELL.Clear()

                Else
                    MsgBox("Bitte einen Mandanten wählen!", MsgBoxStyle.Exclamation, "Keine Auswahl:")
                    cmbMandanten.BackColor = Color.OrangeRed
                End If

            End If
        Catch ex As Exception
            MsgBox(ex.Message, MsgBoxStyle.Critical, "Fehler bei Laden der Gerätedaten:")
        End Try

        Me.Cursor = Cursors.Default
    End Sub


    Private Sub btnSaveKonfig_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnSaveKonfig.Click
        Konfiguration_save()
    End Sub

    Private Sub tsbStatus_Refresh_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles tsbStatus_Refresh.Click
        Status_Refresh()
    End Sub

    Private Sub tsbStatus_Save_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles tsbStatus_Save.Click
        Status_Save()
    End Sub

    Private Sub Timer_Uhrzeit_Tick(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Timer_Uhrzeit.Tick
        Me.Status_Clock.Text = My.Computer.Clock.LocalTime
    End Sub

    Private Sub tsbSupplies_Refresh_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles tsbSupplies_Refresh.Click
        Refresh_Supplies()
    End Sub

    Private Sub TBSTATUSBindingSource_AddingNew(ByVal sender As System.Object, ByVal e As System.ComponentModel.AddingNewEventArgs) Handles TBSTATUSBindingSource.AddingNew
        MyDataset.TBSTATUS.ERFASSTWERColumn.DefaultValue = Environment.UserName
    End Sub

    Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
        Watch_Ordner()
    End Sub
    Sub Archiv_Ordner()
        Try
            'First create a FolderBrowserDialog object
            Dim FolderBrowserDialog1 As New FolderBrowserDialog
            'Then use the following code to create the Dialog window
            'Change the .SelectedPath property to the default location
            With FolderBrowserDialog1
                ' Desktop is the root folder in the dialog.
                .RootFolder = Environment.SpecialFolder.Desktop
                ' Prompt the user with a custom message.
                .Description = "Archiv-Ordner für eingelesene Dateien wählen:"
                If .ShowDialog = DialogResult.OK Then
                    Dim Path As String = .SelectedPath
                    Me.IMPORT_XMLARCHIVTextBox.Text = .SelectedPath
                    Konfiguration_save()
                End If
            End With
        Catch ex As Exception
            MsgBox(ex.Message, MsgBoxStyle.Critical, "Fehler bei Archiv_Ordner:")
        End Try
    End Sub
    Sub Watch_Ordner()
        Try
            'First create a FolderBrowserDialog object
            Dim FolderBrowserDialog1 As New FolderBrowserDialog
            ' Then use the following code to create the Dialog window
            ' Change the .SelectedPath property to the default location
            With FolderBrowserDialog1
                ' Desktop is the root folder in the dialog.
                .RootFolder = Environment.SpecialFolder.Desktop
                ' Prompt the user with a custom message.
                .Description = "Überwachungsordner für Xml-Files wählen:"
                If .ShowDialog = DialogResult.OK Then
                    Dim Path As String = .SelectedPath
                    Me.IMPORT_XMLTextBox.Text = .SelectedPath
                    Konfiguration_save()
                End If
            End With
        Catch ex As Exception
            MsgBox(ex.Message, MsgBoxStyle.Critical, "Fehler bei Watch_Ordner:")
        End Try
    End Sub
    Sub Bestellungen_Ordner()
        Try
            'First create a FolderBrowserDialog object
            Dim FolderBrowserDialog1 As New FolderBrowserDialog
            ' Then use the following code to create the Dialog window
            ' Change the .SelectedPath property to the default location
            With FolderBrowserDialog1
                ' Desktop is the root folder in the dialog.
                .RootFolder = Environment.SpecialFolder.Desktop
                ' Prompt the user with a custom message.
                .Description = "Ordner für Bestellungen wählen:"
                If .ShowDialog = DialogResult.OK Then
                    Dim Path As String = .SelectedPath
                    Me.IMPORT_BESTELLUNGENTextBox.Text = .SelectedPath
                    Konfiguration_save()
                End If
            End With
        Catch ex As Exception
            MsgBox(ex.Message, MsgBoxStyle.Critical, "Fehler bei Bestellungen_Ordner:")
        End Try
    End Sub

    Private Sub btnFolderArchiv_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnFolderArchiv.Click
        Archiv_Ordner()
    End Sub
    Private Sub tsbImport_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles tsbImport.Click
        XML_verarbeiten()
    End Sub

    Private Sub tsbImport1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles tsbImport1.Click
        XML_verarbeiten()
    End Sub

    Private Sub tsbImport2_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles tsbImport2.Click
        XML_verarbeiten()
    End Sub
    Sub Bestellungen_verarbeiten()
        Load_Config()
        If Not Me.bwBestellungen_verarbeiten.IsBusy Then
            tsProgressBar.Visible = True
            tslbl_Files.Visible = True
            'Anzahl der Files auslesen
            Anzahl_Dateien = 0
            Gesamtfiles = 0
            Dim diPfad As New IO.DirectoryInfo(pathBestellungen)
            For Each file As IO.FileInfo In diPfad.GetFiles()
                If (file.Name.ToUpper.Contains("_BESTELLUNG_") And file.Name.ToUpper.EndsWith(".XLS")) Or (file.Name.ToUpper.Contains("_BESTELLUNG_") And file.Name.ToUpper.EndsWith(".XLSX")) Then
                    Gesamtfiles = Gesamtfiles + 1
                End If
            Next
            tslbl_Files.Text = "Noch zu verarbeiten: " & Gesamtfiles & " Files"
            tsProgressBar.Maximum = Gesamtfiles * 100
            bwBestellungen_verarbeiten.RunWorkerAsync()
        Else
            MsgBox("Der aktuelle Import läuft noch!", MsgBoxStyle.Exclamation, "ACHTUNG:")
        End If
    End Sub
    Private Sub bwBestellungen_verarbeiten_DoWork(ByVal sender As Object, ByVal e As System.ComponentModel.DoWorkEventArgs)
        Try
            Dim _errorsOrders As String = ""
            Dim diPfad As New IO.DirectoryInfo(pathBestellungen)
            Dim Progress As Integer = 0
            Dim Counter As Integer = 0
            ClassLoggerSW.Init("", "Supply_Watch", False)

            For Each file As IO.FileInfo In diPfad.GetFiles()
                ' Dim vDatum As String = ""
                If (file.Name.ToUpper.Contains("_BESTELLUNG_") And file.Name.ToUpper.EndsWith(".XLS")) Or (file.Name.ToUpper.Contains("_BESTELLUNG_") And file.Name.ToUpper.EndsWith(".XLSX")) Then
                    Anzahl_Dateien = Anzahl_Dateien + 1
                    Progress += 25
                    'bwXMLverarbeiten.ReportProgress(Progress)
                    'Dim str As String = file.Name
                    ''1106271'
                    'vDatum = file.Name.Substring(4, 2) & "." & file.Name.Substring(2, 2) & ".20" & file.Name.Substring(0, 2)

                    'MsgBox(vDatum & vbNewLine & file.FullName)
                    Dim _DS As New DataSet
                    'Datei auslesen und Dataset rückgeben lassen
                    _DS = XLSReader(file.FullName, "RptOrder_Supplies")
                    If _DS Is Nothing Then
                        MsgBox("Datei: " & vbNewLine & file.Name & vbNewLine & " wurde nicht verarbeitet!" & vbNewLine & "Prüfen Sie ob der Name des Tabellenblattes RptOrder_Supplies ist?!", MsgBoxStyle.Exclamation, "Achtung:")
                        Anzahl_Dateien = Anzahl_Dateien - 1
                    Else

                        'MsgBox("Anzahl: " & _DS.Tables(0).Rows.Count & vbNewLine & "Hier müssten jetzt die Updates erfolgen")
                        Dim DT As System.Data.DataTable
                        Dim DR As System.Data.DataRow
                        ' Dim DC As System.Data.DataColumn
                        '' --- DataSet zuweisen
                        'DS = Me.MyDataset
                        '' --- Zugriff auf Tabelle
                        DT = _DS.Tables(0)
                        If DT.Rows.Count > 0 Then
                            Dim idxGeraet, idxSerial, idxVertrag, idxMarkt, idxSupplyID As Integer

                            Dim _gerät, _markt, _seriennr, _Supply, _Part, _Anzahl As String
                            Dim _VAS As String
                            Dim _BestellSupplyID As String
                            Dim _SupplyID As Integer
                            Dim _BestellID
                            Dim _returnvalueGeraet, _returnvalueSerial, _returnvalueSupplyID, _returnValueCount, _returnvalueVAS As Type
                            'Überprüfen wie die Datei aufgebaut/bearbeitet wurde?
                            Dim RowIndex = 0
                            Dim GeraetebezeichnungHook
                            Dim GeraetebezeichnungHook1

                            For Each DR In DT.Rows
                                _VAS = Nothing
                                idxGeraet = 99

                                If RowIndex >= 5 Then
                                    GeraetebezeichnungHook = DR.Item(0)
                                    GeraetebezeichnungHook1 = DR.Item(1)
                                    If GeraetebezeichnungHook.GetType.ToString <> "System.DBNull" Then
                                        If GeraetebezeichnungHook = "Gerätebezeichnung" Then
                                            idxGeraet = 0
                                        End If
                                    Else
                                        If GeraetebezeichnungHook1.GetType.ToString <> "System.DBNull" Then
                                            If GeraetebezeichnungHook1 = "Gerätebezeichnung" Then
                                                GeraetebezeichnungHook = "Gerätebezeichnung"
                                                idxGeraet = 1
                                            End If
                                        End If
                                    End If
                                End If

                                'Dim Rowstring = DR.Item(0)
                                'Dim Rowstring1 = DR.Item(1)
                                'If Rowstring.GetType.ToString <> "System.DBNull" Then
                                '    If Rowstring.ToString.StartsWith("HP") Then
                                '        idxGeraet = 0
                                '    End If
                                'Else
                                '    If Rowstring1.GetType.ToString <> "System.DBNull" Then
                                '        Rowstring = Rowstring1
                                '    End If

                                'End If

                                'If DR.Item(1).GetType.ToString <> "System.DBNull" Then
                                '    If Rowstring.ToString.StartsWith("HP") Then
                                '        idxGeraet = 1
                                '    End If
                                'End If
                                If idxGeraet < 99 Then
                                    Exit For
                                End If

                                RowIndex += 1
                            Next
                            If idxGeraet = 99 Then
                                MsgBox("In der Datei konnte keine gültige Devicedefinition gefunden werden!", MsgBoxStyle.Exclamation)
                            Else
                                If GeraetebezeichnungHook = "Gerätebezeichnung" Then

                                End If
                                Dim zaehler As Integer = 0
                                For Each DR In DT.Rows
                                    _gerät = ""
                                    _seriennr = ""
                                    _markt = ""
                                    _SupplyID = 0
                                    _BestellSupplyID = ""
                                    _BestellID = 0
                                    _Supply = ""
                                    _Anzahl = "1"
                                    'If zaehler >= 6 Then
                                    '    MsgBox("_gerät " & DR.Item(1) & vbNewLine & _
                                    '"_seriennr  " & DR.Item(2) & vbNewLine & _
                                    '    "_markt: " & DR.Item(4) & vbNewLine & _
                                    '    "_SupplyID: " & DR.Item(5))
                                    'End If
                                    _returnvalueGeraet = DR.Item(idxGeraet).GetType()
                                    _returnvalueSerial = DR.Item(idxGeraet + 1).GetType()
                                    _returnvalueSupplyID = DR.Item(idxGeraet + 4).GetType()
                                    _returnValueCount = DR.Item(idxGeraet + 5).GetType()
                                    _returnvalueVAS = DR.Item(idxGeraet + 9).GetType()
                                    If _returnvalueGeraet.ToString <> "System.DBNull" Then
                                        If _returnvalueSerial.ToString <> "System.DBNull" Then
                                            If _returnvalueSupplyID.ToString <> "System.DBNull" Then 'And _returnvalueVAS.ToString <> "System.DBNull"
                                                Dim Device = DR.Item(idxGeraet)
                                                If CStr(Device) <> "Gerätebezeichnung" Then '.StartsWith("HP") Then
                                                    _gerät = DR.Item(idxGeraet)
                                                    _seriennr = DR.Item(idxGeraet + 1)
                                                    _markt = DR.Item(idxGeraet + 3)
                                                    _BestellSupplyID = RTrim(LTrim(DR.Item(idxGeraet + 4)))
                                                    '_SupplyID = DR.Item(idxGeraet + 4)
                                                    _Supply = DR.Item(idxGeraet + 5)



                                                    Dim _count = DR.Item(6)
                                                    If IsDBNull(_count) Then
                                                        _Anzahl = "1"
                                                    Else
                                                        _Anzahl = _count
                                                    End If

                                                    Dim _vasno = DR.Item(idxGeraet + 9).ToString

                                                    _VAS = RTrim(LTrim(DR.Item(idxGeraet + 9).ToString)).ToString.Replace(" ", "")
                                                    _VAS = _VAS.Replace(vbCr, "").Replace(vbLf, "")
                                                    _VAS = _VAS.Replace("\n", "").Replace("\r", "")
                                                    _VAS = _VAS.Replace(vbCrLf, "")
                                                    _VAS = _VAS.ToString.Where(Function(x) Not Char.IsWhiteSpace(x)).ToArray()
                                                    ' Convert to String data.
                                                    Dim value As New String(_VAS)
                                                    _VAS = value
                                                    If chkLogData.Checked Then
                                                        Dim msg = "Device: '" & _gerät & "'" & vbNewLine &
                                                               "Serial: '" & _seriennr & "'" & vbNewLine &
                                                               "Markt: '" & _markt & "'" & vbNewLine &
                                                               "OrderSupplyID: '" & _BestellSupplyID & "'" & vbNewLine &
                                                               "Supply: '" & _Supply & "'" & vbNewLine &
                                                               "VAS#: '" & _VAS & "'"
                                                        ClassLogger.Add(msg, False)
                                                    End If

                                                    If _BestellSupplyID.StartsWith("#2") Then 'reguläre Bestellung kommt zurück
                                                        _BestellID = _BestellSupplyID.Replace("#2", "")

                                                        'Dim sql = String.Format("SELECT ISNULL(MAX(GUID), 0) FROM TBSUPPLY_BESTELLUNG WHERE (SUPPLY_ID = {0})", _SupplyID)
                                                        '_BestellID = ClassDatabase.Execute_Scalar(sql, True)
                                                    ElseIf _BestellSupplyID.StartsWith("#1") Then 'manuelle Bestellung kommt zurück
                                                        _BestellID = _BestellSupplyID.Replace("#1", "")
                                                    End If

                                                    'Dim GUID As Integer = TBSUPPLY_BESTELLUNGViewTableAdapter.cmdgetID_ORDER_SUPPLYID(_SupplyID)
                                                    'MsgBox(GUID)
                                                    If _BestellID <> 0 Then
                                                        If _VAS <> String.Empty Then
                                                            If _VAS.ToString.StartsWith("5") Then
                                                                MsgBox(_VAS)
                                                            End If
                                                            If Not IsNumeric(_VAS) Then
                                                                MsgBox("Achtung:" & vbNewLine & "Die Bestellnummer '" & _VAS & "' entspricht nicht den Vorgaben. (Numerisch)")
                                                                Continue For
                                                            End If

                                                            Dim sql = String.Format("SELECT COUNT(GUID) FROM TBSUPPLY_BESTELLUNG WHERE GUID = {0}", _BestellID)
                                                            Dim exists = ClassDatabase.Execute_Scalar(sql, True)
                                                            If exists = 0 Then
                                                                Dim DTRECORD As DataTable
                                                                sql = String.Format("SELECT T.BEZEICHNUNG,T1.MARKT,'ERR-ORDER-DELETED',T1.BEZEICHNUNG,T1.SERIENNR,T.GUID,T1.GUID,T.[LEVEL],T1.MANDANT_ID " &
                                                                "FROM TBSUPPLIES T, TBGERAET T1 WHERE T.GERAET_ID = T1.GUID AND T.STATUS_ID <> 6 AND " &
                                                                "UPPER(T1.SERIENNR) = UPPER('{0}') AND " &
                                                                "UPPER(T.BEZEICHNUNG) = UPPER('{1}')", _seriennr, _Supply)
                                                                DTRECORD = ClassDatabase.Return_Datatable(sql, True)
                                                                If Not IsNothing(DTRECORD) And DTRECORD.Rows.Count >= 1 Then
                                                                    _markt = DTRECORD.Rows(0).Item(1)
                                                                    Dim wer = "ERR-ORDER-DELETED"
                                                                    Dim SUPP_ID = DTRECORD.Rows(0).Item(5)
                                                                    Dim GERAETID = DTRECORD.Rows(0).Item(6)
                                                                    Dim BESTELL_LEVEL = DTRECORD.Rows(0).Item(7)
                                                                    Dim MandantID = DTRECORD.Rows(0).Item(8)

                                                                    Dim ins = String.Format("INSERT INTO TBSUPPLY_BESTELLUNG(SUPPLY_BEZEICHNUNG,MARKT,BESTELLT_WER,GERAET,SERIEN_NR,SUPPLY_ID,GERAET_ID,BESTELL_LEVEL,MANDANT_ID,MENGE) VALUES (" &
                                                                                            "'{0}','{1}','{2}','{3}','{4}',{5},{6},'{7}',{8},{9})",
                                                                                            _Supply, _markt, wer, _gerät, _seriennr, SUPP_ID, GERAETID, BESTELL_LEVEL, MandantID, _Anzahl)
                                                                    If ClassDatabase.Execute_non_Query(ins, True) = True Then
                                                                        sql = String.Format("SELECT MAX(GUID) FROM TBSUPPLY_BESTELLUNG WHERE UPPER(SUPPLY_BEZEICHNUNG) = UPPER('{0}') AND UPPER(SERIEN_NR) = UPPER('{1}')", _Supply, _seriennr)
                                                                        _BestellID = ClassDatabase.Execute_Scalar(sql, True)
                                                                        If IsDBNull(_BestellID) Or IsNothing(_BestellID) Or _BestellID = 0 Then
                                                                            MsgBox("Achtung:" & vbNewLine & "Für die hinzugefügte Bestellung konnte kein Datensatz geholt werden!")
                                                                            Continue For
                                                                        End If
                                                                    Else
                                                                        MsgBox("Could not insert the new Order-record! - Why: BestellID was nothing!")
                                                                    End If
                                                                Else
                                                                    MsgBox("Achtung:" & vbNewLine & "Für die OrderID '" & _BestellID & "' konnte kein Supply identifiziert werden!")
                                                                    Continue For
                                                                End If
                                                            End If




                                                            Dim upd
                                                            Try
                                                                upd = String.Format("UPDATE TBSUPPLY_BESTELLUNG SET BESTELLNR = '{0}', FILE_ORDER_CONFIRM = '{1}' WHERE GUID = {2}", _VAS, file.Name, _BestellID)
                                                                If chkLogData.Checked Then
                                                                    ClassLogger.Add(upd, False)
                                                                End If
                                                                If ClassDatabase.Execute_non_Query(upd, True) = True Then
                                                                    Counter = Counter + 1
                                                                End If
                                                            Catch ex As Exception
                                                                MsgBox("Error in update Bestellnr:" & vbNewLine & ex.Message & vbNewLine & "Command copied to clipboard", MsgBoxStyle.Critical)
                                                                My.Computer.Clipboard.SetText(upd)
                                                            End Try

                                                            'TBSUPPLY_BESTELLUNGViewTableAdapter.cmdUpdateVAS(_VAS, file.Name, GUID)
                                                        Else
                                                            If _errorsOrders <> String.Empty Then
                                                                _errorsOrders &= vbNewLine & _BestellID.ToString
                                                            Else
                                                                _errorsOrders = _BestellID.ToString
                                                            End If

                                                            MsgBox("Achtung:" & vbNewLine & "Die Bestellnummer ist leer bzw konnte nicht ausgewertet werden!" & vbNewLine & "Die BestellID: " & _BestellID.ToString & " wird geloggt und später aufgeführt!")
                                                        End If
                                                    End If
                                                Else
                                                    ClassLoggerSW.Add(">> Device is not defined for OrderImport: '" & Device & "'", False)
                                                End If
                                            End If
                                        End If
                                    End If
                                    zaehler += 1
                                Next
                            End If
                        Else
                            MsgBox("Excel-Tabelle konnte nicht gelesen werden!", MsgBoxStyle.MsgBoxHelp)
                        End If



                    End If

                    'For Each DC In DT.Columns
                    '    MsgBox(DC.ColumnName & vbNewLine & DC.Caption)
                    'Next
                    Progress += 75
                    Gesamtfiles += -1
                    bwBestellungen_verarbeiten.ReportProgress(Progress)
                    If Counter > 0 Then
                        MoveFile(file.FullName, file.Name, pathBestellungen, pathBestellungen)
                    End If

                End If
            Next
            If Anzahl_Dateien <> 0 And Counter > 0 Then
                MsgBox("Es wurde(n) " & Anzahl_Dateien & " Datei(en) erfolgreich verarbeitet!" & vbNewLine &
                       Counter & " Bestell-Nummern wurden erfolgreich upgedated.", MsgBoxStyle.Information, "Erfolgsmeldung:")
                'Me.Wertehilfen_fuellen()
            Else
                MsgBox("Keine Dateien zum Verarbeiten vorhanden oder" & vbNewLine & "die Dateizellen können nicht gelesen werden!" & vbNewLine & "Überwachter Ordner: " & vbNewLine & pathBestellungen, MsgBoxStyle.Exclamation, "Achtung:")
            End If

            If _errorsOrders <> String.Empty Then
                MsgBox("Achtung: folgende Bestell-IDs konnten nicht verarbeitet werden: " & vbNewLine & _errorsOrders & vbNewLine & vbNewLine & "Bitte korrigieren Sie etwaige Formatierungen manuell und lesen die Datei erneut ein!", MsgBoxStyle.Exclamation)

            End If
        Catch ex As Exception
            MsgBox(ex.Message, MsgBoxStyle.Critical, "Unexpected Error in bwBestellungen_verarbeiten_DoWork:")
        End Try


    End Sub

    Private Function XLSReader(ByVal filepath As String, Sheetname As String)
        Dim ds As New DataSet
        Dim con As String
        Dim excelConnection As OleDbConnection
        Try

            'Instanz des DataSet-Objektes instanzieren

            Try
                'Verbindungszeichenfolge festlegen, der Name der Excel-Datei wird als Parameter übergeben
                con = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" + filepath + ";Extended Properties='Excel 12.0;HDR=YES;'"
                '"Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" & filepath & ";" &
                '      "Extended Properties=""Excel 8.0;HDR=YES;"""
                excelConnection = New OleDbConnection(con)
                excelConnection.Open()
                If chkLogData.Checked Then ClassLogger.Add("excelConnection opened....", False)
            Catch ex1 As Exception
                If ex1.Message = "Der 'Microsoft.ACE.OLEDB.12.0'-Provider ist nicht auf dem lokalen Computer registriert." Then
                    con = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" + filepath + ";Extended Properties='Excel 8.0;HDR=YES;'"
                    excelConnection = New OleDbConnection(con)
                    Try
                        excelConnection.Open()
                    Catch ex As Exception
                        Return Nothing
                    End Try
                Else
                    MsgBox(ex1.Message, MsgBoxStyle.Critical, "Could not create excel-Connection 12.0:")
                    Try
                        excelConnection.Close()
                    Catch ex As Exception
                    End Try
                    Return Nothing
                End If






            End Try

            Dim da_final As New OleDb.OleDbDataAdapter("SELECT * FROM [" & Sheetname & "$]", con) 'Report
            If chkLogData.Checked Then ClassLogger.Add("da_final opening....", False)
            'DataSet füllen
            da_final.Fill(ds)
            Dim DT As System.Data.DataTable
            DT = ds.Tables(0)
            da_final.Dispose()
            excelConnection.Close()
            'DataSet zurückgeben
            Return ds
        Catch ex As Exception
            MsgBox(ex.Message, MsgBoxStyle.Critical, "Unexpected Error in XLSReader:")
            Try
                excelConnection.Close()
            Catch ex1 As Exception

            End Try

            Return Nothing
        End Try
    End Function
    Sub XML_verarbeiten()
        Load_Config()
        If Not Me.bwXMLverarbeiten.IsBusy Then
            Try
                ClassLoggerSW.Init("", "Supply_Watch", False)
                tsProgressBar.Visible = True
                tslbl_Files.Visible = True
                Me.tsbtnAbbrechen.Visible = True
                'Anzahl der Files auslesen
                Anzahl_Dateien = 0
                Gesamtfiles = 0
                Dim diPfad As New IO.DirectoryInfo(Me.pathImport)
                For Each file As IO.FileInfo In diPfad.GetFiles()
                    If file.Name.EndsWith(".xml") Then
                        Gesamtfiles = Gesamtfiles + 1
                        'MsgBox(file.Name)
                    End If
                Next
                tslbl_Files.Text = "Noch zu verarbeiten: " & Gesamtfiles & " Files"
                tsProgressBar.Maximum = Gesamtfiles * 100

                bwXMLverarbeiten.RunWorkerAsync()
            Catch ex As Exception
                MsgBox(ex.Message, MsgBoxStyle.Critical, "Fehler in XML-Verarbeiten:")
            End Try

        Else
            MsgBox("Der aktuelle Import läuft noch!", MsgBoxStyle.Exclamation, "ACHTUNG:")
        End If
    End Sub
    <STAThread()>
    Private Sub bwXMLverarbeiten_DoWork(ByVal sender As Object, ByVal e As System.ComponentModel.DoWorkEventArgs)
        Try
            Me.TBVERTRAG_NOTEXISTTableAdapter.Delete()
            Dim diPfad As New IO.DirectoryInfo(pathImport)
            Dim Progress As Integer = 0
            For Each file As IO.FileInfo In diPfad.GetFiles()
                Dim vMarkt As String = ""
                Dim vDatum As String = ""
                Dim vVertrag As String = ""
                Dim MANDANTEN_KZ As String = ""
                Dim SUPPLYWATCH_AKTIV As Boolean = False
                If file.Name.EndsWith(".xml") Then
                    ' MsgBox(file.Name)
                    Anzahl_Dateien = Anzahl_Dateien + 1
                    Progress += 25
                    bwXMLverarbeiten.ReportProgress(Progress)
                    'Array für den Dateinamen
                    Dim ArrayDateiname() As String
                    Dim count As Integer
                    'Array erstellen mit Trennzeichen "–"
                    If file.Name.Contains("–") Then
                        ArrayDateiname = file.Name.Split("–")
                    ElseIf file.Name.Contains("-") Then
                        ArrayDateiname = file.Name.Split("-")
                    End If

                    MANDANTEN_KZ = Replace(ArrayDateiname(0), " ", "")
                    'Auslesen ob Supplywatch für diesen Mandanten aktiv ist?
                    SUPPLYWATCH_AKTIV = TBMANDANTENTableAdapter.cmdCheckSW_aktiv(MANDANTEN_KZ)
                    'Array Vertrag und Meldedatum erstellen erstellen mit Trennzeichen UNDERSCORE
                    Dim Vertrag_Arr As String() = Trim(ArrayDateiname(1)).ToString.Split("_")
                    vVertrag = Trim(Vertrag_Arr(0))
                    'MARKT 
                    vMarkt = "ALL_IN"
                    'Das Datum auswerten
                    vDatum = Trim(Vertrag_Arr(2))
                    ClassLoggerSW.Add(" VERTRAG: " & vVertrag & " - Mandanten KZ: " & MANDANTEN_KZ & " - Meldedatum: " & vDatum & " - SW-Aktiv: " & SUPPLYWATCH_AKTIV.ToString, False)

                    'MsgBox(vDatum)
                    'all_de_20100809_131313
                    'For count = 0 To strArr.Length - 1
                    '    'MsgBox(strArr(count).ToString)
                    'Next
                    'MsgBox(vMarkt)
                    'MsgBox(file.Name & vbNewLine & vMarkt & vbNewLine & vDatum)
                    Me.TBGERAETE_NOTINLISTTableAdapter.cmdDeleteGeraete(vVertrag)

                    If XMLReader(file.FullName, file.Name, vMarkt, vDatum, vVertrag, MANDANTEN_KZ, SUPPLYWATCH_AKTIV) = False Then
                        'MsgBox("Datei: " & vbNewLine & file.FullName & vbNewLine & " wurde nicht verarbeitet!", MsgBoxStyle.Exclamation, "Achtung:")
                        Anzahl_Dateien = Anzahl_Dateien - 1
                    End If
                    Progress += 75
                    Gesamtfiles += -1
                    bwXMLverarbeiten.ReportProgress(Progress)
                End If
            Next
            If Anzahl_Dateien <> 0 Then
                MsgBox("Es wurden " & Anzahl_Dateien & " Dateien erfolgreich verarbeitet!", MsgBoxStyle.Information, "Erfolgsmeldung:")
                Me.Wertehilfen_fuellen()
            Else
                MsgBox("Keine Dateien zum Verarbeiten vorhanden!" & vbNewLine & "Überwachter Ordner: " & vbNewLine & pathImport, MsgBoxStyle.Exclamation, "Achtung:")
                bwXMLverarbeiten.CancelAsync()
            End If

        Catch ex As Exception
            MsgBox(ex.Message, MsgBoxStyle.Critical, "Fehler bei bwXMLverarbeiten:")
        End Try

    End Sub
    Private Sub bwBestellungenverarbeiten_RunWorkerCompleted(ByVal sender As Object, ByVal e As System.ComponentModel.RunWorkerCompletedEventArgs)

        If e.Cancelled Then
            MsgBox("Der Importvorgang wurde abgebrochen.", MsgBoxStyle.Information, "Vorgang abgebrochen")
        ElseIf e.Error IsNot Nothing Then
            ' MsgBox("Fehler")
        Else
            'frmImport_Report.ShowDialog()
            ' MsgBox("Fertig")
        End If

        Me.tsProgressBar.Visible = False
        tslbl_Files.Visible = False
        Me.Cursor = Cursors.Default
    End Sub
    Private Sub bwXMLverarbeiten_RunWorkerCompleted(ByVal sender As Object, ByVal e As System.ComponentModel.RunWorkerCompletedEventArgs)

        If e.Cancelled Then
            MsgBox("Der Importvorgang wurde abgebrochen.", MsgBoxStyle.Information, "Vorgang abgebrochen")
        ElseIf e.Error IsNot Nothing Then
            ' MsgBox("Fehler")
        Else
            'frmImport_Report.ShowDialog()
            ' MsgBox("Fertig")
        End If

        Me.tsProgressBar.Visible = False
        tslbl_Files.Visible = False
        Me.tsbtnAbbrechen.Visible = False
        Me.Cursor = Cursors.Default
    End Sub
    Private Sub bwXMLverarbeiten_ProgressChanged(ByVal sender As Object, ByVal e As System.ComponentModel.ProgressChangedEventArgs)
        'Me.Cursor = Cursors.WaitCursor
        'MsgBox(e.ProgressPercentage)
        Dim percent As Integer = e.ProgressPercentage
        'MsgBox(percent & vbNewLine & e.ProgressPercentage)
        Me.tsProgressBar.Value = percent
        tslbl_Files.Text = "Noch zu verarbeiten: " & Gesamtfiles & " File(s)"
        'If e.ProgressPercentage = 25 Then
        '    'Me.tsProgressBar.Minimum = 0
        '    'Me.tsProgressBar.Maximum = 2
        '    Me.tsProgressBar.Value = e.ProgressPercentage
        'ElseIf e.ProgressPercentage = -3 Then
        '    'Me.lblProfilname.Text = Me._EmailProfile.Profilname
        '    'Me.lblDatei.Text = ""
        'ElseIf e.ProgressPercentage = -2 Then
        '    Me.tsProgressBar.Value += 1
        'ElseIf e.ProgressPercentage = -1 Then
        '    'Me.lblDatei.Text = Me.aktivesDokument.aName
        '    Me.tsProgressBar.Value += 1
        'Else
        '    Me.tsProgressBar.Minimum = 0
        '    Me.tsProgressBar.Maximum = e.ProgressPercentage
        '    Me.tsProgressBar.Value = 0
        'End If
    End Sub
    Private Sub bwXLSverarbeiten_ProgressChanged(ByVal sender As Object, ByVal e As System.ComponentModel.ProgressChangedEventArgs)
        'Me.Cursor = Cursors.WaitCursor
        'MsgBox(e.ProgressPercentage)
        Dim percent As Integer = e.ProgressPercentage
        'MsgBox(percent & vbNewLine & e.ProgressPercentage)
        Me.tsProgressBar.Value = percent
        tslbl_Files.Text = "Noch zu verarbeiten: " & Gesamtfiles & " File(s)"
    End Sub

    Sub Export_Send_Data()
        Try
            Me.Cursor = Cursors.WaitCursor
            ClassBWProfileExport.Init()
            Dim dateiname As String
            If ClassBWProfileExport.Profile IsNot Nothing Then
                ClassLogger.Init("", "EmailReporting_", False)
                'Durchlauf für jedes Profil
                For Each item As ClassBWProfilExport In ClassBWProfileExport.Profile
                    _EmailProfile = item
                    ' wenn das selektierte Profil gefunden wurde
                    If Me._EmailProfile IsNot Nothing Then
                        If Me._EmailProfile.Days <> "0000000" Or Me._EmailProfile.Days <> "" Then
                            Dim Dayofweek As Integer = My.Computer.Clock.LocalTime.DayOfWeek
                            If (Me._EmailProfile.Days.Substring(Dayofweek - 1, 1) = 1) And CDate(Me._EmailProfile._lastExport).ToShortDateString <> Now.Today.ToShortDateString Then
                                'Verarbeitung soll heute durchgeführt werden
                                'MsgBox("Soll heute ausgeführt werden" & vbNewLine & My.Computer.Clock.LocalTime.DayOfWeek & vbNewLine & Me._EmailProfile.Days.Substring(Dayofweek - 1, 1))
                                ClassLogger.Add("", False)
                                ClassLogger.Add("Beginn der Exportverarbeitung : " & Now, False)
                                ClassLogger.Add(">> Starte Verarbeitung für Profil: " & _EmailProfile.Profilname, False)

                                ' dient zum Überprüfen auf Fehler
                                Dim Fehler As Boolean = False
                                Dim result As String = ""
                                Dim verknüpfungZähler As Integer = 0

                                ' SQL-String für aktuelle Verknüpfung laden
                                Dim SqlString As String = Me._EmailProfile.vSQL_Anweisung

                                ' wenn kein Fehler aufgetreten ist
                                If Not Fehler Then
                                    Try
                                        Dim _dir1 As New IO.DirectoryInfo(Me._EmailProfile.Path & "\Archiv")
                                    Catch ex As Exception
                                        IO.Directory.CreateDirectory(Me._EmailProfile.Path & "\Archiv")
                                    End Try
                                    Dim _dir As New IO.DirectoryInfo(Me._EmailProfile.Path & "\Archiv")
                                    If _dir.Exists = False Then
                                        IO.Directory.CreateDirectory(Me._EmailProfile.Path & "\Archiv")
                                    End If
                                    Dim SQL_ergebnis = ""
                                    dateiname = Me._EmailProfile.Path & "\" & My.Computer.Clock.LocalTime.Year & "_" & My.Computer.Clock.LocalTime.Month & "_" & My.Computer.Clock.LocalTime.Day & "_" & Me._EmailProfile.Profilname &
                                        "." & Me._EmailProfile.Format
                                    ' die SQL-Abfrage durchführen (liefert den Wert der in den windream-Index geschrieben werden soll)
                                    SQL_ergebnis = ExportDataFromMssqlDb(Me._EmailProfile.Profilname, dateiname, Me._EmailProfile.vSQL_Anweisung, My.Settings.ConfigConnectionString, Me._EmailProfile.Format)

                                    If SQL_ergebnis = "Nothing" Then
                                        result &= " => kein SQL-ergebnis"

                                    ElseIf SQL_ergebnis = "Fehler" Then
                                        Fehler = True
                                    End If

                                    If Not Fehler Then
                                        ClassLogger.Add(" => Erfolgsmeldung: Datei: '" & dateiname & "' wurde ERFOLGREICH ERZEUGT ", False)

                                        If Me._EmailProfile.Email = True Then
                                            Do While file_inuse(Resultdatei) = True
                                                System.Threading.Thread.Sleep(1000)
                                                ClassLogger.Add(" => Datei in Benutzung " & Now.ToShortTimeString, False)
                                            Loop
                                            ClassLogger.Add(" => Datei ist nicht mehr in Benutzung", False)
                                            Dim empfaenger As String()
                                            If Me._EmailProfile.Emailto.Contains(";") Then
                                                empfaenger = Me._EmailProfile.Emailto.Split(";")
                                            Else
                                                ReDim Preserve empfaenger(0)
                                                empfaenger(0) = Me._EmailProfile.Emailto
                                            End If
                                            ClassLogger.Add(" => Anzahl der Email-Empfänger: " & empfaenger.Count, False)
                                            'Für jeden Empfänger eine Neue Mail erzeugen
                                            For Each _mailempfaenger As String In empfaenger
                                                Dim email As New ClassBWExportEmail
                                                'Die Mail zusammenbauen und versenden
                                                With email
                                                    .Absender(Me._EmailProfile.Emailfrom, Me._EmailProfile.EmailAbsender)
                                                    .Empfänger(_mailempfaenger, _mailempfaenger)
                                                    .Nachricht(Me._EmailProfile.EmailBetreff, "<font face=""Arial"">" & Me._EmailProfile.EmailBody & "<br> Gesendet am: " & My.Computer.Clock.LocalTime.ToShortDateString & "-" &
                                                               My.Computer.Clock.LocalTime.ToLongTimeString & "</font>")
                                                    .Nachricht_Einstellungen(True, Net.Mail.MailPriority.Normal)
                                                    .Anlage(Resultdatei)
                                                    .Senden_MitAuthenzierung(Me._EmailProfile.EmailUser, Me._EmailProfile.EmailPW, Me._EmailProfile.EmailSMTP)
                                                    ClassLogger.Add(" => Email wurde ERFOLGREICH  an '" & _mailempfaenger & "' versendet!", False)
                                                End With
                                            Next

                                            If Me._EmailProfile.emailbest <> "" Then
                                                'Bestätigungsemail versenden
                                                Dim bempfaenger As String()
                                                If Me._EmailProfile.emailbest.Contains(";") Then
                                                    bempfaenger = Me._EmailProfile.emailbest.Split(";")
                                                Else
                                                    ReDim Preserve bempfaenger(0)
                                                    bempfaenger(0) = Me._EmailProfile.emailbest
                                                End If
                                                ClassLogger.Add(" => Anzahl der Bestätigungsempfänger: " & bempfaenger.Count, False)
                                                'Für jeden Empfänger eine Neue Mail erzeugen
                                                For Each _bmailempfaenger As String In bempfaenger
                                                    Dim bemail As New ClassBWExportEmail
                                                    With bemail
                                                        .Absender(Me._EmailProfile.Emailfrom, Me._EmailProfile.EmailAbsender)
                                                        .Empfänger(_bmailempfaenger, _bmailempfaenger)
                                                        .Nachricht(Me._EmailProfile.EmailBetreff & " - Bestätigung", "<font face=""Arial""> Email für das Profil: " & Me._EmailProfile.Profilname & " wurde erfolgreich versendet! <br> " & "Datei: " & dateiname & " <br> Gesendet am: " & My.Computer.Clock.LocalTime.ToShortDateString & "-" &
                                                                   My.Computer.Clock.LocalTime.ToLongTimeString & "</font>")
                                                        .Nachricht_Einstellungen(True, Net.Mail.MailPriority.Normal)
                                                        .Anlage(Resultdatei)
                                                        .Senden_MitAuthenzierung(Me._EmailProfile.EmailUser, Me._EmailProfile.EmailPW, Me._EmailProfile.EmailSMTP)
                                                        ClassLogger.Add(" => Bestätigungs-Email wurde ERFOLGREICH  an '" & _bmailempfaenger & "' versendet!", False)
                                                    End With
                                                Next
                                            End If
                                        End If
                                        'bw_Profil.ReportProgress(-2)
                                    End If
                                    ClassLogger.Add("", False)
                                    ClassLogger.Add("", False)
                                End If

                                ' wenn kein Fehler aufgetreten ist
                                If Not Fehler Then
                                    '###############################################################################################
                                    '#### Hintergrundverarbeitung ##################################################################
                                    _EmailProfile.lastExport = Now.Date.ToShortDateString
                                    _EmailProfile.Save(False)
                                    ' Dateiname extrahieren
                                    Dim sFile As String = IO.Path.GetFileName(dateiname)
                                    Dim Zielname As String = Me._EmailProfile.Path & "\Archiv\" & sFile
                                    MsgBox("Es wurde/n soeben eine/mehrere Reporting-Mail/s für das Profil: " & Me._EmailProfile.Profilname & " versendet!", MsgBoxStyle.Information, "Hinweis:")
                                    'System.IO.File.Move(dateiname, Zielname)
                                    'ClassLogger.Add(" => Datei erfolgreich in Archiv verschoben!", False)
                                    '#### Ende #####################################################################
                                    '###############################################################################################
                                Else
                                    ClassLogger.Add("Exportverarbeitung-ExportProfildaten", "Fehler bei ExportProfildaten für das Profil: " & Me._EmailProfile.Profilname)
                                End If
                                Fehler = False

                            Else

                            End If
                        Else

                        End If
                    Else

                    End If
                Next
            End If
        Catch ex As Exception
            MsgBox(ex.Message, MsgBoxStyle.Critical, "Fehler bei Export_Send_Data:")
        End Try
        Me.Cursor = Cursors.Default
    End Sub
    ' führt eine SQL-Anweisung auf der DB aus
    Public Function ExportDataFromMssqlDb(ByVal profilname As String, ByVal dateiname As String, ByVal selectAnweisung As String, ByVal _CS As String, ByVal Format As String) ' 
        Dim anzahl As Integer
        Try
            ClassLogger.Add(" => MS-SQL: Ausführung von MSSQL", False)
            ' die nötigen Variablen definieren

            Dim Connection As SqlConnection = Nothing
            Dim Command As SqlCommand = Nothing
            Dim DataAdapter As SqlDataAdapter = Nothing
            ' ConnectionString aufbauen (aus Settings auslesen)


            ' Verbindung zur Datenbank aufbauen
            Try
                Connection = New SqlConnection(_CS)
                Connection.Open()
            Catch ex As Exception
                ClassLogger.Add("ClassBGExportDatenbankzugriff.GetValueFromMssqlDb", "Verbindung zur Datenbank aufbauen", ex)
                ' DB-Connection schliessen
                Connection.Close()
                Return "Fehler"
            End Try

            Try
                ' Datenadapter definieren
                Dim da As New SqlDataAdapter(selectAnweisung, Connection)
                Dim ds As New DataSet
                da.Fill(ds)

                If ds.Tables(0).Rows.Count > 0 Then
                    'Setzt das Code-Format auf ASCII
                    Dim dt As DataTable = ds.Tables(0)
                    anzahl = ds.Tables(0).Rows.Count
                    If Format = "csv" Then
                        Resultdatei = ProduceCSV(dt, dateiname, True)

                    ElseIf Format = "xlsx" Then
                        Resultdatei = Produce_xlsx(ds, "Tabelle1", dateiname)
                    End If

                    Return ds.Tables(0).Rows.Count
                Else
                    Return Nothing
                End If

                Return True
            Catch ex As Exception
                If ex.Message.StartsWith("Ein COM-Objekt") = False Then
                    ClassLogger.Add("GetValueFromMssqlDb", "Datenabruf", ex)
                    ' DB-Connection schliessen
                    Return "Fehler"
                Else
                    Return anzahl
                End If
                Connection.Close()
            End Try
        Catch ex As Exception
            ' an dieser Stelle sollte jeder unvorhergesehene Fehler der Funktion abgefangen werden
            ClassLogger.Add("GetValueFromMssqlDb", "Ein unbekannter Fehler in GetValuesFromDb.", ex)
            Return "Fehler"
        End Try
    End Function
#Region "CSVExcelProducer"
    Public Shared Function ProduceCSV(ByVal dt As DataTable, ByVal dateiname As String, ByVal WriteHeader As Boolean)
        Dim newname As String = dateiname
        Do While System.IO.File.Exists(newname)
            newname = IO.Path.GetDirectoryName(dateiname) & "\" & Now.Hour & "_" & Now.Minute & "_" & IO.Path.GetFileName(dateiname)
        Loop
        Dim sw As New System.IO.StreamWriter(newname, False, System.Text.Encoding.Default)
        Dim i As Int32
        Dim j As Int32
        If (WriteHeader) Then
            Dim arr(dt.Columns.Count) As String
            For i = 0 To dt.Columns.Count - 1
                arr(i) = dt.Columns(i).ColumnName
                arr(i) = GetWriteableValue(arr(i))
            Next
            sw.WriteLine(String.Join(";", arr))
        End If

        For j = 0 To dt.Rows.Count - 1
            Dim dataArr(dt.Columns.Count - 1) As String
            For i = 0 To dt.Columns.Count - 1
                Dim o As Object = dt.Rows(j)(i)
                dataArr(i) = GetWriteableValue(o)
            Next
            sw.WriteLine(String.Join(";", dataArr))
        Next
        sw.Close()
        ClassLogger.Add(" ==> Datei: " & dateiname & " wurde erfolgreich erzeugt", False)
        Return newname
    End Function

    Public Shared Function GetWriteableValue(ByVal o As Object) As String
        If o Is Nothing OrElse IsDBNull(o) Then
            Return ""
        ElseIf (o.ToString().IndexOf(";") = -1) Then
            Return o.ToString()
        Else
            If o.ToString.Contains("; ") Then
                o.ToString.Replace("; ", "-")
            End If
            'Return "\"" + o.ToString() + " \ ""
        End If
    End Function
#End Region
    Private Function Produce_xlsx(ByVal vDataset As DataSet, ByVal vSheet_Name As String, ByVal Dateiname As String)
        Dim newname As String = Dateiname
        Do While System.IO.File.Exists(newname)
            newname = IO.Path.GetDirectoryName(Dateiname) & "\" & Now.Hour & "_" & Now.Minute & "_" & IO.Path.GetFileName(Dateiname)
        Loop
        Dim xlApp As Excel.Application
        Dim xlWorkBook As Excel.Workbook
        Dim xlWorkSheet As Excel.Worksheet
        Dim misValue As Object = System.Reflection.Missing.Value


        xlApp = New Excel.Application
        xlWorkBook = xlApp.Workbooks.Add(misValue)
        xlWorkSheet = xlWorkBook.Sheets(vSheet_Name)
        'xlWorkSheet.Cells(1, 1) = "http://vb.net-informations.com"
        xlsApp = xlApp
        'Schreiben der Daten
        'Die Datatable definieren
        Dim dt As DataTable
        dt = vDataset.Tables(0)

        'Add the column headings for the Customers
        Dim dc As DataColumn
        Dim iCols As Int32 = 0
        For Each dc In dt.Columns
            xlApp.Range("A1").Offset(0, iCols).Value = dc.ColumnName
            iCols += 1
        Next

        'Add the data
        Dim iRows As Int32
        For iRows = 0 To dt.Rows.Count - 1
            xlApp.Range("A2").Offset(iRows).Resize(1, iCols).Value = dt.Rows(iRows).ItemArray()
        Next
        With xlApp.ActiveSheet.Range("A1")
            .AutoFilter()
            .AutoFormat(Excel.XlRangeAutoFormat.xlRangeAutoFormatSimple) 'xlRangeAutoFormatSimple
        End With
        'Ende
        xlWorkSheet.SaveAs(newname)
        killExcelInstanceById(xlApp)

        releaseObject(xlApp)
        releaseObject(xlWorkBook)
        releaseObject(xlWorkSheet)
        Return newname
        'xlWorkBook.Close()
        'xlApp.Quit()
    End Function
    ''Beenden eines speziellen Excel Prozesses, anhand seiner Id
    Private Shared Sub killExcelInstanceById(ByRef xlsApp As Excel.Application)
        Dim processId As IntPtr
        ''API Funktion, out val: processId
        GetWindowThreadProcessId(xlsApp.Hwnd, processId)
        ''Prozess erstellen
        Dim excelProcess As Process = Process.GetProcessById(processId.ToInt32())
        '  MsgBox("processId: " & processId.ToString & vbNewLine & excelProcess.ProcessName)
        ''die lang ersehnte Erlösung, für den speziellen Excel Process der XlsApp :)
        excelProcess.Kill()
        ' MsgBox("wurde gekillt")
    End Sub


    Private Sub releaseObject(ByVal obj As Object)
        Try
            System.Runtime.InteropServices.Marshal.ReleaseComObject(obj)
            obj = Nothing
        Catch ex As Exception
            obj = Nothing
        Finally
            GC.Collect()
        End Try
    End Sub
    ''Zugang zur API ''user32'' 
    Private Declare Function GetWindowThreadProcessId Lib "user32" (ByVal hWnd As Integer, ByRef lpdwProcessId As IntPtr) As IntPtr
    Public Class Insert_String
        Public Typ As String
        Public Value As String
        Public Sub New(ByVal lBezeichnung As String, ByVal iValue As String)
            Typ = lBezeichnung
            Value = iValue
        End Sub

        Public Sub New()
        End Sub
    End Class

    Private Function XMLReader(filepath As String, filename As String, Markt As String, vDatum As String, vVertrag As String, KD_KZ As String, SW_aktiv As Boolean)
        Dim file_verarbeitet As Boolean
        'Direkt überprüfen ob der Vertrag gültig ist!
        If Me.TBVERTRAG_NOTEXISTTableAdapter.cmdVertragNotIn(vVertrag) > 0 Then
            MsgBox("Vertrag " & vVertrag & " existiert nicht!!!!" & vbNewLine & "Datei wird in Ordner:" & vbNewLine & pathImport & "\Fehler\" & vbNewLine & " verschoben", MsgBoxStyle.Critical, "Achtung:")
            marker &= vbNewLine & "==> VERTRAG " & vVertrag & " EXISTIERT NICHT"
            MoveFile(filepath, filename, pathImport, pathImportArchiv, True)
            file_verarbeitet = False
            Return file_verarbeitet
            Exit Function
        End If
        Dim A3DuplexSheets As Integer = 0,
            A3SimplexSheets As Integer = 0,
            A4DuplexSheets As Integer = 0,
            A4SimplexSheets As Integer = 0,
            A3ColorTotalImpressions As Integer = 0,
            A3MonoTotalImpressions As Integer = 0,
            A4ColorTotalImpressions As Integer = 0,
            A4MonoTotalImpressions As Integer = 0,
            A3TotalImages As Integer = 0,
            A4TotalImages As Integer = 0,
            PPUTotalCopyPageCount As Integer = 0,
            ScanA3Total As Integer = 0,
            ScanA4Total As Integer = 0
        Dim AverageBlackCoverage As Decimal = 0,
            AverageCyanCoverage As Decimal = 0,
            AverageMagentaCoverage As Decimal = 0,
            AverageYellowCoverage As Decimal = 0

        Dim _Feldbezeichnung, _xmlKnoten As String

        Geraet_inserted = False

        Dim Supply_inserted As Boolean = False
        Dim _startInsert As Boolean = False

        'Try
        'If Meldedatum_eintragen(Markt, vDatum) = False Then
        '    MsgBox("Achtung: Meldedatum konnte nicht eingetragen werden!" & vbNewLine & "Bitte verständigen sie: Digital Data " & vbNewLine & "Einlesevorgang wird fortgesetzt!")
        'End If
        Dim vGeraeteZaehler As Integer = 1
        Dim LastGERAETID As Integer

        ' Wir benötigen einen XmlReader für das Auslesen der XML-Datei 
        Dim _XMLReader As Xml.XmlReader = New Xml.XmlTextReader(filepath)
        marker = "############################################################################"
        ClassLoggerSW.Add("############################################################################", False)
        marker = "Start des Verarbeitens für File: " & filepath
        ClassLoggerSW.Add("Start des Verarbeitens für File: " & filepath, False)
        ClassLoggerSW.Add("Uhrzeit: " & Now, False)
        marker &= vbNewLine & Now
        ' Es folgt das Auslesen der XML-Datei 
        With _XMLReader
            Dim Geraetezaehler As Integer = 0

            Do While .Read ' Es sind noch Daten vorhanden 
                ' Welche Art von Daten liegt an? 
                Select Case .NodeType

                    ' Ein Element 
                    Case Xml.XmlNodeType.Element
                        If .Name = "Device" Or .Name = "Devices" Then
                            _xmlKnoten = .Name
                            If _xmlKnoten = "Device" Then
                                'MsgBox("Es folgt ein Element vom Typ " & _xmlKnoten & vbNewLine & "Zähler: " & vGeraeteZaehler, MsgBoxStyle.Information, .HasValue.ToString)
                                ClassLoggerSW.Add("## NEUES GERÄT - Geräte-Zähler: " & vGeraeteZaehler & " ##", False)
                                ClassLoggerSW.Add("Beginn: " & Now, False)
                                marker &= vbNewLine & "## NEUES GERÄT - Geräte-Zähler: " & vGeraeteZaehler & "##"
                                marker = "################# ABLAUFVERFOLGUNG für Device ###################"
                                'Zurücksetzen damit der Insert erfolgen kann
                                Geraet_inserted = False
                                ' Jetzt die gesamten Daten durchlaufen um das Gerät zu inserten
                                'MsgBox(ListeInsert.Count.ToString)
                            End If
                        Else
                            'Hier ist klar, es handelt sich um eine Deviceeigenschaft/ ein Supply
                            _xmlKnoten = .Name
                            _Feldbezeichnung = .Name
                            If _Feldbezeichnung.ToLower = "averageyellowcoverage" Then
                                _startInsert = True
                            End If
                            'MsgBox("Es folgt ein Element vom Typ " & _xmlKnoten & vbNewLine & "Zähler: " & vGeraeteZaehler, MsgBoxStyle.Information, .HasValue.ToString)
                        End If

                    Case Xml.XmlNodeType.Text
                        ' MsgBox("Es folgt ein Text: " & .Value)
                        'If Geraetezaehler <> 0 or _xmlKnoten = "Device" Then
                        If .Value <> "<Nicht unterstützt>" Or .Value <> "<Anmeldedaten erforderlich>" Then
                            marker &= vbNewLine & "Feldbezeichnung: " & _Feldbezeichnung & " - Value: " & .Value
                            'MsgBox(Feldbezeichnung.ToLower)
                            Dim Insert As New Insert_String(_Feldbezeichnung, .Value)
                            ListeInsert.Add(Insert)
                        Else
                            'MsgBox(" .Value = <Nicht unterstützt> Or .Value = <Anmeldedaten erforderlich>", MsgBoxStyle.Critical, vGeraete_Bez & " - " & vSerienNr)
                        End If

                        If _startInsert = True Then   'Es kann der Insert erfolgen, da der letzte EigenschaftenTag ausgewertet wurde

                            'If vSerienNrGeraet <> "<Unbekannt>" Or vSerienNrGeraet <> "<Nicht unterstützt>" Or vSerienNrGeraet <> "<Nicht gemeldet>" Then
                            'Den Geräteverfolgungsdatensatz inserten
                            'MsgBox("Vertrag: " & vVertrag & " Gerät: " & vGeraete_Bez & vbNewLine & "ModelNR: " & vModelNr & vbNewLine & "IP: " & vIP & vbNewLine & "SN:" & vSerienNrGeraet & vbNewLine & "PC: " & vPagecount & vbNewLine & _
                            '      "File: " & filename & vbNewLine & Markt & vbNewLine & vDatum, MsgBoxStyle.Information, "Insert Gerät")

                            marker &= vbNewLine & "2. Den Geräteverfolgungsdatensatz für Seriennummer " & vSerienNrGeraet & " inserten"

                            'ERST den Gerätekopf inserten
                            If Insert_Geraet(Markt, filename, vDatum, vVertrag, KD_KZ) = True Then
                                'Letzte Geräte ID
                                LastGERAETID = Me.TBGERAETTableAdapter.cmdGetGERAET_ID(vSerienNrGeraet)
                                ClassLoggerSW.Add(" ==> Geraete-ID:" & LastGERAETID.ToString, False)
                                Geraet_inserted = True
                                _startInsert = False
                                'Jetzt der Insert der zugehörigen Supplies
                                If SW_aktiv = True Then
                                    'NUR WENN SW AKTIV ist
                                    If Insert_Supply(filename, vSerienNrGeraet, LastGERAETID, vDatum) = True Then

                                    End If
                                Else

                                End If
                                ListeInsert.Clear()
                                'Hochsetzen des Gerätezählers
                                vGeraeteZaehler = vGeraeteZaehler + 1
                                'Geraetezaehler = .Name & " " & vGeraeteZaehler
                                Geraet_inserted = False
                                Supply_inserted = False
                                ClassLoggerSW.Add(" Daten zu Gerät " & vSerienNrGeraet & " wurden erfolgreich verarbeitet! - " & Now, False)
                                marker &= vbNewLine & "################# ENDE ABLAUFVERFOLGUNG GERÄT#########################"
                                ClassLoggerSW.Add("", False)

                            Else
                                _startInsert = False
                                Return file_verarbeitet = False
                            End If
                            'Else
                            '    If vSerienNrGeraet = "<Nicht gemeldet>" Then
                            '        ' MsgBox("<Nicht gemeldet>")
                            '    End If
                            'End If
                        End If

                        ' Ein Kommentar 
                        'Case Xml.XmlNodeType.Comment
                        '    MsgBox("Es folgt ein Kommentar: " & .Value)
                End Select

            Loop  ' Weiter nach Daten schauen 
            '#######################################################################################
            ' MsgBox("Letzter Datensatz")

            .Close()  ' XMLTextReader schließen 
        End With
        'Die XML-File bei Erfolg verschieben
        MoveFile(filepath, filename, pathImport, pathImportArchiv)
        marker &= vbNewLine & "4. MoveFile erfolgreich durchlaufen"
        ClassLoggerSW.Add("############## ==> File erfolgreich verarbeitet - " & Now & "##################################", False)
        ClassLoggerSW.Add("", False)
        file_verarbeitet = True

        Return file_verarbeitet
        'Catch ex As Exception
        '    ClassLoggerSW.Add("###################### ACHTUNG FEHLER:- " & Now & " " & Now.Millisecond & " #############################################", False)
        '    ClassLoggerSW.Add("Marker #############################################################", False)
        '    ClassLoggerSW.Add(marker, False)
        '    ClassLoggerSW.Add("###################################################################", False)
        '    ClassLoggerSW.Add("FEHLERMELDUNG: " & ex.Message, False)
        '    MsgBox("Fehler bei Dateiverarbeitung: " & vbNewLine & "Datei: " & filename & vbNewLine & "Gerät-SN Nummer: " & vSerienNrGeraet & vbNewLine & ex.Message, MsgBoxStyle.Critical, "Fehler bei XML-Reader")
        '    MsgBox("Überprüfen Sie die LogFile", MsgBoxStyle.Critical, "Hinweis:")
        '    file_verarbeitet = False
        '    Return file_verarbeitet
        'End Try
    End Function
    Public Function Insert_Geraet(Markt As String, filename As String, Datum As String, vVertrag As String, vKD_KZ As String)
        Dim vPagecount, A3DuplexSheets, A3SimplexSheets, A4DuplexSheets, A4SimplexSheets, A3TotalColorImpressions, A3TotalMonoImpression, A4TotalMonoImpressions, A4ColorTotalImpressions As Integer
        Dim ScanA3TotalImages, ScanA4TotalImages, FaxIncoming As Integer
        Dim AverageBlackCoverage, AverageCyanCoverage, AverageMagentaCoverage, AverageYellowCoverage As Double
        vSerienNrGeraet = ""

        Try
            vPORT_DISPLAY = Nothing
            For i = 0 To ListeInsert.Count - 1
                Dim Value As String = ListeInsert.Item(i).Value
                Select Case ListeInsert.Item(i).Typ.ToLower
                    Case "ipv4address".ToLower
                        vIP = Value
                        marker &= vbNewLine & "- ipv4address: " & vIP

                    Case "PortDisplayString".ToLower
                        vPORT_DISPLAY = Value
                        marker &= vbNewLine & "- portdisplaystring: " & vPORT_DISPLAY
                    Case "displayname".ToLower
                        vGeraete_Bez = Value
                        marker &= vbNewLine & "- vgeraete_bez: " & vGeraete_Bez
                    Case "serialnumber".ToLower
                        If vSerienNrGeraet = "" Then
                            vSerienNrGeraet = Value
                            If vSerienNrGeraet.ToLower = "<unbekannt>" Or vSerienNrGeraet.ToLower = "<nicht unterstützt>" Or vSerienNrGeraet.ToLower = "<unknown>" Or
                                vSerienNrGeraet.ToLower.StartsWith("<") Or vSerienNrGeraet.Length < 6 Or vSerienNrGeraet.ToLower = "<needs credentials>" Then
                                vSerienNrGeraet = "<nicht gemeldet>"
                            End If

                            marker &= vbNewLine & "- vseriennrgeraet: " & vSerienNrGeraet
                        End If

                        ' msgbox("1 " & vseriennrgeraet)
                    Case "pagecount".ToLower
                        If IsNumeric(Value) Then
                            vPagecount = Value
                        Else
                            vPagecount = "0"
                        End If
                        marker &= vbNewLine & "- vpagecount: " & vPagecount
                    Case "pagecountdigitalsend"
                        If IsNumeric(Value) Then
                            vPagecount = Value
                        Else
                            vPagecount = "0"
                        End If
                        marker &= vbNewLine & "- vpagecount: " & vPagecount
                    Case "printusage.totalimpressions"
                        If IsNumeric(Value) Then
                            vPagecount = Value
                        Else
                            vPagecount = "0"
                        End If
                        marker &= vbNewLine & "- printusage.totalimpressions: " & vPagecount


                    Case "devicemodelnumber".ToLower
                        If Value = "<unbekannt>" Or Value = "<nicht unterstützt>" Or Value.StartsWith("<") Or Value Is Nothing Then
                            vModelNr = "<nicht unterstützt>"
                        Else
                            vModelNr = Value
                        End If
                        marker &= vbNewLine & "- vmodelnr: " & vModelNr
                        '######### A3 Duplex Sheets ##############
                    Case "printsheetusage.isoandjisa3.duplexsheets".ToLower
                        If Value = "<unbekannt>" Or Value = "<nicht unterstützt>" Or Value.StartsWith("<") Or Value Is Nothing Then
                            A3DuplexSheets = 0
                        Else
                            A3DuplexSheets = Value
                        End If
                        '######### A3 Simplex Sheets ##############
                    Case "printsheetusage.isoandjisa3.simplexsheets".ToLower
                        If Value = "<unbekannt>" Or Value = "<nicht unterstützt>" Or Value.StartsWith("<") Or Value Is Nothing Then
                            A3SimplexSheets = 0
                        Else
                            A3SimplexSheets = Value
                        End If
                        '######### A4 Duplex Sheets ##############              
                    Case "printsheetusage.isoandjisa4.duplexsheets".ToLower
                        If Value = "<unbekannt>" Or Value = "<nicht unterstützt>" Or Value.StartsWith("<") Or Value Is Nothing Then
                            A4DuplexSheets = 0
                        Else
                            A4DuplexSheets = Value
                        End If
                        '######### A4 Simplex Sheets ##############   
                    Case "printsheetusage.isoandjisa4.simplexsheets".ToLower
                        If Value = "<unbekannt>" Or Value = "<nicht unterstützt>" Or Value.StartsWith("<") Or Value Is Nothing Then
                            A4SimplexSheets = 0
                        Else
                            A4SimplexSheets = Value
                        End If
                        '######### A3 Total Color ##############   
                    Case "printusage.isoandjisa3.totalcolorimpressions".ToLower
                        If Value = "<unbekannt>" Or Value = "<nicht unterstützt>" Or Value.StartsWith("<") Or Value Is Nothing Then
                            A3TotalColorImpressions = 0
                        Else
                            A3TotalColorImpressions = Value
                        End If
                    Case "printusage.isoandjisa3.color.totalimpressions".ToLower
                        If Value = "<unbekannt>" Or Value = "<nicht unterstützt>" Or Value.StartsWith("<") Or Value Is Nothing Then
                            A3TotalColorImpressions = 0
                        Else
                            A3TotalColorImpressions = Value
                        End If
                        '######### A3 Total Mono ##############   
                    Case "printusage.isoandjisa3.totalmonoimpressions".ToLower
                        If Value = "<unbekannt>" Or Value = "<nicht unterstützt>" Or Value.StartsWith("<") Or Value Is Nothing Then
                            A3TotalMonoImpression = 0
                        Else
                            A3TotalMonoImpression = Value
                        End If
                    Case "printusage.isoandjisa3.mono.totalimpressions".ToLower
                        If Value = "<unbekannt>" Or Value = "<nicht unterstützt>" Or Value.StartsWith("<") Or Value Is Nothing Then
                            A3TotalMonoImpression = 0
                        Else
                            A3TotalMonoImpression = Value
                        End If
                        '######### A4 Total Color ##############   
                    Case "printusage.isoandjisa4.totalcolorimpressions".ToLower
                        ' PrintUsage.ISOandJISA4.Color.TotalImpressions()
                        If Value = "<unbekannt>" Or Value = "<nicht unterstützt>" Or Value.StartsWith("<") Or Value Is Nothing Then
                            A4ColorTotalImpressions = 0
                        Else
                            A4ColorTotalImpressions = Value
                        End If
                    Case "printusage.isoandjisa4.color.totalimpressions".ToLower
                        ' PrintUsage.ISOandJISA4.Color.TotalImpressions()
                        If Value = "<unbekannt>" Or Value = "<nicht unterstützt>" Or Value.StartsWith("<") Or Value Is Nothing Then
                            A4ColorTotalImpressions = 0
                        Else
                            A4ColorTotalImpressions = Value
                        End If
                        '######### A4 Total Mono ##############   
                    Case "printusage.isoandjisa4.totalmonoimpressions".ToLower
                        If Value = "<unbekannt>" Or Value = "<nicht unterstützt>" Or Value.StartsWith("<") Or Value Is Nothing Then
                            A4TotalMonoImpressions = 0
                        Else
                            A4TotalMonoImpressions = Value
                        End If
                    Case "scanusage.isoandjisa3.totalimages".ToLower
                        If Value = "<unbekannt>" Or Value = "<nicht unterstützt>" Or Value.StartsWith("<") Or Value Is Nothing Then
                            ScanA3TotalImages = 0
                        Else
                            ScanA3TotalImages = Value
                        End If
                    Case "scanusage.isoandjisa4.totalimages".ToLower
                        If Value = "<unbekannt>" Or Value = "<nicht unterstützt>" Or Value.StartsWith("<") Or Value Is Nothing Then
                            ScanA4TotalImages = 0
                        Else
                            ScanA4TotalImages = Value
                        End If
                    Case "pagecountfaxincoming"
                        If Value = "<unbekannt>" Or Value = "<nicht unterstützt>" Or Value.StartsWith("<") Or Value Is Nothing Then
                            FaxIncoming = 0
                        Else
                            FaxIncoming = Value
                        End If
                    Case "averageblackcoverage".ToLower
                        If Value = "<unbekannt>" Or Value = "<nicht unterstützt>" Or Value.StartsWith("<") Or Value Is Nothing Then
                            AverageBlackCoverage = CDec(0)
                        Else
                            AverageBlackCoverage = CDec(Value)
                        End If
                    Case "averagecyancoverage".ToLower
                        If Value = "<unbekannt>" Or Value = "<nicht unterstützt>" Or Value.StartsWith("<") Or Value Is Nothing Then
                            AverageCyanCoverage = CDec(0)
                        Else
                            AverageCyanCoverage = CDec(Value)
                        End If
                    Case "averagemagentacoverage".ToLower
                        If Value = "<unbekannt>" Or Value = "<nicht unterstützt>" Or Value.StartsWith("<") Or Value Is Nothing Then
                            AverageMagentaCoverage = CDec(0)
                        Else
                            AverageMagentaCoverage = CDec(Value)
                        End If
                    Case "averageyellowcoverage".ToLower
                        If (Value = "<unbekannt>") Or (Value = "<nicht unterstützt>") Or (Value.StartsWith("<")) Or (Value Is Nothing) Then
                            AverageYellowCoverage = CDec(0)
                        Else
                            AverageYellowCoverage = CDec(Value)
                        End If
                End Select
            Next
            If vPORT_DISPLAY Is Nothing Then
                vPORT_DISPLAY = "NOT SPECIFIED"
            End If
            'Jetzt könnte der Insert für das Gerät erfolgen
            'If vSerienNrGeraet <> "<Nicht gemeldet>" Then
            ' MsgBox(vVertrag)

            'Den Geräteverfolgungsdatensatz inserten
            'MsgBox("Vertrag: " & vVertrag & " Gerät: " & vGeraete_Bez & vbNewLine & "ModelNR: " & vModelNr & vbNewLine & "IP: " & vIP & vbNewLine & "SN:" & vSerienNrGeraet & vbNewLine & "PC: " & vPagecount & vbNewLine & _
            '      "File: " & filename & vbNewLine & Markt & vbNewLine & vDatum, MsgBoxStyle.Information, "Insert Gerät")
            '  MsgBox("1.1 " & vSerienNrGeraet)
            marker &= vbNewLine & "2. Den Geräteverfolgungsdatensatz " & vSerienNrGeraet & " inserten"
            '    MsgBox("2 " & vSerienNrGeraet)
            Me.TBGERAETE_VERFOLGUNGTableAdapter.cmdinsert(vGeraete_Bez, vIP, vSerienNrGeraet, vPagecount, Markt, filename, Datum, vVertrag, vModelNr, A3DuplexSheets, A3SimplexSheets, A4DuplexSheets, A4SimplexSheets, A3TotalColorImpressions,
                                                       A3TotalMonoImpression, A4TotalMonoImpressions, A4ColorTotalImpressions, AverageBlackCoverage, AverageCyanCoverage, AverageMagentaCoverage, AverageYellowCoverage, ScanA3TotalImages, ScanA4TotalImages, vKD_KZ, FaxIncoming, ScanA4TotalImages, ScanA3TotalImages, vPORT_DISPLAY)

            ClassLoggerSW.Add(" ==> Gerät inserted: " & vGeraete_Bez & " - " & vSerienNrGeraet, False)
            Return True
            'Else
            'Return False
            ''If vSerienNrGeraet = "<Nicht gemeldet>" Then
            ''    ' MsgBox("<Nicht gemeldet>")
            ''End If
            'End If
        Catch ex As Exception
            ClassLoggerSW.Add("###################### ACHTUNG FEHLER:- " & Now & " " & Now.Millisecond & " #############################################", False)
            ClassLoggerSW.Add("Marker #############################################################", False)
            ClassLoggerSW.Add(marker, False)
            ClassLoggerSW.Add("###################################################################", False)
            ClassLoggerSW.Add("FEHLERMELDUNG: " & ex.Message, False)
            MsgBox("Fehler bei Insert des Gerätedatensatzes:" & vbNewLine & "Datei: " & filename & vbNewLine & "Gerät-SN Nummer: " & vSerienNrGeraet & vbNewLine & ex.Message, MsgBoxStyle.Critical, "Fehler bei InsertGerät")

            MsgBox("Überprüfen Sie die LogFile", MsgBoxStyle.Critical, "Hinweis:")
            Return False
        End Try

    End Function
    Public Function Insert_Supply(vfilename As String, vSerienNrGeraet As String, LastGERAETID As String, vDatum As String)
        Try
            Dim vSupply_String, vLevel, vPartNumber, vProductNumber, vSerial As String
            Dim insertSupply As Boolean = False
            '###### Der Insert der Supplys - Hierfür die List noch einmal durchlaufen
            For i = 0 To ListeInsert.Count - 1
                Dim Value As String = ListeInsert.Item(i).Value
                Dim SupplyString As String = ListeInsert.Item(i).Typ.ToLower

                'Berücksichtige nur Supply und Marker Strings
                If SupplyString.ToLower.StartsWith("supp") Or SupplyString.ToLower.StartsWith("marker") Then
                    'MsgBox("Value: " & Value & vbNewLine & "SupplyString: " & SupplyString)
                    'Splitten des XML-Flags - Ziel: Typen bestimmen und Parameter auslesen
                    Dim Arr() As String
                    Dim _xmltag As String
                    Arr = ListeInsert.Item(i).Typ.Split(".")
                    Dim _TypID As Integer
                    'Dim _parameter As String
                    If Arr.Length > 1 Then
                        If Arr(1) = "All" Then
                            'ein Supply 
                            _xmltag = Arr(0) & "." & Arr(1) & "." & Arr(2)
                            _TypID = 1
                            ' MsgBox(Arr(1).ToString, MsgBoxStyle.Information, "Arr(1) = All")
                        ElseIf Arr(0).ToString.EndsWith("Kit") Then
                            'Transfer oder Fuserkit
                            _xmltag = Arr(0)
                            _TypID = 4
                        ElseIf Arr(0) = "Supplies" And Arr(1).ToLower = "maintenancekit" Then
                            'Maintenance Kit
                            _xmltag = Arr(0) & "." & Arr(1)
                            _TypID = 5
                        Else
                            'eine Drum
                            _xmltag = Arr(0)
                            _TypID = 2
                            ' MsgBox(Arr(0).ToString, MsgBoxStyle.Information, "Else Drum")
                        End If
                    Else
                        'Entweder ein Marker Supply
                        If Arr(0).ToString.ToLower.StartsWith("markersupplies") Then
                            'ein MarkerSupply
                            _xmltag = Arr(0)
                            _TypID = 3
                            'MsgBox(Arr(0).ToString, MsgBoxStyle.Information, "Arr(0).StartsWith(Markersupplies")
                        End If
                    End If
                    If vSupply_String = "" Then
                        'erstes Supply-Tag
                        vSupply_String = _xmltag
                        'MsgBox("ERSTES Supply: " & _xmltag)
                        'zurücksetzten der Insert-Parameter
                        vPartNumber = ""
                        vProductNumber = ""
                        vLevel = ""
                        vSerial = ""
                    End If
                    'Select Case _TypID
                    '    Case 1 'Supply/Trasnsfer/Fuser
                    '        _parameter = Arr(3)
                    '    Case 2
                    '        _parameter = Arr(1)
                    '    Case 3
                    '        _parameter = Arr(0)
                    'End Select
                    If vSupply_String <> _xmltag Then
                        'Neues Supply
                        'MsgBox("ein NEUES Supply" & vbNewLine & vSupply_String, MsgBoxStyle.Information, _TypID.ToString)
                        vSupply_String = _xmltag
                        'zurücksetzten der Insert-Parameter
                        vPartNumber = ""
                        vProductNumber = ""
                        vLevel = ""
                        vSerial = ""
                    Else
                        'MsgBox("Folgewert")
                    End If

                    If SupplyString.ToLower.EndsWith("partnumber") Then
                        vPartNumber = Value
                        'If vSupply_String.EndsWith("SupplyTransferKit") And vSerienNrGeraet = "JPBTB4GHG1" Then
                        '    MsgBox(Trim(Value).ToString)
                        'End If

                        If vPartNumber = "<Unbekannt>" Or Trim(vPartNumber) = "<Nicht unterstützt>" Or Trim(Value).StartsWith("<") Then
                            vPartNumber = "<Nicht gemeldet>"
                        End If
                    End If
                    If SupplyString.ToLower.EndsWith("level") Then
                        vLevel = Value
                        'If vSupply_String.EndsWith("SupplyTransferKit") And vSerienNrGeraet = "JPBTB4GHG1" Then
                        '    MsgBox(Trim(Value).ToString)
                        'End If
                        If IsNumeric(vLevel) = False Then
                            vLevel = "201"
                        End If
                    End If
                    If SupplyString.ToLower.EndsWith("serialnumber") Then
                        vSerial = ""
                        vSerial = Value
                        'If vSupply_String.EndsWith("SupplyTransferKit") And vSerienNrGeraet = "JPBTB4GHG1" Then
                        '    MsgBox(Trim(Value).ToString)
                        'End If
                        If vSerial = "<Unbekannt>" Or Trim(Value) = "<Nicht unterstützt>" Or Trim(Value).StartsWith("<") Then
                            vSerial = "<Nicht gemeldet>"
                        End If
                        If vSerial.Length = 0 Or vSerial = "" Then
                            vSerial = "<Nicht gemeldet>"
                        End If
                    End If
                    If SupplyString.ToLower.EndsWith("approxpercentremaining") Or SupplyString.ToLower.EndsWith("approxpercentremaining title") Then
                        vLevel = Value
                        'If vSupply_String.EndsWith("SupplyTransferKit") And vSerienNrGeraet = "JPBTB4GHG1" Then
                        '    MsgBox(Trim(Value).ToString)
                        'End If
                        If IsNumeric(vLevel) = False Then
                            vLevel = "201"
                        End If
                    End If
                    If SupplyString.ToLower.StartsWith("markersupplieslevel") And _TypID = 3 Then
                        'Änderung am 11.09.2012, vorher markersuppl am Ende des tags
                        'Bei MarkerSupplies gibt es nur Level
                        marker &= vbNewLine & "==>Ein MarkerSupply - also existieren nur Level-Tags"
                        vLevel = Value
                        vPartNumber = "4711part"
                        vSerial = "4711Serial"
                        vProductNumber = "4711product"

                        If IsNumeric(vLevel) = False Then
                            vLevel = "201"
                        End If
                    End If
                    If SupplyString.ToLower.EndsWith("productnumber") Then
                        vProductNumber = Value
                        If vProductNumber = "<Unbekannt>" Or Trim(Value) = "<Nicht unterstützt>" Or Trim(Value).StartsWith("<") Then
                            vProductNumber = "<Nicht gemeldet>"
                        End If
                    End If
                    If _TypID = 4 Or _TypID = 5 Then
                        'Änderung am 19.06.2013, vorher markersuppl am Ende des tags
                        'Bei Kits gibt es nur Level und/ oderPartnumber
                        marker &= vbNewLine & "==>Ein TransferKit bzw Maintenance - also interessieren nur Level-Tags"
                        vSerial = "4711Serial"
                        vProductNumber = "4711product"
                        vPartNumber = "4711part"
                    End If

                    'MsgBox("vSupply_String: " & vSupply_String & vbNewLine & "vLevel: " & vLevel & vbNewLine & "vSerial: " & vSerial & vbNewLine & "vProductNumber: " & vProductNumber _
                    '          & vbNewLine & "vPartNumber: " & vPartNumber)
                    'Überprüfung ob Insert erfolgen kann?
                    If vLevel <> "" And vSerial <> "" Then
                        If vPartNumber <> "" And vProductNumber <> "" Then
                            insertSupply = True
                        Else
                            If vPartNumber <> "" Then
                                vProductNumber = vPartNumber
                                insertSupply = True
                            Else
                                If vProductNumber <> "" Then
                                    vPartNumber = vProductNumber
                                    insertSupply = True
                                End If
                            End If
                        End If
                    Else
                        insertSupply = False
                    End If
                    'If vSupply_String.EndsWith("SupplyTransferKit") And vSerienNrGeraet = "JPBTB4GHG1" Then
                    '    MsgBox("vSupply_String: " & vSupply_String & vbNewLine & "vLevel: " & vLevel & vbNewLine & "vSerial: " & vSerial & vbNewLine & "vProductNumber: " & vProductNumber _
                    '           & vbNewLine & "vPartNumber: " & vPartNumber)
                    '    MsgBox("insertSupply: " & insertSupply.ToString)
                    'End If
                    If insertSupply = True Then
                        'MsgBox("Jetzt wird Supply inserted: " & "vSupply_String: " & vSupply_String & vbNewLine & "vLevel: " & vLevel & vbNewLine & "vSerial: " & vSerial & vbNewLine & "vProductNumber: " & vProductNumber _
                        '       & vbNewLine & "vPartNumber: " & vPartNumber)
                        'Alle Werte da, dann auch Insert der SupplyVerfolgung
                        marker &= vbNewLine & "3. Den Supplyverfolgungsdatensatz " & vSupply_String & " inserten"
                        marker &= vbNewLine & "-vSerial " & vSerial
                        marker &= vbNewLine & "-vLevel " & vLevel
                        marker &= vbNewLine & "-vPartNumber " & vPartNumber
                        marker &= vbNewLine & "-LastGERAETID " & LastGERAETID
                        marker &= vbNewLine & "-vDatum " & vDatum
                        'MsgBox(marker)
                        Me.TBSUPPLY_VERFOLGUNGTableAdapter.cmdInsertmanuell(vSupply_String, vSerial, vLevel, vPartNumber, Environment.UserName, LastGERAETID, vDatum)
                        marker &= vbNewLine & "==> ## SUPPLY ERFOLGREICH INSERTED! ## - " & Now & " " & Now.Millisecond
                        'Zur Sicherheit die Variablen zurücksetzen
                        vSupply_String = ""
                        vSerial = ""
                        vLevel = ""
                        vPartNumber = ""
                    End If
                End If

            Next 'Nächster XML-Tag
            Return True
            '###### Ende Insert Supplys
        Catch ex As Exception
            ClassLoggerSW.Add("###################### ACHTUNG FEHLER:- " & Now & " " & Now.Millisecond & " #############################################", False)
            ClassLoggerSW.Add("Marker #############################################################", False)
            ClassLoggerSW.Add(marker, False)
            ClassLoggerSW.Add("###################################################################", False)
            ClassLoggerSW.Add("FEHLERMELDUNG: " & ex.Message, False)
            MsgBox("Fehler bei Insert des Supplydatensatzes:" & vbNewLine & "Datei: " & vfilename & vbNewLine & "Gerät-SN Nummer: " & vSerienNrGeraet & vbNewLine & ex.Message, MsgBoxStyle.Critical, "Fehler bei InsertGerät")
            MsgBox("Überprüfen Sie die LogFile", MsgBoxStyle.Critical, "Hinweis:")
            Return False
        End Try
    End Function
    Public Function file_inuse(ByVal _filename) As Boolean
        Dim fs As Integer = FreeFile()
        Dim inuse As Boolean = False
        If System.IO.File.Exists(_filename) Then
            Try
                FileOpen(fs, _filename, OpenMode.Binary,
                OpenAccess.ReadWrite, OpenShare.LockReadWrite)
            Catch
                inuse = True
            Finally
                FileClose(fs)
            End Try
        End If
        Return inuse
    End Function
    Sub MoveFile(ByVal path As String, ByVal dateiname As String, ByVal _folderFehler As String, ByVal _folderArchiv As String, Optional ByVal Fehler As Boolean = False)
        Try
            'Die verarbeitete Datei verschieben
            Dim FileToMove As String = path
            Dim Zielname As String
            If Fehler = True Then
                marker &= vbNewLine & "Die XML-File in" & _folderFehler & "\Fehler verschieben"
                Dim f As New IO.DirectoryInfo(_folderFehler & "\Fehler")
                If f.Exists = False Then
                    IO.Directory.CreateDirectory(_folderFehler & "\Fehler")
                    marker &= vbNewLine & "Ordner \Fehler angelegt"
                End If
                Zielname = _folderFehler & "\Fehler\" & dateiname
            Else
                marker &= vbNewLine & "Die XML-File in" & _folderFehler & "\Archiv verschieben"
                If _folderArchiv.ToLower.EndsWith("\archiv") Then
                    Zielname = _folderArchiv & "\" & dateiname 'Date.Now.Year & Date.Now.Month & Date.Now.Day & "_" & Date.Now.Hour & "_" & Date.Now.Minute & "_" & 
                Else
                    Zielname = _folderArchiv & "\Archiv\" & dateiname 'Date.Now.Year & Date.Now.Month & Date.Now.Day & "_" & Date.Now.Hour & "_" & Date.Now.Minute & "_" &
                End If
            End If
            If System.IO.File.Exists(FileToMove) = True Then
                marker &= vbNewLine & "==> Quelle: " & FileToMove
                marker &= vbNewLine & "==> Ziel: " & Zielname
                System.IO.File.Move(FileToMove, Zielname)
                marker &= vbNewLine & "==> ERFOLGREICH verschoben"
            End If
        Catch ex As Exception
            MsgBox("Fehler in MoveFile: " & vbNewLine & ex.Message, MsgBoxStyle.Critical)
        End Try

    End Sub
    Private Sub tsbGeraeteRefresh_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles tsbGeraeteRefresh.Click
        Refresh_Geraete(cmbMandanten.Text)
    End Sub

    Private Sub tsbGeraeteOrderRefresh_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles tsbGeraeteOrderRefresh.Click
        ' Refresh_GeraeteOrder(cmbMandanten.Text)
        Refresh_Supplies2Order(cmbMandanten.Text)
    End Sub
    'Private Sub Refresh_GeraeteOrder(mandant As String)
    '    Try
    '        Me.VWGERAET_ORDERTableAdapter.Fill(Me.MyDataset.VWGERAET_ORDER, mandant)
    '        Me.VWSUPPLIES_TO_ORDERTableAdapter.Fill(MyDataset.VWSUPPLIES_TO_ORDER, mandant)
    '    Catch ex As Exception
    '        MessageBox.Show(ex.Message, "Fehler beim Laden der Bestelldaten:", MessageBoxButtons.OK, MessageBoxIcon.Error)
    '    End Try
    'End Sub
    Private Sub Refresh_Supplies2Order(mandant As String)
        Try
            Me.VWSUPPLIES_2_ORDERTableAdapter.Fill(Me.MyDataset.VWSUPPLIES_2_ORDER, mandant)
            Me.GridViewSupplies2Order.Columns.Item("GUID").Visible = False
        Catch ex As Exception
            MessageBox.Show(ex.Message, "Fehler beim Laden der Bestelldaten:", MessageBoxButtons.OK, MessageBoxIcon.Error)
        End Try
    End Sub
    Private Sub AlleMarkierenToolStripMenuItem_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles AlleMarkierenToolStripMenuItem.Click
        Try
            'Dim DS As System.Data.DataSet
            'Dim DT As System.Data.DataTable
            'Dim DR As System.Data.DataRow

            '' --- DataSet zuweisen
            'DS = Me.MyDataset
            '' --- Zugriff auf Tabelle
            'DT = DS.Tables("VWGERAET_ORDER")
            'Dim Counter As Integer = 1
            'For Each DR In DT.Rows
            '    Me.TBGERAETTableAdapter.CmdBestellungJa(DR.Item("GUID"))
            'Next
            Dim upd = "UPDATE TBSUPPLIES_2_ORDER_TEMP SET GUI_SELECTED = 1"
            ClassDatabase.Execute_non_Query(upd)
            'For Each row As DataRow In MyDataset.VWSUPPLIES_2_ORDER.Rows
            '    dd()
            '    'Me.TBGERAETTableAdapter.CmdBestellungJa()
            '    row.Item("GUI_MARKER") = True
            'Next
            'Dim i As Integer
            'Dim DisplayedColumn As C1.Win.C1TrueDBGrid.C1DisplayColumnCollection = Me.VWGERAET_ORDERDG.Splits(0).DisplayColumns
            'For i = 0 To VWGERAET_ORDERDG.Splits(0).Rows.Count - 1
            '    'MsgBox(VWGERAET_ORDERDG.Item(i, "Geraete-ID"))
            '    Me.TBGERAETTableAdapter.CmdBestellungJa(VWGERAET_ORDERDG.Item(i, "Geraete-ID"))
            'Next
            Refresh_Supplies2Order(cmbMandanten.Text)
        Catch ex As Exception
            MsgBox(ex.Message, MsgBoxStyle.Critical, "Fehler beim Markieren von allen Geräten:")
        End Try
    End Sub

    Private Sub MarkierungAufhebenToolStripMenuItem_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MarkierungAufhebenToolStripMenuItem.Click
        Try
            'Dim DS As System.Data.DataSet
            'Dim DT As System.Data.DataTable
            'Dim DR As System.Data.DataRow

            '' --- DataSet zuweisen
            'DS = Me.MyDataset
            '' --- Zugriff auf Tabelle
            'DT = DS.Tables("VWGERAET_ORDER")
            'Dim Counter As Integer = 1
            'For Each DR In DT.Rows
            '    row.Item("GUI_MARKER") = False
            '    Me.TBGERAETTableAdapter.CmdUpdateBestellungnein(DR.Item("GUID"))
            'Next
            Dim upd = "UPDATE TBSUPPLIES_2_ORDER_TEMP SET GUI_SELECTED = 0"
            ClassDatabase.Execute_non_Query(upd)
            Refresh_Supplies2Order(cmbMandanten.Text)
        Catch ex As Exception
            MsgBox(ex.Message, MsgBoxStyle.Critical, "Fehler beim Aufheben der Bestellmarkierung von allen Geräten:")
        End Try
    End Sub

    Private Sub TCGeraeteOrder_SelectedIndexChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles TCGeraeteOrder.SelectedIndexChanged
        Try
            SPCOrder.Panel2Collapsed = True
            Select Case TCGeraeteOrder.SelectedIndex
                Case 0
                    SPCOrder.Panel2Collapsed = True
                    Refresh_Supplies2Order(cmbMandanten.Text)
                Case 1
                    Me.Cursor = Cursors.WaitCursor
                    Try
                        Me.VWRPT_SUPPLIES_TOORDERTableAdapter.Fill(Me.MyDataset.VWRPT_SUPPLIES_TOORDER, Me.cmbMandanten.Text)
                    Catch ex As Exception
                        MsgBox(ex.Message, MsgBoxStyle.Critical, "Fehler beim Laden der Daten zu Bericht:")
                    End Try
                    Try
                        Me.rptViewerBestellungen.RefreshReport()
                    Catch ex As Exception
                        MsgBox(ex.Message, MsgBoxStyle.Critical, "Fehler beim Laden des Berichtes Order zu Gerät:")
                    End Try
                    Me.Cursor = Cursors.Default
                Case 2
                    Load_Bestellung_Gesendet()
                Case 3
                    '
                Case 4

                    Dim diPfad As New IO.DirectoryInfo(pathBestellungen)
                    Dim _count As Integer = 0
                    For Each file As IO.FileInfo In diPfad.GetFiles()
                        If (file.Name.ToUpper.Contains("_BESTELLUNG_") And file.Name.ToUpper.EndsWith(".XLS")) Or (file.Name.ToUpper.Contains("_BESTELLUNG_") And file.Name.ToUpper.EndsWith(".XLSX")) Then
                            _count = _count + 1
                        End If
                    Next
                    Me.btnImportBestellungen.Text = "Import Bestellungen" & vbCrLf & "Unverarbeitet: " & _count & " Files"
            End Select
        Catch ex As Exception
            MsgBox(ex.Message, MsgBoxStyle.Critical, "Fehler bei TCGeraeteOrder.SelectedIndexChanged:")
        End Try
    End Sub

    Private Sub ToolStripButton10_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles tsbSetBest_gesendet.Click
        If VWSUPPLIES_2_ORDERBindingSource.Count > 0 Then
            Try
                VWSUPPLIES_2_ORDERBindingSource.EndEdit()
                ' --- Zugriff auf Tabelle
                Dim Counter As Integer = 1
                For Each DR As DataRow In MyDataset.VWSUPPLIES_2_ORDER.Rows
                    Dim sql As String
                    Dim GERAET_ID = DR.Item("GERAET_ID")
                    If DR.Item("GUI_SELECTED") = True Then
                        Dim supply_ID As Integer = DR.Item("SUPPLY_ID")
                        If DR.Item("MANUELL") = False Then
                            sql = String.Format("UPDATE TBSUPPLIES SET STATUS_ID = 10, GEAENDERTWER = '{0}', MARKER = 'Frontend' WHERE GUID = {1}", Environment.UserName, supply_ID)
                            ClassDatabase.Execute_non_Query(sql, True)
                        Else
                            Dim ORDER_ID As Integer = DR.Item("BESTELL_ID")
                            sql = String.Format("UPDATE TBSUPPLY_BESTELLUNG SET BESTELLT_WANN = GETDATE(), MARKER = 'STATUS GESENDET MANUELL', MANUELL_BESTELLT = 1 WHERE (GUID ={0})", ORDER_ID)
                            ClassDatabase.Execute_non_Query(sql, True)
                        End If

                    End If
                Next
                Refresh_Supplies2Order(cmbMandanten.Text)
            Catch ex As Exception
                MsgBox(ex.Message, MsgBoxStyle.Critical, "Fehler beim Markieren als 'Bestellung gesendet':")
            End Try
        End If
    End Sub
    Private Sub btnsetBestellt_Click(sender As Object, e As EventArgs) Handles btnsetBestellt.Click
        If VWSUPPLIES_2_ORDERBindingSource.Count > 0 Then
            Try
                VWSUPPLIES_2_ORDERBindingSource.EndEdit()
                ' --- Zugriff auf Tabelle
                Dim Counter As Integer = 1
                For Each DR As DataRow In MyDataset.VWSUPPLIES_2_ORDER.Rows
                    Dim GUID = DR.Item("GUID")
                    Dim Supply_ID = DR.Item("SUPPLY_ID")
                    Dim sql As String
                    If DR.Item("GUI_SELECTED") = True Then
                        If DR.Item("MANUELL") = False Then
                            sql = String.Format("UPDATE TBSUPPLIES SET STATUS_ID = 4, GEAENDERTWER = '{0}', MARKER = 'Frontend' WHERE (GUID = {1})", Environment.UserName, Supply_ID)
                            ClassDatabase.Execute_non_Query(sql, True)
                        Else
                            Dim ORDER_ID As Integer = DR.Item("BESTELL_ID")
                            'eine manuell ausgeführte Bestellung
                            sql = String.Format("UPDATE TBSUPPLY_BESTELLUNG SET MARKER = 'STATUS BESTELLT MANUELL', MANUELL_BESTELLT = 1 WHERE (GUID ={0})", ORDER_ID)
                            ClassDatabase.Execute_non_Query(sql, True)
                        End If


                        '    Dim sql1 = String.Format("SELECT * FROM TBSUPPLIES_2_ORDER_TEMP WHERE SUPPLY_ID IN (SELECT GUID FROM TBSUPPLIES WHERE GERAET_ID = {0})", G_ID)
                        '    Dim DT_SUPPLIES As DataTable = ClassDatabase.Return_Datatable(sql1, True)
                        '    If Not IsNothing(DT_SUPPLIES) Then
                        '        For Each row As DataRow In DT_SUPPLIES.Rows
                        '            Dim supply_ID As Integer = row.Item("SUPPLY_ID")
                        '            If row.Item("MANUALLY") = False Then
                        '                sql = String.Format("UPDATE TBSUPPLIES SET STATUS_ID = 4, GEAENDERTWER = '{0}', MARKER = 'Frontend' WHERE (GUID = {1})", Environment.UserName, supply_ID)
                        '                ClassDatabase.Execute_non_Query(sql, True)
                        '            Else
                        '                sql = String.Format("UPDATE TBSUPPLY_BESTELLUNG SET MARKER = 'STATUS BESTELLT MANUELL', MANUELL_BESTELLT = 1 WHERE (SUPPLY_ID ={0}) AND (MANUELL_BESTELLT = 0) AND (MANUELL = 1)", supply_ID)
                        '                ClassDatabase.Execute_non_Query(sql, True)
                        '            End If
                        '        Next
                        '    End If
                    End If
                Next
                Refresh_Supplies2Order(cmbMandanten.Text)
            Catch ex As Exception
                MsgBox(ex.Message, MsgBoxStyle.Critical, "Fehler beim Markieren als 'Bestellt' für alle Geräte:")
            End Try
        End If
    End Sub
    Private Sub chbFilterStatus_CheckedChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles chbFilterStatus.CheckedChanged
        If Me.chbFilterStatus.Checked Then
            'If Me.VWSUPPLIESBindingSource.Count < 1 Then
            '    Refresh_Supplies()
            'End If
            'Me.VWSUPPLIESBindingSource.DataSource = TBWH_STATUSFILTERBindingSource
            'VWSUPPLIESBindingSource.DataMember = "TBWH_STATUSFILTER_VWSUPPLIES"
            Me.TBWH_STATUSFILTERDataGridView.Visible = True
        Else
            'Me.VWSUPPLIESBindingSource.DataSource = MyDataset
            'VWSUPPLIESBindingSource.DataMember = "VWSUPPLIES"
            Me.TBWH_STATUSFILTERDataGridView.Visible = False
            Refresh_Supplies()
        End If
    End Sub
    Private Sub tsborders_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles tsborders.Click
        Load_Bestellungen_Manuell()

    End Sub
    Sub Load_Bestellungen_Manuell()
        frmBestellung.Show()
    End Sub


    Private Sub Refresh_Bestellungen()
        Try
            Me.Cursor = Cursors.WaitCursor
            Dim sql = String.Format("SELECT * FROM VWSUPPLY_BESTELLUNG_FRONTEND AS T " &
                "WHERE  (UPPER(Mandant) = UPPER('{0}'))", cmbMandanten.Text)
            If pnlOrderDateSelector.Visible = True Then
                sql &= $" AND convert(Date,[Bestellt wann]) >= CONVERT(DATE,'{DateTimePickerOrdervon.Value}') AND convert(Date,[Bestellt wann]) <= CONVERT(DATE,'{DateTimePickerOrderbis.Value}')"
            Else
                sql &= " AND YEAR([Bestellt wann]) = YEAR(GETDATE())"
            End If
            sql &= " ORDER BY [Bestellt wann] DESC"


            Dim DTRESULT As DataTable = ClassDatabase.Return_Datatable(sql, True)
            If Not IsNothing(DTRESULT) Then
                VWSUPPLY_BESTELLUNG_FRONTENDBindingSource.DataSource = DTRESULT
                GridControlBestellungen.DataSource = VWSUPPLY_BESTELLUNG_FRONTENDBindingSource
                Dim XMLPath = ClassHelper.GetSelectionGridName("GridViewBestellungen_Uebersicht")
                If File.Exists(XMLPath) Then
                    GridControlBestellungen.MainView.RestoreLayoutFromXml(XMLPath)
                End If

            Else
                VWSUPPLY_BESTELLUNG_FRONTENDBindingSource.DataSource = Nothing
                GridControlBestellungen.DataSource = Nothing
                GridViewBestellUebersicht.Columns.Clear()

            End If
            'If Me.chbFilterMarkt_Bestellungen.Checked = False And Me.chkbDatumfilterOrder.Checked = False Then
            '    ' Me.DGTBSUPPLY_BESTELLUNG.Caption = "Bestellungen für alle Märkte"
            '    Me.TBSUPPLY_BESTELLUNGViewTableAdapter.FillByall(Me.MyDataset.VWSUPPLY_BESTELLUNG_FRONTEND, cmbMandanten.Text)
            'Else
            '    If chbFilterMarkt_Bestellungen.Checked Then
            '        Dim Markt As String = DGTBWH_Markt_Bestellungen.CurrentCell.Value()

            '        If Me.chkbDatumfilterOrder.Checked Then
            '            '        Me.DGTBSUPPLY_BESTELLUNG.Caption = "Bestellungen für Markt: " & Markt.ToUpper & " und in Zeitraum"
            '            Me.TBSUPPLY_BESTELLUNGViewTableAdapter.FillBy_DatumMArkt(Me.MyDataset.VWSUPPLY_BESTELLUNG_FRONTEND, Markt, Me.dtpOrder_von.Value, Me.dtpOrder_bis.Value)
            '        Else
            '            '       Me.DGTBSUPPLY_BESTELLUNG.Caption = "Bestellungen für Markt: " & Markt.ToUpper
            '            Me.TBSUPPLY_BESTELLUNGViewTableAdapter.Fill_ByMarkt(Me.MyDataset.VWSUPPLY_BESTELLUNG_FRONTEND, Markt)
            '        End If
            '    ElseIf Me.chkbDatumfilterOrder.Checked Then
            '        '  Me.DGTBSUPPLY_BESTELLUNG.Caption = "Bestellungen in Zeitraum"
            '        Me.TBSUPPLY_BESTELLUNGViewTableAdapter.FillByDatum(Me.MyDataset.VWSUPPLY_BESTELLUNG_FRONTEND, cmbMandanten.Text, Me.dtpOrder_von.Value, Me.dtpOrder_bis.Value)
            '    End If
            'End If
        Catch ex As System.Exception
            MsgBox(ex.Message, MsgBoxStyle.Critical, "Fehler beim Abfragen der Bestellungen:")
        End Try
        Me.Cursor = Cursors.Default
    End Sub

    Private Sub tsbRefresh_Bestellungen_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles tsbRefresh_Bestellungen.Click
        Me.Cursor = Cursors.WaitCursor
        Save_GridLayout_Bestuebersicht()
        Refresh_Bestellungen()
        Cursor = Cursors.Default
    End Sub

    Private Sub tsbexcel_geraete_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles tsbexcel_geraete.Click
        Dim saveFileDialog1 As New SaveFileDialog
        saveFileDialog1.Filter = "Excel (*.xls)|*.xls|Excel (*.xlsx)|*.xlsx"
        saveFileDialog1.Title = "Export to Excel:"
        saveFileDialog1.ShowDialog()
        If saveFileDialog1.FileName <> "" Then
            Cursor = Cursors.WaitCursor
            If saveFileDialog1.FileName.EndsWith("xlsx") Then
                GridViewGeraete.ExportToXlsx(saveFileDialog1.FileName)
            Else
                GridViewGeraete.ExportToXls(saveFileDialog1.FileName)
            End If
            Dim result As MsgBoxResult
            result = MessageBox.Show("Datei wurde erstellt! Wollen Sie diese nun öffnen?", "Erfolgsmeldung:", MessageBoxButtons.YesNo, MessageBoxIcon.Question)
            If result = MsgBoxResult.Yes Then
                Process.Start(saveFileDialog1.FileName)
            End If
        End If
        Cursor = Cursors.Default
    End Sub
    Public Sub XLS_Mit_Filter(ByVal vDataset As DataSet, ByVal vds_dt As String, ByVal vSheet_Name As String)
        Dim dt As DataTable

        'To manipulate an Excel workbook, the code needs to instantiate an Excel Application object, 
        'and then use the object model to add a new workbook, change the name (to Northwind Customers in this example), and do other UI chores.

        'Create an instance of Excel 2003, add a workbook, 
        'and let the user know what's happening
        Dim xl As New Excel.Application
        xl.Workbooks.Add()
        xl.ActiveSheet.Name = vSheet_Name
        xl.Visible = True
        xl.Range("A1").Value = "Exportiere Daten aus Datenbank...."

        'Once Excel is loaded and running, the code needs a reference to the table in the DataSet ds. 
        'Then it loops through the Columns collection of that DataTable object and places the field names 
        'in the first row of the worksheet. This example uses a Customers table and a Customers column heading.

        Try
            xl.ScreenUpdating = False

            'Start with the Customers table
            dt = vDataset.Tables(vds_dt) '"VWDWD_EXP_KPI"

            'Add the column headings for the Customers
            Dim dc As DataColumn
            Dim iCols As Int32 = 0
            For Each dc In dt.Columns
                xl.Range("A1").Offset(0, iCols).Value = dc.ColumnName
                iCols += 1
            Next

            'All that's left is to loop through the rows in the table and use the ItemArray property of the DataRow 
            'object to write the contents of each data row to a row of the worksheet. This is about as close as Excel 
            'comes to supporting a DataSet object directly.

            'Add the data
            Dim iRows As Int32
            For iRows = 0 To dt.Rows.Count - 1
                xl.Range("A2").Offset(iRows).Resize(1, iCols).Value = dt.Rows(iRows).ItemArray()
            Next
        Catch ex As Exception

            'The remaining code in the procedure updates the UI and applies built-in formatting to the worksheet.

        Finally
            xl.ScreenUpdating = True
        End Try
        'Make the sheet pretty
        With xl.ActiveSheet.Range("A1")
            .AutoFilter()
            .AutoFormat(Excel.XlRangeAutoFormat.xlRangeAutoFormatSimple) 'xlRangeAutoFormatSimple
        End With

        xl = Nothing
    End Sub
    Public Sub XLS_FILTER_TEMP_DT(ByVal DATATABLE As DataTable, vSheet_Name As String)
        Dim dt As DataTable

        'To manipulate an Excel workbook, the code needs to instantiate an Excel Application object, 
        'and then use the object model to add a new workbook, change the name (to Northwind Customers in this example), and do other UI chores.

        'Create an instance of Excel 2003, add a workbook, 
        'and let the user know what's happening
        Dim xl As New Excel.Application
        xl.Workbooks.Add()
        xl.ActiveSheet.Name = vSheet_Name
        xl.Visible = True
        xl.Range("A1").Value = "Exportiere Daten aus Datenbank...."

        'Once Excel is loaded and running, the code needs a reference to the table in the DataSet ds. 
        'Then it loops through the Columns collection of that DataTable object and places the field names 
        'in the first row of the worksheet. This example uses a Customers table and a Customers column heading.

        Try
            xl.ScreenUpdating = False

            'Start with the Customers table
            dt = DATATABLE

            'Add the column headings for the Customers
            Dim dc As DataColumn
            Dim iCols As Int32 = 0
            For Each dc In dt.Columns
                xl.Range("A1").Offset(0, iCols).Value = dc.ColumnName
                iCols += 1
            Next

            'All that's left is to loop through the rows in the table and use the ItemArray property of the DataRow 
            'object to write the contents of each data row to a row of the worksheet. This is about as close as Excel 
            'comes to supporting a DataSet object directly.

            'Add the data
            Dim iRows As Int32
            For iRows = 0 To dt.Rows.Count - 1
                xl.Range("A2").Offset(iRows).Resize(1, iCols).Value = dt.Rows(iRows).ItemArray()
            Next
        Catch ex As Exception

            'The remaining code in the procedure updates the UI and applies built-in formatting to the worksheet.

        Finally
            xl.ScreenUpdating = True
        End Try
        'Make the sheet pretty
        With xl.ActiveSheet.Range("A1")
            .AutoFilter()
            .AutoFormat(Excel.XlRangeAutoFormat.xlRangeAutoFormatSimple) 'xlRangeAutoFormatSimple
        End With

        xl = Nothing
    End Sub
    Private Sub tsbExcel_Supplies_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles tsbExcel_Supplies.Click
        Dim saveFileDialog1 As New SaveFileDialog
        saveFileDialog1.Filter = "Excel (*.xls)|*.xls|Excel (*.xlsx)|*.xlsx"
        saveFileDialog1.Title = "Export to Excel:"
        saveFileDialog1.ShowDialog()
        If saveFileDialog1.FileName <> "" Then
            Cursor = Cursors.WaitCursor
            If saveFileDialog1.FileName.EndsWith("xlsx") Then
                GridViewVWSupplies.ExportToXlsx(saveFileDialog1.FileName)
            Else
                GridViewVWSupplies.ExportToXls(saveFileDialog1.FileName)
            End If
            Dim result As MsgBoxResult
            result = MessageBox.Show("Datei wurde erstellt! Wollen Sie diese nun öffnen?", "Erfolgsmeldung:", MessageBoxButtons.YesNo, MessageBoxIcon.Question)
            If result = MsgBoxResult.Yes Then
                Process.Start(saveFileDialog1.FileName)
            End If
        End If
        Cursor = Cursors.Default
    End Sub

    Private Sub tsbExel_bestellungen_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles tsbExel_bestellungen.Click
        Dim saveFileDialog1 As New SaveFileDialog
        saveFileDialog1.Filter = "Excel (*.xls)|*.xls|Excel (*.xlsx)|*.xlsx"
        saveFileDialog1.Title = "Export to Excel:"
        saveFileDialog1.ShowDialog()
        If saveFileDialog1.FileName <> "" Then
            Cursor = Cursors.WaitCursor
            If saveFileDialog1.FileName.EndsWith("xlsx") Then
                GridViewBestellUebersicht.ExportToXlsx(saveFileDialog1.FileName)
            Else
                GridViewBestellUebersicht.ExportToXls(saveFileDialog1.FileName)
            End If
            Dim result As MsgBoxResult
            result = MessageBox.Show("Datei wurde erstellt! Wollen Sie diese nun öffnen?", "Erfolgsmeldung:", MessageBoxButtons.YesNo, MessageBoxIcon.Question)
            If result = MsgBoxResult.Yes Then
                Process.Start(saveFileDialog1.FileName)
            End If


        End If
        Cursor = Cursors.Default
    End Sub

    'Private Sub DGTBSUPPLY_BESTELLUNG_AfterColUpdate(ByVal sender As System.Object, ByVal e As C1.Win.C1TrueDBGrid.ColEventArgs)
    '    If FormLoaded = True Then
    '        Try
    '            Me.TBSUPPLY_BESTELLUNGViewBindingSource.EndEdit()
    '            If MyDataset.VWSUPPLY_BESTELLUNG_FRONTEND.GetChanges Is Nothing = False Then
    '                Dim DataColumn As String = DGTBSUPPLY_BESTELLUNG.Splits(DGTBSUPPLY_BESTELLUNG.SplitIndex).DisplayColumns(DGTBSUPPLY_BESTELLUNG.Col).DataColumn.ToString
    '                'MsgBox(VWGERAET_ORDERDG.Splits(VWGERAET_ORDERDG.SplitIndex).DisplayColumns(VWGERAET_ORDERDG.Col).DataColumn.Value, MsgBoxStyle.Information, DataColumn)
    '                Select Case DataColumn
    '                    Case "Bestell Nr"
    '                        Me.TBSUPPLY_BESTELLUNGViewTableAdapter.cmdUpdate_BestNr(DGTBSUPPLY_BESTELLUNG.Item(DGTBSUPPLY_BESTELLUNG.Row, "Bestell Nr"), Environment.UserName, DGTBSUPPLY_BESTELLUNG.Item(DGTBSUPPLY_BESTELLUNG.Row, "ID"))
    '                End Select
    '                Refresh_Bestellungen()
    '            End If
    '        Catch ex As Exception
    '            MsgBox(ex.Message, MsgBoxStyle.Critical, "Fehler beim Aktualisieren der BestellNr:")
    '        End Try
    '    End If
    'End Sub
    Dim refresh As Boolean = False
    Private Sub chbFilterMarktNV_CheckedChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles chbFilterMarktNV.CheckedChanged
        If Me.chbFilterMarktNV.Checked Then
            refresh = False
            'If Me.TBGERAETBindingSource.Count < 1 Then
            '    Refresh_Geraete()
            'End If
            'Me.TBGERAETBindingSource.DataSource = TBWH_MARKTBindingSource
            'TBGERAETBindingSource.DataMember = "TBWH_MARKT_TBGERAET"
            Me.DGVTBWH_MARKT_VF.Visible = True
            refresh = True
        Else
            'Me.TBGERAETBindingSource.DataSource = MyDataset
            'TBGERAETBindingSource.DataMember = "TBGERAET"
            Me.DGVTBWH_MARKT_VF.Visible = False
        End If
    End Sub
    Private Sub DGVTBWH_MARKT_VF_SelectionChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles DGVTBWH_MARKT_VF.SelectionChanged
        If refresh = True Then
            If TabControlNachverfolgung.SelectedIndex = 0 Then

            Else

            End If

        End If
    End Sub

    Private Sub chkbDatumfilter_CheckedChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles chkbDatumfilter.CheckedChanged
        If Me.chkbDatumfilter.Checked Then
            dtpVerfolgung_bis.Enabled = True
            dtpVerfolgung_von.Enabled = True
        Else
            dtpVerfolgung_bis.Enabled = False
            dtpVerfolgung_von.Enabled = False
        End If
    End Sub
    'Sub Refresh_Verfolgung()
    '    If Me.TBGERAETByMarktBindingSource.Count >= 1 Then
    '        Try
    '            Dim GERAET_ID As Integer = 
    '            If Me.chbFilterMarkt.Checked Then
    '                If Me.chkbDatumfilter.Checked Then
    '                    Refresh_Geraete_Verfolgung(GERAET_ID, True, True)
    '                Else
    '                    Refresh_Geraete_Verfolgung(GERAET_ID, True, False)
    '                End If
    '            Else
    '                If Me.chkbDatumfilter.Checked Then
    '                    Refresh_Geraete_Verfolgung(GERAET_ID, False, True)
    '                Else
    '                    MsgBox("bitte wählen Sie aus ob Sie nach Markt und/oder Datum filtern wollen?", MsgBoxStyle.Exclamation, "Fehlende Einschränkung:")
    '                End If
    '            End If
    '            Refresh_Supply_Verfolgung(GERAET_ID)
    '        Catch ex As Exception
    '            MessageBox.Show(ex.Message, "Fehler bei TBGERAETByMarktDatagridView.RowColChange:", MessageBoxButtons.OK, MessageBoxIcon.Error)
    '        End Try
    '    End If
    'End Sub


    Sub Refresh_Supply_Typen()
        Try
            Me.TBSUPPLY_DEFINITIONTableAdapter.Fill(Me.MyDataset.TBSUPPLY_DEFINITION)
        Catch ex As System.Exception
            MessageBox.Show(ex.Message, "Fehler beim Laden der SupplyTypen:", MessageBoxButtons.OK, MessageBoxIcon.Error)
        End Try
    End Sub
    Private Sub Save_Supply_Typen()
        Try
            Me.Validate()
            Me.TBSUPPLY_DEFINITIONBindingSource.EndEdit()
            If MyDataset.TBSUPPLY_DEFINITION.GetChanges Is Nothing = False Then
                TBSUPPLY_DEFINITIONBindingSource.EndEdit()
                Me.TBSUPPLY_DEFINITIONTableAdapter.Update(Me.MyDataset.TBSUPPLY_DEFINITION)
                MsgBox("Die Supply-Typen wurden erfolgreich gespeichert!", MsgBoxStyle.Information, "Erfolgsmeldung:")
            End If
        Catch ex As Exception
            MsgBox(ex.Message, MsgBoxStyle.Critical, "Fehler bei Speichern der Supply-Typen:")
        End Try
    End Sub
    Sub Refresh_Vertrag_Produkt()
        Try
            Me.TBVERTRAEGETableAdapter.Fill(Me.MyDataset.TBVERTRAEGE)
            Me.TBPRODUKT_VERTRAGTableAdapter.Fill(Me.MyDataset.TBPRODUKT_VERTRAG)
        Catch ex As Exception
            MessageBox.Show(ex.Message, "Fehler bei Laden der Vertragsdaten:", MessageBoxButtons.OK, MessageBoxIcon.Error)
        End Try
    End Sub
    Private Sub tsbexcel_G_Verfolgung_Click(ByVal sender As System.Object, ByVal e As System.EventArgs)
        Me.Cursor = Cursors.WaitCursor
        XLS_Mit_Filter(MyDataset, "VWGERAETE_VERFOLGUNG", "Geräteverfolgung")
        Cursor = Cursors.Default
    End Sub


    Private Sub dtpVerfolgung_von_ValueChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles dtpVerfolgung_von.ValueChanged
        If dtpVerfolgung_bis.Value.ToShortDateString >= dtpVerfolgung_von.Value.ToShortDateString Then
            If TabControlNachverfolgung.SelectedIndex = 0 Then

            Else

            End If

        Else
            dtpVerfolgung_bis.Value = dtpVerfolgung_von.Value
        End If
    End Sub
    Sub Refresh_Geraete_Supply()
        Try
            Me.VWGeraet_Supply_ZuordnungTableAdapter.Fill(Me.MyDataset.VWGeraet_Supply_Zuordnung)
        Catch ex As Exception
            MsgBox(ex.Message, MsgBoxStyle.Critical, "Fehler bei Laden der Geräte-Supply Zuordnung:")
        End Try

    End Sub
    Private Sub tsbn_refresh_Vertraege_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles tsbn_refresh_Vertraege.Click
        Refresh_Vertrag_Produkt()
    End Sub

    Private Sub tsbtn_showImport_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles tsbtn_showImport.Click
        frmImport_Produkte.ShowDialog()
    End Sub

    Private Sub Splitter1_SplitterMoved(ByVal sender As System.Object, ByVal e As System.Windows.Forms.SplitterEventArgs) Handles Splitter1.SplitterMoved
        My.Settings.Save()
    End Sub

    Private Sub spltC_Vertrag_Produkt_SplitterMoved(ByVal sender As System.Object, ByVal e As System.Windows.Forms.SplitterEventArgs) Handles spltC_Vertrag_Produkt.SplitterMoved
        My.Settings.Save()
    End Sub

    Private Sub ToolStripButton21_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles ToolStripButton21.Click
        Refresh_Supply_Typen()
    End Sub

    Private Sub ToolStripButton22_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles ToolStripButton22.Click
        Save_Supply_Typen()
    End Sub

    Private Sub TBSUPPLY_DEFINITIONBindingSource_AddingNew(ByVal sender As Object, ByVal e As System.ComponentModel.AddingNewEventArgs) Handles TBSUPPLY_DEFINITIONBindingSource.AddingNew
        MyDataset.TBSUPPLY_DEFINITION.ERFASSTWERColumn.DefaultValue = Environment.UserName
    End Sub

    Private Sub ToolStripButton27_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles ToolStripButton27.Click
        Try
            TBSUPPLY_DEFINITIONBindingSource.AddNew()
        Catch ex As Exception
            MsgBox(ex.Message, MsgBoxStyle.Critical, "Fehler bei  TBSUPPLY_DEFINITIONBindingSource.AddNew()")
        End Try

    End Sub

    Private Sub ToolStripButton28_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles ToolStripButton28.Click
        Refresh_Geraete_Supply()
    End Sub

    Private Sub ToolStripButton29_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles ToolStripButton29.Click
        Try
            Dim ID As Integer = GridViewSupplyZuordnung.GetFocusedRowCellValue(GridViewSupplyZuordnung.Columns("GUID"))
            Dim SW As Integer = GridViewSupplyZuordnung.GetFocusedRowCellValue(GridViewSupplyZuordnung.Columns("SCHWELLENWERT"))

            Me.TBGERAET_SUPPLY_ZUORDNUNGTableAdapter.Delete(ID)
            Refresh_Geraete_Supply()
        Catch ex As Exception
            MsgBox(ex.Message, MsgBoxStyle.Critical, "Fehler bei Löschen einer Geräte-Supply Zuordnung:")
        End Try
    End Sub

    Private Sub btnaddgeraete_SupplyZO_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnaddgeraete_SupplyZO.Click
        If Me.txtPartnumber.Text = "" Then
            MsgBox("Bitte geben Sie eine Partnumber für das Supply ein!", MsgBoxStyle.Exclamation, "Achtung: Fehlender Parameter!")
            Me.txtPartnumber.Focus()
            Exit Sub
        End If
        Try
            Me.TBGERAET_SUPPLY_ZUORDNUNGTableAdapter.Insert(Me.cmbModelle_WH.SelectedValue, Me.cmbSupplyDefinition.SelectedValue, Environment.UserName, txtPartnumber.Text, txtSchwellenwert.Text, txtPartnumerORDER.Text)
            Me.VWGeraet_Supply_ZuordnungTableAdapter.FillByGeraet(MyDataset.VWGeraet_Supply_Zuordnung, Me.cmbModelle_WH.SelectedValue)
            Me.txtPartnumber.Text = ""
            Me.txtPartnumerORDER.Text = ""
        Catch ex As Exception
            MsgBox(ex.Message, MsgBoxStyle.Critical, "Fehler bei Anlegen einer Geräte-Supply Zuordnung:")
        End Try
    End Sub

    Private Sub cmbModelle_WH_GotFocus(ByVal sender As Object, ByVal e As System.EventArgs) Handles cmbModelle_WH.GotFocus
        Me.cmbModelle_WH.DroppedDown = True
    End Sub
    Private Sub cmbModelle_WH_KeyUp(ByVal sender As System.Object, ByVal e As System.Windows.Forms.KeyEventArgs) Handles cmbModelle_WH.KeyUp
        AutoCompleteCombo_KeyUp(cmbModelle_WH, e)
    End Sub
    Public Sub AutoCompleteCombo_KeyUp(ByVal cbo As ComboBox, ByVal e As KeyEventArgs)
        Dim sTypedText As String
        Dim iFoundIndex As Integer
        Dim oFoundItem As Object
        Dim sFoundText As String
        Dim sAppendText As String

        'Allow select keys without Autocompleting
        Select Case e.KeyCode
            Case Keys.Back, Keys.Left, Keys.Right, Keys.Up, Keys.Delete, Keys.Down
                Return
        End Select

        'Get the Typed Text and Find it in the list

        sTypedText = cbo.Text
        iFoundIndex = cbo.FindString(sTypedText)

        'If we found the Typed Text in the list then Autocomplete

        If iFoundIndex >= 0 Then
            'Get the Item from the list (Return Type depends if Datasource was bound 
            ' or List Created)
            oFoundItem = cbo.Items(iFoundIndex)
            'Use the ListControl.GetItemText to resolve the Name in case the Combo 
            ' was Data bound
            sFoundText = cbo.GetItemText(oFoundItem)
            'Append then found text to the typed text to preserve case
            sAppendText = sFoundText.Substring(sTypedText.Length)
            cbo.Text = sTypedText & sAppendText
            'Select the Appended Text
            cbo.SelectionStart = sTypedText.Length
            cbo.SelectionLength = sAppendText.Length
        End If
    End Sub

    Private Sub TBWH_STATUSFILTERDataGridView_SelectionChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles TBWH_STATUSFILTERDataGridView.SelectionChanged
        If Me.FormLoaded = True And Me.TBWH_STATUSFILTERBindingSource.Count > 0 And Me.chbFilterStatus.Checked Then
            Refresh_Supplies()
        End If
    End Sub

    Private Sub ToolStripButton30_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles ToolStripButton30.Click
        Me.Cursor = Cursors.WaitCursor
        frmImport_Report.Show()
        Me.Cursor = Cursors.Default
    End Sub

    Private Sub cmbSupplyDefinition_SelectedIndexChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles cmbSupplyDefinition.SelectedIndexChanged
        If Me.FormLoaded = True Then
            Me.txtPartnumber.Focus()
        End If
    End Sub

    Private Sub txtPartnumber_TextChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles txtPartnumber.TextChanged
        If Me.txtPartnumber.Text <> "" Then
            Me.txtPartnumerORDER.Text = Me.txtPartnumber.Text
        End If
    End Sub

    Private Sub tsbGeraeteverfolgung_Geraet_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles tsbGeraeteverfolgung_Geraet.Click
        Try
            Dim GERAET_ID As Integer = GridViewGeraete.GetFocusedRowCellValue(GridViewGeraete.Columns("GUID"))
            CURRENT_GERAETE_ID = GERAET_ID
            My.Settings.verf_id = GERAET_ID
            My.Settings.Save()
            open_Verfolgung()
        Catch ex As System.Exception
            'MsgBox(ex.Message, MsgBoxStyle.Critical, "Fehler bei Laden der Nachverfolgung zu Gerät:")
        End Try
    End Sub

    Private Sub btnFolderBestellungen_Click(sender As System.Object, e As System.EventArgs) Handles btnFolderBestellungen.Click
        Bestellungen_Ordner()
    End Sub
    Private Sub btnImportBestellungen_Click(sender As System.Object, e As System.EventArgs) Handles btnImportBestellungen.Click
        Bestellungen_verarbeiten()
    End Sub

    Private Sub tsbtnONHOLD_Click(sender As System.Object, e As System.EventArgs) Handles tsbtnONHOLD.Click
        Try
            Dim GERAET_ID As Integer = GridViewGeraete.GetFocusedRowCellValue(GridViewGeraete.Columns("GUID"))
            Dim _bit As Boolean = GridViewGeraete.GetFocusedRowCellValue(GridViewGeraete.Columns("colONHOLD"))

            Dim _State As Integer
            If _bit = False Then
                _State = 1
            Else
                _State = 0
            End If
            Me.TBGERAETTableAdapter.cmdupdateStateOnHold(_State, GERAET_ID)
            Refresh_Geraete(cmbMandanten.Text)
        Catch ex As System.Exception
            MsgBox(ex.Message, MsgBoxStyle.Critical, "Fehler bei ONHOLD-Setzen:")
        End Try
    End Sub

    Private Sub tsbtnAbbrechen_Click(sender As System.Object, e As System.EventArgs) Handles tsbtnAbbrechen.Click
        Me.bwXMLverarbeiten.CancelAsync()
    End Sub
    Private Sub StarteMailExporterToolStripMenuItem_Click(sender As System.Object, e As System.EventArgs) Handles StarteMailExporterToolStripMenuItem.Click
        Dim result As MsgBoxResult
        result = MessageBox.Show("Wollen Sie den Durchlauf aller hinterlegten Profile starten?" & vbNewLine & "Rückgängig machen nicht möglich!", "Bestätigung erforderlich:", MessageBoxButtons.YesNo, MessageBoxIcon.Question)
        If result = MsgBoxResult.Yes Then
            Export_Send_Data()
        End If
    End Sub

    Private Sub ProfileMailExporterToolStripMenuItem_Click(sender As System.Object, e As System.EventArgs) Handles ProfileMailExporterToolStripMenuItem.Click
        Cursor = Cursors.WaitCursor
        Dim frm As New frmBGExportProfileigenschaften
        frm = frmBGExportProfileigenschaften.Instance
        frm.ShowDialog()
        Cursor = Cursors.Default
    End Sub

    Private Sub TBVERTRAEGEBindingNavigator_RefreshItems(sender As System.Object, e As System.EventArgs) Handles TBVERTRAEGEBindingNavigator.RefreshItems

    End Sub

    Private Sub cmbDatenbank_Click(sender As System.Object, e As System.EventArgs) Handles cmbDatenbank.Click
        Try
            Me.Cursor = Cursors.WaitCursor
            Dim csb As New SqlClient.SqlConnectionStringBuilder
            csb.DataSource = Me.txtServer.Text
            csb.IntegratedSecurity = False
            csb.UserID = Me.txtUser.Text
            csb.Password = Me.txtPasswort.Text
            Dim connection As New SqlClient.SqlConnection(csb.ConnectionString)
            connection.Open()
            Dim cmd As New SqlClient.SqlCommand("sp_databases", connection)
            cmd.CommandType = CommandType.StoredProcedure
            ' Ausführen und Ergebnis in einer ListBox anzeigen
            Dim dr As SqlClient.SqlDataReader = cmd.ExecuteReader
            If dr.HasRows Then
                Do While dr.Read
                    cmbDatenbank.Items.Add(dr("Database_Name"))
                Loop
                cmbDatenbank.DroppedDown = True
            End If
            connection.Close()
        Catch ex As Exception
            MsgBox(ex.Message, MsgBoxStyle.Critical, "Fehler bei Datenbank-Connect:")
        End Try
        Cursor = Cursors.Default
    End Sub

    Private Sub ToolStripLabel7_Click(sender As System.Object, e As System.EventArgs) Handles ToolStripLabel7.Click

    End Sub

    Private Sub Refresh_Marktverfolgung(markt As String, datevon As Date, datebis As Date)
        Me.Cursor = Cursors.WaitCursor
        Try
            Dim oSqlConn As SqlClient.SqlConnection = New SqlClient.SqlConnection(My.Settings.ConfigConnectionString)
            Dim selectstring As String = My.Settings.selectATR
            selectstring = selectstring.Replace("@MARKT", markt)
            selectstring = selectstring.Replace("@DATE_VON", datevon)
            selectstring = selectstring.Replace("@DATE_BIS", datebis)

            Dim sqlcommand As SqlClient.SqlCommand = New SqlClient.SqlCommand(selectstring, oSqlConn)
            sqlcommand.CommandTimeout = Me.txtTimeout.Text
            oSqlConn.Open()
            Dim oSQLDataAdapter As SqlClient.SqlDataAdapter = New SqlClient.SqlDataAdapter
            Dim oDataSet As DataSet = New DataSet
            oSQLDataAdapter.SelectCommand = sqlcommand
            oSQLDataAdapter.Fill(oDataSet, "DATA")
            ATRDATATABLE = oDataSet.Tables(0)
            VWMarkt_VerfolgungBindingSource.DataSource = oDataSet.Tables(0)
            GridControlATR.DataSource = VWMarkt_VerfolgungBindingSource
            '  VWMarkt_VerfolgungTableAdapter.Connection.ConnectionString = My.Settings.ConfigConnectionString
            ' Me.VWMarkt_VerfolgungTableAdapter.Fill(Me.MyDataset.VWMarkt_Verfolgung, markt, datevon, datebis)
        Catch ex As System.Exception
            MsgBox(ex.Message, MsgBoxStyle.Critical, "Fehler bei Refresh_Marktverfolgung:")
        End Try
        Me.Cursor = Cursors.Default
    End Sub

    Private Sub ToolStripButton35_Click(sender As System.Object, e As System.EventArgs) Handles ToolStripButton35.Click
        Try
            Dim Markt As String = DGVTBWH_MARKT_VF.CurrentCell.Value()
            Refresh_Marktverfolgung(Markt, Me.dtpVerfolgung_von.Text, Me.dtpVerfolgung_bis.Text)
        Catch ex As Exception

        End Try

    End Sub

    Private Sub ToolStripButton36_Click(sender As System.Object, e As System.EventArgs) Handles ToolStripButton36.Click
        Me.Cursor = Cursors.WaitCursor
        XLS_FILTER_TEMP_DT(ATRDATATABLE, "ATR Zeitraum")
        Cursor = Cursors.Default
    End Sub
    Private Sub IMPORT_XMLTextBox_TextChanged(sender As System.Object, e As System.EventArgs) Handles IMPORT_XMLTextBox.TextChanged, IMPORT_XMLARCHIVTextBox.TextChanged, IMPORT_BESTELLUNGENTextBox.TextChanged
        Me.btnsavePath.Visible = True
    End Sub

    Private Sub btnsavePath_Click(sender As System.Object, e As System.EventArgs) Handles btnsavePath.Click
        If Konfiguration_save() = True Then
            Me.btnsavePath.Visible = False
        End If
    End Sub
    Private Sub VWSUPPLIES_DG_Click(sender As System.Object, e As System.EventArgs)


    End Sub
    Private Sub tsbtnNAchverfolgung_Click(sender As System.Object, e As System.EventArgs) Handles tsbtnNAchverfolgung.Click
        open_Verfolgung()
    End Sub
    Sub open_Verfolgung()
        'Try
        Cursor = Cursors.WaitCursor
        Dim frm As New frmNachverfolgung
        frm = frmNachverfolgung.Instance
        frm.Show()
        Cursor = Cursors.Default
        '  Catch ex As Exception
        'W%MsgBox(ex.Message, MsgBoxStyle.Critical, "Fehler bei open Verfolgung:")
        ' End Try

    End Sub

    Private Sub ToolStripButton1_Click(sender As System.Object, e As System.EventArgs) Handles ToolStripButton1.Click
        Try
            TBMANDANTENBindingSource.EndEdit()
            If MyDataset.TBMANDANTEN.GetChanges Is Nothing = False Then
                GEAENDERTWERTextBox1.Text = Environment.UserName
                TBMANDANTENBindingSource.EndEdit()
                TBMANDANTENTableAdapter.Update(MyDataset.TBMANDANTEN)
                MsgBox("Änderungen wurden erfolgreich gespeichert!", MsgBoxStyle.Information, "Erfolgsmeldung:")
            End If
        Catch ex As Exception
            MsgBox(ex.Message, MsgBoxStyle.Critical, "Fehler bei Speichern Mandanten:")
        End Try
    End Sub
    Private Sub cmbMandanten_SelectedIndexChanged(sender As Object, e As System.EventArgs) Handles cmbMandanten.SelectedIndexChanged
        If cmbMandanten.SelectedIndex <> -1 Then
            Dim mandant_id As Integer = TBMANDANTENTableAdapter.cmdGetMandID(cmbMandanten.SelectedItem)
            My.Settings.Mandant_ID = mandant_id
        End If
    End Sub
    Private Sub BindingNavigatorAddNewItem_Click(sender As System.Object, e As System.EventArgs) Handles BindingNavigatorAddNewItem.Click
        TBMANDANTENBindingSource.AddNew()
    End Sub
    Private Sub TBMANDANTENBindingSource_AddingNew(sender As Object, e As System.ComponentModel.AddingNewEventArgs) Handles TBMANDANTENBindingSource.AddingNew
        MyDataset.TBMANDANTEN.ERSTELLLTWERColumn.DefaultValue = Environment.UserName
    End Sub
    Private Sub tsbtnChangelog_Click(sender As Object, e As EventArgs) Handles tsbtnChangelog.Click
        Try
            If tsbtnChangelog.Text = "Zeige ChangeLog" Then
                tsbtnChangelog.Text = "Ausblenden ChangeLog"
                Dim GERAET_ID As Integer = GridViewGeraete.GetFocusedRowCellValue(GridViewGeraete.Columns("GUID"))
                Refresh_ChangeLog(GERAET_ID)
                SplitContainerGeraet.Collapsed = False
            Else
                tsbtnChangelog.Text = "Zeige ChangeLog"
                SplitContainerGeraet.Collapsed = True
            End If
        Catch ex As Exception
            MsgBox(ex.Message, MsgBoxStyle.Critical, "Fehler bei Anzeige Changelog:")
        End Try

    End Sub

    Private Sub Refresh_ChangeLog(GID As Integer)
        Cursor = Cursors.WaitCursor
        Try
            Me.TBCHANGE_LOG_GERAETTableAdapter.Fill(Me.MyDataset.TBCHANGE_LOG_GERAET, GID)
        Catch ex As System.Exception
            MsgBox("Fehler bei Refresh ChangeLog:" & vbNewLine & ex.Message, MsgBoxStyle.Critical)
        End Try
        Cursor = Cursors.Default

    End Sub

    Private Sub tsbtnSuppliesSetStatusOnHold_Click(sender As Object, e As EventArgs) Handles tsbtnSuppliesSetStatusOnHold.Click
        Try
            Cursor = Cursors.WaitCursor
            Dim i As Integer
            i = VWSUPPLIES_AKTUELLDataGridView.CurrentRow.Index
            If VWSUPPLIES_AKTUELLDataGridView.Item("VWSUPPLIES_AKTUELLDataGridViewSupplyID", i).Value Is Nothing = False Then
                SelSupplyID = VWSUPPLIES_AKTUELLDataGridView.Item(0, i).Value
                Dim _bit As Boolean = VWSUPPLIES_AKTUELLDataGridView.Item("VWSUPPLIES_AKTUELLDataGridViewOnHold", i).Value
                Dim _State As Integer
                If _bit = False Then
                    _State = 1
                Else
                    _State = 0
                End If
                Me.TBSUPPLIESTableAdapter.CmdUpdateOnHold(Environment.UserName, _State, SelSupplyID)
                Try
                    Dim ID As Integer
                    Dim GERAET_ID As Integer = GridViewGeraete.GetFocusedRowCellValue(GridViewGeraete.Columns("GUID"))
                    Me.VWSUPPLIES_GERAETTableAdapter.FillByGeraet(MyDataset.VWSUPPLIES_AKTUELL, GERAET_ID)
                Catch ex As Exception
                    MessageBox.Show(ex.Message, "Fehler beim Laden der Supply-Daten nach Update OnHold:", MessageBoxButtons.OK, MessageBoxIcon.Error)
                End Try
            End If
        Catch ex As System.Exception
            MsgBox(ex.Message, MsgBoxStyle.Critical, "Fehler bei ONHOLD-Setzen Supply:")
        End Try
        Cursor = Cursors.Default
    End Sub

    Private Sub VWSUPPLIES_AKTUELLDataGridView_SelectionChanged(sender As Object, e As EventArgs) Handles VWSUPPLIES_AKTUELLDataGridView.SelectionChanged
        Try
            If FormLoaded = True And VWSUPPLIES_AKTUELLDataGridView.RowCount > 0 Then
                Dim i = VWSUPPLIES_AKTUELLDataGridView.CurrentRow.Index
                SelSupplyID = VWSUPPLIES_AKTUELLDataGridView.Item("VWSUPPLIES_AKTUELLDataGridViewSupplyID", i).Value

                Me.ViewSUPPLY_STATUS_VERFOLGUNGTableAdapter.Fill(Me.MyDataset.ViewSUPPLY_STATUS_VERFOLGUNG, SelSupplyID)
                Dim marker As String = TBSUPPLIESTableAdapter.CMDGetMarker(SelSupplyID)
                If marker Is Nothing = False Then
                    Me.tslbl_Hinweis.Text = marker
                    Me.tslbl_Hinweis.Visible = True
                Else
                    Me.tslbl_Hinweis.Visible = False
                End If
            End If
        Catch ex As Exception
            MsgBox(ex.Message, MsgBoxStyle.Critical, "VWSUPPLIES_GERAETDataGridView.SelectionChanged:")
        End Try
    End Sub

    Private Sub ToolStripButton10_Click_1(sender As Object, e As EventArgs) Handles ToolStripButton10.Click
        Dim frm As New frmServiceImportLog
        frm.ShowDialog()
    End Sub

    Private Sub SplitContainerSupplyBestellungen_SplitterMoved(sender As Object, e As SplitterEventArgs)
        If SPCOrder.Panel2Collapsed = False Then
            My.Settings.Save()
        End If
    End Sub

    Private Sub SplitContainerSupplies_SplitterMoved(sender As Object, e As SplitterEventArgs) Handles SplitContainerSupplies.SplitterMoved
        My.Settings.Save()
    End Sub
    Sub Load_Nachverfolgung_Supplies()
        Try
            If FormLoaded = True And VWSUPPLIES_2_ORDERBindingSource.Count > 0 And SPCOrder.Panel2Collapsed = False Then
                Dim SupplyID = GridViewSupplies2Order.GetFocusedRowCellValue(GridViewSupplies2Order.Columns("SUPPLY_ID"))
                Me.Cursor = Cursors.WaitCursor
                Me.VWSUPPLY_VERFOLGUNGTableAdapter.FillBySUPPLYID(Me.MyDataset.VWSUPPLY_VERFOLGUNG, SupplyID)
            End If
        Catch ex As Exception
            MsgBox("Fehler in VWSUPPLIES_GERAETDataGridView.SelectionChanged:" & vbNewLine & ex.Message, MsgBoxStyle.Critical, )
        End Try
        Me.Cursor = Cursors.Default
    End Sub


    Private Sub tsbtnChangebestellt_Click(sender As Object, e As EventArgs) Handles tsbtnChangebestellt.Click
        Try
            Cursor = Cursors.WaitCursor
            Dim i As Integer
            i = VWSUPPLIES_AKTUELLDataGridView.CurrentRow.Index
            If VWSUPPLIES_AKTUELLDataGridView.Item("VWSUPPLIES_AKTUELLDataGridViewSupplyID", i).Value Is Nothing = False Then
                SelSupplyID = VWSUPPLIES_AKTUELLDataGridView.Item(0, i).Value
                TBSUPPLIESTableAdapter.cmdUpdateBestelltManuell(Environment.UserName, "BESTELL_STATUS durch User per Oberfläche", SelSupplyID)
                Try
                    Dim GERAET_ID As Integer = GridViewGeraete.GetFocusedRowCellValue(GridViewGeraete.Columns("GUID"))
                    Me.VWSUPPLIES_GERAETTableAdapter.FillByGeraet(MyDataset.VWSUPPLIES_AKTUELL, GERAET_ID)
                Catch ex As Exception
                    MessageBox.Show(ex.Message, "Fehler beim Laden der Supply-Daten nach Update Bestellt:", MessageBoxButtons.OK, MessageBoxIcon.Error)
                End Try
            End If
        Catch ex As System.Exception
            MsgBox(ex.Message, MsgBoxStyle.Critical, "Fehler bei BESTELLT-Setzen Supply:")
        End Try
        Cursor = Cursors.Default
    End Sub


    Sub Load_Bestellung_Gesendet()
        Try
            Cursor = Cursors.WaitCursor
            VWSUPPLIES_BESTELLUNG_GESENDETTableAdapter.Connection.ConnectionString = My.Settings.ConfigConnectionString
            Me.VWSUPPLIES_BESTELLUNG_GESENDETTableAdapter.Fill(Me.MyDataset.VWSUPPLIES_BESTELLUNG_GESENDET, cmbMandanten.Text)
        Catch ex As System.Exception
            MsgBox(ex.Message, MsgBoxStyle.Critical, "Fehler in Load_Bestellung_Gesendet:")
        End Try
        Cursor = Cursors.Default
    End Sub
    Sub Load_GridLayout_BestGesendet()
        Try
            Dim XMLPath = ClassHelper.GetSelectionGridName("GridViewBestellungen_Gesendet")
            If File.Exists(XMLPath) Then
                GridControlBestellungen_gesendet.MainView.RestoreLayoutFromXml(XMLPath)
                GridViewBestellungen_Gesendet.ClearColumnsFilter()
                'grvwSelection.ClearGrouping()
                GridViewBestellungen_Gesendet.ClearSelection()
                GridViewBestellungen_Gesendet.OptionsView.ShowPreview = False
            End If
        Catch ex As Exception

        End Try

    End Sub
    Sub Load_GridLayout_Geraete()
        Try
            Dim XMLPath = ClassHelper.GetSelectionGridName("GridViewGeraete")
            If File.Exists(XMLPath) Then
                GridControlGeraete.MainView.RestoreLayoutFromXml(XMLPath)
                GridViewGeraete.ClearColumnsFilter()
                'grvwSelection.ClearGrouping()
                GridViewGeraete.ClearSelection()
                GridViewGeraete.OptionsView.ShowPreview = False
            End If
        Catch ex As Exception

        End Try

    End Sub
    Sub Load_GridLayoutSupplies()
        Try
            Dim XMLPath = ClassHelper.GetSelectionGridName("GridViewVWSupplies")
            If File.Exists(XMLPath) Then
                GridControlVWSupplies.MainView.RestoreLayoutFromXml(XMLPath)
                GridViewVWSupplies.ClearColumnsFilter()
                'grvwSelection.ClearGrouping()
                GridViewVWSupplies.ClearSelection()
                GridViewVWSupplies.OptionsView.ShowPreview = False
            End If
        Catch ex As Exception

        End Try

    End Sub
    Sub Load_GridLayout_Supllies2Order()
        Try
            Dim XMLPath = ClassHelper.GetSelectionGridName("GridViewSupplies2order")
            If File.Exists(XMLPath) Then
                GridControlSupplies2Order.MainView.RestoreLayoutFromXml(XMLPath)
                'GridViewSupplies2Order.ClearColumnsFilter()
                'grvwSelection.ClearGrouping()
                GridViewSupplies2Order.ClearSelection()
                GridViewSupplies2Order.OptionsView.ShowPreview = False
            End If
        Catch ex As Exception

        End Try

    End Sub
    Sub Load_GridLayout_Bestuebersicht()
        Try
            Dim XMLPath = ClassHelper.GetSelectionGridName("GridViewBestellungen_Uebersicht")
            If File.Exists(XMLPath) Then
                GridControlBestellungen.MainView.RestoreLayoutFromXml(XMLPath)
                GridViewBestellUebersicht.ClearColumnsFilter()
                'grvwSelection.ClearGrouping()
                GridViewBestellUebersicht.ClearSelection()
                GridViewBestellUebersicht.OptionsView.ShowPreview = False
            End If
        Catch ex As Exception

        End Try

    End Sub
    Sub Load_GridLayout_SupplyZuordnung()
        Try
            Dim XMLPath = ClassHelper.GetSelectionGridName("GridViewSupplyZuordnung")
            If File.Exists(XMLPath) Then
                GridControlSupplyZuordnung.MainView.RestoreLayoutFromXml(XMLPath)
                GridViewSupplyZuordnung.ClearColumnsFilter()
                'grvwSelection.ClearGrouping()
                GridViewSupplyZuordnung.ClearSelection()
                GridViewSupplyZuordnung.OptionsView.ShowPreview = False
            End If
        Catch ex As Exception

        End Try

    End Sub
    Sub Load_GridLayout_ProduktVertrag()
        Try
            Dim XMLPath = ClassHelper.GetSelectionGridName("GridViewProduktVertrag")
            If File.Exists(XMLPath) Then
                GridControlProduktVertrag.MainView.RestoreLayoutFromXml(XMLPath)
                GridViewProduktVertrag.ClearColumnsFilter()
                'grvwSelection.ClearGrouping()
                GridViewProduktVertrag.ClearSelection()
                GridViewProduktVertrag.OptionsView.ShowPreview = False
            End If
        Catch ex As Exception

        End Try

    End Sub
    Sub Save_GridLayout_Supplies()
        Dim XMLPath = ClassHelper.GetSelectionGridName("GridViewVWSupplies")
        GridControlVWSupplies.MainView.SaveLayoutToXml(XMLPath)
    End Sub
    Sub Save_GridLayout_Geraete()
        Dim XMLPath = ClassHelper.GetSelectionGridName("GridViewGeraete")
        GridControlGeraete.MainView.SaveLayoutToXml(XMLPath)
    End Sub
    Sub Save_GridLayout_Supplies2Order()
        Dim XMLPath = ClassHelper.GetSelectionGridName("GridViewSupplies2order")
        GridControlSupplies2Order.MainView.SaveLayoutToXml(XMLPath)
    End Sub
    Sub Save_GridLayout_Bestuebersicht()
        Dim XMLPath = ClassHelper.GetSelectionGridName("GridViewBestellungen_Uebersicht")
        GridControlBestellungen.MainView.SaveLayoutToXml(XMLPath)
    End Sub
    Sub Save_GridLayout_BestGesendet()
        Dim XMLPath = ClassHelper.GetSelectionGridName("GridViewBestellungen_Gesendet")
        GridControlBestellungen_gesendet.MainView.SaveLayoutToXml(XMLPath)
    End Sub

    Sub Save_GridLayout_SupplyZuordnung()
        Dim XMLPath = ClassHelper.GetSelectionGridName("GridViewSupplyZuordnung")
        GridControlSupplyZuordnung.MainView.SaveLayoutToXml(XMLPath)
    End Sub
    Sub Save_GridLayout_ProduktVertrag()
        Dim XMLPath = ClassHelper.GetSelectionGridName("GridViewProduktVertrag")
        GridControlProduktVertrag.MainView.SaveLayoutToXml(XMLPath)
    End Sub



    Private Sub ToolStripButton16_Click(sender As Object, e As EventArgs) Handles ToolStripButton16.Click
        Load_Bestellung_Gesendet()
    End Sub

    Private Sub tsbtn_setBack2Besterford_Click(sender As Object, e As EventArgs) Handles tsbtn_setBack2Besterford.Click
        Try
            Dim sql As String
            'Überhaupt Rows in Grid?
            If GridViewBestellungen_Gesendet.RowCount > 0 Then
                Dim BestellID = GridViewBestellungen_Gesendet.GetFocusedRowCellValue(GridViewBestellungen_Gesendet.Columns(0))
                Dim SupplyID = GridViewBestellungen_Gesendet.GetFocusedRowCellValue(GridViewBestellungen_Gesendet.Columns(1))
                Dim Manuell = GridViewBestellungen_Gesendet.GetFocusedRowCellValue(GridViewBestellungen_Gesendet.Columns("MANUELL"))
                Dim BestelltWer = GridViewBestellungen_Gesendet.GetFocusedRowCellValue(GridViewBestellungen_Gesendet.Columns("BESTELLT_WER"))
                If BestellID Is Nothing = False And Not IsNothing(SupplyID) Then
                    If Manuell = False Then
                        sql = String.Format("UPDATE TBSUPPLIES SET STATUS_ID = 2, GEAENDERTWER = '{0}', MARKER = 'Frontend' WHERE GUID = {1} AND STATUS_ID = 10", Environment.UserName, SupplyID)
                        If ClassDatabase.Execute_non_Query(sql, True) = True Then
                            'sql = String.Format("DELETE FROM TBSUPPLY_BESTELLUNG WHERE (GUID = {0})", BestellID)
                            'ClassDatabase.Execute_non_Query(sql, True)

                        End If
                    Else
                        Dim marker
                        If BestelltWer.ToString.StartsWith("FW_") Then
                            marker = "MANUELLE BESTELLUNG PER FLEETWATCH"
                        Else
                            marker = "MANUELLE BESTELLUNG PER SUPPLYWATCH"
                        End If
                        sql = String.Format("INSERT INTO TBSUPPLIES_2_ORDER_TEMP (SUPPLY_ID,MARKER,ERFASSTWER,MANUALLY,BESTELL_ID) VALUES ({0},'{1}','{2}',1,{3})", SupplyID, marker, BestelltWer, BestellID)
                        If ClassDatabase.Execute_non_Query(sql, True) = True Then
                            sql = String.Format("UPDATE TBSUPPLY_BESTELLUNG SET MARKER = 'Rückgängig Bestellung gesendet',STATE_MSG = 'Default', MANUELL_BESTELLT = 0 WHERE GUID = {0}", BestellID)
                            ClassDatabase.Execute_non_Query(sql, True)
                        End If
                    End If
                    Load_Bestellung_Gesendet()
                    tslbl_Hinweis.Text = "Bestellung gelöscht/Supply Status auf 'Bestell. erforderlich' - " & Now
                    tslbl_Hinweis.Visible = True
                Else
                    tslbl_Hinweis.Visible = False

                End If
            End If
        Catch ex As Exception
            MsgBox(ex.Message, MsgBoxStyle.Critical, "Fehler in Set Back 2 'Bestellung erforderlich':")
            tslbl_Hinweis.Visible = False
        End Try
    End Sub

    Private Sub Button2_Click(sender As Object, e As EventArgs) Handles Button2.Click
        Process.Start(Application.UserAppDataPath())
    End Sub

    Private Sub ToolStripButton38_Click(sender As Object, e As EventArgs) Handles tsbtnSet2BestelltManually.Click
        Dim result As MsgBoxResult
        result = MessageBox.Show("Wirklich manuell auf BESTELLT setzen?", "Bestätigung::", MessageBoxButtons.YesNo, MessageBoxIcon.Question)
        If result = MsgBoxResult.No Then
            Exit Sub
        End If
        Try
            Dim sql As String
            'Überhaupt Rows in Grid?
            If GridViewBestellungen_Gesendet.RowCount > 0 Then
                Dim BestellID = GridViewBestellungen_Gesendet.GetFocusedRowCellValue(GridViewBestellungen_Gesendet.Columns(0))
                Dim SupplyID = GridViewBestellungen_Gesendet.GetFocusedRowCellValue(GridViewBestellungen_Gesendet.Columns(1))
                Dim Manuell = GridViewBestellungen_Gesendet.GetFocusedRowCellValue(GridViewBestellungen_Gesendet.Columns("MANUELL"))
                Dim BestelltWer = GridViewBestellungen_Gesendet.GetFocusedRowCellValue(GridViewBestellungen_Gesendet.Columns("BESTELLT_WER"))
                If BestellID Is Nothing = False And Not IsNothing(SupplyID) Then
                    If Manuell = False Then
                        sql = String.Format("UPDATE TBSUPPLIES SET STATUS_ID = 4, STATUS_WER = '{0}', MARKER = 'MANUALLY FROM BESTELLUNG GESENDET' WHERE (STATUS_ID = 10) AND (GUID = {1})", Environment.UserName, SupplyID)
                        If ClassDatabase.Execute_non_Query(sql, True) = True Then
                            sql = String.Format("UPDATE TBSUPPLY_BESTELLUNG SET BESTELLT_WANN = GETDATE(), BESTELLNR = 'PLEASE UPDATE MANUALLY', MARKER = 'Status Bestellt manuell gesetzt durch: {0}' WHERE GUID = {1}", Environment.UserName, BestellID)
                            ClassDatabase.Execute_non_Query(sql, True)
                        End If
                        'TBSUPPLIESTableAdapter.cmdSetBestellt(Environment.UserName, "MANUALLY FROM BESTELLUNG GESENDET", SupplyID)
                    Else
                        'If BestelltWer.ToString.StartsWith("FW_") Then
                        sql = String.Format("UPDATE TBSUPPLY_BESTELLUNG SET BESTELLT_WANN = GETDATE(), MARKER = 'Status Bestellt manuell gesetzt durch: {0}' WHERE GUID = {1}", Environment.UserName, BestellID)
                        ClassDatabase.Execute_non_Query(sql, True)
                        ' End If
                    End If

                    Load_Bestellung_Gesendet()
                    tslbl_Hinweis.Text = "Bestell-ID '" & BestellID.ToString & "' - manuell auf 'Bestellt' gesetzt - " & Now
                    tslbl_Hinweis.Visible = True
                Else
                    tslbl_Hinweis.Visible = False

                End If
            End If
        Catch ex As Exception
            MsgBox(ex.Message, MsgBoxStyle.Critical, "Fehler in Set Back 2 'Bestellung erforderlich':")
            tslbl_Hinweis.Visible = False
        End Try
    End Sub

    Private Sub GridViewBestellUebersicht_RowUpdated(sender As Object, e As DevExpress.XtraGrid.Views.Base.RowObjectEventArgs) Handles GridViewBestellUebersicht.RowUpdated
        Try
            If FormLoaded = True Then
                'Überhaupt Rows in Grid?
                If GridViewBestellUebersicht.RowCount > 0 Then
                    Dim coc = GridViewBestellUebersicht.FocusedValue
                    Dim BestellNr = GridViewBestellUebersicht.GetFocusedRowCellValue(GridViewBestellUebersicht.Columns("BestellNr"))
                    Dim ID = GridViewBestellUebersicht.GetFocusedRowCellValue(GridViewBestellUebersicht.Columns("MC2BestellID"))
                    Dim Menge = GridViewBestellUebersicht.GetFocusedRowCellValue(GridViewBestellUebersicht.Columns("Menge"))
                    If BestellNr Is Nothing = False And Not IsNothing(ID) Then
                        tslbl_Hinweis.Text = "Bestell-Nr./Menge eingepflegt/geändert' - " & Now
                        tslbl_Hinweis.Visible = True
                        Me.TBSUPPLY_BESTELLUNGViewTableAdapter.cmdUpdate_BestNr(BestellNr, Environment.UserName, Menge, ID)
                        Dim XMLPath = ClassHelper.GetSelectionGridName("GridViewBestellungen_Gesendet")
                        Save_GridLayout_Bestuebersicht()
                        Refresh_Bestellungen()
                    Else
                        tslbl_Hinweis.Visible = False
                    End If
                End If
            End If
        Catch ex As Exception
            MsgBox(ex.Message, MsgBoxStyle.Critical, "Fehler beim Aktualisieren der BestellNr:")
            tslbl_Hinweis.Visible = False
        End Try
    End Sub

    Private Sub ToolStripButton37_Click(sender As Object, e As EventArgs) Handles ToolStripButton37.Click
        Dim saveFileDialog1 As New SaveFileDialog
        saveFileDialog1.Filter = "Excel (*.xls)|*.xls|Excel (*.xlsx)|*.xlsx"
        saveFileDialog1.Title = "Export to Excel:"
        saveFileDialog1.ShowDialog()
        If saveFileDialog1.FileName <> "" Then
            Cursor = Cursors.WaitCursor
            If saveFileDialog1.FileName.EndsWith("xlsx") Then
                GridViewBestellungen_Gesendet.ExportToXlsx(saveFileDialog1.FileName)
            Else
                GridViewBestellungen_Gesendet.ExportToXls(saveFileDialog1.FileName)
            End If
            Dim result As MsgBoxResult
            result = MessageBox.Show("Datei wurde erstellt! Wollen Sie diese nun öffnen?", "Erfolgsmeldung:", MessageBoxButtons.YesNo, MessageBoxIcon.Question)
            If result = MsgBoxResult.Yes Then
                Process.Start(saveFileDialog1.FileName)
            End If


        End If
        Cursor = Cursors.Default
    End Sub
    Private Sub GridViewGeraete_FocusedColumnChanged(sender As Object, e As DevExpress.XtraGrid.Views.Base.FocusedColumnChangedEventArgs) Handles GridViewGeraete.FocusedColumnChanged
        ROWCOL_Change_Geraet()
    End Sub

    Private Sub GridViewGeraete_FocusedRowChanged(sender As Object, e As DevExpress.XtraGrid.Views.Base.FocusedRowChangedEventArgs) Handles GridViewGeraete.FocusedRowChanged
        ROWCOL_Change_Geraet()
    End Sub
    Sub ROWCOL_Change_Geraet()
        If FormLoaded = True Then
            Try
                If Me.TBGERAETBindingSource.Count = 0 Then
                    Exit Sub
                End If
                Dim GERAET_ID As Integer = GridViewGeraete.GetFocusedRowCellValue(GridViewGeraete.Columns("GUID"))
                If CURRENT_GERAETE_ID <> GERAET_ID Then
                    CURRENT_GERAETE_ID = GERAET_ID
                    Try
                        Me.VWSUPPLIES_GERAETTableAdapter.FillByGeraet(MyDataset.VWSUPPLIES_AKTUELL, GERAET_ID)
                    Catch ex As Exception
                        MessageBox.Show(ex.Message, "Fehler beim Laden der Supply-Daten:", MessageBoxButtons.OK, MessageBoxIcon.Error)
                    End Try
                    Refresh_ChangeLog(GERAET_ID)
                End If
            Catch ex As Exception
                Exit Sub
            End Try

        End If
    End Sub

    Private Sub ToolStripButton6_Click(sender As Object, e As EventArgs) Handles tsbtnManaulOrders.Click
        Load_Bestellungen_Manuell()
    End Sub

    Private Sub btnTSR_open_Click(sender As Object, e As EventArgs) Handles btnTSR_open.Click
        If cmbMandant.SelectedIndex = -1 Then
            Exit Sub
        End If
        If OpenFileDialog1.ShowDialog() = System.Windows.Forms.DialogResult.OK Then
            Try
                ClassLogger.Init("", "ImportTSR_", False)
                If chkLogData.Checked Then MsgBox("Working on file: " & OpenFileDialog1.FileName)
                Dim _DS As New DataSet
                'Datei auslesen und Dataset rückgeben lassen
                _DS = XLSReader(OpenFileDialog1.FileName, "Report")
                If _DS Is Nothing Then
                    MsgBox("Datei: " & vbNewLine & OpenFileDialog1.FileName & vbNewLine & " wurde nicht verarbeitet!", MsgBoxStyle.Exclamation, "Achtung:")
                Else
                    Me.Cursor = Cursors.WaitCursor
                    If chkLogData.Checked Then ClassLogger.Add("XLSReaderTSR finished....", False)

                    'MsgBox("Anzahl: " & _DS.Tables(0).Rows.Count & vbNewLine & "Hier müssten jetzt die Updates erfolgen")
                    Dim DT As System.Data.DataTable
                    Dim DR As System.Data.DataRow
                    ' Dim DC As System.Data.DataColumn
                    '' --- DataSet zuweisen
                    'DS = Me.MyDataset
                    '' --- Zugriff auf Tabelle
                    DT = _DS.Tables(0)
                    Dim _ORDER_ID, _CREATE_DT, _SHIP_DT, _DEV_SERIAL_NO, _ORD_PART_NO, _ORD_QTY, _SHIP_QTY, _TRACKING_NO, _SHIPTO_POSTCODE, _CUSTOM_LABEL_1, _CUSTOM_LABEL_2 As String

                    'Überprüfen wie die Datei aufgebaut/bearbeitet wurde?
                    Dim RowIndex = 1
                    Dim ordercount As Integer = 0
                    Dim _error As Boolean = False
                    If chkLogData.Checked Then ClassLogger.Add("DS contains '" & DT.Rows.Count & "' rows!", False)
                    For Each DR In DT.Rows
                        If RowIndex >= 1 Then '>= 3 Then
                            Dim FirstColumnValue = DR.Item(0)
                            Dim DateValue = DR.Item(3)
                            If IsNumeric(FirstColumnValue) And IsDate(DateValue) Then
                                If chkLogData.Checked Then ClassLogger.Add("Working on Order '" & FirstColumnValue & "'...", False)
                                Try
                                    _ORDER_ID = FirstColumnValue
                                Catch ex As Exception
                                    ClassLogger.Add("Could not convert _ORDER_ID", False)
                                    Continue For
                                End Try
                                Try
                                    _SHIP_DT = DR.Item(3).ToString
                                    _SHIP_DT = DR.Item(3).ToString.Replace("'", "")
                                Catch ex As Exception
                                    If Not ex.Message.Contains("Replace für den Typ Double") Then
                                        _SHIP_DT = ""
                                    End If
                                End Try
                                Try
                                    _CREATE_DT = DR.Item(2).ToString
                                    _CREATE_DT = DR.Item(2).ToString.Replace("'", "")
                                Catch ex As Exception
                                    If Not ex.Message.Contains("Replace für den Typ Double") Then
                                        _CREATE_DT = ""
                                    End If
                                End Try
                                Try
                                    _DEV_SERIAL_NO = DR.Item(10)
                                    _DEV_SERIAL_NO = DR.Item(10).Replace("'", "")
                                Catch ex As Exception
                                    If Not ex.Message.Contains("Replace für den Typ Double") Then
                                        _DEV_SERIAL_NO = ""
                                    End If
                                End Try
                                Try
                                    _ORD_PART_NO = DR.Item(13)
                                    _ORD_PART_NO = DR.Item(13).Replace("'", "")
                                Catch ex As Exception
                                    If Not ex.Message.Contains("Replace für den Typ Double") Then
                                        _ORD_PART_NO = ""
                                    End If
                                End Try
                                Try
                                    _ORD_QTY = DR.Item(15)
                                    If IsNumeric(_ORD_QTY) = False Then
                                        _SHIP_QTY = DR.Item(15).Replace("'", "")
                                    End If
                                Catch ex As Exception
                                    If Not ex.Message.Contains("Replace für den Typ Double") Then
                                        _ORD_QTY = "1"
                                    End If

                                End Try
                                Try
                                    _SHIP_QTY = DR.Item(16)
                                    If IsNumeric(_SHIP_QTY) = False Then
                                        _SHIP_QTY = DR.Item(16).Replace("'", "")
                                    End If

                                Catch ex As Exception
                                    If Not ex.Message.Contains("Replace für den Typ Double") Then
                                        _SHIP_QTY = "1"
                                    End If

                                End Try
                                Try
                                    _TRACKING_NO = DR.Item(19).ToString
                                    _TRACKING_NO = DR.Item(19).Replace("'", "")
                                Catch ex As Exception
                                    If Not ex.Message.Contains("Replace für den Typ Double") Then
                                        _TRACKING_NO = ""
                                    End If
                                End Try
                                Try
                                    _SHIPTO_POSTCODE = DR.Item(26)
                                    _SHIPTO_POSTCODE = DR.Item(26).Replace("'", "")
                                Catch ex As Exception
                                    If Not ex.Message.Contains("Replace für den Typ Double") Then
                                        _SHIPTO_POSTCODE = ""
                                    End If
                                End Try
                                Try
                                    _CUSTOM_LABEL_1 = DR.Item(29)
                                    _CUSTOM_LABEL_1 = DR.Item(29).Replace("'", "")
                                Catch ex As Exception
                                    If Not ex.Message.Contains("Replace für den Typ Double") Then
                                        _CUSTOM_LABEL_1 = ""
                                    End If
                                End Try
                                Try
                                    _CUSTOM_LABEL_2 = DR.Item(30)
                                    _CUSTOM_LABEL_2 = DR.Item(30).Replace("'", "")
                                Catch ex As Exception
                                    If Not ex.Message.Contains("Replace für den Typ Double") Then
                                        _CUSTOM_LABEL_2 = ""
                                    End If
                                End Try
                                Dim del = $"DELETE FROM TBTONER_SHIPMENT_REPORT WHERE ORDER_ID = '{_ORDER_ID}' AND DEV_SERIAL_NO = '{_DEV_SERIAL_NO}' AND TRACKING_NO = '{_TRACKING_NO}'"
                                If ClassDatabase.Execute_non_Query(del) = True Then
                                    Dim ins = String.Format("INSERT INTO TBTONER_SHIPMENT_REPORT ([ORDER_ID],[SHIP_DT],[DEV_SERIAL_NO],[ORD_PART_NO],[ORD_QTY],[SHIP_QTY],[TRACKING_NO],[SHIPTO_POSTCODE],[CUSTOM_LABEL_1],[CUSTOM_LABEL_2],[ADDED_WHO], MANDANT_ID,CREATE_DT) VALUES (
                                    '{0}','{1}','{2}','{3}','{4}','{5}','{6}','{7}','{8}','{9}','{10}',{11},'{12}')", _ORDER_ID, _SHIP_DT, _DEV_SERIAL_NO, _ORD_PART_NO, _ORD_QTY, _SHIP_QTY, _TRACKING_NO, _SHIPTO_POSTCODE, _CUSTOM_LABEL_1, _CUSTOM_LABEL_2, Environment.UserName, cmbMandant.SelectedValue, _CREATE_DT)
                                    If ClassDatabase.Execute_non_Query(ins) = False Then
                                        _error = True
                                    Else
                                        ordercount += 1
                                    End If
                                End If
                            Else
                                Console.WriteLine("No datevalue: " & DateValue.ToString & " - " & FirstColumnValue.ToString)
                            End If
                        End If
                        RowIndex += 1

                    Next
                    If _error = False And ordercount > 1 Then
                        MsgBox(String.Format("Es wurden {0} Reportzeilen erfolgreich eingelesen!", ordercount), MsgBoxStyle.Information)
                    Else
                        MsgBox("Die Datei wurde verarbeitet, allerdings ereigneten sich hierbei Fehler!", MsgBoxStyle.Exclamation)
                    End If
                End If
            Catch ex As Exception
                MsgBox(ex.Message, MsgBoxStyle.Critical, "Error in working TonerShipment:")
            End Try
            Me.Cursor = Cursors.Default
        End If
    End Sub
    Dim IsFilterMode As Boolean = False
    Private Sub GridViewBestellUebersicht_RowStyle(sender As Object, e As DevExpress.XtraGrid.Views.Grid.RowStyleEventArgs) Handles GridViewBestellUebersicht.RowStyle
        If e.RowHandle = -1 Then
            IsFilterMode = True
            Exit Sub
        Else
            IsFilterMode = False
        End If
        If e.RowHandle = DevExpress.XtraGrid.GridControl.AutoFilterRowHandle Then
            IsFilterMode = True
            e.Appearance.BackColor = Color.Orange

        Else
            IsFilterMode = False
            Try
                Dim rowCellValue = GridViewBestellUebersicht.GetRowCellValue(e.RowHandle, "BestellNr")
                If rowCellValue <> "" Then
                    If rowCellValue = "PLEASE UPDATE MANUALLY" Then
                        e.Appearance.BackColor = Color.Red
                        e.HighPriority = True
                    End If

                End If
            Catch ex As Exception
                    ClassLogger.Add(">> Unexpected Error in RowStyle: " & ex.Message, False)
                End Try

        End If
    End Sub

    Private Sub GridControlBestellungen_Leave(sender As Object, e As EventArgs) Handles GridControlBestellungen.Leave
        Save_GridLayout_Bestuebersicht()
    End Sub

    Private Sub tscmbaktiv_Click(sender As Object, e As EventArgs) Handles tscmbaktiv.Click

    End Sub

    Private Sub tsbtOrderSelectDate_Click(sender As Object, e As EventArgs) Handles tsbtOrderSelectDate.Click
        If pnlOrderDateSelector.Visible = False Then
            pnlOrderDateSelector.Visible = True
        Else
            pnlOrderDateSelector.Visible = False
        End If
    End Sub

    'Private Sub GridViewGeraetOrder_RowUpdated(sender As Object, e As DevExpress.XtraGrid.Views.Base.RowObjectEventArgs)
    '    If FormLoaded = True Then
    '        Try
    '            Me.VWGERAET_ORDERBindingSource.EndEdit()
    '            If MyDataset.VWGERAET_ORDER.GetChanges Is Nothing = False Then
    '                Dim BESTGESENDET = GridViewGeraetOrder.GetFocusedRowCellValue(GridViewGeraetOrder.Columns("BESTELLUNG"))
    '                Dim GUID = GridViewGeraetOrder.GetFocusedRowCellValue(GridViewGeraetOrder.Columns("GUID"))
    '                If BESTGESENDET = True Then
    '                    ClassDatabase.Execute_non_Query("UPDATE TBGERAET SET BESTELLUNG = 1 WHERE GUID = " & GUID, True)
    '                Else
    '                    ClassDatabase.Execute_non_Query("UPDATE TBGERAET SET BESTELLUNG = 0 WHERE GUID = " & GUID, True)
    '                    '                        Me.TBGERAETTableAdapter.CmdUpdateBestellungnein(GUID)
    '                End If
    '                ''MsgBox(VWGERAET_ORDERDG.Splits(VWGERAET_ORDERDG.SplitIndex).DisplayColumns(VWGERAET_ORDERDG.Col).DataColumn.Value, MsgBoxStyle.Information, DataColumn)
    '                'Select Case DataColumn
    '                '    Case "Bestellung ja/nein"
    '                '        Dim Value As Boolean = VWGERAET_ORDERDG.Splits(VWGERAET_ORDERDG.SplitIndex).DisplayColumns(VWGERAET_ORDERDG.Col).DataColumn.Value
    '                '        Dim GERAET_ID As Integer = VWGERAET_ORDERDG.Item(VWGERAET_ORDERDG.Row, "Geraete-ID")
    '                '        'MsgBox(VWGERAET_ORDERDG.Splits(VWGERAET_ORDERDG.SplitIndex).DisplayColumns(VWGERAET_ORDERDG.Col).DataColumn.Value, MsgBoxStyle.Information, DataColumn)
    '                '        If Value = True Then
    '                '            Me.TBGERAETTableAdapter.CmdBestellungJa(GERAET_ID)
    '                '        Else
    '                '            Me.TBGERAETTableAdapter.CmdUpdateBestellungnein(GERAET_ID)
    '                '        End If
    '                'End Select
    '            End If
    '        Catch ex As Exception
    '            MsgBox(ex.Message, MsgBoxStyle.Critical, "Fehler beim Markieren für Bestellung:")
    '        End Try
    '    End If
    'End Sub

    Private Sub GridViewVWSupplies_RowUpdated(sender As Object, e As DevExpress.XtraGrid.Views.Base.RowObjectEventArgs) Handles GridViewVWSupplies.RowUpdated
        If FormLoaded = True Then
            Try
                Me.VWSUPPLIESBindingSource.EndEdit()
                If MyDataset.VWSUPPLIES.GetChanges Is Nothing = False Then
                    Dim Schwellwert = GridViewVWSupplies.GetFocusedRowCellValue(GridViewVWSupplies.Columns("SCHWELLENWERT"))
                    Dim SUPPLY_ID = GridViewVWSupplies.GetFocusedRowCellValue(GridViewVWSupplies.Columns("SUPPLY_ID"))
                    Me.TBSUPPLIESTableAdapter.cmdUpdateSchwellenwert(Schwellwert, Environment.UserName, SUPPLY_ID)
                    'MsgBox(VWGERAET_ORDERDG.Splits(VWGERAET_ORDERDG.SplitIndex).DisplayColumns(VWGERAET_ORDERDG.Col).DataColumn.Value, MsgBoxStyle.Information, DataColumn)
                    Refresh_Supplies()
                End If
            Catch ex As Exception
                MsgBox(ex.Message, MsgBoxStyle.Critical, "Fehler beim Markieren für Bestellung:")
            End Try
        End If
    End Sub
    Private Sub GridViewSupplyZuordnung_RowUpdated(sender As Object, e As DevExpress.XtraGrid.Views.Base.RowObjectEventArgs) Handles GridViewSupplyZuordnung.RowUpdated
        If FormLoaded = True Then
            Try
                VWGeraet_Supply_ZuordnungBindingSource.EndEdit()
                If MyDataset.VWGeraet_Supply_Zuordnung.GetChanges Is Nothing = False Then
                    Cursor = Cursors.WaitCursor
                    Dim ID As Integer = GridViewSupplyZuordnung.GetFocusedRowCellValue(GridViewSupplyZuordnung.Columns("GUID"))
                    Dim SW As Integer = GridViewSupplyZuordnung.GetFocusedRowCellValue(GridViewSupplyZuordnung.Columns("SCHWELLENWERT"))
                    'MsgBox(Me.VWGeraet_Supply_ZuordnungDG.Item(VWGeraet_Supply_ZuordnungDG.Row, "Schwellenwert") & vbNewLine & Me.VWGeraet_Supply_ZuordnungDG.Item(VWGeraet_Supply_ZuordnungDG.Row, "ID"))
                    Me.VWGeraet_Supply_ZuordnungTableAdapter.CmdUpdateSW(SW, ID)
                    Refresh_Geraete_Supply()
                End If
            Catch ex As Exception
                MsgBox(ex.Message, MsgBoxStyle.Critical, "Fehler bei Update des Schwellenwertes:")
            End Try
            Cursor = Cursors.Default
        End If
    End Sub
    Private Sub GerätebestellungLöschenToolStripMenuItem_Click(sender As Object, e As EventArgs) Handles GerätebestellungLöschenToolStripMenuItem.Click
        Try
            If FormLoaded = True Then
                Dim G_ID = GridViewSupplies2Order.GetFocusedRowCellValue(GridViewSupplies2Order.Columns("GERAET_ID"))
                If G_ID > 0 Then
                    Dim del = String.Format("DELETE FROM TBSUPPLIES_2_ORDER_TEMP WHERE SUPPLY_ID in (SELECT GUID FROM TBSUPPLIES WHERE GERAET_ID = {0})", G_ID)
                    If ClassDatabase.Execute_non_Query(del.ToString, True) Then
                        Refresh_Supplies2Order(cmbMandanten.Text)
                    End If
                End If
            End If
        Catch ex As Exception
            MsgBox(ex.Message, MsgBoxStyle.Critical, "Fehler bei Löschen Supplybestellung für Gerät:")
        End Try

    End Sub

    Private Sub SupplybestellungLöschenToolStripMenuItem_Click(sender As Object, e As EventArgs) Handles SupplybestellungLöschenToolStripMenuItem.Click
        Try
            If FormLoaded = True Then
                Cursor = Cursors.WaitCursor
                Dim SupplyID = GridViewSupplies2Order.GetFocusedRowCellValue(GridViewSupplies2Order.Columns("SUPPLY_ID"))
                If SupplyID > 0 Then
                    Dim del = "DELETE FROM TBSUPPLIES_2_ORDER_TEMP WHERE SUPPLY_ID = " & SupplyID.ToString
                    If ClassDatabase.Execute_non_Query(del.ToString, True) Then
                        Refresh_Supplies2Order(cmbMandanten.Text)
                    End If
                End If
            End If
        Catch ex As Exception
            MsgBox(ex.Message, MsgBoxStyle.Critical, "Fehler bei Löschen Supplybestellung:")
        End Try
        Cursor = Cursors.Default

    End Sub

    Private Sub ToolStripButton38_Click_1(sender As Object, e As EventArgs) Handles ToolStripButton38.Click
        If SPCOrder.Panel2Collapsed = False Then
            SPCOrder.Panel2Collapsed = True
        Else
            Load_Nachverfolgung_Supplies()
            SPCOrder.Panel2Collapsed = False
        End If
    End Sub

    Private Sub GridViewSupplies2Order_FocusedRowChanged(sender As Object, e As DevExpress.XtraGrid.Views.Base.FocusedRowChangedEventArgs) Handles GridViewSupplies2Order.FocusedRowChanged
        Load_Nachverfolgung_Supplies()
    End Sub

    Private Sub GridViewSupplies2Order_CellValueChanged(sender As Object, e As DevExpress.XtraGrid.Views.Base.CellValueChangedEventArgs) Handles GridViewSupplies2Order.CellValueChanged

    End Sub

    Private Sub GridViewSupplies2Order_RowUpdated(sender As Object, e As DevExpress.XtraGrid.Views.Base.RowObjectEventArgs) Handles GridViewSupplies2Order.RowUpdated
        If FormLoaded = True Then
            Try
                Me.VWSUPPLIES_2_ORDERBindingSource.EndEdit()
                If MyDataset.VWSUPPLIES_2_ORDER.GetChanges Is Nothing = False Then
                    Dim bool = GridViewSupplies2Order.GetFocusedRowCellValue(GridViewSupplies2Order.Columns("GUI_SELECTED"))
                    Dim GUID = GridViewSupplies2Order.GetFocusedRowCellValue(GridViewSupplies2Order.Columns("GUID"))
                    If bool = True Then
                        bool = 1
                    Else
                        bool = 0
                    End If
                    Dim upd = "UPDATE TBSUPPLIES_2_ORDER_TEMP SET GUI_SELECTED = " & bool & " WHERE GUID = " & GUID
                    ClassDatabase.Execute_non_Query(upd)
                    'MsgBox(VWGERAET_ORDERDG.Splits(VWGERAET_ORDERDG.SplitIndex).DisplayColumns(VWGERAET_ORDERDG.Col).DataColumn.Value, MsgBoxStyle.Information, DataColumn)
                End If
            Catch ex As Exception
                MsgBox(ex.Message, MsgBoxStyle.Critical, "Fehler beim Markieren für Bestellung:")
            End Try
        End If
    End Sub

    Private Sub TCUebersicht_SelectedIndexChanged(sender As Object, e As EventArgs) Handles TCUebersicht.SelectedIndexChanged
        If TCUebersicht.SelectedIndex = 3 Then
            Me.TBWH_MARKTTableAdapter.Fill(MyDataset.TBWH_MARKT)
        End If
    End Sub
End Class
