' 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/>.
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









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

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

        'If Config.OCT_UtilisationOCT = True Then
        '    TabControl1.TabPages.Remove(TabPage3)
        '    TabControl1.TabPages.Remove(TabPage4)

        'End If
        'SMTP
        'XMLelementliste = ConfigXml.GetElementsByTagName("SMTP")
        'TypeEmetteurFichier = XMLelementliste.Item(0).Item("TypeEmetteurFichier").InnerText
        'NumEmetteurFichier = XMLelementliste.Item(0).Item("NumEmetteurFichier").InnerText
        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
        Traitement_Retour()
        Affichage()

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

    Private Sub Teletransmission_MAIN_FormClosed(ByVal sender As Object, ByVal e As System.Windows.Forms.FormClosedEventArgs) Handles Me.FormClosed
        MENU_PRINCIPAL.Enabled = True

    End Sub

    Private Sub RetransmissionLotToolStripMenuItem_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles RetransmissionLotToolStripMenuItem.Click
        Getmail()
        Dim FichierARL As String = Dir("C:\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("C:\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.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
    Public Shared Function Compress(ByVal cheminSource As String, ByVal cheminCible As String) As String
        Try
            Dim hbread As New BinaryReader(File.OpenRead(cheminSource))
            Dim F_array(hbread.BaseStream.Length) As Byte
            hbread.BaseStream.Seek(0, SeekOrigin.Begin)
            hbread.BaseStream.Read(F_array, 0, F_array.Length)
            hbread.BaseStream.Flush()
            hbread.Close()
            Dim tmpstream As FileStream = New FileStream(cheminCible, FileMode.OpenOrCreate)
            Dim gzipper As GZipStream = New GZipStream(tmpstream, CompressionMode.Compress)
            gzipper.Write(F_array, 0, F_array.Length)
            gzipper.Flush()
            gzipper.Close()
            Return "compression effectuée avec succés"
        Catch ex As Exception
            Return ex.ToString
        End Try
    End Function

    Public Function compresserFichier(ByVal cheminSource As String, ByVal cheminDestination As String) As Boolean
        ' cheminSource : chemin complet du fichier à compresser
        ' cheminDestination : chemin complet du fichier compressé à créer

        Try

            ' Le fichier est placé dans le FileStream
            Dim monFileStream As New FileStream(cheminSource, FileMode.Open)


            Dim monBuffer(monFileStream.Length) As Byte
            ' Lecture de l'intégralité du FileStream
            monFileStream.Read(monBuffer, 0, CInt(monFileStream.Length))
            ' Fermeture du FileStream
            monFileStream.Close()
            ' Création du fichier qui va contenir le fichier compressé
            monFileStream = New FileStream(cheminDestination, FileMode.Create)

            ' Compression des données
            Dim monGZipStream As New GZipStream(monFileStream, CompressionMode.Compress, False)
            ' Ecriture des données compressées dans le fichier de destination
            monGZipStream.Write(monBuffer, 0, monBuffer.Length)
            ' Fermeture du GZipStream
            monGZipStream.Close()

            Return True

        Catch ex As Exception

            Return False
            MsgBox(ex.Message)

        End Try

    End Function

    Public Function decompression(ByVal cheminSource As String, ByVal cheminDestination As String) As Boolean
        ' cheminSource : chemin complet du fichier compressé
        ' cheminDestination : chemin complet du fichier où le fichier doit être décompressé

        Try

            'Lecture du fichier compresse
            Dim monFileStream As New FileStream(cheminSource, FileMode.Open)
            ' Données du fichier placées dans un GZipStream
            Dim monGzipStream As New GZipStream(monFileStream, CompressionMode.Decompress)

            ' Tableau qui va contenir la taille du fichier
            Dim tailleOctets(3) As Byte

            ' Positionnement dans le Stream pour récupérer la taille
            Dim position As Integer = CInt(monFileStream.Length - 4)
            monFileStream.Position = position

            ' Récupération de la taille du fichier
            monFileStream.Read(tailleOctets, 0, 4)

            ' Repositionnement en début du Stream
            monFileStream.Position = 0

            ' Conversion de la taille du fichier en entier
            Dim tailleFichier As Integer = BitConverter.ToInt32(tailleOctets, 0)
            ' Dimesionnement du buffer
            Dim buffer(tailleFichier + 100) As Byte
            ' Offset qui permettra de se repérer dans le Stream
            Dim monOffset As Integer = 0


            While (True)

                ' Les données sont décompressées et placées dans le buffer
                Dim decompressionOctets As Integer = monGzipStream.Read(buffer, monOffset, 100)

                ' Tant qu'il reste des données on continue
                If (decompressionOctets = 0) Then
                    Exit While
                End If

                ' On icrémente l'offset pour ne pas repartir de 0 à chaque fois...
                monOffset += decompressionOctets

            End While

            ' Création du fichier décompressé
            monFileStream = New FileStream(cheminDestination, FileMode.Create)
            ' Ecriture des données décomrpessées dans le fichier
            monFileStream.Write(buffer, 0, tailleFichier - 1)

            ' Efface les données en mémoire tampon
            monFileStream.Flush()

            ' Fermeture des Streams
            monFileStream.Close()
            monGzipStream.Close()

            Return True

        Catch ex As Exception

            Return False
            MsgBox(ex.Message)

        End Try

    End Function

#End Region

#Region "Tableaux Factures et Lots"
    'tableaux avec les factures
    Private Sub LoadFSE()
        ReDim FSE_Tab(0)
        Dim file As String = Dir("c:\factures\*.fse")
        Dim compteurfactures As Integer = 0
        Do Until file = ""
            'MsgBox(file)
            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 As DataTable = Me.FacturesTableAdapter1.GetFactureDataByNum1(FSE_Tab(compteurfactures).NumFacture)
                If mydatatable.Rows.Count <> 1 Then
                    MsgBox("erreur: pas ou plusieurs enregisrements dans bdd facture num " + FSE_Tab(compteurfactures).NumFacture)
                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"
                            FSE_Tab(compteurfactures).CodeRégime = mydatatable(0).Item(c)
                        Case "G1310C2"
                            FSE_Tab(compteurfactures).CaisseGestionnaire = mydatatable(0).Item(c)
                        Case "G1310C3"
                            FSE_Tab(compteurfactures).CentreGestionnaire = mydatatable(0).Item(c)
                        Case "G1910C2"
                            FSE_Tab(compteurfactures).Total_montants_facturés = mydatatable(0).Item(c)
                        Case "G1910C3"
                            FSE_Tab(compteurfactures).MontantAMO = mydatatable(0).Item(c)
                        Case "G1910C4"
                            FSE_Tab(compteurfactures).MontantAMC = mydatatable(0).Item(c)
                        Case "G1110C3"
                            FSE_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 "G1410C1"
                            If mydatatable(0).Item(c) = "2" Or mydatatable(0).Item(c) = "3" Or mydatatable(0).Item(c) = "5" Then
                                FSE_Tab(compteurfactures).TP_AMO = True
                            Else
                                FSE_Tab(compteurfactures).TP_AMO = False
                            End If
                    End Select
                Next
                FSE_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 FSE_Tab(FSE_Tab.Length - 2)
    End Sub
    Private Sub LoadDRE()
        ReDim DRE_Tab(0)
        Dim file As String = Dir("c:\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
                    MsgBox("erreur: pas ou plusieurs enregisrements dans bdd facture num " + DRE_Tab(compteurfactures).NumFacture)
                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
    Private Sub ConstitutionLotsButton_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles ConstitutionLotsButton.Click
        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 G8C4 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
                SGD_AjouterChamp_Tracé(NumeroSessionLot, "TESTCNDA1408", Visu_API, FichierTrace)
                'SGD_AjouterChamp_Tracé(NumeroSessionLot, "TESTTOTO9999", 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
                SGD_AjouterChamp_Tracé(NumeroSessionLot, Mid(ValeurChamp, 1, TailleMax), Visu_API, FichierTrace)
                G8C4 = 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
                    '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
                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
                    MsgBox(datatable.Rows.Count)
                    Me.LotsTableAdapter.Delete_By_référence(RéférenceLotFSE_SV, Nothing)
                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("c:\factures\" + FSE_Tab(j).file)
                        My.Computer.FileSystem.WriteAllBytes("c:\factures\lots\temp", bytes, True)
                        FSE_Tab(j).traitée = True
                        Me.FacturesTableAdapter1.Update_Num_Lot_FSE(RéférenceLotFSE_bdd.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, "c:\factures\lots\temp")
                Try
                    My.Computer.FileSystem.DeleteFile("c:\factures\lots\temp")
                Catch exep As Exception
                    MsgBox(exep.ToString)
                End Try
                '____________________________________________________________________________________________________

                'SIS_FormaterLot
                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
                    MsgBox("erreur constitution lot " + Lots_FSE_Tab(i).Organisme + Chr(10) + out.ToString)
                    Affiche_Lots_à_constituer()
                    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("c:\factures\" + FSE_Tab(j).file, "C:\Factures\Traitées\" + FSE_Tab(j).file)
                        Me.FacturesTableAdapter1.Update_Num_Lot_FSE(RéférenceLotFSE_bdd.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)
                'enregistrement lot dans fichier
                SGD_LireChampFichier(NumeroSessionLot, 11, 1, 1, "C:\Factures\Lots\" + RéférenceLotFSE_SV.ToString + ".lotFSE")

                SCOR_Creer_Lot_justificatif(tab_numfacture_scanordo, G8C4, datelot, RéférenceLotFSE_SV.ToString, Lots_FSE_Tab(i).NbreFactures.ToString, Mid(Lots_FSE_Tab(i).CRL, 19, 1), RéférenceLotFSE_SV)

            End If

            SGD_LibererSession(NumeroSessionLot)

        Next

        LoadFSE()
        LoadLots_FSE()
        Affiche_Lots_à_constituer()
        FSE_DataGridView.Rows.Clear()
        Afficher_lots_à_transmettre()
    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

        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, "TESTCNDA1408", Visu_API, FichierTrace)
                'SGD_AjouterChamp_Tracé(NumeroSessionLot, "TESTTOTO9999", 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
                SGD_AjouterChamp_Tracé(NumeroSessionLot, Mid(ValeurChamp, 1, TailleMax), Visu_API, FichierTrace)

                'Champ5
                If Config.Activer_Session_Remplacement = False Then
                    'Dim mybyte As Byte
                    'MsgBox(SGD_LireChamp(NumeroSessionCPS, 2, 1, 1, mybyte, 1))
                    'MsgBox(SGD_AjouterChamp(NumeroSessionLot, mybyte))
                    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)
                    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)
                Else
                    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)
                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
                    MsgBox(datatable.Rows.Count)
                    MsgBox(RéférenceLotDRE)
                    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("c:\factures\" + DRE_Tab(j).file)
                        My.Computer.FileSystem.WriteAllBytes("c:\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, "c:\factures\lots\temp")
                Try
                    My.Computer.FileSystem.DeleteFile("c:\factures\lots\temp")
                Catch exept As Exception
                    MsgBox(exept.ToString)
                End Try

                '____________________________________________________________________________________________________

                'SIS_FormaterLot
                Dim out As Integer = SIS_FormaterLot(NomRessourcePS, NomRessourceLecteur, "", NumeroSessionLot)
                If out <> 0 Then
                    MsgBox("erreur constitution lot " + out.ToString) ' + Lots_DRE_Tab(i).Organisme + Chr(10) + out.ToString)
                    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("c:\factures\" + DRE_Tab(j).file, "C:\Factures\Traitées\" + DRE_Tab(j).file)
                        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)
                'enregistrement lot dans fichier
                SGD_LireChampFichier(NumeroSessionLot, 91, 1, 1, "C:\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()

    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("C:\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
                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("C:\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
                                    MsgBox("DÉLAI TRANSMISSION OBLIGATOIRE DÉPASSÉ")
                                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()
        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
                                    MsgBox("DÉLAI TRANSMISSION OBLIGATOIRE DÉPASSÉ")
                                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()
        End Select
    End Sub
#Region "FORMATER FICHIER"
    Private Sub FormaterFichiers_FSE()
        '____________________________________________________________________________________________________
        '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
                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)
                Else
                    SGD_AjouterChamp_Tracé(NumeroSessionFichier, "TR", Visu_API, FichierTrace)
                    SGD_AjouterChamp_Tracé(NumeroSessionFichier, "", Visu_API, FichierTrace)
                End If
                '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)

                '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)
                Else
                    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)
                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
                    MsgBox("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)
                    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 = "C:\Factures\Fichiers\" + NomFichier + ".fichierFSE"
                Dim fictemp As String = "C:\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("C:\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("C:\Factures\Lots\" + fichierlot, "C:\Factures\Lots\traités\" + fichierlot)
                        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("C:\Factures\Lots\" + fichierlot, "C:\Factures\Lots\transmis\" + fichierlot)
                        End If
                        lots_traités(j) = 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(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)
                Else
                    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)
                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
                    MsgBox("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)
                    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 = "C:\Factures\Fichiers\" + NomFichier + ".fichierDRE"
                Dim fictemp As String = "C:\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("C:\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("C:\Factures\Lots\" + fichierlot, "C:\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("C:\Factures\Lots\" + fichierlot, "C:\Factures\Lots\transmis\" + fichierlot)
                        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)
                ' MsgBox("verifier existencxe C:\Factures\Fichiers\temp.txt")
                bytes = My.Computer.FileSystem.ReadAllBytes(fictemp)
                My.Computer.FileSystem.WriteAllBytes(fichierDRE, bytes, True)
                My.Computer.FileSystem.DeleteFile(fictemp)
                'SGD_LireChamp(NumeroSessionFichier, 26, 1, 1, ValeurChamp, TailleMax)

                '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()
        '____________________________________________________________________________________________________
        '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
        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)
        Else
            SGD_AjouterChamp_Tracé(NumeroSessionFichier, "TR", Visu_API, FichierTrace)
            SGD_AjouterChamp_Tracé(NumeroSessionFichier, "", Visu_API, FichierTrace)
        End If
        'champ7
        SGD_AjouterChamp_Tracé(NumeroSessionFichier, "00000000000000", Visu_API, FichierTrace)

        '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)
        Else
            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)
        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
            MsgBox("Erreur de Formatage du fichier unique" + Chr(10) + "ERREUR N°:" + out.ToString)
            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 = "C:\Factures\Fichiers\" + NomFichier + ".fichierunique"
        Dim fictemp As String = "C:\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("C:\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
                Me.LotsTableAdapter.Update_Etat("ATTENTE ARL", Val(DataGridView_Lots_FSE_à_transmettre(Référence.Index, j).Value), Nothing) 'update état
                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)
                My.Computer.FileSystem.MoveFile("C:\Factures\Lots\" + fichierlot, "C:\Factures\Lots\transmis\" + fichierlot)
            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("C:\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("C:\Factures\Lots\" + fichierlot, "C:\Factures\Lots\transmis\" + fichierlot)
            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
    Private Sub TransmettreButton_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles TransmettreButton.Click
        RichTextBox1.Clear()
        If Traitement_Retour() = True Then
            If Config.OCT_UtilisationOCT = False Or Config.OCT_FSE_FichierUnique = False Then
                FormaterFichiers_FSE()
                'MsgBox("stop")
                SendMail_FSE()
            Else
                FormaterFichiers_Unique()
                SendMail_Fichier_Unique()
            End If
            Afficher_lots_à_transmettre()
            Afficher_lots_DRE_à_transmettre()
        End If
    End Sub

    'DRE
    Private Sub Button_DRE_Transmettre_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button_DRE_Transmettre.Click
        If Traitement_Retour() = True Then
            FormaterFichiers_DRE()
            'MsgBox("stop")
            SendMail_DRE()
            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
            MsgBox("PAS DE FICHIER A TRANSMETTRE", MsgBoxStyle.Information)
            Exit Sub
        End If
        Using swtrace As New StreamWriter("traces\" + Format(Now, "yyyyMMdd") + "TraceMail_send.txt", True) 'TRACE
            If Config.SMTP_Activer_Serveur_Local = True Then
                Do
                    Dim Référence_Fichier As String = Mid(fichieràtransmettre, 1, InStr(fichieràtransmettre, ".fichierFSE") - 1)
                    'Dim fichiermail As String = Mid(fichieràtransmettre, 1, InStr(fichieràtransmettre, ".fichierFSE") - 1) + ".mail"
                    Dim CRF As String = Me.FichiersSVTableAdapter1.GetDataByNomFichier(Val(fichieràtransmettre)).Item(0).CRF
                    Dim from_, Subject, ContentType As String
                    Dim to_ As String = ""
                    Dim ContentDescription As String = ""
                    Using sw As New StreamWriter(chemin + Référence_Fichier + ".mail", True)
                        swtrace.WriteLine("----------------------------------------------------------------------------------------")
                        swtrace.WriteLine("Date:" + FormatDateTime(Now, DateFormat.GeneralDate))
                        sw.WriteLine("Date:" + FormatDateTime(Now, DateFormat.GeneralDate))
                        '--------------------------------------------------------------------------------------------------------------------------
                        'From
                        from_ = Config.SMTP_From
                        sw.WriteLine("From: " + 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"
                            sw.WriteLine("To:" + to_) 'forçage adresse CNDA 
                            swtrace.WriteLine("To:" + to_) 'forçage adresse CNDA 

                        ElseIf Config.OCT_UtilisationOCT = True Then
                            to_ = Config.OCT_AdressemailOCT
                            sw.WriteLine("To: " + to_)
                            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
                            sw.WriteLine("To:" + to_)
                            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
                        sw.WriteLine("Message-ID: <" + fichieràtransmettre + ">")
                        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
                        sw.WriteLine("Subject: " + Subject)
                        swtrace.WriteLine("Subject: " + Subject)
                        '--------------------------------------------------------------------------------------------------------------------------
                        sw.WriteLine("MIME-Version: 1.0")
                        ContentType = "Application/EDI-consent"
                        sw.WriteLine("Content-Type: Application/EDI-consent")
                        swtrace.WriteLine("Content-Type: Application/EDI-consent")
                        sw.WriteLine("Content-Transfer-Encoding: base64")
                        '--------------------------------------------------------------------------------------------------------------------------
                        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
                        '--------------------------------------------------------------------------------------------------------------------------
                        sw.WriteLine("Content-Description: " + ContentDescription)
                        swtrace.WriteLine("Content-Description: " + ContentDescription)
                        '--------------------------------------------------------------------------------------------------------------------------
                        sw.WriteLine()
                        '--------------------------------------------------------------------------------------------------------------------------
                        Me.SmtpTableAdapter1.Insert1(compteur, FormatDateTime(Now, DateFormat.GeneralDate), fichieràtransmettre, Subject, from_, to_, ContentType, ContentDescription, CRF)
                        '--------------------------------------------------------------------------------------------------------------------------
                    End Using
                    '--------------------------------------------------------------------------------------------------------------------------


                    If UCase(XMLelementliste.Item(0).InnerText) = "OUI" Then 'compression
                        ShellandWait("c:\gzip", "gzip.exe", chemin + fichieràtransmettre)
                        Dim bytes = My.Computer.FileSystem.ReadAllBytes(chemin + fichieràtransmettre + ".gz")
                        Dim base64String As String
                        base64String = System.Convert.ToBase64String(bytes, Base64FormattingOptions.InsertLineBreaks)
                        My.Computer.FileSystem.WriteAllText(chemin + Référence_Fichier + ".mail", base64String, True)
                        swtrace.WriteLine("Num Fichier Transmis: " + Référence_Fichier)


                    Else 'pas de compression
                        Dim bytes = My.Computer.FileSystem.ReadAllBytes(chemin + fichieràtransmettre)
                        Dim base64String As String
                        base64String = System.Convert.ToBase64String(bytes, Base64FormattingOptions.InsertLineBreaks)
                        My.Computer.FileSystem.WriteAllText(chemin + Référence_Fichier + ".mail", base64String, True)
                        swtrace.WriteLine("Num Fichier Transmis: " + Référence_Fichier)
                    End If
                    '--------------------------------------------------------------------------------------------------------------------------
                    Using sw As New StreamWriter(chemin + Référence_Fichier + ".mail", True)
                        sw.WriteLine()
                        sw.WriteLine()
                    End Using
                    '--------------------------------------------------------------------------------------------------------------------------
                    If UCase(XMLelementliste.Item(0).InnerText) = "OUI" Then 'compression
                        fichieràtransmettre = fichieràtransmettre + ".gz"
                    End If
                    My.Computer.FileSystem.MoveFile(chemin + fichieràtransmettre, chemin + "Transmis\" + fichieràtransmettre)
                    XMLelementliste = ConfigXml.GetElementsByTagName("RepertoirePickup")
                    My.Computer.FileSystem.MoveFile(chemin + Référence_Fichier + ".mail", XMLelementliste.Item(0).InnerText + Référence_Fichier + ".mail")
                    '--------------------------------------------------------------------------------------------------------------------------
                    fichieràtransmettre = Dir(chemin + "*.fichierFSE")
                Loop Until fichieràtransmettre = ""
                '--------------------------------------------------------------------------------------------------------------------------


            Else 'Config.SMTP_Activer_Serveur_Local = False
                Do
                    Try
                        Dim Référence_Fichier As String = Mid(fichieràtransmettre, 1, InStr(fichieràtransmettre, ".fichierFSE") - 1)
                        'Dim fichiermail As String = Mid(fichieràtransmettre, 1, InStr(fichieràtransmettre, ".fichierFSE") - 1) + ".mail"
                        Dim CRF As String = Me.FichiersSVTableAdapter1.GetDataByNomFichier(Val(fichieràtransmettre)).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
                        '--------------------------------------------------------------------------------------------------------------------------
                        '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(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)
                        client.UseDefaultCredentials = True
                        client.Send(message)
                        alternate.Dispose()
                        message.Dispose()

                        '--------------------------------------------------------------------------------------------------------------------------
                        My.Computer.FileSystem.MoveFile(chemin + fichieràtransmettre, chemin + "Transmis\" + fichieràtransmettre)

                        fichieràtransmettre = Dir(chemin + "*.fichierFSE")
                    Catch ex As Exception
                        MsgBox("ERREUR TRANSMISSION" + Chr(10) + ex.ToString, MsgBoxStyle.Critical)
                        swtrace.WriteLine(ex.ToString)
                    End Try

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

            End If


        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
            MsgBox("PAS DE FICHIER A TRANSMETTRE", MsgBoxStyle.Information)
            Exit Sub
        End If
        Using swtrace As New StreamWriter("Traces\" + Format(Now, "yyyyMMdd") + "TraceMail_send.txt", True) 'TRACE
            If Config.SMTP_Activer_Serveur_Local = True Then
                Do
                    Dim Référence_Fichier As String = Mid(fichieràtransmettre, 1, InStr(fichieràtransmettre, ".fichierDRE") - 1)
                    Dim CRF As String = Me.FichiersSVTableAdapter1.GetDataByNomFichier(Val(fichieràtransmettre)).Item(0).CRF
                    Dim from_, Subject, ContentType As String
                    Dim to_ As String = ""
                    Dim ContentDescription As String = ""
                    Using sw As New StreamWriter(chemin + Référence_Fichier + ".mail", True)
                        swtrace.WriteLine("----------------------------------------------------------------------------------------")
                        swtrace.WriteLine("Date:" + FormatDateTime(Now, DateFormat.GeneralDate))
                        sw.WriteLine("Date:" + FormatDateTime(Now, DateFormat.GeneralDate))
                        '--------------------------------------------------------------------------------------------------------------------------
                        'From
                        from_ = Config.SMTP_From
                        sw.WriteLine("From: " + 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" 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"
                        '    sw.WriteLine("To:" + to_) 'forçage adresse CNDA 
                        '    swtrace.WriteLine("To:" + to_) 'forçage adresse CNDA 
                        If Config.OCT_UtilisationOCT = True And Config.OCT_FSE_Eclatement_Source = True Then
                            to_ = Config.OCT_AdressemailOCT
                            sw.WriteLine("To:" + to_)
                            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
                            sw.WriteLine("To:" + to_)
                            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()
                            sw.WriteLine("To:" + to_)
                            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
                        sw.WriteLine("Message-ID: <" + fichieràtransmettre + ">")
                        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).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
                        sw.WriteLine("Subject: " + Subject)
                        swtrace.WriteLine("Subject: " + Subject)
                        '--------------------------------------------------------------------------------------------------------------------------
                        sw.WriteLine("MIME-Version: 1.0")
                        ContentType = "Application/EDI-consent"
                        sw.WriteLine("Content-Type: Application/EDI-consent")
                        sw.WriteLine("Content-Transfer-Encoding: base64")
                        '--------------------------------------------------------------------------------------------------------------------------
                        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
                        '--------------------------------------------------------------------------------------------------------------------------
                        sw.WriteLine("Content-Description: " + ContentDescription)
                        swtrace.WriteLine("Content-Description: " + ContentDescription)
                        '--------------------------------------------------------------------------------------------------------------------------
                        sw.WriteLine()
                        '--------------------------------------------------------------------------------------------------------------------------
                        Me.SmtpTableAdapter1.Insert1(compteur, FormatDateTime(Now, DateFormat.GeneralDate), fichieràtransmettre, Subject, from_, to_, ContentType, ContentDescription, CRF)
                        '--------------------------------------------------------------------------------------------------------------------------
                    End Using
                    '--------------------------------------------------------------------------------------------------------------------------
                    If UCase(XMLelementliste.Item(0).InnerText) = "OUI" Then 'compression
                        ShellandWait("c:\gzip", "gzip.exe", chemin + fichieràtransmettre)
                        Dim bytes = My.Computer.FileSystem.ReadAllBytes(chemin + fichieràtransmettre + ".gz")
                        Dim base64String As String
                        base64String = System.Convert.ToBase64String(bytes, Base64FormattingOptions.InsertLineBreaks)
                        My.Computer.FileSystem.WriteAllText(chemin + Référence_Fichier + ".mail", base64String, True)
                        swtrace.WriteLine("Num Fichier Transmis: " + Référence_Fichier)


                    Else 'pas de compression
                        Dim bytes = My.Computer.FileSystem.ReadAllBytes(chemin + fichieràtransmettre)
                        Dim base64String As String
                        base64String = System.Convert.ToBase64String(bytes, Base64FormattingOptions.InsertLineBreaks)
                        My.Computer.FileSystem.WriteAllText(chemin + Référence_Fichier + ".mail", base64String, True)
                        swtrace.WriteLine("Num Fichier Transmis: " + Référence_Fichier)
                    End If
                    '--------------------------------------------------------------------------------------------------------------------------
                    Using sw As New StreamWriter(chemin + Référence_Fichier + ".mail", True)
                        sw.WriteLine()
                        sw.WriteLine()
                    End Using
                    '--------------------------------------------------------------------------------------------------------------------------
                    If UCase(XMLelementliste.Item(0).InnerText) = "OUI" Then 'compression
                        fichieràtransmettre = fichieràtransmettre + ".gz"
                    End If
                    My.Computer.FileSystem.MoveFile(chemin + fichieràtransmettre, chemin + "Transmis\" + fichieràtransmettre)
                    XMLelementliste = ConfigXml.GetElementsByTagName("RepertoirePickup")
                    My.Computer.FileSystem.MoveFile(chemin + Référence_Fichier + ".mail", XMLelementliste.Item(0).InnerText + Référence_Fichier + ".mail")
                    '--------------------------------------------------------------------------------------------------------------------------
                    fichieràtransmettre = Dir(chemin + "*.fichierDRE")
                Loop Until fichieràtransmettre = ""
                '--------------------------------------------------------------------------------------------------------------------------
            Else 'Config.SMTP_Activer_Serveur_Local = false
                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(fichieràtransmettre)).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

                        If 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)
                        client.UseDefaultCredentials = True
                        client.Send(message)
                        alternate.Dispose()
                        message.Dispose()

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

                    Catch ex As Exception
                        MsgBox("ERREUR TRANSMISSION" + Chr(10) + ex.ToString, MsgBoxStyle.Critical)
                        swtrace.WriteLine(ex.ToString)
                    End Try

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

        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
            MsgBox("PAS DE FICHIER A TRANSMETTRE", MsgBoxStyle.Information)
            Exit Sub
        End If
        Using swtrace As New StreamWriter("traces\" + Format(Now, "yyyyMMdd") + "TraceMail_send.txt", True) 'TRACE
            If Config.SMTP_Activer_Serveur_Local = True Then
                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(fichieràtransmettre)).Item(0).CRF
                    Dim from_, Subject, ContentType As String
                    Dim to_ As String = ""
                    Dim ContentDescription As String = ""
                    Using sw As New StreamWriter(chemin + Référence_Fichier + ".mail", True)
                        swtrace.WriteLine("----------------------------------------------------------------------------------------")
                        swtrace.WriteLine("Date:" + FormatDateTime(Now, DateFormat.GeneralDate))
                        sw.WriteLine("Date:" + FormatDateTime(Now, DateFormat.GeneralDate))
                        '--------------------------------------------------------------------------------------------------------------------------
                        'From
                        from_ = Config.SMTP_From
                        sw.WriteLine("From: " + 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" 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"
                            sw.WriteLine("To:" + to_) 'forçage adresse CNDA 
                            swtrace.WriteLine("To:" + to_) 'forçage adresse CNDA 
                        Else

                            to_ = Config.OCT_AdressemailOCT
                            sw.WriteLine("To: " + to_)
                            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
                        '--------------------------------------------------------------------------------------------------------------------------
                        'Message-ID
                        sw.WriteLine("Message-ID: <" + fichieràtransmettre + ">")
                        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
                        sw.WriteLine("Subject: " + Subject)
                        swtrace.WriteLine("Subject: " + Subject)
                        '--------------------------------------------------------------------------------------------------------------------------
                        sw.WriteLine("MIME-Version: 1.0")
                        ContentType = "Application/EDI-consent"
                        sw.WriteLine("Content-Type: Application/EDI-consent")
                        sw.WriteLine("Content-Transfer-Encoding: base64")
                        '--------------------------------------------------------------------------------------------------------------------------
                        XMLelementliste = ConfigXml.GetElementsByTagName("CompresserDonnees")
                        If UCase(XMLelementliste.Item(0).InnerText) = "OUI" Then 'compression
                            sw.WriteLine("Content-Description: FACTURE/SV/Z")
                            swtrace.WriteLine("Content-Description: FACTURE/SV/Z")
                        Else
                            sw.WriteLine("Content-Description: FACTURE/SV")
                            swtrace.WriteLine("Content-Description: FACTURE/SV")
                        End If

                        '--------------------------------------------------------------------------------------------------------------------------
                        sw.WriteLine()
                        '--------------------------------------------------------------------------------------------------------------------------
                        Me.SmtpTableAdapter1.Insert1(compteur, FormatDateTime(Now, DateFormat.GeneralDate), fichieràtransmettre, Subject, from_, to_, ContentType, ContentDescription, CRF)
                        '--------------------------------------------------------------------------------------------------------------------------
                    End Using
                    '--------------------------------------------------------------------------------------------------------------------------
                    If UCase(XMLelementliste.Item(0).InnerText) = "OUI" Then 'compression
                        ShellandWait("c:\gzip", "gzip.exe", chemin + fichieràtransmettre)
                        Dim bytes = My.Computer.FileSystem.ReadAllBytes(chemin + fichieràtransmettre + ".gz")
                        Dim base64String As String
                        base64String = System.Convert.ToBase64String(bytes, Base64FormattingOptions.InsertLineBreaks)
                        My.Computer.FileSystem.WriteAllText(chemin + Référence_Fichier + ".mail", base64String, True)
                        swtrace.WriteLine("Num Fichier Transmis: " + Référence_Fichier)
                    Else 'pas de compression
                        Dim bytes = My.Computer.FileSystem.ReadAllBytes(chemin + fichieràtransmettre)
                        Dim base64String As String
                        base64String = System.Convert.ToBase64String(bytes, Base64FormattingOptions.InsertLineBreaks)
                        My.Computer.FileSystem.WriteAllText(chemin + Référence_Fichier + ".mail", base64String, True)
                        swtrace.WriteLine("Num Fichier Transmis: " + Référence_Fichier)
                    End If
                    '--------------------------------------------------------------------------------------------------------------------------
                    Using sw As New StreamWriter(chemin + Référence_Fichier + ".mail", True)
                        sw.WriteLine()
                        sw.WriteLine()
                    End Using
                    '--------------------------------------------------------------------------------------------------------------------------
                    If UCase(XMLelementliste.Item(0).InnerText) = "OUI" Then 'compression
                        fichieràtransmettre = fichieràtransmettre + ".gz"
                    End If
                    My.Computer.FileSystem.MoveFile(chemin + fichieràtransmettre, chemin + "Transmis\" + fichieràtransmettre)
                    XMLelementliste = ConfigXml.GetElementsByTagName("RepertoirePickup")
                    My.Computer.FileSystem.MoveFile(chemin + Référence_Fichier + ".mail", XMLelementliste.Item(0).InnerText + Référence_Fichier + ".mail")
                    '--------------------------------------------------------------------------------------------------------------------------
                    fichieràtransmettre = Dir(chemin + "*.fichierunique")
                Loop Until fichieràtransmettre = ""
                '--------------------------------------------------------------------------------------------------------------------------
            Else 'Config.SMTP_Activer_Serveur_Local = False
                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(fichieràtransmettre)).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" 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)
                    client.UseDefaultCredentials = True
                    client.Send(message)
                    alternate.Dispose()
                    message.Dispose()
                    '--------------------------------------------------------------------------------------------------------------------------
                  
                    My.Computer.FileSystem.MoveFile(chemin + fichieràtransmettre, chemin + "Transmis\" + fichieràtransmettre)
                    '--------------------------------------------------------------------------------------------------------------------------
                    fichieràtransmettre = Dir(chemin + "*.fichierunique")
                Loop Until fichieràtransmettre = ""
                '--------------------------------------------------------------------------------------------------------------------------
            End If
        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 Function Getmail() As Boolean
        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)
                    MsgBox("ERREUR DE CONNECTION", MsgBoxStyle.Critical)
                    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)
                    MsgBox("ERREUR DE CONNECTION", MsgBoxStyle.Critical)
                    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)
                    MsgBox("ERREUR DE CONNECTION", MsgBoxStyle.Critical)
                    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
                '        RichTextBox1.AppendText("_________________________________________________" + vbCrLf)
                '        RichTextBox1.AppendText("Message " + i.ToString + vbCrLf)
                '        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
                '        'While line <> "" And line <> "."
                '        While line <> "."
                '            RichTextBox1.AppendText(line + vbCrLf)
                '            line = RdStrm.ReadLine
                '        End While
                '        RichTextBox1.AppendText("_________________________________________________" + vbCrLf)
                '    Next
                'End If

                'download mail with number mail parameter

                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
                                    If MsgBox("PRESENCE MESSAGE EXPEDITEUR INCONNU DANS BAL" + Chr(10) + "Exp: " + From_ + Chr(10) + "AJOUTER CET EXPEDITEUR DANS LA LISTE DES EMETTEURS DE CONFIANCE?", 20) = MsgBoxResult.Yes Then
                                        Me.Pop_Allowed_ListTableAdapter.Insert(From_)
                                    Else
                                        If MsgBox("PRESENCE MESSAGE EXPEDITEUR INCONNU DANS BAL" + Chr(10) + "Exp: " + From_ + Chr(10) + "LE TELECHARGER?", 20) = 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
                                            If MsgBox("PRESENCE MESSAGE EXPEDITEUR INCONNU DANS BAL" + Chr(10) + "Exp: " + From_ + Chr(10) + "SUPPRIMER?", 20) = 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 UCase(From_) = UCase(XMLelementliste.Item(0).Item("Postmaster").InnerText) Then
                                message_est_sesamVitale = False
                                'MsgBox(i)
                                '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") + 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)
                                'RichTextBox1.AppendText(Chr(10) + "------------------------------------------------------------------------------------------------" + Chr(10))
                                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)
                                'MsgBox(MyFile)
                                'RichTextBox1.AppendText(Chr(10) + "------------------------------------------------------------------------------------------------" + Chr(10))
                            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 <> ""
                                    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
                                        My.Computer.FileSystem.WriteAllText(Fichier_Pièce_Jointe, line, True)
                                        line = RdStrm.ReadLine
                                    End While
                                End If
                            End If
                            '------------------------------------------------------------------------------------------------
                            'My.Computer.FileSystem.WriteAllText("c:\temp.txt", line + Chr(10), False)
                            If message_est_sesamVitale = True 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"), "", "", "", "", "", "", "")
                            'My.Computer.FileSystem.MoveFile(Fichier_Pièce_Jointe, "C:\Factures\ARL\" + Fichier_ARl.ToString + ".arl")
                            If InStr(Content_Description, "/Z") = Content_Description.Length - 1 Then
                                convert_base64file_to_another_file(Fichier_Pièce_Jointe, "C:\Factures\ARL\" + Fichier_ARl.ToString + ".gz", True)
                                ShellandWait("c:\gzip", "gzip.exe", "-d -q C:\Factures\ARL\" + Fichier_ARl.ToString + ".gz")
                                My.Computer.FileSystem.RenameFile("C:\Factures\ARL\" + Fichier_ARl.ToString, Fichier_ARl.ToString + ".arl")
                            Else
                                convert_base64file_to_another_file(Fichier_Pièce_Jointe, "C:\Factures\ARL\" + Fichier_ARl.ToString + ".arl", True)
                            End If


                        ElseIf InStr(Content_Description, "RSP") = 1 And message_est_sesamVitale = True Then
                            '"RSP/NOEMIE", "RSPDRE/NOEMIE", "RSP/NOEMIE/Z", "RSPDRE/NOEMIE/Z", "RSPTEST/NOEMIE", "RSPDRETEST/NOEMIE", "RSPTEST/NOEMIE/Z", "RSPDRETEST/NOEMIE/Z", "RSPDEMO/NOEMIE", "RSPDREDEMO/NOEMIE", "RSPDEMO/NOEMIE/Z", "RSPDREDEMO/NOEMIE/Z" 
                            'My.Computer.FileSystem.MoveFile(Fichier_Pièce_Jointe, "C:\Factures\RSP\" + Format(Now, "yyyyMMddHHmmss") + "@" + Subject + ".RSP")
                            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, "C:\Factures\RSP\temp.gz", True)
                                ShellandWait("c:\gzip", "gzip.exe", "-d -q C:\Factures\RSP\temp.gz")
                                My.Computer.FileSystem.RenameFile("C:\Factures\RSP\temp", Format(Now, "yyyyMMddHHmmss") + "@" + Subject + ".rsp")
                            Else
                                'convert_base64file_to_another_file(Fichier_Pièce_Jointe, "C:\Factures\RSP\" + Mid(Content_Description, InStr(Content_Description, "/") + 1) _
                                '                                + "@" + Format(Now, "yyyyMMddHHmmss") + "@" + Subject + ".rsp", True)
                                My.Computer.FileSystem.RenameFile("C:\Factures\RSP\temp", Format(Now, "yyyyMMddHHmmss") + "@" + Subject + ".rsp")
                            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
                                MsgBox("Nouveau Fichier Conventions Reçu", MsgBoxStyle.Information, "")
                            ElseIf Mid(Subject, Subject.Length - 1, 2) = "@R" Then
                                MsgBox("Nouveau Fichier Regroupement Reçu", MsgBoxStyle.Information, "")
                            End If




                        ElseIf InStr(Content_Description, "ART/PH") = 1 And message_est_sesamVitale = True Then  'fichiers textes (OCT)
                            MsgBox("fichier texte reçu depuis OCT")
                            Try
                                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 + "OCT." + Format(Now, "yyyyMMddhhss").ToString + Subject + ".txt", True)
                            Catch ex As Exception
                                MsgBox(ex.ToString)
                            End Try

                        Else


                        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
                MsgBox("ERREUR DE CONNECTION")
                swtrace.WriteLine(ex.ToString, True)
                LabelReception.Visible = False
                BAL_relevée = False
                Return False
            End Try
        End Using
        BAL_relevée = True
        Return True
    End Function

    Private Function Traitement_Retour() As Boolean
        If Getmail() = False Then
            Return False
        End If
        Dim FichierARL As String = Dir("C:\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("C:\Factures\ARL\*.arl")
        End While

        Traitement_REJET()

        Postmaster()

        Traitement_RSP()

        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 arlbase64 As String = My.Computer.FileSystem.ReadAllText("C:\Factures\ARL\" + FichierARL)
        'Dim bytes As Byte() = Convert.FromBase64String(arlbase64)
        'Dim arl = System.Text.Encoding.UTF8.GetString(bytes)
        Dim arl As String = My.Computer.FileSystem.ReadAllText("C:\Factures\ARL\" + FichierARL)
        SGD_AjouterChamp(NumeroSession, arl)

        If SIS_TraduireARL(NumeroSession) <> 0 Then
            MsgBox("ERREUR TRADUCTION ARL")
            Exit Sub
        End If



        ValeurChamp = "123456789012"
        Dim i = 1
        While SGD_LireChamp(NumeroSession, 31, i, 2, ValeurChamp, 12) = 0
            'MsgBox(i.ToString)
            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("C:\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("C:\Factures\Lots\transmis\" + file_Lot, "C:\Factures\Lots\traités\" + file_Lot)
            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 = "C:\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)
                MsgBox("RECEPTION D'ARL NON LIÉ" + Chr(10) + "voire dans dossier des ARL", MsgBoxStyle.Information)
            End If
            i = i + 1
        End While
        My.Computer.FileSystem.MoveFile("C:\Factures\ARL\" + FichierARL, "C:\Factures\ARL\Traités\" + FichierARL)


    End Sub
#End Region

#Region "SERVICE/REJET"
    Private Sub Traitement_REJET()
        Dim FichierREJET As String = Dir("C:\Factures\BAL\SERVICE\*.*")
        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
                        Exit For
                    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)
                    Else
                        Me.LotsTableAdapter.Update_Etat(Mid(FichierREJET, 1, InStr(FichierREJET, "@") - 1), Nothing, LotsDataTable(r).Item(Référence_DRE_Index).ToString)
                    End If
                Next
            End If
            My.Computer.FileSystem.MoveFile("C:\Factures\BAL\SERVICE\" + FichierREJET, "C:\Factures\BAL\SERVICE\Traités\" + FichierREJET)
            FichierREJET = Dir()
        End While
    End Sub

#End Region

#Region "RSP"
    Private Sub Traitement_RSP()
        Dim FichierRSP As String = Dir("C:\Factures\RSP\*.rsp")
        While FichierRSP <> ""
            Dim string_RSP As String = My.Computer.FileSystem.ReadAllText("C:\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("C:\Factures\RSP\" + FichierRSP, "C:\Factures\RSP\Traités\" + FichierRSP)
            FichierRSP = Dir()
        End While

        Affiche_Rejets_Paiement()

    End Sub

    Private Sub Affiche_Rejets_Paiement()
        DataGridView_Rejets_Paiements.Rows.Clear()
        Dim mydatatable As DataTable = Me.RSP_LIGNE_REJETTableAdapter.GetDataBy_Acquitement(False, 0)
        If mydatatable.Rows.Count > 0 Then
            For r = 0 To mydatatable.Rows.Count - 1
                DataGridView_Rejets_Paiements.Rows.Add()
                For c = 0 To mydatatable.Columns.Count - 1
                    If mydatatable.Columns.Item(c).ColumnName = "NumFacture" Then
                        DataGridView_Rejets_Paiements.Item(Rejets_Paiement_Num_facture.Index, r).Value = Trim(mydatatable(r).Item(c))
                    ElseIf mydatatable.Columns.Item(c).ColumnName = "NumLot" Then
                        DataGridView_Rejets_Paiements.Item(Rejets_Paiement_Num_Lot.Index, r).Value = Trim(mydatatable(r).Item(c))
                    ElseIf mydatatable.Columns.Item(c).ColumnName = "CODIFICATION" Then
                        DataGridView_Rejets_Paiements.Item(Rejets_Paiement_Codification.Index, r).Value = Trim(mydatatable(r).Item(c))
                    ElseIf mydatatable.Columns.Item(c).ColumnName = "LIBELLE" Then
                        DataGridView_Rejets_Paiements.Item(Rejets_Paiement_Libellé.Index, r).Value = Trim(mydatatable(r).Item(c))
                    ElseIf mydatatable.Columns.Item(c).ColumnName = "NIVEAU" Then
                        DataGridView_Rejets_Paiements.Item(Rejets_Paiement_Niveau.Index, r).Value = Trim(mydatatable(r).Item(c))
                    ElseIf mydatatable.Columns.Item(c).ColumnName = "PART CONCERNE" Then
                        DataGridView_Rejets_Paiements.Item(Rejets_Paiement_Part_Concernée.Index, r).Value = Trim(mydatatable(r).Item(c))
                    ElseIf mydatatable.Columns.Item(c).ColumnName = "NATURE DE PRESTATION" Then
                        DataGridView_Rejets_Paiements.Item(Rejets_Paiement_Nature_Prestation.Index, r).Value = Trim(mydatatable(r).Item(c))
                    ElseIf mydatatable.Columns.Item(c).ColumnName = "DATE DES SOINS" Then
                        DataGridView_Rejets_Paiements.Item(Rejets_Paiement_Date_soins.Index, r).Value = Trim(mydatatable(r).Item(c))
                    ElseIf mydatatable.Columns.Item(c).ColumnName = "N° EXECUTANT" Then
                        DataGridView_Rejets_Paiements.Item(Rejets_Paiement_Num_Executant.Index, r).Value = Trim(mydatatable(r).Item(c))
                    ElseIf mydatatable.Columns.Item(c).ColumnName = "N° DE LIGNE" Then
                        DataGridView_Rejets_Paiements.Item(Rejets_Paiement_Num_Ligne.Index, r).Value = Trim(mydatatable(r).Item(c))
                    ElseIf mydatatable.Columns.Item(c).ColumnName = "RANG DU REJET" Then
                        DataGridView_Rejets_Paiements.Item(Rejets_Paiement_Rang.Index, r).Value = Trim(mydatatable(r).Item(c))
                    ElseIf mydatatable.Columns.Item(c).ColumnName = "INFORMATION COMPLEMENTAIRE" Then
                        DataGridView_Rejets_Paiements.Item(Rejets_Paiement_Info_Compl.Index, r).Value = Trim(mydatatable(r).Item(c))
                    End If
                Next
            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)
                    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 Using
            My.Computer.FileSystem.MoveFile(Config.POP3_RepBAL + file, Config.POP3_RepBAL + "POSTMASTER\" + file)
            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 DataTable
        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
                MsgBox("Pas de lot ayant ce numéro: " + Référence_Lot_FSE.ToString + Référence_Lot_DRE)
                Exit Sub
            Case 1
            Case Else
                MsgBox("INCOHERENCE, Plusieurs lots ayant ce numéro: " + Référence_Lot_FSE.ToString + Référence_Lot_DRE)
                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)
        Else
            mydatatable2 = Me.FacturesTableAdapter1.GetDataBy_Ref_Lot(Référence_Lot_FSE.ToString, Référence_Lot_DRE)
        End If
        If mydatatable2.Rows.Count = 0 Then
            MsgBox("PAS DE FACTURES ASSOCIES", MsgBoxStyle.Exclamation)
            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 ToolStripMenuItem_Annuller_DRE_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles ToolStripMenuItem_Annuller_DRE.Click

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

        If datatable.Rows.Count = 0 Then
            MsgBox("Pas de facture avec ce numéro")
            Exit Sub
        End If

        If datatable.Rows.Count > 1 Then
            MsgBox("ANOMALIE:" + Chr(10) + "Plusieurs factures avec ce numéro", MsgBoxStyle.Critical)
            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
            MsgBox("Cette DRE n'a pas étée transmise, pas d'annullation possible.")
            Exit Sub
        End If

        Dim NbrTransmissions As Integer = Val(Me.LotsTableAdapter.GetDataByRéférence(Nothing, RefLot).Item(0).NombreTransmission)
        If NbrTransmissions = 0 Then
            MsgBox("Cette DRE n'a pas étée transmise, pas d'annullation possible.")
            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
        erreur = SIS_FormaterFactures(NomRessourcePS, NomRessourceLecteur, "", "2", "1", NumeroSessionFacture)
        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
        SGD_LireChamp(NumeroSessionFacture, 160, 1, 1, ValeurChamp, TailleMax) 'ValeurChamp=CRL de DRE
        CurrentFactureVitale.CRLdeDRE = ValeurChamp
        Dim fichierDRE As String = "c:\factures\" + ValeurChamp + "@" + NumFactureString + "@" + idposte + "@" + Format(Now, "yyyyMMddhhmmss") + ".dre"
        SGD_LireChampFichier(NumeroSessionFacture, 160, 1, 2, fichierDRE)


        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
                        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
                Transmis_DataGridView.Rows(r).Cells("Transmis_Action").Value = "action"
                Transmis_DataGridView.Rows(r).DefaultCellStyle.BackColor = Color.Orange

            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

            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
                        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"
                    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 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("C:\Factures\Lots\transmis\" + refLot.ToString + ".lotFSE") Then
                                    My.Computer.FileSystem.MoveFile("C:\Factures\Lots\transmis\" + refLot.ToString + ".lotFSE", "C:\Factures\Lots\traités\" + refLot + ".lotFSE")
                                End If
                            Else
                                If My.Computer.FileSystem.FileExists("C:\Factures\Lots\transmis\" + refLot + ".lotDRE") Then
                                    My.Computer.FileSystem.MoveFile("C:\Factures\Lots\transmis\" + refLot + ".lotDRE", "C:\Factures\Lots\traités\" + refLot + ".lotDRE")
                                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("C:\Factures\Lots\transmis\" + refLot.ToString + ".lotFSE") Then
                                    My.Computer.FileSystem.MoveFile("C:\Factures\Lots\transmis\" + refLot.ToString + ".lotFSE", "C:\Factures\Lots\traités\" + refLot.ToString + ".lotFSE")
                                End If

                            Else
                                Traitement_Manuel_Lot(Nothing, refLot)
                                If My.Computer.FileSystem.FileExists("C:\Factures\Lots\transmis\" + refLot + ".lotDRE") Then
                                    My.Computer.FileSystem.MoveFile("C:\Factures\Lots\transmis\" + refLot + ".lotDRE", "C:\Factures\Lots\traités\" + refLot + ".lotDRE")
                                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("C:\Factures\Lots\traités\" + (Transmis_DataGridView.Rows(Transmis_DataGridView.CurrentRow.Index).Cells("Transmis_Référence").Value).ToString + ".lotFSE") <> "" Then
                                    My.Computer.FileSystem.MoveFile("C:\Factures\Lots\traités\" + (Transmis_DataGridView.Rows(Transmis_DataGridView.CurrentRow.Index).Cells("Transmis_Référence").Value).ToString + ".lotFSE", "C:\Factures\Lots\" + (Transmis_DataGridView.Rows(Transmis_DataGridView.CurrentRow.Index).Cells("Transmis_Référence").Value).ToString + ".lotFSE")
                                    Me.LotsTableAdapter.Update_Etat("A TRANSMETTRE", Val(Transmis_DataGridView.Rows(Transmis_DataGridView.CurrentRow.Index).Cells("Transmis_Référence").Value), "")
                                ElseIf Dir("C:\Factures\Lots\transmis\" + (Transmis_DataGridView.Rows(Transmis_DataGridView.CurrentRow.Index).Cells("Transmis_Référence").Value).ToString + ".lotFSE") <> "" Then
                                    My.Computer.FileSystem.MoveFile("C:\Factures\Lots\transmis\" + (Transmis_DataGridView.Rows(Transmis_DataGridView.CurrentRow.Index).Cells("Transmis_Référence").Value).ToString + ".lotFSE", "C:\Factures\Lots\" + (Transmis_DataGridView.Rows(Transmis_DataGridView.CurrentRow.Index).Cells("Transmis_Référence").Value).ToString + ".lotFSE")
                                    Me.LotsTableAdapter.Update_Etat("A TRANSMETTRE", Val(Transmis_DataGridView.Rows(Transmis_DataGridView.CurrentRow.Index).Cells("Transmis_Référence").Value), "")
                                Else
                                    MsgBox("Fichier Lot Introubable: " + (Transmis_DataGridView.Rows(Transmis_DataGridView.CurrentRow.Index).Cells("Transmis_Référence").Value).ToString + ".lotFSE")
                                End If
                            Else
                                If Dir("C:\Factures\Lots\traités\" + (Transmis_DataGridView.Rows(Transmis_DataGridView.CurrentRow.Index).Cells("Transmis_Référence").Value).ToString + ".lotDRE") <> "" Then
                                    My.Computer.FileSystem.MoveFile("C:\Factures\Lots\traités\" + (Transmis_DataGridView.Rows(Transmis_DataGridView.CurrentRow.Index).Cells("Transmis_Référence").Value).ToString + ".lotDRE", "C:\Factures\Lots\" + (Transmis_DataGridView.Rows(Transmis_DataGridView.CurrentRow.Index).Cells("Transmis_Référence").Value).ToString + ".lotDRE")
                                    Me.LotsTableAdapter.Update_Etat("A TRANSMETTRE", Nothing, Transmis_DataGridView.Rows(Transmis_DataGridView.CurrentRow.Index).Cells("Transmis_Référence").Value)
                                ElseIf Dir("C:\Factures\Lots\transmis\" + (Transmis_DataGridView.Rows(Transmis_DataGridView.CurrentRow.Index).Cells("Transmis_Référence").Value).ToString + ".lotDRE") <> "" Then
                                    My.Computer.FileSystem.MoveFile("C:\Factures\Lots\transmis\" + (Transmis_DataGridView.Rows(Transmis_DataGridView.CurrentRow.Index).Cells("Transmis_Référence").Value).ToString + ".lotDRE", "C:\Factures\Lots\" + (Transmis_DataGridView.Rows(Transmis_DataGridView.CurrentRow.Index).Cells("Transmis_Référence").Value).ToString + ".lotDRE")
                                    Me.LotsTableAdapter.Update_Etat("A TRANSMETTRE", Nothing, Transmis_DataGridView.Rows(Transmis_DataGridView.CurrentRow.Index).Cells("Transmis_Référence").Value)
                                Else
                                    MsgBox("Fichier Lot Introubable: " + (Transmis_DataGridView.Rows(Transmis_DataGridView.CurrentRow.Index).Cells("Transmis_Référence").Value).ToString + ".lotFSE")
                                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("C:\Factures\Lots\transmis\" + refLot.ToString + ".lotFSE") Then
                            My.Computer.FileSystem.MoveFile("C:\Factures\Lots\transmis\" + refLot.ToString + ".lotFSE", "C:\Factures\Lots\traités\" + refLot + ".lotFSE")
                        End If
                    Else
                        Traitement_Manuel_Lot(Nothing, refLot)
                        If My.Computer.FileSystem.FileExists("C:\Factures\Lots\transmis\" + refLot + ".lotDRE") Then
                            My.Computer.FileSystem.MoveFile("C:\Factures\Lots\transmis\" + refLot + ".lotDRE", "C:\Factures\Lots\traités\" + refLot + ".lotDRE")
                        End If
                    End If

                Case "Retransmettre"
                    If IsNumeric(Transmis_DataGridView.Rows(Transmis_DataGridView.CurrentRow.Index).Cells("Transmis_Référence").Value) Then
                        If Dir("C:\Factures\Lots\traités\" + (Transmis_DataGridView.Rows(Transmis_DataGridView.CurrentRow.Index).Cells("Transmis_Référence").Value).ToString + ".lotFSE") <> "" Then
                            My.Computer.FileSystem.MoveFile("C:\Factures\Lots\traités\" + (Transmis_DataGridView.Rows(Transmis_DataGridView.CurrentRow.Index).Cells("Transmis_Référence").Value).ToString + ".lotFSE", "C:\Factures\Lots\" + (Transmis_DataGridView.Rows(Transmis_DataGridView.CurrentRow.Index).Cells("Transmis_Référence").Value).ToString + ".lotFSE")
                            Me.LotsTableAdapter.Update_Etat("A TRANSMETTRE", Val(Transmis_DataGridView.Rows(Transmis_DataGridView.CurrentRow.Index).Cells("Transmis_Référence").Value), "")
                        ElseIf Dir("C:\Factures\Lots\transmis\" + (Transmis_DataGridView.Rows(Transmis_DataGridView.CurrentRow.Index).Cells("Transmis_Référence").Value).ToString + ".lotFSE") <> "" Then
                            My.Computer.FileSystem.MoveFile("C:\Factures\Lots\transmis\" + (Transmis_DataGridView.Rows(Transmis_DataGridView.CurrentRow.Index).Cells("Transmis_Référence").Value).ToString + ".lotFSE", "C:\Factures\Lots\" + (Transmis_DataGridView.Rows(Transmis_DataGridView.CurrentRow.Index).Cells("Transmis_Référence").Value).ToString + ".lotFSE")
                            Me.LotsTableAdapter.Update_Etat("A TRANSMETTRE", Val(Transmis_DataGridView.Rows(Transmis_DataGridView.CurrentRow.Index).Cells("Transmis_Référence").Value), "")
                        Else
                            MsgBox("Fichier Lot Introubable: " + (Transmis_DataGridView.Rows(Transmis_DataGridView.CurrentRow.Index).Cells("Transmis_Référence").Value).ToString + ".lotFSE")
                        End If
                    Else
                        If Dir("C:\Factures\Lots\traités\" + (Transmis_DataGridView.Rows(Transmis_DataGridView.CurrentRow.Index).Cells("Transmis_Référence").Value).ToString + ".lotDRE") <> "" Then
                            My.Computer.FileSystem.MoveFile("C:\Factures\Lots\traités\" + (Transmis_DataGridView.Rows(Transmis_DataGridView.CurrentRow.Index).Cells("Transmis_Référence").Value).ToString + ".lotDRE", "C:\Factures\Lots\" + (Transmis_DataGridView.Rows(Transmis_DataGridView.CurrentRow.Index).Cells("Transmis_Référence").Value).ToString + ".lotDRE")
                            Me.LotsTableAdapter.Update_Etat("A TRANSMETTRE", Nothing, Transmis_DataGridView.Rows(Transmis_DataGridView.CurrentRow.Index).Cells("Transmis_Référence").Value)
                        ElseIf Dir("C:\Factures\Lots\transmis\" + (Transmis_DataGridView.Rows(Transmis_DataGridView.CurrentRow.Index).Cells("Transmis_Référence").Value).ToString + ".lotDRE") <> "" Then
                            My.Computer.FileSystem.MoveFile("C:\Factures\Lots\transmis\" + (Transmis_DataGridView.Rows(Transmis_DataGridView.CurrentRow.Index).Cells("Transmis_Référence").Value).ToString + ".lotDRE", "C:\Factures\Lots\" + (Transmis_DataGridView.Rows(Transmis_DataGridView.CurrentRow.Index).Cells("Transmis_Référence").Value).ToString + ".lotDRE")
                            Me.LotsTableAdapter.Update_Etat("A TRANSMETTRE", Nothing, Transmis_DataGridView.Rows(Transmis_DataGridView.CurrentRow.Index).Cells("Transmis_Référence").Value)
                        Else
                            MsgBox("Fichier Lot Introubable: " + (Transmis_DataGridView.Rows(Transmis_DataGridView.CurrentRow.Index).Cells("Transmis_Référence").Value).ToString + ".lotFSE")
                        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("C:\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 DataTable
        If refLotDRE = "" Then
            factures_datatable = Me.FacturesTableAdapter1.GetDataBy_Ref_Lot(refLot_FSE, Nothing)
        Else
            factures_datatable = Me.FacturesTableAdapter1.GetDataBy_Ref_Lot(Nothing, refLotDRE)
        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" Then
            For r = 0 To factures_datatable.Rows.Count - 1
                If factures_datatable(r).Item(Index_Num_Facture) = 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
            '--------------------------------------------------------------------------------------
            ''maj num lot de la facture --> "traitement manuel"
            'If refLotDRE = "" Then
            '    Me.FacturesTableAdapter1.Update_Num_Lot_FSE("TRAITEMENT MANUEL", Format(Now, "yyyyMMddHHmm"), Val(NumFacture_erreur))
            'Else
            '    Me.FacturesTableAdapter1.Update_Num_Lot_DRE("TRAITEMENT MANUEL", Format(Now, "yyyyMMddHHmm"), Val(NumFacture_erreur))
            'End If
            '--------------------------------------------------------------------------------------
            'deplacement du fichier de la facture en erreur
            'Dim file_fact_erreur As String
            'If refLotDRE = "" Then
            '    file_fact_erreur = Dir("C:\Factures\Traitées\*.fse")
            'Else
            '    file_fact_erreur = Dir("C:\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_erreur Then
            '        My.Computer.FileSystem.MoveFile("C:\Factures\Traitées\" + file_fact_erreur, "C:\Factures\erreur\" + file_fact_erreur)
            '        Exit While
            '    End If
            '    file_fact_erreur = Dir()
            'End While
            '--------------------------------------------------------------------------------------
            'impression duplicata
            VenteForm.Imprime_FSE("Impr_Duplicata")
        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 = ""

        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, "TESTCNDA1408", Visu_API, FichierTrace)
            'SGD_AjouterChamp_Tracé(NumeroSessionLot, "TESTTOTO9999", 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
            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("C:\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("C:\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("C:\Factures\Traitées\" + file_fse)
                        My.Computer.FileSystem.WriteAllBytes("c:\factures\lots\temp", bytes, True)
                        Me.FacturesTableAdapter1.Update_Num_Lot_FSE(RéférenceLotFSE_bdd.ToString, Current_datelot, factures_datatable(r).Item(Index_Num_Facture))
                        Exit While
                    End If
                    file_fse = Dir()
                End While
            Next
            SGD_AjouterChampFichier(NumeroSessionLot, "c:\factures\lots\temp")
            Try
                My.Computer.FileSystem.DeleteFile("c:\factures\lots\temp")
            Catch exep As Exception
                MsgBox(exep.ToString)

            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, "TESTCNDA1408", Visu_API, FichierTrace)
            'SGD_AjouterChamp_Tracé(NumeroSessionLot, "TESTTOTO9999", 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
            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("C:\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("C:\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("C:\Factures\Traitées\" + file_dre)
                        My.Computer.FileSystem.WriteAllBytes("c:\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, "c:\factures\lots\temp")
            Try
                My.Computer.FileSystem.DeleteFile("c:\factures\lots\temp")
            Catch exep As Exception
                MsgBox(exep.ToString)

            End Try
        End If


        '____________________________________________________________________________________________________

        'SIS_FormaterLot
        Dim out As Integer = SIS_FormaterLot(NomRessourcePS, NomRessourceLecteur, "", NumeroSessionLot)
        If out <> 0 Then
            If refLotDRE = "" Then
                MsgBox("erreur reconstitution lot " + refLot_FSE.ToString + Chr(10) + out.ToString)
            Else
                MsgBox("erreur reconstitution lot " + refLotDRE.ToString + Chr(10) + out.ToString)
            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)
            SGD_LireChampFichier(NumeroSessionLot, 11, 1, 1, "C:\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)
            SGD_LireChampFichier(NumeroSessionLot, 91, 1, 1, "C:\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 DataTable
        If refLotDRE = "" Then
            factures_datatable = Me.FacturesTableAdapter1.GetDataBy_Ref_Lot(refLot_FSE, Nothing)
        Else
            factures_datatable = Me.FacturesTableAdapter1.GetDataBy_Ref_Lot(Nothing, refLotDRE)
        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("C:\Factures\Traitées\*.fse")
            Else
                file_fact_erreur = Dir("C:\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
                    My.Computer.FileSystem.MoveFile("C:\Factures\Traitées\" + file_fact_erreur, "C:\Factures\erreur\" + file_fact_erreur)
                    Exit While
                End If
                file_fact_erreur = Dir()
            End While
            '--------------------------------------------------------------------------------------
            'impression duplicata

            VenteForm.Imprime_FSE("Impr_Duplicata")

            '--------------------------------------------------------------------------------------
        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()
            DataGridView_paiements.Item(Paiements_NumFact.Index, r).Value = Facturestable(r).Item(Facturestable_G1110C1_index)
            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 = "Montant_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 = "Montant_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) Then
            MyPrintDocument.Print()
        End If


    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 DataGridView_Rejets_Paiements.CurrentCell.ColumnIndex = Rejets_Paiement_Traitement.Index Then
            Dim current_row_index As Integer = DataGridView_Rejets_Paiements.CurrentRow.Index
            'table des factures constituant le lot en erreur-------------------------------------------
            Dim factures_datatable As DataTable

            factures_datatable = Me.FacturesTableAdapter1.GetFactureDataByNum1(Val(DataGridView_Rejets_Paiements.Item(Rejets_Paiement_Num_facture.Index, current_row_index).Value))
            '------------------------------------------------------------------------------------------
            '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 c = 0 To factures_datatable.Columns.Count - 1
                If factures_datatable.Columns.Item(c).ColumnName = "Num" Then
                    NumFacture_Traitement_Manuel = factures_datatable(0).Item(c)
                ElseIf factures_datatable.Columns.Item(c).ColumnName = "G1110C1" Then
                    CurrentFactureVitale.G1110C1 = factures_datatable(0).Item(c)
                ElseIf factures_datatable.Columns.Item(c).ColumnName = "G1110C3" Then
                    CurrentFactureVitale.G1110C3 = factures_datatable(0).Item(c)
                ElseIf factures_datatable.Columns.Item(c).ColumnName = "IDPrescripteur" Then
                    CurrentFactureVitale.IDPrescripteur = factures_datatable(0).Item(c)
                ElseIf factures_datatable.Columns.Item(c).ColumnName = "G1130C2" Then
                    CurrentFactureVitale.G1130C2 = factures_datatable(0).Item(c)
                ElseIf factures_datatable.Columns.Item(c).ColumnName = "G1130C3" Then
                    CurrentFactureVitale.G1130C3 = factures_datatable(0).Item(c)
                ElseIf factures_datatable.Columns.Item(c).ColumnName = "Assuré" Then
                    CurrentFactureVitale.Assuré = factures_datatable(0).Item(c)
                ElseIf factures_datatable.Columns.Item(c).ColumnName = "Bénéficiaire" Then
                    CurrentFactureVitale.Bénéficiaire = factures_datatable(0).Item(c)
                ElseIf factures_datatable.Columns.Item(c).ColumnName = "G1310C1" Then
                    CurrentFactureVitale.G1310C1 = factures_datatable(0).Item(c)
                ElseIf factures_datatable.Columns.Item(c).ColumnName = "G1310C2" Then
                    CurrentFactureVitale.G1310C2 = factures_datatable(0).Item(c)
                ElseIf factures_datatable.Columns.Item(c).ColumnName = "G1310C3" Then
                    CurrentFactureVitale.G1310C3 = factures_datatable(0).Item(c)
                ElseIf factures_datatable.Columns.Item(c).ColumnName = "G1321C2" Then
                    CurrentFactureVitale.G1321C2 = factures_datatable(0).Item(c)
                ElseIf factures_datatable.Columns.Item(c).ColumnName = "G1321C3" Then
                    CurrentFactureVitale.G1321C3 = factures_datatable(0).Item(c)
                ElseIf factures_datatable.Columns.Item(c).ColumnName = "G1910C2" Then
                    CurrentFactureVitale.G1910C2 = factures_datatable(0).Item(c)
                ElseIf factures_datatable.Columns.Item(c).ColumnName = "G1910C3" Then
                    CurrentFactureVitale.G1910C3 = factures_datatable(0).Item(c)
                ElseIf factures_datatable.Columns.Item(c).ColumnName = "G1910C4" Then
                    CurrentFactureVitale.G1910C4 = factures_datatable(0).Item(c)
                ElseIf factures_datatable.Columns.Item(c).ColumnName = "G1910C6" Then
                    CurrentFactureVitale.G1910C6 = factures_datatable(0).Item(c)
                End If
            Next
            '--------------------------------------------------------------------------------------
            'impression duplicata
            VenteForm.Imprime_FSE("Impr_Duplicata")

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

            If MsgBox("Acquiter le rejet?", 36) = MsgBoxResult.Yes Then
                ''maj num lot de la facture --> "REJETEE"
                'If IsNumeric(DataGridView_Rejets_Paiements.Item(Rejets_Paiement_Num_Lot.Index, DataGridView_Rejets_Paiements.CurrentRow.Index).Value) Then
                '    Me.FacturesTableAdapter1.Update_Num_Lot_FSE("REJETEE", Format(Now, "yyyyMMddHHmm"), NumFacture_Traitement_Manuel)
                'Else
                '    Me.FacturesTableAdapter1.Update_Num_Lot_DRE("REJETEE", Format(Now, "yyyyMMddHHmm"), NumFacture_Traitement_Manuel)
                'End If

                '--------------------------------------------------------------------------------------
                'maj Acquitement RSP --> true
                Me.RSP_LIGNE_REJETTableAdapter.Update_Acquitement(True, DataGridView_Rejets_Paiements.Item(Rejets_Paiement_Num_facture.Index, current_row_index).Value)
                '--------------------------------------------------------------------------------------
                Affiche_Rejets_Paiement()
            End If




        End If

    End Sub

#Region "SCANORDO"

    Private Sub SCOR_Creer_Lot_justificatif(ByVal Tab_NumFacture As String(), ByVal G8C4 As String, ByVal G8C8 As String, ByVal G8C10 As String, ByVal G8C11 As String, ByVal Degradé As String, ByVal NumLot As String)
        '--------------------------------------
        '[RG_TT015] Nombre total doc dans lot  
        Dim NbrDoc, NbrDoc_par_facture As Integer
        Dim fichier As String
        'comptage fichiers xml
        For i = 0 To Tab_NumFacture.Length - 2
            NbrDoc_par_facture = 0
            fichier = Dir(Application.StartupPath + "\scanordo\dos\D-" + Tab_NumFacture(i) + ".xml")
            If fichier <> "" Then
                NbrDoc = NbrDoc + 1
            End If
            fichier = Dir()
        Next
        'comptage autres fichiers 
        For i = 0 To Tab_NumFacture.Length - 2
            NbrDoc_par_facture = 0
            fichier = Dir(Application.StartupPath + "\scanordo\doc\" + Tab_NumFacture(i) + "_*.*")
            While fichier <> ""
                Dim numéro_doc As String = Mid(fichier, InStr(fichier, "_") + 1)
                numéro_doc = Mid(numéro_doc, 1, InStr(numéro_doc, "_") - 1)
                If Val(numéro_doc) > NbrDoc_par_facture Then
                    NbrDoc_par_facture = Val(numéro_doc)
                End If
                fichier = Dir()
            End While
            NbrDoc = NbrDoc + NbrDoc_par_facture
        Next
        If NbrDoc = 0 Then Exit Sub
        '--------------------------------------
        Dim E_Model As New XmlDocument
        E_Model.Load(Application.StartupPath + "\scanordo\lot\E-Model.xml")
        Dim XMLelementliste As XmlNodeList
        '--------------------------------------
        'Identification
        Dim Identification, Emetteur_Identite As String
        ValeurChamp = "12345678"
        TailleMax = 8
        SGD_LireChamp(NumeroSessionCPS, 2, Occurence_Grp2, 9, ValeurChamp, TailleMax)
        Identification = Mid(ValeurChamp, 1, 8)
        Emetteur_Identite = Mid(ValeurChamp, 1, 8)
        ValeurChamp = "1"
        TailleMax = 1
        SGD_LireChamp(NumeroSessionCPS, 2, Occurence_Grp2, 10, ValeurChamp, TailleMax)
        Identification = Identification + Mid(ValeurChamp, 1, 1) + "-" + Format(Now, "yyyyMMddHHmmss") + "00001"
        Emetteur_Identite = Emetteur_Identite + Mid(ValeurChamp, 1, 1)
        XMLelementliste = E_Model.GetElementsByTagName("Identification")
        XMLelementliste.Item(0).InnerText = Identification
        'Temps
        XMLelementliste = E_Model.GetElementsByTagName("Temps")
        XMLelementliste.Item(0).InnerText = Format(Now, "yyyy-MM-dd") + "T" + Format(Now, "HH:mm:ss")
        'Fonction
        XMLelementliste = E_Model.GetElementsByTagName("Fonction")
        If UCase(Config.Logiciel_ModeFonctionement) = "TEST" Then
            XMLelementliste.Item(0).InnerText = "53"
        Else
            XMLelementliste.Item(0).InnerText = "9"
        End If
        'NbrDoc
        XMLelementliste = E_Model.GetElementsByTagName("NbrDoc")
        XMLelementliste.Item(0).InnerText = NbrDoc
        'InfoIDXLOT
        XMLelementliste = E_Model.GetElementsByTagName("InfoIDXLOT")
        XMLelementliste.Item(0).InnerText = "1"
        'InfoNBLOT
        XMLelementliste = E_Model.GetElementsByTagName("InfoNBLOT")
        XMLelementliste.Item(0).InnerText = "1"
        'InfoModeEnvoi
        XMLelementliste = E_Model.GetElementsByTagName("InfoModeEnvoi")
        XMLelementliste.Item(0).InnerText = "TELETRANS"

        'Emetteur
        XMLelementliste = E_Model.GetElementsByTagName("Emetteur")
        ''Identite
        XMLelementliste.Item(0).Item("Identite").InnerText = Emetteur_Identite
        ''Nom
        XMLelementliste.Item(0).Item("Nom").InnerText = G8C4
        ''RPPS
        Dim RPPS As String
        ValeurChamp = "123456789012345678901234567890"
        TailleMax = 30
        SGD_LireChamp(NumeroSessionCPS, 1, 1, 3, ValeurChamp, TailleMax)
        RPPS = Mid(ValeurChamp, 1, TailleMax)
        ValeurChamp = "1"
        TailleMax = 1
        SGD_LireChamp(NumeroSessionCPS, 1, 1, 4, ValeurChamp, TailleMax)
        RPPS = RPPS + Mid(ValeurChamp, 1, TailleMax)
        XMLelementliste.Item(0).Item("RPPS").InnerText = RPPS
        ''Telecom
        '   Type
        XMLelementliste.Item(0).Item("Telecom").Item("Type").InnerText = "EM"
        '   Numero
        XMLelementliste.Item(0).Item("Telecom").Item("Numero").InnerText = Config.SMTP_From
        ''Qualite
        XMLelementliste.Item(0).Item("Qualite").InnerText = "OPORDO"
        ''Region
        XMLelementliste.Item(0).Item("Region").InnerText = "41"
        ''SpecialitePS
        XMLelementliste.Item(0).Item("SpecialitePS").InnerText = "50"
        ''Agrement
        '    Id
        XMLelementliste.Item(0).Item("Agrement").Item("Id").InnerText = Mid("TESTCNDA1408", 1, 8)
        '    Version
        XMLelementliste.Item(0).Item("Agrement").Item("Version").InnerText = Mid("TESTCNDA1408", 9, 4)

        'Recepteur
        XMLelementliste = E_Model.GetElementsByTagName("Recepteur")
        ''Identite
        XMLelementliste.Item(0).Item("Identite").InnerText = Me.FacturesTableAdapter1.GetFactureDataByNum1(Tab_NumFacture(0)).Item(0).G1130C1 + _
                                                             Me.FacturesTableAdapter1.GetFactureDataByNum1(Tab_NumFacture(0)).Item(0).G1130C4
        ''Qualite
        XMLelementliste.Item(0).Item("Qualite").InnerText = "OPAMO"

        'Trace
        XMLelementliste = E_Model.GetElementsByTagName("Trace")
        ''Activite
        XMLelementliste.Item(0).Item("Activite").InnerText = "LOTFSE"
        ''Temps
        XMLelementliste.Item(0).Item("Temps").InnerText = Mid(G8C8, 1, 4) + "-" + Mid(G8C8, 5, 2) + "-" + Mid(G8C8, 7, 2) + "T00:00:00"
        ''Archive
        XMLelementliste.Item(0).Item("Archive").InnerText = G8C10
        ''InfoType
        If Degradé = "D" Then
            XMLelementliste.Item(0).Item("InfoType").InnerText = "2"
        Else
            XMLelementliste.Item(0).Item("InfoType").InnerText = "1"
        End If
        ''InfoNBFACT
        XMLelementliste.Item(0).Item("InfoNBFACT").InnerText = G8C11

        For i = 0 To Tab_NumFacture.Length - 2

            Dim fichierXML As String
            fichierXML = Dir(Application.StartupPath + "\scanordo\dos\D-" + Tab_NumFacture(i) + ".xml")

            If fichierXML <> "" Then

                Dim elem_Lien = E_Model.CreateElement("Lien")
                Dim elem_Document = E_Model.CreateElement("Document")
                '--------------------
                'Mindex
                Dim elem_Mindex = E_Model.CreateElement("Mindex")

                Dim elem_Profil = E_Model.CreateElement("Profil")
                elem_Profil.InnerText = "SCANORDO"

                Dim elem_Identification = E_Model.CreateElement("Identification")
                elem_Identification.InnerText = Tab_NumFacture(i)

                Dim elem_Temps = E_Model.CreateElement("Temps")
                Dim index_xml As New XmlDocument
                index_xml.Load(Application.StartupPath + "\scanordo\dos\D-" + Tab_NumFacture(i) + ".xml")
                elem_Temps.InnerText = index_xml.GetElementsByTagName("Temps").Item(0).InnerText

                elem_Mindex.AppendChild(elem_Profil)
                elem_Mindex.AppendChild(elem_Identification)
                elem_Mindex.AppendChild(elem_Temps)

                elem_Document.AppendChild(elem_Mindex)
                '--------------------
                'Lien

                Dim elem_Adresse = E_Model.CreateElement("Adresse")
                elem_Adresse.InnerText = fichierXML
                Dim elem_Type = E_Model.CreateElement("Type")
                elem_Type.InnerText = "XML"
                elem_Type.SetAttribute("Q", "XML")
                elem_Lien.AppendChild(elem_Adresse)
                elem_Lien.AppendChild(elem_Type)
                elem_Document.AppendChild(elem_Lien)

                Dim fichierPDF = Dir(Application.StartupPath + "\scanordo\doc\" + Tab_NumFacture(i) + "_*.*")
                While fichierPDF <> ""
                    elem_Lien = E_Model.CreateElement("Lien")
                    elem_Adresse = E_Model.CreateElement("Adresse")
                    elem_Adresse.InnerText = fichierPDF
                    elem_Type = E_Model.CreateElement("Type")
                    elem_Type.InnerText = "PDF"
                    elem_Type.SetAttribute("Q", "PDF")
                    Dim elem_Nature = E_Model.CreateElement("Nature")
                    elem_Nature.InnerText = Mid(fichierPDF, InStr(fichierPDF, ".") - 4, 4)
                    elem_Identification = E_Model.CreateElement("Identification")
                    elem_Identification.InnerText = Me.FacturesTableAdapter1.GetFactureDataByNum1(Tab_NumFacture(i)).Item(0).G1211C1 + Me.FacturesTableAdapter1.GetFactureDataByNum1(Tab_NumFacture(i)).Item(0).G1211C2
                    If elem_Identification.InnerText = "" Then
                        elem_Identification.InnerText = Me.FacturesTableAdapter1.GetFactureDataByNum1(Tab_NumFacture(i)).Item(0).G1213C1 + Me.FacturesTableAdapter1.GetFactureDataByNum1(Tab_NumFacture(i)).Item(0).G1213C2
                    End If
                    If elem_Identification.InnerText = "" Then
                        elem_Identification.InnerText = Me.FacturesTableAdapter1.GetFactureDataByNum1(Tab_NumFacture(i)).Item(0).G1214C1 + Me.FacturesTableAdapter1.GetFactureDataByNum1(Tab_NumFacture(i)).Item(0).G1214C2
                    End If
                    Dim my_FileInfo As New FileInfo(Application.StartupPath + "\scanordo\dos\" + fichierPDF)
                    elem_Identification.InnerText = elem_Identification.InnerText + "." + elem_Nature.InnerText + "." _
                    + Me.FacturesTableAdapter1.GetFactureDataByNum1(Tab_NumFacture(i)).Item(0).G1120C1 + Me.FacturesTableAdapter1.GetFactureDataByNum1(Tab_NumFacture(i)).Item(0).G1120C2 + "." _
                    + Me.FacturesTableAdapter1.GetFactureDataByNum1(Tab_NumFacture(i)).Item(0).G1310C1 + Me.FacturesTableAdapter1.GetFactureDataByNum1(Tab_NumFacture(i)).Item(0).G1310C2 + Me.FacturesTableAdapter1.GetFactureDataByNum1(Tab_NumFacture(i)).Item(0).G1310C3 + "." _
                    + Format(my_FileInfo.CreationTime, "yyyyMMddHHmmss") + "000000001"

                    elem_Lien.AppendChild(elem_Adresse)
                    elem_Lien.AppendChild(elem_Type)
                    elem_Lien.AppendChild(elem_Nature)
                    elem_Lien.AppendChild(elem_Identification)
                    elem_Document.AppendChild(elem_Lien)

                    fichierPDF = Dir()
                End While

                '--------------------
                'Document

                E_Model.GetElementsByTagName("Entete").Item(0).AppendChild(elem_Document)

            End If



        Next
        E_Model.Save("c:\test.xml")
        Dim compostage As String = Mid(E_Model.GetElementsByTagName("Identification").Item(0).InnerText, E_Model.GetElementsByTagName("Identification").Item(0).InnerText.Length - 18, 14)
        Dim FileName As String = "E-" + Me.FacturesTableAdapter1.GetFactureDataByNum1(Tab_NumFacture(0)).Item(0).G1120C1 + Me.FacturesTableAdapter1.GetFactureDataByNum1(Tab_NumFacture(0)).Item(0).G1120C2 + _
        "-ENTSCANORDO-" + compostage
        E_Model.Save(Application.StartupPath + "\scanordo\lot\" + FileName + ".xml")

        Using zip As New ZipFile
            For i = 0 To E_Model.GetElementsByTagName("Adresse").Count - 1
                If Mid(E_Model.GetElementsByTagName("Adresse").Item(i).InnerText, 1, 2) = "D-" Then
                    zip.AddFile(Application.StartupPath + "\scanordo\dos\" + E_Model.GetElementsByTagName("Adresse").Item(i).InnerText, "")
                Else
                    zip.AddFile(Application.StartupPath + "\scanordo\doc\" + E_Model.GetElementsByTagName("Adresse").Item(i).InnerText, "")
                End If
            Next
            zip.AddFile(Application.StartupPath + "\scanordo\lot\" + FileName + ".xml", "")
            zip.Save(Application.StartupPath + "\scanordo\lot\" + Mid(FileName, 3) + ".zip")
        End Using
        Me.SCOR_lotsTableAdapter.Insert(FileName, NumLot)

    End Sub

    Public Sub SCOR_envoi_Lot_justificatif(ByVal NumLot As String)
        Using sw As New StreamWriter("c:\mail.txt")
            sw.WriteLine("Date:" + FormatDateTime(Now, DateFormat.GeneralDate))
            sw.WriteLine("From:542025291@resopharma.fr")
            sw.WriteLine("To:01.99@01.cnda.scor.rss.fr")
            sw.WriteLine("Message-ID: <" + Format(Now, "yyyyMMddHHmmss") + ">")
            sw.WriteLine("Subject:SO200000")
            sw.WriteLine("MIME-Version: 1.0")
            sw.WriteLine("Content-Type: Application/EDI-consent")
            sw.WriteLine("Content-Transfer-Encoding: base64")
            sw.WriteLine("Content-Description:ORDOTEST/SEH")
            sw.WriteLine()
            EncryptFile("E-99210411751113234400001.zip", "C:\", New X509Certificate2("c:\certificat.cer"))
            sw.Write(Convert.ToBase64String(My.Computer.FileSystem.ReadAllBytes("C:\496245570-entscanordo-2012012711140023006.enc")))
        End Using
    End Sub
    Public Shared Sub EncryptFile(ByVal inFile As String, ByVal PathFile As String, ByVal Certificat As X509Certificate2)
        Dim rsaPublicKey As RSACryptoServiceProvider
        rsaPublicKey = CType(Certificat.PublicKey.Key, RSACryptoServiceProvider)
        Dim aesManaged As New AesManaged()
        Try
            ' Create instance of AesManaged for
            ' symetric encryption of the data.
            aesManaged.KeySize = 128
            aesManaged.BlockSize = 128
            aesManaged.Mode = CipherMode.CBC
            Dim transform As ICryptoTransform = aesManaged.CreateEncryptor()
            Try
                Dim keyFormatter As New RSAPKCS1KeyExchangeFormatter(rsaPublicKey)
                Dim keyEncrypted As Byte() = keyFormatter.CreateKeyExchange(aesManaged.Key, aesManaged.GetType())

                ' Create byte arrays to contain
                ' the length values of the key and IV.
                Dim LenK(3) As Byte
                Dim LenIV(3) As Byte

                Dim lKey As Integer = keyEncrypted.Length
                LenK = BitConverter.GetBytes(lKey)
                Dim lIV As Integer = aesManaged.IV.Length
                LenIV = BitConverter.GetBytes(lIV)

                ' Write the following to the FileStream
                ' for the encrypted file (outFs):
                ' - length of the key
                ' - length of the IV
                ' - ecrypted key
                ' - the IV
                ' - the encrypted cipher content
                Dim startFileName As Integer = inFile.LastIndexOf("\") + 1
                ' Change the file's extension to ".enc"
                Dim outFile As String = PathFile + inFile.Substring(startFileName, inFile.LastIndexOf(".") - startFileName) + ".enc"
                Directory.CreateDirectory(PathFile)

                Dim outFs As New FileStream(outFile, FileMode.Create)
                Try

                    outFs.Write(LenK, 0, 4)
                    outFs.Write(LenIV, 0, 4)
                    outFs.Write(keyEncrypted, 0, lKey)
                    outFs.Write(aesManaged.IV, 0, lIV)

                    ' Now write the cipher text using
                    ' a CryptoStream for encrypting.
                    Dim outStreamEncrypted As New CryptoStream(outFs, transform, CryptoStreamMode.Write)
                    Try

                        ' By encrypting a chunk at
                        ' a time, you can save memory
                        ' and accommodate large files.
                        Dim count As Integer = 0
                        Dim offset As Integer = 0

                        ' blockSizeBytes can be any arbitrary size.
                        Dim blockSizeBytes As Integer = aesManaged.BlockSize / 8
                        Dim data(blockSizeBytes) As Byte
                        Dim bytesRead As Integer = 0

                        Dim inFs As New FileStream(inFile, FileMode.Open)
                        Try
                            Do
                                count = inFs.Read(data, 0, blockSizeBytes)
                                offset += count
                                outStreamEncrypted.Write(data, 0, count)
                                bytesRead += blockSizeBytes
                            Loop While count > 0
                            inFs.Close()
                        Finally
                            inFs.Dispose()
                        End Try
                        outStreamEncrypted.FlushFinalBlock()
                        outStreamEncrypted.Close()
                    Finally
                        outStreamEncrypted.Dispose()
                    End Try
                    outFs.Close()
                Finally
                    outFs.Dispose()
                End Try
            Finally
                transform.Dispose()
            End Try
        Finally
            aesManaged.Clear()
        End Try

    End Sub 'EncryptFile
#End Region


End Class