' Copyright (C) 2025  P4pillon.org
'
' This program is free software: you can redistribute it and/or modify
' it under the terms of the GNU Affero General Public License as
' published by the Free Software Foundation, either version 3 of the
' License, or (at your option) any later version.
'
' This program is distributed in the hope that it will be useful,
' but WITHOUT ANY WARRANTY; without even the implied warranty of
' MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
' GNU Affero General Public License for more details.
'
' You should have received a copy of the GNU Affero General Public License
' along with this program.  If not, see <https://www.gnu.org/licenses/>.
'ETATS DES LOTS:
'A TRANSMETTRE
'ARL RECU
'RECONSTITUE
'DEGRADE
'TRAITEMENT MANUEL
'ATTENTE ARL
'AR PROVISOIRE



Imports System.IO
Imports System.Xml
Imports System.Net.Sockets
Imports System.Threading
Imports System.IO.Compression

Imports System
Imports System.Drawing
Imports System.Windows.Forms
Imports System.Windows.Forms.VisualStyles

'Imports Ionic.Zip

Imports System.Security.Cryptography
Imports System.Security.Cryptography.X509Certificates

Imports System.Net.Mail
Imports System.Net.Mime

Imports System.Security.Cryptography.Pkcs


Public Class Teletransmission_MAIN
    Private drawstring As String
    Dim ConfigXml As New XmlDocument
    Dim XMLelementliste As XmlNodeList
    Dim BAL_relevée As Boolean

    Private MyDataGridViewPrinter As New DataGridViewPrinter.DataGridViewPrinter


#Region "TYPES ET VARIABLES"
    Private Structure FSE
        Dim NumFacture As String
        Dim file As String
        Dim CRL As String
        Dim traitée As Boolean
        Dim à_traiter As Boolean
        Dim Total_montants_facturés As Integer
        Dim MontantAMO As Integer
        Dim MontantAMC As Integer
        Dim Datef As String
        Dim CodeRégime As String
        Dim CaisseGestionnaire As String
        Dim CentreGestionnaire As String
        Dim Bénéficiaire As String
        Dim TP_AMO As Boolean
    End Structure

    Private FSE_Tab() As FSE

    Private Structure Lot_FSE
        Dim CRL As String
        Dim NbreFactures As Integer
        Dim Total As Double
        Dim Organisme As String
        Dim Constitution As Boolean
    End Structure

    Private Lots_FSE_Tab() As Lot_FSE

    Private Structure DRE
        Dim NumFacture As String
        Dim file As String
        Dim CRL As String
        Dim traitée As Boolean
        Dim à_traiter As Boolean
        Dim Total_montants_facturés As Integer
        Dim MontantAMO As Integer
        Dim MontantAMC As Integer
        Dim Datef As String
        Dim CodeRégime As String
        Dim CaisseGestionnaire As String
        Dim CentreGestionnaire As String
        Dim Bénéficiaire As String
        Dim TP_AMC As Boolean
    End Structure

    Private DRE_Tab() As DRE

    Private Structure Lot_DRE
        Dim CRL As String
        Dim NbreFactures As Integer
        Dim Total As Double
        Dim Organisme As String
        Dim Constitution As Boolean
    End Structure

    Private Lots_DRE_Tab() As Lot_DRE
#End Region

#Region "FORMULAIRE"
    Private Sub Teletransmission_MAIN_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
        If Config.OCT_UtilisationOCT = True Then
            TabControl1.TabPages.Remove(TabPage3)
            TabControl1.TabPages.Remove(TabPage4)
        End If
        If Config.Logiciel_ModeFonctionement = "Test" Then
            Me.Text = Me.Text + "  Mode TEST"
        ElseIf Config.Logiciel_ModeFonctionement = "Démonstration" Then
            Me.Text = Me.Text + "  Mode DEMO"
        End If

        DebugFSE()


        If Config.is_local_client = False Then


            SendMail_Fichier_en_attente()


            ConfigXml.Load(Mid(Application.ExecutablePath, 1, InStrRev(Application.ExecutablePath, "\")) + "config.xml")




            SCOR_Getmail()
            Traitement_Retour()
        End If
        Affichage()

        DateTimePicker_Recap_Paiement.Value = DateAdd(DateInterval.DayOfYear, -7, Now)

        If Config.Logiciel_ModeFonctionement = "Test" Then
            ConstitutionLotsButton.Visible = True
            TransmettreButton.Visible = True
            Constituer_lots_DRE_Button.Visible = True
            Button_DRE_Transmettre.Visible = True
        ElseIf Config.is_local_client = True Then
            ConstitutionLotsButton.Visible = False
            TransmettreButton.Visible = False
            Constituer_lots_DRE_Button.Visible = False
            Button_DRE_Transmettre.Visible = False
            Affiche_Rejets_Paiement(DataGridView_Rejets_Paiements)
        End If

      

    End Sub
  

    Private Sub Teletransmission_MAIN_FormClosed(ByVal sender As Object, ByVal e As System.Windows.Forms.FormClosedEventArgs) Handles Me.FormClosed
        If Config.Scor_cdrom = True Then
            If DateDiff(DateInterval.DayOfYear, Config.Scor_cdrom_lastdate, Now) >= Config.Scor_cdrom_inter Then
                SCOR_CDROM()
            End If
        End If
        MENU_PRINCIPAL.Enabled = True
        COMPTOIR_MAIN.DP_Affiche_Msg()

    End Sub

    Private Sub RetransmissionLotToolStripMenuItem1_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles RetransmissionLotToolStripMenuItem1.Click
        Getmail()
        Dim FichierARL As String = Dir(Config.LocalNetwork_ServerName & "\Factures\ARL\*.arl")
        Dim Idarl As String
        While FichierARL <> ""
            Idarl = Me.ARLTableAdapter.SelectIdByFichier(Mid(FichierARL, 1, InStr(FichierARL, ".") - 1))
            Traitement_ARL(FichierARL, NumeroSessionARL, Idarl)
            FichierARL = Dir(Config.LocalNetwork_ServerName & "\Factures\ARL\*.arl")
        End While
        ReTransmission_Lot.Visible = True

    End Sub
#End Region

#Region "COMPRESSION"
    Public Sub ShellandWait(ByVal ProcessDirectory As String, ByVal ProcessName As String, ByVal arguments As String)
        Dim objProcess As System.Diagnostics.Process
        Try
            objProcess = New System.Diagnostics.Process()
            objProcess.StartInfo.FileName = ProcessName
            objProcess.StartInfo.WindowStyle = ProcessWindowStyle.Hidden
            'objProcess.StartInfo.WindowStyle = ProcessWindowStyle.Maximized
            objProcess.StartInfo.Arguments = arguments
            objProcess.StartInfo.WorkingDirectory = ProcessDirectory
            objProcess.Start()

            'Wait until the process passes back an exit code 
            objProcess.WaitForExit()

            'Free resources associated with this process
            objProcess.Close()
        Catch
            MessageBox.Show("Could not start process " & ProcessName, "Error")
        End Try
    End Sub


#End Region

#Region "Tableaux Factures et Lots"
    'tableaux avec les factures
    Private Sub DebugFSE() 'suppression des fichiers de facture en doublon, le cas d'un fichier resté seul sans enregistrement dans la bdd est traité dans LoadFSE
        Bandeau_info_bas_show("Préparation")
        Dim file As String = Dir(Config.LocalNetwork_ServerName & "\factures\*.fse")
        Dim tous_les_fichiers As New List(Of String)
        While file <> ""
            tous_les_fichiers.Add(file)
            'tous_les_fichiers.Add(Mid(file, InStr(file, "@") + 1))
            file = Dir()
        End While
        Dim fichiers_à_supprimmer As New List(Of String)

        For r = 0 To tous_les_fichiers.Count - 2
            Dim simplex = Mid(tous_les_fichiers(r), InStr(tous_les_fichiers(r), "@") + 1)
            Dim numfacture = Val(Mid(simplex, 1, InStr(simplex, "@") - 1))
            Dim datefacture As Double = CDbl(Mid(simplex, InStrRev(simplex, "@") + 1, 14))
            For s = r + 1 To tous_les_fichiers.Count - 1
                Dim simplex2 = Mid(tous_les_fichiers(s), InStr(tous_les_fichiers(s), "@") + 1)
                If Val(Mid(simplex2, 1, InStr(simplex2, "@") - 1)) = numfacture Then
                    If datefacture > CDbl(Mid(simplex2, InStrRev(simplex2, "@") + 1, 14)) Then
                        If Not fichiers_à_supprimmer.Contains(tous_les_fichiers(s)) Then
                            fichiers_à_supprimmer.Add(tous_les_fichiers(s))
                        End If
                    Else
                        If Not fichiers_à_supprimmer.Contains(tous_les_fichiers(r)) Then
                            fichiers_à_supprimmer.Add(tous_les_fichiers(r))
                        End If
                    End If
                End If
            Next
        Next
        For r = 0 To fichiers_à_supprimmer.Count - 1
            Try
                My.Computer.FileSystem.DeleteFile(Config.LocalNetwork_ServerName & "\factures\" & fichiers_à_supprimmer(r))
            Catch ex As Exception

            End Try
        Next


        file = Dir(Config.LocalNetwork_ServerName & "\factures\*.fse")
        While file <> ""

            Dim NumFacture = Val(Mid(Mid(file, InStr(file, "@") + 1), 1, InStr(Mid(file, InStr(file, "@") + 1), "@") - 1)).ToString
            Dim mydatatable = Me.FacturesTableAdapter1.GetFactureDataByNum1(NumFacture)
            If mydatatable.Rows.Count = 0 Then
                My.Computer.FileSystem.DeleteFile(Config.LocalNetwork_ServerName & "\factures\" & file)
            Else
                Try
                    If IsDBNull(mydatatable.Item(0).G1130C1) Then
                        My.Computer.FileSystem.DeleteFile(Config.LocalNetwork_ServerName & "\factures\" & file)
                    End If
                Catch ex As Exception
                    MsgBox(NumFacture)
                End Try

            End If

            file = Dir()
        End While

        Bandeau_info_bas_hide()

    End Sub

    Private Sub LoadFSE()





        ReDim FSE_Tab(0)
        Dim file As String = Dir(Config.LocalNetwork_ServerName & "\factures\*.fse")
        Dim compteurfactures As Integer = 0
        Do Until file = ""
            Dim juju As String = ""
            Try



                Dim dateFichier As String = Mid(file, InStrRev(file, "@") + 1, 14)

                If Val(dateFichier) < Val(Format(Now, "yyyyMMddHHmmss")) Then




                    ReDim Preserve FSE_Tab(FSE_Tab.Length)
                    FSE_Tab(compteurfactures).file = file
                    FSE_Tab(compteurfactures).traitée = False
                    FSE_Tab(compteurfactures).à_traiter = True
                    FSE_Tab(compteurfactures).CRL = Mid(file, 1, 40)
                    file = Mid(file, InStr(file, "@") + 1)
                    FSE_Tab(compteurfactures).NumFacture = Val(Mid(file, 1, InStr(file, "@") - 1)).ToString
                    Dim mydatatable = Me.FacturesTableAdapter1.GetFactureDataByNum1(FSE_Tab(compteurfactures).NumFacture)
                    If mydatatable.Rows.Count = 0 Then
                        MyMsg_Box.Presentation("Erreur fichier", "un fichier en erreur est supprimmé ( " + FSE_Tab(compteurfactures).NumFacture + ")" & vbCrLf & vbCrLf & "Relancez transmission", False, "", False, "", True, "OK")
                        MyMsg_Box.ShowDialog()
                        My.Computer.FileSystem.DeleteFile(Config.LocalNetwork_ServerName & "\factures\" & file)

                        Me.Dispose()
                    End If
                    juju = ("a")
                    FSE_Tab(compteurfactures).CodeRégime = mydatatable(0).G1310C1
                    juju = ("b")
                    FSE_Tab(compteurfactures).CaisseGestionnaire = mydatatable(0).G1310C2
                    juju = ("c")
                    FSE_Tab(compteurfactures).CentreGestionnaire = mydatatable(0).G1310C3
                    juju = ("d")
                    FSE_Tab(compteurfactures).Total_montants_facturés = mydatatable(0).G1910C2
                    juju = ("e")
                    FSE_Tab(compteurfactures).MontantAMO = mydatatable(0).G1910C3
                    juju = ("f")
                    FSE_Tab(compteurfactures).MontantAMC = mydatatable(0).G1910C4
                    juju = ("g")
                    FSE_Tab(compteurfactures).Datef = mydatatable(0).G1110C3
                    juju = ("h")
                    Dim G1130C2 As String = mydatatable(0).G1130C2
                    juju = ("i")
                    Dim G1130C3 As String = mydatatable(0).G1130C3
                    juju = ("j")
                    Dim G1130C4 As String = mydatatable(0).G1130C4
                    juju = ("k")
                    Dim G1130C5 As String = mydatatable(0).G1130C5
                    juju = ("l")
                    Dim G1130C6 As String = mydatatable(0).G1130C6
                    juju = ("m")
                    If mydatatable(0).G1410C1 = "2" Or mydatatable(0).G1410C1 = "3" Or mydatatable(0).G1410C1 = "5" Then
                        FSE_Tab(compteurfactures).TP_AMO = True
                    Else
                        FSE_Tab(compteurfactures).TP_AMO = False
                    End If
                    juju = ("n")
                    Try
                        FSE_Tab(compteurfactures).Bénéficiaire = Me.VitaleTableAdapter1.SelectNomPrénom(G1130C2, G1130C3, G1130C4, G1130C5, G1130C6) + " " + G1130C2 + " " + G1130C3
                    Catch ex As Exception
                        FSE_Tab(compteurfactures).Bénéficiaire = ""
                    End Try

                    compteurfactures = compteurfactures + 1

                End If
                file = Dir()
            Catch ex As Exception
                MsgBox("LoadFSE" & vbCrLf & juju & vbCrLf & vbCrLf & file & vbCrLf & vbCrLf & ex.ToString)
            End Try
        Loop
        ReDim Preserve FSE_Tab(FSE_Tab.Length - 2)

    End Sub
    Private Sub LoadDRE()
        ReDim DRE_Tab(0)
        Dim file As String = Dir(Config.LocalNetwork_ServerName & "\factures\*.DRE")
        Dim compteurfactures As Integer = 0
        Do Until file = ""
            Dim dateFichier As String = Mid(file, InStrRev(file, "@") + 1, 14)
            If Val(dateFichier) < Val(Format(Now, "yyyyMMddHHmmss")) Then
                ReDim Preserve DRE_Tab(DRE_Tab.Length)
                DRE_Tab(compteurfactures).file = file
                DRE_Tab(compteurfactures).traitée = False
                DRE_Tab(compteurfactures).à_traiter = True
                DRE_Tab(compteurfactures).CRL = Mid(file, 1, 71)
                file = Mid(file, InStr(file, "@") + 1)
                DRE_Tab(compteurfactures).NumFacture = Val(Mid(file, 1, InStr(file, "@") - 1)).ToString
                Dim mydatatable As DataTable = Me.FacturesTableAdapter1.GetFactureDataByNum1(DRE_Tab(compteurfactures).NumFacture)
                If mydatatable.Rows.Count <> 1 Then
                    MyMsg_Box.Presentation("Officine", "erreur: pas ou plusieurs enregisrements dans bdd facture num " + DRE_Tab(compteurfactures).NumFacture, False, "", False, "", True, "OK")
                    MyMsg_Box.ShowDialog()
                End If
                Dim G1130C2 As String = ""
                Dim G1130C3 As String = ""
                Dim G1130C4 As String = ""
                Dim G1130C5 As String = ""
                Dim G1130C6 As String = ""
                For c = 0 To mydatatable.Columns.Count - 1
                    Select Case mydatatable.Columns.Item(c).ColumnName
                        Case "G1310C1"
                            DRE_Tab(compteurfactures).CodeRégime = mydatatable(0).Item(c)
                        Case "G1310C2"
                            DRE_Tab(compteurfactures).CaisseGestionnaire = mydatatable(0).Item(c)
                        Case "G1310C3"
                            DRE_Tab(compteurfactures).CentreGestionnaire = mydatatable(0).Item(c)
                        Case "G1910C2"
                            DRE_Tab(compteurfactures).Total_montants_facturés = mydatatable(0).Item(c)
                        Case "G1910C3"
                            DRE_Tab(compteurfactures).MontantAMO = mydatatable(0).Item(c)
                        Case "G1910C4"
                            DRE_Tab(compteurfactures).MontantAMC = mydatatable(0).Item(c)
                        Case "G1110C3"
                            DRE_Tab(compteurfactures).Datef = mydatatable(0).Item(c)
                        Case "G1130C2"
                            G1130C2 = mydatatable(0).Item(c)
                        Case "G1130C3"
                            G1130C3 = mydatatable(0).Item(c)
                        Case "G1130C4"
                            G1130C4 = mydatatable(0).Item(c)
                        Case "G1130C5"
                            G1130C5 = mydatatable(0).Item(c)
                        Case "G1130C6"
                            G1130C6 = mydatatable(0).Item(c)
                        Case "G1321C5"
                            If Mid(mydatatable(0).Item(c), 3, 1) = "T" Then
                                DRE_Tab(compteurfactures).TP_AMC = True
                            Else
                                DRE_Tab(compteurfactures).TP_AMC = False
                            End If
                    End Select
                Next
                DRE_Tab(compteurfactures).Bénéficiaire = Me.VitaleTableAdapter1.SelectNomPrénom(G1130C2, G1130C3, G1130C4, G1130C5, G1130C6) + " " + G1130C2 + " " + G1130C3
                compteurfactures = compteurfactures + 1
            End If
            file = Dir()
        Loop
        ReDim Preserve DRE_Tab(DRE_Tab.Length - 2)

    End Sub

    'tableaux avec les lots constituables
    Private Sub LoadLots_FSE()
        ReDim Lots_FSE_Tab(0)
        For i = 0 To FSE_Tab.Length - 1
            If FSE_Tab(i).à_traiter = True Then
                Dim Found As Boolean = False
                For j = 0 To Lots_FSE_Tab.Length - 1
                    If FSE_Tab(i).CRL = Lots_FSE_Tab(j).CRL Then 'si il y a déja une ligne créée dans LotsTab poue ce CRL
                        Found = True
                        Lots_FSE_Tab(j).NbreFactures = Lots_FSE_Tab(j).NbreFactures + 1
                        Lots_FSE_Tab(j).Total = Lots_FSE_Tab(j).Total + FSE_Tab(i).MontantAMO ' + FSE_Tab(i).MontantAMC
                    End If
                Next
                If Found = False Then 'si il n'y a pas déja une ligne créée dans LotsTab poue ce CRL
                    ReDim Preserve Lots_FSE_Tab(Lots_FSE_Tab.Length)
                    Lots_FSE_Tab(Lots_FSE_Tab.Length - 2).CRL = FSE_Tab(i).CRL
                    Lots_FSE_Tab(Lots_FSE_Tab.Length - 2).Constitution = True
                    Lots_FSE_Tab(Lots_FSE_Tab.Length - 2).NbreFactures = 1
                    Lots_FSE_Tab(Lots_FSE_Tab.Length - 2).Total = FSE_Tab(i).MontantAMO ' + FSE_Tab(i).MontantAMC
                    Lots_FSE_Tab(Lots_FSE_Tab.Length - 2).Organisme = Me.AmoTableAdapter1.SelectLibellé(FSE_Tab(i).CodeRégime, FSE_Tab(i).CaisseGestionnaire, FSE_Tab(i).CentreGestionnaire)
                End If
            End If
        Next
        ReDim Preserve Lots_FSE_Tab(Lots_FSE_Tab.Length - 2)
    End Sub
    Private Sub LoadLots_DRE()
        ReDim Lots_DRE_Tab(0)
        For i = 0 To DRE_Tab.Length - 1
            If DRE_Tab(i).à_traiter = True Then
                Dim Found As Boolean = False
                For j = 0 To Lots_DRE_Tab.Length - 1
                    If DRE_Tab(i).CRL = Lots_DRE_Tab(j).CRL Then 'si il y a déja une ligne créée dans LotsTab poue ce CRL
                        Found = True
                        Lots_DRE_Tab(j).NbreFactures = Lots_DRE_Tab(j).NbreFactures + 1
                        Lots_DRE_Tab(j).Total = Lots_DRE_Tab(j).Total + DRE_Tab(i).MontantAMC
                    End If
                Next
                If Found = False Then 'si il n'y a pas déja une ligne créée dans LotsTab poue ce CRL
                    ReDim Preserve Lots_DRE_Tab(Lots_DRE_Tab.Length)
                    Lots_DRE_Tab(Lots_DRE_Tab.Length - 2).CRL = DRE_Tab(i).CRL
                    Lots_DRE_Tab(Lots_DRE_Tab.Length - 2).Constitution = True
                    Lots_DRE_Tab(Lots_DRE_Tab.Length - 2).NbreFactures = 1
                    Lots_DRE_Tab(Lots_DRE_Tab.Length - 2).Total = DRE_Tab(i).MontantAMC
                    'Lots_DRE_Tab(Lots_DRE_Tab.Length - 2).Organisme = Me.AmoTableAdapter1.SelectLibellé(DRE_Tab(i).CodeRégime, DRE_Tab(i).CaisseGestionnaire, DRE_Tab(i).CentreGestionnaire)
                End If
            End If
        Next
        ReDim Preserve Lots_DRE_Tab(Lots_DRE_Tab.Length - 2)
    End Sub
#End Region

#Region "AFFICHAGE DES LOTS A CONSTITUER"
    Private Sub Affiche_Lots_à_constituer()
        LotDataGridView.Rows.Clear()
        For i = 0 To Lots_FSE_Tab.Length - 1
            LotDataGridView.Rows.Add()
            If Lots_FSE_Tab(i).Constitution = False Then
                LotDataGridView(Constitution.Index, i).Value = False
            Else
                LotDataGridView(Constitution.Index, i).Value = True
            End If
            LotDataGridView(Organisme.Index, i).Value = Lots_FSE_Tab(i).Organisme
            LotDataGridView(FacturesNombre.Index, i).Value = Lots_FSE_Tab(i).NbreFactures
            LotDataGridView(Total.Index, i).Value = (Lots_FSE_Tab(i).Total / 100).ToString + "€"
            LotDataGridView(CRL.Index, i).Value = Lots_FSE_Tab(i).CRL
        Next
    End Sub
    Private Sub Affiche_Lots_DRE_à_constituer()
        Lots_DRE_DataGridView.Rows.Clear()
        For i = 0 To Lots_DRE_Tab.Length - 1
            Lots_DRE_DataGridView.Rows.Add()
            If Lots_DRE_Tab(i).Constitution = False Then
                Lots_DRE_DataGridView(Constitution.Index, i).Value = False
            Else
                Lots_DRE_DataGridView(Constitution.Index, i).Value = True
            End If
            Lots_DRE_DataGridView(Organisme_DRE.Index, i).Value = Lots_DRE_Tab(i).Organisme
            Lots_DRE_DataGridView(FacturesNombre_DRE.Index, i).Value = Lots_DRE_Tab(i).NbreFactures
            Lots_DRE_DataGridView(Total_DRE.Index, i).Value = (Lots_DRE_Tab(i).Total / 100).ToString + "€"
            Lots_DRE_DataGridView(DRE_CRL.Index, i).Value = Lots_DRE_Tab(i).CRL
        Next
    End Sub
#End Region

#Region "CONSTITUTION DES LOTS"
    'Constitution Lots FSE
    Public Sub ConstitutionLots()


        CPS_Code.ShowDialog()


        Bandeau_info_bas_show("Constitution des Lots")
        'Dim code = InputBox("Code CPS")

        Dim Nombre_Lots_à_formatter As Integer = 0
        Dim index_premier_lot_à_formatter As Integer = 0
        Dim index_premier_lot_à_formatter_valorisé As Boolean = False
        Dim index_dernier_lot_à_formatter As Integer = 0

        Dim tab_numfacture_scanordo() As String

        For i = 0 To Lots_FSE_Tab.Length - 1
            If Lots_FSE_Tab(i).Constitution = True And Lots_FSE_Tab(i).NbreFactures <> 0 Then
                Nombre_Lots_à_formatter = Nombre_Lots_à_formatter + 1
                If index_premier_lot_à_formatter_valorisé = False Then
                    index_premier_lot_à_formatter = i
                    index_premier_lot_à_formatter_valorisé = True
                End If
                index_dernier_lot_à_formatter = i
            End If
        Next


        For i = 0 To Lots_FSE_Tab.Length - 1
            If Lots_FSE_Tab(i).Constitution = True And Lots_FSE_Tab(i).NbreFactures <> 0 Then
                Dim G8_G88_C4 As String
                '____________________________________________________________________________________________________
                'Trace
                Trace_Reset_compteur()
                FichierTrace = Mid(Application.ExecutablePath, 1, InStrRev(Application.ExecutablePath, "\")) + "traces\Formater_Lot_FSE_in.txt"
                '____________________________________________________________________________________________________
                SGD_ReserverSession(10000000, NumeroSessionLot)

                'Groupe7
                SGD_AjouterGroupe_Tracé(NumeroSessionLot, 7, Visu_API, FichierTrace)

                'Champ1
                ValeurChamp = "12345678"
                SGD_LireChamp(NumeroSessionCPS, 2, Occurence_Grp2, 9, ValeurChamp, 8)
                SGD_AjouterChamp_Tracé(NumeroSessionLot, ValeurChamp, Visu_API, FichierTrace)

                'Champ2
                ValeurChamp = "1"
                SGD_LireChamp(NumeroSessionCPS, 2, Occurence_Grp2, 10, ValeurChamp, 1)
                SGD_AjouterChamp_Tracé(NumeroSessionLot, ValeurChamp, Visu_API, FichierTrace)

                'Groupe8
                SGD_AjouterGroupe_Tracé(NumeroSessionLot, 8, Visu_API, FichierTrace)

                'Champ1
                If Config.Logiciel_ModeFonctionement = "Test" Then
                    SGD_AjouterChamp_Tracé(NumeroSessionLot, "TESTCNDA1409", Visu_API, FichierTrace)
                Else
                    SGD_AjouterChamp_Tracé(NumeroSessionLot, "GSNW3B000110", Visu_API, FichierTrace)
                End If

                'Champ2
                If Config.Activer_Session_Remplacement = False Then
                    ValeurChamp = "12345678"
                    SGD_LireChamp(NumeroSessionCPS, 2, Occurence_Grp2, 9, ValeurChamp, 8)
                Else
                    ValeurChamp = Config.Titulaire_Num_Id_Facturation
                End If
                SGD_AjouterChamp_Tracé(NumeroSessionLot, ValeurChamp, Visu_API, FichierTrace)


                'Champ3
                If Config.Activer_Session_Remplacement = False Then
                    ValeurChamp = "1"
                    SGD_LireChamp(NumeroSessionCPS, 2, Occurence_Grp2, 10, ValeurChamp, 1)
                Else
                    ValeurChamp = Config.Titulaire_Cle_Num_Id_Facturation
                End If
                SGD_AjouterChamp_Tracé(NumeroSessionLot, ValeurChamp, Visu_API, FichierTrace)

                'Champ4
                If Config.Activer_Session_Remplacement = False Then
                    ValeurChamp = "1"
                    ValeurChamp = "1234567890123456789012345678901234567890"
                    TailleMax = 40
                    SGD_LireChamp(NumeroSessionCPS, 2, Occurence_Grp2, 8, ValeurChamp, TailleMax)
                    If TailleMax = 0 Then
                        ValeurChamp = "123456789012345678901234567"
                        TailleMax = 27
                        SGD_LireChamp(NumeroSessionCPS, 1, 1, 6, ValeurChamp, TailleMax)
                    End If
                Else
                    ValeurChamp = Config.Titulaire_raison_sociale
                End If
                SGD_AjouterChamp_Tracé(NumeroSessionLot, Mid(ValeurChamp, 1, TailleMax), Visu_API, FichierTrace)
                G8_G88_C4 = Mid(ValeurChamp, 1, TailleMax)

                'Champ5
                If Config.Activer_Session_Remplacement = False Then
                    ValeurChamp = "1"
                    SGD_LireChamp(NumeroSessionCPS, 2, Occurence_Grp2, 1, ValeurChamp, 1)
                    SGD_AjouterChamp_Tracé(NumeroSessionLot, ValeurChamp, Visu_API, FichierTrace)
                Else
                    Dim bytes() As Byte = BitConverter.GetBytes(CInt(Config.Remplacant_Num_log_situ_fact))
                    SGD_AjouterChamp_Tracé(NumeroSessionLot, bytes(0), Visu_API, FichierTrace)
                End If

                'Champ6
                SGD_AjouterChamp_Tracé(NumeroSessionLot, Config.Type_émetteur_fichier, Visu_API, FichierTrace)

                'Champ7
                If Config.Type_émetteur_fichier = "SI" Then
                    SGD_AjouterChamp_Tracé(NumeroSessionLot, Config.num_émetteur_fichier, Visu_API, FichierTrace)
                ElseIf Config.Activer_Session_Remplacement = False Then
                    ValeurChamp = "12345678"
                    SGD_LireChamp(NumeroSessionCPS, 2, Occurence_Grp2, 9, ValeurChamp, 8)
                    Config.num_émetteur_fichier = ValeurChamp
                    ValeurChamp = "1"
                    SGD_LireChamp(NumeroSessionCPS, 2, Occurence_Grp2, 10, ValeurChamp, 1)
                    Config.num_émetteur_fichier = "00000" + Config.num_émetteur_fichier + ValeurChamp
                    SGD_AjouterChamp_Tracé(NumeroSessionLot, Config.num_émetteur_fichier, Visu_API, FichierTrace)
                Else
                    Config.num_émetteur_fichier = "00000" + Config.Titulaire_Num_Id_Facturation + Config.Titulaire_Cle_Num_Id_Facturation
                    SGD_AjouterChamp_Tracé(NumeroSessionLot, Config.num_émetteur_fichier, Visu_API, FichierTrace)
                End If

                'Champ8
                Dim datelot As String = Format(Now, "yyyyMMdd") + "0000"
                SGD_AjouterChamp_Tracé(NumeroSessionLot, datelot, Visu_API, FichierTrace)

                'Champ9 Rang du lot
                If Nombre_Lots_à_formatter = 1 Then
                    SGD_AjouterChamp_Tracé(NumeroSessionLot, "7", Visu_API, FichierTrace)
                ElseIf i = index_premier_lot_à_formatter Then
                    SGD_AjouterChamp_Tracé(NumeroSessionLot, "5", Visu_API, FichierTrace)
                ElseIf i = index_dernier_lot_à_formatter Then
                    SGD_AjouterChamp_Tracé(NumeroSessionLot, "6", Visu_API, FichierTrace)
                ElseIf i > index_premier_lot_à_formatter And i < index_dernier_lot_à_formatter Then
                    SGD_AjouterChamp_Tracé(NumeroSessionLot, "4", Visu_API, FichierTrace)
                End If

                'champ10
                Dim RéférenceLotFSE_bdd As Integer = Me.LotsTableAdapter.SELECT_max_Référence_bdd + 1
                Dim RéférenceLotFSE_SV As Integer
                If RéférenceLotFSE_bdd Mod 1000 = 0 Then
                    RéférenceLotFSE_bdd = RéférenceLotFSE_bdd + 1
                End If
                RéférenceLotFSE_SV = RéférenceLotFSE_bdd Mod 1000
                Dim datatable As DataTable = Me.LotsTableAdapter.GetDataByRéférence(RéférenceLotFSE_SV, Nothing)
                If datatable.Rows.Count > 0 Then
                    Me.LotsTableAdapter.Delete_By_référence(RéférenceLotFSE_SV, Nothing)
                    Me.SCOR_lotsTableAdapter.Delete_By_NumLot(RéférenceLotFSE_SV.ToString)
                End If
                SGD_AjouterChamp_Tracé(NumeroSessionLot, RéférenceLotFSE_SV.ToString, Visu_API, FichierTrace)

                'champ11
                SGD_AjouterChamp_Tracé(NumeroSessionLot, Lots_FSE_Tab(i).NbreFactures.ToString, Visu_API, FichierTrace)

                'champ12,13,14
                ValeurChamp = "XXXXXXXXXXXXXX"
                SGD_LireChamp(NumeroSessionCPS, 2, Occurence_Grp2, 6, ValeurChamp, 14)
                If ValeurChamp <> "XXXXXXXXXXXXXX" Then
                    ValeurChamp = "X"
                    SGD_LireChamp(NumeroSessionCPS, 2, Occurence_Grp2, 5, ValeurChamp, 1)
                    SGD_AjouterChamp_Tracé(NumeroSessionLot, ValeurChamp, Visu_API, FichierTrace)
                    ValeurChamp = "XXXXXXXXXXXXXX"
                    TailleMax = 14
                    SGD_LireChamp(NumeroSessionCPS, 2, Occurence_Grp2, 6, ValeurChamp, TailleMax)
                    SGD_AjouterChamp_Tracé(NumeroSessionLot, Mid(ValeurChamp, 1, TailleMax), Visu_API, FichierTrace)
                    ValeurChamp = "X"
                    SGD_LireChamp(NumeroSessionCPS, 2, Occurence_Grp2, 7, ValeurChamp, 1)
                    SGD_AjouterChamp_Tracé(NumeroSessionLot, ValeurChamp, Visu_API, FichierTrace)
                Else
                    SGD_AjouterChamp_Tracé(NumeroSessionLot, "9", Visu_API, FichierTrace)
                    SGD_AjouterChamp_Tracé(NumeroSessionLot, "9", Visu_API, FichierTrace)
                    ValeurChamp = "X"
                    SGD_LireChamp(1, 2, 1, 10, ValeurChamp, 1)
                    SGD_AjouterChamp_Tracé(NumeroSessionLot, ValeurChamp, Visu_API, FichierTrace)
                End If

                'groupe6
                SGD_AjouterGroupe_Tracé(NumeroSessionLot, 6, Visu_API, FichierTrace)
                SGD_AjouterChamp_Tracé(NumeroSessionLot, Lots_FSE_Tab(i).CRL, Visu_API, FichierTrace)

                'groupe9
                SGD_AjouterGroupe_Tracé(NumeroSessionLot, 9, Visu_API, FichierTrace)

                ReDim tab_numfacture_scanordo(0)

                For j = 0 To FSE_Tab.Length - 1
                    If FSE_Tab(j).CRL = Lots_FSE_Tab(i).CRL And FSE_Tab(j).traitée = False And FSE_Tab(j).à_traiter = True Then
                        Dim bytes = My.Computer.FileSystem.ReadAllBytes(Config.LocalNetwork_ServerName & "\factures\" + FSE_Tab(j).file)
                        My.Computer.FileSystem.WriteAllBytes(Config.LocalNetwork_ServerName & "\factures\lots\temp", bytes, True)
                        FSE_Tab(j).traitée = True
                        Me.FacturesTableAdapter1.Update_Num_Lot_FSE(RéférenceLotFSE_SV.ToString, datelot, FSE_Tab(j).NumFacture)

                        tab_numfacture_scanordo(tab_numfacture_scanordo.Length - 1) = FSE_Tab(j).NumFacture
                        ReDim Preserve tab_numfacture_scanordo(tab_numfacture_scanordo.Length)

                    End If
                Next
                SGD_AjouterChampFichier(NumeroSessionLot, Config.LocalNetwork_ServerName & "\factures\lots\temp")
                Try
                    My.Computer.FileSystem.DeleteFile(Config.LocalNetwork_ServerName & "\factures\lots\temp")
                Catch exep As Exception
                    MyMsg_Box.Presentation("Officine", exep.ToString, False, "", False, "", True, "OK")
                    MyMsg_Box.ShowDialog()
                End Try
                '____________________________________________________________________________________________________

                'SIS_FormaterLot

                'Dim out As Integer = SIS_FormaterLot(NomRessourcePS, NomRessourceLecteur, code.ToString, NumeroSessionLot)
                Dim out As Integer = SIS_FormaterLot(NomRessourcePS, NomRessourceLecteur, CodeCPS, NumeroSessionLot)
                'Dim out As Integer = SIS_FormaterLot(NomRessourcePS, NomRessourceLecteur, "", NumeroSessionLot)
                If out <> 0 Then
                    For j = 0 To FSE_Tab.Length - 1
                        If FSE_Tab(j).CRL = Lots_FSE_Tab(i).CRL And FSE_Tab(j).traitée = True And FSE_Tab(j).à_traiter = True Then
                            Me.FacturesTableAdapter1.Update_Num_Lot_FSE("", "", Val(FSE_Tab(j).NumFacture))
                        End If
                    Next
                    MyMsg_Box.Presentation("Officine", "erreur constitution lot " + Lots_FSE_Tab(i).Organisme + Chr(10) + out.ToString, False, "", False, "", True, "OK")
                    MyMsg_Box.ShowDialog()
                    Affiche_Lots_à_constituer()
                    Bandeau_info_bas_hide() 'Bandeau_info_bas_show_thread)
                    Exit Sub
                End If
                '____________________________________________________________________________________________________
                'deplacement fichier FSE apres traitement et sauvegarde bdd
                For j = 0 To FSE_Tab.Length - 1
                    If FSE_Tab(j).CRL = Lots_FSE_Tab(i).CRL And FSE_Tab(j).traitée = True And FSE_Tab(j).à_traiter = True Then
                        My.Computer.FileSystem.MoveFile(Config.LocalNetwork_ServerName & "\factures\" + FSE_Tab(j).file, Config.LocalNetwork_ServerName & "\Factures\Traitées\" + FSE_Tab(j).file, True)
                        Me.FacturesTableAdapter1.Update_Num_Lot_FSE(RéférenceLotFSE_SV.ToString, datelot, FSE_Tab(j).NumFacture)
                    End If
                Next
                '____________________________________________________________________________________________________
                'Visu_API agrement CNDA
                If Visu_API = True Then
                    Technique_MAIN.LireSession_Out_VersFichier2(NumeroSessionLot, Application.StartupPath + "\traces\Formater_Lot_FSE_out.txt")
                End If
                '____________________________________________________________________________________________________
                'enregistrement lot dans bdd
                Dim CRF As String = "123456789012345678901234567890"
                SGD_LireChamp(NumeroSessionLot, 10, 1, 1, CRF, 30)
                Dim TailleLot = 0
                SGD_LireChampBin(NumeroSessionLot, 11, 1, 1, ValeurChamp, TailleLot)
                Dim G13C1 As String = "@"
                SGD_LireChamp(NumeroSessionLot, 13, 1, 1, G13C1, 1)
                If G13C1 = "@" Then G13C1 = ""
                Dim G13C2 As String = "@"
                SGD_LireChamp(NumeroSessionLot, 13, 1, 2, G13C2, 1)
                If G13C2 = "@" Then G13C2 = ""
                Dim G13C3 As String = "@@@@@@@@@@@@@@"
                SGD_LireChamp(NumeroSessionLot, 13, 1, 3, G13C3, 14)
                If G13C3 = "@@@@@@@@@@@@@@" Then G13C3 = ""
                Dim G13C4 As String = "@@@@@@@@@@@@@@"
                SGD_LireChamp(NumeroSessionLot, 13, 1, 4, G13C4, 14)
                If G13C4 = "@@@@@@@@@@@@@@" Then G13C4 = ""
                Dim G13C5 As String = "@@@"
                SGD_LireChamp(NumeroSessionLot, 13, 1, 5, G13C5, 3)
                If G13C5 = "@@@" Then G13C5 = ""
                Dim G13C6 As String = "@"
                SGD_LireChamp(NumeroSessionLot, 13, 1, 6, G13C6, 1)
                If G13C6 = "@" Then G13C6 = ""
                Dim G13C7 As String = "@@@@@@@@"
                SGD_LireChamp(NumeroSessionLot, 13, 1, 7, G13C7, 8)
                If G13C7 = "@@@@@@@@" Then G13C7 = ""
                Dim G93C1 As String = "@@@@@@@@@@@@@@"
                SGD_LireChamp(NumeroSessionLot, 93, 1, 1, G93C1, 14)
                If G93C1 = "@@@@@@@@@@@@@@" Then G93C1 = ""
                Dim G93C2 As String = "@@@@@@@@@@"
                SGD_LireChamp(NumeroSessionLot, 93, 1, 2, G93C2, 10)
                If G93C2 = "@@@@@@@@@@" Then G93C2 = ""
                Dim G93C3 As String = "@@@"
                SGD_LireChamp(NumeroSessionLot, 93, 1, 3, G93C3, 3)
                If G93C3 = "@@@" Then G93C3 = ""
                Dim G93C4 As String = "@@@@@@@@@@@@@@@@@@@@"
                SGD_LireChamp(NumeroSessionLot, 93, 1, 4, G93C4, 20)
                If G93C4 = "@@@@@@@@@@@@@@@@@@@@" Then G93C4 = ""
                Dim G93C5 As String = "@@@@@@@@@@@@@@@@@@@@"
                SGD_LireChamp(NumeroSessionLot, 93, 1, 5, G93C5, 20)
                If G93C5 = "@@@@@@@@@@@@@@@@@@@@" Then G93C5 = ""
                Dim G93C6 As String = "@"
                SGD_LireChamp(NumeroSessionLot, 93, 1, 6, G93C6, 8)
                If G93C6 = "@" Then G93C6 = ""
                Dim G93C7 As String = "@@@@@@@@"
                SGD_LireChamp(NumeroSessionLot, 93, 1, 7, G93C7, 8)
                If G93C7 = "@@@@@@@@" Then G93C7 = ""
                Me.LotsTableAdapter.Insert1(RéférenceLotFSE_SV, Nothing, Lots_FSE_Tab(i).CRL, CRF, datelot, Lots_FSE_Tab(i).NbreFactures, Lots_FSE_Tab(i).Total, TailleLot, Lots_FSE_Tab(i).Organisme, G13C1, G13C2, G13C3, G13C4, G13C5, G13C6, G13C7, G93C1, G93C2, G93C3, G93C4, G93C5, G93C6, G93C7, "A TRANSMETTRE", 0, RéférenceLotFSE_bdd, Nothing, G8_G88_C4, False)
                'enregistrement lot dans fichier
                SGD_LireChampFichier(NumeroSessionLot, 11, 1, 1, Config.LocalNetwork_ServerName & "\Factures\Lots\" + RéférenceLotFSE_SV.ToString + ".lotFSE")

            End If

            SGD_LibererSession(NumeroSessionLot)

        Next
        CodeCPS = ""

        LoadFSE()
        LoadLots_FSE()
        Affiche_Lots_à_constituer()
        FSE_DataGridView.Rows.Clear()
        Afficher_lots_à_transmettre()
        Bandeau_info_bas_hide() 'Bandeau_info_bas_show_thread)
    End Sub
    Private Sub ConstitutionLotsButton_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles ConstitutionLotsButton.Click
        ConstitutionLots()
    End Sub

    'Constitution Lots DRE
    Private Sub Constituer_lots_DRE_Button_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Constituer_lots_DRE_Button.Click
        Bandeau_info_bas_show("Constitution des Lots")

        Dim Nombre_Lots_à_formatter As Integer = 0
        Dim index_premier_lot_à_formatter As Integer = 0
        Dim index_premier_lot_à_formatter_valorisé As Boolean = False
        Dim index_dernier_lot_à_formatter As Integer = 0
        For i = 0 To Lots_DRE_Tab.Length - 1
            If Lots_DRE_Tab(i).Constitution = True And Lots_DRE_Tab(i).NbreFactures <> 0 Then
                Nombre_Lots_à_formatter = Nombre_Lots_à_formatter + 1
                If index_premier_lot_à_formatter_valorisé = False Then
                    index_premier_lot_à_formatter = i
                    index_premier_lot_à_formatter_valorisé = True
                End If
                index_dernier_lot_à_formatter = i
            End If
        Next

        For i = 0 To Lots_DRE_Tab.Length - 1
            If Lots_DRE_Tab(i).Constitution = True And Lots_DRE_Tab(i).NbreFactures <> 0 Then


                '____________________________________________________________________________________________________
                'Trace
                Trace_Reset_compteur()
                FichierTrace = "traces\Formater_Lot_DRE_in.txt"
                '____________________________________________________________________________________________________

                SGD_LibererSession(NumeroSessionLot)
                SGD_ReserverSession(10000000, NumeroSessionLot)

                'Groupe87
                SGD_AjouterGroupe_Tracé(NumeroSessionLot, 87, Visu_API, FichierTrace)

                'Champ1
                ValeurChamp = "12345678"
                SGD_LireChamp(NumeroSessionCPS, 2, Occurence_Grp2, 9, ValeurChamp, 8)
                SGD_AjouterChamp_Tracé(NumeroSessionLot, ValeurChamp, Visu_API, FichierTrace)

                'Champ2
                ValeurChamp = "1"
                SGD_LireChamp(NumeroSessionCPS, 2, Occurence_Grp2, 10, ValeurChamp, 1)
                SGD_AjouterChamp_Tracé(NumeroSessionLot, ValeurChamp, Visu_API, FichierTrace)

                'Groupe88
                SGD_AjouterGroupe_Tracé(NumeroSessionLot, 88, Visu_API, FichierTrace)

                'Champ1
                'SGD_AjouterChamp_Tracé(NumeroSessionLot, "TESTCNDA1409", Visu_API, FichierTrace)
                'SGD_AjouterChamp_Tracé(NumeroSessionLot, "GSNW1B000100", Visu_API, FichierTrace)
                'SGD_AjouterChamp_Tracé(NumeroSessionLot, "TESTTOTO9999", Visu_API, FichierTrace)
                SGD_AjouterChamp_Tracé(NumeroSessionLot, "GSNW3B000110", Visu_API, FichierTrace)

                'Champ2
                If Config.Activer_Session_Remplacement = False Then
                    ValeurChamp = "12345678"
                    SGD_LireChamp(NumeroSessionCPS, 2, Occurence_Grp2, 9, ValeurChamp, 8)
                Else
                    ValeurChamp = Config.Titulaire_Num_Id_Facturation
                End If
                SGD_AjouterChamp_Tracé(NumeroSessionLot, ValeurChamp, Visu_API, FichierTrace)


                'Champ3
                If Config.Activer_Session_Remplacement = False Then
                    ValeurChamp = "1"
                    SGD_LireChamp(NumeroSessionCPS, 2, Occurence_Grp2, 10, ValeurChamp, 1)
                Else
                    ValeurChamp = Config.Titulaire_Cle_Num_Id_Facturation
                End If
                SGD_AjouterChamp_Tracé(NumeroSessionLot, ValeurChamp, Visu_API, FichierTrace)

                'Champ4
                If Config.Activer_Session_Remplacement = False Then
                    ValeurChamp = "1"
                    ValeurChamp = "1234567890123456789012345678901234567890"
                    TailleMax = 40
                    SGD_LireChamp(NumeroSessionCPS, 2, Occurence_Grp2, 8, ValeurChamp, TailleMax)
                    If TailleMax = 0 Then
                        ValeurChamp = "123456789012345678901234567"
                        TailleMax = 27
                        SGD_LireChamp(NumeroSessionCPS, 1, 1, 6, ValeurChamp, TailleMax)
                    End If
                Else
                    ValeurChamp = Config.Titulaire_raison_sociale
                End If
                Dim G8_G88_C4 As String = ValeurChamp
                SGD_AjouterChamp_Tracé(NumeroSessionLot, Mid(ValeurChamp, 1, TailleMax), Visu_API, FichierTrace)

                'Champ5
                If Config.Activer_Session_Remplacement = False Then
                    ValeurChamp = "1"
                    SGD_LireChamp(NumeroSessionCPS, 2, Occurence_Grp2, 1, ValeurChamp, 1)
                    SGD_AjouterChamp_Tracé(NumeroSessionLot, ValeurChamp, Visu_API, FichierTrace)
                Else
                    Dim bytes() As Byte = BitConverter.GetBytes(CInt(Config.Remplacant_Num_log_situ_fact))
                    SGD_AjouterChamp_Tracé(NumeroSessionLot, bytes(0), Visu_API, FichierTrace)
                End If

                'Champ6
                SGD_AjouterChamp_Tracé(NumeroSessionLot, Config.Type_émetteur_fichier, Visu_API, FichierTrace)

                'Champ7
                If Config.Type_émetteur_fichier = "SI" Then
                    SGD_AjouterChamp_Tracé(NumeroSessionLot, Config.num_émetteur_fichier, Visu_API, FichierTrace)
                ElseIf Config.Activer_Session_Remplacement = False Then
                    ValeurChamp = "12345678"
                    SGD_LireChamp(NumeroSessionCPS, 2, Occurence_Grp2, 9, ValeurChamp, 8)
                    Config.num_émetteur_fichier = ValeurChamp
                    ValeurChamp = "1"
                    SGD_LireChamp(NumeroSessionCPS, 2, Occurence_Grp2, 10, ValeurChamp, 1)
                    Config.num_émetteur_fichier = "00000" + Config.num_émetteur_fichier + ValeurChamp
                    SGD_AjouterChamp_Tracé(NumeroSessionLot, Config.num_émetteur_fichier, Visu_API, FichierTrace)
                Else
                    Config.num_émetteur_fichier = "00000" + Config.Titulaire_Num_Id_Facturation + Config.Titulaire_Cle_Num_Id_Facturation
                    SGD_AjouterChamp_Tracé(NumeroSessionLot, Config.num_émetteur_fichier, Visu_API, FichierTrace)
                End If

                'Champ8
                Dim datelot As String = Format(Now, "yyyyMMdd") + "0000"
                SGD_AjouterChamp_Tracé(NumeroSessionLot, datelot, Visu_API, FichierTrace)

                'Champ9 Rang du lot
                If Nombre_Lots_à_formatter = 1 Then
                    SGD_AjouterChamp_Tracé(NumeroSessionLot, "7", Visu_API, FichierTrace)
                ElseIf i = index_premier_lot_à_formatter Then
                    SGD_AjouterChamp_Tracé(NumeroSessionLot, "5", Visu_API, FichierTrace)
                ElseIf i = index_dernier_lot_à_formatter Then
                    SGD_AjouterChamp_Tracé(NumeroSessionLot, "6", Visu_API, FichierTrace)
                ElseIf i > index_premier_lot_à_formatter And i < index_dernier_lot_à_formatter Then
                    SGD_AjouterChamp_Tracé(NumeroSessionLot, "4", Visu_API, FichierTrace)
                End If



                'champ10

                Dim RéférenceLotDRE_bdd As String = Me.LotsTableAdapter.SELECT_max_Référence_DRE_bdd

                While RéférenceLotDRE_bdd.Length < 4
                    RéférenceLotDRE_bdd = " " + RéférenceLotDRE_bdd
                End While
                Dim TabRef As Char()
                ReDim TabRef(4)
                For n = 1 To 4
                    TabRef(n) = Mid(RéférenceLotDRE_bdd, n, 1)
                Next
                If TabRef(4) <> "Z" Then
                    TabRef(4) = Chr(Asc(TabRef(4)) + 1)
                Else
                    TabRef(4) = "A"
                    If TabRef(3) <> "Z" Then
                        TabRef(3) = Chr(Asc(TabRef(3)) + 1)
                    Else
                        TabRef(3) = "A"
                        If TabRef(2) <> "Z" Then
                            TabRef(2) = Chr(Asc(TabRef(2)) + 1)
                        Else
                            TabRef(2) = "A"
                            If TabRef(1) <> " " Then
                                TabRef(1) = Chr(Asc(TabRef(1)) + 1)
                            Else
                                TabRef(1) = "A"
                            End If
                        End If
                    End If
                End If
                Dim RéférenceLotDRE As String = ""
                For n = 2 To 4
                    If TabRef(n) <> " " Then
                        RéférenceLotDRE = RéférenceLotDRE + TabRef(n)
                    End If
                Next
                RéférenceLotDRE_bdd = ""
                For n = 1 To 4
                    If TabRef(n) <> " " Then
                        RéférenceLotDRE_bdd = RéférenceLotDRE_bdd + TabRef(n)
                    End If
                Next
                Dim datatable As DataTable = Me.LotsTableAdapter.GetDataByRéférence(Nothing, RéférenceLotDRE)
                If datatable.Rows.Count > 0 Then
                    Me.LotsTableAdapter.Delete_By_référence(Nothing, RéférenceLotDRE)

                End If
                SGD_AjouterChamp_Tracé(NumeroSessionLot, RéférenceLotDRE, Visu_API, FichierTrace)

                'champ11
                SGD_AjouterChamp_Tracé(NumeroSessionLot, Lots_DRE_Tab(i).NbreFactures, Visu_API, FichierTrace)

                'groupe86
                SGD_AjouterGroupe_Tracé(NumeroSessionLot, 86, Visu_API, FichierTrace)
                SGD_AjouterChamp_Tracé(NumeroSessionLot, Lots_DRE_Tab(i).CRL, Visu_API, FichierTrace)

                'groupe89
                SGD_AjouterGroupe_Tracé(NumeroSessionLot, 89, Visu_API, FichierTrace)
                For j = 0 To DRE_Tab.Length - 1
                    If DRE_Tab(j).CRL = Lots_DRE_Tab(i).CRL And DRE_Tab(j).traitée = False And DRE_Tab(j).à_traiter = True Then
                        Dim bytes = My.Computer.FileSystem.ReadAllBytes(Config.LocalNetwork_ServerName & "\factures\" + DRE_Tab(j).file)
                        My.Computer.FileSystem.WriteAllBytes(Config.LocalNetwork_ServerName & "\factures\lots\temp", bytes, True)
                        DRE_Tab(j).traitée = True
                        Me.FacturesTableAdapter1.Update_Num_Lot_DRE(RéférenceLotDRE.ToString, datelot, DRE_Tab(j).NumFacture)
                    End If
                Next
                SGD_AjouterChampFichier(NumeroSessionLot, Config.LocalNetwork_ServerName & "\factures\lots\temp")
                Try
                    My.Computer.FileSystem.DeleteFile(Config.LocalNetwork_ServerName & "\factures\lots\temp")
                Catch exept As Exception
                    MyMsg_Box.Presentation("Officine", exept.ToString, False, "", False, "", True, "OK")
                    MyMsg_Box.ShowDialog()
                End Try

                '____________________________________________________________________________________________________

                'SIS_FormaterLot
                Dim code = InputBox("Code CPS")
                Dim out As Integer = SIS_FormaterLot(NomRessourcePS, NomRessourceLecteur, code.ToString, NumeroSessionLot)
                'Dim out As Integer = SIS_FormaterLot(NomRessourcePS, NomRessourceLecteur, "", NumeroSessionLot)
                If out <> 0 Then
                    MyMsg_Box.Presentation("Officine", "erreur constitution lot " + out.ToString, False, "", False, "", True, "OK")
                    MyMsg_Box.ShowDialog() ' + Lots_DRE_Tab(i).Organisme + Chr(10) + out.ToString)
                    Affiche_Lots_à_constituer()
                    Bandeau_info_bas_hide() 'Bandeau_info_bas_show_thread)
                    Exit Sub
                End If
                '____________________________________________________________________________________________________
                'deplacement fichier FSE apres traitement et sauvegarde bdd
                For j = 0 To DRE_Tab.Length - 1
                    If DRE_Tab(j).CRL = Lots_DRE_Tab(i).CRL And DRE_Tab(j).traitée = True And DRE_Tab(j).à_traiter = True Then
                        My.Computer.FileSystem.MoveFile(Config.LocalNetwork_ServerName & "\factures\" + DRE_Tab(j).file, Config.LocalNetwork_ServerName & "\Factures\Traitées\" + DRE_Tab(j).file, True)
                        Me.FacturesTableAdapter1.Update_Num_Lot_DRE(RéférenceLotDRE.ToString, datelot, DRE_Tab(j).NumFacture)
                    End If
                Next
                '____________________________________________________________________________________________________
                'Visu_API agrement CNDA
                If Visu_API = True Then
                    Technique_MAIN.LireSession_Out_VersFichier2(NumeroSessionLot, Application.StartupPath + "\traces\Formater_Lot_DRE_out.txt")
                End If
                '____________________________________________________________________________________________________
                'enregistrement lot dans bdd
                Dim CRF As String = "1234567890123456789012345678901234567890123456789012345678901234"
                SGD_LireChamp(NumeroSessionLot, 90, 1, 1, CRF, 64)
                Dim TailleLot = 0
                SGD_LireChampBin(NumeroSessionLot, 91, 1, 1, ValeurChamp, TailleLot)
                Dim G13C1 As String = "@"
                SGD_LireChamp(NumeroSessionLot, 13, 1, 1, G13C1, 1)
                If G13C1 = "@" Then G13C1 = ""
                Dim G13C2 As String = "@"
                SGD_LireChamp(NumeroSessionLot, 13, 1, 2, G13C2, 1)
                If G13C2 = "@" Then G13C2 = ""
                Dim G13C3 As String = "@@@@@@@@@@@@@@"
                SGD_LireChamp(NumeroSessionLot, 13, 1, 3, G13C3, 14)
                If G13C3 = "@@@@@@@@@@@@@@" Then G13C3 = ""
                Dim G13C4 As String = "@@@@@@@@@@@@@@"
                SGD_LireChamp(NumeroSessionLot, 13, 1, 4, G13C4, 14)
                If G13C4 = "@@@@@@@@@@@@@@" Then G13C4 = ""
                Dim G13C5 As String = "@@@"
                SGD_LireChamp(NumeroSessionLot, 13, 1, 5, G13C5, 3)
                If G13C5 = "@@@" Then G13C5 = ""
                Dim G13C6 As String = "@"
                SGD_LireChamp(NumeroSessionLot, 13, 1, 6, G13C6, 1)
                If G13C6 = "@" Then G13C6 = ""
                Dim G13C7 As String = "@@@@@@@@"
                SGD_LireChamp(NumeroSessionLot, 13, 1, 7, G13C7, 8)
                If G13C7 = "@@@@@@@@" Then G13C7 = ""
                Dim G93C1 As String = "@@@@@@@@@@@@@@"
                SGD_LireChamp(NumeroSessionLot, 93, 1, 1, G93C1, 14)
                If G93C1 = "@@@@@@@@@@@@@@" Then G93C1 = ""
                Dim G93C2 As String = "@@@@@@@@@@"
                SGD_LireChamp(NumeroSessionLot, 93, 1, 2, G93C2, 10)
                If G93C2 = "@@@@@@@@@@" Then G93C2 = ""
                Dim G93C3 As String = "@@@"
                SGD_LireChamp(NumeroSessionLot, 93, 1, 3, G93C3, 3)
                If G93C3 = "@@@" Then G93C3 = ""
                Dim G93C4 As String = "@@@@@@@@@@@@@@@@@@@@"
                TailleMax = 20
                SGD_LireChamp(NumeroSessionLot, 93, 1, 4, G93C4, TailleMax)
                If G93C4 = "@@@@@@@@@@@@@@@@@@@@" Then G93C4 = ""
                G93C4 = Mid(G93C4, 1, TailleMax)
                Dim G93C5 As String = "@@@@@@@@@@@@@@@@@@@@"
                TailleMax = 20
                SGD_LireChamp(NumeroSessionLot, 93, 1, 5, G93C5, TailleMax)
                If G93C5 = "@@@@@@@@@@@@@@@@@@@@" Then G93C5 = ""
                G93C5 = Mid(G93C5, 1, TailleMax)
                Dim G93C6 As String = "@"
                SGD_LireChamp(NumeroSessionLot, 93, 1, 6, G93C6, 8)
                If G93C6 = "@" Then G93C6 = ""
                Dim G93C7 As String = "@@@@@@@@"
                SGD_LireChamp(NumeroSessionLot, 93, 1, 7, G93C7, 8)
                If G93C7 = "@@@@@@@@" Then G93C7 = ""
                Me.LotsTableAdapter.Insert1(Nothing, RéférenceLotDRE, Lots_DRE_Tab(i).CRL, CRF, datelot, Lots_DRE_Tab(i).NbreFactures, Lots_DRE_Tab(i).Total, TailleLot, Lots_DRE_Tab(i).Organisme, G13C1, G13C2, G13C3, G13C4, G13C5, G13C6, G13C7, G93C1, G93C2, G93C3, G93C4, G93C5, G93C6, G93C7, "A TRANSMETTRE", 0, 0, RéférenceLotDRE_bdd, G8_G88_C4, False)
                'enregistrement lot dans fichier
                SGD_LireChampFichier(NumeroSessionLot, 91, 1, 1, Config.LocalNetwork_ServerName & "\Factures\Lots\" + RéférenceLotDRE.ToString + ".lotDRE")
            End If
            SGD_LibererSession(NumeroSessionLot)
        Next

        LoadDRE()
        LoadLots_DRE()
        Affiche_Lots_DRE_à_constituer()
        DRE_DataGridView.Rows.Clear()
        Afficher_lots_DRE_à_transmettre()
        Bandeau_info_bas_hide() 'Bandeau_info_bas_show_thread)
    End Sub

#End Region

#Region "AFFICHAGE DES LOTS ET DES FACTURES DANS LES DATAGRIDVIEW"
    Private Sub Affiche_Factures(ByVal CRL As String, ByVal Organisme As String)
        Label1.Text = Organisme + " (détail)"
        FSE_DataGridView.Rows.Clear()
        Dim j = 0
        For i = 0 To FSE_Tab.Length - 1
            If FSE_Tab(i).CRL = CRL Then
                FSE_DataGridView.Rows.Add()
                If FSE_Tab(i).à_traiter = False Then
                    FSE_DataGridView(à_traiter.Index, j).Value = False
                Else
                    FSE_DataGridView(à_traiter.Index, j).Value = True
                End If
                FSE_DataGridView(NumFacture.Index, j).Value = FSE_Tab(i).NumFacture
                FSE_DataGridView(Bénéficiaire.Index, j).Value = FSE_Tab(i).Bénéficiaire
                FSE_DataGridView(Datef.Index, j).Value = Mid(FSE_Tab(i).Datef, 7, 2) + "/" + Mid(FSE_Tab(i).Datef, 5, 2) + "/" + Mid(FSE_Tab(i).Datef, 1, 4)
                FSE_DataGridView(BaseRemboursement.Index, j).Value = FSE_Tab(i).Total_montants_facturés / 100
                FSE_DataGridView(MontantAMO.Index, j).Value = FSE_Tab(i).MontantAMO / 100
                FSE_DataGridView(MontantAMC.Index, j).Value = FSE_Tab(i).MontantAMC / 100
                j = j + 1
            End If
        Next

    End Sub
    Private Sub Affiche_Factures_DRE(ByVal CRL As String, ByVal Organisme As String)
        Label2.Text = Organisme + " (détail)"
        DRE_DataGridView.Rows.Clear()
        Dim j = 0
        For i = 0 To DRE_Tab.Length - 1
            If DRE_Tab(i).CRL = CRL Then
                DRE_DataGridView.Rows.Add()
                If DRE_Tab(i).à_traiter = False Then
                    DRE_DataGridView(à_traiter.Index, j).Value = False
                Else
                    DRE_DataGridView(DRE_à_traiter.Index, j).Value = True
                End If
                DRE_DataGridView(DRE_Num.Index, j).Value = DRE_Tab(i).NumFacture
                DRE_DataGridView(DRE_Bénéficiaire.Index, j).Value = DRE_Tab(i).Bénéficiaire
                DRE_DataGridView(DRE_date.Index, j).Value = Mid(DRE_Tab(i).Datef, 7, 2) + "/" + Mid(DRE_Tab(i).Datef, 5, 2) + "/" + Mid(DRE_Tab(i).Datef, 1, 4)
                DRE_DataGridView(DRE_total.Index, j).Value = DRE_Tab(i).Total_montants_facturés / 100
                DRE_DataGridView(DRE_AMO.Index, j).Value = DRE_Tab(i).MontantAMO / 100
                DRE_DataGridView(DRE_AMC.Index, j).Value = DRE_Tab(i).MontantAMC / 100
                j = j + 1
            End If
        Next

    End Sub
    Private Sub Afficher_lots_à_transmettre()
        DataGridView_Lots_FSE_à_transmettre.Rows.Clear()
        DataGridView_Lots_FSE_à_transmettre.AutoGenerateColumns = False
        Dim fichierlot As String = Dir(Config.LocalNetwork_ServerName & "\Factures\Lots\*.lotFSE")
        Dim RéférenceLot As String
        Dim nombrelots As Integer = 0
        Do Until fichierlot = ""
            RéférenceLot = Mid(fichierlot, 1, InStr(fichierlot, ".lotFSE") - 1)
            Dim myDataTable As DataTable
            myDataTable = Me.LotsTableAdapter.GetDataByRéférence(Val(RéférenceLot), Nothing)

            'recupère date du lot
            Dim date_lot As String = ""
            For c = 0 To myDataTable.Columns.Count - 1
                If myDataTable.Columns.Item(c).ColumnName = "Date" Then
                    date_lot = myDataTable(0).Item(c).ToString
                    Exit For
                End If
            Next

            If Val(date_lot) <= Val(Format(Now, "yyyyMMdd") + "0000") Then 'compare date du lot avec date système

                DataGridView_Lots_FSE_à_transmettre.Rows.Add()
                For c = 0 To myDataTable.Columns.Count - 1
                    Select Case myDataTable.Columns.Item(c).ColumnName
                        ' Référence, CRL, CRL, Date, NombreDeFSE, Taille, Montant, Organisme, FichierLots 
                        Case "Référence"
                            DataGridView_Lots_FSE_à_transmettre(Référence.Index, nombrelots).Value = myDataTable(0).Item(c).ToString
                        Case "Organisme"
                            DataGridView_Lots_FSE_à_transmettre(Organismet.Index, nombrelots).Value = myDataTable(0).Item(c).ToString
                        Case "Montant"
                            DataGridView_Lots_FSE_à_transmettre(Montant.Index, nombrelots).Value = myDataTable(0).Item(c).ToString
                        Case "NombreDeFSE"
                            DataGridView_Lots_FSE_à_transmettre(NombreDeFSE.Index, nombrelots).Value = myDataTable(0).Item(c).ToString
                        Case "Date"
                            DataGridView_Lots_FSE_à_transmettre(Datet.Index, nombrelots).Value = myDataTable(0).Item(c).ToString
                        Case "Taille"
                            DataGridView_Lots_FSE_à_transmettre(Taille.Index, nombrelots).Value = myDataTable(0).Item(c).ToString
                        Case "CRL"
                            DataGridView_Lots_FSE_à_transmettre(CRLt.Index, nombrelots).Value = myDataTable(0).Item(c).ToString
                        Case "CRF"
                            DataGridView_Lots_FSE_à_transmettre(CRF.Index, nombrelots).Value = myDataTable(0).Item(c).ToString
                    End Select
                    DataGridView_Lots_FSE_à_transmettre(Transmission.Index, nombrelots).Value = True
                Next
                nombrelots = nombrelots + 1
            End If
            fichierlot = Dir()
        Loop
    End Sub
    Private Sub Afficher_lots_DRE_à_transmettre()
        DataGridView_Lots_DRE_à_transmettre.Rows.Clear()
        DataGridView_Lots_DRE_à_transmettre.AutoGenerateColumns = False
        Dim fichierlot As String = Dir(Config.LocalNetwork_ServerName & "\Factures\Lots\*.lotDRE")
        Dim RéférenceLot As String
        Dim nombrelots As Integer = 0
        Do Until fichierlot = ""

            RéférenceLot = Mid(fichierlot, 1, InStr(fichierlot, ".lotDRE") - 1)
            Dim myDataTable As DataTable
            myDataTable = Me.LotsTableAdapter.GetDataByRéférence(Nothing, RéférenceLot)


            'recupère date du lot
            Dim date_lot As String = ""
            For c = 0 To myDataTable.Columns.Count - 1
                If myDataTable.Columns.Item(c).ColumnName = "Date" Then
                    date_lot = myDataTable(0).Item(c).ToString
                    Exit For
                End If
            Next

            If Val(date_lot) <= Val(Format(Now, "yyyyMMdd") + "0000") Then 'compare date du lot avec date système
                DataGridView_Lots_DRE_à_transmettre.Rows.Add()
                Dim destinataire As String = "@"
                For c = 0 To myDataTable.Columns.Count - 1
                    Select Case myDataTable.Columns.Item(c).ColumnName
                        Case "Référence_DRE"
                            DataGridView_Lots_DRE_à_transmettre(DRE_Transmettre_Référence.Index, nombrelots).Value = myDataTable(0).Item(c).ToString
                        Case "G93C4"
                            destinataire = myDataTable(0).Item(c).ToString + destinataire
                        Case "G93C5"
                            destinataire = destinataire + myDataTable(0).Item(c).ToString
                        Case "NombreDeFSE"
                            DataGridView_Lots_DRE_à_transmettre(DRE_Transmettre_NbreFactures.Index, nombrelots).Value = myDataTable(0).Item(c).ToString
                        Case "Date"
                            DataGridView_Lots_DRE_à_transmettre(DRE_Transmettre_Date.Index, nombrelots).Value = myDataTable(0).Item(c).ToString
                        Case "Taille"
                            DataGridView_Lots_DRE_à_transmettre(DRE_Transmettre_Taille.Index, nombrelots).Value = myDataTable(0).Item(c).ToString
                        Case "CRL"
                            DataGridView_Lots_DRE_à_transmettre(DRE_Transmettre_CRL.Index, nombrelots).Value = myDataTable(0).Item(c).ToString
                        Case "CRF"
                            DataGridView_Lots_DRE_à_transmettre(DRE_Transmettre_CRF.Index, nombrelots).Value = myDataTable(0).Item(c).ToString
                    End Select
                Next
                DataGridView_Lots_DRE_à_transmettre(DRE_Transmettre_Destinataire.Index, nombrelots).Value = destinataire
                nombrelots = nombrelots + 1
            End If
            fichierlot = Dir()
        Loop
    End Sub
#End Region

    Private Sub LotDataGridView_CellContentClick(ByVal sender As System.Object, ByVal e As System.Windows.Forms.DataGridViewCellEventArgs) Handles LotDataGridView.CellContentClick

        Select Case LotDataGridView.CurrentCellAddress.X

            Case Détail.Index
                Affiche_Factures(LotDataGridView(CRL.Index, LotDataGridView.CurrentRow.Index).Value, LotDataGridView(Organisme.Index, LotDataGridView.CurrentRow.Index).Value)

            Case Constitution.Index
                If Lots_FSE_Tab(LotDataGridView.CurrentCellAddress.Y).Constitution = True Then
                    Lots_FSE_Tab(LotDataGridView.CurrentCellAddress.Y).Constitution = False
                Else
                    Lots_FSE_Tab(LotDataGridView.CurrentCellAddress.Y).Constitution = True
                End If
        End Select

    End Sub
    Private Sub Lots_DRE_DataGridView_CellContentClick(ByVal sender As System.Object, ByVal e As System.Windows.Forms.DataGridViewCellEventArgs) Handles Lots_DRE_DataGridView.CellContentClick

        Select Case Lots_DRE_DataGridView.CurrentCellAddress.X

            Case DRE_Détail.Index
                Affiche_Factures_DRE(Lots_DRE_DataGridView(CRL.Index, Lots_DRE_DataGridView.CurrentRow.Index).Value, Lots_DRE_DataGridView(Organisme.Index, Lots_DRE_DataGridView.CurrentRow.Index).Value)

            Case Constitution.Index
                If Lots_DRE_Tab(Lots_DRE_DataGridView.CurrentCellAddress.Y).Constitution = True Then
                    Lots_DRE_Tab(Lots_DRE_DataGridView.CurrentCellAddress.Y).Constitution = False
                Else
                    Lots_DRE_Tab(Lots_DRE_DataGridView.CurrentCellAddress.Y).Constitution = True
                End If
        End Select

    End Sub
    Private Sub FSE_DataGridView_CellContentClick(ByVal sender As System.Object, ByVal e As System.Windows.Forms.DataGridViewCellEventArgs) Handles FSE_DataGridView.CellContentClick

        Select Case FSE_DataGridView.CurrentCellAddress.X

            Case à_traiter.Index 'case à cocher traitement oui/non
                For i = 0 To FSE_Tab.Length - 1
                    If FSE_Tab(i).NumFacture = FSE_DataGridView.Item(NumFacture.Index, FSE_DataGridView.CurrentRow.Index).Value Then
                        Select Case FSE_Tab(i).à_traiter
                            Case True
                                If ((Val(Format(Now, "yyyyMMdd") + "0000") - Val(FSE_Tab(i).Datef)) >= 30000 And FSE_Tab(i).TP_AMO = False) Or _
                            ((Val(Format(Now, "yyyyMMdd") + "0000") - Val(FSE_Tab(i).Datef)) >= 80000 And FSE_Tab(i).TP_AMO = True) Then '3 jours HTP ou 8 jours TP max, test tech 12.60.01 et 12.60.02
                                    MyMsg_Box.Presentation("Officine", "DÉLAI TRANSMISSION OBLIGATOIRE DÉPASSÉ", False, "", False, "", True, "OK")
                                    MyMsg_Box.ShowDialog()
                                Else
                                    FSE_Tab(i).à_traiter = False
                                    For j = 0 To Lots_FSE_Tab.Length - 1
                                        If Lots_FSE_Tab(j).CRL = FSE_Tab(i).CRL Then
                                            Lots_FSE_Tab(j).NbreFactures = Lots_FSE_Tab(j).NbreFactures - 1
                                            Lots_FSE_Tab(j).Total = Lots_FSE_Tab(j).Total - FSE_Tab(i).MontantAMO
                                            If Lots_FSE_Tab(j).NbreFactures = 0 Then Lots_FSE_Tab(j).Constitution = False
                                            Exit For
                                        End If
                                    Next
                                End If
                            Case False
                                FSE_Tab(i).à_traiter = True
                                For j = 0 To Lots_FSE_Tab.Length - 1
                                    If Lots_FSE_Tab(j).CRL = FSE_Tab(i).CRL Then
                                        Lots_FSE_Tab(j).NbreFactures = Lots_FSE_Tab(j).NbreFactures + 1
                                        Lots_FSE_Tab(j).Total = Lots_FSE_Tab(j).Total + FSE_Tab(i).MontantAMO
                                        Exit For
                                    End If
                                Next
                        End Select
                        Exit For
                    End If
                Next
                Affiche_Lots_à_constituer()

            Case EditionFacture.Index
                Edition_Facture(FSE_DataGridView.Item(NumFacture.Index, FSE_DataGridView.CurrentRow.Index).Value)

        End Select
    End Sub
    Private Sub DRE_DataGridView_CellContentClick(ByVal sender As System.Object, ByVal e As System.Windows.Forms.DataGridViewCellEventArgs) Handles DRE_DataGridView.CellContentClick

        Select Case DRE_DataGridView.CurrentCellAddress.X

            Case DRE_à_traiter.Index 'case à cocher traitement oui/non
                For i = 0 To DRE_Tab.Length - 1
                    If DRE_Tab(i).NumFacture = DRE_DataGridView.Item(NumFacture.Index, DRE_DataGridView.CurrentRow.Index).Value Then
                        Select Case DRE_Tab(i).à_traiter
                            Case True
                                If ((Val(Format(Now, "yyyyMMdd") + "0000") - Val(DRE_Tab(i).Datef)) >= 30000 And DRE_Tab(i).TP_AMC = False) Or _
                                ((Val(Format(Now, "yyyyMMdd") + "0000") - Val(DRE_Tab(i).Datef)) >= 80000 And DRE_Tab(i).TP_AMC = True) Then '3 jours HTP ou 8 jours TP max, test tech 12.60.01 et 12.60.02
                                    MyMsg_Box.Presentation("Officine", "DÉLAI TRANSMISSION OBLIGATOIRE DÉPASSÉ", False, "", False, "", True, "OK")
                                    MyMsg_Box.ShowDialog()
                                Else
                                    DRE_Tab(i).à_traiter = False
                                    For j = 0 To Lots_DRE_Tab.Length - 1
                                        If Lots_DRE_Tab(j).CRL = DRE_Tab(i).CRL Then
                                            Lots_DRE_Tab(j).NbreFactures = Lots_DRE_Tab(j).NbreFactures - 1
                                            Lots_DRE_Tab(j).Total = Lots_DRE_Tab(j).Total - DRE_Tab(i).MontantAMC
                                            If Lots_DRE_Tab(j).NbreFactures = 0 Then Lots_DRE_Tab(j).Constitution = False
                                            Exit For
                                        End If
                                    Next
                                End If
                            Case False
                                DRE_Tab(i).à_traiter = True
                                For j = 0 To Lots_DRE_Tab.Length - 1
                                    If Lots_DRE_Tab(j).CRL = DRE_Tab(i).CRL Then
                                        Lots_DRE_Tab(j).NbreFactures = Lots_DRE_Tab(j).NbreFactures + 1
                                        Lots_DRE_Tab(j).Total = Lots_DRE_Tab(j).Total + DRE_Tab(i).MontantAMC
                                        Exit For
                                    End If
                                Next
                        End Select
                        Exit For
                    End If
                Next
                Affiche_Lots_DRE_à_constituer()

            Case DRE_EditionFacture.Index
                Edition_Facture(DRE_DataGridView.Item(DRE_Num.Index, DRE_DataGridView.CurrentRow.Index).Value)
        End Select
    End Sub

    Public Sub Edition_Facture(ByVal Num_Facture)
        Dim détailfactureform As New Détail_Facture
        détailfactureform.Visible = True

        Dim Facture As DataTable = Me.FacturesTableAdapter1.GetFactureDataByNum1(Num_Facture)

        Dim lignes_datatable As DataTable = Me.Facture_LigneFactureTableAdapter1.GetDataByNumFacture(Num_Facture)

        détailfactureform.Text = ("Détail Facture " + Num_Facture.ToString + Chr(10))
        '------------------------
        For c = 0 To Facture.Columns.Count - 1
            If Facture.Columns.Item(c).ColumnName = "G1110C3" Then
                détailfactureform.RichTextBox1.AppendText("Date d’élaboration: " + Mid(Facture(0).Item(c).ToString, 7, 2) + "/" + Mid(Facture(0).Item(c).ToString, 5, 2) + "/" + Mid(Facture(0).Item(c).ToString, 1, 4) + Chr(10))
                Exit For
            End If
        Next
        '------------------------
        détailfactureform.RichTextBox1.AppendText("Identification du bénéficiaire: ")
        '------------------------
        For c = 0 To Facture.Columns.Count - 1
            If Facture.Columns.Item(c).ColumnName = "G1130C2" Then
                détailfactureform.RichTextBox1.AppendText(Facture(0).Item(c).ToString)
                Exit For
            End If
        Next
        '------------------------
        For c = 0 To Facture.Columns.Count - 1
            If Facture.Columns.Item(c).ColumnName = "G1130C3" Then
                détailfactureform.RichTextBox1.AppendText(" " + Facture(0).Item(c).ToString + Chr(10))
                Exit For
            End If
        Next
        '------------------------
        For c = 0 To Facture.Columns.Count - 1
            If Facture.Columns.Item(c).ColumnName = "G1130C4" Then
                détailfactureform.RichTextBox1.AppendText("Né(é): " + Mid(Facture(0).Item(c).ToString, 7, 2) + "/" + Mid(Facture(0).Item(c).ToString, 5, 2) + "/" + Mid(Facture(0).Item(c).ToString, 1, 4))
                Exit For
            End If
        Next
        '------------------------
        For c = 0 To Facture.Columns.Count - 1
            If Facture.Columns.Item(c).ColumnName = "G1130C5" Then
                détailfactureform.RichTextBox1.AppendText(" rang " + Facture(0).Item(c).ToString)
                Exit For
            End If
        Next
        '------------------------
        For c = 0 To Facture.Columns.Count - 1
            If Facture.Columns.Item(c).ColumnName = "G1130C6" Then
                détailfactureform.RichTextBox1.AppendText(" Qualité " + Facture(0).Item(c).ToString + Chr(10))
                Exit For
            End If
        Next
        '------------------------
        For c = 0 To Facture.Columns.Count - 1
            If Facture.Columns.Item(c).ColumnName = "G1130C7" Then
                détailfactureform.RichTextBox1.AppendText("ALD: " + Facture(0).Item(c).ToString)
                Exit For
            End If
        Next
        '------------------------
        For c = 0 To Facture.Columns.Count - 1
            If Facture.Columns.Item(c).ColumnName = "G1130C8" Then
                détailfactureform.RichTextBox1.AppendText(" Code Situation " + Facture(0).Item(c).ToString + Chr(10))
                Exit For
            End If
        Next
        '------------------------
        'LIGNES FACTURES
        For r = 0 To lignes_datatable.Rows.Count - 1

            '------------------------
            For c = 0 To lignes_datatable.Columns.Count - 1
                If lignes_datatable.Columns.Item(c).ColumnName = "G1610C1" Then
                    détailfactureform.RichTextBox1.AppendText("________________________________" + Chr(10) + "Prestation " + lignes_datatable(r).Item(c).ToString)
                    Exit For
                End If
            Next
            '------------------------
            For c = 0 To lignes_datatable.Columns.Count - 1
                If lignes_datatable.Columns.Item(c).ColumnName = "G1610C2" Then
                    détailfactureform.RichTextBox1.AppendText("  " + Mid(lignes_datatable(r).Item(c).ToString, 7, 2) + "/" + Mid(lignes_datatable(r).Item(c).ToString, 5, 2) + "/" + Mid(lignes_datatable(r).Item(c).ToString, 1, 4))
                    Exit For
                End If
            Next
            '------------------------
            For c = 0 To lignes_datatable.Columns.Count - 1
                If lignes_datatable.Columns.Item(c).ColumnName = "G1610C4" Then
                    détailfactureform.RichTextBox1.AppendText("  " + lignes_datatable(r).Item(c).ToString + Chr(10))
                    Exit For
                End If
            Next
            '------------------------
            For c = 0 To lignes_datatable.Columns.Count - 1
                If lignes_datatable.Columns.Item(c).ColumnName = "G1610C6" Then
                    détailfactureform.RichTextBox1.AppendText("honoraires: " + lignes_datatable(r).Item(c).ToString + Chr(10))
                    Exit For
                End If
            Next
            '------------------------
            For c = 0 To lignes_datatable.Columns.Count - 1
                If lignes_datatable.Columns.Item(c).ColumnName = "G1610C7" Then
                    détailfactureform.RichTextBox1.AppendText("Qualificatif de la dépense: " + lignes_datatable(r).Item(c).ToString + Chr(10))
                    Exit For
                End If
            Next
            '------------------------
            For c = 0 To lignes_datatable.Columns.Count - 1
                If lignes_datatable.Columns.Item(c).ColumnName = "G1610C12" Then
                    détailfactureform.RichTextBox1.AppendText("Base de remboursement: " + lignes_datatable(r).Item(c).ToString)
                    Exit For
                End If
            Next
            '------------------------
            For c = 0 To lignes_datatable.Columns.Count - 1
                If lignes_datatable.Columns.Item(c).ColumnName = "G1610C13" Then
                    détailfactureform.RichTextBox1.AppendText("  Taux: " + lignes_datatable(r).Item(c).ToString + "%" + Chr(10))
                    Exit For
                End If
            Next
            '------------------------
            For c = 0 To lignes_datatable.Columns.Count - 1
                If lignes_datatable.Columns.Item(c).ColumnName = "G1610C14" Then
                    détailfactureform.RichTextBox1.AppendText("Montant remboursable par l’AMO: " + lignes_datatable(r).Item(c).ToString)
                    Exit For
                End If
            Next
            '------------------------
            For c = 0 To lignes_datatable.Columns.Count - 1
                If lignes_datatable.Columns.Item(c).ColumnName = "G1610C16" Then
                    détailfactureform.RichTextBox1.AppendText("  Montant restant TM: " + lignes_datatable(r).Item(c).ToString + Chr(10))
                    Exit For
                End If
            Next
        Next
    End Sub

#Region "FORMATER FICHIER"
    Private Sub FormaterFichiers_FSE(ByRef SCOR_Liste_Lots As List(Of String))
        '____________________________________________________________________________________________________
        'Trace
        Trace_Reset_compteur()
        FichierTrace = "traces\Formater_Fichier_in.txt"
        '____________________________________________________________________________________________________

        Dim ConfigXml As New XmlDocument
        ConfigXml.Load("config.xml")
        Dim XMLelementliste As XmlNodeList


        Dim fichierlot As String
        Dim lots_traités(DataGridView_Lots_FSE_à_transmettre.RowCount) As Boolean

        For i = 0 To DataGridView_Lots_FSE_à_transmettre.RowCount - 1
            Dim NombreTotalLotsDansFichier As Integer = 0
            Dim LongueurTotaleLotsDansFichier As Integer = 0
            Dim NombreTotalFacturessDansFichier As Integer = 0

            If DataGridView_Lots_FSE_à_transmettre(Transmission.Index, i).Value = True And lots_traités(i) = False Then
                For j = i To DataGridView_Lots_FSE_à_transmettre.RowCount - 1
                    If DataGridView_Lots_FSE_à_transmettre(Transmission.Index, j).Value = True And lots_traités(j) = False And DataGridView_Lots_FSE_à_transmettre(CRF.Index, i).Value = DataGridView_Lots_FSE_à_transmettre(CRF.Index, j).Value Then
                        NombreTotalLotsDansFichier = NombreTotalLotsDansFichier + 1
                        LongueurTotaleLotsDansFichier = LongueurTotaleLotsDansFichier + Val(DataGridView_Lots_FSE_à_transmettre(Taille.Index, j).Value)
                        NombreTotalFacturessDansFichier = NombreTotalFacturessDansFichier + Val(DataGridView_Lots_FSE_à_transmettre(NombreDeFSE.Index, j).Value)
                    End If
                Next

                SGD_LibererSession(NumeroSessionFichier)
                SGD_ReserverSession(10000000, NumeroSessionFichier)
                'groupe10
                SGD_AjouterGroupe_Tracé(NumeroSessionFichier, 10, Visu_API, FichierTrace)
                'champ1
                SGD_AjouterChamp_Tracé(NumeroSessionFichier, DataGridView_Lots_FSE_à_transmettre(CRF.Index, i).Value, Visu_API, FichierTrace)

                'groupe12
                SGD_AjouterGroupe_Tracé(NumeroSessionFichier, 12, Visu_API, FichierTrace)
                'champ1
                Dim DateFichier As String = Format(Now, "yyyyMMdd") + "0000"
                SGD_AjouterChamp_Tracé(NumeroSessionFichier, DateFichier, Visu_API, FichierTrace)
                'champ2
                Dim NomFichier As String
                NomFichier = (Val(Me.FichiersSVTableAdapter1.SelectMaxNomFichier) + 1).ToString
                SGD_AjouterChamp_Tracé(NumeroSessionFichier, NomFichier, Visu_API, FichierTrace)
                'champ3
                SGD_AjouterChamp_Tracé(NumeroSessionFichier, NombreTotalLotsDansFichier.ToString, Visu_API, FichierTrace)
                'champ4
                SGD_AjouterChamp_Tracé(NumeroSessionFichier, LongueurTotaleLotsDansFichier.ToString, Visu_API, FichierTrace)
                'champ5,6,7
                If Config.OCT_UtilisationOCT = True Then
                    SGD_AjouterChamp_Tracé(NumeroSessionFichier, Config.OCT_Application, Visu_API, FichierTrace)
                    SGD_AjouterChamp_Tracé(NumeroSessionFichier, Config.OCT_TypeDestinataire, Visu_API, FichierTrace)
                    SGD_AjouterChamp_Tracé(NumeroSessionFichier, Config.OCT_NumDestinataire, Visu_API, FichierTrace)
                Else
                    SGD_AjouterChamp_Tracé(NumeroSessionFichier, "TR", Visu_API, FichierTrace)
                    SGD_AjouterChamp_Tracé(NumeroSessionFichier, "", Visu_API, FichierTrace)

                    'champ7
                    Dim CodeRégimeFichier As String
                    Dim CodeOrgDestFichier As String
                    Dim NumDestinataire As String
                    Dim CodeCentreInfo As String = "000"
                    CodeRégimeFichier = Mid(DataGridView_Lots_FSE_à_transmettre(CRF.Index, i).Value, InStr(DataGridView_Lots_FSE_à_transmettre(CRF.Index, i).Value, "PH") - 2, 2)
                    CodeOrgDestFichier = Mid(DataGridView_Lots_FSE_à_transmettre(CRF.Index, i).Value, InStr(DataGridView_Lots_FSE_à_transmettre(CRF.Index, i).Value, "PH") + 2, 3)
                    If Config.Logiciel_ModeFonctionement = "Test" Then
                        CodeOrgDestFichier = "349"
                        CodeCentreInfo = "000"
                    ElseIf Config.Logiciel_ModeFonctionement = "Démonstration" Then
                        CodeOrgDestFichier = "999"
                        CodeCentreInfo = "999"
                    Else
                        CodeCentreInfo = "000"
                    End If

                    NumDestinataire = "000000" + CodeRégimeFichier + CodeCentreInfo + CodeOrgDestFichier
                    SGD_AjouterChamp_Tracé(NumeroSessionFichier, NumDestinataire, Visu_API, FichierTrace)
                End If
                'groupe14
                SGD_AjouterGroupe_Tracé(NumeroSessionFichier, 14, Visu_API, FichierTrace)

                'Champ1
                SGD_AjouterChamp_Tracé(NumeroSessionFichier, Config.Type_émetteur_fichier, Visu_API, FichierTrace)

                'Champ2
                If Config.Type_émetteur_fichier = "SI" Then
                    SGD_AjouterChamp_Tracé(NumeroSessionFichier, Config.num_émetteur_fichier, Visu_API, FichierTrace)
                ElseIf Config.Activer_Session_Remplacement = False Then
                    ValeurChamp = "12345678"
                    SGD_LireChamp(NumeroSessionCPS, 2, Occurence_Grp2, 9, ValeurChamp, 8)
                    Config.num_émetteur_fichier = ValeurChamp
                    ValeurChamp = "1"
                    SGD_LireChamp(NumeroSessionCPS, 2, Occurence_Grp2, 10, ValeurChamp, 1)
                    Config.num_émetteur_fichier = "00000" + Config.num_émetteur_fichier + ValeurChamp
                    SGD_AjouterChamp_Tracé(NumeroSessionFichier, Config.num_émetteur_fichier, Visu_API, FichierTrace)
                Else
                    Config.num_émetteur_fichier = "00000" + Config.Titulaire_Num_Id_Facturation + Config.Titulaire_Cle_Num_Id_Facturation
                    SGD_AjouterChamp_Tracé(NumeroSessionFichier, Config.num_émetteur_fichier, Visu_API, FichierTrace)
                End If

                'champ3
                XMLelementliste = ConfigXml.GetElementsByTagName("SMTP")
                SGD_AjouterChamp_Tracé(NumeroSessionFichier, XMLelementliste.Item(0).Item("MessageFormatFichier").InnerText, Visu_API, FichierTrace)

                '____________________________________________________________________________________________________

                'formaterfichier
                Dim out As Integer = SIS_FormaterFichier(NumeroSessionFichier)
                If out <> 0 Then
                    MyMsg_Box.Presentation("Officine", "Erreur de Formatage du fichier pour les lots avec" + Chr(10) + "CRF=" + DataGridView_Lots_FSE_à_transmettre(CRF.Index, i).Value + Chr(10) + "ERREUR N°:" + out.ToString, False, "", False, "", True, "OK")
                    MyMsg_Box.ShowDialog()
                    Exit Sub
                End If
                '____________________________________________________________________________________________________

                'Visu_API agrement CNDA
                If Visu_API = True Then
                    Technique_MAIN.LireSession_Out_VersFichier2(NumeroSessionFichier, Application.StartupPath + "\traces\Formater_Fichier_out.txt")
                End If
                '____________________________________________________________________________________________________

                'création fichier  à envoyer
                Dim fichierFSE As String = Config.LocalNetwork_ServerName & "\Factures\Fichiers\" + NomFichier + ".fichierFSE"
                Dim fictemp As String = Config.LocalNetwork_ServerName & "\Factures\Fichiers\temp.txt"
                Dim bytes() As Byte
                'En-tête de fichier de FSE
                ValeurChamp = "12345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678"
                TailleMax = 128
                SGD_LireChampFichier(NumeroSessionFichier, 20, 1, 1, fichierFSE)
                SGD_LireChamp(NumeroSessionFichier, 20, 1, 1, ValeurChamp, TailleMax)


                'ecrit les Lot de FSE dans le fichier 
                For j = i To DataGridView_Lots_FSE_à_transmettre.RowCount - 1
                    If DataGridView_Lots_FSE_à_transmettre(Transmission.Index, j).Value = True And lots_traités(j) = False And DataGridView_Lots_FSE_à_transmettre(CRF.Index, i).Value = DataGridView_Lots_FSE_à_transmettre(CRF.Index, j).Value Then
                        fichierlot = DataGridView_Lots_FSE_à_transmettre(Référence.Index, j).Value.ToString + ".lotFSE"
                        bytes = My.Computer.FileSystem.ReadAllBytes(Config.LocalNetwork_ServerName & "\Factures\Lots\" + fichierlot)
                        My.Computer.FileSystem.WriteAllBytes(fichierFSE, bytes, True)
                        Me.LotsTableAdapter.Update_Fichier(NomFichier, Val(DataGridView_Lots_FSE_à_transmettre(Référence.Index, j).Value), Nothing) 'update nom de fichier dans lequel est mis le lot
                        Me.LotsTableAdapter.Update_DateTransmission(Format(Now, "yyyyMMddHHmmss"), Val(DataGridView_Lots_FSE_à_transmettre(Référence.Index, j).Value), Nothing) 'update état
                        Dim nombretransmission As Integer = Me.LotsTableAdapter.GetDataByRéférence(Val(DataGridView_Lots_FSE_à_transmettre(Référence.Index, j).Value), Nothing).Item(0).NombreTransmission
                        Me.LotsTableAdapter.Update_NombreTransmission(nombretransmission + 1, Val(DataGridView_Lots_FSE_à_transmettre(Référence.Index, j).Value), Nothing)
                        If Mid(DataGridView_Lots_FSE_à_transmettre(CRLt.Index, j).Value, 19, 1) = "D" Then
                            Me.LotsTableAdapter.Update_Etat("DEGRADE", Val(DataGridView_Lots_FSE_à_transmettre(Référence.Index, j).Value), Nothing) 'update état
                            My.Computer.FileSystem.MoveFile(Config.LocalNetwork_ServerName & "\Factures\Lots\" + fichierlot, Config.LocalNetwork_ServerName & "\Factures\Lots\traités\" + fichierlot, True)
                        Else
                            Me.LotsTableAdapter.Update_Etat("ATTENTE ARL", Val(DataGridView_Lots_FSE_à_transmettre(Référence.Index, j).Value), Nothing) 'update état
                            My.Computer.FileSystem.MoveFile(Config.LocalNetwork_ServerName & "\Factures\Lots\" + fichierlot, Config.LocalNetwork_ServerName & "\Factures\Lots\transmis\" + fichierlot, True)
                        End If
                        lots_traités(j) = True
                        SCOR_Liste_Lots.Add(DataGridView_Lots_FSE_à_transmettre(Référence.Index, j).Value.ToString)
                    End If
                Next

                'Fin de fichier de FSE
                ValeurChamp = "12345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678"
                TailleMax = 128
                SGD_LireChampFichier(NumeroSessionFichier, 21, 1, 1, fictemp)
                bytes = My.Computer.FileSystem.ReadAllBytes(fictemp)
                My.Computer.FileSystem.WriteAllBytes(fichierFSE, bytes, True)
                My.Computer.FileSystem.DeleteFile(fictemp)
                'SGD_LireChamp(NumeroSessionFichier, 21, 1, 1, ValeurChamp, TailleMax)

                'enregistre info fichier dans bdd
                Me.FichiersSVTableAdapter1.Insert(Val(NomFichier).ToString, DataGridView_Lots_FSE_à_transmettre(CRF.Index, i).Value, DateFichier, LongueurTotaleLotsDansFichier, NombreTotalLotsDansFichier, NombreTotalFacturessDansFichier)
                SGD_LibererSession(NumeroSessionFichier)
            End If
        Next
    End Sub
    Private Sub FormaterFichiers_DRE()

        '____________________________________________________________________________________________________
        'Trace
        Trace_Reset_compteur()
        FichierTrace = "traces\Formater_Fichier_DRE_in.txt"
        '____________________________________________________________________________________________________

        Dim ConfigXml As New XmlDocument
        ConfigXml.Load("config.xml")
        Dim XMLelementliste As XmlNodeList


        Dim fichierlot As String
        Dim lots_traités(DataGridView_Lots_DRE_à_transmettre.RowCount) As Boolean

        For i = 0 To DataGridView_Lots_DRE_à_transmettre.RowCount - 1

            Dim NombreTotalLotsDansFichier As Integer = 0
            Dim LongueurTotaleLotsDansFichier As Integer = 0
            Dim NombreTotalFacturessDansFichier As Integer = 0

            If DataGridView_Lots_DRE_à_transmettre(DRE_Transmettre_Selection.Index, i).Value = True And lots_traités(i) = False Then
                For j = i To DataGridView_Lots_DRE_à_transmettre.RowCount - 1
                    If DataGridView_Lots_DRE_à_transmettre(DRE_Transmettre_Selection.Index, j).Value = True And lots_traités(j) = False And DataGridView_Lots_DRE_à_transmettre(DRE_Transmettre_CRF.Index, i).Value = DataGridView_Lots_DRE_à_transmettre(DRE_Transmettre_CRF.Index, j).Value Then
                        NombreTotalLotsDansFichier = NombreTotalLotsDansFichier + 1
                        LongueurTotaleLotsDansFichier = LongueurTotaleLotsDansFichier + Val(DataGridView_Lots_DRE_à_transmettre(DRE_Transmettre_Taille.Index, j).Value)
                        NombreTotalFacturessDansFichier = NombreTotalFacturessDansFichier + Val(DataGridView_Lots_DRE_à_transmettre(DRE_Transmettre_NbreFactures.Index, j).Value)
                    End If
                Next

                SGD_LibererSession(NumeroSessionFichier)
                SGD_ReserverSession(10000000, NumeroSessionFichier)
                'groupe90
                SGD_AjouterGroupe_Tracé(NumeroSessionFichier, 90, Visu_API, FichierTrace)
                'champ1
                SGD_AjouterChamp_Tracé(NumeroSessionFichier, DataGridView_Lots_DRE_à_transmettre(DRE_Transmettre_CRF.Index, i).Value, Visu_API, FichierTrace)

                'groupe92
                SGD_AjouterGroupe_Tracé(NumeroSessionFichier, 92, Visu_API, FichierTrace)
                'champ1
                Dim DateFichier As String = Format(Now, "yyyyMMdd") + "0000"
                SGD_AjouterChamp_Tracé(NumeroSessionFichier, DateFichier, Visu_API, FichierTrace)
                'champ2
                Dim NomFichier As String
                NomFichier = (Val(Me.FichiersSVTableAdapter1.SelectMaxNomFichier) + 1).ToString
                SGD_AjouterChamp_Tracé(NumeroSessionFichier, NomFichier, Visu_API, FichierTrace)
                'champ3
                SGD_AjouterChamp_Tracé(NumeroSessionFichier, NombreTotalLotsDansFichier.ToString, Visu_API, FichierTrace)
                'champ4
                SGD_AjouterChamp_Tracé(NumeroSessionFichier, LongueurTotaleLotsDansFichier.ToString, Visu_API, FichierTrace)

                'groupe94
                SGD_AjouterGroupe_Tracé(NumeroSessionFichier, 94, Visu_API, FichierTrace)
                'Champ1
                SGD_AjouterChamp_Tracé(NumeroSessionFichier, Config.Type_émetteur_fichier, Visu_API, FichierTrace)

                'Champ2
                If Config.Type_émetteur_fichier = "SI" Then
                    SGD_AjouterChamp_Tracé(NumeroSessionFichier, Config.num_émetteur_fichier, Visu_API, FichierTrace)
                ElseIf Config.Activer_Session_Remplacement = False Then
                    ValeurChamp = "12345678"
                    SGD_LireChamp(NumeroSessionCPS, 2, Occurence_Grp2, 9, ValeurChamp, 8)
                    Config.num_émetteur_fichier = ValeurChamp
                    ValeurChamp = "1"
                    SGD_LireChamp(NumeroSessionCPS, 2, Occurence_Grp2, 10, ValeurChamp, 1)
                    Config.num_émetteur_fichier = "00000" + Config.num_émetteur_fichier + ValeurChamp
                    SGD_AjouterChamp_Tracé(NumeroSessionFichier, Config.num_émetteur_fichier, Visu_API, FichierTrace)
                Else
                    Config.num_émetteur_fichier = "00000" + Config.Titulaire_Num_Id_Facturation + Config.Titulaire_Cle_Num_Id_Facturation
                    SGD_AjouterChamp_Tracé(NumeroSessionFichier, Config.num_émetteur_fichier, Visu_API, FichierTrace)
                End If
                'champ3
                XMLelementliste = ConfigXml.GetElementsByTagName("SMTP")
                SGD_AjouterChamp_Tracé(NumeroSessionFichier, XMLelementliste.Item(0).Item("MessageFormatFichier").InnerText, Visu_API, FichierTrace)

                '____________________________________________________________________________________________________

                'formaterfichier
                Dim out As Integer = SIS_FormaterFichier(NumeroSessionFichier)
                If out <> 0 Then
                    MyMsg_Box.Presentation("Officine", "Erreur de Formatage du fichier pour les lots avec" + Chr(10) + "CRF=" + DataGridView_Lots_DRE_à_transmettre(DRE_Transmettre_CRF.Index, i).Value + Chr(10) + "ERREUR N°:" + out.ToString, False, "", False, "", True, "OK")
                    MyMsg_Box.ShowDialog()
                    Exit Sub
                End If

                '____________________________________________________________________________________________________

                'Visu_API agrement CNDA
                If Visu_API = True Then
                    Technique_MAIN.LireSession_Out_VersFichier2(NumeroSessionFichier, Application.StartupPath + "\traces\Formater_Fichier_DRE_out.txt")
                End If
                '____________________________________________________________________________________________________

                'création fichier  à envoyer
                Dim fichierDRE As String = Config.LocalNetwork_ServerName & "\Factures\Fichiers\" + NomFichier + ".fichierDRE"
                Dim fictemp As String = Config.LocalNetwork_ServerName & "\Factures\Fichiers\temp.txt"
                Dim bytes() As Byte
                'En-tête de fichier de DRE
                ValeurChamp = "12345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678"
                TailleMax = 128
                SGD_LireChampFichier(NumeroSessionFichier, 25, 1, 1, fichierDRE)
                SGD_LireChamp(NumeroSessionFichier, 25, 1, 1, ValeurChamp, TailleMax)

                'ecrit les Lot de DRE dans le fichier 
                For j = i To DataGridView_Lots_DRE_à_transmettre.RowCount - 1
                    If DataGridView_Lots_DRE_à_transmettre(DRE_Transmettre_Selection.Index, j).Value = True And lots_traités(j) = False And DataGridView_Lots_DRE_à_transmettre(DRE_Transmettre_CRF.Index, i).Value = DataGridView_Lots_DRE_à_transmettre(DRE_Transmettre_CRF.Index, j).Value Then
                        fichierlot = DataGridView_Lots_DRE_à_transmettre(DRE_Transmettre_Référence.Index, j).Value.ToString + ".lotDRE"
                        bytes = My.Computer.FileSystem.ReadAllBytes(Config.LocalNetwork_ServerName & "\Factures\Lots\" + fichierlot)
                        My.Computer.FileSystem.WriteAllBytes(fichierDRE, bytes, True)
                        Me.LotsTableAdapter.Update_Fichier(NomFichier, Nothing, DataGridView_Lots_DRE_à_transmettre(DRE_Transmettre_Référence.Index, j).Value) 'update nom de fichier dans lequel est mis le lot
                        Me.LotsTableAdapter.Update_DateTransmission(Format(Now, "yyyyMMddHHmmss"), Nothing, DataGridView_Lots_DRE_à_transmettre(DRE_Transmettre_Référence.Index, j).Value) 'update état
                        Dim nombretransmission As Integer = Me.LotsTableAdapter.GetDataByRéférence(Nothing, DataGridView_Lots_DRE_à_transmettre(DRE_Transmettre_Référence.Index, j).Value).Item(0).NombreTransmission
                        Me.LotsTableAdapter.Update_NombreTransmission(nombretransmission + 1, Nothing, DataGridView_Lots_DRE_à_transmettre(DRE_Transmettre_Référence.Index, j).Value)
                        'If Mid(DataGridView_Lots_DRE_à_transmettre(DRE_Transmettre_CRL.Index, j).Value, 41, 1) = "D" Then

                        'Me.LotsTableAdapter.Update_Etat("DEGRADE", Nothing, DataGridView_Lots_DRE_à_transmettre(DRE_Transmettre_Référence.Index, j).Value) 'update état
                        'My.Computer.FileSystem.MoveFile(Config.LocalNetwork_ServerName & "\Factures\Lots\" + fichierlot, Config.LocalNetwork_ServerName & "\Factures\Lots\traités\" + fichierlot)
                        'Else
                        Me.LotsTableAdapter.Update_Etat("ATTENTE ARL", Nothing, DataGridView_Lots_DRE_à_transmettre(DRE_Transmettre_Référence.Index, j).Value) 'update état
                        My.Computer.FileSystem.MoveFile(Config.LocalNetwork_ServerName & "\Factures\Lots\" + fichierlot, Config.LocalNetwork_ServerName & "\Factures\Lots\transmis\" + fichierlot, True)
                        'End If
                        lots_traités(j) = True
                    End If
                Next

                'Fin de fichier de DRE
                ValeurChamp = "12345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678"
                TailleMax = 128
                SGD_LireChampFichier(NumeroSessionFichier, 26, 1, 1, fictemp)
                bytes = My.Computer.FileSystem.ReadAllBytes(fictemp)
                My.Computer.FileSystem.WriteAllBytes(fichierDRE, bytes, True)
                My.Computer.FileSystem.DeleteFile(fictemp)

                'enregistre info fichier dans bdd
                Me.FichiersSVTableAdapter1.Insert(Val(NomFichier).ToString, DataGridView_Lots_DRE_à_transmettre(DRE_Transmettre_CRF.Index, i).Value, DateFichier, LongueurTotaleLotsDansFichier, NombreTotalLotsDansFichier, NombreTotalFacturessDansFichier)
                SGD_LibererSession(NumeroSessionFichier)
            End If
        Next
    End Sub

    Private Sub FormaterFichiers_Unique(ByRef SCOR_Liste_Lots As List(Of String))
        '____________________________________________________________________________________________________
        'Trace
        Trace_Reset_compteur()
        FichierTrace = "traces\Formater_Fichier_in.txt"
        '____________________________________________________________________________________________________

        Dim ConfigXml As New XmlDocument
        ConfigXml.Load("config.xml")
        Dim XMLelementliste As XmlNodeList

        Dim NombreTotalLotsDansFichier As Integer = 0
        Dim LongueurTotaleLotsDansFichier As Integer = 0
        Dim NombreTotalFacturessDansFichier As Integer = 0
        Dim fichierlot As String
        'Dim lots_traités(DataGridView_Lots_FSE_à_transmettre.RowCount + DataGridView_Lots_DRE_à_transmettre.RowCount) As Boolean
        Dim CRF_Fichier_Unique As String = ""

        For j = 0 To DataGridView_Lots_FSE_à_transmettre.RowCount - 1
            If DataGridView_Lots_FSE_à_transmettre(Transmission.Index, j).Value = True Then
                NombreTotalLotsDansFichier = NombreTotalLotsDansFichier + 1
                LongueurTotaleLotsDansFichier = LongueurTotaleLotsDansFichier + Val(DataGridView_Lots_FSE_à_transmettre(Taille.Index, j).Value)
                NombreTotalFacturessDansFichier = NombreTotalFacturessDansFichier + Val(DataGridView_Lots_FSE_à_transmettre(NombreDeFSE.Index, j).Value)
                If CRF_Fichier_Unique = "" Then
                    CRF_Fichier_Unique = DataGridView_Lots_FSE_à_transmettre(CRF.Index, j).Value
                End If

            End If
        Next
        For j = 0 To DataGridView_Lots_DRE_à_transmettre.RowCount - 1
            If DataGridView_Lots_DRE_à_transmettre(DRE_Transmettre_Selection.Index, j).Value = True Then
                NombreTotalLotsDansFichier = NombreTotalLotsDansFichier + 1
                LongueurTotaleLotsDansFichier = LongueurTotaleLotsDansFichier + Val(DataGridView_Lots_DRE_à_transmettre(DRE_Transmettre_Taille.Index, j).Value)
                NombreTotalFacturessDansFichier = NombreTotalFacturessDansFichier + Val(DataGridView_Lots_DRE_à_transmettre(DRE_Transmettre_NbreFactures.Index, j).Value)
                If CRF_Fichier_Unique = "" Then
                    CRF_Fichier_Unique = DataGridView_Lots_DRE_à_transmettre(DRE_Transmettre_CRF.Index, j).Value
                End If
            End If
        Next

        SGD_LibererSession(NumeroSessionFichier)
        SGD_ReserverSession(10000000, NumeroSessionFichier)
        'groupe10
        SGD_AjouterGroupe_Tracé(NumeroSessionFichier, 10, Visu_API, FichierTrace)
        'champ1
        'SGD_AjouterChamp_Tracé(NumeroSessionFichier, DataGridView_Lots_FSE_à_transmettre(CRF.Index, i).Value, Visu_API, FichierTrace)
        SGD_AjouterChamp_Tracé(NumeroSessionFichier, CRF_Fichier_Unique, Visu_API, FichierTrace)

        'groupe12
        SGD_AjouterGroupe_Tracé(NumeroSessionFichier, 12, Visu_API, FichierTrace)
        'champ1
        Dim DateFichier As String = Format(Now, "yyyyMMdd") + "0000"
        SGD_AjouterChamp_Tracé(NumeroSessionFichier, DateFichier, Visu_API, FichierTrace)
        'champ2
        Dim NomFichier As String
        NomFichier = (Val(Me.FichiersSVTableAdapter1.SelectMaxNomFichier) + 1).ToString
        SGD_AjouterChamp_Tracé(NumeroSessionFichier, NomFichier, Visu_API, FichierTrace)
        'champ3
        SGD_AjouterChamp_Tracé(NumeroSessionFichier, NombreTotalLotsDansFichier.ToString, Visu_API, FichierTrace)
        'champ4
        SGD_AjouterChamp_Tracé(NumeroSessionFichier, LongueurTotaleLotsDansFichier.ToString, Visu_API, FichierTrace)
        'champ5,6,7
        If Config.OCT_UtilisationOCT = True Then
            SGD_AjouterChamp_Tracé(NumeroSessionFichier, Config.OCT_Application, Visu_API, FichierTrace)
            SGD_AjouterChamp_Tracé(NumeroSessionFichier, Config.OCT_TypeDestinataire, Visu_API, FichierTrace)
            SGD_AjouterChamp_Tracé(NumeroSessionFichier, Config.OCT_NumDestinataire, Visu_API, FichierTrace)
        Else
            SGD_AjouterChamp_Tracé(NumeroSessionFichier, "TR", Visu_API, FichierTrace)
            SGD_AjouterChamp_Tracé(NumeroSessionFichier, "", Visu_API, FichierTrace)
            SGD_AjouterChamp_Tracé(NumeroSessionFichier, "00000000000000", Visu_API, FichierTrace)
        End If

        'groupe14
        SGD_AjouterGroupe_Tracé(NumeroSessionFichier, 14, Visu_API, FichierTrace)

        'Champ1
        SGD_AjouterChamp_Tracé(NumeroSessionFichier, Config.Type_émetteur_fichier, Visu_API, FichierTrace)

        'Champ2
        If Config.Type_émetteur_fichier = "SI" Then
            SGD_AjouterChamp_Tracé(NumeroSessionFichier, Config.num_émetteur_fichier, Visu_API, FichierTrace)
        ElseIf Config.Activer_Session_Remplacement = False Then
            ValeurChamp = "12345678"
            SGD_LireChamp(NumeroSessionCPS, 2, Occurence_Grp2, 9, ValeurChamp, 8)
            Config.num_émetteur_fichier = ValeurChamp
            ValeurChamp = "1"
            SGD_LireChamp(NumeroSessionCPS, 2, Occurence_Grp2, 10, ValeurChamp, 1)
            Config.num_émetteur_fichier = "00000" + Config.num_émetteur_fichier + ValeurChamp
            SGD_AjouterChamp_Tracé(NumeroSessionFichier, Config.num_émetteur_fichier, Visu_API, FichierTrace)
        Else
            Config.num_émetteur_fichier = "00000" + Config.Titulaire_Num_Id_Facturation + Config.Titulaire_Cle_Num_Id_Facturation
            SGD_AjouterChamp_Tracé(NumeroSessionFichier, Config.num_émetteur_fichier, Visu_API, FichierTrace)
        End If

        'champ3
        XMLelementliste = ConfigXml.GetElementsByTagName("SMTP")
        SGD_AjouterChamp_Tracé(NumeroSessionFichier, XMLelementliste.Item(0).Item("MessageFormatFichier").InnerText, Visu_API, FichierTrace)

        '____________________________________________________________________________________________________

        'formaterfichier
        Dim out As Integer = SIS_FormaterFichier(NumeroSessionFichier)
        If out <> 0 Then
            MyMsg_Box.Presentation("Officine", "Erreur de Formatage du fichier unique" + Chr(10) + "ERREUR N°:" + out.ToString, False, "", False, "", True, "OK")
            MyMsg_Box.ShowDialog()
            Exit Sub
        End If

        '____________________________________________________________________________________________________

        'Visu_API agrement CNDA
        If Visu_API = True Then
            Technique_MAIN.LireSession_Out_VersFichier2(NumeroSessionFichier, Application.StartupPath + "\traces\Formater_Fichier_out.txt")
        End If
        '____________________________________________________________________________________________________

        'création fichier  à envoyer
        Dim fichierunique As String = Config.LocalNetwork_ServerName & "\Factures\Fichiers\" + NomFichier + ".fichierunique"
        Dim fictemp As String = Config.LocalNetwork_ServerName & "\Factures\Fichiers\temp.txt"
        Dim bytes() As Byte
        'En-tête de fichier de FSE
        ValeurChamp = "12345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678"
        TailleMax = 128
        SGD_LireChampFichier(NumeroSessionFichier, 20, 1, 1, fichierunique)
        SGD_LireChamp(NumeroSessionFichier, 20, 1, 1, ValeurChamp, TailleMax)

        'ecrit les Lot de FSE dans le fichier 
        For j = 0 To DataGridView_Lots_FSE_à_transmettre.RowCount - 1
            If DataGridView_Lots_FSE_à_transmettre(Transmission.Index, j).Value = True Then
                fichierlot = DataGridView_Lots_FSE_à_transmettre(Référence.Index, j).Value.ToString + ".lotFSE"
                bytes = My.Computer.FileSystem.ReadAllBytes(Config.LocalNetwork_ServerName & "\Factures\Lots\" + fichierlot)
                My.Computer.FileSystem.WriteAllBytes(fichierunique, bytes, True)
                Me.LotsTableAdapter.Update_Fichier(NomFichier, Val(DataGridView_Lots_FSE_à_transmettre(Référence.Index, j).Value), Nothing) 'update nom de fichier dans lequel est mis le lot
                If Mid(DataGridView_Lots_FSE_à_transmettre(CRLt.Index, j).Value, 19, 1) = "D" Then
                    Me.LotsTableAdapter.Update_Etat("DEGRADE", Val(DataGridView_Lots_FSE_à_transmettre(Référence.Index, j).Value), Nothing) 'update état
                Else
                    Me.LotsTableAdapter.Update_Etat("ATTENTE ARL", Val(DataGridView_Lots_FSE_à_transmettre(Référence.Index, j).Value), Nothing) 'update état
                End If
                Me.LotsTableAdapter.Update_DateTransmission(Format(Now, "yyyyMMddHHmmss"), Val(DataGridView_Lots_FSE_à_transmettre(Référence.Index, j).Value), Nothing) 'update date transm
                Dim nombretransmission As Integer = Me.LotsTableAdapter.GetDataByRéférence(Val(DataGridView_Lots_FSE_à_transmettre(Référence.Index, j).Value), Nothing).Item(0).NombreTransmission
                Me.LotsTableAdapter.Update_NombreTransmission(nombretransmission + 1, Val(DataGridView_Lots_FSE_à_transmettre(Référence.Index, j).Value), Nothing)
                My.Computer.FileSystem.MoveFile(Config.LocalNetwork_ServerName & "\Factures\Lots\" + fichierlot, Config.LocalNetwork_ServerName & "\Factures\Lots\transmis\" + fichierlot, True)
                SCOR_Liste_Lots.Add(DataGridView_Lots_FSE_à_transmettre(Référence.Index, j).Value.ToString)
            End If
        Next
        'ecrit les Lot de DRE dans le fichier 
        For j = 0 To DataGridView_Lots_DRE_à_transmettre.RowCount - 1
            If DataGridView_Lots_DRE_à_transmettre(DRE_Transmettre_Selection.Index, j).Value = True Then
                fichierlot = DataGridView_Lots_DRE_à_transmettre(DRE_Transmettre_Référence.Index, j).Value.ToString + ".lotDRE"
                bytes = My.Computer.FileSystem.ReadAllBytes(Config.LocalNetwork_ServerName & "\Factures\Lots\" + fichierlot)
                My.Computer.FileSystem.WriteAllBytes(fichierunique, bytes, True)
                Me.LotsTableAdapter.Update_Fichier(NomFichier, Nothing, DataGridView_Lots_DRE_à_transmettre(DRE_Transmettre_Référence.Index, j).Value) 'update nom de fichier dans lequel est mis le lot
                Me.LotsTableAdapter.Update_Etat("ATTENTE ARL", Nothing, DataGridView_Lots_DRE_à_transmettre(DRE_Transmettre_Référence.Index, j).Value) 'update état
                Me.LotsTableAdapter.Update_DateTransmission(Format(Now, "yyyyMMddHHmmss"), Nothing, DataGridView_Lots_DRE_à_transmettre(DRE_Transmettre_Référence.Index, j).Value) 'update état
                Dim nombretransmission As Integer = Me.LotsTableAdapter.GetDataByRéférence(Nothing, DataGridView_Lots_DRE_à_transmettre(DRE_Transmettre_Référence.Index, j).Value).Item(0).NombreTransmission
                Me.LotsTableAdapter.Update_NombreTransmission(nombretransmission + 1, Nothing, DataGridView_Lots_DRE_à_transmettre(DRE_Transmettre_Référence.Index, j).Value)
                My.Computer.FileSystem.MoveFile(Config.LocalNetwork_ServerName & "\Factures\Lots\" + fichierlot, Config.LocalNetwork_ServerName & "\Factures\Lots\transmis\" + fichierlot, True)
            End If
        Next

        'Fin de fichier de FSE
        ValeurChamp = "12345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678"
        TailleMax = 128
        SGD_LireChampFichier(NumeroSessionFichier, 21, 1, 1, fictemp)
        bytes = My.Computer.FileSystem.ReadAllBytes(fictemp)
        My.Computer.FileSystem.WriteAllBytes(fichierunique, bytes, True)
        My.Computer.FileSystem.DeleteFile(fictemp)
        'SGD_LireChamp(NumeroSessionFichier, 21, 1, 1, ValeurChamp, TailleMax)

        'enregistre info fichier dans bdd
        Me.FichiersSVTableAdapter1.Insert(Val(NomFichier).ToString, "Fichier Unique", DateFichier, LongueurTotaleLotsDansFichier, NombreTotalLotsDansFichier, NombreTotalFacturessDansFichier)
        SGD_LibererSession(NumeroSessionFichier)

    End Sub
#End Region

#Region "ENVOI RECEPTION"
    'FSE
    Public Sub Transmettre_Lots_FSE()


        RichTextBox1.Clear()

        If Traitement_Retour() = True Then

            Dim SCOR_Liste_Lots As New List(Of String)
            Bandeau_info_bas_show("Transmission des lots... ")
            If Config.OCT_UtilisationOCT = False Then 'Or Config.OCT_FSE_FichierUnique = False Then
                FormaterFichiers_FSE(SCOR_Liste_Lots)
                SendMail_FSE()
            Else
                FormaterFichiers_Unique(SCOR_Liste_Lots)
                SendMail_Fichier_Unique()
            End If
            Bandeau_info_bas_hide() 'Bandeau_info_bas_show_thread)
            Afficher_lots_à_transmettre()
            Afficher_lots_DRE_à_transmettre()
            If Config.Scor_cdrom = False Then
                SCOR_GO(SCOR_Liste_Lots, False)

                Scor_TrasmettreLotsnonTransmis()

            Else
                For Each lot In SCOR_Liste_Lots
                    Me.SCOR_lotsTableAdapter.Insert("", lot, "Sauvegarde pour Cdrom", "", "", "")
                    SCOR_affiche_Lots()
                Next
            End If

        End If
        Affiche_Lots_erreur()
    End Sub
    Private Sub TransmettreButton_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles TransmettreButton.Click
        Transmettre_Lots_FSE()
    End Sub

    'DRE
    Private Sub Button_DRE_Transmettre_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button_DRE_Transmettre.Click
        RichTextBox1.Clear()

        If Traitement_Retour() = True Then
            Dim SCOR_Liste_Lots As New List(Of String)
            If Config.OCT_UtilisationOCT = False Or Config.OCT_FSE_FichierUnique = False Then
                FormaterFichiers_DRE()
                SendMail_DRE()
            Else
                FormaterFichiers_Unique(SCOR_Liste_Lots)
                SendMail_Fichier_Unique()
                SCOR_GO(SCOR_Liste_Lots, False)
            End If
            Afficher_lots_à_transmettre()
            Afficher_lots_DRE_à_transmettre()

        End If
    End Sub

    Private Sub SendMail_FSE()
        Dim fichieràtransmettre As String
        Dim ConfigXml As New XmlDocument
        ConfigXml.Load("config.xml")
        Dim XMLelementliste As XmlNodeList
        XMLelementliste = ConfigXml.GetElementsByTagName("RepertoireFichiers")
        Dim chemin As String = XMLelementliste.Item(0).InnerText
        fichieràtransmettre = Dir(chemin + "*.fichierFSE")
        If fichieràtransmettre = "" Then
            MyMsg_Box.Presentation("Officine", "PAS DE FICHIER A TRANSMETTRE", False, "", False, "", True, "OK")
            MyMsg_Box.ShowDialog()
            Exit Sub
        End If
        Using swtrace As New StreamWriter("traces\" + Format(Now, "yyyyMMdd") + "TraceMail_send.txt", True) 'TRACE

            Do
                Try
                    Dim Référence_Fichier As String = Mid(fichieràtransmettre, 1, InStr(fichieràtransmettre, ".fichierFSE") - 1)
                    Dim CRF As String = Me.FichiersSVTableAdapter1.GetDataByNomFichier(Val(Référence_Fichier)).Item(0).CRF
                    Dim from_, Subject, ContentType As String
                    Dim to_ As String = ""
                    Dim ContentDescription As String = ""
                    swtrace.WriteLine("----------------------------------------------------------------------------------------")
                    swtrace.WriteLine("Date:" + FormatDateTime(Now, DateFormat.GeneralDate))
                    '--------------------------------------------------------------------------------------------------------------------------
                    'From
                    from_ = Config.SMTP_From
                    swtrace.WriteLine("from: " + from_)
                    '--------------------------------------------------------------------------------------------------------------------------
                    'To
                    Dim CNDAXml As New XmlDocument 'forçage adresse CNDA 
                    CNDAXml.Load(Application.StartupPath + "\CNDA.xml")
                    Dim CNDAXmlelementliste As XmlNodeList 'forçage adresse CNDA 
                    CNDAXmlelementliste = CNDAXml.GetElementsByTagName("Adr_CNDA") 'forçage adresse CNDA 
                    If UCase(CNDAXmlelementliste.Item(0).InnerText) = "OUI" Then 'forçage adresse CNDA 
                        Dim pos As Integer = InStr(CRF, "PH") 'forçage adresse CNDA 
                        to_ = Mid(CRF, pos - 2, 2) + "349@349." + Mid(CRF, pos - 2, 2) + ".rss.fr" '& " , julien.misiak@orange.fr"
                        swtrace.WriteLine("To:" + to_) 'forçage adresse CNDA 

                    ElseIf Config.OCT_UtilisationOCT = True Then
                        to_ = Config.OCT_AdressemailOCT
                        swtrace.WriteLine("To: " + to_)

                    Else
                        Dim pos As Integer = InStr(CRF, "PH")
                        to_ = Mid(CRF, pos - 2, 2) + Mid(CRF, pos + 2, 3) + "@" + Mid(CRF, pos + 2, 3) + "." + Mid(CRF, pos - 2, 2) + ".rss.fr"
                        'to_ = "bal.tampon@349.01.RSS.FR" 'test AR_P
                        swtrace.WriteLine("To:" + to_)

                    End If

                    If Me.Pop_Allowed_ListTableAdapter.Select_Count_By_Adresse(to_) = 0 Then
                        Me.Pop_Allowed_ListTableAdapter.InsertQuery(to_)
                    End If
                    '--------------------------------------------------------------------------------------------------------------------------
                    'Message-ID
                    swtrace.WriteLine("Message-ID: <" + fichieràtransmettre + ">")
                    '--------------------------------------------------------------------------------------------------------------------------
                    'Subject
                    Dim numemetteur As String
                    numemetteur = Me.LotsTableAdapter.GetDataByFichierLots(Mid(fichieràtransmettre, 1, InStr(fichieràtransmettre, ".") - 1)).Item(0).G13C3.ToString()
                    Dim compteur As Integer = SmtpTableAdapter1.SelectMaxCompteur + 1
                    Dim compteurstring As String = compteur.ToString
                    While compteurstring.Length < 5
                        compteurstring = "0" + compteurstring
                    End While
                    Dim NombreFactures As Integer = Me.FichiersSVTableAdapter1.GetDataByNomFichier(Val(fichieràtransmettre)).Item(0).NombresFactures
                    Dim NombreFacturesstring As String = NombreFactures.ToString
                    While NombreFacturesstring.Length < 5
                        NombreFacturesstring = "0" + NombreFacturesstring
                    End While
                    Subject = Me.LotsTableAdapter.GetDataByFichierLots(Mid(fichieràtransmettre, 1, InStr(fichieràtransmettre, ".") - 1)).Item(0).G13C7.ToString() + "/" + numemetteur + "/" + Format(Now, "yyyyMMddHHmmss") + compteurstring + "/" + NombreFacturesstring
                    swtrace.WriteLine("Subject: " + Subject)
                    '--------------------------------------------------------------------------------------------------------------------------
                    ContentType = "Application/EDI-consent"
                    swtrace.WriteLine("Content-Type: Application/EDI-consent")
                    '--------------------------------------------------------------------------------------------------------------------------
                    Select Case Me.LotsTableAdapter.GetDataBy_FichierLots(Mid(fichieràtransmettre, 1, InStr(fichieràtransmettre, ".") - 1)).Item(0).G13C6
                        Case "T"
                            ContentDescription = "FSETEST/B2"
                        Case "R"
                            ContentDescription = "FSE/B2"
                        Case "D"
                            ContentDescription = "FSEDEMO/B2"
                    End Select
                    'XMLelementliste = ConfigXml.GetElementsByTagName("ModeFonctionnement")
                    'Select Case XMLelementliste.Item(0).InnerText
                    '    Case "Test"
                    '        ContentDescription = "FSETEST/B2"
                    '    Case "Réel"
                    '        ContentDescription = "FSE/B2"
                    '    Case "Demonstration"
                    '        ContentDescription = "FSEDEMO/B2"
                    'End Select
                    XMLelementliste = ConfigXml.GetElementsByTagName("CompresserDonnees")
                    If UCase(XMLelementliste.Item(0).InnerText) = "OUI" Then 'compression
                        ContentDescription = ContentDescription + "/Z"
                    End If
                    '--------------------------------------------------------------------------------------------------------------------------
                    swtrace.WriteLine("Content-Description: " + ContentDescription)
                    '--------------------------------------------------------------------------------------------------------------------------
                    Me.SmtpTableAdapter1.Insert1(compteur, FormatDateTime(Now, DateFormat.GeneralDate), fichieràtransmettre, Subject, from_, to_, ContentType, ContentDescription, CRF)
                    '--------------------------------------------------------------------------------------------------------------------------

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


                    If UCase(XMLelementliste.Item(0).InnerText) = "OUI" Then 'compression
                        ShellandWait("c:\gzip", "gzip.exe", chemin + fichieràtransmettre)
                        fichieràtransmettre = fichieràtransmettre + ".gz"
                    End If
                    swtrace.WriteLine("Num Fichier Transmis: " + Référence_Fichier)
                    '--------------------------------------------------------------------------------------------------------------------------
                    Dim message As New MailMessage(from_, to_, Subject, Nothing)
                    'Dim message As New MailMessage(from_, "542025291@resopharma.fr", Subject, Nothing)
                    Dim mimeType As ContentType = New ContentType("Application/EDI-consent")
                    mimeType.MediaType = "Application/EDI-consent"
                    Dim alternate As New AlternateView(chemin + fichieràtransmettre, mimeType)
                    alternate.TransferEncoding = TransferEncoding.Base64
                    message.AlternateViews.Add(alternate)
                    message.Headers.Add("Content-Description", ContentDescription)
                    Dim client = New SmtpClient(Config.SMTP_Serveur_Externe, Config.SMTP_Serveur_Externe_port)
                    If Config.SMTP_Serveur_Externe_User <> "" Then
                        client.Credentials = New System.Net.NetworkCredential(Config.SMTP_Serveur_Externe_User, Config.SMTP_Serveur_Externe_Password)
                    ElseIf Config.SMTP_Serveur_Externe_port = 587 Then
                        client.Credentials = New System.Net.NetworkCredential(Config.POP3_User, Config.POP3_Password)
                    Else
                        client.UseDefaultCredentials = True
                    End If
                    client.Send(message)
                    alternate.Dispose()
                    message.Dispose()
                    '--------------------------------------------------------------------------------------------------------------------------
                    My.Computer.FileSystem.MoveFile(chemin + fichieràtransmettre, chemin + "Transmis\" + fichieràtransmettre, True)

                    fichieràtransmettre = Dir(chemin + "*.fichierFSE")
                Catch ex As Exception
                    MyMsg_Box.Presentation("Officine", "ERREUR TRANSMISSION" + Chr(10) + ex.ToString, False, "", False, "", True, "OK")
                    MyMsg_Box.ShowDialog()
                    swtrace.WriteLine(ex.ToString)
                    Exit Sub
                End Try
            Loop Until fichieràtransmettre = ""
            '--------------------------------------------------------------------------------------------------------------------------




        End Using
    End Sub

    Private Sub SendMail_DRE()
        Dim fichieràtransmettre As String

        Dim ConfigXml As New XmlDocument
        ConfigXml.Load("config.xml")
        Dim XMLelementliste As XmlNodeList
        XMLelementliste = ConfigXml.GetElementsByTagName("RepertoireFichiers")
        Dim chemin As String = XMLelementliste.Item(0).InnerText
        fichieràtransmettre = Dir(chemin + "*.fichierDRE")
        If fichieràtransmettre = "" Then
            MyMsg_Box.Presentation("Officine", "PAS DE FICHIER A TRANSMETTRE", False, "", False, "", True, "OK")
            MyMsg_Box.ShowDialog()
            Exit Sub
        End If
        Using swtrace As New StreamWriter("Traces\" + Format(Now, "yyyyMMdd") + "TraceMail_send.txt", True) 'TRACE

            Do
                Try
                    Dim Référence_Fichier As String = Mid(fichieràtransmettre, 1, InStr(fichieràtransmettre, ".fichierDRE") - 1)
                    Dim CRF As String = Me.FichiersSVTableAdapter1.GetDataByNomFichier(Val(Référence_Fichier)).Item(0).CRF
                    Dim from_, Subject, ContentType As String
                    Dim to_ As String = ""
                    Dim ContentDescription As String = ""
                    swtrace.WriteLine("----------------------------------------------------------------------------------------")
                    swtrace.WriteLine("Date:" + FormatDateTime(Now, DateFormat.GeneralDate))
                    '--------------------------------------------------------------------------------------------------------------------------
                    'From
                    from_ = Config.SMTP_From
                    swtrace.WriteLine("From: " + from_)
                    '--------------------------------------------------------------------------------------------------------------------------
                    'To
                    Dim CNDAXml As New XmlDocument 'forçage adresse CNDA 
                    CNDAXml.Load("CNDA.xml")
                    Dim CNDAXmlelementliste As XmlNodeList 'forçage adresse CNDA 
                    CNDAXmlelementliste = CNDAXml.GetElementsByTagName("Adr_CNDA") 'forçage adresse CNDA 

                    If UCase(CNDAXmlelementliste.Item(0).InnerText) = "OUI" Then 'forçage adresse CNDA 
                        Select Case Mid(CRF, 31, 2)
                            Case "OC"
                                to_ = "DRE.9999999999.001.9@cnda.rss.fr"
                            Case Else
                                to_ = "DRE." + Mid(CRF, 17, 2) + ".001.9@cnda.rss.fr"
                        End Select
                        swtrace.WriteLine("To: " + to_)

                    ElseIf Config.OCT_UtilisationOCT = True And Config.OCT_FSE_Eclatement_Source = True Then
                        to_ = Config.OCT_AdressemailOCT
                        swtrace.WriteLine("To: " + to_)


                        'ElseIf Config.Logiciel_ModeFonctionement = "Test" Then
                        '    Select Case Mid(CRF, 31, 2)
                        '        Case "OC"
                        '            to_ = "DRE.9999999999.001.9@cnda.rss.fr"
                        '        Case Else
                        '            to_ = "DRE." + Mid(CRF, 17, 2) + ".001.9@cnda.rss.fr"
                        '    End Select
                        '    swtrace.WriteLine("To: " + to_)

                    Else
                        to_ = Me.LotsTableAdapter.GetDataByFichierLots(Mid(fichieràtransmettre, 1, InStr(fichieràtransmettre, ".") - 1)).Item(0).G93C4.ToString() + "@" + Me.LotsTableAdapter.GetDataByFichierLots(Mid(fichieràtransmettre, 1, InStr(fichieràtransmettre, ".") - 1)).Item(0).G93C5.ToString()
                        swtrace.WriteLine("To: " + to_)
                    End If

                    If Me.Pop_Allowed_ListTableAdapter.Select_Count_By_Adresse(to_) = 0 Then
                        Me.Pop_Allowed_ListTableAdapter.InsertQuery(to_)
                    End If
                    '--------------------------------------------------------------------------------------------------------------------------
                    'Subject
                    Dim numemetteur As String
                    numemetteur = Me.LotsTableAdapter.GetDataByFichierLots(Mid(fichieràtransmettre, 1, InStr(fichieràtransmettre, ".") - 1)).Item(0).G93C1.ToString()
                    Dim compteur As Integer = SmtpTableAdapter1.SelectMaxCompteur + 1
                    Dim compteurstring As String = compteur.ToString
                    While compteurstring.Length < 5
                        compteurstring = "0" + compteurstring
                    End While
                    Dim NombreFactures As Integer = Me.FichiersSVTableAdapter1.GetDataByNomFichier(Val(fichieràtransmettre)).Item(0).NombresFactures
                    Dim NombreFacturesstring As String = NombreFactures.ToString
                    While NombreFacturesstring.Length < 5
                        NombreFacturesstring = "0" + NombreFacturesstring
                    End While
                    Subject = Me.LotsTableAdapter.GetDataByFichierLots(Mid(fichieràtransmettre, 1, InStr(fichieràtransmettre, ".") - 1)).Item(0).G93C7.ToString() + "/" + numemetteur + "/" + Format(Now, "yyyyMMddHHmmss") + compteurstring + "/" + NombreFacturesstring
                    swtrace.WriteLine("Subject: " + Subject)
                    '--------------------------------------------------------------------------------------------------------------------------
                    ContentType = "Application/EDI-consent"
                    '--------------------------------------------------------------------------------------------------------------------------
                    Select Case Me.LotsTableAdapter.GetDataBy_FichierLots(Mid(fichieràtransmettre, 1, InStr(fichieràtransmettre, ".") - 1)).Item(0).G93C6
                        Case "T"
                            ContentDescription = "DRETEST/DR"
                        Case "R"
                            ContentDescription = "DRE/DR"
                        Case "D"
                            ContentDescription = "DREDEMO/DR"
                    End Select
                    'XMLelementliste = ConfigXml.GetElementsByTagName("ModeFonctionnement")
                    'Select Case XMLelementliste.Item(0).InnerText
                    '    Case "Test"
                    '        ContentDescription = "DRETEST/DR"
                    '    Case "Réel"
                    '        ContentDescription = "DRE/DR"
                    '    Case "Demonstration"
                    '        ContentDescription = "DREDEMO/DR"
                    'End Select
                    XMLelementliste = ConfigXml.GetElementsByTagName("CompresserDonnees")
                    If UCase(XMLelementliste.Item(0).InnerText) = "OUI" Then 'compression
                        ContentDescription = ContentDescription + "/Z"
                    End If
                    '--------------------------------------------------------------------------------------------------------------------------
                    swtrace.WriteLine("Content-Description: " + ContentDescription)
                    '--------------------------------------------------------------------------------------------------------------------------
                    Me.SmtpTableAdapter1.Insert1(compteur, FormatDateTime(Now, DateFormat.GeneralDate), fichieràtransmettre, Subject, from_, to_, ContentType, ContentDescription, CRF)
                    '--------------------------------------------------------------------------------------------------------------------------
                    '--------------------------------------------------------------------------------------------------------------------------
                    If UCase(XMLelementliste.Item(0).InnerText) = "OUI" Then 'compression
                        ShellandWait("c:\gzip", "gzip.exe", chemin + fichieràtransmettre)
                        fichieràtransmettre = fichieràtransmettre + ".gz"
                    End If
                    swtrace.WriteLine("Num Fichier Transmis: " + Référence_Fichier)
                    '--------------------------------------------------------------------------------------------------------------------------
                    Dim message As New MailMessage(from_, to_, Subject, Nothing)
                    'Dim message As New MailMessage(from_, "542025291@resopharma.fr", Subject, Nothing)

                    Dim mimeType As ContentType = New ContentType("Application/EDI-consent")
                    mimeType.MediaType = "Application/EDI-consent"
                    Dim alternate As New AlternateView(chemin + fichieràtransmettre, mimeType)
                    alternate.TransferEncoding = TransferEncoding.Base64
                    message.AlternateViews.Add(alternate)
                    message.Headers.Add("Content-Description", ContentDescription)
                    Dim client = New SmtpClient(Config.SMTP_Serveur_Externe, Config.SMTP_Serveur_Externe_port)
                    If Config.SMTP_Serveur_Externe_User <> "" Then
                        client.Credentials = New System.Net.NetworkCredential(Config.SMTP_Serveur_Externe_User, Config.SMTP_Serveur_Externe_Password)
                    ElseIf Config.SMTP_Serveur_Externe_port = 587 Then
                        client.Credentials = New System.Net.NetworkCredential(Config.POP3_User, Config.POP3_Password)
                    Else
                        client.UseDefaultCredentials = True
                    End If
                    client.Send(message)
                    alternate.Dispose()
                    message.Dispose()

                    '--------------------------------------------------------------------------------------------------------------------------
                    My.Computer.FileSystem.MoveFile(chemin + fichieràtransmettre, chemin + "Transmis\" + fichieràtransmettre, True)
                    '--------------------------------------------------------------------------------------------------------------------------
                    fichieràtransmettre = Dir(chemin + "*.fichierDRE")

                Catch ex As Exception
                    MyMsg_Box.Presentation("Officine", "ERREUR TRANSMISSION" + Chr(10) + ex.ToString, False, "", False, "", True, "OK")
                    MyMsg_Box.ShowDialog()
                    swtrace.WriteLine(ex.ToString)
                End Try

            Loop Until fichieràtransmettre = ""
            '--------------------------------------------------------------------------------------------------------------------------


        End Using
    End Sub

    Private Sub SendMail_Fichier_Unique()
        Dim fichieràtransmettre As String

        Dim ConfigXml As New XmlDocument
        ConfigXml.Load("config.xml")
        Dim XMLelementliste As XmlNodeList
        XMLelementliste = ConfigXml.GetElementsByTagName("RepertoireFichiers")
        Dim chemin As String = XMLelementliste.Item(0).InnerText
        fichieràtransmettre = Dir(chemin + "*.fichierunique")
        If fichieràtransmettre = "" Then
            MyMsg_Box.Presentation("Officine", "PAS DE FICHIER A TRANSMETTRE", False, "", False, "", True, "OK")
            MyMsg_Box.ShowDialog()
            Exit Sub
        End If
        Using swtrace As New StreamWriter("traces\" + Format(Now, "yyyyMMdd") + "TraceMail_send.txt", True) 'TRACE

            Do
                Dim Référence_Fichier As String = Mid(fichieràtransmettre, 1, InStr(fichieràtransmettre, ".fichierunique") - 1)
                'Dim fichiermail As String = Mid(fichieràtransmettre, 1, InStr(fichieràtransmettre, ".fichierFSE") - 1) + ".mail"
                Dim CRF As String = Me.FichiersSVTableAdapter1.GetDataByNomFichier(Val(Référence_Fichier)).Item(0).CRF
                Dim from_, Subject, ContentType As String
                Dim to_ As String = ""
                Dim ContentDescription As String = ""
                swtrace.WriteLine("----------------------------------------------------------------------------------------")
                swtrace.WriteLine("Date:" + FormatDateTime(Now, DateFormat.GeneralDate))
                '--------------------------------------------------------------------------------------------------------------------------
                'From
                from_ = Config.SMTP_From
                swtrace.WriteLine("From: " + from_)
                '--------------------------------------------------------------------------------------------------------------------------
                'To
                Dim CNDAXml As New XmlDocument 'forçage adresse CNDA 
                CNDAXml.Load("CNDA.xml")
                Dim CNDAXmlelementliste As XmlNodeList 'forçage adresse CNDA 
                CNDAXmlelementliste = CNDAXml.GetElementsByTagName("Adr_CNDA") 'forçage adresse CNDA 

                If CNDAXmlelementliste.Item(0).InnerText = "oui" And Config.OCT_UtilisationOCT = False Then 'forçage adresse CNDA 
                    Dim pos As Integer = InStr(CRF, "PH") 'forçage adresse CNDA 
                    to_ = Mid(CRF, pos - 2, 2) + "349@349." + Mid(CRF, pos - 2, 2) + ".rss.fr"
                    swtrace.WriteLine("To:" + to_) 'forçage adresse CNDA 
                Else

                    to_ = Config.OCT_AdressemailOCT
                    swtrace.WriteLine("To: " + to_)

                    If Me.Pop_Allowed_ListTableAdapter.Select_Count_By_Adresse(to_) = 0 Then
                        Me.Pop_Allowed_ListTableAdapter.InsertQuery(to_)
                    End If
                End If

                '--------------------------------------------------------------------------------------------------------------------------
                'Subject
                Dim numemetteur As String
                numemetteur = Me.LotsTableAdapter.GetDataByFichierLots(Mid(fichieràtransmettre, 1, InStr(fichieràtransmettre, ".") - 1)).Item(0).G13C3.ToString()
                Dim compteur As Integer = SmtpTableAdapter1.SelectMaxCompteur + 1
                Dim compteurstring As String = compteur.ToString
                While compteurstring.Length < 5
                    compteurstring = "0" + compteurstring
                End While
                Dim NombreFactures As Integer = Me.FichiersSVTableAdapter1.GetDataByNomFichier(Val(fichieràtransmettre)).Item(0).NombresFactures
                Dim NombreFacturesstring As String = NombreFactures.ToString
                While NombreFacturesstring.Length < 5
                    NombreFacturesstring = "0" + NombreFacturesstring
                End While
                Subject = Me.LotsTableAdapter.GetDataByFichierLots(Mid(fichieràtransmettre, 1, InStr(fichieràtransmettre, ".") - 1)).Item(0).G13C7.ToString() + "/" + numemetteur + "/" + Format(Now, "yyyyMMddHHmmss") + compteurstring + "/" + NombreFacturesstring
                swtrace.WriteLine("Subject: " + Subject)
                '--------------------------------------------------------------------------------------------------------------------------
                ContentType = "Application/EDI-consent"
                '--------------------------------------------------------------------------------------------------------------------------
                XMLelementliste = ConfigXml.GetElementsByTagName("CompresserDonnees")
                If UCase(XMLelementliste.Item(0).InnerText) = "OUI" Then 'compression
                    ContentDescription = "FACTURE/SV/Z"
                    swtrace.WriteLine("Content-Description: FACTURE/SV/Z")
                Else
                    ContentDescription = "FACTURE/SV"
                    swtrace.WriteLine("Content-Description: FACTURE/SV")
                End If

                '--------------------------------------------------------------------------------------------------------------------------
                Me.SmtpTableAdapter1.Insert1(compteur, FormatDateTime(Now, DateFormat.GeneralDate), fichieràtransmettre, Subject, from_, to_, ContentType, ContentDescription, CRF)
                '--------------------------------------------------------------------------------------------------------------------------
                '--------------------------------------------------------------------------------------------------------------------------
                If UCase(XMLelementliste.Item(0).InnerText) = "OUI" Then 'compression
                    ShellandWait("c:\gzip", "gzip.exe", chemin + fichieràtransmettre)
                    fichieràtransmettre = fichieràtransmettre + ".gz"
                End If
                swtrace.WriteLine("Num Fichier Transmis: " + Référence_Fichier)
                '--------------------------------------------------------------------------------------------------------------------------
                Dim message As New MailMessage(from_, to_, Subject, Nothing)
                'Dim message As New MailMessage(from_, "542025291@resopharma.fr", Subject, Nothing)

                Dim mimeType As ContentType = New ContentType("Application/EDI-consent")
                mimeType.MediaType = "Application/EDI-consent"
                Dim alternate As New AlternateView(chemin + fichieràtransmettre, mimeType)
                alternate.TransferEncoding = TransferEncoding.Base64
                message.AlternateViews.Add(alternate)
                message.Headers.Add("Content-Description", ContentDescription)
                Dim client = New SmtpClient(Config.SMTP_Serveur_Externe, Config.SMTP_Serveur_Externe_port)
                If Config.SMTP_Serveur_Externe_User <> "" Then
                    client.Credentials = New System.Net.NetworkCredential(Config.SMTP_Serveur_Externe_User, Config.SMTP_Serveur_Externe_Password)
                ElseIf Config.SMTP_Serveur_Externe_port = 587 Then
                    client.Credentials = New System.Net.NetworkCredential(Config.POP3_User, Config.POP3_Password)
                Else
                    client.UseDefaultCredentials = True
                End If
                client.Send(message)
                alternate.Dispose()
                message.Dispose()
                '--------------------------------------------------------------------------------------------------------------------------

                My.Computer.FileSystem.MoveFile(chemin + fichieràtransmettre, chemin + "Transmis\" + fichieràtransmettre, True)
                '--------------------------------------------------------------------------------------------------------------------------
                fichieràtransmettre = Dir(chemin + "*.fichierunique")
            Loop Until fichieràtransmettre = ""
            '--------------------------------------------------------------------------------------------------------------------------

        End Using
    End Sub

    Private Sub tempo(ByVal minute As Double)

        LabelReception.Text = "TEMPORISATION EN COURS AVANT RECEPTION RETOURS NOEMI"
        LabelReception.Visible = True
        Me.Refresh()

        'temporisation
        Dim mydate = Now
        While Now < DateAdd(DateInterval.Minute, minute, mydate)
            LabelReception.Text = "TEMPORISATION EN COURS AVANT RECEPTION RETOURS NOEMI, " + DateDiff(DateInterval.Second, Now, DateAdd(DateInterval.Minute, minute, mydate)).ToString + " SECONDES"
            Me.Refresh()
            Thread.Sleep(1000)
        End While
    End Sub

    Private Sub SendMail_Fichier_en_attente()
        If Config.is_local_client = True Then Exit Sub

        Dim fichieràtransmettre As String
        Dim ConfigXml As New XmlDocument
        ConfigXml.Load("config.xml")
        Dim XMLelementliste As XmlNodeList
        XMLelementliste = ConfigXml.GetElementsByTagName("RepertoireFichiers")
        Dim chemin As String = XMLelementliste.Item(0).InnerText
        fichieràtransmettre = Dir(chemin + "*.fichier*.gz")
        If fichieràtransmettre = "" Then
            Exit Sub
        End If
        Using swtrace As New StreamWriter("traces\" + Format(Now, "yyyyMMdd") + "TraceMail_send.txt", True) 'TRACE

            Do
                Try
                    Dim Référence_Fichier As String = Mid(fichieràtransmettre, 1, InStr(fichieràtransmettre, ".fichier") - 1)
                    Dim CRF As String = Me.FichiersSVTableAdapter1.GetDataByNomFichier(Val(Référence_Fichier)).Item(0).CRF
                    Dim from_, Subject, ContentType As String
                    Dim to_ As String = ""
                    Dim ContentDescription As String = ""
                    swtrace.WriteLine("----------------------------------------------------------------------------------------")
                    swtrace.WriteLine("Date:" + FormatDateTime(Now, DateFormat.GeneralDate))
                    '--------------------------------------------------------------------------------------------------------------------------
                    'From
                    from_ = Config.SMTP_From
                    swtrace.WriteLine("from: " + from_)
                    '--------------------------------------------------------------------------------------------------------------------------
                    'To
                    Dim CNDAXml As New XmlDocument 'forçage adresse CNDA 
                    CNDAXml.Load(Application.StartupPath + "\CNDA.xml")
                    Dim CNDAXmlelementliste As XmlNodeList 'forçage adresse CNDA 
                    CNDAXmlelementliste = CNDAXml.GetElementsByTagName("Adr_CNDA") 'forçage adresse CNDA 
                    If UCase(CNDAXmlelementliste.Item(0).InnerText) = "OUI" Then 'forçage adresse CNDA 
                        Dim pos As Integer = InStr(CRF, "PH") 'forçage adresse CNDA 
                        to_ = Mid(CRF, pos - 2, 2) + "349@349." + Mid(CRF, pos - 2, 2) + ".rss.fr"
                        swtrace.WriteLine("To:" + to_) 'forçage adresse CNDA 

                    ElseIf Config.OCT_UtilisationOCT = True Then
                        to_ = Config.OCT_AdressemailOCT
                        swtrace.WriteLine("To: " + to_)

                    Else
                        Dim pos As Integer = InStr(CRF, "PH")
                        to_ = Mid(CRF, pos - 2, 2) + Mid(CRF, pos + 2, 3) + "@" + Mid(CRF, pos + 2, 3) + "." + Mid(CRF, pos - 2, 2) + ".rss.fr"
                        'to_ = "bal.tampon@349.01.RSS.FR" 'test AR_P
                        swtrace.WriteLine("To:" + to_)

                    End If

                    If Me.Pop_Allowed_ListTableAdapter.Select_Count_By_Adresse(to_) = 0 Then
                        Me.Pop_Allowed_ListTableAdapter.InsertQuery(to_)
                    End If
                    '--------------------------------------------------------------------------------------------------------------------------
                    'Message-ID
                    swtrace.WriteLine("Message-ID: <" + fichieràtransmettre + ">")
                    '--------------------------------------------------------------------------------------------------------------------------
                    'Subject
                    Dim numemetteur As String
                    numemetteur = Me.LotsTableAdapter.GetDataByFichierLots(Référence_Fichier).Item(0).G13C3.ToString()
                    Dim compteur As Integer = SmtpTableAdapter1.SelectMaxCompteur + 1
                    Dim compteurstring As String = compteur.ToString
                    While compteurstring.Length < 5
                        compteurstring = "0" + compteurstring
                    End While
                    Dim NombreFactures As Integer = Me.FichiersSVTableAdapter1.GetDataByNomFichier(Val(Référence_Fichier)).Item(0).NombresFactures
                    Dim NombreFacturesstring As String = NombreFactures.ToString
                    While NombreFacturesstring.Length < 5
                        NombreFacturesstring = "0" + NombreFacturesstring
                    End While
                    Subject = Me.LotsTableAdapter.GetDataByFichierLots(Référence_Fichier).Item(0).G13C7.ToString() + "/" + numemetteur + "/" + Format(Now, "yyyyMMddHHmmss") + compteurstring + "/" + NombreFacturesstring
                    swtrace.WriteLine("Subject: " + Subject)
                    '--------------------------------------------------------------------------------------------------------------------------
                    ContentType = "Application/EDI-consent"
                    swtrace.WriteLine("Content-Type: Application/EDI-consent")
                    '--------------------------------------------------------------------------------------------------------------------------
                    If InStr(fichieràtransmettre, "fichierFSE") <> 0 Then
                        Select Case Me.LotsTableAdapter.GetDataBy_FichierLots(Référence_Fichier).Item(0).G13C6
                            Case "T"
                                ContentDescription = "FSETEST/B2/Z"
                            Case "R"
                                ContentDescription = "FSE/B2/Z"
                            Case "D"
                                ContentDescription = "FSEDEMO/B2/Z"
                        End Select
                    ElseIf InStr(fichieràtransmettre, "fichierDRE") <> 0 Then
                        Select Case Me.LotsTableAdapter.GetDataBy_FichierLots(Mid(fichieràtransmettre, 1, InStr(fichieràtransmettre, ".") - 1)).Item(0).G93C6
                            Case "T"
                                ContentDescription = "DRETEST/DR/Z"
                            Case "R"
                                ContentDescription = "DRE/DR/Z"
                            Case "D"
                                ContentDescription = "DREDEMO/DR/Z"
                        End Select
                    ElseIf InStr(fichieràtransmettre, "fichierunique") <> 0 Then
                        ContentDescription = "FACTURE/SV/Z"
                    End If


                    '--------------------------------------------------------------------------------------------------------------------------
                    swtrace.WriteLine("Content-Description: " + ContentDescription)
                    '--------------------------------------------------------------------------------------------------------------------------
                    Me.SmtpTableAdapter1.Insert1(compteur, FormatDateTime(Now, DateFormat.GeneralDate), fichieràtransmettre, Subject, from_, to_, ContentType, ContentDescription, CRF)
                    '--------------------------------------------------------------------------------------------------------------------------

                    swtrace.WriteLine("Num Fichier Transmis: " + Référence_Fichier)
                    '--------------------------------------------------------------------------------------------------------------------------
                    Dim message As New MailMessage(from_, to_, Subject, Nothing)
                    'Dim message As New MailMessage(from_, "542025291@resopharma.fr", Subject, Nothing)
                    Dim mimeType As ContentType = New ContentType("Application/EDI-consent")
                    mimeType.MediaType = "Application/EDI-consent"
                    Dim alternate As New AlternateView(chemin + fichieràtransmettre, mimeType)
                    alternate.TransferEncoding = TransferEncoding.Base64
                    message.AlternateViews.Add(alternate)
                    message.Headers.Add("Content-Description", ContentDescription)
                    Dim client = New SmtpClient(Config.SMTP_Serveur_Externe, Config.SMTP_Serveur_Externe_port)
                    If Config.SMTP_Serveur_Externe_User <> "" Then
                        client.Credentials = New System.Net.NetworkCredential(Config.SMTP_Serveur_Externe_User, Config.SMTP_Serveur_Externe_Password)
                    ElseIf Config.SMTP_Serveur_Externe_port = 587 Then
                        client.Credentials = New System.Net.NetworkCredential(Config.POP3_User, Config.POP3_Password)
                    Else
                        client.UseDefaultCredentials = True
                    End If
                    client.Send(message)
                    alternate.Dispose()
                    message.Dispose()
                    '--------------------------------------------------------------------------------------------------------------------------
                    My.Computer.FileSystem.MoveFile(chemin + fichieràtransmettre, chemin + "Transmis\" + fichieràtransmettre, True)
                    fichieràtransmettre = Dir(chemin + "*.fichier*.gz")
                Catch ex As Exception
                    MyMsg_Box.Presentation("Officine", "ERREUR TRANSMISSION" + Chr(10) + ex.ToString, False, "", False, "", True, "OK")
                    MyMsg_Box.ShowDialog()
                    swtrace.WriteLine(ex.ToString)
                    Exit Sub
                End Try
            Loop Until fichieràtransmettre = ""
            '--------------------------------------------------------------------------------------------------------------------------




        End Using
    End Sub
    Private Function Getmail() As Boolean
        Bandeau_info_bas_show("RECEPTION DES MESSAGES Bal SV")

        Dim Trace_File As String = Mid(Application.ExecutablePath, 1, InStrRev(Application.ExecutablePath, "\")) + "traces\" + Format(Now, "yyyyMMdd") + "TraceMail_Get.txt"
        Using swtrace As New StreamWriter(Trace_File, True) 'TRACE
            Try

                Dim Server As TcpClient
                Dim NetStrm As System.Net.Sockets.NetworkStream
                Dim RdStrm As System.IO.StreamReader
                Dim Data As String
                Dim szData As Byte()

                Dim ConfigXml As New XmlDocument
                ConfigXml.Load("config.xml")
                Dim nodeliste As XmlNodeList
                nodeliste = ConfigXml.GetElementsByTagName("Pop3")
                Dim Serveur As String = nodeliste.Item(0).Item("Serveur").InnerText
                Dim Port As Integer = Val(nodeliste.Item(0).Item("Port").InnerText)
                Dim User As String = nodeliste.Item(0).Item("User").InnerText
                Dim Password As String = nodeliste.Item(0).Item("Password").InnerText

                Dim retour As String



                'create server POP3 with port 110
                LabelReception.Text = "CONNECTION"
                Server = New TcpClient(Serveur, Port)
                NetStrm = Server.GetStream()
                RdStrm = New StreamReader(NetStrm)
                RichTextBox1.Visible = True
                retour = RdStrm.ReadLine()
                swtrace.WriteLine("-------------------------------------------")
                swtrace.WriteLine(Format(Now, "dd/MM/yyyy   HH:mm:ss"))
                swtrace.WriteLine(retour)
                RichTextBox1.AppendText(retour + vbCrLf)
                If InStr(retour, "OK") = 0 Then
                    swtrace.WriteLine("ERREUR DE CONNECTION")
                    RichTextBox1.AppendText("ERREUR DE CONNECTION" + vbCrLf)
                    MyMsg_Box.Presentation("Officine", "ERREUR DE CONNECTION", False, "", False, "", True, "OK")
                    MyMsg_Box.ShowDialog()
                    Bandeau_info_bas_hide() 'Bandeau_info_bas_show_thread)
                    Return False
                End If

                retour = "connected:" + Server.Connected.ToString
                swtrace.WriteLine(retour)
                RichTextBox1.AppendText(retour + vbCrLf)

                'Login Process
                LabelReception.Text = "LOGIN"
                Data = "USER " + User & vbCrLf
                szData = System.Text.Encoding.ASCII.GetBytes(Data.ToCharArray())
                NetStrm.Write(szData, 0, szData.Length)
                retour = RdStrm.ReadLine
                swtrace.WriteLine(retour)
                RichTextBox1.AppendText(retour + vbCrLf)
                If InStr(retour, "OK") = 0 Then
                    swtrace.WriteLine("ERREUR DE CONNECTION")
                    RichTextBox1.AppendText("ERREUR DE CONNECTION" + vbCrLf)
                    MyMsg_Box.Presentation("Officine", "ERREUR DE CONNECTION", False, "", False, "", True, "OK")
                    MyMsg_Box.ShowDialog()
                    Bandeau_info_bas_hide() 'Bandeau_info_bas_show_thread)
                    Return False
                End If

                Data = "PASS " + Password & vbCrLf
                szData = System.Text.Encoding.ASCII.GetBytes(Data.ToCharArray())
                NetStrm.Write(szData, 0, szData.Length)
                retour = RdStrm.ReadLine
                swtrace.WriteLine(retour)
                RichTextBox1.AppendText(retour + vbCrLf)
                If InStr(retour, "OK") = 0 Then
                    swtrace.WriteLine("ERREUR DE CONNECTION")
                    RichTextBox1.AppendText("ERREUR DE CONNECTION" + vbCrLf)
                    MyMsg_Box.Presentation("Officine", "ERREUR DE CONNECTION", False, "", False, "", True, "OK")
                    MyMsg_Box.ShowDialog()
                    Bandeau_info_bas_hide() 'Bandeau_info_bas_show_thread)
                    Return False
                End If

                'Send STAT command to get information ie: number of mail
                LabelReception.Text = "STAT"
                Data = "STAT" & vbCrLf
                szData = System.Text.Encoding.ASCII.GetBytes(Data.ToCharArray())
                NetStrm.Write(szData, 0, szData.Length)
                retour = RdStrm.ReadLine
                swtrace.WriteLine(retour)
                RichTextBox1.AppendText("STAT:" + retour + vbCrLf)
                Dim NumberOfMail As Integer = Val(Trim(Mid(retour, 5, 2)))
                swtrace.WriteLine("Nombre de Message:" + NumberOfMail.ToString)
                RichTextBox1.AppendText("Nombre de Message:" + NumberOfMail.ToString + vbCrLf)


                'retrieve mail with number mail parameter
                LabelReception.Text = "NumberOfMail:" + NumberOfMail.ToString

                If NumberOfMail <> 0 Then

                    For i = 1 To NumberOfMail
                        swtrace.WriteLine("-----Message " + i.ToString + " -----")
                        LabelReception.Text = "Telechargement message " + i.ToString
                        Dim MessageId As String = ""
                        Dim InReplyTo As String = ""
                        Dim Subject As String = ""
                        Dim From_ As String = ""
                        Dim To_ As String = ""
                        Dim Content_Description As String = ""
                        Dim Content_Type As String = ""
                        'Dim FichierPieceJointe As Integer
                        Data = "retr " + i.ToString & vbCrLf
                        szData = System.Text.Encoding.ASCII.GetBytes(Data.ToCharArray())
                        NetStrm.Write(szData, 0, szData.Length)
                        Dim line As String = RdStrm.ReadLine
                        Dim multipart As Boolean = False
                        Dim délimiteur As String = ""
                        Dim Pièce_jointe_téléchargée As Boolean = False
                        Dim message_est_sesamVitale As Boolean = True
                        Dim Fichier_Pièce_Jointe As String = Config.POP3_RepBAL + Format(Now, "yyyyMMddHHmmss") + ".temp"
                        '------------------------------------------------------------------------------------------------
                        While line <> "." And message_est_sesamVitale = True

                            '------------------------------------------------------------------------------------------------
                            If InStr(UCase(line), "MESSAGE-ID:") = 1 Then
                                MessageId = Trim(Mid(line, "Message-Id:".Length + 1))
                                swtrace.WriteLine("MessageId: " + MessageId)
                            ElseIf InStr(UCase(line), "IN-REPLY-TO:") = 1 Then
                                InReplyTo = Trim(Mid(line, "In-Reply-To:".Length + 1))
                                swtrace.WriteLine("In-Reply-To: " + InReplyTo)
                            ElseIf InStr(UCase(line), "SUBJECT:") = 1 Then
                                Subject = Trim(Mid(line, "Subject:".Length + 1))
                                swtrace.WriteLine("Subject: " + Subject)
                            ElseIf InStr(UCase(line), "FROM:") = 1 Then
                                From_ = Trim(Mid(line, "From:".Length + 1))
                                If InStr(From_, "<") = 1 And InStr(From_, ">") = From_.Length Then
                                    From_ = Mid(From_, 2, From_.Length - 2)
                                End If
                                swtrace.WriteLine("From: " + From_)
                            ElseIf InStr(UCase(line), "TO:") = 1 Then
                                To_ = Trim(Mid(line, "To:".Length + 1))
                                swtrace.WriteLine("To: " + To_)
                            ElseIf InStr(UCase(line), "CONTENT-TYPE:") = 1 Then
                                Content_Type = Trim(Mid(line, "Content-Type:".Length + 1))
                                swtrace.WriteLine("Content-Type: " + Content_Type)
                                If InStr(Content_Type, "multipart") <> 0 Then
                                    délimiteur = Mid(Content_Type, InStr(Content_Type, "boundary=") + 9)
                                    multipart = True
                                End If
                            ElseIf InStr(UCase(line), "CONTENT-DESCRIPTION:") = 1 Then
                                Content_Description = Trim(Mid(line, "Content-Description:".Length + 1))
                                swtrace.WriteLine("Content-Description: " + Content_Description)
                            End If

                            '------------------------------------------------------------------------------------------------
                            If From_ <> "" Then
                                If Me.Pop_Allowed_ListTableAdapter.Select_Count_By_Adresse(From_) = 0 Then
                                    MyMsg_Box.Presentation("Officine", "PRESENCE MESSAGE EXPEDITEUR INCONNU DANS BAL" + Chr(10) + "Exp: " + From_ + Chr(10) + "AJOUTER CET EXPEDITEUR DANS LA LISTE DES EMETTEURS DE CONFIANCE?", True, "OUI", True, "NON", False, "")
                                    If MyMsg_Box.ShowDialog() = MsgBoxResult.Yes Then
                                        Me.Pop_Allowed_ListTableAdapter.Insert(From_)
                                    Else
                                        MyMsg_Box.Presentation("Officine", "PRESENCE MESSAGE EXPEDITEUR INCONNU DANS BAL" + Chr(10) + "Exp: " + From_ + Chr(10) + "LE TELECHARGER?", True, "OUI", True, "NON", False, "")
                                        If MyMsg_Box.ShowDialog() = MsgBoxResult.Yes Then
                                            Data = "retr " + i.ToString & vbCrLf
                                            szData = System.Text.Encoding.ASCII.GetBytes(Data.ToCharArray())
                                            NetStrm.Write(szData, 0, szData.Length)
                                            Dim MyFile As String = Config.POP3_RepBAL + Format(Now, "yyyyMMddHHmmss") + "_exp_inconnu.txt"
                                            line = RdStrm.ReadLine
                                            Do
                                                My.Computer.FileSystem.WriteAllText(MyFile, line + Chr(10), True)
                                                line = RdStrm.ReadLine
                                            Loop Until line = "." Or line Is Nothing
                                            multipart = False 'pour ne pas traiter comm un arl
                                            délimiteur = "" 'pour ne pas traiter comm un arl
                                            message_est_sesamVitale = False

                                            'suppression message
                                            LabelReception.Text = "SUPPRESSION MESSAGE " + i.ToString
                                            Data = "DELE " + i.ToString & vbCrLf
                                            szData = System.Text.Encoding.ASCII.GetBytes(Data.ToCharArray())
                                            NetStrm.Write(szData, 0, szData.Length)
                                            While retour <> ""
                                                retour = RdStrm.ReadLine
                                            End While
                                            swtrace.WriteLine(retour)
                                            RichTextBox1.AppendText("MESSAGE " + i.ToString + " SUPPRIMÉ" & vbCrLf)
                                        Else
                                            MyMsg_Box.Presentation("Officine", "PRESENCE MESSAGE EXPEDITEUR INCONNU DANS BAL" + Chr(10) + "Exp: " + From_ + Chr(10) + "SUPPRIMER?", True, "OUI", True, "NON", False, "")
                                            If MyMsg_Box.ShowDialog() = MsgBoxResult.Yes Then
                                                Data = "retr " + i.ToString & vbCrLf
                                                szData = System.Text.Encoding.ASCII.GetBytes(Data.ToCharArray())
                                                NetStrm.Write(szData, 0, szData.Length)
                                                line = RdStrm.ReadLine
                                                Do
                                                    line = RdStrm.ReadLine
                                                Loop Until line = "." Or line Is Nothing
                                                multipart = False 'pour ne pas traiter comm un arl
                                                délimiteur = "" 'pour ne pas traiter comm un arl
                                                message_est_sesamVitale = False

                                                'suppression message
                                                LabelReception.Text = "SUPPRESSION MESSAGE " + i.ToString
                                                Data = "DELE " + i.ToString & vbCrLf
                                                szData = System.Text.Encoding.ASCII.GetBytes(Data.ToCharArray())
                                                NetStrm.Write(szData, 0, szData.Length)
                                                While retour <> ""
                                                    retour = RdStrm.ReadLine
                                                End While
                                                swtrace.WriteLine(retour)
                                                RichTextBox1.AppendText("MESSAGE " + i.ToString + " SUPPRIMÉ" & vbCrLf)
                                            End If
                                        End If
                                    End If
                                End If
                            End If
                            '------------------------------------------------------------------------------------------------
                            'NON REMISE
                            XMLelementliste = ConfigXml.GetElementsByTagName("SMTP")
                            If InStr(UCase(From_), UCase(Config.SMTP_Postmaster)) <> 0 Then
                                message_est_sesamVitale = False
                                Dim MyFile As String = Config.POP3_RepBAL + Format(Now, "yyyyMMddHHmmss") + i.ToString + ".Postmaster"
                                While Dir(Config.POP3_RepBAL + MyFile) <> ""
                                    MyFile = Config.POP3_RepBAL + Format(Now, "yyyyMMddHHmmss") + ".Postmaster"
                                End While
                                My.Computer.FileSystem.WriteAllText(MyFile, Chr(10) + "------------------------------------------------------------------------------------------------" + Chr(10), True)
                                line = RdStrm.ReadLine
                                Do
                                    RichTextBox1.AppendText(line + Chr(10))
                                    My.Computer.FileSystem.WriteAllText(MyFile, line + Chr(10), True)
                                    line = RdStrm.ReadLine
                                Loop Until line = "." Or line Is Nothing
                                My.Computer.FileSystem.WriteAllText(MyFile, "------------------------------------------------------------------------------------------------" + Chr(10), True)
                            End If
                            '------------------------------------------------------------------------------------------------
                            If multipart = False And Content_Description <> "" And Pièce_jointe_téléchargée = False And message_est_sesamVitale = True Then
                                While line <> "" 'avance jusqu'à ligne blanche(juste avant pièce jointe)
                                    line = RdStrm.ReadLine
                                End While
                                'sauvegarde pièce jointe dans fichier temp
                                line = RdStrm.ReadLine 'debut pièce jointe
                                While line <> "" And line <> "."
                                    My.Computer.FileSystem.WriteAllText(Fichier_Pièce_Jointe, line, True)
                                    line = RdStrm.ReadLine
                                End While
                                Pièce_jointe_téléchargée = True
                            End If
                            '------------------------------------------------------------------------------------------------
                            If multipart = True And délimiteur <> "" And message_est_sesamVitale = True Then
                                If InStr(line, "Content-Description") <> 0 Then
                                    While line <> "" 'avance jusqu'à ligne blanche(juste avant pièce jointe)
                                        line = RdStrm.ReadLine
                                    End While
                                    'sauvegarde pièce jointe dans fichier temp
                                    line = RdStrm.ReadLine 'debut pièce jointe
                                    While InStr(line, délimiteur) = 0 And line <> "."
                                        My.Computer.FileSystem.WriteAllText(Fichier_Pièce_Jointe, line, True)
                                        line = RdStrm.ReadLine
                                    End While
                                End If
                            End If
                            '------------------------------------------------------------------------------------------------
                            If message_est_sesamVitale = True And line <> "." Then
                                line = RdStrm.ReadLine
                            End If
                            '------------------------------------------------------------------------------------------------
                        End While

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

                        If InStr(Content_Description, "ARL") = 1 And message_est_sesamVitale = True Then
                            '"ARL/NOEMIE", "ARLDRE/NOEMIE", "ARL/NOEMIE/Z", "ARLDRE/NOEMIE/Z", "ARLTEST/NOEMIE", "ARLDRETEST/NOEMIE", "ARLTEST/NOEMIE/Z", "ARLDRETEST/NOEMIE/Z", "ARLDEMO/NOEMIE", "ARLDREDEMO/NOEMIE", "ARLDEMO/NOEMIE/Z", "ARLDREDEMO/NOEMIE/Z" 
                            'sauvegarde données ARL dans bdd
                            Dim Fichier_ARl As String = Me.ARLTableAdapter.SelectMaxFichierPieceJointe + 1
                            Me.ARLTableAdapter.Insert1(MessageId, InReplyTo, Subject, From_, Fichier_ARl, Content_Description, "", "", _
                                                       Format(Now, "yyyyMMddHHmm"), "", "", "", "", "", "", "")
                            If InStr(Content_Description, "/Z") = Content_Description.Length - 1 Then
                                convert_base64file_to_another_file(Fichier_Pièce_Jointe, Config.LocalNetwork_ServerName & "\Factures\ARL\" + Fichier_ARl.ToString + ".gz", True)
                                ShellandWait("c:\gzip", "gzip.exe", "-d -q " & Config.LocalNetwork_ServerName & "\Factures\ARL\" + Fichier_ARl.ToString + ".gz")
                                My.Computer.FileSystem.RenameFile(Config.LocalNetwork_ServerName & "\Factures\ARL\" + Fichier_ARl.ToString, Fichier_ARl.ToString + ".arl")
                            Else
                                convert_base64file_to_another_file(Fichier_Pièce_Jointe, Config.LocalNetwork_ServerName & "\Factures\ARL\" + Fichier_ARl.ToString + ".arl", True)
                            End If


                        ElseIf InStr(Content_Description, "RSP") = 1 And message_est_sesamVitale = True Then
                            While InStr(Subject, "/") <> 0
                                Subject = Mid(Subject, 1, InStr(Subject, "/") - 1) + "@" + Mid(Subject, InStr(Subject, "/") + 1)
                            End While
                            If InStr(Content_Description, "/Z") = Content_Description.Length - 1 Then
                                convert_base64file_to_another_file(Fichier_Pièce_Jointe, Config.LocalNetwork_ServerName & "\Factures\RSP\temp.gz", True)
                                ShellandWait("c:\gzip", "gzip.exe", "-d -q " & Config.LocalNetwork_ServerName & "\Factures\RSP\temp.gz")
                                My.Computer.FileSystem.RenameFile(Config.LocalNetwork_ServerName & "\Factures\RSP\temp", Format(Now, "yyyyMMddHHmmss") + "@" + Subject + ".rsp")
                            Else
                                If convert_base64file_to_another_file(Fichier_Pièce_Jointe, Config.LocalNetwork_ServerName & "\Factures\RSP\temp", True) = True Then
                                    My.Computer.FileSystem.RenameFile(Config.LocalNetwork_ServerName & "\Factures\RSP\temp", Format(Now, "yyyyMMddHHmmss") + "@" + Subject + ".rsp")
                                Else
                                    Dim name_rsp_file As String = Format(Now, "yyyyMMddHHmmss") + "@" + Subject + ".rsp"
                                    My.Computer.FileSystem.RenameFile(Fichier_Pièce_Jointe, name_rsp_file)
                                    My.Computer.FileSystem.MoveFile(Config.POP3_RepBAL & name_rsp_file, Config.LocalNetwork_ServerName & "\Factures\RSP", True)
                                End If

                            End If


                        ElseIf InStr(Content_Description, "SERVICE/AR_PROVISOIRE") = 1 And message_est_sesamVitale = True And InReplyTo <> "" Then
                            traitement_AR_P(From_, To_, Subject, InReplyTo)


                        ElseIf InStr(Content_Description, "SERVICE/REJET_") = 1 And message_est_sesamVitale = True Then
                            Dim NumRejet As Integer = Me.Service_RejetTableAdapter.SelectMaxNum + 1
                            convert_base64file_to_another_file(Fichier_Pièce_Jointe, Config.POP3_RepBAL + "SERVICE\" + Mid(Content_Description, InStr(Content_Description, "/") + 1) _
                                                                          + "@" + NumRejet.ToString, True)
                            Me.Service_RejetTableAdapter.Insert(Mid(Content_Description, InStr(Content_Description, "/") + 1) + "@" + NumRejet.ToString, _
                                                                From_, To_, Subject, InReplyTo, Content_Description, NumRejet)


                        ElseIf InStr(Content_Description, "REPONSE/dLOI") = 1 And message_est_sesamVitale = True Then 'Message SMTP contenant le fichier d’incrément dLOI signé



                        ElseIf InStr(Content_Description, "REPONSE/ARAN") = 1 And message_est_sesamVitale = True Then 'impossibilité fonctionnelle (ARAN)



                        ElseIf InStr(Content_Description, "SERVICE/FICHIER_NORME") = 1 And message_est_sesamVitale = True Then 'FICHIERS NORMES
                            While InStr(Subject, "/") <> 0
                                Subject = Mid(Subject, 1, InStr(Subject, "/") - 1) + "@" + Mid(Subject, InStr(Subject, "/") + 1)
                            End While
                            convert_base64file_to_another_file(Fichier_Pièce_Jointe, Config.POP3_RepBAL + "Conventions\" + Subject, True)
                            If Mid(Subject, Subject.Length - 1, 2) = "@C" Then
                                MyMsg_Box.Presentation("Officine", "Nouveau Fichier Conventions Reçu", False, "", False, "", True, "OK")
                                MyMsg_Box.ShowDialog()
                            ElseIf Mid(Subject, Subject.Length - 1, 2) = "@R" Then
                                MyMsg_Box.Presentation("Officine", "Nouveau Fichier Regroupement Reçu", False, "", False, "", True, "OK")
                                MyMsg_Box.ShowDialog()
                            End If




                        ElseIf (InStr(Content_Description, "ART/") = 1 Or InStr(Subject, "ART/") = 1) And message_est_sesamVitale = True Then  'fichiers textes (OCT)
                            Try
                                While InStr(Subject, "/") <> 0
                                    Subject = Replace(Subject, "/", "_")
                                End While
                                Dim contenu_fichier = My.Computer.FileSystem.ReadAllText(Fichier_Pièce_Jointe)
                                If InStr(contenu_fichier, "=") <> 0 Then
                                    contenu_fichier = Mid(contenu_fichier, 1, InStr(contenu_fichier, "="))
                                End If
                                My.Computer.FileSystem.DeleteFile(Fichier_Pièce_Jointe)
                                My.Computer.FileSystem.WriteAllText(Fichier_Pièce_Jointe, contenu_fichier, False)
                                If convert_base64file_to_another_file(Fichier_Pièce_Jointe, Config.POP3_RepBAL + "\ART\" + Subject + ".txt", True) = False Then
                                    My.Computer.FileSystem.CopyFile(Fichier_Pièce_Jointe, Config.POP3_RepBAL + "\ART\" + Subject, True)
                                    My.Computer.FileSystem.DeleteFile(Fichier_Pièce_Jointe)
                                Else
                                    Web_browser.Visible = True
                                    Web_browser.WindowState = FormWindowState.Maximized
                                    Web_browser.WebBrowser1.Navigate(Config.POP3_RepBAL + "ART\" + Subject + ".txt")
                                End If

                            Catch ex As Exception
                                MyMsg_Box.Presentation("Officine", ex.ToString, False, "", False, "", True, "OK")
                                MyMsg_Box.ShowDialog()
                            End Try


                        ElseIf InStr(Content_Description, "PH/ACC") = 1 And message_est_sesamVitale = True Then
                            Dim file_new_name = Format(Now, "yyyyMMddHHmmss") + Subject
                            convert_base64file_to_another_file(Fichier_Pièce_Jointe, Config.POP3_RepBAL + "Resopharma\ACC\" + file_new_name, True)
                            Web_browser.Visible = True
                            Web_browser.WindowState = FormWindowState.Maximized
                            Web_browser.WebBrowser1.Navigate(Config.POP3_RepBAL + "Resopharma\ACC\" + file_new_name)

                        ElseIf (InStr(Content_Description, "PH/RPH") = 1 Or InStr(Subject, "Retour Concentrateur RPH LFL345.rph") = 1) And message_est_sesamVitale = True Then
                            convert_base64file_to_another_file(Fichier_Pièce_Jointe, Config.POP3_RepBAL + "Resopharma\RPH\" + Format(Now, "yyyyMMddHHmmss") + Subject + ".rph", True)



                            ''''''''''''''
                        ElseIf InStr(Subject, "dLOI/") = 1 And From_ = Config.LOI_Distr_OCT And message_est_sesamVitale = True Then  'Message SMTP contenant le fichier d’incrément dLOI signé

                            If LOI.LOI_DemandeTableAdapter.Select_Count_By_Subject(InReplyTo) > 0 Or Config.LOI_Controle_Correspondance = False Then
                                ''-------------------
                                ''suppr doublons
                                'If My.Computer.FileSystem.FileExists(Config.LOI_Pop3_RepBAL + "dLOI\" + Mid(Subject, InStr(Subject, "/") + 1) + ".dloi") Then
                                '    My.Computer.FileSystem.DeleteFile(Config.LOI_Pop3_RepBAL + "dLOI\" + Mid(Subject, InStr(Subject, "/") + 1) + ".dloi")
                                'End If
                                '-------------------
                                'If InStr(Content_Description, "/Z") <> 0 Then
                                convert_base64file_to_another_file(Fichier_Pièce_Jointe, Config.LOI_Pop3_RepBAL + "dLOI\temp.gz", True)
                                ShellandWait("c:\gzip", "gzip.exe", "-d -q " + Config.LOI_Pop3_RepBAL + "dLOI\temp.gz")
                                'Else
                                '    convert_base64file_to_another_file(Fichier_Pièce_Jointe, Config.LOI_Pop3_RepBAL + "dLOI\temp", True)
                                'End If
                                Dim name_string As String
                                Dim fs As FileStream
                                fs = File.Open(Config.LOI_Pop3_RepBAL + "dLOI\temp", FileMode.Open)
                                Using be As New BinaryReader(fs)
                                    be.ReadChars(42)
                                    name_string = be.ReadChars(12)
                                    name_string = name_string + "_" + be.ReadChars(12)
                                End Using
                                fs.Close()
                                '-------------------
                                'suppr doublons
                                If My.Computer.FileSystem.FileExists(Config.LOI_Pop3_RepBAL + "dLOI\" + name_string + ".dloi") Then
                                    My.Computer.FileSystem.DeleteFile(Config.LOI_Pop3_RepBAL + "dLOI\" + name_string + ".dloi")
                                End If
                                My.Computer.FileSystem.RenameFile(Config.LOI_Pop3_RepBAL + "dLOI\temp", name_string + ".dloi")
                                '-------------------
                                'RichTextBox_BAL.AppendText("reçu dLOI " + Mid(Subject, InStr(Subject, "/") + 1) + Chr(10))
                                My.Computer.FileSystem.WriteAllText(Application.StartupPath + "\traces\LOI.log", "--------------------------------------------------" + Chr(10) + Format(Now, "dd/MM/yyyy  hh:mm:ss") + Chr(10) + _
                                     "reçu dLOI " + Mid(Subject, InStr(Subject, "/") + 1) + Chr(10), True)
                            Else
                                My.Computer.FileSystem.WriteAllText(Application.StartupPath + "\traces\LOI.log", "--------------------------------------------------" + Chr(10) + Format(Now, "dd/MM/yyyy  hh:mm:ss") + Chr(10) + Chr(10) + _
                                       "Réception d'un retour dLOI ne correspondant à aucune demande envoyée, Incrémént rejeté (InReplyTo " + InReplyTo + ")" + Chr(10), True)
                            End If
                            ''''''''''''''
                        End If




                        'suppression message
                        LabelReception.Text = "SUPPRESSION MESSAGE " + i.ToString
                        Data = "DELE " + i.ToString & vbCrLf
                        szData = System.Text.Encoding.ASCII.GetBytes(Data.ToCharArray())
                        NetStrm.Write(szData, 0, szData.Length)
                        RichTextBox1.AppendText("MESSAGE " + i.ToString + " SUPPRIMÉ" & vbCrLf)
                        swtrace.WriteLine("MESSAGE " + i.ToString + " SUPPRIMÉ")
                    Next

                End If
                'Send QUIT command to close session from POP server
                LabelReception.Text = "DECONNECTION"
                Data = "QUIT" & vbCrLf
                szData = System.Text.Encoding.ASCII.GetBytes(Data.ToCharArray())
                NetStrm.Write(szData, 0, szData.Length)
                RichTextBox1.AppendText("SESSION FERMEE" & vbCrLf)

            Catch ex As Exception
                MyMsg_Box.Presentation("Officine", "ERREUR DE CONNECTION", False, "", False, "", True, "OK")
                MyMsg_Box.ShowDialog()
                swtrace.WriteLine(ex.ToString, True)
                LabelReception.Visible = False
                BAL_relevée = False
                Bandeau_info_bas_hide() 'Bandeau_info_bas_show_thread)
                Return False
            End Try
        End Using
        BAL_relevée = True
        Bandeau_info_bas_hide() 'Bandeau_info_bas_show_thread)
        Return True
    End Function

    Private Function Traitement_Retour() As Boolean

        If Config.is_local_client = True And Config.Logiciel_ModeFonctionement <> "Test" Then Return False

        If Getmail() = False Then
            Return False
        End If
        Dim FichierARL As String = Dir(Config.LocalNetwork_ServerName & "\Factures\ARL\*.arl")
        Dim Idarl As String
        While FichierARL <> ""
            Idarl = Me.ARLTableAdapter.SelectIdByFichier(Mid(FichierARL, 1, InStr(FichierARL, ".") - 1))
            Traitement_ARL(FichierARL, NumeroSessionARL, Idarl)
            FichierARL = Dir(Config.LocalNetwork_ServerName & "\Factures\ARL\*.arl")
        End While

        Traitement_REJET()

        Postmaster()

        Traitement_RSP()

        RPH_traitement_retour()

        Return True
    End Function

    Private Sub Affichage()
        LoadFSE()
        LoadDRE()

        LoadLots_FSE()
        LoadLots_DRE()

        Affiche_Lots_à_constituer()
        Affiche_Lots_DRE_à_constituer()

        Afficher_lots_à_transmettre()
        Afficher_lots_DRE_à_transmettre()
        Affiche_Lots_erreur()

    End Sub
#End Region

#Region "ARL"

    Private Sub Traitement_ARL(ByVal FichierARL As String, ByVal NumeroSession As Integer, ByVal IdARL As String)
        SGD_ReserverSession(10000, NumeroSession)
        SGD_AjouterGroupe(NumeroSession, 30)

        Dim arl As String = My.Computer.FileSystem.ReadAllText(Config.LocalNetwork_ServerName & "\Factures\ARL\" + FichierARL)
        SGD_AjouterChamp(NumeroSession, arl)

        If SIS_TraduireARL(NumeroSession) <> 0 Then
            MyMsg_Box.Presentation("Officine", "ERREUR TRADUCTION ARL", False, "", False, "", True, "OK")
            MyMsg_Box.ShowDialog()
            My.Computer.FileSystem.MoveFile(Config.LocalNetwork_ServerName & "\Factures\ARL\" + FichierARL, Config.LocalNetwork_ServerName & "\Factures\ARL\error\" + FichierARL + Format(Now, "yyyyMMddHHmmss"), True)
            Exit Sub
        End If



        ValeurChamp = "123456789012"
        Dim i = 1
        While SGD_LireChamp(NumeroSession, 31, i, 2, ValeurChamp, 12) = 0
            Dim G31C1 As String = "@@@"
            Dim G31C2 As String = "@@@@@@@@@@@@"
            Dim G31C3 As String = "@"
            Dim G31C4 As String = "@@@@@@@@@@@@@@"
            Dim G31C5 As String = "@@@@@@@@@@@@@@"
            Dim G31C6 As String = "@@@"
            Dim G31C7 As String = "@@@@@@@@@@@@"
            Dim G31C8 As String = "@"
            Dim G31C9 As String = "@@@@@@@@@@"
            Dim G31C10 As String = "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"

            TailleMax = 3
            SGD_LireChamp(NumeroSession, 31, i, 1, G31C1, TailleMax)
            G31C1 = Mid(G31C1, 1, TailleMax)

            TailleMax = 12
            SGD_LireChamp(NumeroSession, 31, i, 2, G31C2, TailleMax)
            G31C2 = Mid(G31C2, 1, TailleMax)

            TailleMax = 1
            SGD_LireChamp(NumeroSession, 31, i, 3, G31C3, TailleMax)
            G31C3 = Mid(G31C3, 1, TailleMax)

            TailleMax = 14
            SGD_LireChamp(NumeroSession, 31, i, 4, G31C4, TailleMax)
            G31C4 = Mid(G31C4, 1, TailleMax)

            TailleMax = 14
            SGD_LireChamp(NumeroSession, 31, i, 5, G31C5, TailleMax)
            G31C5 = Mid(G31C5, 1, TailleMax)

            TailleMax = 3
            SGD_LireChamp(NumeroSession, 31, i, 6, G31C6, TailleMax)
            G31C6 = Mid(G31C6, 1, TailleMax)

            TailleMax = 12
            SGD_LireChamp(NumeroSession, 31, i, 7, G31C7, TailleMax)
            G31C7 = Mid(G31C7, 1, TailleMax)

            TailleMax = 1
            SGD_LireChamp(NumeroSession, 31, i, 8, G31C8, TailleMax)
            G31C8 = Mid(G31C8, 1, TailleMax)

            TailleMax = 10
            SGD_LireChamp(NumeroSession, 31, i, 9, G31C9, TailleMax)
            G31C9 = Mid(G31C9, 1, TailleMax)

            TailleMax = 80
            SGD_LireChamp(NumeroSession, 31, i, 10, G31C10, TailleMax)
            G31C10 = Mid(G31C10, 1, TailleMax)

            Dim file_Lot As String = Dir(Config.LocalNetwork_ServerName & "\Factures\Lots\transmis\" + G31C6.ToString + ".*")
            If file_Lot <> "" Then
                If IsNumeric(G31C6) Then
                    Me.LotsTableAdapter.Update_ARL("ARL RECU", G31C1, G31C2, G31C3, G31C4, G31C5, G31C6, G31C7, G31C8, G31C9, G31C10, IdARL, G31C6, Nothing)
                    Impression_Borderau(G31C6, Nothing)
                Else
                    Me.LotsTableAdapter.Update_ARL("ARL RECU", G31C1, G31C2, G31C3, G31C4, G31C5, G31C6, G31C7, G31C8, G31C9, G31C10, IdARL, Nothing, G31C6)
                    Impression_Borderau(Nothing, G31C6)
                End If
                My.Computer.FileSystem.MoveFile(Config.LocalNetwork_ServerName & "\Factures\Lots\transmis\" + file_Lot, Config.LocalNetwork_ServerName & "\Factures\Lots\traités\" + file_Lot, True)
            Else
                Dim mydatatable As DataTable
                Dim Index_FichierPieceJointe As Integer = 0
                mydatatable = Me.ARLTableAdapter.GetData
                For c = 0 To mydatatable.Columns.Count - 1
                    If mydatatable.Columns.Item(c).ColumnName = "FichierPieceJointe" Then
                        Index_FichierPieceJointe = c
                    End If
                Next
                Dim myfile As String = Config.LocalNetwork_ServerName & "\Factures\ARL\" + Format(Now, "yyyyMMddHHmmss") + "_ARL_Non_lié.txt"
                My.Computer.FileSystem.WriteAllText(myfile, Chr(10) + "------------------------------------------------------------------------------", True)
                For r = 0 To mydatatable.Rows.Count - 1

                    If mydatatable(r).Item(Index_FichierPieceJointe).ToString + ".arl" = FichierARL Then

                        For c = 0 To mydatatable.Columns.Count - 1
                            If mydatatable(r).Item(c).ToString <> "" Then
                                My.Computer.FileSystem.WriteAllText(myfile, Chr(10) + _
                                                           mydatatable.Columns(c).ColumnName + ": " + mydatatable(r).Item(c).ToString, True)
                            End If
                        Next
                    End If
                Next
                My.Computer.FileSystem.WriteAllText(myfile, Chr(10) + "N° de l’ARL: " + G31C1 + Chr(10) + "Date de création de l’ARL: " + G31C2 + _
                                                    Chr(10) + "Type du N° de l’émetteur de lot: " + G31C3 + Chr(10) + "Emetteur du lot: " + G31C4 + _
                                                    Chr(10) + "N° du destinataire: " + G31C5 + Chr(10) + "Référence du lot: " + G31C6 + Chr(10) _
                                                    + "Date du lot: " + G31C7 + Chr(10) + "Type du code de traitement du lot: " + G31C8 + Chr(10) _
                                                    + "Code de traitement du lot: " + G31C9 + Chr(10) + "Libellé du traitement du lot: " + G31C10, True)
                MyMsg_Box.Presentation("Officine", "RECEPTION D'ARL NON LIÉ" + Chr(10) + "voire dans dossier des ARL", False, "", False, "", True, "OK")
                MyMsg_Box.ShowDialog()
            End If
            i = i + 1
        End While
        My.Computer.FileSystem.MoveFile(Config.LocalNetwork_ServerName & "\Factures\ARL\" + FichierARL, Config.LocalNetwork_ServerName & "\Factures\ARL\Traités\" + FichierARL, True)


    End Sub
#End Region

#Region "SERVICE/REJET"
    Private Sub Traitement_REJET()
        Dim FichierREJET As String = Dir(Config.LocalNetwork_ServerName & "\Factures\BAL\SERVICE\*.*")
        Dim coderejet As String = ""

        While FichierREJET <> ""
            If InStr(FichierREJET, "REJET_") = 1 Then
                Dim RejetDataTable As DataTable = Me.Service_RejetTableAdapter.GetDataBy_Num(Val(Mid(FichierREJET, InStr(FichierREJET, "@") + 1)))
                Dim In_Reply_To_Index As Integer
                For c = 0 To RejetDataTable.Columns.Count - 1
                    If RejetDataTable.Columns.Item(c).ColumnName = "In_Reply_To" Then
                        In_Reply_To_Index = c
                    ElseIf RejetDataTable.Columns.Item(c).ColumnName = "Subject" Then
                        coderejet = Mid(RejetDataTable(0).Item(c).ToString, InStrRev(RejetDataTable(0).Item(c).ToString, "/") + 1)
                    End If
                Next
                Dim NumFichierRejeté As String = Me.SmtpTableAdapter1.Select_NumFichier_By_Subject(RejetDataTable(0).Item(In_Reply_To_Index).ToString)
                If InStr(NumFichierRejeté, ".") <> 0 Then
                    NumFichierRejeté = Mid(NumFichierRejeté, 1, InStr(NumFichierRejeté, ".") - 1)
                End If
                Dim LotsDataTable As DataTable = Me.LotsTableAdapter.GetDataByFichierLots(NumFichierRejeté)
                Dim Référence_Index, Référence_DRE_Index As Integer
                For c = 0 To LotsDataTable.Columns.Count - 1
                    If LotsDataTable.Columns.Item(c).ColumnName = "Référence" Then
                        Référence_Index = c
                    ElseIf LotsDataTable.Columns.Item(c).ColumnName = "Référence_DRE" Then
                        Référence_DRE_Index = c
                    End If
                Next
                For r = 0 To LotsDataTable.Rows.Count - 1
                    If IsNumeric(LotsDataTable(r).Item(Référence_Index)) Then
                        Me.LotsTableAdapter.Update_Etat(Mid(FichierREJET, 1, InStr(FichierREJET, "@") - 1), Val(LotsDataTable(r).Item(Référence_Index).ToString), Nothing)
                        Me.LotsTableAdapter.Update_ARLG31C9(coderejet, Val(LotsDataTable(r).Item(Référence_Index).ToString), Nothing)
                    Else
                        Me.LotsTableAdapter.Update_Etat(Mid(FichierREJET, 1, InStr(FichierREJET, "@") - 1), Nothing, LotsDataTable(r).Item(Référence_DRE_Index).ToString)
                        Me.LotsTableAdapter.Update_ARLG31C9(coderejet, Nothing, LotsDataTable(r).Item(Référence_DRE_Index).ToString)
                    End If
                Next
            End If
            My.Computer.FileSystem.MoveFile(Config.LocalNetwork_ServerName & "\Factures\BAL\SERVICE\" + FichierREJET, Config.LocalNetwork_ServerName & "\Factures\BAL\SERVICE\Traités\" + FichierREJET, True)
            FichierREJET = Dir()
        End While
    End Sub

#End Region

#Region "RSP"
    Private Sub Traitement_RSP()
        Dim FichierRSP As String = Dir(Config.LocalNetwork_ServerName & "\Factures\RSP\*.rsp")
        While FichierRSP <> ""
            Dim string_RSP As String = My.Computer.FileSystem.ReadAllText(Config.LocalNetwork_ServerName & "\Factures\RSP\" + FichierRSP)
            Dim ligne_RSP As String
            Dim numLot As String = ""
            Dim numFacture As String = ""
            Dim update As Boolean = False
            Dim date_virement As String = ""
            Dim Libellé_Virement_1 As String = ""
            Dim Libellé_Virement_2 As String = ""
            Dim Org_Payeur As String = ""
            Dim Org_emetteur As String = ""
            Dim num_destinataire As String = ""
            While InStr(string_RSP, "@") <> 0
                ligne_RSP = Mid(string_RSP, 1, InStr(string_RSP, "@"))



                '-----------------------------------------------------------
                'toutes normes

                If InStr(ligne_RSP, "000") = 1 Then
                    Select Case Mid(ligne_RSP, 4, 2)
                        Case "CS"
                            Org_emetteur = Mid(ligne_RSP, 6, 5)
                        Case "OC"
                            Org_emetteur = Mid(ligne_RSP, 6, 10)
                        Case Else
                            Org_emetteur = Mid(ligne_RSP, 12, 9)
                            num_destinataire = Mid(ligne_RSP, 28, 14)
                    End Select

                    '-----------------------------------------------------------
                    'norme 580
                ElseIf InStr(ligne_RSP, "102") = 1 Then 'norme 580
                    numFacture = Mid(ligne_RSP, 6, 9)
                    numLot = Mid(ligne_RSP, 21, 3)

                ElseIf InStr(ligne_RSP, "071") = 1 Then 'norme 580
                    date_virement = Mid(ligne_RSP, 6, 6)
                    Libellé_Virement_1 = Trim(Mid(ligne_RSP, 12, 32))
                    Libellé_Virement_2 = Trim(Mid(ligne_RSP, 44, 32))
                    Org_Payeur = Mid(ligne_RSP, 76, 10)

                ElseIf InStr(ligne_RSP, "198") = 1 And Val(Mid(ligne_RSP, 6, 8)) <> 0 Then 'norme 580
                    Me.RSP_PaiementsTableAdapter.Insert(date_virement, Libellé_Virement_1, Libellé_Virement_2, Org_Payeur, "AMO", Mid(ligne_RSP, 6, 8), _
                                                        Mid(ligne_RSP, 14, 1), Mid(ligne_RSP, 15, 8), numFacture, numLot, FichierRSP.ToString, Org_emetteur, num_destinataire)

                ElseIf InStr(ligne_RSP, "199") = 1 And Val(Mid(ligne_RSP, 6, 8)) <> 0 Then 'norme 580
                    Me.RSP_PaiementsTableAdapter.Insert(date_virement, Libellé_Virement_1, Libellé_Virement_2, Org_Payeur, "AMC", Mid(ligne_RSP, 6, 8), _
                                                        Mid(ligne_RSP, 14, 1), Mid(ligne_RSP, 15, 8), numFacture, numLot, FichierRSP.ToString, Org_emetteur, num_destinataire)

                ElseIf InStr(ligne_RSP, "294") = 1 Then 'norme 580
                    Me.RSP_LIGNE_REJETTableAdapter.Insert(Me.RSP_LIGNE_REJETTableAdapter.Select_Max_num + 1, numFacture, numLot, Mid(ligne_RSP, 6, 10), Mid(ligne_RSP, 16, 80), _
                                                      Mid(ligne_RSP, 96, 1), Mid(ligne_RSP, 97, 1), Mid(ligne_RSP, 98, 5), Mid(ligne_RSP, 103, 6), Mid(ligne_RSP, 109, 9), _
                                                      Mid(ligne_RSP, 118, 3), Mid(ligne_RSP, 121, 2), Mid(ligne_RSP, 123, 30), False, Org_emetteur, num_destinataire)
                    '-----------------------------------------------------------
                    'anciennes normes (576 et 900)

                ElseIf InStr(ligne_RSP, "070") = 1 Then
                    date_virement = Mid(ligne_RSP, 6, 6)
                ElseIf InStr(ligne_RSP, "080") = 1 Then
                    numLot = Mid(ligne_RSP, 12, 3)
                ElseIf InStr(ligne_RSP, "100") = 1 Then
                    numLot = Mid(ligne_RSP, 6, 9)
                ElseIf InStr(ligne_RSP, "212") = 1 Then
                    Me.RSP_PaiementsTableAdapter.Insert(date_virement, Libellé_Virement_1, Libellé_Virement_2, Org_Payeur, "", "", "P", Mid(ligne_RSP, 53, 8), numFacture, numLot, _
                                                        FichierRSP.ToString, Org_emetteur, num_destinataire)
                ElseIf InStr(ligne_RSP, "290") = 1 Then 'rejet
                    Me.RSP_LIGNE_REJETTableAdapter.Insert(Me.RSP_LIGNE_REJETTableAdapter.Select_Max_num + 1, numFacture, numLot, Mid(ligne_RSP, 8, 10), Mid(ligne_RSP, 18, 80), "", "", "", "", "", _
                                                          "", "", "", False, Org_emetteur, num_destinataire)

                    '-----------------------------------------------------------
                End If
                string_RSP = Mid(string_RSP, InStr(string_RSP, "@") + 1)
            End While
            My.Computer.FileSystem.MoveFile(Config.LocalNetwork_ServerName & "\Factures\RSP\" + FichierRSP, Config.LocalNetwork_ServerName & "\Factures\RSP\Traités\" + FichierRSP, True)
            FichierRSP = Dir()
        End While

        Affiche_Rejets_Paiement(DataGridView_Rejets_Paiements)

    End Sub

    Public Sub Affiche_Rejets_Paiement(ByVal dtgrdvw As Windows.Forms.DataGridView)
        dtgrdvw.Rows.Clear()
        Dim mydatatable = Me.RSP_LIGNE_REJETTableAdapter.GetDataBy_Acquitement(False, 0)
        If mydatatable.Rows.Count > 0 Then
            For r = 0 To mydatatable.Rows.Count - 1
                dtgrdvw.Rows.Add()
                dtgrdvw.Item(Rejets_Paiement_Num_facture.Index, r).Value = Trim(mydatatable(r).NumFacture)
                dtgrdvw.Item(Rejets_Paiement_Num_Lot.Index, r).Value = Trim(mydatatable(r).NumLot)
                dtgrdvw.Item(Rejets_Paiement_Codification.Index, r).Value = Trim(mydatatable(r).CODIFICATION)
                dtgrdvw.Item(Rejets_Paiement_Libellé.Index, r).Value = Trim(mydatatable(r).LIBELLE)
                dtgrdvw.Item(Rejets_Paiement_Niveau.Index, r).Value = Trim(mydatatable(r).NIVEAU)
                dtgrdvw.Item(Rejets_Paiement_Part_Concernée.Index, r).Value = Trim(mydatatable(r).PART_CONCERNE)
                dtgrdvw.Item(Rejets_Paiement_Nature_Prestation.Index, r).Value = Trim(mydatatable(r).NATURE_DE_PRESTATION)
                dtgrdvw.Item(Rejets_Paiement_Date_soins.Index, r).Value = Trim(mydatatable(r).DATE_DES_SOINS)
                dtgrdvw.Item(Rejets_Paiement_Num_Executant.Index, r).Value = Trim(mydatatable(r)._N__EXECUTANT)
                dtgrdvw.Item(Rejets_Paiement_Num_Ligne.Index, r).Value = Trim(mydatatable(r)._N__DE_LIGNE)
                dtgrdvw.Item(Rejets_Paiement_Rang.Index, r).Value = Trim(mydatatable(r).RANG_DU_REJET)
                dtgrdvw.Item(Rejets_Paiement_Info_Compl.Index, r).Value = Trim(mydatatable(r).INFORMATION_COMPLEMENTAIRE)
            Next
        End If

    End Sub
#End Region

#Region "AR_P"
    Private Sub traitement_AR_P(ByVal From_ As String, ByVal To_ As String, ByVal Subject As String, ByVal InReplyTo As String)
        Dim num_ARP As Integer = Me.AR_PTableAdapter.Select_Max_Num + 1
        Me.AR_PTableAdapter.Insert(num_ARP, From_, To_, Subject, InReplyTo)
        Dim NumFichier As String = Me.SmtpTableAdapter1.Select_NumFichier_By_Subject(InReplyTo)
        Dim LotsDataTable = Me.LotsTableAdapter.GetDataBy_FichierLots(Mid(NumFichier, 1, InStr(NumFichier, ".") - 1))
        Dim Référence_Index, Référence_DRE_Index As Integer
        For c = 0 To LotsDataTable.Columns.Count - 1
            If LotsDataTable.Columns.Item(c).ColumnName = "Référence" Then
                Référence_Index = c
            ElseIf LotsDataTable.Columns.Item(c).ColumnName = "Référence_DRE" Then
                Référence_DRE_Index = c
            End If
        Next
        For r = 0 To LotsDataTable.Rows.Count - 1

            If IsNumeric(LotsDataTable(r).Item(Référence_Index)) Then
                If LotsDataTable(r).Etat <> "DEGRADE" Then
                    Me.LotsTableAdapter.Update_Etat("AR PROVISOIRE", Val(LotsDataTable(r).Item(Référence_Index).ToString), Nothing)
                End If
            Else
                Me.LotsTableAdapter.Update_Etat("AR PROVISOIRE", Nothing, LotsDataTable(r).Item(Référence_DRE_Index).ToString)

            End If
        Next
    End Sub
#End Region

#Region "POSTMASTER"
    Private Sub Postmaster()
        Dim file As String
        file = Dir(Config.POP3_RepBAL + "*.postmaster")
        While file <> ""
            Using sr As New StreamReader(Config.POP3_RepBAL + file)
                Dim line As String
                line = sr.ReadLine
                Dim subject As String = ""
                Dim Action As String = ""
                While Not line Is Nothing
                    If InStr(line, "Subject:") = 1 Then
                        line = Mid(line, 9)
                        While InStr(line, " ") = 1
                            line = Mid(line, 2)
                        End While
                        subject = line
                    ElseIf InStr(line, "Action:") = 1 Then
                        Action = line
                    End If
                    line = sr.ReadLine
                End While
                If InStr(UCase(Action), "FAILED") <> 0 Then
                    Dim FichierLots As String
                    FichierLots = Me.SmtpTableAdapter1.Select_NumFichier_By_Subject(subject)
                    If Not FichierLots Is Nothing Then
                        FichierLots = Mid(FichierLots, 1, InStr(FichierLots, ".") - 1)
                        Dim table_lots As DataTable = Me.LotsTableAdapter.GetDataByFichierLots(FichierLots)
                        Dim index_Référence, index_Référence_DRE As Integer
                        'Dim index_NombreTransmission As Integer
                        For c = 0 To table_lots.Columns.Count - 1
                            If table_lots.Columns.Item(c).ColumnName = "Référence" Then
                                index_Référence = c
                            ElseIf table_lots.Columns.Item(c).ColumnName = "Référence_DRE" Then
                                index_Référence_DRE = c
                                ' ElseIf table_lots.Columns.Item(c).ColumnName = "NombreTransmission" Then
                                ' index_NombreTransmission = c
                            End If
                        Next
                        For r = 0 To table_lots.Rows.Count - 1
                            ' Dim NombreTransmission = Val(table_lots(r).Item(index_NombreTransmission))
                            If Not IsDBNull(table_lots(r).Item(index_Référence)) Then
                                Me.LotsTableAdapter.Update_Etat("POSTMASTER", Val(table_lots(r).Item(index_Référence)), Nothing)
                                'Me.LotsTableAdapter.Update_NombreTransmission(NombreTransmission - 1, Val(table_lots(r).Item(index_Référence)), Nothing)
                            Else
                                Me.LotsTableAdapter.Update_Etat("POSTMASTER", 0, table_lots(r).Item(index_Référence_DRE))
                                'Me.LotsTableAdapter.Update_NombreTransmission(NombreTransmission - 1, Nothing, table_lots(r).Item(index_Référence_DRE))
                            End If
                        Next
                    End If
                End If
            End Using
            My.Computer.FileSystem.MoveFile(Config.POP3_RepBAL + file, Config.POP3_RepBAL + "POSTMASTER\" + file, True)
            file = Dir()

        End While
    End Sub
#End Region

#Region "IMPRESSION"
    Private Sub Impression_Borderau(ByVal Référence_Lot_FSE As Integer, ByVal Référence_Lot_DRE As String)
        Dim mydatatable As PharmaDataSet.LotsDataTable
        If Val(Référence_Lot_FSE) = 0 Then
            mydatatable = Me.LotsTableAdapter.GetDataByRéférence(Nothing, Référence_Lot_DRE)
        Else
            mydatatable = Me.LotsTableAdapter.GetDataByRéférence(Référence_Lot_FSE, Référence_Lot_DRE)
        End If
        '_________________________________________________________________________
        'controle 1 seul enregistrement Référence_Lot
        Select Case mydatatable.Rows.Count
            Case 0
                MyMsg_Box.Presentation("Officine", "Pas de lot ayant ce numéro: " + Référence_Lot_FSE.ToString + Référence_Lot_DRE, False, "", False, "", True, "OK")
                MyMsg_Box.ShowDialog()
                Exit Sub
            Case 1
            Case Else
                MyMsg_Box.Presentation("Officine", "INCOHERENCE, Plusieurs lots ayant ce numéro: " + Référence_Lot_FSE.ToString + Référence_Lot_DRE, False, "", False, "", True, "OK")
                MyMsg_Box.ShowDialog()
                Exit Sub
        End Select
        '_________________________________________________________________________
        drawstring = ""
        Dim coderégime As String = ""
        Dim G2C9 As String = "" 'N° d’identification de facturation du PS
        Dim Montant_Lot As Single = 0
        Dim Date_Lot As String = ""
        '_________________________________________________________________________
        For c = 0 To mydatatable.Columns.Count - 1
            Select Case mydatatable.Columns.Item(c).ColumnName
                Case "CRL"
                    coderégime = Mid(mydatatable(0).Item(c).ToString, 12, 2)
                Case "CRF"
                    G2C9 = Mid(mydatatable(0).Item(c).ToString, 8, 8)
                Case "Montant"
                    Montant_Lot = mydatatable(0).Item(c) / 100
                Case "ARLG31C7"
                    Date_Lot = mydatatable(0).Item(c).ToString
            End Select
        Next
        '_________________________________________________________________________
        drawstring = "Bordereau récapitulatif des ordonnances pour le régime " + TraductionCodeRégime(coderégime) + Chr(10) + Chr(10)
        drawstring = drawstring + "Emetteur: " + G2C9 + Chr(10)
        If Val(Référence_Lot_FSE) = 0 Then
            drawstring = drawstring + "Lot: " + Référence_Lot_DRE
        Else
            drawstring = drawstring + "Lot: " + Référence_Lot_FSE.ToString + Référence_Lot_DRE
        End If
        If Date_Lot <> "" Then
            drawstring = drawstring + "  transmis: " + Mid(Date_Lot, 7, 2) + "/" + Mid(Date_Lot, 5, 2) + "/" + Mid(Date_Lot, 1, 4) + Chr(10)
        Else
            drawstring = drawstring + "  Pas d'ARL reçu" + Chr(10)
        End If

        '_________________________________________________________________________
        Dim mydatatable2 As DataTable
        If Val(Référence_Lot_FSE) = 0 Then
            mydatatable2 = Me.FacturesTableAdapter1.GetDataBy_Ref_Lot(Nothing, "@@@@@@", Référence_Lot_DRE, mydatatable(0)._Date)
        Else
            mydatatable2 = Me.FacturesTableAdapter1.GetDataBy_Ref_Lot(Référence_Lot_FSE.ToString, mydatatable(0)._Date, Référence_Lot_DRE, mydatatable(0)._Date)
        End If
        If mydatatable2.Rows.Count = 0 Then
            MyMsg_Box.Presentation("Officine", "PAS DE FACTURES ASSOCIES", False, "", False, "", True, "OK")
            MyMsg_Box.ShowDialog()
            Exit Sub
        End If
        '_________________________________________________________________________
        Dim G1310C1 As String = ""
        Dim G1310C2 As String = ""
        Dim G1310C3 As String = ""
        For c = 0 To mydatatable2.Columns.Count - 1
            Select Case mydatatable2.Columns.Item(c).ColumnName
                Case "G1410C1"
                    Select Case mydatatable2(0).Item(c).ToString
                        Case "1", "4"
                            drawstring = drawstring + Chr(10) + "PAIEMENT À L'ASSURÉ"
                        Case Else
                            drawstring = drawstring + Chr(10) + "PAIEMENT AU P.S."
                    End Select
                Case "G1310C1"
                    G1310C1 = mydatatable2(0).Item(c).ToString
                Case "G1310C2"
                    G1310C2 = mydatatable2(0).Item(c).ToString
                Case "G1310C3"
                    G1310C3 = mydatatable2(0).Item(c).ToString
            End Select
        Next
        drawstring = drawstring + Chr(10) + "Destinataire: " + Me.AmoTableAdapter1.SelectLibellé(G1310C1, G1310C2, G1310C3) + " " + G1310C1 + " " + G1310C2 + " " + G1310C3
        '_________________________________________________________________________
        drawstring = drawstring + Chr(10) + "Nbre Factures: " + mydatatable2.Rows.Count.ToString
        Dim Total_facture As Single = 0
        Dim Total_facture_String As String = ""
        Dim Total_Amo As Single = 0
        Dim Total_Amo_String As String = ""
        '_________________________________________________________________________
        drawstring = drawstring + Chr(10) + Chr(10) + Chr(10) + "R NUM FACT  BENEFICIAIRE                                   DATENAIS  MOMTANT      AMO"
        For r = 0 To mydatatable2.Rows.Count - 1
            Dim Renouvellement As String = "."
            Dim num_facture As String = ""
            Dim NIR As String = ""
            Dim clé_NIR As String = ""
            Dim DateNaissance As String = ""
            Dim montant_facture As Single = 0
            Dim montant_facture_String As String = ""
            Dim participation_Amo_Facture As Single
            Dim participation_Amo_Facture_String As String = ""
            Dim Bénéficiaire_fact As String = ""

            '_________________________________________________________________________
            For c = 0 To mydatatable2.Columns.Count - 1
                Select Case mydatatable2.Columns.Item(c).ColumnName
                    Case "G1850C2"
                        If Val(mydatatable2(r).Item(c)) <> 0 Then
                            Renouvellement = "R "
                        End If
                    Case "Num"
                        num_facture = mydatatable2(r).Item(c).ToString
                        While num_facture.Length < 9
                            num_facture = "0" + num_facture
                        End While
                    Case "G1130C2"
                        NIR = mydatatable2(r).Item(c).ToString
                    Case "G1130C3"
                        clé_NIR = mydatatable2(r).Item(c).ToString
                    Case "Bénéficiaire"
                        Bénéficiaire_fact = mydatatable2(r).Item(c).ToString
                        If Bénéficiaire_fact.Length > 30 Then
                            Bénéficiaire_fact = Mid(Bénéficiaire_fact, 1, 30)
                        End If
                        While Bénéficiaire_fact.Length < 30
                            Bénéficiaire_fact = Bénéficiaire_fact & " "
                        End While
                    Case "G1130C4"
                        DateNaissance = Mid(mydatatable2(r).Item(c).ToString, 7, 2) + Mid(mydatatable2(r).Item(c).ToString, 5, 2) + Mid(mydatatable2(r).Item(c).ToString, 1, 4)
                    Case "G1910C2"
                        montant_facture = mydatatable2(r).Item(c) / 100
                        Total_facture = Total_facture + montant_facture
                        montant_facture_String = montant_facture.ToString
                        While montant_facture_String.Length < 8
                            montant_facture_String = " " & montant_facture_String
                        End While
                    Case "G1910C3"
                        participation_Amo_Facture = mydatatable2(r).Item(c) / 100
                        participation_Amo_Facture_String = participation_Amo_Facture.ToString
                        Total_Amo = Total_Amo + participation_Amo_Facture
                        While participation_Amo_Facture_String.Length < 8
                            participation_Amo_Facture_String = " " & participation_Amo_Facture_String
                        End While
                End Select
            Next
            drawstring = drawstring + Chr(10) + Renouvellement + " " + num_facture + " " + Bénéficiaire_fact + " " + NIR + clé_NIR + " " + DateNaissance + " " + montant_facture_String + " " + participation_Amo_Facture_String
        Next
        Total_facture_String = Total_facture.ToString
        While Total_facture_String.Length < 8
            Total_facture_String = " " & Total_facture_String
        End While
        Total_Amo_String = Total_Amo.ToString
        While Total_Amo_String.Length < 8
            Total_Amo_String = " " & Total_Amo_String
        End While
        drawstring = drawstring + Chr(10) + Chr(10) + "TOTAL: " + Total_facture_String + "     TOTAL RMBRSMENT AMO: " + Total_Amo_String
        PrintPreviewDialog1.Document = PrintDocument1
        PrintDialog1.Document = PrintDocument1
        If PrintDialog1.ShowDialog() = Windows.Forms.DialogResult.OK Then
            PrintPreviewDialog1.ShowDialog()
            If PrintPreviewDialog1.DialogResult = DialogResult.OK Then
                PrintDocument1.Print()
            End If
        End If

    End Sub

    Private Sub PrintDocument1_PrintPage(ByVal sender As System.Object, ByVal e As System.Drawing.Printing.PrintPageEventArgs) Handles PrintDocument1.PrintPage
        Dim drawFont As New Font("Courier New", 10)
        Dim drawBrush As New SolidBrush(Color.Black)
        e.Graphics.DrawString(drawstring, drawFont, drawBrush, 10, 10)
    End Sub

    Private Sub Button_Impression_Borderau_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button_Impression_Borderau.Click
        Dim RefLot = InputBox("Réf lot?")
        If IsNumeric(RefLot) Then
            Impression_Borderau(RefLot, Nothing)
        Else
            Impression_Borderau(Nothing, UCase(RefLot))
        End If

    End Sub
#End Region


    Private Sub DREDAnullationToolStripMenuItem_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles DREDAnullationToolStripMenuItem.Click

        Dim NumDRE As String = InputBox("Numéro de la facture pour la DRE à annuler?")
        Dim datatable = Me.FacturesTableAdapter1.GetFactureDataByNum1(NumDRE)

        If datatable.Rows.Count = 0 Then
            MyMsg_Box.Presentation("Officine", "Pas de facture avec ce numéro", False, "", False, "", True, "OK")
            MyMsg_Box.ShowDialog()
            Exit Sub
        End If

        If datatable.Rows.Count > 1 Then
            MyMsg_Box.Presentation("Officine", "ANOMALIE:" + Chr(10) + "Plusieurs factures avec ce numéro", False, "", False, "", True, "OK")
            MyMsg_Box.ShowDialog()
            Exit Sub
        End If

        'Dim RefLot As String = Me.FacturesTableAdapter1.GetFactureDataByNum(NumDRE).Item(0).Num_Lot_DRE.ToString
        Dim RefLot As String = datatable.Item(0).Num_Lot_DRE.ToString
        If RefLot = "" Then
            MyMsg_Box.Presentation("Officine", "Cette DRE n'a pas étée transmise, pas d'annullation possible.", False, "", False, "", True, "OK")
            MyMsg_Box.ShowDialog()
            Exit Sub
        End If

        Dim NbrTransmissions As Integer = Val(Me.LotsTableAdapter.GetDataByRéférence(Nothing, RefLot).Item(0).NombreTransmission)
        If NbrTransmissions = 0 Then
            MyMsg_Box.Presentation("Officine", "Cette DRE n'a pas étée transmise, pas d'annullation possible.", False, "", False, "", True, "OK")
            MyMsg_Box.ShowDialog()
            Exit Sub
        End If

        FichierTrace = "traces\Annulation_DRE_in.txt"
        Trace_Reset_compteur()

        SGD_LibererSession(NumeroSessionFacture)
        SGD_ReserverSession(20000, NumeroSessionFacture)

        '1110
        SGD_AjouterGroupe_Tracé(NumeroSessionFacture, 1110, Visu_API, FichierTrace)
        '1110-1
        SGD_AjouterChamp_Tracé(NumeroSessionFacture, NumDRE, Visu_API, FichierTrace)
        '1110-2
        SGD_AjouterChamp_Tracé(NumeroSessionFacture, "1", Visu_API, FichierTrace) '1 Normale (pas d'autre valeur dans dico des données)
        '1110-3
        SGD_AjouterChamp_Tracé(NumeroSessionFacture, datatable.Item(0).G1110C3.ToString, Visu_API, FichierTrace)
        '1110-4
        ValeurChamp = "@"
        TailleMax = 1
        SGD_LireChamp(NumeroSessionCPS, 2, Occurence_Grp2, 1, ValeurChamp, TailleMax)
        SGD_AjouterChamp_Tracé(NumeroSessionFacture, ValeurChamp, Visu_API, FichierTrace)
        CurrentFactureVitale.G1110C4 = ValeurChamp
        '1110-5
        SGD_AjouterChamp_Tracé(NumeroSessionFacture, "", Visu_API, FichierTrace)
        '1110-6
        SGD_AjouterChamp_Tracé(NumeroSessionFacture, "", Visu_API, FichierTrace)

        '1120
        COMPTOIR_MAIN.groupe1120(NumeroSessionFacture)

        '1130
        SGD_AjouterGroupe_Tracé(NumeroSessionFacture, 1130, Visu_API, FichierTrace)
        '1130-1
        SGD_AjouterChamp_Tracé(NumeroSessionFacture, datatable.Item(0).G1130C1.ToString, Visu_API, FichierTrace)
        '1130-2
        SGD_AjouterChamp_Tracé(NumeroSessionFacture, datatable.Item(0).G1130C2.ToString, Visu_API, FichierTrace)
        '1130-3
        SGD_AjouterChamp_Tracé(NumeroSessionFacture, datatable.Item(0).G1130C3.ToString, Visu_API, FichierTrace)
        '1130-4
        SGD_AjouterChamp_Tracé(NumeroSessionFacture, datatable.Item(0).G1130C4.ToString, Visu_API, FichierTrace)
        '1130-5
        SGD_AjouterChamp_Tracé(NumeroSessionFacture, datatable.Item(0).G1130C5.ToString, Visu_API, FichierTrace)
        '1130-6
        SGD_AjouterChamp_Tracé(NumeroSessionFacture, datatable.Item(0).G1130C6.ToString, Visu_API, FichierTrace)
        '1130-7
        SGD_AjouterChamp_Tracé(NumeroSessionFacture, datatable.Item(0).G1130C7.ToString, Visu_API, FichierTrace)
        '1130-8
        SGD_AjouterChamp_Tracé(NumeroSessionFacture, datatable.Item(0).G1130C8.ToString, Visu_API, FichierTrace)
        '1130-9
        SGD_AjouterChamp_Tracé(NumeroSessionFacture, "", Visu_API, FichierTrace)

        '1140
        COMPTOIR_MAIN.groupe1140(NumeroSessionFacture)

        '1160
        If datatable.Item(0).G1160C1.ToString <> "" Or datatable.Item(0).G1160C2.ToString <> "" Then
            SGD_AjouterGroupe_Tracé(NumeroSessionFacture, 1160, Visu_API, FichierTrace)
            '1160-1
            SGD_AjouterChamp_Tracé(NumeroSessionFacture, datatable.Item(0).G1160C1.ToString, Visu_API, FichierTrace)
            '1160-2
            SGD_AjouterChamp_Tracé(NumeroSessionFacture, datatable.Item(0).G1160C2.ToString, Visu_API, FichierTrace)
        End If

        '1211-1213-1214
        If datatable.Item(0).G1211C1.ToString <> "" Then
            SGD_AjouterGroupe_Tracé(NumeroSessionFacture, 1211, Visu_API, FichierTrace)
            SGD_AjouterChamp_Tracé(NumeroSessionFacture, datatable.Item(0).G1211C1.ToString, Visu_API, FichierTrace)
            SGD_AjouterChamp_Tracé(NumeroSessionFacture, datatable.Item(0).G1211C2.ToString, Visu_API, FichierTrace)
            SGD_AjouterChamp_Tracé(NumeroSessionFacture, datatable.Item(0).G1211C3.ToString, Visu_API, FichierTrace)
            SGD_AjouterChamp_Tracé(NumeroSessionFacture, datatable.Item(0).G1211C4.ToString, Visu_API, FichierTrace)
            SGD_AjouterChamp_Tracé(NumeroSessionFacture, datatable.Item(0).G1211C5.ToString, Visu_API, FichierTrace)
            SGD_AjouterChamp_Tracé(NumeroSessionFacture, datatable.Item(0).G1211C6.ToString, Visu_API, FichierTrace)
            SGD_AjouterChamp_Tracé(NumeroSessionFacture, datatable.Item(0).G1211C7.ToString, Visu_API, FichierTrace)
        ElseIf datatable.Item(0).G1213C1.ToString <> "" Then
            SGD_AjouterGroupe_Tracé(NumeroSessionFacture, 1213, Visu_API, FichierTrace)
            SGD_AjouterChamp_Tracé(NumeroSessionFacture, datatable.Item(0).G1213C1.ToString, Visu_API, FichierTrace)
            SGD_AjouterChamp_Tracé(NumeroSessionFacture, datatable.Item(0).G1213C2.ToString, Visu_API, FichierTrace)
            SGD_AjouterChamp_Tracé(NumeroSessionFacture, datatable.Item(0).G1213C3.ToString, Visu_API, FichierTrace)
            SGD_AjouterChamp_Tracé(NumeroSessionFacture, datatable.Item(0).G1213C4.ToString, Visu_API, FichierTrace)
            SGD_AjouterChamp_Tracé(NumeroSessionFacture, datatable.Item(0).G1213C5.ToString, Visu_API, FichierTrace)
            SGD_AjouterChamp_Tracé(NumeroSessionFacture, datatable.Item(0).G1213C6.ToString, Visu_API, FichierTrace)
            SGD_AjouterChamp_Tracé(NumeroSessionFacture, datatable.Item(0).G1213C7.ToString, Visu_API, FichierTrace)
            SGD_AjouterChamp_Tracé(NumeroSessionFacture, datatable.Item(0).G1213C8.ToString, Visu_API, FichierTrace)
        ElseIf datatable.Item(0).G1214C1.ToString <> "" Then
            SGD_AjouterGroupe_Tracé(NumeroSessionFacture, 1214, Visu_API, FichierTrace)
            SGD_AjouterChamp_Tracé(NumeroSessionFacture, datatable.Item(0).G1214C1.ToString, Visu_API, FichierTrace)
            SGD_AjouterChamp_Tracé(NumeroSessionFacture, datatable.Item(0).G1214C2.ToString, Visu_API, FichierTrace)
            SGD_AjouterChamp_Tracé(NumeroSessionFacture, datatable.Item(0).G1214C3.ToString, Visu_API, FichierTrace)
            SGD_AjouterChamp_Tracé(NumeroSessionFacture, datatable.Item(0).G1214C4.ToString, Visu_API, FichierTrace)
            SGD_AjouterChamp_Tracé(NumeroSessionFacture, datatable.Item(0).G1214C5.ToString, Visu_API, FichierTrace)
            SGD_AjouterChamp_Tracé(NumeroSessionFacture, datatable.Item(0).G1214C6.ToString, Visu_API, FichierTrace)
            SGD_AjouterChamp_Tracé(NumeroSessionFacture, datatable.Item(0).G1214C7.ToString, Visu_API, FichierTrace)
            SGD_AjouterChamp_Tracé(NumeroSessionFacture, datatable.Item(0).G1214C8.ToString, Visu_API, FichierTrace)
        End If

        '1230
        If datatable.Item(0).G1230C1.ToString <> "" Then
            SGD_AjouterGroupe_Tracé(NumeroSessionFacture, 1230, Visu_API, FichierTrace)
            SGD_AjouterChamp_Tracé(NumeroSessionFacture, datatable.Item(0).G1230C1.ToString, Visu_API, FichierTrace)
        End If

        '1310
        SGD_AjouterGroupe_Tracé(NumeroSessionFacture, 1310, Visu_API, FichierTrace)
        SGD_AjouterChamp_Tracé(NumeroSessionFacture, datatable.Item(0).G1310C1.ToString, Visu_API, FichierTrace)
        SGD_AjouterChamp_Tracé(NumeroSessionFacture, datatable.Item(0).G1310C2.ToString, Visu_API, FichierTrace)
        SGD_AjouterChamp_Tracé(NumeroSessionFacture, datatable.Item(0).G1310C3.ToString, Visu_API, FichierTrace)
        SGD_AjouterChamp_Tracé(NumeroSessionFacture, datatable.Item(0).G1310C4.ToString, Visu_API, FichierTrace)
        SGD_AjouterChamp_Tracé(NumeroSessionFacture, datatable.Item(0).G1310C5.ToString, Visu_API, FichierTrace)


        '1321
        SGD_AjouterGroupe_Tracé(NumeroSessionFacture, 1321, Visu_API, FichierTrace)
        SGD_AjouterChamp_Tracé(NumeroSessionFacture, datatable.Item(0).G1321C1.ToString, Visu_API, FichierTrace)
        SGD_AjouterChamp_Tracé(NumeroSessionFacture, datatable.Item(0).G1321C2.ToString, Visu_API, FichierTrace)
        SGD_AjouterChamp_Tracé(NumeroSessionFacture, datatable.Item(0).G1321C3.ToString, Visu_API, FichierTrace)
        SGD_AjouterChamp_Tracé(NumeroSessionFacture, datatable.Item(0).G1321C4.ToString, Visu_API, FichierTrace)
        SGD_AjouterChamp_Tracé(NumeroSessionFacture, Mid(datatable.Item(0).G1321C5.ToString, 1, 3) + "2", Visu_API, FichierTrace)
        SGD_AjouterChamp_Tracé(NumeroSessionFacture, datatable.Item(0).G1321C6.ToString, Visu_API, FichierTrace)
        SGD_AjouterChamp_Tracé(NumeroSessionFacture, datatable.Item(0).G1321C7.ToString, Visu_API, FichierTrace)
        SGD_AjouterChamp_Tracé(NumeroSessionFacture, datatable.Item(0).G1321C8.ToString, Visu_API, FichierTrace)
        SGD_AjouterChamp_Tracé(NumeroSessionFacture, datatable.Item(0).G1321C9.ToString, Visu_API, FichierTrace)
        SGD_AjouterChamp_Tracé(NumeroSessionFacture, datatable.Item(0).G1321C10.ToString, Visu_API, FichierTrace)
        SGD_AjouterChamp_Tracé(NumeroSessionFacture, datatable.Item(0).G1321C11.ToString, Visu_API, FichierTrace)
        SGD_AjouterChamp_Tracé(NumeroSessionFacture, datatable.Item(0).G1321C12.ToString, Visu_API, FichierTrace)
        SGD_AjouterChamp_Tracé(NumeroSessionFacture, "", Visu_API, FichierTrace)

        '1330
        SGD_AjouterGroupe_Tracé(NumeroSessionFacture, 1330, Visu_API, FichierTrace)
        SGD_AjouterChamp_Tracé(NumeroSessionFacture, datatable.Item(0).G1330C1.ToString, Visu_API, FichierTrace)
        SGD_AjouterChamp_Tracé(NumeroSessionFacture, datatable.Item(0).G1330C2.ToString, Visu_API, FichierTrace)
        SGD_AjouterChamp_Tracé(NumeroSessionFacture, "", Visu_API, FichierTrace)

        '1410
        SGD_AjouterGroupe_Tracé(NumeroSessionFacture, 1410, Visu_API, FichierTrace)
        SGD_AjouterChamp_Tracé(NumeroSessionFacture, datatable.Item(0).G1410C1.ToString, Visu_API, FichierTrace)
        SGD_AjouterChamp_Tracé(NumeroSessionFacture, "", Visu_API, FichierTrace)

        '151X
        If datatable.Item(0).G1512C1.ToString <> "" Then
            SGD_AjouterGroupe_Tracé(NumeroSessionFacture, 1512, Visu_API, FichierTrace)
            SGD_AjouterChamp_Tracé(NumeroSessionFacture, datatable.Item(0).G1512C1.ToString, Visu_API, FichierTrace)
        ElseIf datatable.Item(0).G1513C1.ToString <> "" Then
            SGD_AjouterGroupe_Tracé(NumeroSessionFacture, 1513, Visu_API, FichierTrace)
            SGD_AjouterChamp_Tracé(NumeroSessionFacture, datatable.Item(0).G1513C1.ToString, Visu_API, FichierTrace)
            SGD_AjouterChamp_Tracé(NumeroSessionFacture, datatable.Item(0).G1513C2.ToString, Visu_API, FichierTrace)
            SGD_AjouterChamp_Tracé(NumeroSessionFacture, datatable.Item(0).G1513C3.ToString, Visu_API, FichierTrace)
        ElseIf datatable.Item(0).G1514C1.ToString <> "" Then
            SGD_AjouterGroupe_Tracé(NumeroSessionFacture, 1513, Visu_API, FichierTrace)
            SGD_AjouterChamp_Tracé(NumeroSessionFacture, datatable.Item(0).G1514C1.ToString, Visu_API, FichierTrace)
            SGD_AjouterChamp_Tracé(NumeroSessionFacture, datatable.Item(0).G1514C2.ToString, Visu_API, FichierTrace)
            SGD_AjouterChamp_Tracé(NumeroSessionFacture, datatable.Item(0).G1514C3.ToString, Visu_API, FichierTrace)
            SGD_AjouterChamp_Tracé(NumeroSessionFacture, datatable.Item(0).G1514C4.ToString, Visu_API, FichierTrace)
        Else
            SGD_AjouterGroupe_Tracé(NumeroSessionFacture, 1511, Visu_API, FichierTrace)
            SGD_AjouterChamp_Tracé(NumeroSessionFacture, datatable.Item(0).G1511C1.ToString, Visu_API, FichierTrace)
            SGD_AjouterChamp_Tracé(NumeroSessionFacture, datatable.Item(0).G1511C2.ToString, Visu_API, FichierTrace)
        End If

        '1610
        Dim datatable2 = Me.Facture_LigneFactureTableAdapter1.GetDataByNumFacture(NumDRE)
        For i = 0 To datatable2.Rows.Count - 1
            If Val(datatable2.Item(i).G1610C1) = i + 1 Then
                SGD_AjouterGroupe_Tracé(NumeroSessionFacture, 1610, Visu_API, FichierTrace)
                SGD_AjouterChamp_Tracé(NumeroSessionFacture, datatable2.Item(0).G1610C1.ToString, Visu_API, FichierTrace)
                SGD_AjouterChamp_Tracé(NumeroSessionFacture, datatable2.Item(0).G1610C2.ToString, Visu_API, FichierTrace)
                SGD_AjouterChamp_Tracé(NumeroSessionFacture, datatable2.Item(0).G1610C3.ToString, Visu_API, FichierTrace)
                SGD_AjouterChamp_Tracé(NumeroSessionFacture, datatable2.Item(0).G1610C4.ToString, Visu_API, FichierTrace)
                SGD_AjouterChamp_Tracé(NumeroSessionFacture, datatable2.Item(0).G1610C5.ToString, Visu_API, FichierTrace)
                SGD_AjouterChamp_Tracé(NumeroSessionFacture, datatable2.Item(0).G1610C6.ToString, Visu_API, FichierTrace)
                SGD_AjouterChamp_Tracé(NumeroSessionFacture, datatable2.Item(0).G1610C7.ToString, Visu_API, FichierTrace)
                SGD_AjouterChamp_Tracé(NumeroSessionFacture, datatable2.Item(0).G1610C8.ToString, Visu_API, FichierTrace)
                SGD_AjouterChamp_Tracé(NumeroSessionFacture, datatable2.Item(0).G1610C9.ToString, Visu_API, FichierTrace)
                SGD_AjouterChamp_Tracé(NumeroSessionFacture, datatable2.Item(0).G1610C10.ToString, Visu_API, FichierTrace)
                SGD_AjouterChamp_Tracé(NumeroSessionFacture, datatable2.Item(0).G1610C11.ToString, Visu_API, FichierTrace)
                SGD_AjouterChamp_Tracé(NumeroSessionFacture, datatable2.Item(0).G1610C12.ToString, Visu_API, FichierTrace)
                SGD_AjouterChamp_Tracé(NumeroSessionFacture, datatable2.Item(0).G1610C12.ToString, Visu_API, FichierTrace)
                SGD_AjouterChamp_Tracé(NumeroSessionFacture, datatable2.Item(0).G1610C14.ToString, Visu_API, FichierTrace)
                SGD_AjouterChamp_Tracé(NumeroSessionFacture, datatable2.Item(0).G1610C15.ToString, Visu_API, FichierTrace)
                SGD_AjouterChamp_Tracé(NumeroSessionFacture, datatable2.Item(0).G1610C16.ToString, Visu_API, FichierTrace)
                SGD_AjouterGroupe_Tracé(NumeroSessionFacture, 1820, Visu_API, FichierTrace)
                SGD_AjouterChamp_Tracé(NumeroSessionFacture, datatable2.Item(0).G1610C1.ToString, Visu_API, FichierTrace)
                SGD_AjouterChamp_Tracé(NumeroSessionFacture, "0", Visu_API, FichierTrace)
            End If
        Next

        '1910
        SGD_AjouterGroupe_Tracé(NumeroSessionFacture, 1910, Visu_API, FichierTrace)
        SGD_AjouterChamp_Tracé(NumeroSessionFacture, datatable.Item(0).G1910C1.ToString, Visu_API, FichierTrace)
        SGD_AjouterChamp_Tracé(NumeroSessionFacture, datatable.Item(0).G1910C2.ToString, Visu_API, FichierTrace)
        SGD_AjouterChamp_Tracé(NumeroSessionFacture, datatable.Item(0).G1910C3.ToString, Visu_API, FichierTrace)
        SGD_AjouterChamp_Tracé(NumeroSessionFacture, datatable.Item(0).G1910C4.ToString, Visu_API, FichierTrace)
        SGD_AjouterChamp_Tracé(NumeroSessionFacture, datatable.Item(0).G1910C5.ToString, Visu_API, FichierTrace)
        SGD_AjouterChamp_Tracé(NumeroSessionFacture, datatable.Item(0).G1910C6.ToString, Visu_API, FichierTrace)

        Dim erreur As Integer

        If Config.Configuration_Desynchroniser = False Then
            erreur = SIS_FormaterFactures(NomRessourcePS, NomRessourceLecteur, "", "2", "1", NumeroSessionFacture)
        Else
            erreur = SIS_FormaterFactures(NomRessourcePS, NomRessourceLecteur, "", "2", "4", NumeroSessionFacture)
        End If
        If erreur <> 0 Then
            AfficheErreur(erreur)
            Exit Sub
        End If


        Dim NumFactureString As String = NumDRE.ToString
        While NumFactureString.Length < 9
            NumFactureString = "0" & NumFactureString
        End While
        Dim idposte = "P01"
        ValeurChamp = "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
        TailleMax = 71
        If Config.Configuration_Desynchroniser = False Then
            SGD_LireChamp(NumeroSessionFacture, 160, 1, 1, ValeurChamp, TailleMax) 'ValeurChamp=CRL de DRE
        Else
            SGD_LireChamp(NumeroSessionFacture, 161, 1, 1, ValeurChamp, TailleMax) 'ValeurChamp=CRL de DRE
        End If
        CurrentFactureVitale.CRLdeDRE = ValeurChamp
        If Config.Configuration_Desynchroniser = False Then
            Dim fichierDRE As String = Config.LocalNetwork_ServerName & "\factures\" + ValeurChamp + "@" + NumFactureString + "@" + idposte + "@" + Format(Now, "yyyyMMddHHmmss") + ".dre"
            SGD_LireChampFichier(NumeroSessionFacture, 160, 1, 2, fichierDRE)
        Else
            Dim fichierDRE As String = Config.LocalNetwork_ServerName & "\factures\desync\" + Mid(ValeurChamp, 1, TailleMax) + "@" + NumFactureString + "@" + idposte + "@" + Format(Now, "yyyyMMddHHmmss") + ".dre"
            SGD_LireChampFichier(NumeroSessionFacture, 161, 1, 2, fichierDRE)
        End If

        If Visu_API = True Then
            Technique_MAIN.LireSession_Out_VersFichier2(NumeroSessionFacture, Application.StartupPath + "\traces\Annulation_DRE_out.txt")
        End If
    End Sub

#Region "Transmis"
    Private Sub Affiche_Lots_erreur()
        Transmis_DataGridView.Rows.Clear()
        Dim mydatable As DataTable = Me.LotsTableAdapter.GetData_Lots_en_echec()
        For r = 0 To mydatable.Rows.Count - 1
            Transmis_DataGridView.Rows.Add()
            For c = 0 To mydatable.Columns.Count - 1
                Select Case mydatable.Columns.Item(c).ColumnName
                    Case "Référence", "Référence_DRE"
                        If Transmis_DataGridView.Item(Transmis_Référence.Index, r).Value = "" Then
                            Transmis_DataGridView.Item(Transmis_Référence.Index, r).Value = mydatable(r).Item(c).ToString
                            While Transmis_DataGridView.Item(Transmis_Référence.Index, r).Value.ToString.Length < 3
                                Transmis_DataGridView.Item(Transmis_Référence.Index, r).Value = "0" & Transmis_DataGridView.Item(Transmis_Référence.Index, r).Value
                            End While
                        End If
                    Case "NombreTransmission"
                        Transmis_DataGridView.Item(Transmis_NombreTransmission.Index, r).Value = mydatable(r).Item(c).ToString
                    Case "DateTransmission"
                        Transmis_DataGridView.Item(Transmis_DateTransmission.Index, r).Value = mydatable(r).Item(c).ToString
                    Case "NombreDeFSE"
                        Transmis_DataGridView.Item(Transmis_Nombre_Fact.Index, r).Value = mydatable(r).Item(c).ToString
                    Case "Montant"
                        Transmis_DataGridView.Item(Transmis_Remboursement.Index, r).Value = mydatable(r).Item(c).ToString
                    Case "Etat"
                        Transmis_DataGridView.Item(Transmis_Etat.Index, r).Value = mydatable(r).Item(c).ToString
                    Case "ARLG31C8"
                        Transmis_DataGridView.Item(Transmis_Type_cod_trait.Index, r).Value = mydatable(r).Item(c).ToString
                    Case "ARLG31C9"
                        Transmis_DataGridView.Item(Transmis_Code.Index, r).Value = mydatable(r).Item(c).ToString
                    Case "ARLG31C10"
                        Transmis_DataGridView.Item(Transmis_libellé.Index, r).Value = mydatable(r).Item(c).ToString
                End Select
            Next
        Next

        Transmis_DataGridView.Sort(Transmis_DateTransmission, System.ComponentModel.ListSortDirection.Descending)

        For r = 0 To Transmis_DataGridView.RowCount - 1

            If Transmis_DataGridView.Item(Transmis_Etat.Index, r).Value = "ATTENTE ARL" And ((Val(Format(Now, "yyyyMMddHHmmss")) - Val(Transmis_DataGridView.Item(Transmis_DateTransmission.Index, r).Value)) < 2000000) Then
                Transmis_DataGridView.Rows(r).Cells("Transmis_Action").Value = "En Cours "
                Transmis_DataGridView.Rows(r).DefaultCellStyle.BackColor = Color.Green

            ElseIf Transmis_DataGridView.Item(Transmis_Etat.Index, r).Value = "ATTENTE ARL" And BAL_relevée = False Then
                Transmis_DataGridView.Rows(r).Cells("Transmis_Action").Value = "En Cours (BAL non relevée) "
                Transmis_DataGridView.Rows(r).DefaultCellStyle.BackColor = Color.Green

            ElseIf Transmis_DataGridView.Item(Transmis_Etat.Index, r).Value = "ATTENTE ARL" And _
                Val(Transmis_DataGridView.Rows(r).Cells("Transmis_NombreTransmission").Value) < 2 And _
                (Val(Format(Now, "yyyyMMddHHmmss")) - Val(Transmis_DataGridView.Item(Transmis_DateTransmission.Index, r).Value) > 2000000) Then
                Transmis_DataGridView.Rows(r).Cells("Transmis_Action").Value = "Retransmettre"
                Transmis_DataGridView.Rows(r).DefaultCellStyle.BackColor = Color.Yellow

            ElseIf InStr(Transmis_DataGridView.Item(Transmis_Etat.Index, r).Value, "REJET_") <> 0 And _
              Val(Transmis_DataGridView.Rows(r).Cells("Transmis_NombreTransmission").Value) < 2 Then
                If InStr(Transmis_DataGridView.Item(Transmis_Code.Index, r).Value, "3") = 1 Then
                    Transmis_DataGridView.Rows(r).Cells("Transmis_Action").Value = "action"
                    Transmis_DataGridView.Rows(r).DefaultCellStyle.BackColor = Color.Orange
                Else
                    Transmis_DataGridView.Rows(r).Cells("Transmis_Action").Value = "Retransmettre"
                    Transmis_DataGridView.Rows(r).DefaultCellStyle.BackColor = Color.Yellow
                End If

            ElseIf Transmis_DataGridView.Item(Transmis_Etat.Index, r).Value = "POSTMASTER" And _
                   Val(Transmis_DataGridView.Rows(r).Cells("Transmis_NombreTransmission").Value) < 2 Then
                Transmis_DataGridView.Rows(r).Cells("Transmis_Action").Value = "Retransmettre"
                Transmis_DataGridView.Rows(r).DefaultCellStyle.BackColor = Color.Yellow

            ElseIf Transmis_DataGridView.Item(Transmis_Etat.Index, r).Value = "AR PROVISOIRE" Then
                If DateDiff(DateInterval.Day, Date.ParseExact(Transmis_DataGridView.Item(Transmis_DateTransmission.Index, r).Value, "yyyyMMddHHmmss", System.Globalization.CultureInfo.CurrentCulture), Now) > 15 Then
                    'If ((Val(Format(Now, "yyyyMMddHHmmss")) - Val(Transmis_DataGridView.Item(Transmis_DateTransmission.Index, r).Value)) > 15000000) Then
                    Transmis_DataGridView.Rows(r).Cells("Transmis_Action").Value = "traitement manuel"
                    Transmis_DataGridView.Rows(r).DefaultCellStyle.BackColor = Color.LightSkyBlue
                Else
                    Transmis_DataGridView.Rows(r).Cells("Transmis_Action").Value = "Attente"
                    Transmis_DataGridView.Rows(r).DefaultCellStyle.BackColor = Color.LightGray
                End If


            ElseIf Transmis_DataGridView.Item(Transmis_Etat.Index, r).Value = "A TRANSMETTRE" Then
                Transmis_DataGridView.Rows(r).Cells("Transmis_Action").Value = "remis en transmission"

            Else
                If Val(Transmis_DataGridView.Rows(r).Cells("Transmis_NombreTransmission").Value) < 2 Then
                    Transmis_DataGridView.Rows(r).Cells("Transmis_Action").Value = "action"
                    Transmis_DataGridView.Rows(r).DefaultCellStyle.BackColor = Color.Orange
                Else
                    Transmis_DataGridView.Rows(r).Cells("Transmis_Action").Value = "traitement manuel"
                    Transmis_DataGridView.Rows(r).DefaultCellStyle.BackColor = Color.LightSkyBlue
                End If

            End If

        Next
    End Sub
    Private Sub Affiche_Lots_aquittés()
        Transmis_DataGridView.Rows.Clear()
        Dim mydatable As DataTable = Me.LotsTableAdapter.GetData_Lots_aquittés(Val(Format(DateTimePicker_Aquittés.Value, "yyyyMMdd") + "000000"))
        For r = 0 To mydatable.Rows.Count - 1
            Transmis_DataGridView.Rows.Add()
            For c = 0 To mydatable.Columns.Count - 1
                Select Case mydatable.Columns.Item(c).ColumnName
                    Case "Référence", "Référence_DRE"
                        If Transmis_DataGridView.Item(Transmis_Référence.Index, r).Value = "" Then
                            Transmis_DataGridView.Item(Transmis_Référence.Index, r).Value = mydatable(r).Item(c).ToString
                            While Transmis_DataGridView.Item(Transmis_Référence.Index, r).Value.ToString.Length < 3
                                Transmis_DataGridView.Item(Transmis_Référence.Index, r).Value = "0" & Transmis_DataGridView.Item(Transmis_Référence.Index, r).Value
                            End While
                        End If
                    Case "NombreTransmission"
                        Transmis_DataGridView.Item(Transmis_NombreTransmission.Index, r).Value = mydatable(r).Item(c).ToString
                    Case "DateTransmission"
                        Transmis_DataGridView.Item(Transmis_DateTransmission.Index, r).Value = mydatable(r).Item(c).ToString
                    Case "NombreDeFSE"
                        Transmis_DataGridView.Item(Transmis_Nombre_Fact.Index, r).Value = mydatable(r).Item(c).ToString
                    Case "Montant"
                        Transmis_DataGridView.Item(Transmis_Remboursement.Index, r).Value = mydatable(r).Item(c).ToString
                    Case "Etat"
                        Transmis_DataGridView.Item(Transmis_Etat.Index, r).Value = mydatable(r).Item(c).ToString
                    Case "ARLG31C8"
                        Transmis_DataGridView.Item(Transmis_Type_cod_trait.Index, r).Value = mydatable(r).Item(c).ToString
                    Case "ARLG31C9"
                        Transmis_DataGridView.Item(Transmis_Code.Index, r).Value = mydatable(r).Item(c).ToString
                    Case "ARLG31C10"
                        Transmis_DataGridView.Item(Transmis_libellé.Index, r).Value = mydatable(r).Item(c).ToString
                End Select
            Next
        Next
        Transmis_DataGridView.Sort(Transmis_DateTransmission, System.ComponentModel.ListSortDirection.Descending)
        For r = 0 To Transmis_DataGridView.RowCount - 1
            If Transmis_DataGridView.Item(Transmis_Etat.Index, r).Value = "DEGRADE" And _
           (Val(Format(Now, "yyyyMMddHHmmss")) - Val(Transmis_DataGridView.Item(Transmis_DateTransmission.Index, r).Value) < 2000000) Then
                Transmis_DataGridView.Rows(r).Cells("Transmis_Action").Value = "48H"
                Transmis_DataGridView.Rows(r).DefaultCellStyle.BackColor = Color.LightGray
            Else
                Transmis_DataGridView.Rows(r).Cells("Transmis_Action").Value = "Acquitté"
                Transmis_DataGridView.Rows(r).DefaultCellStyle.BackColor = Color.LightGreen
            End If

        Next
    End Sub
    Private Sub Button_Transmis_Encours_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button_Transmis_Encours.Click
        Affiche_Lots_erreur()
        Button_Transmis_Aquittés.BackColor = Color.Gray
        Button_Transmis_Encours.BackColor = Color.LightGreen
    End Sub

    Private Sub Button_Transmis_Aquittés_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button_Transmis_Aquittés.Click
        Affiche_Lots_aquittés()
        Button_Transmis_Aquittés.BackColor = Color.LightGreen
        Button_Transmis_Encours.BackColor = Color.Gray
    End Sub

    Private Sub Transmis_DataGridView_CellContentClick(ByVal sender As System.Object, ByVal e As System.Windows.Forms.DataGridViewCellEventArgs) Handles Transmis_DataGridView.CellContentClick

        If Transmis_DataGridView.CurrentCell.ColumnIndex = Transmis_Action.Index Then
            Select Case Transmis_DataGridView.Rows(Transmis_DataGridView.CurrentRow.Index).Cells("Transmis_Action").Value
                Case "action"

                    If Config.is_local_client = True Then Exit Sub

                    'affichage seulement des bouttons possibles
                    Choix_Action_Lot_Erreur.Button_Reconstitution.Visible = False
                    Choix_Action_Lot_Erreur.Button_Manuel.Visible = False

                    Select Case Transmis_DataGridView.Rows(Transmis_DataGridView.CurrentRow.Index).Cells("Transmis_Code").Value
                        Case "5001", "5002"
                            Choix_Action_Lot_Erreur.Button_Manuel.Visible = True
                        Case Else
                            Choix_Action_Lot_Erreur.Button_Manuel.Visible = True
                            Choix_Action_Lot_Erreur.Button_Reconstitution.Visible = True
                    End Select




                    Select Case Choix_Action_Lot_Erreur.ShowDialog()
                        Case Windows.Forms.DialogResult.Cancel

                        Case Windows.Forms.DialogResult.OK 'reconstitution
                            Dim refLot = Transmis_DataGridView.Rows(Transmis_DataGridView.CurrentRow.Index).Cells("Transmis_Référence").Value
                            If IsNumeric(refLot) Then
                                Dim mydatatable As DataTable = Me.LotsTableAdapter.GetDataByRéférence(Val(refLot), Nothing)
                                Dim organisme_index As Integer
                                For c = 0 To mydatatable.Columns.Count - 1
                                    If mydatatable.Columns.Item(c).ColumnName = "Organisme" Then
                                        organisme_index = c
                                        Exit For
                                    End If
                                Next
                                Dim organisme As String = mydatatable(0).Item(organisme_index).ToString

                                If Config.OCT_UtilisationOCT = True Then
                                    Reconstitution_Lot(refLot, "", organisme, Transmis_DataGridView.Rows(Transmis_DataGridView.CurrentRow.Index).Cells("Transmis_Code").Value, _
                                                      Val(Mid(Transmis_DataGridView.Rows(Transmis_DataGridView.CurrentRow.Index).Cells("Transmis_libellé").Value, 8, 9)))
                                ElseIf InStr(Transmis_DataGridView.Rows(Transmis_DataGridView.CurrentRow.Index).Cells("Transmis_libellé").Value, "=") = 10 Then
                                    Reconstitution_Lot(refLot, "", organisme, Transmis_DataGridView.Rows(Transmis_DataGridView.CurrentRow.Index).Cells("Transmis_Code").Value, _
                                                       Val(Mid(Transmis_DataGridView.Rows(Transmis_DataGridView.CurrentRow.Index).Cells("Transmis_libellé").Value, 1, 9)))
                                Else
                                    Reconstitution_Lot(refLot, "", organisme, Transmis_DataGridView.Rows(Transmis_DataGridView.CurrentRow.Index).Cells("Transmis_Code").Value, 0)
                                End If
                            Else
                                Dim mydatatable As DataTable = Me.LotsTableAdapter.GetDataByRéférence(Nothing, refLot)
                                Dim organisme_index As Integer
                                For c = 0 To mydatatable.Columns.Count - 1
                                    If mydatatable.Columns.Item(c).ColumnName = "Organisme" Then
                                        organisme_index = c
                                        Exit For
                                    End If
                                Next
                                Dim organisme As String = mydatatable(0).Item(organisme_index).ToString
                                If InStr(Transmis_DataGridView.Rows(Transmis_DataGridView.CurrentRow.Index).Cells("Transmis_libellé").Value, "=") = 10 Then
                                    Reconstitution_Lot(0, refLot, organisme, Transmis_DataGridView.Rows(Transmis_DataGridView.CurrentRow.Index).Cells("Transmis_Code").Value, _
                                                      Val(Mid(Transmis_DataGridView.Rows(Transmis_DataGridView.CurrentRow.Index).Cells("Transmis_libellé").Value, 1, 9)))
                                Else
                                    Reconstitution_Lot(0, refLot, organisme, Transmis_DataGridView.Rows(Transmis_DataGridView.CurrentRow.Index).Cells("Transmis_Code").Value, 0)
                                End If
                            End If
                            If IsNumeric(refLot) Then
                                If My.Computer.FileSystem.FileExists(Config.LocalNetwork_ServerName & "\Factures\Lots\transmis\" + refLot.ToString + ".lotFSE") Then
                                    My.Computer.FileSystem.MoveFile(Config.LocalNetwork_ServerName & "\Factures\Lots\transmis\" + refLot.ToString + ".lotFSE", Config.LocalNetwork_ServerName & "\Factures\Lots\traités\" + refLot + ".lotFSE", True)
                                End If
                            Else
                                If My.Computer.FileSystem.FileExists(Config.LocalNetwork_ServerName & "\Factures\Lots\transmis\" + refLot + ".lotDRE") Then
                                    My.Computer.FileSystem.MoveFile(Config.LocalNetwork_ServerName & "\Factures\Lots\transmis\" + refLot + ".lotDRE", Config.LocalNetwork_ServerName & "\Factures\Lots\traités\" + refLot + ".lotDRE", True)
                                End If
                            End If


                        Case Windows.Forms.DialogResult.Yes 'traitement manuel
                            Dim refLot As String = Transmis_DataGridView.Rows(Transmis_DataGridView.CurrentRow.Index).Cells("Transmis_Référence").Value
                            If IsNumeric(refLot) Then
                                Traitement_Manuel_Lot(Val(refLot), "")
                                If My.Computer.FileSystem.FileExists(Config.LocalNetwork_ServerName & "\Factures\Lots\transmis\" + refLot.ToString + ".lotFSE") Then
                                    My.Computer.FileSystem.MoveFile(Config.LocalNetwork_ServerName & "\Factures\Lots\transmis\" + refLot.ToString + ".lotFSE", Config.LocalNetwork_ServerName & "\Factures\Lots\traités\" + refLot.ToString + ".lotFSE", True)
                                End If

                            Else
                                Traitement_Manuel_Lot(Nothing, refLot)
                                If My.Computer.FileSystem.FileExists(Config.LocalNetwork_ServerName & "\Factures\Lots\transmis\" + refLot + ".lotDRE") Then
                                    My.Computer.FileSystem.MoveFile(Config.LocalNetwork_ServerName & "\Factures\Lots\transmis\" + refLot + ".lotDRE", Config.LocalNetwork_ServerName & "\Factures\Lots\traités\" + refLot + ".lotDRE", True)
                                End If

                            End If


                        Case Windows.Forms.DialogResult.No 'retransmettre
                            If IsNumeric(Transmis_DataGridView.Rows(Transmis_DataGridView.CurrentRow.Index).Cells("Transmis_Référence").Value) Then
                                If Dir(Config.LocalNetwork_ServerName & "\Factures\Lots\traités\" + (Transmis_DataGridView.Rows(Transmis_DataGridView.CurrentRow.Index).Cells("Transmis_Référence").Value).ToString + ".lotFSE") <> "" Then
                                    My.Computer.FileSystem.MoveFile(Config.LocalNetwork_ServerName & "\Factures\Lots\traités\" + (Transmis_DataGridView.Rows(Transmis_DataGridView.CurrentRow.Index).Cells("Transmis_Référence").Value).ToString + ".lotFSE", Config.LocalNetwork_ServerName & "\Factures\Lots\" + (Transmis_DataGridView.Rows(Transmis_DataGridView.CurrentRow.Index).Cells("Transmis_Référence").Value).ToString + ".lotFSE", True)
                                    Me.LotsTableAdapter.Update_Etat("A TRANSMETTRE", Val(Transmis_DataGridView.Rows(Transmis_DataGridView.CurrentRow.Index).Cells("Transmis_Référence").Value), "")
                                ElseIf Dir(Config.LocalNetwork_ServerName & "\Factures\Lots\transmis\" + (Transmis_DataGridView.Rows(Transmis_DataGridView.CurrentRow.Index).Cells("Transmis_Référence").Value).ToString + ".lotFSE") <> "" Then
                                    My.Computer.FileSystem.MoveFile(Config.LocalNetwork_ServerName & "\Factures\Lots\transmis\" + (Transmis_DataGridView.Rows(Transmis_DataGridView.CurrentRow.Index).Cells("Transmis_Référence").Value).ToString + ".lotFSE", Config.LocalNetwork_ServerName & "\Factures\Lots\" + (Transmis_DataGridView.Rows(Transmis_DataGridView.CurrentRow.Index).Cells("Transmis_Référence").Value).ToString + ".lotFSE", True)
                                    Me.LotsTableAdapter.Update_Etat("A TRANSMETTRE", Val(Transmis_DataGridView.Rows(Transmis_DataGridView.CurrentRow.Index).Cells("Transmis_Référence").Value), "")
                                Else
                                    MyMsg_Box.Presentation("Officine", "Fichier Lot Introubable: " + (Transmis_DataGridView.Rows(Transmis_DataGridView.CurrentRow.Index).Cells("Transmis_Référence").Value).ToString + ".lotFSE", False, "", False, "", True, "OK")
                                    MyMsg_Box.ShowDialog()
                                End If
                            Else
                                If Dir(Config.LocalNetwork_ServerName & "\Factures\Lots\traités\" + (Transmis_DataGridView.Rows(Transmis_DataGridView.CurrentRow.Index).Cells("Transmis_Référence").Value).ToString + ".lotDRE") <> "" Then
                                    My.Computer.FileSystem.MoveFile(Config.LocalNetwork_ServerName & "\Factures\Lots\traités\" + (Transmis_DataGridView.Rows(Transmis_DataGridView.CurrentRow.Index).Cells("Transmis_Référence").Value).ToString + ".lotDRE", Config.LocalNetwork_ServerName & "\Factures\Lots\" + (Transmis_DataGridView.Rows(Transmis_DataGridView.CurrentRow.Index).Cells("Transmis_Référence").Value).ToString + ".lotDRE", True)
                                    Me.LotsTableAdapter.Update_Etat("A TRANSMETTRE", Nothing, Transmis_DataGridView.Rows(Transmis_DataGridView.CurrentRow.Index).Cells("Transmis_Référence").Value)
                                ElseIf Dir(Config.LocalNetwork_ServerName & "\Factures\Lots\transmis\" + (Transmis_DataGridView.Rows(Transmis_DataGridView.CurrentRow.Index).Cells("Transmis_Référence").Value).ToString + ".lotDRE") <> "" Then
                                    My.Computer.FileSystem.MoveFile(Config.LocalNetwork_ServerName & "\Factures\Lots\transmis\" + (Transmis_DataGridView.Rows(Transmis_DataGridView.CurrentRow.Index).Cells("Transmis_Référence").Value).ToString + ".lotDRE", Config.LocalNetwork_ServerName & "\Factures\Lots\" + (Transmis_DataGridView.Rows(Transmis_DataGridView.CurrentRow.Index).Cells("Transmis_Référence").Value).ToString + ".lotDRE", True)
                                    Me.LotsTableAdapter.Update_Etat("A TRANSMETTRE", Nothing, Transmis_DataGridView.Rows(Transmis_DataGridView.CurrentRow.Index).Cells("Transmis_Référence").Value)
                                Else
                                    MyMsg_Box.Presentation("Officine", "Fichier Lot Introubable: " + (Transmis_DataGridView.Rows(Transmis_DataGridView.CurrentRow.Index).Cells("Transmis_Référence").Value).ToString + ".lotFSE", False, "", False, "", True, "OK")
                                    MyMsg_Box.ShowDialog()
                                End If

                            End If
                    End Select

                Case "traitement manuel"
                    Dim refLot = Transmis_DataGridView.Rows(Transmis_DataGridView.CurrentRow.Index).Cells("Transmis_Référence").Value
                    If IsNumeric(refLot) Then
                        Traitement_Manuel_Lot(Val(refLot), "")
                        If My.Computer.FileSystem.FileExists(Config.LocalNetwork_ServerName & "\Factures\Lots\transmis\" + refLot.ToString + ".lotFSE") Then
                            My.Computer.FileSystem.MoveFile(Config.LocalNetwork_ServerName & "\Factures\Lots\transmis\" + refLot.ToString + ".lotFSE", Config.LocalNetwork_ServerName & "\Factures\Lots\traités\" + refLot + ".lotFSE", True)
                        End If
                    Else
                        Traitement_Manuel_Lot(Nothing, refLot)
                        If My.Computer.FileSystem.FileExists(Config.LocalNetwork_ServerName & "\Factures\Lots\transmis\" + refLot + ".lotDRE") Then
                            My.Computer.FileSystem.MoveFile(Config.LocalNetwork_ServerName & "\Factures\Lots\transmis\" + refLot + ".lotDRE", Config.LocalNetwork_ServerName & "\Factures\Lots\traités\" + refLot + ".lotDRE", True)
                        End If
                    End If

                Case "Retransmettre"
                    If IsNumeric(Transmis_DataGridView.Rows(Transmis_DataGridView.CurrentRow.Index).Cells("Transmis_Référence").Value) Then
                        If Dir(Config.LocalNetwork_ServerName & "\Factures\Lots\traités\" + (Transmis_DataGridView.Rows(Transmis_DataGridView.CurrentRow.Index).Cells("Transmis_Référence").Value).ToString + ".lotFSE") <> "" Then
                            My.Computer.FileSystem.MoveFile(Config.LocalNetwork_ServerName & "\Factures\Lots\traités\" + (Transmis_DataGridView.Rows(Transmis_DataGridView.CurrentRow.Index).Cells("Transmis_Référence").Value).ToString + ".lotFSE", Config.LocalNetwork_ServerName & "\Factures\Lots\" + (Transmis_DataGridView.Rows(Transmis_DataGridView.CurrentRow.Index).Cells("Transmis_Référence").Value).ToString + ".lotFSE", True)
                            Me.LotsTableAdapter.Update_Etat("A TRANSMETTRE", Val(Transmis_DataGridView.Rows(Transmis_DataGridView.CurrentRow.Index).Cells("Transmis_Référence").Value), "")
                        ElseIf Dir(Config.LocalNetwork_ServerName & "\Factures\Lots\transmis\" + (Transmis_DataGridView.Rows(Transmis_DataGridView.CurrentRow.Index).Cells("Transmis_Référence").Value).ToString + ".lotFSE") <> "" Then
                            My.Computer.FileSystem.MoveFile(Config.LocalNetwork_ServerName & "\Factures\Lots\transmis\" + (Transmis_DataGridView.Rows(Transmis_DataGridView.CurrentRow.Index).Cells("Transmis_Référence").Value).ToString + ".lotFSE", Config.LocalNetwork_ServerName & "\Factures\Lots\" + (Transmis_DataGridView.Rows(Transmis_DataGridView.CurrentRow.Index).Cells("Transmis_Référence").Value).ToString + ".lotFSE", True)
                            Me.LotsTableAdapter.Update_Etat("A TRANSMETTRE", Val(Transmis_DataGridView.Rows(Transmis_DataGridView.CurrentRow.Index).Cells("Transmis_Référence").Value), "")
                        Else
                            MyMsg_Box.Presentation("Officine", "Fichier Lot Introubable: " + (Transmis_DataGridView.Rows(Transmis_DataGridView.CurrentRow.Index).Cells("Transmis_Référence").Value).ToString + ".lotFSE", False, "", False, "", True, "OK")
                            MyMsg_Box.ShowDialog()
                        End If
                    Else
                        If Dir(Config.LocalNetwork_ServerName & "\Factures\Lots\traités\" + (Transmis_DataGridView.Rows(Transmis_DataGridView.CurrentRow.Index).Cells("Transmis_Référence").Value).ToString + ".lotDRE") <> "" Then
                            My.Computer.FileSystem.MoveFile(Config.LocalNetwork_ServerName & "\Factures\Lots\traités\" + (Transmis_DataGridView.Rows(Transmis_DataGridView.CurrentRow.Index).Cells("Transmis_Référence").Value).ToString + ".lotDRE", Config.LocalNetwork_ServerName & "\Factures\Lots\" + (Transmis_DataGridView.Rows(Transmis_DataGridView.CurrentRow.Index).Cells("Transmis_Référence").Value).ToString + ".lotDRE", True)
                            Me.LotsTableAdapter.Update_Etat("A TRANSMETTRE", Nothing, Transmis_DataGridView.Rows(Transmis_DataGridView.CurrentRow.Index).Cells("Transmis_Référence").Value)
                        ElseIf Dir(Config.LocalNetwork_ServerName & "\Factures\Lots\transmis\" + (Transmis_DataGridView.Rows(Transmis_DataGridView.CurrentRow.Index).Cells("Transmis_Référence").Value).ToString + ".lotDRE") <> "" Then
                            My.Computer.FileSystem.MoveFile(Config.LocalNetwork_ServerName & "\Factures\Lots\transmis\" + (Transmis_DataGridView.Rows(Transmis_DataGridView.CurrentRow.Index).Cells("Transmis_Référence").Value).ToString + ".lotDRE", Config.LocalNetwork_ServerName & "\Factures\Lots\" + (Transmis_DataGridView.Rows(Transmis_DataGridView.CurrentRow.Index).Cells("Transmis_Référence").Value).ToString + ".lotDRE", True)
                            Me.LotsTableAdapter.Update_Etat("A TRANSMETTRE", Nothing, Transmis_DataGridView.Rows(Transmis_DataGridView.CurrentRow.Index).Cells("Transmis_Référence").Value)
                        Else
                            MyMsg_Box.Presentation("Officine", "Fichier Lot Introubable: " + (Transmis_DataGridView.Rows(Transmis_DataGridView.CurrentRow.Index).Cells("Transmis_Référence").Value).ToString + ".lotFSE", False, "", False, "", True, "OK")
                            MyMsg_Box.ShowDialog()
                        End If

                    End If


            End Select

            Afficher_lots_à_transmettre()
            Afficher_lots_DRE_à_transmettre()
            Affiche_Lots_erreur()

        ElseIf Transmis_DataGridView.CurrentCell.ColumnIndex = Transmis_Etat.Index Then

            If InStr(Transmis_DataGridView.CurrentCell.Value, "REJET_") <> 0 Then
                Dim mydatatableLot As DataTable
                If IsNumeric(Transmis_DataGridView.Rows(Transmis_DataGridView.CurrentRow.Index).Cells("Transmis_Référence").Value) Then
                    mydatatableLot = Me.LotsTableAdapter.GetDataByRéférence(Val(Transmis_DataGridView.Rows(Transmis_DataGridView.CurrentRow.Index).Cells("Transmis_Référence").Value), Nothing)
                Else
                    mydatatableLot = Me.LotsTableAdapter.GetDataByRéférence(Nothing, Transmis_DataGridView.Rows(Transmis_DataGridView.CurrentRow.Index).Cells("Transmis_Référence").Value)
                End If
                Dim FichierLots As String = ""
                For c = 0 To mydatatableLot.Columns.Count - 1
                    If mydatatableLot.Columns(c).ColumnName = "FichierLots" Then
                        If IsNumeric(Transmis_DataGridView.Rows(Transmis_DataGridView.CurrentRow.Index).Cells("Transmis_Référence").Value) Then
                            FichierLots = mydatatableLot(0).Item(c).ToString + ".fichierFSE"
                        Else
                            FichierLots = mydatatableLot(0).Item(c).ToString + ".fichierDRE"
                        End If
                        Exit For
                    End If
                Next
                Dim mydatatableSMTP As DataTable = Me.SmtpTableAdapter1.GetDataBy_NomFichier(FichierLots)
                Dim subjectSMTP As String = ""
                For c = 0 To mydatatableSMTP.Columns.Count - 1
                    If mydatatableSMTP.Columns.Item(c).ColumnName = "Subject" Then
                        subjectSMTP = mydatatableSMTP(0).Item(c).ToString
                        Exit For
                    End If

                Next

                Dim mydatatable_Service_Rejet As DataTable
                mydatatable_Service_Rejet = Me.Service_RejetTableAdapter.GetDataBy_In_Reply_To(subjectSMTP)
                Dim FichierRejet As String = ""
                For c = 0 To mydatatable_Service_Rejet.Columns.Count - 1
                    If mydatatable_Service_Rejet.Columns.Item(c).ColumnName = "Fichier" Then
                        FichierRejet = mydatatable_Service_Rejet(0).Item(c).ToString
                        Exit For
                    End If
                Next


                Affiche_Retour.Visible = True
                Affiche_Retour.RichTextBox1.Clear()
                Using sr As New StreamReader(Config.LocalNetwork_ServerName & "\Factures\BAL\SERVICE\Traités\" + FichierRejet)
                    Dim line As String
                    line = sr.ReadLine
                    While line <> "" And line IsNot Nothing
                        Affiche_Retour.RichTextBox1.AppendText(line + Chr(10))
                        line = sr.ReadLine
                    End While

                End Using

            ElseIf Transmis_DataGridView.CurrentCell.Value = "ARL RECU" Then
                Affiche_Retour.Visible = True
                Affiche_Retour.RichTextBox1.Clear()
                Dim mydatatable As DataTable
                If IsNumeric(Transmis_DataGridView.Item(Transmis_Référence.Index, Transmis_DataGridView.CurrentRow.Index).Value) Then
                    mydatatable = Me.LotsTableAdapter.GetDataByRéférence(Val(Transmis_DataGridView.Item(Transmis_Référence.Index, Transmis_DataGridView.CurrentRow.Index).Value), Nothing)
                Else
                    mydatatable = Me.LotsTableAdapter.GetDataByRéférence(Nothing, Transmis_DataGridView.Item(Transmis_Référence.Index, Transmis_DataGridView.CurrentRow.Index).Value)
                End If
                Dim index_G31C1, index_G31C2, index_G31C3, index_G31C4, index_G31C5, index_G31C6, index_G31C7, index_G31C8, index_G31C9, index_G31C10 As Integer
                For c = 0 To mydatatable.Columns.Count - 1
                    If mydatatable.Columns.Item(c).ColumnName = "ARLG31C1" Then
                        index_G31C1 = c
                    ElseIf mydatatable.Columns.Item(c).ColumnName = "ARLG31C2" Then
                        index_G31C2 = c
                    ElseIf mydatatable.Columns.Item(c).ColumnName = "ARLG31C3" Then
                        index_G31C3 = c
                    ElseIf mydatatable.Columns.Item(c).ColumnName = "ARLG31C4" Then
                        index_G31C4 = c
                    ElseIf mydatatable.Columns.Item(c).ColumnName = "ARLG31C5" Then
                        index_G31C5 = c
                    ElseIf mydatatable.Columns.Item(c).ColumnName = "ARLG31C6" Then
                        index_G31C6 = c
                    ElseIf mydatatable.Columns.Item(c).ColumnName = "ARLG31C7" Then
                        index_G31C7 = c
                    ElseIf mydatatable.Columns.Item(c).ColumnName = "ARLG31C8" Then
                        index_G31C8 = c
                    ElseIf mydatatable.Columns.Item(c).ColumnName = "ARLG31C9" Then
                        index_G31C9 = c
                    ElseIf mydatatable.Columns.Item(c).ColumnName = "ARLG31C10" Then
                        index_G31C10 = c
                    End If
                Next
                Affiche_Retour.RichTextBox1.AppendText("N° de l’ARL: " + mydatatable(0).Item(index_G31C1).ToString + Chr(10) + _
                                        "Date de création de l’ARL: " + mydatatable(0).Item(index_G31C2).ToString + Chr(10) + _
                                        "Type du N° de l’émetteur de lot: " + mydatatable(0).Item(index_G31C3).ToString + Chr(10) + _
                                        "Emetteur du lot: " + mydatatable(0).Item(index_G31C4).ToString + Chr(10) + _
                                        "N° du destinataire: " + mydatatable(0).Item(index_G31C5).ToString + Chr(10) + _
                                        "Référence du lot: " + mydatatable(0).Item(index_G31C6).ToString + Chr(10) + _
                                        "Date du lot: " + mydatatable(0).Item(index_G31C7).ToString + Chr(10) + _
                                        "Type du code de traitement du lot: " + mydatatable(0).Item(index_G31C8).ToString + Chr(10) + _
                                        "Code de traitement du lot: " + mydatatable(0).Item(index_G31C9).ToString + Chr(10) + _
                                        "Libellé du traitement du lot: " + mydatatable(0).Item(index_G31C10).ToString + Chr(10))


            End If

        End If

    End Sub

    Private Sub Reconstitution_Lot(ByVal refLot_FSE As Integer, ByVal refLotDRE As String, ByVal organisme As String, ByVal code_erreur As String, ByVal NumFacture_erreur As Integer)

        Dim Current_CRL_FSE As String = ""
        Dim Current_CRL_DRE As String = ""
        Dim Current_datelot As String
        Dim Current_Total As Integer
        'table des factures constituant le lot en erreur-------------------------------------------
        Dim factures_datatable As PharmaDataSet.FacturesDataTable
        If refLotDRE = "" Then
            factures_datatable = Me.FacturesTableAdapter1.GetDataBy_Ref_Lot(refLot_FSE, Me.LotsTableAdapter.GetDataByRéférence(CDec(refLot_FSE), "@@@@@@").Item(0)._Date, Nothing, "@@@@@")
        Else
            factures_datatable = Me.FacturesTableAdapter1.GetDataBy_Ref_Lot(Nothing, "@@@@@", refLotDRE, Me.LotsTableAdapter.GetDataByRéférence("99999", refLotDRE).Item(0)._Date)
        End If
        '------------------------------------------------------------------------------------------
        'récupération index
        Dim Index_Num_Facture, Index_Total_AMO, Index_Total_AMC As Integer
        For c = 0 To factures_datatable.Columns.Count - 1
            If factures_datatable.Columns.Item(c).ColumnName = "Num" Then
                Index_Num_Facture = c
            ElseIf factures_datatable.Columns.Item(c).ColumnName = "G1910C3" Then
                Index_Total_AMO = c
            ElseIf factures_datatable.Columns.Item(c).ColumnName = "G1910C6" Then
                Index_Total_AMC = c
            End If

        Next

        '------------------------------------------------------------------------------------------
        'suppression si facture en erreur de la table et impression duplicata
        If code_erreur = "1002" Or code_erreur = "2004" Or code_erreur = "2007" Or code_erreur = "3002" Or (Config.OCT_UtilisationOCT = True) Then
            For r = 0 To factures_datatable.Rows.Count - 1
                If Val(factures_datatable(r).Item(Index_Num_Facture)) = Val(NumFacture_erreur) Then
                    CurrentFactureVitale.Clear(True)
                    For c = 0 To factures_datatable.Columns.Count - 1
                        If factures_datatable.Columns.Item(c).ColumnName = "G1110C1" Then
                            CurrentFactureVitale.G1110C1 = factures_datatable(r).Item(c)
                        ElseIf factures_datatable.Columns.Item(c).ColumnName = "G1110C3" Then
                            CurrentFactureVitale.G1110C3 = factures_datatable(r).Item(c)
                        ElseIf factures_datatable.Columns.Item(c).ColumnName = "IDPrescripteur" Then
                            CurrentFactureVitale.IDPrescripteur = factures_datatable(r).Item(c)
                        ElseIf factures_datatable.Columns.Item(c).ColumnName = "G1130C2" Then
                            CurrentFactureVitale.G1130C2 = factures_datatable(r).Item(c)
                        ElseIf factures_datatable.Columns.Item(c).ColumnName = "G1130C3" Then
                            CurrentFactureVitale.G1130C3 = factures_datatable(r).Item(c)
                        ElseIf factures_datatable.Columns.Item(c).ColumnName = "Assuré" Then
                            CurrentFactureVitale.Assuré = factures_datatable(r).Item(c)
                        ElseIf factures_datatable.Columns.Item(c).ColumnName = "Bénéficiaire" Then
                            CurrentFactureVitale.Bénéficiaire = factures_datatable(r).Item(c)
                        ElseIf factures_datatable.Columns.Item(c).ColumnName = "G1310C1" Then
                            CurrentFactureVitale.G1310C1 = factures_datatable(r).Item(c)
                        ElseIf factures_datatable.Columns.Item(c).ColumnName = "G1310C2" Then
                            CurrentFactureVitale.G1310C2 = factures_datatable(r).Item(c)
                        ElseIf factures_datatable.Columns.Item(c).ColumnName = "G1310C3" Then
                            CurrentFactureVitale.G1310C3 = factures_datatable(r).Item(c)
                        ElseIf factures_datatable.Columns.Item(c).ColumnName = "G1321C2" Then
                            CurrentFactureVitale.G1321C2 = factures_datatable(r).Item(c)
                        ElseIf factures_datatable.Columns.Item(c).ColumnName = "G1321C3" Then
                            CurrentFactureVitale.G1321C3 = factures_datatable(r).Item(c)
                        ElseIf factures_datatable.Columns.Item(c).ColumnName = "G1910C2" Then
                            CurrentFactureVitale.G1910C2 = factures_datatable(r).Item(c)
                        ElseIf factures_datatable.Columns.Item(c).ColumnName = "G1910C3" Then
                            CurrentFactureVitale.G1910C3 = factures_datatable(r).Item(c)
                        ElseIf factures_datatable.Columns.Item(c).ColumnName = "G1910C4" Then
                            CurrentFactureVitale.G1910C4 = factures_datatable(r).Item(c)
                        ElseIf factures_datatable.Columns.Item(c).ColumnName = "G1910C6" Then
                            CurrentFactureVitale.G1910C6 = factures_datatable(r).Item(c)
                        End If
                    Next
                    factures_datatable.Rows.Remove(factures_datatable.Rows.Item(r))
                    Exit For
                End If
            Next
            If factures_datatable.Rows.Count = 0 Then
                MyMsg_Box.Presentation("Officine", "Plus de facture à transmettre, opération abandonnée", False, "", False, "", True, "OK")
                MyMsg_Box.ShowDialog()
                Exit Sub
            End If
            '--------------------------------------------------------------------------------------
            'impression duplicata
            MyMsg_Box.Presentation("Officine", "Imprimer facture en erreur?", True, "OUI", True, "NON", False, "")
            If MyMsg_Box.ShowDialog() = Windows.Forms.DialogResult.Yes Then
                If refLotDRE = "" Then
                    VenteForm.Imprime_FSE("Impr_Duplicata_FSE")
                Else
                    VenteForm.Imprime_FSE("Impr_Duplicata_DRE")
                End If
            End If
        End If 'If code_erreur = "1002" Or code_erreur = "2004" Or code_erreur = "2007" Or code_erreur = "3002" Then
        '--------------------------------------------------------------------------------------

        '____________________________________________________________________________________________________
        'Trace
        Trace_Reset_compteur()
        If refLotDRE = "" Then
            FichierTrace = Mid(Application.ExecutablePath, 1, InStrRev(Application.ExecutablePath, "\")) + "traces\Formater_Lot_FSE_Reconstitution_in.txt"
        Else
            FichierTrace = Mid(Application.ExecutablePath, 1, InStrRev(Application.ExecutablePath, "\")) + "traces\Formater_Lot_DRE_Reconstitution_in.txt"
        End If
        '____________________________________________________________________________________________________
        SGD_ReserverSession(10000000, NumeroSessionLot)
        Dim RéférenceLotFSE_bdd As Integer
        Dim RéférenceLotFSE_SV As Integer
        Dim RéférenceLotDRE_bdd As String = ""
        Dim RéférenceLotDRE As String = ""
        Dim G8_G88_C4 As String = ""

        If refLotDRE = "" Then 'lot FSE
            'Groupe7
            SGD_AjouterGroupe_Tracé(NumeroSessionLot, 7, Visu_API, FichierTrace)

            'Champ1
            ValeurChamp = "12345678"
            SGD_LireChamp(NumeroSessionCPS, 2, Occurence_Grp2, 9, ValeurChamp, 8)
            SGD_AjouterChamp_Tracé(NumeroSessionLot, ValeurChamp, Visu_API, FichierTrace)

            'Champ2
            ValeurChamp = "1"
            SGD_LireChamp(NumeroSessionCPS, 2, Occurence_Grp2, 10, ValeurChamp, 1)
            SGD_AjouterChamp_Tracé(NumeroSessionLot, ValeurChamp, Visu_API, FichierTrace)

            'Groupe8
            SGD_AjouterGroupe_Tracé(NumeroSessionLot, 8, Visu_API, FichierTrace)

            'Champ1
            'SGD_AjouterChamp_Tracé(NumeroSessionLot, "TESTCNDA1409", Visu_API, FichierTrace)
            'SGD_AjouterChamp_Tracé(NumeroSessionLot, "TESTTOTO9999", Visu_API, FichierTrace)
            'SGD_AjouterChamp_Tracé(NumeroSessionLot, "GSNW1B000100", Visu_API, FichierTrace)'GSNW3B000110
            SGD_AjouterChamp_Tracé(NumeroSessionLot, "GSNW3B000110", Visu_API, FichierTrace)

            'Champ2
            If Config.Activer_Session_Remplacement = False Then
                ValeurChamp = "12345678"
                SGD_LireChamp(NumeroSessionCPS, 2, Occurence_Grp2, 9, ValeurChamp, 8)
            Else
                ValeurChamp = Config.Titulaire_Num_Id_Facturation
            End If
            SGD_AjouterChamp_Tracé(NumeroSessionLot, ValeurChamp, Visu_API, FichierTrace)


            'Champ3
            If Config.Activer_Session_Remplacement = False Then
                ValeurChamp = "1"
                SGD_LireChamp(NumeroSessionCPS, 2, Occurence_Grp2, 10, ValeurChamp, 1)
            Else
                ValeurChamp = Config.Titulaire_Cle_Num_Id_Facturation
            End If
            SGD_AjouterChamp_Tracé(NumeroSessionLot, ValeurChamp, Visu_API, FichierTrace)

            'Champ4
            If Config.Activer_Session_Remplacement = False Then
                ValeurChamp = "1"
                ValeurChamp = "1234567890123456789012345678901234567890"
                TailleMax = 40
                SGD_LireChamp(NumeroSessionCPS, 2, Occurence_Grp2, 8, ValeurChamp, TailleMax)
                If TailleMax = 0 Then
                    ValeurChamp = "123456789012345678901234567"
                    TailleMax = 27
                    SGD_LireChamp(NumeroSessionCPS, 1, 1, 6, ValeurChamp, TailleMax)
                End If
            Else
                ValeurChamp = Config.Titulaire_raison_sociale
            End If
            G8_G88_C4 = Mid(ValeurChamp, 1, TailleMax)
            SGD_AjouterChamp_Tracé(NumeroSessionLot, Mid(ValeurChamp, 1, TailleMax), Visu_API, FichierTrace)

            'Champ5
            If Config.Activer_Session_Remplacement = False Then
                ValeurChamp = "1"
                SGD_LireChamp(NumeroSessionCPS, 2, Occurence_Grp2, 1, ValeurChamp, 1)
                SGD_AjouterChamp_Tracé(NumeroSessionLot, ValeurChamp, Visu_API, FichierTrace)
            Else
                'SGD_AjouterChampBin_Tracé(NumeroSessionCPS, CByte(Config.Titulaire_Num_log_situ_fact), Visu_API, FichierTrace)
                'SGD_AjouterChampBin(NumeroSessionCPS, Config.Titulaire_Num_log_situ_fact, ) ', Visu_API, FichierTrace)
                'SGD_AjouterChamp_Tracé(NumeroSessionLot, CByte(Config.Titulaire_Num_log_situ_fact), Visu_API, FichierTrace)
                ValeurChamp = "1"
                SGD_LireChamp(NumeroSessionCPS, 2, Occurence_Grp2, 1, ValeurChamp, 1)
                SGD_AjouterChamp_Tracé(NumeroSessionLot, ValeurChamp, Visu_API, FichierTrace)
            End If

            'Champ6
            SGD_AjouterChamp_Tracé(NumeroSessionLot, Config.Type_émetteur_fichier, Visu_API, FichierTrace)

            'Champ7
            If Config.Type_émetteur_fichier = "SI" Then
                SGD_AjouterChamp_Tracé(NumeroSessionLot, Config.num_émetteur_fichier, Visu_API, FichierTrace)
            ElseIf Config.Activer_Session_Remplacement = False Then
                ValeurChamp = "12345678"
                SGD_LireChamp(NumeroSessionCPS, 2, Occurence_Grp2, 9, ValeurChamp, 8)
                Config.num_émetteur_fichier = ValeurChamp
                ValeurChamp = "1"
                SGD_LireChamp(NumeroSessionCPS, 2, Occurence_Grp2, 10, ValeurChamp, 1)
                Config.num_émetteur_fichier = "00000" + Config.num_émetteur_fichier + ValeurChamp
                SGD_AjouterChamp_Tracé(NumeroSessionLot, Config.num_émetteur_fichier, Visu_API, FichierTrace)
            Else
                Config.num_émetteur_fichier = "00000" + Config.Titulaire_Num_Id_Facturation + Config.Titulaire_Cle_Num_Id_Facturation
                SGD_AjouterChamp_Tracé(NumeroSessionLot, Config.num_émetteur_fichier, Visu_API, FichierTrace)
            End If

            'Champ8
            Current_datelot = Format(Now, "yyyyMMdd") + "0000"
            SGD_AjouterChamp_Tracé(NumeroSessionLot, Current_datelot, Visu_API, FichierTrace)

            'Champ9 Rang du lot
            SGD_AjouterChamp_Tracé(NumeroSessionLot, "7", Visu_API, FichierTrace)

            'champ10
            RéférenceLotFSE_bdd = Me.LotsTableAdapter.SELECT_max_Référence_bdd + 1
            If RéférenceLotFSE_bdd Mod 1000 = 0 Then
                RéférenceLotFSE_bdd = RéférenceLotFSE_bdd + 1
            End If
            RéférenceLotFSE_SV = RéférenceLotFSE_bdd Mod 1000

            SGD_AjouterChamp_Tracé(NumeroSessionLot, RéférenceLotFSE_SV.ToString, Visu_API, FichierTrace)

            'champ11
            SGD_AjouterChamp_Tracé(NumeroSessionLot, factures_datatable.Rows.Count.ToString, Visu_API, FichierTrace)

            'champ12,13,14
            ValeurChamp = "XXXXXXXXXXXXXX"
            SGD_LireChamp(NumeroSessionCPS, 2, Occurence_Grp2, 6, ValeurChamp, 14)
            If ValeurChamp <> "XXXXXXXXXXXXXX" Then
                ValeurChamp = "X"
                SGD_LireChamp(NumeroSessionCPS, 2, Occurence_Grp2, 5, ValeurChamp, 1)
                SGD_AjouterChamp_Tracé(NumeroSessionLot, ValeurChamp, Visu_API, FichierTrace)
                ValeurChamp = "XXXXXXXXXXXXXX"
                TailleMax = 14
                SGD_LireChamp(NumeroSessionCPS, 2, Occurence_Grp2, 6, ValeurChamp, TailleMax)
                SGD_AjouterChamp_Tracé(NumeroSessionLot, Mid(ValeurChamp, 1, TailleMax), Visu_API, FichierTrace)
                ValeurChamp = "X"
                SGD_LireChamp(NumeroSessionCPS, 2, Occurence_Grp2, 7, ValeurChamp, 1)
                SGD_AjouterChamp_Tracé(NumeroSessionLot, ValeurChamp, Visu_API, FichierTrace)
            Else
                SGD_AjouterChamp_Tracé(NumeroSessionLot, "9", Visu_API, FichierTrace)
                SGD_AjouterChamp_Tracé(NumeroSessionLot, "9", Visu_API, FichierTrace)
                ValeurChamp = "X"
                SGD_LireChamp(1, 2, 1, 10, ValeurChamp, 1)
                SGD_AjouterChamp_Tracé(NumeroSessionLot, ValeurChamp, Visu_API, FichierTrace)
            End If

            'groupe6
            SGD_AjouterGroupe_Tracé(NumeroSessionLot, 6, Visu_API, FichierTrace)
            Dim file_fse As String
            file_fse = Dir(Config.LocalNetwork_ServerName & "\Factures\Traitées\*.fse")
            Dim num_file_fse As String
            While file_fse <> ""
                num_file_fse = Mid(file_fse, InStr(file_fse, "@") + 1)
                num_file_fse = Mid(num_file_fse, 1, InStr(num_file_fse, "@") - 1)
                If Val(num_file_fse) = factures_datatable(0).Item(Index_Num_Facture) Then
                    Current_CRL_FSE = Mid(file_fse, 1, InStr(file_fse, "@") - 1)
                    Exit While
                End If
                file_fse = Dir()
            End While
            SGD_AjouterChamp_Tracé(NumeroSessionLot, Current_CRL_FSE, Visu_API, FichierTrace)


            'groupe9
            SGD_AjouterGroupe_Tracé(NumeroSessionLot, 9, Visu_API, FichierTrace)
            For r = 0 To factures_datatable.Rows.Count - 1
                Current_Total = Current_Total + factures_datatable(r).Item(Index_Total_AMO)
                file_fse = Dir(Config.LocalNetwork_ServerName & "\Factures\Traitées\*.fse")
                While file_fse <> ""
                    num_file_fse = Mid(file_fse, InStr(file_fse, "@") + 1)
                    num_file_fse = Mid(num_file_fse, 1, InStr(num_file_fse, "@") - 1)
                    If Val(num_file_fse) = factures_datatable(r).Item(Index_Num_Facture) Then
                        Dim bytes = My.Computer.FileSystem.ReadAllBytes(Config.LocalNetwork_ServerName & "\Factures\Traitées\" + file_fse)
                        My.Computer.FileSystem.WriteAllBytes(Config.LocalNetwork_ServerName & "\factures\lots\temp", bytes, True)
                        Me.FacturesTableAdapter1.Update_Num_Lot_FSE(RéférenceLotFSE_SV.ToString, Current_datelot, factures_datatable(r).Item(Index_Num_Facture))
                        Exit While
                    End If
                    file_fse = Dir()
                End While
            Next
            SGD_AjouterChampFichier(NumeroSessionLot, Config.LocalNetwork_ServerName & "\factures\lots\temp")
            Try
                My.Computer.FileSystem.DeleteFile(Config.LocalNetwork_ServerName & "\factures\lots\temp")
            Catch exep As Exception
                MyMsg_Box.Presentation("Officine", exep.ToString, False, "", False, "", True, "OK")
                MyMsg_Box.ShowDialog()

            End Try

        Else 'lot DRE
            'Groupe87
            SGD_AjouterGroupe_Tracé(NumeroSessionLot, 87, Visu_API, FichierTrace)

            'Champ1
            ValeurChamp = "12345678"
            SGD_LireChamp(NumeroSessionCPS, 2, Occurence_Grp2, 9, ValeurChamp, 8)
            SGD_AjouterChamp_Tracé(NumeroSessionLot, ValeurChamp, Visu_API, FichierTrace)
            'Champ2
            ValeurChamp = "1"
            SGD_LireChamp(NumeroSessionCPS, 2, Occurence_Grp2, 10, ValeurChamp, 1)
            SGD_AjouterChamp_Tracé(NumeroSessionLot, ValeurChamp, Visu_API, FichierTrace)

            'Groupe88
            SGD_AjouterGroupe_Tracé(NumeroSessionLot, 88, Visu_API, FichierTrace)

            'Champ1
            'SGD_AjouterChamp_Tracé(NumeroSessionLot, "TESTCNDA1409", Visu_API, FichierTrace)
            'SGD_AjouterChamp_Tracé(NumeroSessionLot, "TESTTOTO9999", Visu_API, FichierTrace)
            'SGD_AjouterChamp_Tracé(NumeroSessionLot, "GSNW1B000100", Visu_API, FichierTrace)
            SGD_AjouterChamp_Tracé(NumeroSessionLot, "GSNW3B000110", Visu_API, FichierTrace)

            'Champ2
            If Config.Activer_Session_Remplacement = False Then
                ValeurChamp = "12345678"
                SGD_LireChamp(NumeroSessionCPS, 2, Occurence_Grp2, 9, ValeurChamp, 8)
            Else
                ValeurChamp = Config.Titulaire_Num_Id_Facturation
            End If
            SGD_AjouterChamp_Tracé(NumeroSessionLot, ValeurChamp, Visu_API, FichierTrace)


            'Champ3
            If Config.Activer_Session_Remplacement = False Then
                ValeurChamp = "1"
                SGD_LireChamp(NumeroSessionCPS, 2, Occurence_Grp2, 10, ValeurChamp, 1)
            Else
                ValeurChamp = Config.Titulaire_Cle_Num_Id_Facturation
            End If
            SGD_AjouterChamp_Tracé(NumeroSessionLot, ValeurChamp, Visu_API, FichierTrace)

            'Champ4
            If Config.Activer_Session_Remplacement = False Then
                ValeurChamp = "1"
                ValeurChamp = "1234567890123456789012345678901234567890"
                TailleMax = 40
                SGD_LireChamp(NumeroSessionCPS, 2, Occurence_Grp2, 8, ValeurChamp, TailleMax)
                If TailleMax = 0 Then
                    ValeurChamp = "123456789012345678901234567"
                    TailleMax = 27
                    SGD_LireChamp(NumeroSessionCPS, 1, 1, 6, ValeurChamp, TailleMax)
                End If
            Else
                ValeurChamp = Config.Titulaire_raison_sociale
            End If
            G8_G88_C4 = Mid(ValeurChamp, 1, TailleMax)
            SGD_AjouterChamp_Tracé(NumeroSessionLot, Mid(ValeurChamp, 1, TailleMax), Visu_API, FichierTrace)

            'Champ5
            If Config.Activer_Session_Remplacement = False Then
                ValeurChamp = "1"
                SGD_LireChamp(NumeroSessionCPS, 2, Occurence_Grp2, 1, ValeurChamp, 1)
                SGD_AjouterChamp_Tracé(NumeroSessionLot, ValeurChamp, Visu_API, FichierTrace)
            Else
                'SGD_AjouterChampBin_Tracé(NumeroSessionCPS, CByte(Config.Titulaire_Num_log_situ_fact), Visu_API, FichierTrace)
                'SGD_AjouterChampBin(NumeroSessionCPS, Config.Titulaire_Num_log_situ_fact, ) ', Visu_API, FichierTrace)
                'SGD_AjouterChamp_Tracé(NumeroSessionLot, CByte(Config.Titulaire_Num_log_situ_fact), Visu_API, FichierTrace)
                ValeurChamp = "1"
                SGD_LireChamp(NumeroSessionCPS, 2, Occurence_Grp2, 1, ValeurChamp, 1)
                SGD_AjouterChamp_Tracé(NumeroSessionLot, ValeurChamp, Visu_API, FichierTrace)
            End If

            'Champ6
            SGD_AjouterChamp_Tracé(NumeroSessionLot, Config.Type_émetteur_fichier, Visu_API, FichierTrace)

            'Champ7
            If Config.Type_émetteur_fichier = "SI" Then
                SGD_AjouterChamp_Tracé(NumeroSessionLot, Config.num_émetteur_fichier, Visu_API, FichierTrace)
            ElseIf Config.Activer_Session_Remplacement = False Then
                ValeurChamp = "12345678"
                SGD_LireChamp(NumeroSessionCPS, 2, Occurence_Grp2, 9, ValeurChamp, 8)
                Config.num_émetteur_fichier = ValeurChamp
                ValeurChamp = "1"
                SGD_LireChamp(NumeroSessionCPS, 2, Occurence_Grp2, 10, ValeurChamp, 1)
                Config.num_émetteur_fichier = "00000" + Config.num_émetteur_fichier + ValeurChamp
                SGD_AjouterChamp_Tracé(NumeroSessionLot, Config.num_émetteur_fichier, Visu_API, FichierTrace)
            Else
                Config.num_émetteur_fichier = "00000" + Config.Titulaire_Num_Id_Facturation + Config.Titulaire_Cle_Num_Id_Facturation
                SGD_AjouterChamp_Tracé(NumeroSessionLot, Config.num_émetteur_fichier, Visu_API, FichierTrace)
            End If

            'Champ8
            Current_datelot = Format(Now, "yyyyMMdd") + "0000"
            SGD_AjouterChamp_Tracé(NumeroSessionLot, Current_datelot, Visu_API, FichierTrace)

            'Champ9 Rang du lot
            SGD_AjouterChamp_Tracé(NumeroSessionLot, "7", Visu_API, FichierTrace)


            'champ10
            RéférenceLotDRE_bdd = Me.LotsTableAdapter.SELECT_max_Référence_DRE_bdd
            While RéférenceLotDRE_bdd.Length < 4
                RéférenceLotDRE_bdd = " " + RéférenceLotDRE_bdd
            End While
            Dim TabRef As Char()
            ReDim TabRef(4)
            For n = 1 To 4
                TabRef(n) = Mid(RéférenceLotDRE_bdd, n, 1)
            Next
            If TabRef(4) <> "Z" Then
                TabRef(4) = Chr(Asc(TabRef(4)) + 1)
            Else
                TabRef(4) = "A"
                If TabRef(3) <> "Z" Then
                    TabRef(3) = Chr(Asc(TabRef(3)) + 1)
                Else
                    TabRef(3) = "A"
                    If TabRef(2) <> "Z" Then
                        TabRef(2) = Chr(Asc(TabRef(2)) + 1)
                    Else
                        TabRef(2) = "A"
                        TabRef(1) = Chr(Asc(TabRef(1)) + 1)
                    End If
                End If
            End If
            For n = 2 To 4
                If TabRef(n) <> " " Then
                    RéférenceLotDRE = RéférenceLotDRE + TabRef(n)
                End If
            Next
            RéférenceLotDRE_bdd = ""
            For n = 1 To 4
                If TabRef(n) <> " " Then
                    RéférenceLotDRE_bdd = RéférenceLotDRE_bdd + TabRef(n)
                End If
            Next
            SGD_AjouterChamp_Tracé(NumeroSessionLot, RéférenceLotDRE, Visu_API, FichierTrace)

            'champ11
            SGD_AjouterChamp_Tracé(NumeroSessionLot, factures_datatable.Rows.Count.ToString, Visu_API, FichierTrace)



            'groupe86
            SGD_AjouterGroupe_Tracé(NumeroSessionLot, 86, Visu_API, FichierTrace)
            Dim file_dre As String
            file_dre = Dir(Config.LocalNetwork_ServerName & "\Factures\Traitées\*.dre")
            Dim num_file_dre As String
            While file_dre <> ""
                num_file_dre = Mid(file_dre, InStr(file_dre, "@") + 1)
                num_file_dre = Mid(num_file_dre, 1, InStr(num_file_dre, "@") - 1)
                If Val(num_file_dre) = factures_datatable(0).Item(Index_Num_Facture) Then
                    Current_CRL_DRE = Mid(file_dre, 1, InStr(file_dre, "@") - 1)
                    Exit While
                End If
                file_dre = Dir()
            End While
            SGD_AjouterChamp_Tracé(NumeroSessionLot, Current_CRL_DRE, Visu_API, FichierTrace)





            'groupe89
            SGD_AjouterGroupe_Tracé(NumeroSessionLot, 89, Visu_API, FichierTrace)
            For r = 0 To factures_datatable.Rows.Count - 1
                Current_Total = Current_Total + factures_datatable(r).Item(Index_Total_AMO)
                file_dre = Dir(Config.LocalNetwork_ServerName & "\Factures\Traitées\*.dre")
                While file_dre <> ""
                    num_file_dre = Mid(file_dre, InStr(file_dre, "@") + 1)
                    num_file_dre = Mid(num_file_dre, 1, InStr(num_file_dre, "@") - 1)
                    If Val(num_file_dre) = factures_datatable(r).Item(Index_Num_Facture) Then
                        Dim bytes = My.Computer.FileSystem.ReadAllBytes(Config.LocalNetwork_ServerName & "\Factures\Traitées\" + file_dre)
                        My.Computer.FileSystem.WriteAllBytes(Config.LocalNetwork_ServerName & "\factures\lots\temp", bytes, True)
                        Me.FacturesTableAdapter1.Update_Num_Lot_DRE(RéférenceLotDRE.ToString, Current_datelot, factures_datatable(r).Item(Index_Num_Facture))
                        Exit While
                    End If
                    file_dre = Dir()
                End While
            Next
            SGD_AjouterChampFichier(NumeroSessionLot, Config.LocalNetwork_ServerName & "\factures\lots\temp")
            Try
                My.Computer.FileSystem.DeleteFile(Config.LocalNetwork_ServerName & "\factures\lots\temp")
            Catch exep As Exception
                MyMsg_Box.Presentation("Officine", exep.ToString, False, "", False, "", True, "OK")
                MyMsg_Box.ShowDialog()

            End Try
        End If


        '____________________________________________________________________________________________________

        'SIS_FormaterLot
        Dim code = InputBox("Code CPS")
        Dim out As Integer = SIS_FormaterLot(NomRessourcePS, NomRessourceLecteur, code.ToString, NumeroSessionLot)
        'Dim out As Integer = SIS_FormaterLot(NomRessourcePS, NomRessourceLecteur, "", NumeroSessionLot)
        If out <> 0 Then
            If refLotDRE = "" Then
                MyMsg_Box.Presentation("Officine", "erreur reconstitution lot " + refLot_FSE.ToString + Chr(10) + out.ToString, False, "", False, "", True, "OK")
                MyMsg_Box.ShowDialog()
            Else
                MyMsg_Box.Presentation("Officine", "erreur reconstitution lot " + refLotDRE.ToString + Chr(10) + out.ToString, False, "", False, "", True, "OK")
                MyMsg_Box.ShowDialog()
            End If

            Exit Sub
        End If
        '____________________________________________________________________________________________________
        'Visu_API agrement CNDA
        If Visu_API = True Then
            If refLotDRE = "" Then
                Technique_MAIN.LireSession_Out_VersFichier2(NumeroSessionLot, Application.StartupPath + "\traces\Formater_Lot_FSE_out.txt")
            Else
                Technique_MAIN.LireSession_Out_VersFichier2(NumeroSessionLot, Application.StartupPath + "\traces\Formater_Lot_DRE_out.txt")
            End If
        End If
        '____________________________________________________________________________________________________
        'enregistrement lot dans bdd
        Dim CRF_FSE As String = "123456789012345678901234567890"
        SGD_LireChamp(NumeroSessionLot, 10, 1, 1, CRF_FSE, 30)
        Dim TailleLot_FSE = 0
        SGD_LireChampBin(NumeroSessionLot, 11, 1, 1, ValeurChamp, TailleLot_FSE)
        Dim G13C1 As String = "@"
        SGD_LireChamp(NumeroSessionLot, 13, 1, 1, G13C1, 1)
        If G13C1 = "@" Then G13C1 = ""
        Dim G13C2 As String = "@"
        SGD_LireChamp(NumeroSessionLot, 13, 1, 2, G13C2, 1)
        If G13C2 = "@" Then G13C2 = ""
        Dim G13C3 As String = "@@@@@@@@@@@@@@"
        SGD_LireChamp(NumeroSessionLot, 13, 1, 3, G13C3, 14)
        If G13C3 = "@@@@@@@@@@@@@@" Then G13C3 = ""
        Dim G13C4 As String = "@@@@@@@@@@@@@@"
        SGD_LireChamp(NumeroSessionLot, 13, 1, 4, G13C4, 14)
        If G13C4 = "@@@@@@@@@@@@@@" Then G13C4 = ""
        Dim G13C5 As String = "@@@"
        SGD_LireChamp(NumeroSessionLot, 13, 1, 5, G13C5, 3)
        If G13C5 = "@@@" Then G13C5 = ""
        Dim G13C6 As String = "@"
        SGD_LireChamp(NumeroSessionLot, 13, 1, 6, G13C6, 1)
        If G13C6 = "@" Then G13C6 = ""
        Dim G13C7 As String = "@@@@@@@@"
        SGD_LireChamp(NumeroSessionLot, 13, 1, 7, G13C7, 8)
        If G13C7 = "@@@@@@@@" Then G13C7 = ""
        Dim G93C1 As String = "@@@@@@@@@@@@@@"
        SGD_LireChamp(NumeroSessionLot, 93, 1, 1, G93C1, 14)

        Dim CRF_DRE As String = "1234567890123456789012345678901234567890123456789012345678901234"
        SGD_LireChamp(NumeroSessionLot, 90, 1, 1, CRF_DRE, 64)
        Dim TailleLot_DRE = 0
        SGD_LireChampBin(NumeroSessionLot, 91, 1, 1, ValeurChamp, TailleLot_DRE)
        If G93C1 = "@@@@@@@@@@@@@@" Then G93C1 = ""
        Dim G93C2 As String = "@@@@@@@@@@"
        SGD_LireChamp(NumeroSessionLot, 93, 1, 2, G93C2, 10)
        If G93C2 = "@@@@@@@@@@" Then G93C2 = ""
        Dim G93C3 As String = "@@@"
        SGD_LireChamp(NumeroSessionLot, 93, 1, 3, G93C3, 3)
        If G93C3 = "@@@" Then G93C3 = ""
        Dim G93C4 As String = "@@@@@@@@@@@@@@@@@@@@"
        TailleMax = 20
        SGD_LireChamp(NumeroSessionLot, 93, 1, 4, G93C4, TailleMax)
        If G93C4 = "@@@@@@@@@@@@@@@@@@@@" Then G93C4 = ""
        G93C4 = Mid(G93C4, 1, TailleMax)
        Dim G93C5 As String = "@@@@@@@@@@@@@@@@@@@@"
        TailleMax = 20
        SGD_LireChamp(NumeroSessionLot, 93, 1, 5, G93C5, TailleMax)
        If G93C5 = "@@@@@@@@@@@@@@@@@@@@" Then G93C5 = ""
        G93C5 = Mid(G93C5, 1, TailleMax)
        Dim G93C6 As String = "@"
        SGD_LireChamp(NumeroSessionLot, 93, 1, 6, G93C6, 8)
        If G93C6 = "@" Then G93C6 = ""
        Dim G93C7 As String = "@@@@@@@@"
        SGD_LireChamp(NumeroSessionLot, 93, 1, 7, G93C7, 8)
        If G93C7 = "@@@@@@@@" Then G93C7 = ""

        If refLotDRE = "" Then
            Me.LotsTableAdapter.Insert1(RéférenceLotFSE_SV, Nothing, Current_CRL_FSE, CRF_FSE, Current_datelot, factures_datatable.Rows.Count, Current_Total, TailleLot_FSE, organisme, G13C1, G13C2, G13C3, G13C4, G13C5, G13C6, G13C7, G93C1, G93C2, G93C3, G93C4, G93C5, G93C6, G93C7, "A TRANSMETTRE", 1, RéférenceLotFSE_bdd, Nothing, G8_G88_C4, False)
            SGD_LireChampFichier(NumeroSessionLot, 11, 1, 1, Config.LocalNetwork_ServerName & "\Factures\Lots\" + RéférenceLotFSE_SV.ToString + ".lotFSE")
            Me.LotsTableAdapter.Update_Etat("RECONSTITUE", refLot_FSE, Nothing)
        Else
            Me.LotsTableAdapter.Insert1(Nothing, RéférenceLotDRE, Current_CRL_DRE, CRF_DRE, Current_datelot, factures_datatable.Rows.Count, Current_Total, TailleLot_DRE, organisme, G13C1, G13C2, G13C3, G13C4, G13C5, G13C6, G13C7, G93C1, G93C2, G93C3, G93C4, G93C5, G93C6, G93C7, "A TRANSMETTRE", 1, Nothing, RéférenceLotDRE_bdd, G8_G88_C4, False)
            SGD_LireChampFichier(NumeroSessionLot, 91, 1, 1, Config.LocalNetwork_ServerName & "\Factures\Lots\" + RéférenceLotDRE + ".lotDRE")
            Me.LotsTableAdapter.Update_Etat("RECONSTITUE", Nothing, refLotDRE)
        End If
        SGD_LibererSession(NumeroSessionLot)

        Afficher_lots_à_transmettre()
        Afficher_lots_DRE_à_transmettre()
        Affiche_Lots_erreur()

    End Sub

    Private Sub Traitement_Manuel_Lot(ByVal refLot_FSE As Integer, ByVal refLotDRE As String)
        'table des factures constituant le lot en erreur-------------------------------------------
        Dim factures_datatable As PharmaDataSet.FacturesDataTable
        If refLotDRE = "" Then
            factures_datatable = Me.FacturesTableAdapter1.GetDataBy_Ref_Lot(refLot_FSE, Me.LotsTableAdapter.GetDataByRéférence(CDec(refLot_FSE), "@@@@@").Item(0)._Date, Nothing, "@@@@@@")
        Else
            factures_datatable = Me.FacturesTableAdapter1.GetDataBy_Ref_Lot(Nothing, "@@@@@@", refLotDRE, Me.LotsTableAdapter.GetDataByRéférence(999999, refLotDRE).Item(0)._Date)
        End If
        '------------------------------------------------------------------------------------------
        ''récupération index
        'Dim Index_Num_Facture As Integer
        'For c = 0 To factures_datatable.Columns.Count - 1
        '    If factures_datatable.Columns.Item(c).ColumnName = "Num" Then
        '        Index_Num_Facture = c
        '    End If
        'Next
        '------------------------------------------------------------------------------------------
        'Dim NumFacture_Traitement_Manuel As Integer
        'suppression si facture en erreur de la table et impression duplicata
        For r = 0 To factures_datatable.Rows.Count - 1
            'For c = 0 To factures_datatable.Columns.Count - 1
            '    If factures_datatable.Columns.Item(c).ColumnName = "Num" Then
            '        NumFacture_Traitement_Manuel = factures_datatable(r).Item(c)
            '    ElseIf factures_datatable.Columns.Item(c).ColumnName = "G1110C1" Then
            '        CurrentFactureVitale.G1110C1 = factures_datatable(r).Item(c)
            '    ElseIf factures_datatable.Columns.Item(c).ColumnName = "G1110C3" Then
            '        CurrentFactureVitale.G1110C3 = factures_datatable(r).Item(c)
            '    ElseIf factures_datatable.Columns.Item(c).ColumnName = "IDPrescripteur" Then
            '        CurrentFactureVitale.IDPrescripteur = factures_datatable(r).Item(c)
            '    ElseIf factures_datatable.Columns.Item(c).ColumnName = "G1130C2" Then
            '        CurrentFactureVitale.G1130C2 = factures_datatable(r).Item(c)
            '    ElseIf factures_datatable.Columns.Item(c).ColumnName = "G1130C3" Then
            '        CurrentFactureVitale.G1130C3 = factures_datatable(r).Item(c)
            '    ElseIf factures_datatable.Columns.Item(c).ColumnName = "Assuré" Then
            '        CurrentFactureVitale.Assuré = factures_datatable(r).Item(c)
            '    ElseIf factures_datatable.Columns.Item(c).ColumnName = "Bénéficiaire" Then
            '        CurrentFactureVitale.Bénéficiaire = factures_datatable(r).Item(c)
            '    ElseIf factures_datatable.Columns.Item(c).ColumnName = "G1310C1" Then
            '        CurrentFactureVitale.G1310C1 = factures_datatable(r).Item(c)
            '    ElseIf factures_datatable.Columns.Item(c).ColumnName = "G1310C2" Then
            '        CurrentFactureVitale.G1310C2 = factures_datatable(r).Item(c)
            '    ElseIf factures_datatable.Columns.Item(c).ColumnName = "G1310C3" Then
            '        CurrentFactureVitale.G1310C3 = factures_datatable(r).Item(c)
            '    ElseIf factures_datatable.Columns.Item(c).ColumnName = "G1321C2" Then
            '        CurrentFactureVitale.G1321C2 = factures_datatable(r).Item(c)
            '    ElseIf factures_datatable.Columns.Item(c).ColumnName = "G1321C3" Then
            '        CurrentFactureVitale.G1321C3 = factures_datatable(r).Item(c)
            '    ElseIf factures_datatable.Columns.Item(c).ColumnName = "G1910C2" Then
            '        CurrentFactureVitale.G1910C2 = factures_datatable(r).Item(c)
            '    ElseIf factures_datatable.Columns.Item(c).ColumnName = "G1910C3" Then
            '        CurrentFactureVitale.G1910C3 = factures_datatable(r).Item(c)
            '    ElseIf factures_datatable.Columns.Item(c).ColumnName = "G1910C4" Then
            '        CurrentFactureVitale.G1910C4 = factures_datatable(r).Item(c)
            '    ElseIf factures_datatable.Columns.Item(c).ColumnName = "G1910C6" Then
            '        CurrentFactureVitale.G1910C6 = factures_datatable(r).Item(c)
            '    End If
            'Next


            '--------------------------------------------------------------------------------------
            'maj num lot de la facture --> "traitement manuel"
            'If refLotDRE = "" Then
            '    Me.FacturesTableAdapter1.Update_Num_Lot_FSE("TRAITEMENT MANUEL", Format(Now, "yyyyMMddHHmm"), NumFacture_Traitement_Manuel)
            'Else
            '    Me.FacturesTableAdapter1.Update_Num_Lot_DRE("TRAITEMENT MANUEL", Format(Now, "yyyyMMddHHmm"), NumFacture_Traitement_Manuel)
            'End If
            '--------------------------------------------------------------------------------------
            'deplacement du fichier de la facture en erreur
            Dim file_fact_erreur As String
            If refLotDRE = "" Then
                file_fact_erreur = Dir(Config.LocalNetwork_ServerName & "\Factures\Traitées\*.fse")
            Else
                file_fact_erreur = Dir(Config.LocalNetwork_ServerName & "\Factures\Traitées\*.dre")
            End If

            Dim num_file_fact_erreur As String
            While file_fact_erreur <> ""
                num_file_fact_erreur = Mid(file_fact_erreur, InStr(file_fact_erreur, "@") + 1)
                num_file_fact_erreur = Mid(num_file_fact_erreur, 1, InStr(num_file_fact_erreur, "@") - 1)
                'If Val(num_file_fact_erreur) = NumFacture_Traitement_Manuel Then
                If Val(num_file_fact_erreur) = factures_datatable(r).Num Then
                    My.Computer.FileSystem.MoveFile(Config.LocalNetwork_ServerName & "\Factures\Traitées\" + file_fact_erreur, Config.LocalNetwork_ServerName & "\Factures\erreur\" + file_fact_erreur, True)
                    Exit While
                End If
                file_fact_erreur = Dir()
            End While
            '--------------------------------------------------------------------------------------
            ''impression duplicata
            'If refLotDRE = "" Then
            '    VenteForm.Imprime_FSE("Impr_Duplicata_FSE")
            'Else
            '    VenteForm.Imprime_FSE("Impr_Duplicata_DRE")
            'End If

            '--------------------------------------------------------------------------------------
        Next



        '____________________________________________________________________________________________________
        'enregistrement lot dans bdd
        If refLotDRE = "" Then
            Me.LotsTableAdapter.Update_Etat("TRAITEMENT MANUEL", refLot_FSE, Nothing)
        Else
            Me.LotsTableAdapter.Update_Etat("TRAITEMENT MANUEL", Nothing, refLotDRE)
        End If

        Afficher_lots_à_transmettre()
        Afficher_lots_DRE_à_transmettre()
        Affiche_Lots_erreur()


    End Sub

#End Region


    Private Sub DateTimePicker_Aquittés_ValueChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles DateTimePicker_Aquittés.ValueChanged
        Affiche_Lots_aquittés()
        Button_Transmis_Aquittés.BackColor = Color.LightGreen
        Button_Transmis_Encours.BackColor = Color.Gray
    End Sub

    Private Sub affiche_Paiements_facture()
        DataGridView_paiements.Rows.Clear()

        Dim Facturestable As DataTable = Me.FacturesTableAdapter1.GetDataBy_DateMini(Val(Format(DateTimePicker_Paiements.Value, "yyyyMMdd") + "0000"))

        '-----------------------------------------------------------
        'recup des index
        Dim Facturestable_G1110C1_index, Facturestable_G1310C1_index, Facturestable_G1310C2_index, Facturestable_G1310C3_index, Facturestable_G1910C3_index, Facturestable_G1910C6_index As Integer
        For c = 0 To Facturestable.Columns.Count - 1
            If Facturestable.Columns.Item(c).ColumnName = "G1110C1" Then
                Facturestable_G1110C1_index = c
            ElseIf Facturestable.Columns.Item(c).ColumnName = "G1310C1" Then
                Facturestable_G1310C1_index = c
            ElseIf Facturestable.Columns.Item(c).ColumnName = "G1310C2" Then
                Facturestable_G1310C2_index = c
            ElseIf Facturestable.Columns.Item(c).ColumnName = "G1310C3" Then
                Facturestable_G1310C3_index = c
            ElseIf Facturestable.Columns.Item(c).ColumnName = "G1910C3" Then
                Facturestable_G1910C3_index = c
            ElseIf Facturestable.Columns.Item(c).ColumnName = "G1910C6" Then
                Facturestable_G1910C6_index = c
            End If
        Next
        '-----------------------------------------------------------

        For r = 0 To Facturestable.Rows.Count - 1
            DataGridView_paiements.Rows.Add()
            Dim num_facture As String = Facturestable(r).Item(Facturestable_G1110C1_index)
            While num_facture.Length < 9
                num_facture = "0" & num_facture
            End While
            DataGridView_paiements.Item(Paiements_NumFact.Index, r).Value = num_facture
            DataGridView_paiements.Item(Paiements_Montant_Demandé_AMO.Index, r).Value = Facturestable(r).Item(Facturestable_G1910C3_index)
            DataGridView_paiements.Item(Paiements_Montant_Demandé_AMC.Index, r).Value = Facturestable(r).Item(Facturestable_G1910C6_index)
            DataGridView_paiements.Item(Paiements_Org_emetteur_AMO.Index, r).Value = Me.AmoTableAdapter1.SelectLibellé(Facturestable(r).Item(Facturestable_G1310C1_index), Facturestable(r).Item(Facturestable_G1310C2_index), Facturestable(r).Item(Facturestable_G1310C3_index))
            Dim numfacture As String = Facturestable(r).Item(Facturestable_G1110C1_index)
            Dim Montant_AMO = Facturestable(r).Item(Facturestable_G1910C3_index)
            Dim Montant_AMC = Facturestable(r).Item(Facturestable_G1910C6_index)
            While numfacture.Length < 9
                numfacture = "0" + numfacture
            End While
            Dim paiements_datatable As DataTable = Me.RSP_PaiementsTableAdapter.GetDataBy_NumFacture(numfacture)
            For r2 = 0 To paiements_datatable.Rows.Count - 1
                Dim part As String = ""

                For c = 0 To paiements_datatable.Columns.Count - 1
                    If paiements_datatable.Columns.Item(c).ColumnName = "Part" Then
                        part = paiements_datatable(r2).Item(c)
                        Exit For
                    End If
                Next

                If part = "AMO" Then
                    For c = 0 To paiements_datatable.Columns.Count - 1
                        If paiements_datatable.Columns.Item(c).ColumnName = "Date" Then
                            DataGridView_paiements.Item(Paiements_Date_AMO.Index, r).Value = Mid(paiements_datatable(r2).Item(c), 1, 2) + "/" + Mid(paiements_datatable(r2).Item(c), 3, 2) + "/" + Mid(paiements_datatable(r2).Item(c), 5, 2)
                        ElseIf paiements_datatable.Columns.Item(c).ColumnName = "Libellé_Ligne_1" Then
                            DataGridView_paiements.Item(Paiements_Libellé1_AMO.Index, r).Value = paiements_datatable(r2).Item(c)
                        ElseIf paiements_datatable.Columns.Item(c).ColumnName = "Libellé_Ligne_2" Then
                            DataGridView_paiements.Item(Paiements_libellé2_AMO.Index, r).Value = paiements_datatable(r2).Item(c)
                        ElseIf paiements_datatable.Columns.Item(c).ColumnName = "Org_Payeur" Then
                            DataGridView_paiements.Item(Paiements_Org_Payeur_AMO.Index, r).Value = paiements_datatable(r2).Item(c)
                        ElseIf paiements_datatable.Columns.Item(c).ColumnName = "Etat_Paiement" Then
                            DataGridView_paiements.Item(Paiements_Etat_Paiement_AMO.Index, r).Value = paiements_datatable(r2).Item(c)
                        ElseIf paiements_datatable.Columns.Item(c).ColumnName = "Payé" Then
                            DataGridView_paiements.Item(Paiements_Montant_Payé_AMO.Index, r).Value = paiements_datatable(r2).Item(c)

                        End If
                    Next
                ElseIf part = "AMC" Then
                    For c = 0 To paiements_datatable.Columns.Count - 1
                        If paiements_datatable.Columns.Item(c).ColumnName = "Date" Then
                            DataGridView_paiements.Item(Paiements_Date_AMC.Index, r).Value = paiements_datatable(r2).Item(c)
                        ElseIf paiements_datatable.Columns.Item(c).ColumnName = "Libellé_Ligne_1" Then
                            DataGridView_paiements.Item(Paiements_libellé1_AMC.Index, r).Value = paiements_datatable(r2).Item(c)
                        ElseIf paiements_datatable.Columns.Item(c).ColumnName = "Libellé_Ligne_2" Then
                            DataGridView_paiements.Item(Paiements_libellé2_AMC.Index, r).Value = paiements_datatable(r2).Item(c)
                        ElseIf paiements_datatable.Columns.Item(c).ColumnName = "Org_Payeur" Then
                            DataGridView_paiements.Item(Paiements_org_payeur_AMC.Index, r).Value = paiements_datatable(r2).Item(c)
                        ElseIf paiements_datatable.Columns.Item(c).ColumnName = "Etat_Paiement" Then
                            DataGridView_paiements.Item(Paiements_Etat_paiement_AMC.Index, r).Value = paiements_datatable(r2).Item(c)
                        ElseIf paiements_datatable.Columns.Item(c).ColumnName = "Payé" Then
                            DataGridView_paiements.Item(Paiements_Montant_Payé_AMC.Index, r).Value = paiements_datatable(r2).Item(c)

                        End If
                    Next
                End If

            Next
        Next


    End Sub

    Private Sub Button_Paiements_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button_Paiements.Click
        affiche_Paiements_facture()
    End Sub
    Private Sub DateTimePicker_Paiements_ValueChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles DateTimePicker_Paiements.ValueChanged
        affiche_Paiements_facture()
    End Sub

    Private Sub DateTimePicker1_ValueChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles DateTimePicker_Recap_Paiement.ValueChanged
        DataGridView_Recap_Paiements.Rows.Clear()
        Dim mydatatable As DataTable = Me.RSP_PaiementsTableAdapter.GetData_Paiements(Val(Format(DateTimePicker_Recap_Paiement.Value, "yyMMdd")))
        For r = 0 To mydatatable.Rows.Count - 1
            DataGridView_Recap_Paiements.Rows.Add()
            For c = 0 To mydatatable.Columns.Count - 1
                If mydatatable.Columns.Item(c).ColumnName = "Date" Then
                    DataGridView_Recap_Paiements.Item(Recap_Paiements_Date.Index, r).Value = Mid(mydatatable(r).Item(c), 1, 2) + "/" + Mid(mydatatable(r).Item(c), 3, 2) + "/" + Mid(mydatatable(r).Item(c), 5, 2)
                ElseIf mydatatable.Columns.Item(c).ColumnName = "Org_emetteur" Then
                    DataGridView_Recap_Paiements.Item(Recap_Paiements_Organisme_emetteur.Index, r).Value = mydatatable(r).Item(c)
                ElseIf mydatatable.Columns.Item(c).ColumnName = "Libellé_Ligne_1" Then
                    DataGridView_Recap_Paiements.Item(Recap_Paiements_Libellé1.Index, r).Value = mydatatable(r).Item(c)
                ElseIf mydatatable.Columns.Item(c).ColumnName = "Libellé_Ligne_2" Then
                    DataGridView_Recap_Paiements.Item(Recap_Paiements_libellé2.Index, r).Value = mydatatable(r).Item(c)
                ElseIf mydatatable.Columns.Item(c).ColumnName = "Org_Payeur" Then
                    DataGridView_Recap_Paiements.Item(Recap_Paiements_organisme_payeur.Index, r).Value = mydatatable(r).Item(c)
                ElseIf mydatatable.Columns.Item(c).ColumnName = "num_destinataire" Then
                    DataGridView_Recap_Paiements.Item(Recap_Paiements_num_destinataire.Index, r).Value = mydatatable(r).Item(c)
                ElseIf mydatatable.Columns.Item(c).ColumnName = "Montant" Then
                    DataGridView_Recap_Paiements.Item(Recap_Paiements_Montant.Index, r).Value = mydatatable(r).Item(c)
                End If
            Next

        Next
    End Sub

    Private Sub DataGridView_Recap_Paiements_CellClick(ByVal sender As System.Object, ByVal e As System.Windows.Forms.DataGridViewCellEventArgs) Handles DataGridView_Recap_Paiements.CellClick
        Dim myform As New Détail_Recap_Paiement
        myform.datepaiement = DataGridView_Recap_Paiements.Item(Recap_Paiements_Date.Index, DataGridView_Recap_Paiements.CurrentRow.Index).Value
        myform.libellé1 = DataGridView_Recap_Paiements.Item(Recap_Paiements_Libellé1.Index, DataGridView_Recap_Paiements.CurrentRow.Index).Value
        myform.libellé2 = DataGridView_Recap_Paiements.Item(Recap_Paiements_libellé2.Index, DataGridView_Recap_Paiements.CurrentRow.Index).Value
        myform.org_payeur = DataGridView_Recap_Paiements.Item(Recap_Paiements_organisme_payeur.Index, DataGridView_Recap_Paiements.CurrentRow.Index).Value
        myform.org_emetteur = DataGridView_Recap_Paiements.Item(Recap_Paiements_Organisme_emetteur.Index, DataGridView_Recap_Paiements.CurrentRow.Index).Value
        myform.Visible = True

    End Sub


    Private Sub ImprimerToolStripMenuItem_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles ToolStripMenuItem_DataGridViewPrinter.Click


        If MyDataGridViewPrinter.SetupThePrinting(ContextMenuStrip_DataGridViewPrinter.SourceControl, ContextMenuStrip_DataGridViewPrinter.SourceControl.Name.ToString, PrintDocument1) Then
            MyPrintDocument.Print()
        End If
        Try
            System.Threading.Thread.Sleep(1000)
            Process.Start(Application.StartupPath & "\temp.XPS")
        Catch ex As Exception
        End Try

    End Sub

    Private Sub MyPrintDocument_PrintPage(ByVal sender As System.Object, ByVal e As System.Drawing.Printing.PrintPageEventArgs) Handles MyPrintDocument.PrintPage
        Dim more As Boolean = MyDataGridViewPrinter.DrawDataGridView(e.Graphics)
        If more = True Then
            e.HasMorePages = True
        End If
    End Sub


    Private Sub DataGridView_Rejets_Paiements_CellClick(ByVal sender As System.Object, ByVal e As System.Windows.Forms.DataGridViewCellEventArgs) Handles DataGridView_Rejets_Paiements.CellClick
        If e.RowIndex = -1 Then
            Exit Sub
        End If
        Select Case DataGridView_Rejets_Paiements.CurrentCell.ColumnIndex
            Case Rejets_Paiement_Traitement.Index
                Dim current_row_index As Integer = DataGridView_Rejets_Paiements.CurrentRow.Index

                MyMsg_Box.Presentation("Officine", "Acquiter le rejet?", True, "OUI", True, "NON", False, "")
                If MyMsg_Box.ShowDialog() = Windows.Forms.DialogResult.Yes Then
                    '--------------------------------------------------------------------------------------
                    'maj Acquitement RSP --> true
                    Me.RSP_LIGNE_REJETTableAdapter.Update_Acquitement(True, DataGridView_Rejets_Paiements.Item(Rejets_Paiement_Num_facture.Index, current_row_index).Value, DataGridView_Rejets_Paiements.Item(Rejets_Paiement_Part_Concernée.Index, current_row_index).Value)
                    '--------------------------------------------------------------------------------------
                    'traitée comme recyclée pour nu plus attendre le paiement
                    BDD.FacturesTableAdapter.Set_Recyclée(True, CDec(DataGridView_Rejets_Paiements.Item(Rejets_Paiement_Num_facture.Index, current_row_index).Value))
                    '--------------------------------------------------------------------------------------
                    Affiche_Rejets_Paiement(DataGridView_Rejets_Paiements)
                End If


            Case Else

                Web_browser.Visible = True
                Web_browser.WindowState = FormWindowState.Maximized
                Dim parameters As String = "&Num=" & Val(DataGridView_Rejets_Paiements.Item(Rejets_Paiement_Num_facture.Index, DataGridView_Rejets_Paiements.CurrentRow.Index).Value).ToString
                Web_browser.WebBrowser1.Navigate("http://" & Replace(Config.LocalNetwork_ServerName, "\", "") & "/ReportServer_SQLEXPRESS/Pages/ReportViewer.aspx?%2fFactures%2fFacture+Sesam-Vitale&rs:Command=Render" & parameters)
                Web_browser.BringToFront()
                Web_browser.Select()

        End Select

    End Sub

#Region "SCANORDO"
    Public Function TT03(ByVal Num_Lot_FSE As String, ByVal InfoModeEnvoi As String, ByVal to_ As String, ByVal liste_factures As List(Of String), ByVal InfoIDXLOT As Integer, ByVal InfoNBLOT As Integer) As String

        'TT03.01 : Préparer les dossiers de justificatifs
        'xml file:Instance_SCANORDO_V02_03
        Dim My_Xml_Doc As New XmlDocument
        My_Xml_Doc.Load(Config.LocalNetwork_ServerName & "\scor\XML\ENTSCANORDO_V02_08.xml")
        Dim XMLelementliste As XmlNodeList
        Dim my_fact_datatable = COMPTOIR_MAIN.FacturesTableAdapter.GetDataBy_Ref_Lot(Num_Lot_FSE, Me.LotsTableAdapter.GetDataByRéférence(CDec(Num_Lot_FSE), "@@@@@").Item(0)._Date, "XXXXXXXXXXXXXXXXXXXXXX", "XXXXXXXXXXXXXXXXXXXXXX")
        Dim my_lot_datatable = Me.LotsTableAdapter.GetDataByRéférence(Num_Lot_FSE, "XXXXXXXXXXXXXXXXXXXXXX")
        If my_fact_datatable.Rows.Count = 0 Or my_lot_datatable.Rows.Count = 0 Or liste_factures.Count = 0 Then
            trace_log("TT03 Error 1" & vbCrLf & "Num_Lot_FSE:" & Num_Lot_FSE & vbCrLf & "my_fact_datatable.Rows.Count:" & my_fact_datatable.Rows.Count.ToString & vbCrLf & _
                      "liste_factures.Count:" & liste_factures.Count.ToString & vbCrLf & "my_lot_datatable.Rows.Count:" & my_lot_datatable.Rows.Count.ToString)
            MyMsg_Box.Presentation("Officine !", "Erreur transmission SCOR Lot " & Num_Lot_FSE, False, "", False, "", True, "OK")
            MyMsg_Box.ShowDialog()
            Return ""
        End If
        '[RG_TT026] Préparer l’entité «Entête SEH lot de justificatifs»
        XMLelementliste = My_Xml_Doc.GetElementsByTagName("Entete")
        Thread.Sleep(2000) '<-- pour eviter que deux lots aient le même compostage
        Dim Compostage As String = Format(Now, "yyyyMMddHHmmss") & "00001"
        Dim IDPS As String
        ValeurChamp = "@@@@@@@@"
        TailleMax = 8
        SGD_LireChamp(NumeroSessionCPS, 2, Occurence_Grp2, 9, ValeurChamp, TailleMax)
        IDPS = ValeurChamp
        ValeurChamp = "@"
        TailleMax = 1
        SGD_LireChamp(NumeroSessionCPS, 2, Occurence_Grp2, 10, ValeurChamp, TailleMax)
        IDPS = IDPS & ValeurChamp
        'XMLelementliste.Item(0).Item("Identification").InnerText = my_fact_datatable(0).G1120C1.ToString() & my_fact_datatable(0).G1120C2.ToString() & "-" & Compostage
        XMLelementliste.Item(0).Item("Identification").InnerText = IDPS & "-" & Compostage
        XMLelementliste.Item(0).Item("Temps").InnerText = Format(Now, "yyyy-MM-dd") & "T" & Format(Now, "HH:mm:ss")
        If Config.Logiciel_ModeFonctionement = "Test" Then
            XMLelementliste.Item(0).Item("Fonction").InnerText = "53" '53 pour test, 9 pour réel
        Else
            XMLelementliste.Item(0).Item("Fonction").InnerText = "9" '53 pour test, 9 pour réel
        End If

        Dim NbrDoc As Integer
        Dim nombre_factures_dans_lot As Integer = liste_factures.Count    'my_fact_datatable.Rows.Count
        For r = 0 To my_fact_datatable.Rows.Count - 1
            If liste_factures.Contains(my_fact_datatable(r).G1110C1) Then
                Dim num_facture As String = my_fact_datatable(r).G1110C1
                If My.Computer.FileSystem.FileExists(Config.LocalNetwork_ServerName & "\scor\Index\" & num_facture & ".xml") Then 'verification présence fichier d'index
                    NbrDoc = NbrDoc + 1 'fichier d'index
                    Dim file = Dir(Config.LocalNetwork_ServerName & "\scor\doc\" & num_facture & "_*.pdf")
                    While file <> ""
                        NbrDoc = NbrDoc + 1
                        file = Dir()
                    End While
                End If
            End If
        Next
        XMLelementliste.Item(0).Item("NbrDoc").InnerText = NbrDoc.ToString
        Dim InfoIDXLOT_strg = InfoIDXLOT.ToString
        While InfoIDXLOT_strg.Length < 2
            InfoIDXLOT_strg = "0" & InfoIDXLOT_strg
        End While
        XMLelementliste.Item(0).Item("InfoIDXLOT").InnerText = InfoIDXLOT_strg
        Dim InfoNBLOT_strg = InfoNBLOT.ToString
        While InfoNBLOT_strg.Length < 2
            InfoNBLOT_strg = "0" & InfoNBLOT_strg
        End While
        XMLelementliste.Item(0).Item("InfoNBLOT").InnerText = InfoNBLOT_strg
        XMLelementliste.Item(0).Item("InfoModeEnvoi").InnerText = InfoModeEnvoi

        '[RG_TT027] Préparer l’entité «Emetteur lot de justificatifs »
        XMLelementliste = My_Xml_Doc.GetElementsByTagName("Emetteur")
        XMLelementliste.Item(0).Item("Identite").InnerText = my_fact_datatable(0).G1120C1.ToString() & my_fact_datatable(0).G1120C2.ToString()
        XMLelementliste.Item(0).Item("Nom").InnerText = my_lot_datatable(0).G8_G88_C4
        If my_fact_datatable(0).G1120C13.ToString() & my_fact_datatable(0).G1120C14.ToString() <> "" Then
            XMLelementliste.Item(0).Item("RPPS").InnerText = my_fact_datatable(0).G1120C13.ToString() & my_fact_datatable(0).G1120C14.ToString()
        Else
            XMLelementliste.Item(0).RemoveChild(XMLelementliste.Item(0).Item("RPPS"))
        End If
        XMLelementliste.Item(0).Item("Qualite").InnerText = "OPORDO"
        XMLelementliste.Item(0).Item("Region").InnerText = "41"
        XMLelementliste.Item(0).Item("SpecialitePS").InnerText = "50"

        '[RG_TT028] Préparer l’entité «Télécommunication»
        XMLelementliste = My_Xml_Doc.GetElementsByTagName("Telecom")
        XMLelementliste.Item(0).Item("Type").InnerText = "EM"
        If Config.OCT_UtilisationOCT = False Then
            XMLelementliste.Item(0).Item("Numero").InnerText = "PS:" + Config.Scor_from
        Else
            If Config.Scor_Dest_ARL = "PS" Then
                XMLelementliste.Item(0).Item("Numero").InnerText = "PS:" + Config.Scor_from
            ElseIf Config.Scor_Dest_ARL = "OCT" Then
                XMLelementliste.Item(0).Item("Numero").InnerText = "PRT:" + Config.Scor_Adr_OCT
            ElseIf Config.Scor_Dest_ARL = "PS/OCT" Then
                XMLelementliste.Item(0).Item("Numero").InnerText = "PS:" + Config.Scor_from + ";PRT:" + Config.Scor_Adr_OCT
            End If

        End If

        '[RG_TT030] Préparer l’entité « Destinataire lot de justificatifs »
        XMLelementliste = My_Xml_Doc.GetElementsByTagName("Recepteur")

        XMLelementliste.Item(0).Item("Identite").InnerText = my_fact_datatable(0).G1310C1.ToString() & my_fact_datatable(0).G1310C4.ToString()
        XMLelementliste.Item(0).Item("Qualite").InnerText = "OPAMO"

        '[RG_TT032] Préparer l’entité «Identification lot FSE»
        XMLelementliste = My_Xml_Doc.GetElementsByTagName("Trace")
        XMLelementliste.Item(0).Item("Activite").InnerText = "LOTFSE"
        Dim date_lot As String = my_lot_datatable(0)._Date
        XMLelementliste.Item(0).Item("Temps").InnerText = Mid(date_lot, 1, 4) & "-" & Mid(date_lot, 5, 2) & "-" & Mid(date_lot, 7, 2) & "T00:00:00"
        XMLelementliste.Item(0).Item("Archive").InnerText = Num_Lot_FSE
        If Mid(my_lot_datatable(0).CRL, 19, 1) = "S" Then  '[RG_TT048] Lier le mode de sécurisation FSE
            XMLelementliste.Item(0).Item("InfoType").InnerText = "1"
        Else
            XMLelementliste.Item(0).Item("InfoType").InnerText = "2"
        End If
        'XMLelementliste.Item(0).Item("InfoNBFACT").InnerText = my_lot_datatable(0).NombreDeFSE
        XMLelementliste.Item(0).Item("InfoNBFACT").InnerText = nombre_factures_dans_lot.ToString
        While XMLelementliste.Item(0).Item("InfoNBFACT").InnerText.Length < 3
            XMLelementliste.Item(0).Item("InfoNBFACT").InnerText = "0" & XMLelementliste.Item(0).Item("InfoNBFACT").InnerText
        End While

        '[RG_TT033] Préparer l’entité «Agrément»
        XMLelementliste = My_Xml_Doc.GetElementsByTagName("Agrement")
        'XMLelementliste.Item(0).Item("Id").InnerText = "TESTCNDA"
        'XMLelementliste.Item(0).Item("Version").InnerText = "1409"
        XMLelementliste.Item(0).Item("Id").InnerText = "GSNW3B00"
        XMLelementliste.Item(0).Item("Version").InnerText = "0110"
        'repertoire temp pour mettre les fichiers qu'on va mettre dans un lot 
        If My.Computer.FileSystem.DirectoryExists(Config.LocalNetwork_ServerName & "\scor\index\tempmisiak") Then
            My.Computer.FileSystem.DeleteDirectory(Config.LocalNetwork_ServerName & "\scor\index\tempmisiak", FileIO.DeleteDirectoryOption.DeleteAllContents)
        End If

        My.Computer.FileSystem.CreateDirectory(Config.LocalNetwork_ServerName & "\scor\index\tempmisiak")
        Dim num_odre As Integer = 0
        For r = 0 To my_fact_datatable.Rows.Count - 1
            If liste_factures.Contains(my_fact_datatable(r).G1110C1) Then
                If My.Computer.FileSystem.FileExists(Config.LocalNetwork_ServerName & "\scor\index\" & my_fact_datatable(r).G1110C1 & ".xml") Then

                    'fichier index
                    num_odre = num_odre + 1
                    Dim num_odre_string As String = num_odre.ToString
                    While num_odre_string.Length < 3
                        num_odre_string = "0" & num_odre_string
                    End While
                    '[RG_TT034] Préparer l’entité «Lien fichier du dossier de justificatifs »
                    'champ à renseigner dans l'index lors de ma mise en lot (non renseigné à [RG_TT007])
                    Dim D_xml As New XmlDocument
                    D_xml.Load(Config.LocalNetwork_ServerName & "\scor\index\" & my_fact_datatable(r).G1110C1 & ".xml")
                    Dim D_XMLelementliste As XmlNodeList
                    D_XMLelementliste = D_xml.GetElementsByTagName("SCANORDO")
                    D_XMLelementliste.Item(0).Item("Identifiant").InnerText = "D-" & num_odre_string
                    D_XMLelementliste.Item(0).Item("Identifiant").InnerText = num_odre_string
                    D_xml.Save(Config.LocalNetwork_ServerName & "\scor\index\" & my_fact_datatable(r).G1110C1 & ".xml")

                    If Not My.Computer.FileSystem.DirectoryExists(Config.LocalNetwork_ServerName & "\scor\index\tempmisiak\") Then
                        My.Computer.FileSystem.CreateDirectory(Config.LocalNetwork_ServerName & "\scor\index\tempmisiak\")
                    End If
                    While Not My.Computer.FileSystem.DirectoryExists(Config.LocalNetwork_ServerName & "\scor\index\tempmisiak\")
                        Thread.Sleep(1000)
                    End While
                    My.Computer.FileSystem.CopyFile(Config.LocalNetwork_ServerName & "\scor\index\" & my_fact_datatable(r).G1110C1 & ".xml", _
                                                    Config.LocalNetwork_ServerName & "\scor\index\tempmisiak\D-" & num_odre_string & ".xml")
                    '''''''''''''''
                    Dim Lien_Node As XmlNode = My_Xml_Doc.CreateElement("Lien", My_Xml_Doc.DocumentElement.NamespaceURI)

                    Dim Lien_Adresse_Node As XmlElement = My_Xml_Doc.CreateElement("Adresse", My_Xml_Doc.DocumentElement.NamespaceURI)

                    'Lien_Adresse_Node.InnerText = "D-" & num_odre_string & ".xml"
                    Lien_Adresse_Node.InnerText = "D-" & num_odre_string & ".pkcs7"


                    Lien_Node.AppendChild(Lien_Adresse_Node)

                    Dim Lien_Type_Node As XmlElement = My_Xml_Doc.CreateElement("Type", My_Xml_Doc.DocumentElement.NamespaceURI)
                    'Lien_Type_Node.InnerText = "XML"
                    Lien_Type_Node.InnerText = "PKCS7"
                    Lien_Type_Node.SetAttribute("Q", "XML")
                    Lien_Node.AppendChild(Lien_Type_Node)

                    Dim Mindex_Node As XmlNode = My_Xml_Doc.CreateElement("Mindex", My_Xml_Doc.DocumentElement.NamespaceURI)

                    Dim Mindex_Profil_Node As XmlElement = My_Xml_Doc.CreateElement("Profil", My_Xml_Doc.DocumentElement.NamespaceURI)
                    Mindex_Profil_Node.InnerText = "SCANORDO"
                    Mindex_Node.AppendChild(Mindex_Profil_Node)

                    Dim Mindex_Identification_Node As XmlElement = My_Xml_Doc.CreateElement("Identification", My_Xml_Doc.DocumentElement.NamespaceURI)
                    Mindex_Identification_Node.InnerText = num_odre_string
                    Mindex_Node.AppendChild(Mindex_Identification_Node)

                    Dim index_xmldoc As New XmlDocument
                    index_xmldoc.Load(Config.LocalNetwork_ServerName & "\scor\index\tempmisiak\D-" & num_odre_string & ".xml")

                    Dim Mindex_Temps_Node As XmlElement = My_Xml_Doc.CreateElement("Temps", My_Xml_Doc.DocumentElement.NamespaceURI)
                    Mindex_Temps_Node.InnerText = index_xmldoc.GetElementsByTagName("Temps").Item(0).InnerText
                    Mindex_Node.AppendChild(Mindex_Temps_Node)

                    Dim Mindex_Descriptif_Node As XmlElement = My_Xml_Doc.CreateElement("Descriptif", My_Xml_Doc.DocumentElement.NamespaceURI)
                    Mindex_Descriptif_Node.InnerText = "1"
                    Mindex_Node.AppendChild(Mindex_Descriptif_Node)

                    Dim Mindex_Archive_Node As XmlElement = My_Xml_Doc.CreateElement("Archive", My_Xml_Doc.DocumentElement.NamespaceURI)
                    Mindex_Archive_Node.InnerText = my_fact_datatable(r).G1110C1
                    While Mindex_Archive_Node.InnerText.Length < 9
                        Mindex_Archive_Node.InnerText = "0" & Mindex_Archive_Node.InnerText
                    End While
                    Mindex_Node.AppendChild(Mindex_Archive_Node)

                    Dim Document_node As XmlElement
                    Document_node = My_Xml_Doc.CreateElement("Document", My_Xml_Doc.DocumentElement.NamespaceURI)
                    Document_node.AppendChild(Mindex_Node)
                    Document_node.AppendChild(Lien_Node)

                    Dim file As String
                    file = Dir(Config.LocalNetwork_ServerName & "\scor\doc\" & my_fact_datatable(r).G1110C1 & "_*_*.pdf")

                    Dim indice_pièce As Integer '[RG_TT018] Nom physique du fichier PDF de justificatif
                    indice_pièce = 0
                    While file <> ""
                        indice_pièce = indice_pièce + 1
                        Dim indice_pièce_string As String = indice_pièce.ToString
                        While indice_pièce_string.Length < 3
                            indice_pièce_string = "0" & indice_pièce_string
                        End While
                        Dim adresse As String
                        'adresse = "P-" + num_odre_string + "-" + indice_pièce_string + ".pdf"
                        adresse = "P-" + num_odre_string + "-" + indice_pièce_string + ".pkcs7"
                        Dim fLien_Node As XmlNode = My_Xml_Doc.CreateElement("Lien", My_Xml_Doc.DocumentElement.NamespaceURI)


                        Dim fLien_Adresse_Node As XmlElement = My_Xml_Doc.CreateElement("Adresse", My_Xml_Doc.DocumentElement.NamespaceURI)
                        fLien_Adresse_Node.InnerText = adresse
                        fLien_Node.AppendChild(fLien_Adresse_Node)

                        Dim fLien_Type_Node As XmlElement = My_Xml_Doc.CreateElement("Type", My_Xml_Doc.DocumentElement.NamespaceURI)
                        fLien_Type_Node.SetAttribute("Q", "PDF")
                        'fLien_Type_Node.InnerText = "PDF"
                        fLien_Type_Node.InnerText = "PKCS7"
                        fLien_Node.AppendChild(fLien_Type_Node)

                        'Dim fLien_Version_Node As XmlElement = My_Xml_Doc.CreateElement("Version", My_Xml_Doc.DocumentElement.NamespaceURI)
                        'fLien_Version_Node.InnerText = "02.02"
                        'fLien_Node.AppendChild(fLien_Version_Node)

                        Dim fLien_Nature_Node As XmlElement = My_Xml_Doc.CreateElement("Nature", My_Xml_Doc.DocumentElement.NamespaceURI)
                        fLien_Nature_Node.InnerText = Mid(file, InStrRev(file, "_") + 1, 4)
                        fLien_Node.AppendChild(fLien_Nature_Node)

                        Dim fLien_Identification_Node As XmlElement = My_Xml_Doc.CreateElement("Identification", My_Xml_Doc.DocumentElement.NamespaceURI)
                        If ScanOrdo.SCOR_PJTableAdapter.GetDataBy_Fichier(file).Rows.Count = 0 Then

                            MyMsg_Box.Presentation("Officine !", "Problème d'enregistrement pour la pièce jointe." & vbCrLf & file, False, "", False, "", True, "Ok")
                            MyMsg_Box.ShowDialog()

                        End If
                        fLien_Identification_Node.InnerText = ScanOrdo.SCOR_PJTableAdapter.GetDataBy_Fichier(file)(0).ID
                        fLien_Node.AppendChild(fLien_Identification_Node)

                        Document_node.AppendChild(fLien_Node)

                        My.Computer.FileSystem.CopyFile(Config.LocalNetwork_ServerName & "\scor\doc\" + file, Config.LocalNetwork_ServerName & "\scor\index\tempmisiak\" + Mid(adresse, 1, InStrRev(adresse, ".")) + "pdf")
                        file = Dir()

                    End While
                    My_Xml_Doc.DocumentElement.AppendChild(Document_node)
                    '-----------------------------------------------------------------------------------------------------------------------------------------
                    'lien externe papier
                    Dim file_ext As String
                    file_ext = Dir(Config.LocalNetwork_ServerName & "\scor\doc\papier\" & my_fact_datatable(r).G1110C1 & "_*_*.pdf")

                    While file_ext <> ""
                        Dim fLienExterne_Node As XmlNode = My_Xml_Doc.CreateElement("LienExterne", My_Xml_Doc.DocumentElement.NamespaceURI)


                        Dim fLienExterne_Type_Node As XmlElement = My_Xml_Doc.CreateElement("Type", My_Xml_Doc.DocumentElement.NamespaceURI)
                        fLienExterne_Type_Node.SetAttribute("Q", "PAPIER")
                        'fLien_Type_Node.InnerText = "PDF"
                        fLienExterne_Type_Node.InnerText = "PAPIER"
                        fLienExterne_Node.AppendChild(fLienExterne_Type_Node)



                        Dim fLienExterne_Nature_Node As XmlElement = My_Xml_Doc.CreateElement("Nature", My_Xml_Doc.DocumentElement.NamespaceURI)
                        fLienExterne_Nature_Node.InnerText = Mid(file_ext, InStrRev(file_ext, "_") + 1, 4)
                        fLienExterne_Node.AppendChild(fLienExterne_Nature_Node)

                        'Dim fLienExterne_Identification_Node As XmlElement = My_Xml_Doc.CreateElement("Identification", My_Xml_Doc.DocumentElement.NamespaceURI)
                        'fLienExterne_Identification_Node.InnerText = ""
                        'fLienExterne_Node.AppendChild(fLienExterne_Identification_Node)

                        Dim fLienExterne_InfoModeEnvoi_Node As XmlElement = My_Xml_Doc.CreateElement("InfoModeEnvoi", My_Xml_Doc.DocumentElement.NamespaceURI)
                        fLienExterne_InfoModeEnvoi_Node.InnerText = "PAPIER"
                        fLienExterne_Node.AppendChild(fLienExterne_InfoModeEnvoi_Node)

                        Document_node.AppendChild(fLienExterne_Node)


                        file_ext = Dir()

                    End While
                    My_Xml_Doc.DocumentElement.AppendChild(Document_node)
                    '-----------------------------------------------------------------------------------------------------------------------------------------
                    'lien externe pièces déja transmises
                    Dim liens_externes_table = ScanOrdo.SCOR_PJTableAdapter.GetDataBy_Num_Facture_and_Statut_Transmission(my_fact_datatable(r).G1110C1, "DOCUMENT EXTERNE")

                    For rr = 0 To liens_externes_table.Rows.Count - 1

                        Dim fLienExterne_Node As XmlNode = My_Xml_Doc.CreateElement("LienExterne", My_Xml_Doc.DocumentElement.NamespaceURI)


                        Dim fLienExterne_Type_Node As XmlElement = My_Xml_Doc.CreateElement("Type", My_Xml_Doc.DocumentElement.NamespaceURI)
                        fLienExterne_Type_Node.SetAttribute("Q", "PDF")
                        'fLien_Type_Node.InnerText = "PDF"
                        fLienExterne_Type_Node.InnerText = "PKCS7"
                        fLienExterne_Node.AppendChild(fLienExterne_Type_Node)



                        Dim fLienExterne_Nature_Node As XmlElement = My_Xml_Doc.CreateElement("Nature", My_Xml_Doc.DocumentElement.NamespaceURI)
                        fLienExterne_Nature_Node.InnerText = Mid(liens_externes_table(rr).ID, InStr(liens_externes_table(rr).ID, ".") + 1, 4)
                        fLienExterne_Node.AppendChild(fLienExterne_Nature_Node)

                        Dim fLienExterne_Identification_Node As XmlElement = My_Xml_Doc.CreateElement("Identification", My_Xml_Doc.DocumentElement.NamespaceURI)
                        fLienExterne_Identification_Node.InnerText = liens_externes_table(rr).ID
                        fLienExterne_Node.AppendChild(fLienExterne_Identification_Node)

                        Dim fLienExterne_InfoModeEnvoi_Node As XmlElement = My_Xml_Doc.CreateElement("InfoModeEnvoi", My_Xml_Doc.DocumentElement.NamespaceURI)
                        fLienExterne_InfoModeEnvoi_Node.InnerText = "TELETRANS"
                        fLienExterne_Node.AppendChild(fLienExterne_InfoModeEnvoi_Node)

                        Document_node.AppendChild(fLienExterne_Node)



                    Next
                    My_Xml_Doc.DocumentElement.AppendChild(Document_node)

                Else
                End If
            End If
        Next
        My_Xml_Doc.Save(Config.LocalNetwork_ServerName & "\scor\index\tempmisiak\E-" & My_Xml_Doc.GetElementsByTagName("Identite").Item(0).InnerText & "-ENTSCANORDO-" & Compostage & ".xml")
        ' Chiffrement des documents
        My.Computer.FileSystem.CreateDirectory(Config.LocalNetwork_ServerName & "\scor\archive\" & My_Xml_Doc.GetElementsByTagName("Identite").Item(0).InnerText & "-ENTSCANORDO-" & Compostage)
        My.Computer.FileSystem.CopyFile(Config.LocalNetwork_ServerName & "\scor\index\tempmisiak\E-" & My_Xml_Doc.GetElementsByTagName("Identite").Item(0).InnerText & "-ENTSCANORDO-" & Compostage & ".xml", _
        Config.LocalNetwork_ServerName & "\scor\archive\" & My_Xml_Doc.GetElementsByTagName("Identite").Item(0).InnerText & "-ENTSCANORDO-" & Compostage & "\E-" & My_Xml_Doc.GetElementsByTagName("Identite").Item(0).InnerText & "-ENTSCANORDO-" & Compostage & ".xml")
        Dim file_to_encryt = Dir(Config.LocalNetwork_ServerName & "\scor\index\tempmisiak\*.*")
        While file_to_encryt <> ""
            If InStr(file_to_encryt, "E-") <> 1 And InStr(file_to_encryt, ".pkcs7") = 0 Then



                'création de cerificats FAUX pour initialisation, les certificats VRAIS devraient être reçu en retour, le lot SCOR sera à retransmettre
                If My.Computer.FileSystem.FileExists(Config.LocalNetwork_ServerName & "\scor\certificats\" & to_ & ".pem") = False Then
                    My.Computer.FileSystem.CopyFile(Config.LocalNetwork_ServerName & "\scor\certificats\01.99@01.cnda.scor.rss.fr.pem", Config.LocalNetwork_ServerName & "\scor\certificats\" & to_ & ".pem")
                End If



                'convertir les certificats: "openssl x509 -inform der -in certificate.cer -out certificate.pem"
                'encrypt: "openssl cms -binary -encrypt -in  file_to_encryt -out file_to_encryt.pkcs7 -aes-128-cbc -outform DER certificats.pem"
                ShellandWait("C:\OpenSSL-Win32\bin", "openssl.exe", "cms -binary -encrypt -in " & Config.LocalNetwork_ServerName & "\scor\index\tempmisiak\" & file_to_encryt & _
                             " -out " & Config.LocalNetwork_ServerName & "\scor\index\tempmisiak\" & Mid(file_to_encryt, 1, InStr(file_to_encryt, ".")) & "pkcs7 -aes-128-cbc -outform DER " & _
                             Config.LocalNetwork_ServerName & "\scor\certificats\" & to_ & ".pem")

                My.Computer.FileSystem.MoveFile(Config.LocalNetwork_ServerName & "\scor\index\tempmisiak\" & file_to_encryt, Config.LocalNetwork_ServerName & "\scor\archive\" & My_Xml_Doc.GetElementsByTagName("Identite").Item(0).InnerText & "-ENTSCANORDO-" & Compostage & "\" & file_to_encryt, True)

            End If
            file_to_encryt = Dir()

        End While

        '[RG_TT037] Préparer le fichier du lot de justificatifs compressé
        System.IO.Compression.ZipFile.CreateFromDirectory(Config.LocalNetwork_ServerName & "\scor\index\tempmisiak", Config.LocalNetwork_ServerName & "\scor\Fichiers\" & _
                                     My_Xml_Doc.GetElementsByTagName("Identite").Item(0).InnerText & "-ENTSCANORDO-" & Compostage & ".zip")
        If My.Computer.FileSystem.DirectoryExists(Config.LocalNetwork_ServerName & "\scor\index\tempmisiak") Then
            My.Computer.FileSystem.DeleteDirectory(Config.LocalNetwork_ServerName & "\scor\index\tempmisiak", FileIO.DeleteDirectoryOption.DeleteAllContents)
        End If

        Return Config.LocalNetwork_ServerName & "\scor\Fichiers\" & My_Xml_Doc.GetElementsByTagName("Identite").Item(0).InnerText & "-ENTSCANORDO-" & Compostage & ".zip"

    End Function

    Public Sub TT03_cdrom(ByVal Num_Lot_FSE As String, ByVal rep_dest As String)

        'TT03.01 : Préparer les dossiers de justificatifs
        'xml file:Instance_SCANORDO_V02_03
        Dim My_Xml_Doc As New XmlDocument
        My_Xml_Doc.Load(Config.LocalNetwork_ServerName & "\scor\XML\ENTSCANORDO_V02_08.xml")
        Dim XMLelementliste As XmlNodeList

        Dim my_fact_datatable = COMPTOIR_MAIN.FacturesTableAdapter.GetDataBy_Ref_Lot(Num_Lot_FSE, Me.LotsTableAdapter.GetDataByRéférence(CDec(Num_Lot_FSE), "@@@@@").Item(0)._Date, "XXXXXXXXXXXXXXXXXXXXXX", "XXXXXXXXXXXXXXXXXXXXXX")
        Dim my_lot_datatable = Me.LotsTableAdapter.GetDataByRéférence(Num_Lot_FSE, "XXXXXXXXXXXXXXXXXXXXXX")
        '[RG_TT026] Préparer l’entité «Entête SEH lot de justificatifs»
        XMLelementliste = My_Xml_Doc.GetElementsByTagName("Entete")
        Dim Compostage As String = Format(Now, "yyyyMMddHHmmss") & "00001"
        Dim IDPS As String
        ValeurChamp = "@@@@@@@@"
        TailleMax = 8
        SGD_LireChamp(NumeroSessionCPS, 2, Occurence_Grp2, 9, ValeurChamp, TailleMax)
        IDPS = ValeurChamp
        ValeurChamp = "@"
        TailleMax = 1
        SGD_LireChamp(NumeroSessionCPS, 2, Occurence_Grp2, 10, ValeurChamp, TailleMax)
        IDPS = IDPS & ValeurChamp
        'XMLelementliste.Item(0).Item("Identification").InnerText = my_fact_datatable(0).G1120C1.ToString() & my_fact_datatable(0).G1120C2.ToString() & "-" & Compostage
        XMLelementliste.Item(0).Item("Identification").InnerText = IDPS & "-" & Compostage
        XMLelementliste.Item(0).Item("Temps").InnerText = Format(Now, "yyyy-MM-dd") & "T" & Format(Now, "HH:mm:ss")
        If Config.Logiciel_ModeFonctionement = "Test" Then
            XMLelementliste.Item(0).Item("Fonction").InnerText = "53" '53 pour test, 9 pour réel
        Else
            XMLelementliste.Item(0).Item("Fonction").InnerText = "9" '53 pour test, 9 pour réel
        End If

        Dim nbrFSE_html As Integer
        Dim nbrpiècesjustif_html As Integer
        Dim NbrDoc As Integer
        Dim nombre_factures_dans_lot As Integer = my_fact_datatable.Rows.Count
        'For r = 0 To nombre_factures_dans_lot - 1
        For r = 0 To my_fact_datatable.Rows.Count - 1
            NbrDoc = NbrDoc + 1 'fichier d'index, pas de verification de sa présence, il est censé exister
            Dim num_facture As String = my_fact_datatable(r).G1110C1
            Dim file = Dir(Config.LocalNetwork_ServerName & "\scor\doc\" & num_facture & "_*.pdf")
            While file <> ""
                NbrDoc = NbrDoc + 1
                file = Dir()
            End While
        Next

        If NbrDoc = 0 Then
            Exit Sub
        End If
        XMLelementliste.Item(0).Item("NbrDoc").InnerText = NbrDoc.ToString
        XMLelementliste.Item(0).Item("InfoIDXLOT").InnerText = "01"
        XMLelementliste.Item(0).Item("InfoNBLOT").InnerText = "01"
        XMLelementliste.Item(0).Item("InfoModeEnvoi").InnerText = "CDROM"

        '[RG_TT027] Préparer l’entité «Emetteur lot de justificatifs »
        XMLelementliste = My_Xml_Doc.GetElementsByTagName("Emetteur")
        XMLelementliste.Item(0).Item("Identite").InnerText = my_fact_datatable(0).G1120C1.ToString() & my_fact_datatable(0).G1120C2.ToString()
        XMLelementliste.Item(0).Item("Nom").InnerText = my_lot_datatable(0).G8_G88_C4
        If my_fact_datatable(0).G1120C13.ToString() & my_fact_datatable(0).G1120C14.ToString() <> "" Then
            XMLelementliste.Item(0).Item("RPPS").InnerText = my_fact_datatable(0).G1120C13.ToString() & my_fact_datatable(0).G1120C14.ToString()
        Else
            XMLelementliste.Item(0).RemoveChild(XMLelementliste.Item(0).Item("RPPS"))
        End If
        XMLelementliste.Item(0).Item("Qualite").InnerText = "OPORDO"
        XMLelementliste.Item(0).Item("Region").InnerText = "41"
        XMLelementliste.Item(0).Item("SpecialitePS").InnerText = "50"

        '[RG_TT028] Préparer l’entité «Télécommunication»
        XMLelementliste = My_Xml_Doc.GetElementsByTagName("Telecom")
        XMLelementliste.Item(0).Item("Type").InnerText = "EM"
        If Config.OCT_UtilisationOCT = False Then
            XMLelementliste.Item(0).Item("Numero").InnerText = "PS:" + Config.Scor_from
        Else
            If Config.Scor_Dest_ARL = "PS" Then
                XMLelementliste.Item(0).Item("Numero").InnerText = "PS:" + Config.Scor_from
            ElseIf Config.Scor_Dest_ARL = "OCT" Then
                XMLelementliste.Item(0).Item("Numero").InnerText = "PRT:" + Config.Scor_Adr_OCT
            ElseIf Config.Scor_Dest_ARL = "PS/OCT" Then
                XMLelementliste.Item(0).Item("Numero").InnerText = "PS:" + Config.Scor_from + ";PRT:" + Config.Scor_Adr_OCT
            End If

        End If


        '[RG_TT030] Préparer l’entité « Destinataire lot de justificatifs »
        XMLelementliste = My_Xml_Doc.GetElementsByTagName("Recepteur")

        XMLelementliste.Item(0).Item("Identite").InnerText = my_fact_datatable(0).G1310C1.ToString() & my_fact_datatable(0).G1310C4.ToString()
        XMLelementliste.Item(0).Item("Qualite").InnerText = "OPAMO"

        '[RG_TT032] Préparer l’entité «Identification lot FSE»
        XMLelementliste = My_Xml_Doc.GetElementsByTagName("Trace")
        XMLelementliste.Item(0).Item("Activite").InnerText = "LOTFSE"
        Dim date_lot As String = my_lot_datatable(0)._Date
        XMLelementliste.Item(0).Item("Temps").InnerText = Mid(date_lot, 1, 4) & "-" & Mid(date_lot, 5, 2) & "-" & Mid(date_lot, 7, 2) & "T00:00:00"
        XMLelementliste.Item(0).Item("Archive").InnerText = Num_Lot_FSE
        If Mid(my_lot_datatable(0).CRL, 19, 1) = "S" Then  '[RG_TT048] Lier le mode de sécurisation FSE
            XMLelementliste.Item(0).Item("InfoType").InnerText = "1"
        Else
            XMLelementliste.Item(0).Item("InfoType").InnerText = "2"
        End If
        'XMLelementliste.Item(0).Item("InfoNBFACT").InnerText = my_lot_datatable(0).NombreDeFSE
        XMLelementliste.Item(0).Item("InfoNBFACT").InnerText = nombre_factures_dans_lot.ToString
        While XMLelementliste.Item(0).Item("InfoNBFACT").InnerText.Length < 3
            XMLelementliste.Item(0).Item("InfoNBFACT").InnerText = "0" & XMLelementliste.Item(0).Item("InfoNBFACT").InnerText
        End While

        '[RG_TT033] Préparer l’entité «Agrément»
        XMLelementliste = My_Xml_Doc.GetElementsByTagName("Agrement")
        'XMLelementliste.Item(0).Item("Id").InnerText = "TESTCNDA"
        'XMLelementliste.Item(0).Item("Version").InnerText = "1409"
        XMLelementliste.Item(0).Item("Id").InnerText = "GSNW3B00"
        XMLelementliste.Item(0).Item("Version").InnerText = "0110"

        Dim borderau As String = rep_dest & "Bordereau_ " & Mid(my_lot_datatable.Item(0).CRL, 1, 9) & "_" & Mid(my_lot_datatable.Item(0).CRL, 12, 2) & "_" & _
            Mid(my_lot_datatable.Item(0).CRL, 14, 3) & "_" & my_lot_datatable.Item(0).G13C5 & "_" & Mid(my_lot_datatable.Item(0)._Date, 1, 8) & ".htm"

        My.Computer.FileSystem.WriteAllText(borderau, "<HTML>" & vbCrLf, True)
        My.Computer.FileSystem.WriteAllText(borderau, "<BODY>" & vbCrLf, True)
        My.Computer.FileSystem.WriteAllText(borderau, "Bordereau récapitulatif des ordonnances pour le régime " & Mid(my_lot_datatable.Item(0).CRL, 12, 2) & "<BR>" & vbCrLf, True)
        My.Computer.FileSystem.WriteAllText(borderau, "PRATICIEN : " & Mid(my_lot_datatable.Item(0).CRL, 1, 9) & " pharmacie" & "<BR>" & vbCrLf, True)
        My.Computer.FileSystem.WriteAllText(borderau, "Lot : " & my_lot_datatable.Item(0).G13C5 & "  du " & Mid(my_lot_datatable.Item(0)._Date, 1, 8) & "<BR>" & vbCrLf, True)
        My.Computer.FileSystem.WriteAllText(borderau, "<table  cellspacing=" + Chr(34) + "0" + Chr(34) + "cellpadding=" + Chr(34) + "0" + Chr(34) + ">" + vbCrLf, True)
        My.Computer.FileSystem.WriteAllText(borderau, "<tr>" + vbCrLf, True)
        My.Computer.FileSystem.WriteAllText(borderau, "<td style=" + Chr(34) + "border:1px solid black" + Chr(34) + ">" & "Lot&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbspN°Facture" & "<td>" & Chr(10), True)
        My.Computer.FileSystem.WriteAllText(borderau, "<td style=" + Chr(34) + "border:1px solid black" + Chr(34) + ">" & "Matricule&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbspClé&nbsp;&nbsp;&nbsp;&nbspDate de naissance Bénéficiaire&nbsp;&nbsp;&nbsp;&nbsp;Rang" & "<td>" & Chr(10), True)
        My.Computer.FileSystem.WriteAllText(borderau, "<td style=" + Chr(34) + "border:1px solid black" + Chr(34) + ">" & "Mt Caisse" & "<td>" & Chr(10), True)
        My.Computer.FileSystem.WriteAllText(borderau, "<td style=" + Chr(34) + "border:1px solid black" + Chr(34) + ">" & "Mt Total Facture" & "<td>" & Chr(10), True)
        My.Computer.FileSystem.WriteAllText(borderau, "<td style=" + Chr(34) + "border:1px solid black" + Chr(34) + ">" & "Caisse" & "<td>" & Chr(10), True)
        My.Computer.FileSystem.WriteAllText(borderau, "</tr>" + vbCrLf, True)


        Dim num_odre As Integer = 0
        For r = 0 To my_fact_datatable.Rows.Count - 1

            If My.Computer.FileSystem.FileExists(Config.LocalNetwork_ServerName & "\scor\index\" & my_fact_datatable(r).G1110C1 & ".xml") Then
                'fichier index
                num_odre = num_odre + 1
                Dim num_odre_string As String = num_odre.ToString
                While num_odre_string.Length < 3
                    num_odre_string = "0" & num_odre_string
                End While

                '[RG_TT034] Préparer l’entité «Lien fichier du dossier de justificatifs »
                'champ à renseigner dans l'index lors de ma mise en lot (non renseigné à [RG_TT007])
                Dim D_xml As New XmlDocument
                D_xml.Load(Config.LocalNetwork_ServerName & "\scor\index\" & my_fact_datatable(r).G1110C1 & ".xml")
                Dim D_XMLelementliste As XmlNodeList
                D_XMLelementliste = D_xml.GetElementsByTagName("SCANORDO")
                D_XMLelementliste.Item(0).Item("Identifiant").InnerText = "D-" & num_odre_string
                D_XMLelementliste.Item(0).Item("Identifiant").InnerText = num_odre_string
                D_xml.Save(Config.LocalNetwork_ServerName & "\scor\index\" & my_fact_datatable(r).G1110C1 & ".xml")


                My.Computer.FileSystem.CopyFile(Config.LocalNetwork_ServerName & "\scor\index\" & my_fact_datatable(r).G1110C1 & ".xml", _
                                                rep_dest & "D-" & num_odre_string & ".xml")
                '''''''''''''''
                Dim Lien_Node As XmlNode = My_Xml_Doc.CreateElement("Lien", My_Xml_Doc.DocumentElement.NamespaceURI)

                Dim Lien_Adresse_Node As XmlElement = My_Xml_Doc.CreateElement("Adresse", My_Xml_Doc.DocumentElement.NamespaceURI)

                Lien_Adresse_Node.InnerText = "D-" & num_odre_string & ".xml"



                Lien_Node.AppendChild(Lien_Adresse_Node)

                Dim Lien_Type_Node As XmlElement = My_Xml_Doc.CreateElement("Type", My_Xml_Doc.DocumentElement.NamespaceURI)
                'Lien_Type_Node.InnerText = "XML"
                Lien_Type_Node.InnerText = "XML"
                Lien_Type_Node.SetAttribute("Q", "XML")
                Lien_Node.AppendChild(Lien_Type_Node)

                Dim Mindex_Node As XmlNode = My_Xml_Doc.CreateElement("Mindex", My_Xml_Doc.DocumentElement.NamespaceURI)

                Dim Mindex_Profil_Node As XmlElement = My_Xml_Doc.CreateElement("Profil", My_Xml_Doc.DocumentElement.NamespaceURI)
                Mindex_Profil_Node.InnerText = "SCANORDO"
                Mindex_Node.AppendChild(Mindex_Profil_Node)

                Dim Mindex_Identification_Node As XmlElement = My_Xml_Doc.CreateElement("Identification", My_Xml_Doc.DocumentElement.NamespaceURI)
                Mindex_Identification_Node.InnerText = num_odre_string
                Mindex_Node.AppendChild(Mindex_Identification_Node)

                Dim index_xmldoc As New XmlDocument
                index_xmldoc.Load(rep_dest & "D-" & num_odre_string & ".xml")

                Dim Mindex_Temps_Node As XmlElement = My_Xml_Doc.CreateElement("Temps", My_Xml_Doc.DocumentElement.NamespaceURI)
                Mindex_Temps_Node.InnerText = index_xmldoc.GetElementsByTagName("Temps").Item(0).InnerText
                Mindex_Node.AppendChild(Mindex_Temps_Node)

                Dim Mindex_Descriptif_Node As XmlElement = My_Xml_Doc.CreateElement("Descriptif", My_Xml_Doc.DocumentElement.NamespaceURI)
                Mindex_Descriptif_Node.InnerText = "1"
                Mindex_Node.AppendChild(Mindex_Descriptif_Node)

                Dim Mindex_Archive_Node As XmlElement = My_Xml_Doc.CreateElement("Archive", My_Xml_Doc.DocumentElement.NamespaceURI)
                Mindex_Archive_Node.InnerText = my_fact_datatable(r).G1110C1
                While Mindex_Archive_Node.InnerText.Length < 9
                    Mindex_Archive_Node.InnerText = "0" & Mindex_Archive_Node.InnerText
                End While
                Mindex_Node.AppendChild(Mindex_Archive_Node)

                Dim Document_node As XmlElement
                Document_node = My_Xml_Doc.CreateElement("Document", My_Xml_Doc.DocumentElement.NamespaceURI)
                Document_node.AppendChild(Mindex_Node)
                Document_node.AppendChild(Lien_Node)

                Dim file As String
                file = Dir(Config.LocalNetwork_ServerName & "\scor\doc\" & my_fact_datatable(r).G1110C1 & "_*_*.pdf")

                Dim indice_pièce As Integer '[RG_TT018] Nom physique du fichier PDF de justificatif
                indice_pièce = 0
                If file <> "" Then
                    nbrFSE_html = nbrFSE_html + 1
                End If

                While file <> ""
                    nbrpiècesjustif_html = nbrpiècesjustif_html + 1
                    indice_pièce = indice_pièce + 1
                    Dim indice_pièce_string As String = indice_pièce.ToString
                    While indice_pièce_string.Length < 3
                        indice_pièce_string = "0" & indice_pièce_string
                    End While
                    Dim adresse As String
                    adresse = "P-" + num_odre_string + "-" + indice_pièce_string + ".pdf"
                    Dim fLien_Node As XmlNode = My_Xml_Doc.CreateElement("Lien", My_Xml_Doc.DocumentElement.NamespaceURI)


                    Dim fLien_Adresse_Node As XmlElement = My_Xml_Doc.CreateElement("Adresse", My_Xml_Doc.DocumentElement.NamespaceURI)
                    fLien_Adresse_Node.InnerText = adresse
                    fLien_Node.AppendChild(fLien_Adresse_Node)

                    Dim fLien_Type_Node As XmlElement = My_Xml_Doc.CreateElement("Type", My_Xml_Doc.DocumentElement.NamespaceURI)
                    fLien_Type_Node.SetAttribute("Q", "PDF")
                    fLien_Type_Node.InnerText = "PDF"
                    fLien_Node.AppendChild(fLien_Type_Node)

                    'Dim fLien_Version_Node As XmlElement = My_Xml_Doc.CreateElement("Version", My_Xml_Doc.DocumentElement.NamespaceURI)
                    'fLien_Version_Node.InnerText = "02.02"
                    'fLien_Node.AppendChild(fLien_Version_Node)

                    Dim fLien_Nature_Node As XmlElement = My_Xml_Doc.CreateElement("Nature", My_Xml_Doc.DocumentElement.NamespaceURI)
                    fLien_Nature_Node.InnerText = Mid(file, InStrRev(file, "_") + 1, 4)
                    fLien_Node.AppendChild(fLien_Nature_Node)

                    Dim fLien_Identification_Node As XmlElement = My_Xml_Doc.CreateElement("Identification", My_Xml_Doc.DocumentElement.NamespaceURI)
                    fLien_Identification_Node.InnerText = ScanOrdo.SCOR_PJTableAdapter.GetDataBy_Fichier(file)(0).ID
                    fLien_Node.AppendChild(fLien_Identification_Node)

                    Document_node.AppendChild(fLien_Node)

                    My.Computer.FileSystem.CopyFile(Config.LocalNetwork_ServerName & "\scor\doc\" + file, rep_dest + Mid(adresse, 1, InStrRev(adresse, ".")) + "pdf")
                    file = Dir()

                End While
                My_Xml_Doc.DocumentElement.AppendChild(Document_node)
                '-----------------------------------------------------------------------------------------------------------------------------------------
                'lien externe papier
                Dim file_ext As String
                file_ext = Dir(Config.LocalNetwork_ServerName & "\scor\doc\papier\" & my_fact_datatable(r).G1110C1 & "_*_*.pdf")

                While file_ext <> ""
                    Dim fLienExterne_Node As XmlNode = My_Xml_Doc.CreateElement("LienExterne", My_Xml_Doc.DocumentElement.NamespaceURI)
                    Dim fLienExterne_Type_Node As XmlElement = My_Xml_Doc.CreateElement("Type", My_Xml_Doc.DocumentElement.NamespaceURI)
                    fLienExterne_Type_Node.SetAttribute("Q", "PAPIER")
                    fLienExterne_Type_Node.InnerText = "PAPIER"
                    fLienExterne_Node.AppendChild(fLienExterne_Type_Node)

                    Dim fLienExterne_Nature_Node As XmlElement = My_Xml_Doc.CreateElement("Nature", My_Xml_Doc.DocumentElement.NamespaceURI)
                    fLienExterne_Nature_Node.InnerText = Mid(file_ext, InStrRev(file_ext, "_") + 1, 4)
                    fLienExterne_Node.AppendChild(fLienExterne_Nature_Node)

                    'Dim fLienExterne_Identification_Node As XmlElement = My_Xml_Doc.CreateElement("Identification", My_Xml_Doc.DocumentElement.NamespaceURI)
                    'fLienExterne_Identification_Node.InnerText = ""
                    'fLienExterne_Node.AppendChild(fLienExterne_Identification_Node)

                    Dim fLienExterne_InfoModeEnvoi_Node As XmlElement = My_Xml_Doc.CreateElement("InfoModeEnvoi", My_Xml_Doc.DocumentElement.NamespaceURI)
                    fLienExterne_InfoModeEnvoi_Node.InnerText = "PAPIER"
                    fLienExterne_Node.AppendChild(fLienExterne_InfoModeEnvoi_Node)

                    Document_node.AppendChild(fLienExterne_Node)


                    file_ext = Dir()

                End While
                My_Xml_Doc.DocumentElement.AppendChild(Document_node)
                '-----------------------------------------------------------------------------------------------------------------------------------------
                'lien externe pièces déja transmises
                Dim liens_externes_table = ScanOrdo.SCOR_PJTableAdapter.GetDataBy_Num_Facture_and_Statut_Transmission(my_fact_datatable(r).G1110C1, "DOCUMENT EXTERNE")

                For rr = 0 To liens_externes_table.Rows.Count - 1

                    Dim fLienExterne_Node As XmlNode = My_Xml_Doc.CreateElement("LienExterne", My_Xml_Doc.DocumentElement.NamespaceURI)


                    Dim fLienExterne_Type_Node As XmlElement = My_Xml_Doc.CreateElement("Type", My_Xml_Doc.DocumentElement.NamespaceURI)
                    fLienExterne_Type_Node.SetAttribute("Q", "PDF")
                    'fLien_Type_Node.InnerText = "PDF"
                    fLienExterne_Type_Node.InnerText = "PDF"
                    fLienExterne_Node.AppendChild(fLienExterne_Type_Node)



                    Dim fLienExterne_Nature_Node As XmlElement = My_Xml_Doc.CreateElement("Nature", My_Xml_Doc.DocumentElement.NamespaceURI)
                    fLienExterne_Nature_Node.InnerText = Mid(liens_externes_table(rr).ID, InStr(liens_externes_table(rr).ID, ".") + 1, 4)
                    fLienExterne_Node.AppendChild(fLienExterne_Nature_Node)

                    Dim fLienExterne_Identification_Node As XmlElement = My_Xml_Doc.CreateElement("Identification", My_Xml_Doc.DocumentElement.NamespaceURI)
                    fLienExterne_Identification_Node.InnerText = liens_externes_table(rr).ID
                    fLienExterne_Node.AppendChild(fLienExterne_Identification_Node)

                    Dim fLienExterne_InfoModeEnvoi_Node As XmlElement = My_Xml_Doc.CreateElement("InfoModeEnvoi", My_Xml_Doc.DocumentElement.NamespaceURI)
                    fLienExterne_InfoModeEnvoi_Node.InnerText = "TELETRANS"
                    fLienExterne_Node.AppendChild(fLienExterne_InfoModeEnvoi_Node)

                    Document_node.AppendChild(fLienExterne_Node)



                Next
                My_Xml_Doc.DocumentElement.AppendChild(Document_node)

                My.Computer.FileSystem.WriteAllText(borderau, "<tr>" & vbCrLf, True)
                Dim renouv As Boolean = False
                Dim lignesfacture = Me.Facture_LigneFactureTableAdapter1.GetDataByNumFacture(my_fact_datatable(r).G1110C1)
                For rrr = 0 To lignesfacture.Rows.Count - 1
                    If lignesfacture(rrr).G1850C2 <> "" Then
                        renouv = True
                    End If
                Next
                If renouv = False Then
                    My.Computer.FileSystem.WriteAllText(borderau, "<td style=" + Chr(34) + "border:1px solid black" + Chr(34) + ">" & "&nbsp;&nbsp" & my_fact_datatable(r).Num_Lot_FSE & "&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp" & my_fact_datatable(r).G1110C1 + "<td>" & vbCrLf, True)
                Else
                    My.Computer.FileSystem.WriteAllText(borderau, "<td style=" + Chr(34) + "border:1px solid black" + Chr(34) + ">" & "R&nbsp" & my_fact_datatable(r).Num_Lot_FSE & "&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp" & my_fact_datatable(r).G1110C1 + "<td>" & vbCrLf, True)
                End If
                My.Computer.FileSystem.WriteAllText(borderau, "<td style=" + Chr(34) + "border:1px solid black" + Chr(34) + ">" & my_fact_datatable(r).G1130C2 & "&nbsp;&nbsp" & my_fact_datatable(r).G1130C3 & "&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp" & Mid(my_fact_datatable(r).G1130C4, 1, 8) & "&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp" & my_fact_datatable(r).G1130C5 & "<td>" & Chr(10), True)
                My.Computer.FileSystem.WriteAllText(borderau, "<td style=" + Chr(34) + "border:1px solid black" + Chr(34) + ">" + (my_fact_datatable(r).G1910C3 / 100).ToString + "<td>" & vbCrLf, True)
                My.Computer.FileSystem.WriteAllText(borderau, "<td style=" + Chr(34) + "border:1px solid black" + Chr(34) + ">" + (my_fact_datatable(r).G1910C2 / 100).ToString + "<td>" & vbCrLf, True)
                My.Computer.FileSystem.WriteAllText(borderau, "<td style=" + Chr(34) + "border:1px solid black" + Chr(34) + ">" + my_fact_datatable(r).G1310C3 + my_fact_datatable(r).G1310C4 + "<td>" & vbCrLf, True)
                My.Computer.FileSystem.WriteAllText(borderau, "</tr>" + vbCrLf, True)
            End If


        Next
        My_Xml_Doc.Save(rep_dest & "E-" & My_Xml_Doc.GetElementsByTagName("Identite").Item(0).InnerText & "-ENTSCANORDO-" & Compostage & ".xml")
        My.Computer.FileSystem.WriteAllText(borderau, "</table>" & vbCrLf, True)
        Dim nbrpiècesjustif_html_strg = nbrpiècesjustif_html.ToString
        While nbrpiècesjustif_html_strg.Length < 3
            nbrpiècesjustif_html_strg = "0" & nbrpiècesjustif_html_strg
        End While
        Dim nbrFSE_html_strg = nbrFSE_html.ToString
        While nbrFSE_html_strg.Length < 3
            nbrFSE_html_strg = "0" & nbrFSE_html_strg
        End While
        My.Computer.FileSystem.WriteAllText(borderau, "TOTAL GENERAL DU BORDEREAU : Nombre de FSE " & nbrFSE_html_strg & "&nbsp;&nbsp;&nbsp;&nbspNombre pièces justificatives " & _
                                            nbrpiècesjustif_html_strg & "<BR>" & vbCrLf, True)
        My.Computer.FileSystem.WriteAllText(borderau, "R= Renouvellement<BR>" & vbCrLf, True)
        My.Computer.FileSystem.WriteAllText(borderau, "N° facture=FSE<BR>" & vbCrLf, True)
        My.Computer.FileSystem.WriteAllText(borderau, "CAISSE = Organisme de rattachement<BR>" & vbCrLf, True)
        My.Computer.FileSystem.WriteAllText(borderau, "</BODY>" & vbCrLf, True)
        My.Computer.FileSystem.WriteAllText(borderau, "</HTML>" & vbCrLf, True)

        'My.Computer.FileSystem.CopyDirectory(rep_dest, Mid(Mid(rep_dest, 1, rep_dest.Length - 1), 1, InStrRev(rep_dest, "\")) & Mid(my_lot_datatable.Item(0).CRL, 1, 9) & "_lot_" _
        '                                       & my_lot_datatable.Item(0).G13C5 & "_du_" & Mid(my_lot_datatable.Item(0)._Date, 1, 8) & "_Nb_" & nbrFSE_html_strg)
        'My.Computer.FileSystem.DeleteDirectory(rep_dest, FileIO.DeleteDirectoryOption.DeleteAllContents)

        My.Computer.FileSystem.RenameDirectory(rep_dest, _
                Mid(my_lot_datatable.Item(0).CRL, 1, 9) & "_lot_" & my_lot_datatable.Item(0).G13C5 & "_du_" & Mid(my_lot_datatable.Item(0)._Date, 1, 8) & "_Nb_" & nbrFSE_html_strg)

    End Sub
    Public Sub SCOR_SendMail(ByVal Référence_Fichier As String, ByVal to_ As String, ByVal numlot As String, ByVal Retransmission As Boolean)

        'to_ = "julien.misiak@orange.fr"

        Try

            Dim Subject, ContentType As String

            'Subject
            Subject = Mid(Référence_Fichier, 1, InStrRev(Référence_Fichier, ".") - 1)
            Subject = Mid(Subject, Subject.Length - 18)
            Dim IDPS As String
            ValeurChamp = "@@@@@@@@"
            TailleMax = 8
            SGD_LireChamp(NumeroSessionCPS, 2, Occurence_Grp2, 9, ValeurChamp, TailleMax)
            IDPS = ValeurChamp
            ValeurChamp = "@"
            TailleMax = 1
            SGD_LireChamp(NumeroSessionCPS, 2, Occurence_Grp2, 10, ValeurChamp, TailleMax)
            IDPS = IDPS & ValeurChamp
            Subject = "SO211000/" & IDPS & "/" & Subject
            'Subject = InputBox("", "", Subject)

            'Subject = "SO210000/496245570/2012012711140023006"
            'Subject = InputBox("subject", "", Subject)
            '--------------------------------------------------------------------------------------------------------------------------
            ContentType = "Application/EDI-consent"
            '--------------------------------------------------------------------------------------------------------------------------
            Dim message As New MailMessage(Config.Scor_from, to_, Subject, Nothing)
            Dim mimeType As ContentType = New ContentType("Application/EDI-consent")
            mimeType.MediaType = "Application/EDI-consent"
            ' Dim mimetype2 As New ContentDisposition
            Dim alternate As New AlternateView(Référence_Fichier, mimeType)
            Dim cd As String
            If Config.Logiciel_ModeFonctionement = "Test" Then
                message.Headers.Add("Content-Description", "ORDOTEST/SEH")
                cd = "ORDOTEST/SEH"
            Else
                message.Headers.Add("Content-Description", "ORDO/SEH")
                cd = "ORDO/SEH"
            End If



            alternate.TransferEncoding = TransferEncoding.Base64
            message.AlternateViews.Add(alternate)
            Dim client = New SmtpClient(Config.SMTP_Serveur_Externe, Config.SMTP_Serveur_Externe_port)
            If Config.SMTP_Serveur_Externe_User <> "" Then
                client.Credentials = New System.Net.NetworkCredential(Config.SMTP_Serveur_Externe_User, Config.SMTP_Serveur_Externe_Password)
            ElseIf Config.SMTP_Serveur_Externe_port = 587 Then
                client.Credentials = New System.Net.NetworkCredential(Config.POP3_User, Config.POP3_Password)
            Else
                client.UseDefaultCredentials = True
            End If
            client.Send(message)
            alternate.Dispose()
            message.Dispose()
            Try
                My.Computer.FileSystem.MoveFile(Référence_Fichier, Mid(Référence_Fichier, 1, InStrRev(Référence_Fichier, "\")) & "Transmis" & Mid(Référence_Fichier, InStrRev(Référence_Fichier, "\")), True)
            Catch ex As Exception
                trace_log("Problème de deplacement fichier scor après transmission (SCOR_SendMail)" & vbCrLf & ex.Message)
            End Try

            My.Computer.FileSystem.WriteAllText(Config.LocalNetwork_ServerName & "\scor\traces\" & Format(Now, "yyyyMMdd") & "_SCOR.txt", Format(Now, "dd MM yyyy HH:mm:ss") & Chr(13) & to_ & Chr(13) & "Subject:" & Subject & Chr(13) & _
                                                Mid(Référence_Fichier, InStrRev(Référence_Fichier, "\") + 1) + Chr(13) + cd + Chr(13) + Chr(13) + Chr(13), True)


            If Retransmission = False Then
                If Me.LotsTableAdapter.GetDataByRéférence(Val(numlot), "@@@@@@@").Item(0).NombreTransmission > 1 Then
                    Me.SCOR_lotsTableAdapter.Insert("", numlot, "RETRANSMIS", Subject, to_, "")
                Else
                    Me.SCOR_lotsTableAdapter.Insert("", numlot, "EMIS", Subject, to_, "")
                End If
            Else
                Me.SCOR_lotsTableAdapter.Insert("", numlot, "RETRANSMIS", Subject, to_, "")
            End If
        Catch ex As Exception
            MyMsg_Box.Presentation("Officine", "ERREUR TRANSMISSION" + Chr(10) + ex.ToString, False, "", False, "", True, "OK")
            MyMsg_Box.ShowDialog()
        End Try
        SCOR_affiche_Lots()
    End Sub

    Private Sub SCOR_GO(ByVal Liste_Lots As List(Of String), ByVal Retransmission As Boolean)


        Dim compteur_lot = 0

        For Each Lot In Liste_Lots
            Try


                compteur_lot = compteur_lot + 1
                Bandeau_info_bas_show("SCOR: LOT " & Lot & "  Traitement en cours... " & compteur_lot.ToString & "/" & Liste_Lots.Count.ToString)
                Dim code_régime As String = Mid(Me.LotsTableAdapter.GetDataByRéférence(Lot, "XXXXXXXXXXXXXXXXXXXXXX").Item(0).G13C4.ToString, 7, 2)

                Dim to_ As String = ""
                'To
                If Config.Logiciel_ModeFonctionement = "Test" Then
                    Select Case code_régime
                        Case "01"
                            to_ = "01.99@01.cnda.scor.rss.fr"
                        Case "02"
                            to_ = "02.99@02.cnda.scor.rss.fr"

                    End Select
                    'to_ = "julien.misiak@orange.fr"
                Else
                    If Config.OCT_UtilisationOCT = True And Config.Scor_Transmission_via_OCT = True Then
                        to_ = Config.Scor_Adr_OCT
                    Else
                        Select Case code_régime
                            Case "01"
                                to_ = "01." & Config.Scor_CodeRégion.ToString & "@01.scor.rss.fr"
                            Case Else
                                to_ = code_régime & "@" + code_régime & ".scor.rss.fr"
                        End Select
                    End If
                End If
                'to_ = "01.88@01.scor.rss.fr" 'tests AR_P
                'calcul taille des lots de scor
                Dim list_of_facture As New List(Of String)
                Dim list_of_DocsSize As New List(Of Long)

                Dim factures_table = COMPTOIR_MAIN.FacturesTableAdapter.GetDataBy_Ref_Lot(CDec(Lot), Me.LotsTableAdapter.GetDataByRéférence(CDec(Lot), "@@@@@").Item(0)._Date, "XXXXXXXXXXXXXXXXXXXXXX", "XXXXXXXXXXXXXXXXXXXXXX")
                For r = 0 To factures_table.Rows.Count - 1
                    Dim size_files As Long
                    Dim Fact_Files = Dir(Config.LocalNetwork_ServerName & "\scor\doc\" & factures_table(r).G1110C1 & "_*_*.pdf")
                    While Fact_Files <> ""
                        Dim myFile As New FileInfo(Config.LocalNetwork_ServerName & "\scor\doc\" & Fact_Files)
                        size_files = size_files + myFile.Length
                        Fact_Files = Dir()
                    End While
                    If size_files > 0 Then
                        list_of_facture.Add(factures_table(r).G1110C1)
                        list_of_DocsSize.Add(size_files)
                        size_files = 0
                    ElseIf ScanOrdo.SCOR_PJTableAdapter.GetDataBy_Num_Facture_and_Statut_Transmission(factures_table(r).G1110C1, "DOCUMENT EXTERNE").Rows.Count > 0 Then 'ajout de facture n'ayant que des documents externes dans la liste
                        list_of_facture.Add(factures_table(r).G1110C1)
                        list_of_DocsSize.Add(0)
                    End If
                Next
                Dim list_of_list_of_facture As New List(Of List(Of String))
                Dim taille_lot As Long = 0
                Dim list_temp As New List(Of String)
                For i = 0 To list_of_facture.Count - 1
                    If taille_lot + list_of_DocsSize(i) < Config.Scor_TaillMaxLot Then 'taille max lot par defaut 4mo à rendre parametrable
                        taille_lot = taille_lot + list_of_DocsSize(i)
                        list_temp.Add(list_of_facture(i))
                    Else
                        list_of_list_of_facture.Add(list_temp)
                        list_temp = New List(Of String)
                        taille_lot = list_of_DocsSize(i)
                        list_temp.Add(list_of_facture(i))
                    End If
                Next
                list_of_list_of_facture.Add(list_temp)
                For Each liste_factures In list_of_list_of_facture
                    Dim file_to_send As String = TT03(Lot, "TELETRANS", to_, liste_factures, list_of_list_of_facture.IndexOf(liste_factures) + 1, list_of_list_of_facture.Count)
                    If file_to_send <> "" Then
                        SCOR_SendMail(file_to_send, to_, Lot, Retransmission)
                    End If
                    If Me.Pop_Allowed_ListTableAdapter.Select_Count_By_Adresse(to_) = 0 Then
                        Me.Pop_Allowed_ListTableAdapter.InsertQuery(to_)
                    End If

                Next
                Bandeau_info_bas_hide() 'Bandeau_info_bas_show_thread)
            Catch ex As Exception

            End Try
        Next


    End Sub

    Private Function SCOR_Getmail() As Boolean

        If Config.is_local_client = True Then Return False

        Bandeau_info_bas_show("RECEPTION DES MESSAGES SCOR")

        Dim Trace_File As String = Config.LocalNetwork_ServerName & "\scor\traces\" + Format(Now, "yyyyMMdd") + "TraceMail_Get.txt"
        Using swtrace As New StreamWriter(Trace_File, True) 'TRACE
            'Try

            Dim Server As TcpClient
            Dim NetStrm As System.Net.Sockets.NetworkStream
            Dim RdStrm As System.IO.StreamReader
            Dim Data As String
            Dim szData As Byte()

            Dim ConfigXml As New XmlDocument
            ConfigXml.Load("config.xml")
            Dim nodeliste As XmlNodeList
            nodeliste = ConfigXml.GetElementsByTagName("Pop3")
            Dim Serveur As String = nodeliste.Item(0).Item("SCOR_Serveur").InnerText
            Dim Port As Integer = Val(nodeliste.Item(0).Item("SCOR_Port").InnerText)
            Dim User As String = nodeliste.Item(0).Item("SCOR_User").InnerText
            Dim Password As String = nodeliste.Item(0).Item("SCOR_Password").InnerText

            Dim retour As String



            'create server POP3 with port 110
            LabelReception.Text = "CONNECTION bal SCOR"
            Server = New TcpClient(Serveur, Port)
            NetStrm = Server.GetStream()
            RdStrm = New StreamReader(NetStrm)
            RichTextBox1.Visible = True
            retour = RdStrm.ReadLine()
            swtrace.WriteLine("SCOR-------------------------------------------")
            swtrace.WriteLine(Format(Now, "dd/MM/yyyy   HH:mm:ss"))
            swtrace.WriteLine(retour)
            RichTextBox1.AppendText(retour + vbCrLf)
            If InStr(retour, "OK") = 0 Then
                swtrace.WriteLine("ERREUR DE CONNECTION")
                RichTextBox1.AppendText("ERREUR DE CONNECTION" + vbCrLf)
                MyMsg_Box.Presentation("Officine", "ERREUR DE CONNECTION", False, "", False, "", True, "OK")
                MyMsg_Box.ShowDialog()
                Bandeau_info_bas_hide() 'Bandeau_info_bas_show_thread)
                Return False
            End If

            retour = "connected:" + Server.Connected.ToString
            swtrace.WriteLine(retour)
            RichTextBox1.AppendText(retour + vbCrLf)

            'Login Process
            LabelReception.Text = "LOGIN"
            Data = "USER " + User & vbCrLf
            szData = System.Text.Encoding.ASCII.GetBytes(Data.ToCharArray())
            NetStrm.Write(szData, 0, szData.Length)
            retour = RdStrm.ReadLine
            swtrace.WriteLine(retour)
            RichTextBox1.AppendText(retour + vbCrLf)
            If InStr(retour, "OK") = 0 Then
                swtrace.WriteLine("ERREUR DE CONNECTION")
                RichTextBox1.AppendText("ERREUR DE CONNECTION" + vbCrLf)
                MyMsg_Box.Presentation("Officine", "ERREUR DE CONNECTION", False, "", False, "", True, "OK")
                MyMsg_Box.ShowDialog()
                Bandeau_info_bas_hide() 'Bandeau_info_bas_show_thread)
                Return False
            End If

            Data = "PASS " + Password & vbCrLf
            szData = System.Text.Encoding.ASCII.GetBytes(Data.ToCharArray())
            NetStrm.Write(szData, 0, szData.Length)
            retour = RdStrm.ReadLine
            swtrace.WriteLine(retour)
            RichTextBox1.AppendText(retour + vbCrLf)
            If InStr(retour, "OK") = 0 Then
                swtrace.WriteLine("ERREUR DE CONNECTION")
                RichTextBox1.AppendText("ERREUR DE CONNECTION" + vbCrLf)
                MyMsg_Box.Presentation("Officine", "ERREUR DE CONNECTION", False, "", False, "", True, "OK")
                MyMsg_Box.ShowDialog()
                Bandeau_info_bas_hide() 'Bandeau_info_bas_show_thread)
                Return False
            End If

            'Send STAT command to get information ie: number of mail
            LabelReception.Text = "STAT"
            Data = "STAT" & vbCrLf
            szData = System.Text.Encoding.ASCII.GetBytes(Data.ToCharArray())
            NetStrm.Write(szData, 0, szData.Length)
            retour = RdStrm.ReadLine
            swtrace.WriteLine(retour)
            RichTextBox1.AppendText("STAT:" + retour + vbCrLf)
            Dim NumberOfMail As Integer = Val(Trim(Mid(retour, 5, 2)))
            swtrace.WriteLine("Nombre de Message:" + NumberOfMail.ToString)
            RichTextBox1.AppendText("Nombre de Message:" + NumberOfMail.ToString + vbCrLf)


            'retrieve mail with number mail parameter
            LabelReception.Text = "NumberOfMail:" + NumberOfMail.ToString

            If NumberOfMail <> 0 Then

                For i = 1 To NumberOfMail
                    swtrace.WriteLine("-----Message SCOR " + i.ToString + " -----")
                    LabelReception.Text = "Telechargement message SCOR " + i.ToString
                    Dim MessageId As String = ""
                    Dim InReplyTo As String = ""
                    Dim Subject As String = ""
                    Dim From_ As String = ""
                    Dim To_ As String = ""
                    Dim Content_Description As String = ""
                    Dim Content_Type As String = ""
                    Data = "retr " + i.ToString & vbCrLf
                    szData = System.Text.Encoding.ASCII.GetBytes(Data.ToCharArray())
                    NetStrm.Write(szData, 0, szData.Length)
                    Dim line As String = RdStrm.ReadLine
                    Dim multipart As Boolean = False
                    Dim délimiteur As String = ""
                    Dim Pièce_jointe_téléchargée As Boolean = False
                    Dim Fichier_Pièce_Jointe As String = Config.LocalNetwork_ServerName & "\scor\bal\" + Format(Now, "yyyyMMddHHmmss") + ".temp"
                    '------------------------------------------------------------------------------------------------
                    While line <> "." 'And message_est_sesamVitale = True
                        '------------------------------------------------------------------------------------------------
                        If InStr(UCase(line), "MESSAGE-ID:") = 1 Then
                            MessageId = Trim(Mid(line, "Message-Id:".Length + 1))
                            swtrace.WriteLine("MessageId: " + MessageId)
                        ElseIf InStr(UCase(line), "IN-REPLY-TO:") = 1 Then
                            InReplyTo = Trim(Mid(line, "In-Reply-To:".Length + 1))
                            swtrace.WriteLine("In-Reply-To: " + InReplyTo)
                        ElseIf InStr(UCase(line), "SUBJECT:") = 1 Then
                            Subject = Trim(Mid(line, "Subject:".Length + 1))
                            swtrace.WriteLine("Subject: " + Subject)
                        ElseIf InStr(UCase(line), "FROM:") = 1 Then
                            From_ = Trim(Mid(line, "From:".Length + 1))
                            If InStr(From_, "<") = 1 And InStr(From_, ">") = From_.Length Then
                                From_ = Mid(From_, 2, From_.Length - 2)
                            End If
                            swtrace.WriteLine("From: " + From_)
                        ElseIf InStr(UCase(line), "TO:") = 1 Then
                            To_ = Trim(Mid(line, "To:".Length + 1))
                            swtrace.WriteLine("To: " + To_)
                        ElseIf InStr(UCase(line), "CONTENT-TYPE:") = 1 Then
                            Content_Type = Trim(Mid(line, "Content-Type:".Length + 1))
                            swtrace.WriteLine("Content-Type: " + Content_Type)
                            If InStr(Content_Type, "multipart") <> 0 Then
                                délimiteur = Mid(Content_Type, InStr(Content_Type, "boundary=") + 9)
                                multipart = True
                            End If
                        ElseIf InStr(UCase(line), "CONTENT-DESCRIPTION:") = 1 Then
                            Content_Description = Trim(Mid(line, "Content-Description:".Length + 1))
                            swtrace.WriteLine("Content-Description: " + Content_Description)
                        End If

                        '------------------------------------------------------------------------------------------------
                        If From_ <> "" Then
                            If Me.Pop_Allowed_ListTableAdapter.Select_Count_By_Adresse(From_) = 0 Then

                                multipart = False 'pour ne pas traiter comm un arl
                                délimiteur = "" 'pour ne pas traiter comm un arl
                                'message_est_sesamVitale = False

                                'suppression message
                                LabelReception.Text = "SUPPRESSION MESSAGE " + i.ToString
                                Data = "DELE " + i.ToString & vbCrLf
                                szData = System.Text.Encoding.ASCII.GetBytes(Data.ToCharArray())
                                NetStrm.Write(szData, 0, szData.Length)
                                While retour <> ""
                                    retour = RdStrm.ReadLine
                                End While
                                swtrace.WriteLine(retour)
                                RichTextBox1.AppendText("MESSAGE " + i.ToString + " SUPPRIMÉ" & vbCrLf)
                            End If
                        End If
                        '------------------------------------------------------------------------------------------------


                        If InReplyTo <> "" Then

                            If Me.SCOR_lotsTableAdapter.GetDataBy_Subject(InReplyTo).Rows.Count = 0 Then

                                multipart = False 'pour ne pas traiter comm un arl
                                délimiteur = "" 'pour ne pas traiter comm un arl
                                'message_est_sesamVitale = False

                                'suppression message
                                LabelReception.Text = "SUPPRESSION MESSAGE " + i.ToString
                                Data = "DELE " + i.ToString & vbCrLf
                                szData = System.Text.Encoding.ASCII.GetBytes(Data.ToCharArray())
                                NetStrm.Write(szData, 0, szData.Length)
                                While retour <> ""
                                    retour = RdStrm.ReadLine
                                End While
                                swtrace.WriteLine(retour)
                                RichTextBox1.AppendText("MESSAGE " + i.ToString + " SUPPRIMÉ" & vbCrLf)
                            End If
                        End If
                        '------------------------------------------------------------------------------------------------
                        'NON REMISE
                        XMLelementliste = ConfigXml.GetElementsByTagName("SMTP")
                        If InStr(UCase(From_), UCase(Config.SMTP_Postmaster)) <> 0 Then
                            Dim MyFile As String = Config.LocalNetwork_ServerName & "\scor\bal\" + Format(Now, "yyyyMMddHHmmss") + i.ToString + ".Postmaster"
                            While Dir(Config.POP3_RepBAL + MyFile) <> ""
                                MyFile = Config.POP3_RepBAL + Format(Now, "yyyyMMddHHmmss") + ".Postmaster"
                            End While
                            My.Computer.FileSystem.WriteAllText(MyFile, Chr(10) + "------------------------------------------------------------------------------------------------" + Chr(10), True)
                            line = RdStrm.ReadLine
                            Do
                                RichTextBox1.AppendText(line + Chr(10))
                                My.Computer.FileSystem.WriteAllText(MyFile, line + Chr(10), True)
                                line = RdStrm.ReadLine
                            Loop Until line = "." Or line Is Nothing
                            My.Computer.FileSystem.WriteAllText(MyFile, "------------------------------------------------------------------------------------------------" + Chr(10), True)
                        End If
                        '------------------------------------------------------------------------------------------------
                        If multipart = False And Content_Description <> "" And Pièce_jointe_téléchargée = False Then 'And message_est_sesamVitale = True Then
                            While line <> "" 'avance jusqu'à ligne blanche(juste avant pièce jointe)
                                line = RdStrm.ReadLine
                            End While
                            'sauvegarde pièce jointe dans fichier temp
                            line = RdStrm.ReadLine
                            While line <> "" And line <> "."
                                My.Computer.FileSystem.WriteAllText(Fichier_Pièce_Jointe, line, True)
                                line = RdStrm.ReadLine
                            End While
                            Pièce_jointe_téléchargée = True
                        End If
                        '------------------------------------------------------------------------------------------------
                        If multipart = True And délimiteur <> "" Then 'And message_est_sesamVitale = True Then
                            If InStr(line, "Content-Description") <> 0 Then
                                While line <> "" 'avance jusqu'à ligne blanche(juste avant pièce jointe)
                                    line = RdStrm.ReadLine
                                End While
                                'sauvegarde pièce jointe dans fichier temp
                                line = RdStrm.ReadLine
                                While InStr(line, délimiteur) = 0
                                    My.Computer.FileSystem.WriteAllText(Fichier_Pièce_Jointe, line, True)
                                    line = RdStrm.ReadLine
                                End While
                            End If
                        End If
                        '------------------------------------------------------------------------------------------------
                        If InStr(Subject, "/chiffrement") <> 0 And From_ <> "" Then

                            While line <> ""
                                line = RdStrm.ReadLine
                            End While
                            line = RdStrm.ReadLine
                            'While InStr(line, "==") = 0
                            While InStr(line, "=") = 0
                                My.Computer.FileSystem.WriteAllText(Fichier_Pièce_Jointe, line, True)
                                line = RdStrm.ReadLine
                            End While
                            SCOR_Certificate_Update(From_, Fichier_Pièce_Jointe)

                            While line <> "."

                                line = RdStrm.ReadLine
                            End While
                        End If


                        '------------------------------------------------------------------------------------------------
                        If line <> "." Then
                            line = RdStrm.ReadLine
                        End If
                    End While


                    '------------------------------------------------------------------------------------------------
                    Select Case Content_Description
                        Case "ARL/SEH", "ARLTEST/SEH"
                            convert_base64file_to_another_file(Replace(Fichier_Pièce_Jointe, "/", "_"), Config.LocalNetwork_ServerName & "\scor\bal\arl\" + Replace(InReplyTo, "/", "_") + ".zip", True)
                            ZipFile.ExtractToDirectory(Config.LocalNetwork_ServerName & "\scor\bal\arl\" + Replace(InReplyTo, "/", "_") + ".zip", Config.LocalNetwork_ServerName & "\scor\bal\arl\" + Replace(InReplyTo, "/", "_"))
                            My.Computer.FileSystem.DeleteFile(Config.LocalNetwork_ServerName & "\scor\bal\arl\" + Replace(InReplyTo, "/", "_") + ".zip")
                            SCOR_Traitement_ARL(Config.LocalNetwork_ServerName & "\scor\bal\arl\" + Replace(InReplyTo, "/", "_"), InReplyTo, From_)
                        Case "SERVICE/REJET_FICHIER", "SERVICE/REJET_SMTP"
                            SCOR_Traitement_SERVICE_REJET(Fichier_Pièce_Jointe, Subject, InReplyTo, From_, Content_Description)
                        Case "SERVICE/AR_PROVISOIRE"
                            SCOR_Traitement_SERVICE_AR_PROVISOIRE(Subject, InReplyTo, From_)



                    End Select

                    'suppression message
                    LabelReception.Text = "SUPPRESSION MESSAGE SCOR " + i.ToString
                    Data = "DELE " + i.ToString & vbCrLf
                    szData = System.Text.Encoding.ASCII.GetBytes(Data.ToCharArray())
                    NetStrm.Write(szData, 0, szData.Length)
                    RichTextBox1.AppendText("MESSAGE " + i.ToString + " SUPPRIMÉ" & vbCrLf)
                    swtrace.WriteLine("MESSAGE " + i.ToString + " SUPPRIMÉ")
                Next



            End If




            'Send QUIT command to close session from POP server
            LabelReception.Text = "DECONNECTION"
            Data = "QUIT" & vbCrLf
            szData = System.Text.Encoding.ASCII.GetBytes(Data.ToCharArray())
            NetStrm.Write(szData, 0, szData.Length)
            RichTextBox1.AppendText("SESSION FERMEE" & vbCrLf)

            'Catch ex As Exception
            '    swtrace.WriteLine(ex.ToString, True)
            '    LabelReception.Visible = False
            '    BAL_relevée = False
            '    If Config.Show_progressbar_Form = True Then
            '        t.Abort()
            '    End If
            '    Return False
            'End Try
        End Using
        BAL_relevée = True
        Bandeau_info_bas_hide() 'Bandeau_info_bas_show_thread)
        SCOR_controle_48h()
        SCOR_controle_15j()
        SCOR_affiche_Lots()
        Return True
    End Function

    Private Sub SCOR_controle_48h()
        Dim lot_emis_datatable = Me.SCOR_lotsTableAdapter.GetDataBy_Statut("EMIS")
        For r = 0 To lot_emis_datatable.Rows.Count - 1
            Dim date_transmission As New Date
            date_transmission = Date.ParseExact(Mid(lot_emis_datatable.Item(r).Subject, InStrRev(lot_emis_datatable.Item(r).Subject, "/") + 1, 12), "yyyyMMddHHmm", Globalization.CultureInfo.InvariantCulture)
            If DateDiff(DateInterval.Hour, date_transmission, Now) >= 48 Then
                Me.SCOR_lotsTableAdapter.UpdateARL("", "A RETRANSMETTRE", lot_emis_datatable.Item(r).NumLot, lot_emis_datatable.Item(r).Subject, lot_emis_datatable.Item(r).To_, "EMIS")
            End If
        Next
        lot_emis_datatable = Nothing
        lot_emis_datatable = Me.SCOR_lotsTableAdapter.GetDataBy_Statut("RETRANSMIS")
        For r = 0 To lot_emis_datatable.Rows.Count - 1
            Dim date_transmission As New Date
            date_transmission = Date.ParseExact(Mid(lot_emis_datatable.Item(r).Subject, InStrRev(lot_emis_datatable.Item(r).Subject, "/") + 1, 12), "yyyyMMddHHmm", Globalization.CultureInfo.InvariantCulture)
            If DateDiff(DateInterval.Hour, date_transmission, Now) >= 48 Then
                Me.SCOR_lotsTableAdapter.UpdateARL("", "A TRAITER MANUELLEMENT PAR PS", lot_emis_datatable.Item(r).NumLot, lot_emis_datatable.Item(r).Subject, lot_emis_datatable.Item(r).To_, "RETRANSMIS")
            End If
        Next
    End Sub

    Private Sub SCOR_controle_15j()
        Dim lot_emis_datatable = Me.SCOR_lotsTableAdapter.GetDataBy_Statut("EMIS-EN ATTENTE")
        For r = 0 To lot_emis_datatable.Rows.Count - 1
            Dim date_transmission As New Date
            date_transmission = Date.ParseExact(Mid(lot_emis_datatable.Item(r).Subject, InStrRev(lot_emis_datatable.Item(r).Subject, "/") + 1, 12), "yyyyMMddHHmm", Globalization.CultureInfo.InvariantCulture)
            If DateDiff(DateInterval.DayOfYear, date_transmission, Now) >= 15 Then
                Me.SCOR_lotsTableAdapter.UpdateARL("", "A TRAITER MANUELLEMENT PAR PS", lot_emis_datatable.Item(r).NumLot, lot_emis_datatable.Item(r).Subject, lot_emis_datatable.Item(r).To_, "EMIS-EN ATTENTE")
            End If
        Next
        lot_emis_datatable = Nothing
        lot_emis_datatable = Me.SCOR_lotsTableAdapter.GetDataBy_Statut("REEMIS-EN ATTENTE")
        For r = 0 To lot_emis_datatable.Rows.Count - 1
            Dim date_transmission As New Date
            date_transmission = Date.ParseExact(Mid(lot_emis_datatable.Item(r).Subject, InStrRev(lot_emis_datatable.Item(r).Subject, "/") + 1, 12), "yyyyMMddHHmm", Globalization.CultureInfo.InvariantCulture)
            If DateDiff(DateInterval.DayOfYear, date_transmission, Now) > 15 Then
                Me.SCOR_lotsTableAdapter.UpdateARL("", "A TRAITER MANUELLEMENT PAR PS", lot_emis_datatable.Item(r).NumLot, lot_emis_datatable.Item(r).Subject, lot_emis_datatable.Item(r).To_, "REEMIS-EN ATTENTE")
            End If
        Next
    End Sub

    Private Sub SCOR_Traitement_ARL(ByVal Rep_ARL As String, ByVal Subject_Lot As String, to_ As String)
        Dim ARL_file = Dir(Rep_ARL + "\D-ARLSCANORDO-*.xml")
        If ARL_file = "" Then
            My.Computer.FileSystem.DeleteDirectory(Rep_ARL, FileIO.DeleteDirectoryOption.DeleteAllContents)
            Exit Sub
        End If
        Dim ARL_xml As New XmlDocument
        ARL_xml.Load(Rep_ARL & "\" & ARL_file)
        Dim numlot = ARL_xml.GetElementsByTagName("Archive").Item(0).InnerText
        Dim Etat As String = "A"
        For Each item As XmlNode In ARL_xml.GetElementsByTagName("Etat")
            If item.InnerText = "R" Then
                Etat = "R"
                Exit For
            End If
        Next
        If Me.SCOR_lotsTableAdapter.GetDataBy_all(numlot, Subject_Lot, to_, "EMIS").Rows.Count = 0 And Me.SCOR_lotsTableAdapter.GetDataBy_all(numlot, Subject_Lot, to_, "RETRANSMIS").Rows.Count = 0 Then
            If Me.SCOR_lotsTableAdapter.GetData_lot_inconnu(Subject_Lot, to_).Rows.Count = 0 Then
                My.Computer.FileSystem.DeleteDirectory(Rep_ARL, FileIO.DeleteDirectoryOption.DeleteAllContents)
            Else
                My.Computer.FileSystem.CreateDirectory(Config.LocalNetwork_ServerName & "\scor\bal\arl\non rapprochés\" & Mid(Rep_ARL, InStrRev(Rep_ARL, "\") + 1))
                My.Computer.FileSystem.MoveDirectory(Rep_ARL, Config.LocalNetwork_ServerName & "\scor\bal\arl\non rapprochés\" & Mid(Rep_ARL, InStrRev(Rep_ARL, "\") + 1), True)
            End If
        Else

            'If ARL_xml.GetElementsByTagName("Etat").Item(0).InnerText = "A" Then
            '    Me.SCOR_lotsTableAdapter.UpdateARL(ARL_file, "ACQUITE", numlot, Subject_Lot, to_, "EMIS")
            '    Me.SCOR_lotsTableAdapter.UpdateARL(ARL_file, "ACQUITE", numlot, Subject_Lot, to_, "RETRANSMIS")
            'ElseIf ARL_xml.GetElementsByTagName("Etat").Item(0).InnerText = "R" Then
            '    Me.SCOR_lotsTableAdapter.UpdateARL(ARL_file, "A RECONSTITUER", numlot, Subject_Lot, to_, "EMIS")
            '    Me.SCOR_lotsTableAdapter.UpdateARL(ARL_file, "A TRAITER MANUELLEMENT PAR PS", numlot, Subject_Lot, to_, "RETRANSMIS")
            'End If
            If Etat = "A" Then
                Me.SCOR_lotsTableAdapter.UpdateARL(ARL_file, "ACQUITE", numlot, Subject_Lot, to_, "EMIS")
                Me.SCOR_lotsTableAdapter.UpdateARL(ARL_file, "ACQUITE", numlot, Subject_Lot, to_, "RETRANSMIS")
            ElseIf Etat = "R" Then
                Me.SCOR_lotsTableAdapter.UpdateARL(ARL_file, "A RECONSTITUER", numlot, Subject_Lot, to_, "EMIS")
                Me.SCOR_lotsTableAdapter.UpdateARL(ARL_file, "A TRAITER MANUELLEMENT PAR PS", numlot, Subject_Lot, to_, "RETRANSMIS")
            End If
        End If
    End Sub

    Private Sub SCOR_Traitement_ARL_manuel(ByVal Rep_ARL As String)
        Dim ARL_file = Dir(Rep_ARL + "\D-ARLSCANORDO-*.xml")
        If ARL_file = "" Then
            My.Computer.FileSystem.DeleteDirectory(Rep_ARL, FileIO.DeleteDirectoryOption.DeleteAllContents)
            Exit Sub
        End If
        Dim ARL_xml As New XmlDocument
        ARL_xml.Load(Rep_ARL & "\" & ARL_file)


        'ConfigXMLelementliste = ConfigXml.GetElementsByTagName("SMTP")
        'SMTP_From = ConfigXMLelementliste.Item(0).Item("From").InnerText
        'SMTP_VersionCDC = ConfigXMLelementliste.Item(0).Item("VersionCDC").InnerText
        Dim Subject_Lot = ARL_xml.GetElementsByTagName("DiagEntete").Item(0).Item("Identification").InnerText
        Subject_Lot = "SO211000/" & Replace(Subject_Lot, "-", "/")


        Dim numlot = ARL_xml.GetElementsByTagName("Archive").Item(0).InnerText
        Dim Etat As String = "A"
        For Each item As XmlNode In ARL_xml.GetElementsByTagName("Etat")
            If item.InnerText = "R" Then
                Etat = "R"
                Exit For
            End If
        Next
        'In-Reply-To: SO211000/232001511/2019100322042300001
        '<Identification>232001511-2019100322042300001</Identification>

        If Etat = "A" Then
            Me.SCOR_lotsTableAdapter.UpdateARL_manuel(ARL_file, "ACQUITE", numlot, Subject_Lot)
        ElseIf Etat = "R" Then
            Me.SCOR_lotsTableAdapter.UpdateARL_manuel(ARL_file, "A RECONSTITUER", numlot, Subject_Lot)
        End If

    End Sub
    Private Sub SCOR_Traitement_SERVICE_REJET(ByVal fictemp As String, ByVal subject As String, ByVal Subject_Lot As String, ByVal to_ As String, ByVal Content_Description As String)
        convert_base64file_to_another_file(fictemp, Config.LocalNetwork_ServerName & "\scor\bal\rejet\" + Replace(Subject_Lot, "/", "_") + ".txt", True)
        Select Case Content_Description
            Case "SERVICE/REJET_FICHIER"
                If Me.SCOR_lotsTableAdapter.GetDataBy_Subject(Subject_Lot).Item(0).Statut = "RETRANSMIS" Then
                    Me.SCOR_lotsTableAdapter.Update_Rejet(subject & "|" & My.Computer.FileSystem.ReadAllText(Config.LocalNetwork_ServerName & "\scor\bal\rejet\" + Replace(Subject_Lot, "/", "_") + ".txt"), "A TRAITER MANUELLEMENT PAR PS", Subject_Lot, to_)
                Else
                    Me.SCOR_lotsTableAdapter.Update_Rejet(subject & "|" & My.Computer.FileSystem.ReadAllText(Config.LocalNetwork_ServerName & "\scor\bal\rejet\" + Replace(Subject_Lot, "/", "_") + ".txt"), "A RECONSTITUER", Subject_Lot, to_)
                End If
            Case "SERVICE/REJET_SMTP"
                If Me.SCOR_lotsTableAdapter.GetDataBy_Subject(Subject_Lot).Item(0).Statut = "RETRANSMIS" Then
                    Me.SCOR_lotsTableAdapter.Update_Rejet(subject & "|" & My.Computer.FileSystem.ReadAllText(Config.LocalNetwork_ServerName & "\scor\bal\rejet\" + Replace(Subject_Lot, "/", "_") + ".txt"), "A TRAITER MANUELLEMENT PAR PS", Subject_Lot, to_)
                Else
                    Me.SCOR_lotsTableAdapter.Update_Rejet(subject & "|" & My.Computer.FileSystem.ReadAllText(Config.LocalNetwork_ServerName & "\scor\bal\rejet\" + Replace(Subject_Lot, "/", "_") + ".txt"), "A RETRANSMETTRE", Subject_Lot, to_)
                End If
        End Select

    End Sub

    Private Sub SCOR_Traitement_SERVICE_AR_PROVISOIRE(ByVal subject As String, ByVal Subject_Lot As String, ByVal to_ As String)
        If Me.SCOR_lotsTableAdapter.GetDataBy_Subject(Subject_Lot).Item(0).Statut = "RETRANSMIS" Then
            Me.SCOR_lotsTableAdapter.Update_Rejet(subject, "REEMIS-EN ATTENTE", Subject_Lot, to_)
        Else
            Me.SCOR_lotsTableAdapter.Update_Rejet(subject, "EMIS-EN ATTENTE", Subject_Lot, to_)
        End If
    End Sub

    Private Sub SCOR_Certificate_Update(ByVal from_ As String, ByVal Fichier_Pièce_Jointe As String)
        If My.Computer.FileSystem.FileExists(Config.LocalNetwork_ServerName & "\scor\certificats\" + from_ + ".cer") Then
            My.Computer.FileSystem.MoveFile(Config.LocalNetwork_ServerName & "\scor\certificats\" + from_ + ".cer", Config.LocalNetwork_ServerName & "\scor\certificats\old\" + Format(Now, "yyyyMMddHHmmss") + "_" + from_ + ".cer", True)
        End If
        If My.Computer.FileSystem.FileExists(Config.LocalNetwork_ServerName & "\scor\certificats\" + from_ + ".pem") Then
            My.Computer.FileSystem.MoveFile(Config.LocalNetwork_ServerName & "\scor\certificats\" + from_ + ".pem", Config.LocalNetwork_ServerName & "\scor\certificats\old\" + Format(Now, "yyyyMMddHHmmss") + "_" + from_ + ".pem", True)
        End If
        convert_base64file_to_another_file(Fichier_Pièce_Jointe, Config.LocalNetwork_ServerName & "\scor\certificats\" + from_ + ".cer.temp", True)
        Dim sr = My.Computer.FileSystem.OpenTextFileReader(Config.LocalNetwork_ServerName & "\scor\certificats\" + from_ + ".cer.temp")
        Dim line = sr.ReadLine
        While line <> ""
            line = sr.ReadLine
        End While
        Dim b64message As String = ""
        While InStr(line, "==") = 0
            b64message = b64message & line
            line = sr.ReadLine
        End While
        b64message = b64message & line
        sr.Close()

        MyMsg_Box.Presentation("Officine", System.Text.Encoding.UTF8.GetString(Convert.FromBase64String(b64message)), False, "", False, "", True, "OK")
        MyMsg_Box.ShowDialog()

        Dim bytes = My.Computer.FileSystem.ReadAllBytes(Config.LocalNetwork_ServerName & "\scor\certificats\" + from_ + ".cer.temp")
        Dim index = 0
        For i = 0 To bytes.Length - 10
            If Hex(bytes(i)).ToString = "30" And Hex(bytes(i + 1)).ToString = "82" And Hex(bytes(i + 2)).ToString = "4" Then 'And Hex(bytes(i + 3)).ToString = "C4" And _
                'Hex(bytes(i + 4)).ToString = "30" And Hex(bytes(i + 5)).ToString = "82" And Hex(bytes(i + 6)).ToString = "3" And Hex(bytes(i + 7)).ToString = "AC" Then
                index = i
            End If
        Next
        Dim cert_array As Byte()
        ReDim cert_array(bytes.Length - index - 1)

        For i = 0 To cert_array.Length - 1
            cert_array(i) = bytes(i + index)
        Next
        My.Computer.FileSystem.WriteAllBytes(Config.LocalNetwork_ServerName & "\scor\certificats\" + from_ + ".cer", cert_array, False)
        My.Computer.FileSystem.DeleteFile(Config.LocalNetwork_ServerName & "\scor\certificats\" + from_ + ".cer.temp")

        'convertir les certificats: "openssl x509 -inform der -in certificate.cer -out certificate.pem"
        'encrypt: "openssl cms -binary -encrypt -in  file_to_encryt -out file_to_encryt.pkcs7 -aes-128-cbc -outform DER certificats.pem"

        ShellandWait("C:\OpenSSL-Win32\bin", "openssl.exe", "x509 -inform der -in " & Config.LocalNetwork_ServerName & "\scor\certificats\" + from_ + ".cer" & _
                     " -out " & Config.LocalNetwork_ServerName & "\scor\certificats\" + from_ + ".pem")

    End Sub
    Private Sub SCOR_affiche_Lots()
        SCOR_lotsDataGridView.Rows.Clear()
        Dim datatable = Me.SCOR_lotsTableAdapter.GetDataBy_Statut_non_Acquitté
        For r = 0 To datatable.Rows.Count - 2
            SCOR_lotsDataGridView.Rows.Add()
        Next
        For r = 0 To datatable.Rows.Count - 1
            For c = 1 To datatable.Columns.Count - 1
                Select Case datatable.Columns.Item(c).ColumnName
                    Case "NumLot"
                        SCOR_lotsDataGridView.Item(SCOR_lotsDataGridView_NumLot.Index, r).Value = datatable.Item(r).Item(c).ToString
                    Case "Subject"
                        SCOR_lotsDataGridView.Item(SCOR_lotsDataGridView_Subject.Index, r).Value = datatable.Item(r).Item(c).ToString
                    Case "Statut"
                        SCOR_lotsDataGridView.Item(SCOR_lotsDataGridView_Statut.Index, r).Value = datatable.Item(r).Item(c).ToString
                        Select Case datatable.Item(r).Item(c)
                            Case "EMIS", "REEMIS", "EMIS-EN ATTENTE", "REEMIS-EN ATTENTE", "RETRANSMIS", "Sauvegarde pour Cdrom"
                                SCOR_lotsDataGridView.Rows(r).DefaultCellStyle.BackColor = Color.LightYellow
                            Case "A RECONSTITUER", "A TRAITER MANUELLEMENT PAR PS", "A RETRANSMETTRE"
                                SCOR_lotsDataGridView.Rows(r).DefaultCellStyle.BackColor = Color.OrangeRed
                            Case "ACQUITE", "COLLECTE PAPIER", "Archivé sur CDROM"
                                SCOR_lotsDataGridView.Rows(r).DefaultCellStyle.BackColor = Color.LightGreen
                        End Select
                    Case "To_"
                        SCOR_lotsDataGridView.Item(SCOR_lotsDataGridView_To_.Index, r).Value = datatable.Item(r).Item(c).ToString
                End Select

            Next
        Next
    End Sub

    Private Sub SCOR_lotsDataGridView_CellClick(sender As Object, e As DataGridViewCellEventArgs) Handles SCOR_lotsDataGridView.CellClick
        If e.RowIndex = -1 Then
            Exit Sub
        End If

        Dim LotData As DataTable = Me.LotsTableAdapter.GetDataByRéférence(Val(SCOR_lotsDataGridView.Item(SCOR_lotsDataGridView_NumLot.Index, SCOR_lotsDataGridView.CurrentRow.Index).Value), "XXXXXXXXXXXXXXXXXXXXXX")
        SCOR_RichTextBox.Clear()
        For c = 0 To LotData.Columns.Count - 1
            SCOR_RichTextBox.AppendText(LotData.Columns.Item(c).ColumnName + ": " + LotData(0).Item(c).ToString + Chr(10))
        Next
        If Config.is_local_client = True Then Exit Sub

        Select Case SCOR_lotsDataGridView.Item(SCOR_lotsDataGridView_Statut.Index, SCOR_lotsDataGridView.CurrentRow.Index).Value
            Case "A RECONSTITUER", "A RETRANSMETTRE"
                MyMsg_Box.Presentation("Officine", "SCOR: retransmettre lot " + SCOR_lotsDataGridView.Item(SCOR_lotsDataGridView_NumLot.Index, SCOR_lotsDataGridView.CurrentRow.Index).Value.ToString + " ?", True, "OUI", True, "NON", False, "")
                If MyMsg_Box.ShowDialog() = Windows.Forms.DialogResult.Yes Then
                    Me.SCOR_lotsTableAdapter.Delete_By_NumLot(SCOR_lotsDataGridView.Item(SCOR_lotsDataGridView_NumLot.Index, SCOR_lotsDataGridView.CurrentRow.Index).Value)
                    Dim liste_lots As New List(Of String)
                    liste_lots.Add(SCOR_lotsDataGridView.Item(SCOR_lotsDataGridView_NumLot.Index, SCOR_lotsDataGridView.CurrentRow.Index).Value)
                    SCOR_GO(liste_lots, True)
                End If
            Case "A TRAITER MANUELLEMENT PAR PS", "COLLECTE PAPIER"
                Dim SCOR_Traitement_Papier_ As New SCOR_Traitement_Papier
                SCOR_Traitement_Papier_.NumLot = SCOR_lotsDataGridView.Item(SCOR_lotsDataGridView_NumLot.Index, SCOR_lotsDataGridView.CurrentRow.Index).Value.ToString
                SCOR_Traitement_Papier_.Date_lot = Me.LotsTableAdapter.GetDataByRéférence(CDec(SCOR_lotsDataGridView.Item(SCOR_lotsDataGridView_NumLot.Index, SCOR_lotsDataGridView.CurrentRow.Index).Value.ToString), "@@@@@@@@@@").Item(0)._Date
                SCOR_Traitement_Papier_.ShowDialog()
                SCOR_Traitement_Papier_ = Nothing
                Me.SCOR_lotsTableAdapter.UpdateARL("", "COLLECTE PAPIER", SCOR_lotsDataGridView.Item(SCOR_lotsDataGridView_NumLot.Index, SCOR_lotsDataGridView.CurrentRow.Index).Value.ToString, _
                                                   SCOR_lotsDataGridView.Item(SCOR_lotsDataGridView_Subject.Index, SCOR_lotsDataGridView.CurrentRow.Index).Value.ToString, _
                                                   SCOR_lotsDataGridView.Item(SCOR_lotsDataGridView_To_.Index, SCOR_lotsDataGridView.CurrentRow.Index).Value.ToString, _
                                                   SCOR_lotsDataGridView.Item(SCOR_lotsDataGridView_Statut.Index, SCOR_lotsDataGridView.CurrentRow.Index).Value.ToString)
                SCOR_affiche_Lots()
            Case Else
                Dim SCOR_Traitement_Papier_ As New SCOR_Traitement_Papier
                SCOR_Traitement_Papier_.NumLot = SCOR_lotsDataGridView.Item(SCOR_lotsDataGridView_NumLot.Index, SCOR_lotsDataGridView.CurrentRow.Index).Value.ToString
                SCOR_Traitement_Papier_.ShowDialog()
                SCOR_Traitement_Papier_ = Nothing
        End Select
    End Sub


#End Region



    Private Sub SCOR_CDROM()

        Dim root_directory = Config.LocalNetwork_ServerName & "\scor\cdrom\" & Format(Now, "yyyyMMddHHmmss")
        My.Computer.FileSystem.CreateDirectory(root_directory)

        Dim lots = Me.SCOR_lotsTableAdapter.GetDataBy_Statut("Sauvegarde pour Cdrom")

        Dim numPS = ""
        Dim premier_lot = ""
        Dim dernier_lot = ""

        For r = 0 To lots.Rows.Count - 1

            Dim lot_FSE = Me.LotsTableAdapter.GetDataByRéférence(Val(lots(r).NumLot), "@@@@@@@").Item(0)
            If r = 0 Then
                premier_lot = lot_FSE.Référence.ToString
            ElseIf r = lots.Rows.Count - 1 Then
                dernier_lot = lot_FSE.Référence.ToString
            End If
            numPS = Mid(lot_FSE.CRL, 1, 9)
            Dim lot_SCOR = lots.Item(r)
            Dim coderégime As String = Mid(lot_FSE.CRL, 12, 2)
            If My.Computer.FileSystem.DirectoryExists(root_directory & "\" & coderégime) = False Then
                My.Computer.FileSystem.CreateDirectory(root_directory & "\" & coderégime)
            End If

            Dim OrgDest As String = Mid(lot_FSE.CRL, 14, 3)
            If My.Computer.FileSystem.DirectoryExists(root_directory & "\" & coderégime & "\" & OrgDest) = False Then
                My.Computer.FileSystem.CreateDirectory(root_directory & "\" & coderégime & "\" & OrgDest)
            End If

            My.Computer.FileSystem.CreateDirectory(root_directory & "\" & coderégime & "\" & OrgDest & "\" & lot_FSE.Référence.ToString)



            TT03_cdrom(lot_FSE.Référence.ToString, root_directory & "\" & coderégime & "\" & OrgDest & "\" & lot_FSE.Référence.ToString & "\")
            Me.SCOR_lotsTableAdapter.UpdateARL("", "Archivé sur CDROM", lot_FSE.Référence.ToString, lot_SCOR.Subject, lot_SCOR.To_, "Sauvegarde pour Cdrom")

        Next


        Dim coderégime_reps = My.Computer.FileSystem.GetDirectories(root_directory)
        For Each coderégime_rep In coderégime_reps

            Dim regime_html = coderégime_rep & "\" & numPS & "_" & Mid(coderégime_rep, InStrRev(coderégime_rep, "\") + 1) & "_" & Format(Now, "yyyyMMdd") & ".htm"
            My.Computer.FileSystem.WriteAllText(regime_html, "<HTML>" & vbCrLf, True)
            My.Computer.FileSystem.WriteAllText(regime_html, "<BODY>" & vbCrLf, True)

            My.Computer.FileSystem.WriteAllText(regime_html, "<P>Page récapitulative des organismes pour le régime " & Mid(coderégime_rep, InStrRev(coderégime_rep, "\") + 1) & "</P> " & vbCrLf, True)
            My.Computer.FileSystem.WriteAllText(regime_html, "<P>Organismes destinataires:</P> " & vbCrLf, True)

            Dim OrgDest_reps = My.Computer.FileSystem.GetDirectories(coderégime_rep)
            For Each OrgDest_rep In OrgDest_reps



                Dim nbr_lot As Integer = 0
                Dim orgdest_html = OrgDest_rep & "\" & numPS & "_" & Mid(coderégime_rep, InStrRev(coderégime_rep, "\") + 1) & "_" & Mid(OrgDest_rep, InStrRev(OrgDest_rep, "\") + 1) & "_" & Format(Now, "yyyyMMdd") & ".htm"



                My.Computer.FileSystem.WriteAllText(orgdest_html, "<HTML>" & vbCrLf, True)
                My.Computer.FileSystem.WriteAllText(orgdest_html, "<BODY>" & vbCrLf, True)
                My.Computer.FileSystem.WriteAllText(orgdest_html, "<P>Page récapitulative des lots de justificatifs pour l’organisme " & Mid(OrgDest_rep, InStrRev(OrgDest_rep, "\") + 1) & _
                                                  " du régime " & Mid(coderégime_rep, InStrRev(coderégime_rep, "\") + 1) & "</P> " & vbCrLf, True)
                My.Computer.FileSystem.WriteAllText(orgdest_html, "<P>Bordereaux récapitulatif de lot:</P> " & vbCrLf, True)
                For Each lot In My.Computer.FileSystem.GetDirectories(OrgDest_rep)
                    nbr_lot = nbr_lot + 1
                    My.Computer.FileSystem.WriteAllText(orgdest_html, "<a href=" + Chr(34) + "./" + Mid(lot, InStrRev(lot, "\") + 1) + "\" + Dir(lot + "\*.htm") + Chr(34) + ">" + _
                                                        Dir(lot + "\*.htm") + "</a><BR>" & vbCrLf, True)
                Next
                Dim nbr_lot_strg = nbr_lot.ToString
                While nbr_lot_strg.Length < 3
                    nbr_lot_strg = "0" & nbr_lot_strg
                End While
                My.Computer.FileSystem.WriteAllText(orgdest_html, "</BODY>" & vbCrLf, True)
                My.Computer.FileSystem.WriteAllText(orgdest_html, "</HTML>" & vbCrLf, True)
                Dim new_OrgDest_rep = Mid(OrgDest_rep, InStrRev(OrgDest_rep, "\") + 1) & "_Nb_" & nbr_lot_strg
                My.Computer.FileSystem.RenameDirectory(OrgDest_rep, new_OrgDest_rep)
                Dim orgdest_html2 = numPS & "_" & Mid(coderégime_rep, InStrRev(coderégime_rep, "\") + 1) & "_" & Mid(OrgDest_rep, InStrRev(OrgDest_rep, "\") + 1) & "_" & Format(Now, "yyyyMMdd")
                My.Computer.FileSystem.WriteAllText(regime_html, "<a href=" + Chr(34) + "./" + new_OrgDest_rep + "\" + orgdest_html2 + ".htm" + Chr(34) + ">" _
                                                    + Mid(orgdest_html2, 14, 3) + "</a><BR>" & vbCrLf, True)

            Next
            My.Computer.FileSystem.WriteAllText(regime_html, "</BODY>" & vbCrLf, True)
            My.Computer.FileSystem.WriteAllText(regime_html, "</HTML>" & vbCrLf, True)
        Next


        My.Computer.FileSystem.WriteAllText(root_directory & "\" & "etiquette.txt", numPS + vbCrLf + _
                                            "Quinzaine de facturation: " + Config.Scor_cdrom_lastdate.ToShortDateString + " à " + Now.ToShortDateString + vbCrLf + _
                                            "n° lot " & premier_lot & " à n° lot " & dernier_lot, False)
        Config.Scor_cdrom_lastdate = Now
        Dim ConfigXml As New XmlDocument
        ConfigXml.Load(Application.StartupPath + "\config.xml")
        Dim XMLelementliste As XmlNodeList
        XMLelementliste = ConfigXml.GetElementsByTagName("SCOR")
        XMLelementliste.Item(0).Item("cdrom_lastdate").InnerText = Now.ToShortDateString
        ConfigXml.Save("config.xml")



        SCOR_affiche_Lots()

    End Sub

    Private Sub SecuriserUneFactureToolStripMenuItem_Click(sender As Object, e As EventArgs) Handles SecuriserUneFactureToolStripMenuItem.Click
        If Sécuriser_Facture.Visible = False Then
            Sécuriser_Facture.Visible = True
        Else
            Sécuriser_Facture.Select()
        End If
    End Sub

#Region "RESOPHARMA"
    Public Sub RPH_traitement_retour()

        '          ElseIf InStr(Content_Description, "PH/ACC") = 1 And message_est_sesamVitale = True Then
        'convert_base64file_to_another_file(Fichier_Pièce_Jointe, Config.POP3_RepBAL + "Resopharma\ACC\" + Subject, True)
        '                ElseIf InStr(Content_Description, "PH/RPH") = 1 And message_est_sesamVitale = True Then
        'convert_base64file_to_another_file(Fichier_Pièce_Jointe, Config.POP3_RepBAL + "Resopharma\RPH\" + Subject, True)
        'traitement fichiers.rph
        Dim file = Dir(Config.POP3_RepBAL & "Resopharma\RPH\*.rph")
        While file <> ""
            Bandeau_info_bas_show("Traitement des retours RPH " & file)
            Dim sr As New StreamReader(Config.POP3_RepBAL & "Resopharma\RPH\" & file, True)
            Dim line As String = sr.ReadLine
            While Not line Is Nothing




                'My.Computer.FileSystem.WriteAllText(Config.POP3_RepBAL & "Resopharma\RPH\test.txt", line & vbCrLf, True)
                While line.Length >= 128
                    Select Case Mid(line, 1, 1)
                        Case "2" 'AVIS DE REGLEMENTS
                            Dim Org_emetteur = Mid(line, 2, 12)
                            Dim Type_retour = Mid(line, 14, 2)
                            Dim NumFacture = Mid(line, 16, 9)
                            Dim Date_de_facturation = Mid(line, 25, 6)
                            If Config.OCT_RPH_date_Format_DDMMAA Then
                                Date_de_facturation = Mid(Date_de_facturation, 5, 2) & Mid(Date_de_facturation, 3, 2) & Mid(Date_de_facturation, 1, 2)
                            End If

                            Dim NIR = Mid(line, 31, 15)
                            Dim Montant_facturé_RO = Mid(line, 46, 8)
                            Dim Montant_facturé_RC = Mid(line, 54, 8)
                            Dim Montant_payé_RO = Mid(line, 62, 8)
                            Dim Montant_payé_RC = Mid(line, 70, 8)
                            Dim Code_rejet = Mid(line, 78, 3)
                            Dim Libelle_rejet = Mid(line, 81, 37)
                            Dim NumLot = Mid(line, 118, 3)
                            Dim Jour_comptable = Mid(line, 121, 6)
                            Dim Unité_monétaire = Mid(line, 127, 1)


                            If Not IsNumeric(NumFacture) Then
                                My.Computer.FileSystem.WriteAllText(Config.POP3_RepBAL & "Resopharma\RPH\Traitement retour resopharma.log", vbCrLf & _
                                                                      "retour rph avec numéro facture non numérique:" & vbCrLf & Mid(line, 1, 128) & vbCrLf, True)
                            ElseIf Type_retour = "11" Then 'Règlement RO
                                If Me.RSP_PaiementsTableAdapter.GetDataBy_NumFacture_NumLot_Part(CInt(NumFacture), NumLot, "AMO").Rows.Count = 0 Then
                                    Me.RSP_PaiementsTableAdapter.Insert(Jour_comptable, "Règlement RO", "", Org_emetteur, "AMO", Montant_facturé_RO, "P", Montant_payé_RO, NumFacture, NumLot, file, Org_emetteur, "")
                                    If Montant_facturé_RO = Montant_payé_RO Then
                                        BDD.FacturesTableAdapter.Set_Part_AMO_payée(True, CDec(NumFacture))
                                    End If
                                End If
                            ElseIf Type_retour = "12" Then 'Règlement RC
                                If Me.RSP_PaiementsTableAdapter.GetDataBy_NumFacture_NumLot_Part(CInt(NumFacture), NumLot, "AMC").Rows.Count = 0 Then
                                    Me.RSP_PaiementsTableAdapter.Insert(Jour_comptable, "Règlement RC", "", Org_emetteur, "AMC", Montant_facturé_RC, "P", Montant_payé_RC, NumFacture, NumLot, file, Org_emetteur, "")
                                End If
                                If Montant_facturé_RC = Montant_payé_RC Then
                                    BDD.FacturesTableAdapter.Set_Part_AMC_payée(True, CDec(NumFacture))
                                End If
                            ElseIf Type_retour = "13" Then 'Règlement RO+RC
                                If Me.RSP_PaiementsTableAdapter.GetDataBy_NumFacture_NumLot_Part(CInt(NumFacture), NumLot, "AMO").Rows.Count = 0 Then
                                    Me.RSP_PaiementsTableAdapter.Insert(Jour_comptable, "Règlement RO", "", Org_emetteur, "AMO", Montant_facturé_RO, "P", Montant_payé_RO, NumFacture, NumLot, file, Org_emetteur, "")
                                End If
                                If Me.RSP_PaiementsTableAdapter.GetDataBy_NumFacture_NumLot_Part(CInt(NumFacture), NumLot, "AMC").Rows.Count = 0 Then
                                    Me.RSP_PaiementsTableAdapter.Insert(Jour_comptable, "Règlement RC", "", Org_emetteur, "AMC", Montant_facturé_RC, "P", Montant_payé_RC, NumFacture, NumLot, file, Org_emetteur, "")
                                End If
                                If Montant_facturé_RO = Montant_payé_RO Then
                                    BDD.FacturesTableAdapter.Set_Part_AMO_payée(True, CDec(NumFacture))
                                End If
                                If Montant_facturé_RC = Montant_payé_RC Then
                                    BDD.FacturesTableAdapter.Set_Part_AMC_payée(True, CDec(NumFacture))
                                End If
                            ElseIf Type_retour = "21" Then 'Rejet RO
                                If Me.RSP_LIGNE_REJETTableAdapter.GetDataBy_NumFacture_NumLot_PARTCONCERNE(CInt(NumFacture), NumLot, "AMO").Rows.Count = 0 Then
                                    Me.RSP_LIGNE_REJETTableAdapter.Insert(Me.RSP_LIGNE_REJETTableAdapter.Select_Max_num + 1, NumFacture, NumLot, Code_rejet, Libelle_rejet, "", "AMO", "", Date_de_facturation, "", "", "", "Montant facturé RO:" & Montant_facturé_RO, False, Org_emetteur, "")
                                End If
                            ElseIf Type_retour = "22" Then 'Rejet RC
                                If Me.RSP_LIGNE_REJETTableAdapter.GetDataBy_NumFacture_NumLot_PARTCONCERNE(CInt(NumFacture), NumLot, "AMC").Rows.Count = 0 Then
                                    Me.RSP_LIGNE_REJETTableAdapter.Insert(Me.RSP_LIGNE_REJETTableAdapter.Select_Max_num + 1, NumFacture, NumLot, Code_rejet, Libelle_rejet, "", "AMC", "", Date_de_facturation, "", "", "", "Montant facturé RC:" & Montant_facturé_RC, False, Org_emetteur, "")
                                End If
                            ElseIf Type_retour = "23" Then 'Rejet RO+RC
                                If Me.RSP_LIGNE_REJETTableAdapter.GetDataBy_NumFacture_NumLot_PARTCONCERNE(CInt(NumFacture), NumLot, "AMO").Rows.Count = 0 Then
                                    Me.RSP_LIGNE_REJETTableAdapter.Insert(Me.RSP_LIGNE_REJETTableAdapter.Select_Max_num + 1, NumFacture, NumLot, Code_rejet, Libelle_rejet, "", "AMO", "", Date_de_facturation, "", "", "", "Montant facturé RO:" & Montant_facturé_RO, False, Org_emetteur, "")
                                End If
                                If Me.RSP_LIGNE_REJETTableAdapter.GetDataBy_NumFacture_NumLot_PARTCONCERNE(CInt(NumFacture), NumLot, "AMC").Rows.Count = 0 Then
                                    Me.RSP_LIGNE_REJETTableAdapter.Insert(Me.RSP_LIGNE_REJETTableAdapter.Select_Max_num + 1, NumFacture, NumLot, Code_rejet, Libelle_rejet, "", "AMC", "", Date_de_facturation, "", "", "", "Montant facturé RC:" & Montant_facturé_RC, False, Org_emetteur, "")
                                End If
                            ElseIf Type_retour = "31" Then 'Retenue RO (Montant RO négatif)
                                Me.RSP_PaiementsTableAdapter.Insert(Jour_comptable, "Retenue RO (Montant RO négatif)", "", Org_emetteur, "AMO", Montant_facturé_RO, "R", "-" & Montant_payé_RO, NumFacture, NumLot, file, Org_emetteur, "")
                                My.Computer.FileSystem.WriteAllText(Config.POP3_RepBAL & "Resopharma\RPH\Traitement retour resopharma.log", vbCrLf & _
                                                                    "Retenue RO:" & vbCrLf & Mid(line, 1, 128) & vbCrLf, True)
                            ElseIf Type_retour = "32" Then 'Retenue RC (Montant RC négatif)
                                Me.RSP_PaiementsTableAdapter.Insert(Jour_comptable, "Retenue RC (Montant RC négatif)", "", Org_emetteur, "AMC", Montant_facturé_RC, "R", "-" & Montant_payé_RC, NumFacture, NumLot, file, Org_emetteur, "")
                                My.Computer.FileSystem.WriteAllText(Config.POP3_RepBAL & "Resopharma\RPH\Traitement retour resopharma.log", vbCrLf & _
                                                                  "Retenue RC:" & vbCrLf & Mid(line, 1, 128) & vbCrLf, True)
                            ElseIf Type_retour = "33" Then 'Retenue RO + RC (Montant RO+RC négatif)
                                Me.RSP_PaiementsTableAdapter.Insert(Jour_comptable, "Retenue RO (Montant RO négatif)", "", Org_emetteur, "AMO", Montant_facturé_RO, "R", "-" & Montant_payé_RO, NumFacture, NumLot, file, Org_emetteur, "")
                                Me.RSP_PaiementsTableAdapter.Insert(Jour_comptable, "Retenue RC (Montant RC négatif)", "", Org_emetteur, "AMC", Montant_facturé_RC, "R", "-" & Montant_payé_RC, NumFacture, NumLot, file, Org_emetteur, "")
                                My.Computer.FileSystem.WriteAllText(Config.POP3_RepBAL & "Resopharma\RPH\Traitement retour resopharma.log", vbCrLf & _
                                                                  "Retenue RO:" & vbCrLf & Mid(line, 1, 128) & vbCrLf, True)
                                My.Computer.FileSystem.WriteAllText(Config.POP3_RepBAL & "Resopharma\RPH\Traitement retour resopharma.log", vbCrLf & _
                                                                 "Retenue RC:" & vbCrLf & Mid(line, 1, 128) & vbCrLf, True)
                            End If

                        Case "3" 'ARL
                            Dim organisme = Mid(line, 2, 14)
                            Dim type_retour = Mid(line, 16, 1)
                            Dim numlot = Mid(line, 17, 3)
                            Dim date_constitution_lot As String
                            If Config.OCT_RPH_date_Format_DDMMAA Then
                                date_constitution_lot = "20" & Mid(line, 20, 2) & Mid(line, 22, 2) & Mid(line, 24, 2) & "0000"
                            Else
                                date_constitution_lot = "20" & Mid(line, 24, 2) & Mid(line, 22, 2) & Mid(line, 20, 2) & "0000"
                            End If

                            Dim code_rejet = Mid(line, 26, 10)
                            Dim libellé_rejet = Mid(line, 36, 80)
                            Me.LotsTableAdapter.Update_ARL("ARL RECU", Mid(file, InStrRev(file, "\") + 1), "", "", "", organisme, numlot, date_constitution_lot, _
                                                           type_retour, code_rejet, libellé_rejet, Mid(file, InStrRev(file, "\") + 1), Val(numlot), "")
                            If code_rejet <> "" And InStr(libellé_rejet, "FACT N") = 1 Then
                                Try
                                    Dim facture = BDD.FacturesTableAdapter.GetFactureDataByNum1(CDec(Mid(libellé_rejet, 8, 9))).Item(0)
                                    If facture.TP_AMO = True Then
                                        Me.RSP_LIGNE_REJETTableAdapter.Delete_by_facture_lot_part(Mid(libellé_rejet, 8, 9), numlot, "AMO")
                                        Me.RSP_LIGNE_REJETTableAdapter.Insert(Me.RSP_LIGNE_REJETTableAdapter.Select_Max_num + 1, Mid(libellé_rejet, 8, 9), numlot, code_rejet, libellé_rejet, "", "AMO", "", "", "", "", "", "", False, "", "")
                                    End If
                                    If facture.TP_AMC = True Then
                                        Me.RSP_LIGNE_REJETTableAdapter.Delete_by_facture_lot_part(Mid(libellé_rejet, 8, 9), numlot, "AMC")
                                        Me.RSP_LIGNE_REJETTableAdapter.Insert(Me.RSP_LIGNE_REJETTableAdapter.Select_Max_num + 1, Mid(libellé_rejet, 8, 9), numlot, code_rejet, libellé_rejet, "", "AMC", "", "", "", "", "", "", False, "", "")

                                    End If
                                Catch ex As Exception
                                    trace_log(ex.Message)
                                End Try

                            End If

                        Case Else
                            'MyMsg_Box.Presentation("Officine", line, False, "", False, "", True, "OK")
                            'MyMsg_Box.ShowDialog()
                    End Select

                    If line.Length > 128 Then
                        line = Mid(line, 129)
                    Else
                        line = ""
                    End If

                End While


                line = sr.ReadLine

            End While


            sr.Close()


            My.Computer.FileSystem.RenameFile(Config.POP3_RepBAL & "Resopharma\RPH\" & file, file & ".old")
            System.Threading.Thread.Sleep(3000)
            file = Dir()
            Bandeau_info_bas_hide() 'Bandeau_info_bas_show_thread)
        End While
    End Sub

#End Region

    Private Sub SCOR_lotsDataGridView_CellContentClick(sender As Object, e As DataGridViewCellEventArgs) Handles SCOR_lotsDataGridView.CellContentClick

    End Sub

 


    Private Sub ART_ListBox_Click(sender As Object, e As EventArgs) Handles ART_ListBox.Click
        'If InStr(ART_ListBox.SelectedItem.ToString, "ACC\") = 1 Then
        '    Web_browser.Visible = True
        '    Web_browser.WindowState = FormWindowState.Maximized
        '    Web_browser.WebBrowser1.Navigate(Config.POP3_RepBAL + "Resopharma\" & ART_ListBox.SelectedItem.ToString)

        'ElseIf InStr(ART_ListBox.SelectedItem.ToString, "ART\") = 1 Then
        Web_browser.Visible = True
        Web_browser.WindowState = FormWindowState.Maximized
        Web_browser.WebBrowser1.Navigate(Config.POP3_RepBAL & "ART\" & ART_ListBox.SelectedItem.ToString)
        'End If
    End Sub

  
    Private Sub ART_Afficher_Button_Click(sender As Object, e As EventArgs) Handles ART_Afficher_Button.Click
        Dim file As String = ""
        'file = Dir(Config.POP3_RepBAL + "Resopharma\ACC\*.*")
        'While file <> ""




        '    ART_ListBox.Items.Add("ACC\" & file)
        '    file = Dir()
        'End While

        file = Dir(Config.POP3_RepBAL + "ART\*.txt")
        While file <> ""
            Dim datefile As New Date(CInt(Mid(file, 20, 4)), CInt(Mid(file, 24, 2)), CInt(Mid(file, 26, 2)))

            If datefile >= ART_Début_DateTimePicker.Value And datefile <= ART_Fin_DateTimePicker.Value Then
                ART_ListBox.Items.Add(file)
            End If

            file = Dir()
        End While
    End Sub

    Private Sub Scor_trans_manuelle_Button_Click(sender As Object, e As EventArgs) Handles Scor_trans_manuelle_Button.Click
        Dim liste_lots As New List(Of String)
        liste_lots.Add(InputBox(" num lot pour transmettre scor ?"))
        SCOR_GO(liste_lots, False)
    End Sub



    Private Sub Scor_Lots_Erreurs_Click(sender As Object, e As EventArgs) Handles Scor_Lots_Erreurs.Click
        Scor_TrasmettreLotsnonTransmis()
    End Sub
    Private Sub Scor_TrasmettreLotsnonTransmis()
        Dim lots = Me.LotsTableAdapter.LotsTransmis_ScorNonTransmis
        If lots.Rows.Count > 0 Then
            Dim lots_list As New List(Of String)
            For r = 0 To lots.Rows.Count - 1
                lots_list.Add(lots(r).Référence.ToString)
            Next
            SCOR_GO(lots_list, False)
        End If
    End Sub

    Private Sub Button1_Click(sender As Object, e As EventArgs)

    End Sub

    Private Sub Button1_Click_1(sender As Object, e As EventArgs) Handles Button1.Click
        Dim SCOR_Traitement_Papier_ As New SCOR_Traitement_Papier
        SCOR_Traitement_Papier_.NumLot = InputBox("numéro lot?")
        If Me.LotsTableAdapter.GetDataByRéférence(CDec(SCOR_Traitement_Papier_.NumLot), "@@@@@@@@").Rows.Count = 0 Then
            Exit Sub
        End If
        SCOR_Traitement_Papier_.Date_lot = Me.LotsTableAdapter.GetDataByRéférence(CDec(SCOR_Traitement_Papier_.NumLot), "@@@@@@@@").Item(0)._Date
        SCOR_Traitement_Papier_.ShowDialog()
        SCOR_Traitement_Papier_ = Nothing
    End Sub

    Private Sub TT02_Debug_Button_Click(sender As Object, e As EventArgs) Handles TT02_Debug_Button.Click
        ScanOrdo.TT02_Debug()
    End Sub

    Private Sub Button2_Click(sender As Object, e As EventArgs) Handles Button2.Click
        Dim lots = Me.SCOR_lotsTableAdapter.GetDataBy_Statut("A RETRANSMETTRE")
        If lots.Rows.Count > 0 Then
            Dim lots_list As New List(Of String)
            For r = 0 To lots.Rows.Count - 1
                lots_list.Add(lots(r).NumLot.ToString)
            Next
            SCOR_GO(lots_list, True)
            SCOR_affiche_Lots()
        End If
    End Sub

    Private Sub Button3_Click(sender As Object, e As EventArgs) Handles Button3.Click
        Bandeau_info_bas_show("recherche ARL")
        Dim file = Dir(Config.LocalNetwork_ServerName & "\scor\bal\arl\SO_*.zip")
        While file <> ""
            Bandeau_info_bas_change_text(file)
            ZipFile.ExtractToDirectory(Config.LocalNetwork_ServerName & "\scor\bal\arl\" & file, Config.LocalNetwork_ServerName & "\scor\bal\arl\" & Mid(file, 1, InStr(file, ".") - 1))
            My.Computer.FileSystem.DeleteFile(Config.LocalNetwork_ServerName & "\scor\bal\arl\" & file)
            SCOR_Traitement_ARL_manuel(Config.LocalNetwork_ServerName & "\scor\bal\arl\" & Mid(file, 1, InStr(file, ".") - 1))
            file = Dir(Config.LocalNetwork_ServerName & "\scor\bal\arl\SO_*.zip")
        End While

        Bandeau_info_bas_hide()

    End Sub

End Class