' 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.Xml
Imports System.Security.Cryptography.Xml
Imports System.Security.Cryptography
Imports System.Security.Cryptography.X509Certificates
Imports System.Threading
Imports System.IO
Imports System.Text
Imports System.Diagnostics
Imports System.Net
Imports System.Net.Security
Imports System.Reflection
Imports System.Xml.Serialization

Public Class MAIN
    Public Sub save_alerte(ByVal myalerte As alerte, ByVal File As String)
        Dim serializer As New XmlSerializer(GetType(alerte))
        Dim writer As New System.IO.StreamWriter(File)
        serializer.Serialize(writer, myalerte)
        writer.Close()
    End Sub
    Public Sub load_alerte(ByVal File As String, ByRef myalerte As alerte)
        Dim serializer As New XmlSerializer(GetType(alerte))
        Dim reader As New IO.StreamReader(File)
        myalerte = serializer.Deserialize(reader)
        reader.Close()
        reader.Dispose()
    End Sub
    Public Structure configuration
        Dim LocalNetwork_ServerName As String
        Dim DP_Certif As String 'serial number
        Dim DP_URI As String
        Dim DP_Activer As Boolean
        Dim DP_EtaTyp As String
        Dim DP_EtaIdent As String
        'Dim DP_is_local_client As Boolean
        Dim DP_LogValid As String
        Dim DP_LogVers As String
        Dim DP_LogVDP As String
        Dim DP_Directory As String
        Public Sub load()
            Dim ConfigXml As New XmlDocument
            Dim ConfigXMLelementliste As XmlNodeList
            ConfigXml.Load(Application.StartupPath & "\config.xml")

            ConfigXMLelementliste = ConfigXml.GetElementsByTagName("DATA")


            LocalNetwork_ServerName = ConfigXMLelementliste.Item(0).Item("LocalNetwork_ServerName").InnerText
            DP_Certif = ConfigXMLelementliste.Item(0).Item("DP_Certif").InnerText
            DP_URI = ConfigXMLelementliste.Item(0).Item("DP_URI").InnerText
            If UCase(ConfigXMLelementliste.Item(0).Item("DP_Activer").InnerText) = "OUI" Then
                DP_Activer = True
            Else
                DP_Activer = False
            End If
            DP_EtaTyp = ConfigXMLelementliste.Item(0).Item("DP_EtaTyp").InnerText
            DP_EtaIdent = ConfigXMLelementliste.Item(0).Item("DP_EtaIdent").InnerText
            DP_LogValid = ConfigXMLelementliste.Item(0).Item("DP_LogValid").InnerText
            DP_LogVers = ConfigXMLelementliste.Item(0).Item("DP_LogVers").InnerText
            DP_LogVDP = ConfigXMLelementliste.Item(0).Item("DP_LogVDP").InnerText
            DP_Directory = ConfigXMLelementliste.Item(0).Item("DP_Directory").InnerText


        End Sub
    End Structure
    Private Sub MAIN_Load(sender As Object, e As EventArgs) Handles Me.Load

  



        System.Net.ServicePointManager.SecurityProtocol = System.Net.SecurityProtocolType.Tls12

        start()
    End Sub
    Public Sub start()

        Me.WindowState = FormWindowState.Normal
        Try
            Dim toto = BDD.DP_MsgTableAdapter.GetData_where_AR_must_be_send(Now)
        Catch ex As Exception
            MsgBox("IMPOSSIBLE DE SE CONNECTER AU SERVEUR SQL")
            MsgBox(ex.Message)
            Me.Close()
        End Try




        NotifyIcon1.Visible = True
        'nettoyage()

        Config.load()


        Dim list_files_to_delete As New List(Of String)
        Dim file = Dir(Config.LocalNetwork_ServerName & "\DP\Clients\*.*")
        While file <> ""
            If InStr(file, ".xml") = 0 Then
                list_files_to_delete.Add(file)
            End If
            file = Dir()
        End While
        For Each filestrg As String In list_files_to_delete
            Try
                My.Computer.FileSystem.DeleteFile(Config.LocalNetwork_ServerName & "\DP\Clients\" & filestrg)
            Catch ex As Exception
            End Try
        Next
        file = Nothing
        list_files_to_delete = Nothing


        ID_user = "JUJU"
56:     X_DP_Sequence_Number = Val(My.Computer.FileSystem.ReadAllText(Config.LocalNetwork_ServerName & "\DP\X_DP_Sequence_Number"))
        HEARTBEAT_variables.MetNbC = 0
        HEARTBEAT_variables.MetCnx = 0
        HEARTBEAT_variables.MetNbCr = 0
        HEARTBEAT_variables.MetCre = 0
        HEARTBEAT_variables.MetNbCs = 0
        HEARTBEAT_variables.MetCon = 0
        HEARTBEAT_variables.MetNbAl = 0
        HEARTBEAT_variables.MetAli = 0
        HEARTBEAT_variables.MetNbEd = 0
        HEARTBEAT_variables.MetEdi = 0
        HEARTBEAT_variables.MetNbSu = 0
        HEARTBEAT_variables.MetSup = 0
        Write_Trace_Tech("", "IDENTIFIANT_ETABLISSEMENT", Config.DP_EtaTyp & "-" & Config.DP_EtaIdent)
        RichTextBox1.AppendText("IDENTIFIANT_ETABLISSEMENT: " & Config.DP_EtaTyp & "-" & Config.DP_EtaIdent & vbCrLf)
        Write_Trace_Tech("", "DENTIFIANT_LOGICIEL", Config.DP_LogValid & "-" & Config.DP_LogVers & "-" & Config.DP_LogVDP)
        RichTextBox1.AppendText("DENTIFIANT_LOGICIEL: " & Config.DP_LogValid & "-" & Config.DP_LogVers & "-" & Config.DP_LogVDP & vbCrLf)
        RichTextBox1.AppendText("DEMARRAGE DP_Connect.connect" & vbCrLf)

        'Dim chain = New X509Chain()
        'chain.ChainPolicy.RevocationMode = X509RevocationMode.NoCheck
        'chain.Build(DP_get_certif)
        'For r = 0 To chain.ChainElements.Count - 1
        '    MsgBox(chain.ChainElements(r).Certificate.Subject)
        'Next

        connect()

    End Sub

    Private Sub nettoyage()
        Try


            RichTextBox1.AppendText("VIDAGE" & vbCrLf)
            Application.DoEvents()
            Dim file = Dir(Config.LocalNetwork_ServerName & "\DP\XML\log\*.*")
            Dim files_to_delete As New List(Of String)
            While file <> ""
                If file <> "" Then
                    If BDD.DP_ReqTableAdapter.GetDataBy_ReqId(Mid(file, 1, InStr(file, ".") - 1)).Rows.Count > 0 Then
                        If BDD.DP_ReqTableAdapter.GetDataBy_ReqId(Mid(file, 1, InStr(file, ".") - 1)).Item(0).Statut = "OK" Then
                            files_to_delete.Add(file)
                        End If
                    End If
                End If
                file = Dir()
            End While
            RichTextBox1.AppendText("Suppression de " & files_to_delete.Count.ToString & " fichiers" & vbCrLf)
            Application.DoEvents()
            For Each file_ As String In files_to_delete
                Try
                    BDD.DP_ReqTableAdapter.DeleteBy_ReqId(Mid(file_, 1, InStr(file_, ".") - 1))
                    My.Computer.FileSystem.DeleteFile(Config.LocalNetwork_ServerName & "\DP\XML\log\" & file_)
                Catch ex As Exception
                    My.Computer.FileSystem.WriteAllText(Application.StartupPath & "\nettoyage.txt", ex.Message & vbCrLf, True)
                End Try
            Next
        Catch ex As Exception

        End Try
    End Sub

    Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click



        Heartbeat("FIN")
        nettoyage()
        'Environment.Exit(0)
        ' Me.Close()

    End Sub




    Public Async Sub connect()


        'https://blogs.msdn.microsoft.com/webapps/2012/11/05/use-system-net-trace-and-ssl-alert-protocol-to-troubleshoot-ssl-connection-issue/


        'http://zerosandtheone.com/blogs/vb/archive/2009/07/13/ssl-testing-certificate-and-the-net-framework.aspx

        'left with 0 client certificates to choose from'

        'https://support.microsoft.com/fr-fr/help/2464556/failed-tls-connection-between-unified-communications-peers-generates-an-schannel-warning


        Me.Visible = True
        RichTextBox1.AppendText("DP_Connect.connect()" & vbCrLf)
        Application.DoEvents()

        Dim nbre_tentatives As Integer = 1
        DP_connection_établie = False

        Dim Connection_debut, Connection_fin As Date
        Dim objRequest = HttpWebRequest.CreateHttp(Config.DP_URI & Config.DP_EtaTyp & "/" & Config.DP_EtaIdent & "/heartbeat")
        'objRequest = HttpWebRequest.CreateHttp(Config.DP_URI & Config.DP_EtaTyp & "/" & Config.DP_EtaIdent)
        objRequest.ServicePoint.ConnectionLimit = 1
        objRequest.Method = "POST"
        'Dim cert = DP_get_certif()
        'Dim ch = New X509Chain
        'ch.Build(cert)
        'Me.Close()
        'objRequest.ClientCertificates.Add(cert)
        objRequest.ClientCertificates.Add(DP_get_certif)
        Dim datastream As Stream
        Try
            Connection_debut = Now
            datastream = objRequest.GetRequestStream
            Connection_fin = Now
            If objRequest.ServicePoint.CurrentConnections > 0 Then
                HEARTBEAT_variables.calcul_moyenne(HEARTBEAT_variables.MetNbC, HEARTBEAT_variables.MetCnx, Connection_debut, Connection_fin)
            End If
        Catch wex As WebException
            Write_Trace_Tech(wex.Message, "CONNEXION_REFUSEE", DP_get_certif.Subject)
            RichTextBox1.AppendText("CONNEXION REFUSÉE" & vbCrLf)
            Application.DoEvents()
            My.Computer.FileSystem.WriteAllText(Application.StartupPath & "\error.log", vbCrLf & "@@@" & vbCrLf & MethodBase.GetCurrentMethod.Name & vbCrLf & wex.Message & vbCrLf & "@@@" & vbCrLf, True)
        Catch ex As Exception
            Write_Trace_Tech(ex.Message, "CONNEXION_REFUSEE", DP_get_certif.Subject)
            RichTextBox1.AppendText("CONNEXION REFUSÉE" & vbCrLf)
            Application.DoEvents()
            My.Computer.FileSystem.WriteAllText(Application.StartupPath & "\error.log", vbCrLf & "@@@" & vbCrLf & MethodBase.GetCurrentMethod.Name & vbCrLf & ex.Message & vbCrLf & "@@@" & vbCrLf, True)
        End Try
        DP_connection_établie = objRequest.ServicePoint.CurrentConnections > 0

        While DP_connection_établie = False And nbre_tentatives <= 3

            nbre_tentatives = nbre_tentatives + 1
            Dim Generator As System.Random = New System.Random()
            Await Task.Delay(45000 + Generator.Next(0, 30000))
            objRequest = System.Net.HttpWebRequest.CreateHttp(Config.DP_URI & Config.DP_EtaTyp & "/" & Config.DP_EtaIdent & "/heartbeat")
            objRequest.Method = "POST"
            Try
                Connection_debut = Now
                datastream = objRequest.GetRequestStream
                Connection_fin = Now
                If objRequest.ServicePoint.CurrentConnections > 0 Then
                    HEARTBEAT_variables.calcul_moyenne(HEARTBEAT_variables.MetNbC, HEARTBEAT_variables.MetCnx, Connection_debut, Connection_fin)
                End If
            Catch ex As Exception
                Write_Trace_Tech(ex.Message, "CONNEXION_REFUSEE", DP_get_certif.Subject)
                RichTextBox1.AppendText("CONNEXION REFUSÉE" & vbCrLf)
                Application.DoEvents()
            End Try
            DP_connection_établie = objRequest.ServicePoint.CurrentConnections > 0
        End While
        If DP_connection_établie = False Then

            Dim nbre_minute_avant_tentative As Integer = Val(InputBox("Le logiciel n’arrive pas à se connecter au Dossier Pharmaceutique. L’accès est provisoirement désactivé pendant une période de 15 min." + Chr(10) _
                                                                      + "Saisissez une valeur pour modifier ce délai (0 pour desactiver la connection au DP)", "Problème de connexion au DP", "15"))
            If nbre_minute_avant_tentative = 0 Then
                Write_Trace_Tech("DP désactivé par l'utilisateur après echec connexion", "CONNEXION_REFUSEE", DP_get_certif.Subject)
                RichTextBox1.AppendText("DP désactivé par l'utilisateur après echec connexion" & vbCrLf)
                Application.DoEvents()
                DP_connection_établie = False
                Config.DP_Activer = False
                Dim ConfigXml As New XmlDocument
                ConfigXml.Load(Application.StartupPath + "\config.xml")
                Dim XMLelementliste As XmlNodeList
                XMLelementliste = ConfigXml.GetElementsByTagName("DP")
                XMLelementliste.Item(0).Item("DP_Activer").InnerText = "NON"
                ConfigXml.Save("config.xml")
                Exit Sub
            End If
            'While DP_connection_établie = False
            '    Await Task.Delay(nbre_minute_avant_tentative * 60 * 1000)
            '    objRequest = System.Net.HttpWebRequest.CreateHttp(Config.DP_URI & Config.DP_EtaTyp & "/" & Config.DP_EtaIdent & "/heartbeat")
            '    objRequest.Method = "POST"
            '    Try
            '        Connection_debut = Now
            '        datastream = objRequest.GetRequestStream
            '        Connection_fin = Now
            '        If objRequest.ServicePoint.CurrentConnections > 0 Then
            '            HEARTBEAT_variables.calcul_moyenne(HEARTBEAT_variables.MetNbC, HEARTBEAT_variables.MetCnx, Connection_debut, Connection_fin)
            '        End If
            '    Catch ex As Exception
            '        Write_Trace_Tech(ex.Message, "CONNEXION_REFUSEE", DP_get_certif.Subject)
            '        RichTextBox1.AppendText("CONNEXION REFUSÉE" & vbCrLf)
            '        Application.DoEvents()
            '    End Try
            '    DP_connection_établie = objRequest.ServicePoint.CurrentConnections > 0
            'End While
            DP_connection_établie = True
        End If
        'Write_Trace_Tech("", "CONNEXION_ETABLIE", DP_get_certif.Subject)
        RichTextBox1.AppendText("SAISIE CODE CPS ATTENDU" & vbCrLf)
        Application.DoEvents()
        If DP_Connection_reseted = True Then
            DP_Connection_reseted = False
        End If
        Try
            objRequest.GetResponse()
        Catch ex As Exception
            My.Computer.FileSystem.WriteAllText(Application.StartupPath & "\error.log", vbCrLf & "@@@" & vbCrLf & MethodBase.GetCurrentMethod.Name & vbCrLf & ex.Message & vbCrLf & "@@@" & vbCrLf, True)
        End Try


        'DP_queue_iam()
        'DP_queue()
        If DP_Heartbeat_Debut_envoyé = False Then
            Dim Generator2 As System.Random = New System.Random()
            ' Await Task.Delay(Generator2.Next(0, 15 * 60 * 1000))
            Heartbeat("DEBUT")


            DP_Heartbeat_Debut_envoyé = True
        End If


        RichTextBox1.AppendText("DEMARRAGE SERVEUR DE RELAI DES REQUETES POSTES CLIENTS" & vbCrLf)
        Application.DoEvents()
        Local_Server()
        RichTextBox1.AppendText("DEMARRÉ" & vbCrLf)
        Application.DoEvents()

        RichTextBox1.AppendText("demarrage service d'envoi des ar_msg" & vbCrLf)
        Application.DoEvents()
        send_AR_MSG()
        RichTextBox1.AppendText("demarré" & vbCrLf)
        Application.DoEvents()

        While DP_connection_établie = True


            Dim Generator2 As System.Random = New System.Random()
            Await Task.Delay(885000 + Generator2.Next(0, 30000))
            Heartbeat("SUITE")
            Try
                BDD.DP_ReqTableAdapter.Update_Requetes_Perimées(DateTime.Now.AddMonths(-4)) 'les requetes en file d'attente non transmises sous 4 mois ne doivent pas être transmises
            Catch ex As Exception
            End Try
            DP_queue_iam()
            DP_queue()

        End While


        Await Task.Delay(1)


    End Sub
#Region "FILE D'ATTENTE"
    Public Sub DP_queue()
        Try


            RichTextBox1.AppendText(vbCrLf & "file d'attente " & BDD.DP_ReqTableAdapter.GetData_Queue(Now).Rows.Count.ToString)
            While BDD.DP_ReqTableAdapter.GetData_Queue(Now).Rows.Count > 0
                Dim req_row As DP_Relay.PharmaDataSet1.DP_ReqRow
                Try
                    req_row = BDD.DP_ReqTableAdapter.GetData_Queue(Now).Item(0)
                Catch ex As Exception
                    Exit Sub
                End Try


                Try

                    Dim xmlreq As New XmlDocument
                    xmlreq.Load(Config.LocalNetwork_ServerName & "\DP\XML\log\" & req_row.ReqId & ".xml")

                    If DP_objRequest_has_been_used = True Then
                        If Not DP_objRequest Is Nothing Then DP_objRequest.Headers.Clear()
                    Else
                        DP_objRequest_has_been_used = True
                    End If

                    'signature
                    Sign_XML(Config.LocalNetwork_ServerName & "\DP\XML\log\" & req_row.ReqId & ".xml", req_row.ReqId, Config.LocalNetwork_ServerName & "\DP\XML\log\" & req_row.ReqId & ".signed")

                    Dim xmldoc As New XmlDocument
                    xmldoc.Load(Config.LocalNetwork_ServerName & "\DP\XML\log\" & req_row.ReqId & ".signed")

                    Dim postdata_signed As String = xmldoc.OuterXml

                    Dim byteArray As Byte() = Encoding.UTF8.GetBytes(postdata_signed)



                    DP_objRequest = System.Net.HttpWebRequest.CreateHttp(Config.DP_URI & Config.DP_EtaTyp & "/" & Config.DP_EtaIdent & "/alimentation")

                    DP_objRequest.ContentLength = byteArray.Length

                    DP_objRequest.Timeout = "30000"

                    DP_objRequest.Method = "POST"

                    DP_objRequest.ClientCertificates.Add(DP_get_certif)

                    DP_objRequest.UserAgent = Config.DP_EtaTyp & "-" & Config.DP_EtaIdent & "-" & Config.DP_LogValid & "-" & Config.DP_LogVers & "-" & Config.DP_LogVDP

                    DP_objRequest.ContentType = "application/vnd.cnop.dp.alimentation+signature"

                    DP_objRequest.Headers.Add("X-DP-ReqId", req_row.ReqId)

                    DP_objRequest.Headers.Add("X-DP-Sequence-Number", req_row.Sequence_Number)

                    DP_objRequest.Headers.Add("X-DP-ASyncReq", "Alimentation")



                    '''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''
                    'envoi


                    Dim dataStream As Stream = DP_objRequest.GetRequestStream

                    dataStream.Write(byteArray, 0, byteArray.Length)

                    dataStream.Close()

                    Write_Trace_Tech(req_row.ReqId, "REQUETE_EN_ATTENTE_RENVOYEE", "")

                    Dim objResponse As System.Net.HttpWebResponse
                    Dim request_time_debut, request_time_fin As Date
                    Write_Trace_Tech(req_row.ReqId, "ALIMENTATION", req_row.Identifiant_patient)
                    request_time_debut = Now
                    objResponse = DP_objRequest.GetResponse()
                    request_time_fin = Now
                    HEARTBEAT_variables.calcul_moyenne(HEARTBEAT_variables.MetNbAl, HEARTBEAT_variables.MetAli, request_time_debut, request_time_fin)

                    Dim StreamReader As System.IO.StreamReader
                    StreamReader = New System.IO.StreamReader(objResponse.GetResponseStream())

                    My.Computer.FileSystem.WriteAllText(Config.LocalNetwork_ServerName & "\DP\XML\log\Réponse\REP_REQUETE_EN_ATTENTE_RENVOYEE_" & Format(Now, "yyyyMMddHHmmss") & "_" & req_row.ReqId & ".xml", StreamReader.ReadToEnd.ToString, False)
                    Write_Trace_Fonc_Queue("Alimentation du DP effectuée", req_row.référence_interne, "réemission requete en echec", req_row.Identifiant_patient)
                    Write_Trace_Tech(req_row.ReqId, "REP_ALIMENTATION", "OK")
                    BDD.DP_ReqTableAdapter.Update_byReqId(req_row.Sequence_Number, "OK", req_row.nbr_trans + 1, Now, req_row.Identifiant_patient, req_row.référence_interne, req_row.ReqId)

                Catch ex As System.Net.WebException

                    If Not ex.Response Is Nothing Then
                        Dim StreamReader As System.IO.StreamReader
                        StreamReader = New System.IO.StreamReader(ex.Response.GetResponseStream)

                        My.Computer.FileSystem.WriteAllText(Config.LocalNetwork_ServerName & "\DP\XML\log\Réponse\temp", StreamReader.ReadToEnd.ToString, False)
                        StreamReader.Close()

                        Dim xml_retour As New XmlDocument
                        xml_retour.Load(Config.LocalNetwork_ServerName & "\DP\XML\log\Réponse\temp")
                        Dim XMLelementliste As XmlNodeList
                        XMLelementliste = xml_retour.GetElementsByTagName("acknowledgementDetail")

                        If XMLelementliste.Item(0).Item("code").GetAttribute("code") <> "ERREUR_TECHNIQUE" Then
                            BDD.DP_ReqTableAdapter.Update_byReqId(req_row.Sequence_Number.ToString, XMLelementliste.Item(0).Item("code").GetAttribute("code"), req_row.nbr_trans + 1, Now, req_row.Identifiant_patient, req_row.référence_interne, req_row.ReqId)
                            Write_Trace_Tech(req_row.ReqId, "REP_ALIMENTATION", XMLelementliste.Item(0).Item("code").GetAttribute("code") & "|" & XMLelementliste.Item(0).Item("text").InnerText)
                            Write_Trace_Fonc_Queue("Échec de l’alimentation du DP", req_row.référence_interne, "Alimentation non effectuée suite à un problème technique", req_row.Identifiant_patient)

                        Else
                            Dim next_trans_time As Date = Now
                            Dim Generator As System.Random = New System.Random()
                            Select Case req_row.nbr_trans
                                Case 2
                                    next_trans_time = next_trans_time.AddHours(24)
                                    next_trans_time = next_trans_time.AddMinutes(Generator.Next(0, 59))
                                Case 3
                                    next_trans_time = next_trans_time.AddHours(48)
                                    next_trans_time = next_trans_time.AddMinutes(Generator.Next(0, 59))
                            End Select
                            BDD.DP_ReqTableAdapter.Update_byReqId(req_row.Sequence_Number.ToString, XMLelementliste.Item(0).Item("code").GetAttribute("code"), req_row.nbr_trans + 1, next_trans_time, req_row.Identifiant_patient, req_row.référence_interne, req_row.ReqId)
                            Write_Trace_Tech(req_row.ReqId, "REP_ALIMENTATION", XMLelementliste.Item(0).Item("code").GetAttribute("code") & "|" & XMLelementliste.Item(0).Item("text").InnerText)
                            If (req_row.nbr_trans) < 4 Then
                                Write_Trace_Fonc_Queue("Échec de l’alimentation du DP", req_row.référence_interne, "Problème technique : l'alimentation est mise en file d’attente", req_row.Identifiant_patient)
                                Write_Trace_Tech(req_row.ReqId, "REQUETE_EN_ATTENTE", XMLelementliste.Item(0).Item("code").GetAttribute("code") & "|" & XMLelementliste.Item(0).Item("text").InnerText)
                            Else
                                Write_Trace_Fonc_Queue("Échec de l’alimentation du DP", req_row.référence_interne, "Alimentation non effectuée suite à un problème technique", req_row.Identifiant_patient)
                            End If
                        End If


                    Else
                        Write_Trace_Tech(req_row.ReqId, "REQUETE_EN_ATTENTE", ex.Message.ToString)
                        Write_Trace_Fonc_Queue("Échec de l’alimentation du DP", req_row.référence_interne, "Problème technique : l'alimentation est mise en file d’attente", req_row.Identifiant_patient)
                        BDD.DP_ReqTableAdapter.Update_byReqId(req_row.Sequence_Number, "A_REEMETTRE", req_row.nbr_trans, req_row.next_trans_time.AddMinutes(15), req_row.Identifiant_patient, req_row.référence_interne, req_row.ReqId)


                    End If

                Catch ex2 As Exception


                End Try



            End While
        Catch ex As Exception

        End Try
    End Sub

    Public Sub DP_queue_iam()
        Try
            RichTextBox1.AppendText(vbCrLf & "file d'attente IAM " & BDD.DP_ReqTableAdapter.GetData_Queue_IAM.Rows.Count.ToString)
            While BDD.DP_ReqTableAdapter.GetData_Queue_IAM.Rows.Count > 0

                Dim req_row = BDD.DP_ReqTableAdapter.GetData_Queue_IAM.Item(0)
                Try
                    If DP_objRequest_has_been_used = True Then
                        If Not DP_objRequest Is Nothing Then DP_objRequest.Headers.Clear()
                    Else
                        DP_objRequest_has_been_used = True
                    End If
                    If My.Computer.FileSystem.FileExists(Config.LocalNetwork_ServerName & "\DP\XML\log\" & req_row.ReqId & ".xml") = False Then
                        BDD.DP_ReqTableAdapter.Update_byReqId("", "ERREUR_TECHNIQUE", 2, Now, "IAM", req_row.référence_interne, req_row.ReqId)
                    End If
                    Dim byteArray As Byte() = Encoding.UTF8.GetBytes(My.Computer.FileSystem.ReadAllText(Config.LocalNetwork_ServerName & "\DP\XML\log\" & req_row.ReqId & ".xml"))

                    DP_objRequest = System.Net.HttpWebRequest.CreateHttp(Config.DP_URI & Config.DP_EtaTyp & "/" & Config.DP_EtaIdent & "/iam")

                    DP_objRequest.ContentLength = byteArray.Length

                    DP_objRequest.Timeout = "30000"
                    DP_objRequest.Method = "POST"
                    DP_objRequest.ClientCertificates.Add(DP_get_certif)
                    DP_objRequest.UserAgent = Config.DP_EtaTyp & "-" & Config.DP_EtaIdent & "-" & Config.DP_LogValid & "-" & Config.DP_LogVers & "-" & Config.DP_LogVDP
                    DP_objRequest.ContentType = "application/vnd.cnop.dp.iam"
                    DP_objRequest.Headers.Add("X-DP-ReqId", req_row.ReqId)
                    DP_objRequest.Headers.Add("X-DP-ASyncReq", "Alimentation-IAM")

                    ' Get the request stream.
                    Dim dataStream As Stream = DP_objRequest.GetRequestStream()
                    ' Write the data to the request stream.
                    dataStream.Write(byteArray, 0, byteArray.Length)
                    ' Close the Stream object.
                    dataStream.Close()

                    Write_Trace_Tech(req_row.ReqId, "REQUETE_IAM_EN_ATTENTE_RENVOYEE", "")


                    Dim DP_IAM_objResponse As System.Net.HttpWebResponse = DP_objRequest.GetResponse()


                    'write_Trace_Tech(req_row.ReqId, "REP_ALIMENTATION_IAM_QUEUE", "OK")

                    BDD.DP_ReqTableAdapter.Update_byReqId("", "OK", 2, Now, "IAM", req_row.référence_interne, req_row.ReqId)
                    Dim StreamReader As System.IO.StreamReader
                    StreamReader = New System.IO.StreamReader(DP_IAM_objResponse.GetResponseStream())
                    Dim réponse As String = StreamReader.ReadToEnd.ToString
                    If réponse = "" Then
                        BDD.DP_ReqTableAdapter.Update_byReqId("", "OK", 2, Now, "IAM", req_row.référence_interne, req_row.ReqId)
                        Write_Trace_Tech(req_row.ReqId, "REP_ALIMENTATION_IAM", "OK")
                    Else
                        BDD.DP_ReqTableAdapter.Update_byReqId("", réponse, 2, Now, "IAM", req_row.référence_interne, req_row.ReqId)
                        Write_Trace_Tech(req_row.ReqId, "REP_ALIMENTATION_IAM", réponse)
                    End If


                Catch wex As System.Net.WebException
                    BDD.DP_ReqTableAdapter.Update_byReqId("", wex.Message.ToString, 2, Now, "IAM", req_row.référence_interne, req_row.ReqId)
                    If Not wex.Response Is Nothing Then
                        Dim StreamReader As System.IO.StreamReader
                        StreamReader = New System.IO.StreamReader(wex.Response.GetResponseStream)

                        Write_Trace_Tech(req_row.ReqId, "REP_ALIMENTATION_IAM", CType(wex.Response, System.Net.HttpWebResponse).StatusCode & "|" & wex.Message.ToString)
                        StreamReader.Close()
                    Else
                        Write_Trace_Tech(req_row.ReqId, "REP_ALIMENTATION_IAM", wex.Message.ToString)
                    End If
                Catch ex As Exception
                    Write_Trace_Tech(req_row.ReqId, "REP_ALIMENTATION_IAM", ex.Message.ToString)
                End Try
            End While
        Catch ex As Exception

        End Try
    End Sub
#End Region
    Public Function Heartbeat(ByVal ReqCtx As String) As Boolean

        RichTextBox1.Clear()
        RichTextBox1.AppendText("HEARTBEAT " & ReqCtx & vbCrLf)

        Dim X_DP_ReqId As String = System.Guid.NewGuid.ToString
        Dim objResponse As System.Net.HttpWebResponse
        Dim objRequest As System.Net.HttpWebRequest
        Try
            objRequest = System.Net.HttpWebRequest.CreateHttp(Config.DP_URI & Config.DP_EtaTyp & "/" & Config.DP_EtaIdent & "/heartbeat")
            'objRequest = System.Net.HttpWebRequest.CreateHttp("http://127.0.0.1:13000/" & Config.DP_EtaTyp & "/" & Config.DP_EtaIdent & "/heartbeat")
            'objRequest.SendChunked = False




            Dim postData As String
            postData = "statut=${ReqCtx}&delaiHeartbeats=${ReqDelai}&nombreReconnexions=${MetNbC}&delaiReconnexion=${MetCnx}&nombreCreations=${MetNbCr}&delaiCreation=${MetCre}&" & _
                        "nombreConsultations=${MetNbCs}&delaiConsultation=${MetCon}&nombreAlimentations=${MetNbAl}&delaiAlimentation=${MetAli}&nombreEditions=${MetNbEd}&" & _
                        "delaiEdition=${MetEdi}&nombreSuppressions=${MetNbSu}&delaiSuppression=${MetSup}"

            postData = Replace(postData, "${ReqCtx}", ReqCtx)
            Dim ReqDelai As Integer
            If ReqCtx = "DEBUT" Or HEARTBEAT_variables.ReqDelai_last.ToShortDateString = "01/01/0001" Then
                ReqDelai = 0
            Else
                ReqDelai = DateDiff(DateInterval.Second, HEARTBEAT_variables.ReqDelai_last, Now)
            End If
            postData = Replace(postData, "${ReqDelai}", ReqDelai.ToString)
            postData = Replace(postData, "${MetNbC}", HEARTBEAT_variables.MetNbC)
            postData = Replace(postData, "${MetCnx}", HEARTBEAT_variables.MetCnx)
            postData = Replace(postData, "${MetNbCr}", HEARTBEAT_variables.MetNbCr)
            postData = Replace(postData, "${MetCre}", HEARTBEAT_variables.MetCre)
            postData = Replace(postData, "${MetNbCs}", HEARTBEAT_variables.MetNbCs)
            postData = Replace(postData, "${MetCon}", HEARTBEAT_variables.MetCon)
            postData = Replace(postData, "${MetNbAl}", HEARTBEAT_variables.MetNbAl)
            postData = Replace(postData, "${MetAli}", HEARTBEAT_variables.MetAli)
            postData = Replace(postData, "${MetNbEd}", HEARTBEAT_variables.MetNbEd)
            postData = Replace(postData, "${MetEdi}", HEARTBEAT_variables.MetEdi)
            postData = Replace(postData, "${MetNbSu}", HEARTBEAT_variables.MetNbSu)
            postData = Replace(postData, "${MetSup}", HEARTBEAT_variables.MetSup)
            Dim byteArray As Byte() = Encoding.UTF8.GetBytes(postData)
            objRequest.ContentLength = byteArray.Length

            objRequest.AllowAutoRedirect = False


            objRequest.Method = "POST"
            objRequest.Timeout = 30000
            If ReqCtx = "FIN" Or ReqCtx = "DESACTIVATION" Then
                objRequest.KeepAlive = False
            End If
            objRequest.ClientCertificates.Add(DP_get_certif)

            objRequest.UserAgent = Config.DP_EtaTyp & "-" & Config.DP_EtaIdent & "-" & Config.DP_LogValid & "-" & Config.DP_LogVers & "-" & Config.DP_LogVDP

            objRequest.ContentType = "application/x-www-form-urlencoded"

            objRequest.Headers.Add("X-DP-ReqId", X_DP_ReqId)

            'Get the request stream.
            Dim dataStream As Stream = objRequest.GetRequestStream
            ' Write the data to the request stream.
            dataStream.Write(byteArray, 0, byteArray.Length)
            'Close the Stream object.
            dataStream.Close()
            Write_Trace_Tech(X_DP_ReqId, "HEARTBEAT", ReqCtx & "|" & ReqDelai.ToString & "|" & HEARTBEAT_variables.MetNbC & "|" & HEARTBEAT_variables.MetCnx & "|" & HEARTBEAT_variables.MetNbCr & "|" _
                                & HEARTBEAT_variables.MetCre & "|" & HEARTBEAT_variables.MetNbCs & "|" & HEARTBEAT_variables.MetCon & "|" & HEARTBEAT_variables.MetNbAl & "|" & _
                                 HEARTBEAT_variables.MetAli & "|" & HEARTBEAT_variables.MetNbEd & "|" & HEARTBEAT_variables.MetEdi & "|" & HEARTBEAT_variables.MetNbSu & "|" & HEARTBEAT_variables.MetSup)
            RichTextBox1.AppendText("HEARTBEAT " & ReqCtx & "|" & ReqDelai.ToString & "|" & HEARTBEAT_variables.MetNbC & "|" & HEARTBEAT_variables.MetCnx & "|" & HEARTBEAT_variables.MetNbCr & "|" _
                                 & HEARTBEAT_variables.MetCre & "|" & HEARTBEAT_variables.MetNbCs & "|" & HEARTBEAT_variables.MetCon & "|" & HEARTBEAT_variables.MetNbAl & "|" & _
                                  HEARTBEAT_variables.MetAli & "|" & HEARTBEAT_variables.MetNbEd & "|" & HEARTBEAT_variables.MetEdi & "|" & HEARTBEAT_variables.MetNbSu & "|" & HEARTBEAT_variables.MetSup & vbCrLf)
            Application.DoEvents()

            objResponse = objRequest.GetResponse

            If objResponse.StatusCode = 302 Then
                If InStr(objResponse.GetResponseHeader("location"), "lecture_msg") <> 0 Then
                    Dim MsgRef = Mid(objResponse.GetResponseHeader("location"), InStrRev(objResponse.GetResponseHeader("location"), "/") + 1)
                    Write_Trace_Tech(X_DP_ReqId, "REP_HEARTBEAT", "MESSAGE:" & MsgRef)
                    RichTextBox1.AppendText("REP_HEARTBEAT MESSAGE:" & MsgRef & vbCrLf)
                    Application.DoEvents()
                    LECTURE_MSG(MsgRef)
                End If
            Else
                Write_Trace_Tech(X_DP_ReqId, "REP_HEARTBEAT", "OK")
                RichTextBox1.AppendText("REP_HEARTBEAT OK" & vbCrLf)
                Application.DoEvents()
            End If



            HEARTBEAT_variables.ReqDelai_last = Now
            HEARTBEAT_variables.MetNbC = 0
            HEARTBEAT_variables.MetCnx = 0
            HEARTBEAT_variables.MetNbCr = 0
            HEARTBEAT_variables.MetCre = 0
            HEARTBEAT_variables.MetNbCs = 0
            HEARTBEAT_variables.MetCon = 0
            HEARTBEAT_variables.MetNbAl = 0
            HEARTBEAT_variables.MetAli = 0
            HEARTBEAT_variables.MetNbEd = 0
            HEARTBEAT_variables.MetEdi = 0
            HEARTBEAT_variables.MetNbSu = 0
            HEARTBEAT_variables.MetSup = 0




            Dim StreamReader As System.IO.StreamReader
            StreamReader = New System.IO.StreamReader(objResponse.GetResponseStream())
            StreamReader.Close()
            'MsgBox("FIN  Heartbeat -->True")
            Return True


        Catch wex As System.Net.WebException
            If Not wex.Response Is Nothing Then
                Dim StreamReader As System.IO.StreamReader
                StreamReader = New System.IO.StreamReader(wex.Response.GetResponseStream)
                Write_Trace_Tech(X_DP_ReqId, "REP_HEARTBEAT", CType(wex.Response, System.Net.HttpWebResponse).StatusCode & "|" & wex.Message)
                RichTextBox1.AppendText("REP_HEARTBEAT " & CType(wex.Response, System.Net.HttpWebResponse).StatusCode & vbCrLf & wex.Message & vbCrLf)
                Application.DoEvents()
                StreamReader.Close()
                'MsgBox("FIN  Heartbeat --> wex")
            Else
                Write_Trace_Tech(X_DP_ReqId, "REP_HEARTBEAT", wex.Message.ToString)
                RichTextBox1.AppendText("REP_HEARTBEAT " & wex.Message & vbCrLf & "LA CONNECTION VA ETRE REINITIALISEE" & vbCrLf)
                Application.DoEvents()
                'MsgBox("FIN  Heartbeat --> reset_connection()")
                reset_connection()
            End If

        End Try

        'MsgBox("FIN  Heartbeat --> False")
        Return False
    End Function

    Public Config As configuration

    Public X_DP_Sequence_Number As Integer

    Public ID_user As String

    Public DP_objRequest_has_been_used As Boolean

    Public DP_objRequest As System.Net.HttpWebRequest

    Public DP_Missing_Sequence_Numbers() As String


    Public DP_connection_établie As Boolean

    Public DP_Connection_reseted As Boolean

    Public DP_Heartbeat_Debut_envoyé As Boolean


    Public Structure HEARTBEAT_variables_structure
        Dim ReqDelai_last As Date ' date du dernier heartbeat réussi pour calcul de ReqDelai entre Heartbeat secondes

        Dim MetNbC As Integer 'Nombre de reconnexions
        Dim MetCnx As Integer 'Temps de connexion millisecondes

        Dim MetNbCr As Integer 'Nombre de créations
        Dim MetCre As Integer 'Temps de création DP millisecondes

        Dim MetNbCs As Integer 'Nombre de consultations
        Dim MetCon As Integer 'Temps de consultation DP millisecondes

        Dim MetNbAl As Integer 'Nombre d’alimentations
        Dim MetAli As Integer 'Temps d’alimentation DP millisecondes

        Dim MetNbEd As Integer 'Nombre d’éditions
        Dim MetEdi As Integer 'Temps d’édition DP millisecondes

        Dim MetNbSu As Integer 'Nombre de suppressions
        Dim MetSup As Integer 'Temps de suppression DP millisecondes

        Public Sub calcul_moyenne(ByRef nombre As Integer, ByRef moyenne As Integer, ByVal request_time_debut As Date, ByVal request_time_fin As Date)
            Dim date_dif As Global.System.TimeSpan = request_time_fin.Subtract(request_time_debut)
            Dim millisecs As Integer = date_dif.Milliseconds


            moyenne = ((moyenne * nombre) + millisecs) / (nombre + 1)
            nombre = nombre + 1

        End Sub

    End Structure
    Public HEARTBEAT_variables As HEARTBEAT_variables_structure


    Public Function DP_get_certif() As X509Certificate2
        Dim store As New X509Store(StoreLocation.CurrentUser)
        store.Open(OpenFlags.ReadOnly)
        Dim certCollection As X509Certificate2Collection = store.Certificates
        Dim certificate As X509Certificate2 = Nothing
        Dim c As X509Certificate2

        For Each c In certCollection
            If Trim(UCase(c.SerialNumber.ToString)) = Trim(UCase(Config.DP_Certif)) Then '"4C8CC5" Then
                certificate = c
                Exit For
            End If
        Next c
        If certificate Is Nothing Then
        End If
        Return certificate
    End Function

    Public Sub Sign_XML(ByVal Doc_To_Sign_Path As String, ByVal X_DP_ReqId As String, ByVal Signed_Doc_Path As String)
        Try
            If My.Computer.FileSystem.FileExists(Signed_Doc_Path) Then
                My.Computer.FileSystem.DeleteFile(Signed_Doc_Path)
            End If
            ' Load data to sign.
            Dim document As New XmlDocument()
            document.Load(Doc_To_Sign_Path)

            ' Create the SignedXml message.
            Dim signedXml As New SignedXml()
            Dim key As RSA = RSA.Create()
            Dim cert = DP_get_certif()
            key = cert.PrivateKey
            signedXml.SigningKey = key



            ' Create a data object to hold the data to sign.
            Dim dataObject As New DataObject()
            dataObject.Data = document.ChildNodes
            dataObject.Id = X_DP_ReqId

            ' Add the data object to the signature.
            signedXml.AddObject(dataObject)

            ' Create a reference to be able to package everything into the
            ' message.
            Dim reference As New Reference()
            reference.Uri = "#" & X_DP_ReqId

            ' Add the reference to the message.
            signedXml.AddReference(reference)

            ' Add a KeyInfo.
            Dim keyInfo As New KeyInfo()
            'keyInfo.AddClause(New RSAKeyValue(key))
            keyInfo.AddClause(New KeyInfoX509Data(cert))
            signedXml.KeyInfo = keyInfo

            ' Compute the signature.
            signedXml.ComputeSignature()
            My.Computer.FileSystem.WriteAllText(Signed_Doc_Path, signedXml.GetXml.OuterXml, False)
            'Console.WriteLine("The data was signed.")

            For i = 0 To 2
                If Not My.Computer.FileSystem.FileExists(Signed_Doc_Path) Then
                    Thread.Sleep(500)
                End If
            Next

        Catch ex As CryptographicException
            'Console.WriteLine(ex.Message)
        End Try

    End Sub
    Public Sub Sign_XML_sha256(ByVal Doc_To_Sign_Path As String, ByVal X_DP_ReqId As String, ByVal Signed_Doc_Path As String)
        ''''' http://stackoverflow.com/questions/29005876/signedxml-compute-signature-with-sha256 '''''

        Dim cert = DP_get_certif()
        Dim exportedKeyMaterial = cert.PrivateKey.ToXmlString(True)
        Dim key = New RSACryptoServiceProvider(New CspParameters(24))
        key.PersistKeyInCsp = False
        key.FromXmlString(exportedKeyMaterial)
        Dim doc = New XmlDocument
        doc.PreserveWhitespace = True
        doc.Load(Doc_To_Sign_Path)
        Dim signedXml = New SignedXml(doc)
        signedXml.SigningKey = key
        signedXml.SignedInfo.SignatureMethod = "http://www.w3.org/2001/04/xmldsig-more#rsa-sha256"
        Dim reference As New Reference()
        reference.AddTransform(New XmlDsigEnvelopedSignatureTransform())
        reference.AddTransform(New XmlDsigExcC14NTransform())
        reference.Uri = "#" & X_DP_ReqId
        signedXml.AddReference(reference)
        Dim KeyInfo = New KeyInfo()
        KeyInfo.AddClause(New KeyInfoX509Data(cert))
        signedXml.KeyInfo = KeyInfo
        signedXml.ComputeSignature()
        My.Computer.FileSystem.WriteAllText(Signed_Doc_Path, signedXml.GetXml.OuterXml, False)



    End Sub
    Public Sub Next_Sequence_Number(ByVal objResponse As System.Net.HttpWebResponse)
        For i = 0 To objResponse.Headers.Count - 1
            If objResponse.Headers.Keys.Item(i) = "X-DP-Next-Sequence-Number" Then
                X_DP_Sequence_Number = objResponse.Headers.Item(i)
                My.Computer.FileSystem.WriteAllText(Config.LocalNetwork_ServerName & "\DP\X_DP_Sequence_Number", X_DP_Sequence_Number.ToString, False)
                Exit For
            End If
        Next
    End Sub
#Region "Missing Sequence Number"
    Public Sub Missing_Sequence_Number(ByVal objResponse As System.Net.HttpWebResponse, ByVal X_DP_ReqId As String)
        ReDim DP_Missing_Sequence_Numbers(0)
        For i = 0 To objResponse.Headers.Count - 1
            If objResponse.Headers.Keys.Item(i) = "X-DP-Missing-Sequence-Numbers" And objResponse.Headers.Item(i).ToString <> "" Then
                Write_Trace_Tech(X_DP_ReqId, "SEQUENCE_MANQUANTE", objResponse.Headers.Item(i))
                RichTextBox1.AppendText("SEQUENCE_MANQUANTE " & objResponse.Headers.Item(i).ToString & vbCrLf)
                Application.DoEvents()
                Dim j = 0
                Dim strg As String = objResponse.Headers.Item(i)
                While InStr(strg, "|") <> 0
                    ReDim Preserve DP_Missing_Sequence_Numbers(DP_Missing_Sequence_Numbers.Length)
                    DP_Missing_Sequence_Numbers(j) = Mid(strg, 1, InStr(strg, "|") - 1)
                    strg = Mid(strg, InStr(strg, "|") + 1)
                    j = j + 1
                End While
                DP_Missing_Sequence_Numbers(j) = strg
            End If
        Next

        Missing_Sequence_Number_Send()

    End Sub



    Public Sub Missing_Sequence_Number_Send()
        For i = 0 To DP_Missing_Sequence_Numbers.Length - 1
            If BDD.DP_ReqTableAdapter.GetDataBy_Sequence_Number(DP_Missing_Sequence_Numbers(i)).Rows.Count > 0 Then

                Dim reqrow = BDD.DP_ReqTableAdapter.GetDataBy_Sequence_Number(DP_Missing_Sequence_Numbers(i)).Item(0)

                Dim interactionId As String = ""
                Dim xmlreq As New XmlDocument
                Dim ReqId As String = reqrow.ReqId
                Dim Identifiant_patient As String = reqrow.Identifiant_patient
                Dim référence_interne As String = reqrow.référence_interne

                If My.Computer.FileSystem.FileExists(Config.LocalNetwork_ServerName & "\DP\XML\log\" & ReqId & ".xml") Then
                    xmlreq.Load(Config.LocalNetwork_ServerName & "\DP\XML\log\" & ReqId & ".xml")
                    If xmlreq.FirstChild.Item("interactionId").HasAttribute("extension") Then
                        interactionId = xmlreq.FirstChild.Item("interactionId").GetAttribute("extension")
                    End If
                End If


                Select Case interactionId
                    Case "ALIMENTATION"
                        Missing_Sequence_Number_Dispensation(ReqId, DP_Missing_Sequence_Numbers(i), xmlreq, Identifiant_patient, référence_interne)
                    Case Else
                End Select

            End If


        Next
    End Sub

    Public Sub Missing_Sequence_Number_Dispensation(ByVal X_DP_ReqId As String, ByVal missing_X_DP_Sequence_Number As String, ByVal xmlreq As XmlDocument, ByVal Identifiant_patient As String, ByVal référence_interne As String)
        'Dim X_DP_ReqId_new As String = System.Guid.NewGuid.ToString
        Try


            If DP_objRequest_has_been_used = True Then
                If Not DP_objRequest Is Nothing Then DP_objRequest.Headers.Clear()
            Else
                DP_objRequest_has_been_used = True
            End If

            DP_objRequest = System.Net.HttpWebRequest.CreateHttp(Config.DP_URI & Config.DP_EtaTyp & "/" & Config.DP_EtaIdent & "/alimentation")

            Dim xmldoc As New XmlDocument
            xmldoc.Load(Config.LocalNetwork_ServerName & "\DP\XML\log\" & X_DP_ReqId & ".signed")

            Dim postdata_signed As String = xmldoc.OuterXml

            Dim byteArray As Byte() = Encoding.UTF8.GetBytes(postdata_signed)

            DP_objRequest.ContentLength = byteArray.Length

            DP_objRequest.Timeout = "30000"

            DP_objRequest.Method = "POST"

            DP_objRequest.ClientCertificates.Add(DP_get_certif)

            DP_objRequest.UserAgent = Config.DP_EtaTyp & "-" & Config.DP_EtaIdent & "-" & Config.DP_LogValid & "-" & Config.DP_LogVers & "-" & Config.DP_LogVDP

            DP_objRequest.ContentType = "application/vnd.cnop.dp.alimentation+signature"

            'DP_objRequest.Headers.Add("X-DP-ReqId", X_DP_ReqId_new)
            DP_objRequest.Headers.Add("X-DP-ReqId", X_DP_ReqId)

            DP_objRequest.Headers.Add("X-DP-Sequence-Number", missing_X_DP_Sequence_Number)


            'signature
            Sign_XML(Config.LocalNetwork_ServerName & "\DP\XML\log\" & X_DP_ReqId & ".xml", X_DP_ReqId, Config.LocalNetwork_ServerName & "\DP\XML\log\" & X_DP_ReqId & ".signed")

            '''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''
            'envoi



            Dim dataStream As Stream = DP_objRequest.GetRequestStream

            dataStream.Write(byteArray, 0, byteArray.Length)

            dataStream.Close()

            'Write_Trace_Tech(X_DP_ReqId_new, "REQUETE_REEMISE", "X_DP_Sequence_Number:" & missing_X_DP_Sequence_Number & "    X_DP_ReqId(old):" & X_DP_ReqId)
            Write_Trace_Tech(X_DP_ReqId, "REQUETE_REEMISE", "")
            RichTextBox1.AppendText("REQUETE_REEMISE " & X_DP_ReqId & vbCrLf)
            Application.DoEvents()
            'bdd.DP_ReqTableAdapter.Update_ReqId(X_DP_ReqId_new, missing_X_DP_Sequence_Number)

            Dim objResponse As System.Net.HttpWebResponse
            Dim request_time_debut, request_time_fin As Date

            request_time_debut = Now
            objResponse = DP_objRequest.GetResponse()
            request_time_fin = Now
            HEARTBEAT_variables.calcul_moyenne(HEARTBEAT_variables.MetNbAl, HEARTBEAT_variables.MetAli, request_time_debut, request_time_fin)

            Dim StreamReader As System.IO.StreamReader
            StreamReader = New System.IO.StreamReader(objResponse.GetResponseStream())

            My.Computer.FileSystem.WriteAllText(Config.LocalNetwork_ServerName & "\DP\XML\log\Réponse\REP_DISPENSATION_" & Format(Now, "yyyyMMddHHmmss") & "_" & X_DP_ReqId & ".xml", StreamReader.ReadToEnd.ToString, False)

            Write_Trace_Fonc("Alimentation du DP effectuée", référence_interne, "", Identifiant_patient)
            Write_Trace_Tech(X_DP_ReqId, "REP_ALIMENTATION", "OK")
            BDD.DP_ReqTableAdapter.Update_byReqId(X_DP_Sequence_Number.ToString, "OK", 1, Now, Identifiant_patient, "ALIMENTATION", X_DP_ReqId)
            RichTextBox1.AppendText("Alimentation du DP effectuée " & Identifiant_patient & vbCrLf)
            Application.DoEvents()

        Catch ex As System.Net.WebException

            If Not ex.Response Is Nothing Then
                Dim StreamReader As System.IO.StreamReader
                StreamReader = New System.IO.StreamReader(ex.Response.GetResponseStream)

                My.Computer.FileSystem.WriteAllText(Config.LocalNetwork_ServerName & "\DP\XML\log\Réponse\temp", StreamReader.ReadToEnd.ToString, False)
                StreamReader.Close()

                Dim xml_retour As New XmlDocument
                xml_retour.Load(Config.LocalNetwork_ServerName & "\DP\XML\log\Réponse\temp")
                Dim XMLelementliste As XmlNodeList
                XMLelementliste = xml_retour.GetElementsByTagName("acknowledgementDetail")

                If XMLelementliste.Item(0).Item("code").GetAttribute("code") <> "ERREUR_TECHNIQUE" Then
                    BDD.DP_ReqTableAdapter.Update_byReqId(missing_X_DP_Sequence_Number.ToString, XMLelementliste.Item(0).Item("code").GetAttribute("code"), 1, Now, Identifiant_patient, "ALIMENTATION", X_DP_ReqId)
                    Write_Trace_Tech(X_DP_ReqId, "REP_ALIMENTATION", XMLelementliste.Item(0).Item("code").GetAttribute("code") & "|" & XMLelementliste.Item(0).Item("text").InnerText)
                    Write_Trace_Fonc("Échec de l’alimentation du DP", référence_interne, "Alimentation non effectuée suite à un problème technique", Identifiant_patient)
                    RichTextBox1.AppendText("Échec de l’alimentation du DP. Alimentation non effectuée suite à un problème technique. " & Identifiant_patient & vbCrLf)
                    Application.DoEvents()
                Else
                    Dim next_trans_time As Date = Now
                    Dim Generator As System.Random = New System.Random()
                    next_trans_time = next_trans_time.AddMinutes(45 + Generator.Next(0, 30))
                    BDD.DP_ReqTableAdapter.Update_byReqId(missing_X_DP_Sequence_Number.ToString, XMLelementliste.Item(0).Item("code").GetAttribute("code"), 1, next_trans_time, Identifiant_patient, "ALIMENTATION", X_DP_ReqId)
                    Write_Trace_Tech(X_DP_ReqId, "REP_ALIMENTATION", XMLelementliste.Item(0).Item("code").GetAttribute("code") & "|" & XMLelementliste.Item(0).Item("text").InnerText)
                    Write_Trace_Tech(X_DP_ReqId, "REQUETE_EN_ATTENTE", XMLelementliste.Item(0).Item("code").GetAttribute("code") & "|" & XMLelementliste.Item(0).Item("text").InnerText)
                    Write_Trace_Fonc("Échec de l’alimentation du DP", référence_interne, "Problème technique : l'alimentation est mise en file d’attente", Identifiant_patient)
                    RichTextBox1.AppendText("Échec de l’alimentation du DP. Problème technique : l'alimentation est mise en file d’attente. " & Identifiant_patient & vbCrLf)
                    Application.DoEvents()
                End If

            Else
                BDD.DP_ReqTableAdapter.Update_byReqId(missing_X_DP_Sequence_Number.ToString, "A_REEMETTRE", 1, Now, Identifiant_patient, "ALIMENTATION", X_DP_ReqId)
                Write_Trace_Tech(X_DP_ReqId, "REQUETE_EN_ATTENTE", ex.Message.ToString)
                Write_Trace_Fonc("Échec de l’alimentation du DP", référence_interne, "Problème technique : l'alimentation est mise en file d’attente", Identifiant_patient)
                RichTextBox1.AppendText("Échec de l’alimentation du DP. Problème technique : l'alimentation est mise en file d’attente. " & Identifiant_patient & vbCrLf & _
                                              "LA CONNEXION VA ETRE REENITIALISEE" & vbCrLf)
                Application.DoEvents()
                reset_connection()
            End If

        End Try
    End Sub
#End Region
    Public Sub reset_connection()
        Dim objRequest = System.Net.HttpWebRequest.CreateHttp(Config.DP_URI & Config.DP_EtaTyp & "/" & Config.DP_EtaIdent)
        objRequest.ClientCertificates.Add(DP_get_certif)
        objRequest.ServicePoint.ConnectionLimit = 1
        objRequest.Method = "POST"
        objRequest.KeepAlive = False
        Try
            Dim dataStream = objRequest.GetRequestStream
            objRequest.GetResponse()
        Catch ex As Exception
        End Try
        DP_Connection_reseted = True
        connect()


    End Sub
    Public Sub Write_Trace_Tech(ByVal Identifiant_requête As String, ByVal action As String, ByVal Détail As String)
        My.Computer.FileSystem.WriteAllText(Config.LocalNetwork_ServerName & "\DP\traces_tech\trace_tech_" & Format(Now, "yyyyMMdd") & ".txt", Format(Now, "dd/MM/yyyy HH:mm:ss") & "|" & "1" & "|" & Identifiant_requête _
                                       & "|" & action & "|" & Détail + Chr(10), True)
    End Sub
    Public Sub Write_Trace_Fonc(ByVal action As String, ByVal Référence As String, ByVal Détail As String, ByVal Identifiant_patient As String)
        My.Computer.FileSystem.WriteAllText(Config.LocalNetwork_ServerName & "\DP\traces\trace_fonc_" & Identifiant_patient, Format(Now, "dd/MM/yyyy HH:mm:ss") & "|" & action & "|" & Détail & _
                                        "|" & Référence & "|" & ID_user & Chr(10), True)
    End Sub

    Public Sub Write_Trace_Fonc_Queue(ByVal action As String, ByVal Référence As String, ByVal Détail As String, ByVal Identifiant_patient As String)
        My.Computer.FileSystem.WriteAllText(Config.LocalNetwork_ServerName & "\DP\traces\trace_fonc_" & Identifiant_patient, Format(Now, "dd/MM/yyyy HH:mm:ss") & "|" & action & "|" & Détail & _
                                    "|" & Référence & "|" & ID_user & Chr(10), True)
    End Sub




    Public Async Sub Local_Server()
        'If Config.Show_progressbar_Form = True Then
        '    Progress_Bar_Form_Texte = "DEMARRAGE SERVEUR LOCAL DP"
        '    Dim t = New Thread(New ThreadStart(AddressOf show_prgbar))
        '    t.Start()
        '     Await Task.Delay(2000)
        '    t.Abort()
        '    t.Join()
        'End If

debut:
        Me.Visible = True
        Await Task.Delay(50)
        Dim file As String
        file = Dir(Config.LocalNetwork_ServerName & "\DP\Clients\*.xml")
        If file <> "" Then
            Try
                Application.DoEvents()

                Await Task.Delay(50)

                Dim ReqXml As New XmlDocument

                ReqXml.Load(Config.LocalNetwork_ServerName & "\DP\Clients\" & file)
                Select Case ReqXml.FirstChild.Name

                    Case "RCMR_IN000031UV01" 'consultation
                        Affichage_relay(ReqXml)

                        My_move_file(Config.LocalNetwork_ServerName & "\DP\Clients\" & file, Config.LocalNetwork_ServerName & "\DP\XML\log\" & file, True)

                    Case "PRPA_IN201311UV02" 'création
                        Select Case ReqXml.FirstChild.Item("interactionId").GetAttribute("extension")
                            Case "CREATION"
                                Création_relay(ReqXml)
                            Case "REFUS_CREATION"
                                Refus_Création_relay(ReqXml)

                        End Select

                    Case "PRPA_IN201314UV02"
                        Suppression_relay(ReqXml)

                    Case "RCMR_IN000002UV02"
                        Dispensation_relay(ReqXml)


                    Case "iam"
                        IAM_Send_requeste_relay(ReqXml, Mid(file, 1, InStr(file, ".") - 1))

                End Select
            Catch ex As Exception
                Try
                    My.Computer.FileSystem.DeleteFile(Config.LocalNetwork_ServerName & "\DP\Clients\" & file)
                Catch ex2 As Exception
                End Try
            End Try
        End If




        GoTo debut
        Await Task.Delay(1)
    End Sub
    Public Sub Affichage_relay(ByVal ReqXml As XmlDocument)



        Dim ConTyp As String = ""
        Dim XMLelementliste = ReqXml.GetElementsByTagName("RCMR_IN000031UV01")
        Try
            For Each item As XmlNode In XMLelementliste.Item(0).ChildNodes
                If item.Name = "controlActProcess" Then
                    For Each item2 As XmlNode In item.ChildNodes
                        If item2.Name = "queryByParameter" Then
                            For Each item3 As XmlNode In item2.ChildNodes
                                If item3.Name = "serviceEvent.code" Then
                                    ConTyp = item3.FirstChild.Attributes("code").Value
                                End If
                            Next
                        End If
                    Next
                End If
            Next
        Catch ex As Exception
        End Try
        If ConTyp = "" Then
            ConTyp = XMLelementliste.Item(0).Item("interactionId").GetAttribute("extension")
        End If



        'If ConTyp <> "EDITION" Then
        '    COMPTOIR_ DP_affichage_statut("Accès au DP en cours")
        'End If

        Dim X_DP_ReqId As String = XMLelementliste.Item(0).Item("id").GetAttribute("extension")


        Try

            If DP_objRequest_has_been_used = True Then
                If Not DP_objRequest Is Nothing Then DP_objRequest.Headers.Clear()
            Else
                DP_objRequest_has_been_used = True
            End If

            RichTextBox1.AppendText(vbCrLf & "*************************" & vbCrLf & ConTyp & vbCrLf & "*************************")
            Select Case ConTyp
                Case "EDITION"
                    DP_objRequest = System.Net.HttpWebRequest.CreateHttp(Config.DP_URI & Config.DP_EtaTyp & "/" & Config.DP_EtaIdent & "/edition")
                Case "CONSULTATION_TOUT", "CONSULTATION", "REFUS_CONSULTATION"
                    DP_objRequest = System.Net.HttpWebRequest.CreateHttp(Config.DP_URI & Config.DP_EtaTyp & "/" & Config.DP_EtaIdent & "/consultation")
            End Select
            RichTextBox1.AppendText(vbCrLf & ConTyp & " " & X_DP_ReqId & vbCrLf)
            Application.DoEvents()
            Dim postdata As String = ReqXml.OuterXml
            Dim byteArray As Byte() = Encoding.UTF8.GetBytes(postdata)
            DP_objRequest.ContentLength = byteArray.Length
            DP_objRequest.Timeout = "10000"

            DP_objRequest.Method = "POST"
            DP_objRequest.ClientCertificates.Add(DP_get_certif)

            DP_objRequest.UserAgent = Config.DP_EtaTyp & "-" & Config.DP_EtaIdent & "-" & Config.DP_LogValid & "-" & Config.DP_LogVers & "-" & Config.DP_LogVDP
            DP_objRequest.ContentType = "application/vnd.cnop.dp.consultation"

            DP_objRequest.Headers.Add("X-DP-ReqId", X_DP_ReqId)

            BDD.DP_ReqTableAdapter.Insert("", X_DP_ReqId, "Local_Server", Now, 1, "", "")



            Dim dataStream As Stream = DP_objRequest.GetRequestStream

            dataStream.Write(byteArray, 0, byteArray.Length)

            dataStream.Close()

            Dim objResponse As System.Net.HttpWebResponse
            Dim request_time_debut, request_time_fin As Date
            request_time_debut = Now
            objResponse = DP_objRequest.GetResponse()
            request_time_fin = Now
            Select Case ConTyp
                Case "EDITION"
                    HEARTBEAT_variables.calcul_moyenne(HEARTBEAT_variables.MetNbEd, HEARTBEAT_variables.MetEdi, request_time_debut, request_time_fin)
                Case "CONSULTATION_TOUT", "CONSULTATION"
                    HEARTBEAT_variables.calcul_moyenne(HEARTBEAT_variables.MetNbCs, HEARTBEAT_variables.MetCon, request_time_debut, request_time_fin)
            End Select


            Dim StreamReader As System.IO.StreamReader

            StreamReader = New System.IO.StreamReader(objResponse.GetResponseStream())
            Dim histo_dp As New XmlDocument


            histo_dp.LoadXml(StreamReader.ReadToEnd.ToString)
            StreamReader.Close()
            histo_dp.Save(Config.LocalNetwork_ServerName & "\DP\Clients\" & X_DP_ReqId & "_ok")

            RichTextBox1.AppendText("_ok" & vbCrLf)
            Application.DoEvents()

        Catch wex As System.Net.WebException

            If Not wex.Response Is Nothing Then
                Dim StreamReader As System.IO.StreamReader
                StreamReader = New System.IO.StreamReader(wex.Response.GetResponseStream)
                My.Computer.FileSystem.WriteAllText(Config.LocalNetwork_ServerName & "\DP\Clients\" & X_DP_ReqId & "_error", StreamReader.ReadToEnd.ToString, False)
                StreamReader.Close()
                RichTextBox1.AppendText("_error" & vbCrLf)
                Application.DoEvents()
            Else
                My.Computer.FileSystem.WriteAllText(Config.LocalNetwork_ServerName & "\DP\Clients\" & X_DP_ReqId & "_ko", wex.Message.ToString, False)
                RichTextBox1.AppendText("_ko" & vbCrLf)
                Application.DoEvents()
            End If

        Catch ex As Exception
            My.Computer.FileSystem.WriteAllText(Config.LocalNetwork_ServerName & "\DP\Clients\" & X_DP_ReqId & "_ko", ex.Message.ToString, False)
            RichTextBox1.AppendText("_ko" & vbCrLf)
            Application.DoEvents()
        End Try

    End Sub

    Public Sub Création_relay(ByVal ReqXml As XmlDocument)

        Dim XMLelementliste = ReqXml.GetElementsByTagName("PRPA_IN201311UV02")

        Dim X_DP_ReqId As String = XMLelementliste.Item(0).Item("id").GetAttribute("extension")
        RichTextBox1.AppendText(vbCrLf & "Création " & X_DP_ReqId & vbCrLf)
        Try
            If DP_objRequest_has_been_used = True Then
                If Not DP_objRequest Is Nothing Then DP_objRequest.Headers.Clear()
            Else
                DP_objRequest_has_been_used = True
            End If

            'signature
            Sign_XML(Config.LocalNetwork_ServerName & "\DP\Clients\" & X_DP_ReqId & ".xml", X_DP_ReqId, Config.LocalNetwork_ServerName & "\DP\Clients\" & X_DP_ReqId & ".signed")
            My_move_file(Config.LocalNetwork_ServerName & "\DP\Clients\" & X_DP_ReqId & ".xml", Config.LocalNetwork_ServerName & "\DP\xml\log\" & X_DP_ReqId & ".xml", True)
            'envoi
            DP_objRequest = System.Net.HttpWebRequest.CreateHttp(Config.DP_URI & Config.DP_EtaTyp & "/" & Config.DP_EtaIdent & "/creation")

            Dim xmldoc As New XmlDocument
            xmldoc.Load(Config.LocalNetwork_ServerName & "\DP\Clients\" & X_DP_ReqId & ".signed")
            My_move_file(Config.LocalNetwork_ServerName & "\DP\Clients\" & X_DP_ReqId & ".signed", Config.LocalNetwork_ServerName & "\DP\xml\log\" & X_DP_ReqId & ".signed", True)
            Dim postdata_signed As String = xmldoc.OuterXml
            Dim byteArray As Byte() = Encoding.UTF8.GetBytes(postdata_signed)
            DP_objRequest.ContentLength = byteArray.Length



            DP_objRequest.Timeout = "10000"

            DP_objRequest.Method = "POST"

            DP_objRequest.ClientCertificates.Add(DP_get_certif)

            DP_objRequest.UserAgent = Config.DP_EtaTyp & "-" & Config.DP_EtaIdent & "-" & Config.DP_LogValid & "-" & Config.DP_LogVers & "-" & Config.DP_LogVDP

            DP_objRequest.ContentType = "application/vnd.cnop.dp.creation+signature"

            DP_objRequest.Headers.Add("X-DP-ReqId", X_DP_ReqId)

            DP_objRequest.Headers.Add("X-DP-Sequence-Number", X_DP_Sequence_Number.ToString)

            BDD.DP_ReqTableAdapter.Insert(X_DP_Sequence_Number.ToString, X_DP_ReqId, "Local_Server", Now, 1, "", "")



            Dim dataStream As Stream = DP_objRequest.GetRequestStream
            dataStream.Write(byteArray, 0, byteArray.Length)
            dataStream.Close()
            Dim objResponse As System.Net.HttpWebResponse
            Dim request_time_debut, request_time_fin As Date
            request_time_debut = Now
            objResponse = DP_objRequest.GetResponse()
            request_time_fin = Now
            HEARTBEAT_variables.calcul_moyenne(HEARTBEAT_variables.MetNbCr, HEARTBEAT_variables.MetCre, request_time_debut, request_time_fin)
            Dim StreamReader As System.IO.StreamReader
            StreamReader = New System.IO.StreamReader(objResponse.GetResponseStream())
            My.Computer.FileSystem.WriteAllText(Config.LocalNetwork_ServerName & "\DP\Clients\" & X_DP_ReqId & "_ok", StreamReader.ReadToEnd.ToString, False)
            RichTextBox1.AppendText("_ok" & vbCrLf)
            Next_Sequence_Number(objResponse)
            Missing_Sequence_Number(objResponse, X_DP_ReqId)
        Catch wex As System.Net.WebException

            If Not wex.Response Is Nothing Then
                Dim StreamReader As System.IO.StreamReader
                StreamReader = New System.IO.StreamReader(wex.Response.GetResponseStream)
                My.Computer.FileSystem.WriteAllText(Config.LocalNetwork_ServerName & "\DP\Clients\" & X_DP_ReqId & "_error", StreamReader.ReadToEnd.ToString, False)
                StreamReader.Close()
                RichTextBox1.AppendText("_error" & vbCrLf)
            Else
                My.Computer.FileSystem.WriteAllText(Config.LocalNetwork_ServerName & "\DP\Clients\" & X_DP_ReqId & "_ko", wex.Message.ToString, False)
                RichTextBox1.AppendText("_ko-->reset_connection()" & vbCrLf)
                reset_connection()
            End If

        Catch ex As Exception
            My.Computer.FileSystem.WriteAllText(Config.LocalNetwork_ServerName & "\DP\Clients\" & X_DP_ReqId & "_ko", ex.Message.ToString, False)
            RichTextBox1.AppendText("_ko" & vbCrLf)
        End Try

    End Sub

    Public Sub Refus_Création_relay(ByVal ReqXML As XmlDocument)

        Dim XMLelementliste = ReqXML.GetElementsByTagName("PRPA_IN201311UV02")

        Dim X_DP_ReqId As String = XMLelementliste.Item(0).Item("id").GetAttribute("extension")
        RichTextBox1.AppendText(vbCrLf & "Refus Création " & X_DP_ReqId & vbCrLf)
        Try
            If DP_objRequest_has_been_used = True Then
                If Not DP_objRequest Is Nothing Then DP_objRequest.Headers.Clear()
            Else
                DP_objRequest_has_been_used = True
            End If
            'signature
            Sign_XML(Config.LocalNetwork_ServerName & "\DP\Clients\" & X_DP_ReqId & ".xml", X_DP_ReqId, Config.LocalNetwork_ServerName & "\DP\Clients\" & X_DP_ReqId & ".signed")
            My_move_file(Config.LocalNetwork_ServerName & "\DP\Clients\" & X_DP_ReqId & ".xml", Config.LocalNetwork_ServerName & "\DP\xml\log\" & X_DP_ReqId & ".xml", True)
            DP_objRequest = System.Net.HttpWebRequest.CreateHttp(Config.DP_URI & Config.DP_EtaTyp & "/" & Config.DP_EtaIdent & "/refus_creation")
            Dim xmldoc As New XmlDocument
            xmldoc.Load(Config.LocalNetwork_ServerName & "\DP\Clients\" & X_DP_ReqId & ".signed")
            My_move_file(Config.LocalNetwork_ServerName & "\DP\Clients\" & X_DP_ReqId & ".signed", Config.LocalNetwork_ServerName & "\DP\xml\log\" & X_DP_ReqId & ".signed", True)
            Dim postdata_signed As String = xmldoc.OuterXml
            Dim byteArray As Byte() = Encoding.UTF8.GetBytes(postdata_signed)
            DP_objRequest.ContentLength = byteArray.Length


            DP_objRequest.Timeout = "10000"

            DP_objRequest.Method = "POST"

            DP_objRequest.ClientCertificates.Add(DP_get_certif)

            DP_objRequest.UserAgent = Config.DP_EtaTyp & "-" & Config.DP_EtaIdent & "-" & Config.DP_LogValid & "-" & Config.DP_LogVers & "-" & Config.DP_LogVDP

            DP_objRequest.ContentType = "application/vnd.cnop.dp.refuscreation+signature"


            DP_objRequest.Headers.Add("X-DP-ReqId", X_DP_ReqId)

            DP_objRequest.Headers.Add("X-DP-Sequence-Number", X_DP_Sequence_Number.ToString)

            BDD.DP_ReqTableAdapter.Insert(X_DP_Sequence_Number.ToString, X_DP_ReqId, "Local_Server", Now, 1, "", "")


            'envoi

            Dim dataStream As Stream = DP_objRequest.GetRequestStream
            dataStream.Write(byteArray, 0, byteArray.Length)
            dataStream.Close()
            Dim objResponse As System.Net.HttpWebResponse
            Dim request_time_debut, request_time_fin As Date
            request_time_debut = Now
            objResponse = DP_objRequest.GetResponse()
            request_time_fin = Now
            HEARTBEAT_variables.calcul_moyenne(HEARTBEAT_variables.MetNbCr, HEARTBEAT_variables.MetCre, request_time_debut, request_time_fin)
            Dim StreamReader As System.IO.StreamReader
            StreamReader = New System.IO.StreamReader(objResponse.GetResponseStream())
            My.Computer.FileSystem.WriteAllText(Config.LocalNetwork_ServerName & "\DP\Clients\" & X_DP_ReqId & "_ok", StreamReader.ReadToEnd.ToString, False)
            RichTextBox1.AppendText("_ok" & vbCrLf)
            Next_Sequence_Number(objResponse)
            Missing_Sequence_Number(objResponse, X_DP_ReqId)
        Catch wex As System.Net.WebException

            If Not wex.Response Is Nothing Then
                Dim StreamReader As System.IO.StreamReader
                StreamReader = New System.IO.StreamReader(wex.Response.GetResponseStream)
                My.Computer.FileSystem.WriteAllText(Config.LocalNetwork_ServerName & "\DP\Clients\" & X_DP_ReqId & "_error", StreamReader.ReadToEnd.ToString, False)
                RichTextBox1.AppendText("_error" & vbCrLf)
                StreamReader.Close()
            Else

                My.Computer.FileSystem.WriteAllText(Config.LocalNetwork_ServerName & "\DP\Clients\" & X_DP_ReqId & "_ko", wex.Message.ToString, False)
                RichTextBox1.AppendText("_ko -->reset_connection" & vbCrLf)
                reset_connection()
            End If

        Catch ex As Exception
            My.Computer.FileSystem.WriteAllText(Config.LocalNetwork_ServerName & "\DP\Clients\" & X_DP_ReqId & "_ko", ex.Message.ToString, False)
            RichTextBox1.AppendText("_ko" & X_DP_ReqId & vbCrLf)
        End Try


    End Sub

    Public Sub Suppression_relay(ByVal ReqXml As XmlDocument)
        Dim XMLelementliste = ReqXml.GetElementsByTagName("PRPA_IN201314UV02")

        Dim X_DP_ReqId As String = XMLelementliste.Item(0).Item("id").GetAttribute("extension")
        RichTextBox1.AppendText(vbCrLf & "Suppression " & X_DP_ReqId & vbCrLf)
        Try
            If DP_objRequest_has_been_used = True Then
                If Not DP_objRequest Is Nothing Then DP_objRequest.Headers.Clear()
            Else
                DP_objRequest_has_been_used = True
            End If
            'signature
            Sign_XML(Config.LocalNetwork_ServerName & "\DP\Clients\" & X_DP_ReqId & ".xml", X_DP_ReqId, Config.LocalNetwork_ServerName & "\DP\Clients\" & X_DP_ReqId & ".signed")
            My_move_file(Config.LocalNetwork_ServerName & "\DP\Clients\" & X_DP_ReqId & ".xml", Config.LocalNetwork_ServerName & "\DP\xml\log\" & X_DP_ReqId & ".xml", True)
            DP_objRequest = System.Net.HttpWebRequest.CreateHttp(Config.DP_URI & Config.DP_EtaTyp & "/" & Config.DP_EtaIdent & "/suppression")
            Dim xmldoc As New XmlDocument
            xmldoc.Load(Config.LocalNetwork_ServerName & "\DP\Clients\" & X_DP_ReqId & ".signed")
            My_move_file(Config.LocalNetwork_ServerName & "\DP\Clients\" & X_DP_ReqId & ".signed", Config.LocalNetwork_ServerName & "\DP\xml\log\" & X_DP_ReqId & ".signed", True)
            Dim postdata_signed As String = xmldoc.OuterXml
            Dim byteArray As Byte() = Encoding.UTF8.GetBytes(postdata_signed)
            DP_objRequest.ContentLength = byteArray.Length


            DP_objRequest.Timeout = "30000"

            DP_objRequest.Method = "POST"

            DP_objRequest.ClientCertificates.Add(DP_get_certif)

            DP_objRequest.UserAgent = Config.DP_EtaTyp & "-" & Config.DP_EtaIdent & "-" & Config.DP_LogValid & "-" & Config.DP_LogVers & "-" & Config.DP_LogVDP

            DP_objRequest.ContentType = "application/vnd.cnop.dp.suppression+signature"


            DP_objRequest.Headers.Add("X-DP-ReqId", X_DP_Sequence_Number.ToString)

            DP_objRequest.Headers.Add("X-DP-Sequence-Number", X_DP_Sequence_Number.ToString)

            BDD.DP_ReqTableAdapter.Insert(X_DP_Sequence_Number.ToString, X_DP_ReqId, "Local_Server", Now, 1, "", "")


            'envoi

            Dim dataStream As Stream = DP_objRequest.GetRequestStream
            dataStream.Write(byteArray, 0, byteArray.Length)
            dataStream.Close()
            Dim objResponse As System.Net.HttpWebResponse
            Dim request_time_debut, request_time_fin As Date
            request_time_debut = Now
            objResponse = DP_objRequest.GetResponse()
            request_time_fin = Now
            HEARTBEAT_variables.calcul_moyenne(HEARTBEAT_variables.MetNbSu, HEARTBEAT_variables.MetSup, request_time_debut, request_time_fin)
            Dim StreamReader As System.IO.StreamReader
            StreamReader = New System.IO.StreamReader(objResponse.GetResponseStream())
            My.Computer.FileSystem.WriteAllText(Config.LocalNetwork_ServerName & "\DP\Clients\" & X_DP_ReqId & "_ok", StreamReader.ReadToEnd.ToString, False)
            RichTextBox1.AppendText("_ok" & vbCrLf)
            Next_Sequence_Number(objResponse)
            Missing_Sequence_Number(objResponse, X_DP_ReqId)
        Catch wex As System.Net.WebException

            If Not wex.Response Is Nothing Then
                Dim StreamReader As System.IO.StreamReader
                StreamReader = New System.IO.StreamReader(wex.Response.GetResponseStream)
                My.Computer.FileSystem.WriteAllText(Config.LocalNetwork_ServerName & "\DP\Clients\" & X_DP_ReqId & "_error", StreamReader.ReadToEnd.ToString, False)
                RichTextBox1.AppendText("_error" & vbCrLf)
                StreamReader.Close()
            Else
                My.Computer.FileSystem.WriteAllText(Config.LocalNetwork_ServerName & "\DP\Clients\" & X_DP_ReqId & "_ko", wex.Message.ToString, False)
                RichTextBox1.AppendText("_ko -->reset_connection" & vbCrLf)
                reset_connection()
            End If
        Catch ex As Exception

            My.Computer.FileSystem.WriteAllText(Config.LocalNetwork_ServerName & "\DP\Clients\" & X_DP_ReqId & "_ko", ex.Message.ToString, False)
            RichTextBox1.AppendText("_ko" & X_DP_ReqId & vbCrLf)
        End Try
    End Sub

    Public Sub Dispensation_relay(ByVal ReqXml As XmlDocument)
        Dim XMLelementliste = ReqXml.GetElementsByTagName("RCMR_IN000002UV02")

        Dim X_DP_ReqId As String = XMLelementliste.Item(0).Item("id").GetAttribute("extension")
        RichTextBox1.AppendText(vbCrLf & "Dispensation " & X_DP_ReqId & vbCrLf)

        Try
            If DP_objRequest_has_been_used = True Then
                If Not DP_objRequest Is Nothing Then DP_objRequest.Headers.Clear()
            Else
                DP_objRequest_has_been_used = True
            End If


            'signature
            Sign_XML(Config.LocalNetwork_ServerName & "\DP\Clients\" & X_DP_ReqId & ".xml", X_DP_ReqId, Config.LocalNetwork_ServerName & "\DP\Clients\" & X_DP_ReqId & ".signed")
            My_move_file(Config.LocalNetwork_ServerName & "\DP\Clients\" & X_DP_ReqId & ".xml", Config.LocalNetwork_ServerName & "\DP\xml\log\" & X_DP_ReqId & ".xml", True)

            Dim xmldoc As New XmlDocument
            xmldoc.Load(Config.LocalNetwork_ServerName & "\DP\Clients\" & X_DP_ReqId & ".signed")
            My_move_file(Config.LocalNetwork_ServerName & "\DP\Clients\" & X_DP_ReqId & ".signed", Config.LocalNetwork_ServerName & "\DP\xml\log\" & X_DP_ReqId & ".signed", True)
            Dim postdata_signed As String = xmldoc.OuterXml
            Dim byteArray As Byte() = Encoding.UTF8.GetBytes(postdata_signed)
            DP_objRequest = System.Net.HttpWebRequest.CreateHttp(Config.DP_URI & Config.DP_EtaTyp & "/" & Config.DP_EtaIdent & "/alimentation")
            DP_objRequest.ContentLength = byteArray.Length


            DP_objRequest.Timeout = "30000"

            DP_objRequest.Method = "POST"

            DP_objRequest.ClientCertificates.Add(DP_get_certif)

            DP_objRequest.UserAgent = Config.DP_EtaTyp & "-" & Config.DP_EtaIdent & "-" & Config.DP_LogValid & "-" & Config.DP_LogVers & "-" & Config.DP_LogVDP

            DP_objRequest.ContentType = "application/vnd.cnop.dp.alimentation+signature"


            DP_objRequest.Headers.Add("X-DP-ReqId", X_DP_ReqId)

            DP_objRequest.Headers.Add("X-DP-Sequence-Number", X_DP_Sequence_Number.ToString)

            BDD.DP_ReqTableAdapter.Insert(X_DP_Sequence_Number.ToString, X_DP_ReqId, "Local_Server", Now, 1, "", "")


            'envoi

            Dim dataStream As Stream = DP_objRequest.GetRequestStream
            dataStream.Write(byteArray, 0, byteArray.Length)
            dataStream.Close()
            Dim objResponse As System.Net.HttpWebResponse
            Dim request_time_debut, request_time_fin As Date
            request_time_debut = Now
            objResponse = DP_objRequest.GetResponse()
            request_time_fin = Now
            HEARTBEAT_variables.calcul_moyenne(HEARTBEAT_variables.MetNbAl, HEARTBEAT_variables.MetAli, request_time_debut, request_time_fin)
            Dim StreamReader As System.IO.StreamReader
            StreamReader = New System.IO.StreamReader(objResponse.GetResponseStream())
            My.Computer.FileSystem.WriteAllText(Config.LocalNetwork_ServerName & "\DP\Clients\" & X_DP_ReqId & "_ok", StreamReader.ReadToEnd.ToString, False)
            RichTextBox1.AppendText("_ok" & vbCrLf)
            StreamReader.Close()
            Next_Sequence_Number(objResponse)
            Missing_Sequence_Number(objResponse, X_DP_ReqId)
        Catch wex As System.Net.WebException

            If Not wex.Response Is Nothing Then
                Dim StreamReader As System.IO.StreamReader
                StreamReader = New System.IO.StreamReader(wex.Response.GetResponseStream)
                My.Computer.FileSystem.WriteAllText(Config.LocalNetwork_ServerName & "\DP\Clients\" & X_DP_ReqId & "_error", StreamReader.ReadToEnd.ToString, False)
                RichTextBox1.AppendText("_error" & vbCrLf)
                StreamReader.Close()
            Else
                My.Computer.FileSystem.WriteAllText(Config.LocalNetwork_ServerName & "\DP\Clients\" & X_DP_ReqId & "_ko", wex.Message.ToString, False)
                RichTextBox1.AppendText("_ko -->reset_connection" & vbCrLf)
                reset_connection()
            End If

        Catch ex As Exception
            My.Computer.FileSystem.WriteAllText(Config.LocalNetwork_ServerName & "\DP\Clients\" & X_DP_ReqId & "_ko", ex.Message.ToString, False)
            RichTextBox1.AppendText("_ko" & X_DP_ReqId & vbCrLf)
        End Try

        traitement_retour_alimentation(X_DP_ReqId)
    End Sub

    Private Sub traitement_retour_alimentation(ByVal X_DP_ReqId As String)
        RichTextBox1.AppendText("traitement_retour_alimentation " & X_DP_ReqId.ToString)
        Dim tentative = 0
        Dim response_file As String = Dir(Config.LocalNetwork_ServerName & "\DPclients\" & X_DP_ReqId & "_*")
        While response_file = "" And tentative < 200
            System.Threading.Thread.Sleep(100)
            response_file = Dir(Config.LocalNetwork_ServerName & "\DPclients\" & X_DP_ReqId & "_*")
            tentative = tentative + 1
        End While
        If tentative = 200 Then
            RichTextBox1.AppendText("traitement_retour_alimentation: pas de retour")
            Exit Sub
        End If
        response_file = Config.LocalNetwork_ServerName & "\DPclients\" & response_file

        '________________________________________________________________________________________________________________________
        '________________________________________________________________________________________________________________________
        '________________________________________________________________________________________________________________________
        Dim statut_retour As String
        Select Case Mid(response_file, InStrRev(response_file, "_"))
            Case "_ok"
                Dim xml_retour As New XmlDocument
                xml_retour.Load(response_file)
                Dim XMLelementliste As XmlNodeList
                XMLelementliste = xml_retour.GetElementsByTagName("acknowledgementDetail")

                If XMLelementliste.Count > 0 Then


                    statut_retour = XMLelementliste.Item(0).Item("code").GetAttribute("code")

                    If XMLelementliste.Item(0).Item("code").GetAttribute("code") <> "ERREUR_TECHNIQUE" Then
                        'Me.DP_ReqTableAdapter.Insert(X_DP_Sequence_Number.ToString, X_DP_ReqId, XMLelementliste.Item(0).Item("code").GetAttribute("code"), 1, Now, Identifiant_patient_function, référence_interne)
                        Write_Trace_Tech(X_DP_ReqId, "REP_ALIMENTATION", XMLelementliste.Item(0).Item("code").GetAttribute("code") & "|" & XMLelementliste.Item(0).Item("text").InnerText)
                        Write_Trace_Fonc("Échec de l’alimentation du DP", X_DP_ReqId, "Alimentation non effectuée suite à un problème technique", "")
                        RichTextBox1.AppendText("Échec de l’alimentation du DP: Alimentation non effectuée suite à un problème technique" & vbCrLf)

                    Else
                        Dim next_trans_time As Date = Now
                        Dim Generator As System.Random = New System.Random()
                        next_trans_time = next_trans_time.AddMinutes(45 + Generator.Next(0, 30))
                        'Me.DP_ReqTableAdapter.Insert(X_DP_Sequence_Number.ToString, X_DP_ReqId, XMLelementliste.Item(0).Item("code").GetAttribute("code"), 1, next_trans_time, Identifiant_patient_function, référence_interne)
                        Write_Trace_Tech(X_DP_ReqId, "REP_ALIMENTATION", XMLelementliste.Item(0).Item("code").GetAttribute("code") & "|" & XMLelementliste.Item(0).Item("text").InnerText)
                        Write_Trace_Tech(X_DP_ReqId, "REQUETE_EN_ATTENTE", XMLelementliste.Item(0).Item("code").GetAttribute("code") & "|" & XMLelementliste.Item(0).Item("text").InnerText)
                        Write_Trace_Fonc("Échec de l’alimentation du DP", X_DP_ReqId, "Problème technique : l'alimentation est mise en file d’attente", "")
                        RichTextBox1.AppendText("Échec de l’alimentation du DP. Problème technique : l'alimentation est mise en file d’attente" & vbCrLf)

                    End If
                Else
                    statut_retour = "OK"
                    RichTextBox1.AppendText("Alimentation du DP effectuée" & vbCrLf)
                    Write_Trace_Fonc("Alimentation du DP effectuée", X_DP_ReqId, "", "")
                    Write_Trace_Tech(X_DP_ReqId, "REP_ALIMENTATION", "OK")

                End If
                'Me.DP_ReqTableAdapter.Insert(X_DP_Sequence_Number.ToString, X_DP_ReqId, "OK", 1, Now, Identifiant_patient_function, référence_interne)
            Case "_error"
                Dim xml_retour As New XmlDocument
                xml_retour.Load(response_file)
                Dim XMLelementliste As XmlNodeList
                XMLelementliste = xml_retour.GetElementsByTagName("acknowledgementDetail")
                statut_retour = XMLelementliste.Item(0).Item("code").GetAttribute("code")

                If XMLelementliste.Item(0).Item("code").GetAttribute("code") <> "ERREUR_TECHNIQUE" Then
                    'Me.DP_ReqTableAdapter.Insert(X_DP_Sequence_Number.ToString, X_DP_ReqId, XMLelementliste.Item(0).Item("code").GetAttribute("code"), 1, Now, Identifiant_patient_function, référence_interne)
                    Write_Trace_Tech(X_DP_ReqId, "REP_ALIMENTATION", XMLelementliste.Item(0).Item("code").GetAttribute("code") & "|" & XMLelementliste.Item(0).Item("text").InnerText)
                    Write_Trace_Fonc("Échec de l’alimentation du DP", X_DP_ReqId, "Alimentation non effectuée suite à un problème technique", "")
                    RichTextBox1.AppendText("Échec de l’alimentation du DP: Alimentation non effectuée suite à un problème technique" & vbCrLf)

                Else
                    Dim next_trans_time As Date = Now
                    Dim Generator As System.Random = New System.Random()
                    next_trans_time = next_trans_time.AddMinutes(45 + Generator.Next(0, 30))
                    'Me.DP_ReqTableAdapter.Insert(X_DP_Sequence_Number.ToString, X_DP_ReqId, XMLelementliste.Item(0).Item("code").GetAttribute("code"), 1, next_trans_time, Identifiant_patient_function, référence_interne)
                    Write_Trace_Tech(X_DP_ReqId, "REP_ALIMENTATION", XMLelementliste.Item(0).Item("code").GetAttribute("code") & "|" & XMLelementliste.Item(0).Item("text").InnerText)
                    Write_Trace_Tech(X_DP_ReqId, "REQUETE_EN_ATTENTE", XMLelementliste.Item(0).Item("code").GetAttribute("code") & "|" & XMLelementliste.Item(0).Item("text").InnerText)
                    Write_Trace_Fonc("Échec de l’alimentation du DP", X_DP_ReqId, "Problème technique : l'alimentation est mise en file d’attente", "")
                    RichTextBox1.AppendText("Échec de l’alimentation du DP" + Chr(10) + "Problème technique : l'alimentation est mise en file d’attente" & vbCrLf)
                End If
            Case "_ko"
                statut_retour = My.Computer.FileSystem.ReadAllText(response_file)
                'Me.DP_ReqTableAdapter.Insert(X_DP_Sequence_Number.ToString, X_DP_ReqId, "A_REEMETTRE", 1, Now, Identifiant_patient_function, référence_interne)
                Write_Trace_Tech(X_DP_ReqId, "REQUETE_EN_ATTENTE", My.Computer.FileSystem.ReadAllText(response_file))
                Write_Trace_Fonc("Échec de l’alimentation du DP", X_DP_ReqId, "Problème technique : l'alimentation est mise en file d’attente", "")
                RichTextBox1.AppendText("Dispensation placée en file d'attente pour alimentation du DP ultérieure." & vbCrLf)

                Dim row_ = BDD.DP_ReqTableAdapter.GetDataBy_ReqId(X_DP_ReqId).Item(0)
                BDD.DP_ReqTableAdapter.Update_byReqId(row_.Sequence_Number, statut_retour, row_.nbr_trans, row_.next_trans_time, "", "", X_DP_ReqId)

        End Select
    End Sub

    Public Sub IAM_Send_requeste_relay(ByVal ReqXml As XmlDocument, ByVal X_DP_ReqId As String)
        RichTextBox1.AppendText(vbCrLf & "IAM " & X_DP_ReqId & vbCrLf)
        Try
            If DP_objRequest_has_been_used = True Then
                If Not DP_objRequest Is Nothing Then DP_objRequest.Headers.Clear()
            Else
                DP_objRequest_has_been_used = True
            End If
            DP_objRequest = System.Net.HttpWebRequest.CreateHttp(Config.DP_URI & Config.DP_EtaTyp & "/" & Config.DP_EtaIdent & "/iam")

            Dim postdata As String = ReqXml.OuterXml

            My_move_file(Config.LocalNetwork_ServerName & "\DP\Clients\" & X_DP_ReqId & ".xml", Config.LocalNetwork_ServerName & "\DP\XML\log\" & X_DP_ReqId & ".xml", True)
            Dim byteArray As Byte() = Encoding.UTF8.GetBytes(postdata)


            DP_objRequest.ContentLength = byteArray.Length
            DP_objRequest.Timeout = "10000"

            DP_objRequest.Method = "POST"
            DP_objRequest.ClientCertificates.Add(DP_get_certif)

            DP_objRequest.UserAgent = Config.DP_EtaTyp & "-" & Config.DP_EtaIdent & "-" & Config.DP_LogValid & "-" & Config.DP_LogVers & "-" & Config.DP_LogVDP
            DP_objRequest.ContentType = "application/vnd.cnop.dp.iam"

            DP_objRequest.Headers.Add("X-DP-ReqId", X_DP_ReqId)



            ' Get the request stream.
            Dim dataStream As Stream = DP_objRequest.GetRequestStream()
            ' Write the data to the request stream.
            dataStream.Write(byteArray, 0, byteArray.Length)
            ' Close the Stream object.
            dataStream.Close()

            Write_Trace_Tech(X_DP_ReqId, "ALIMENTATION_IAM", "")


            Dim DP_IAM_objResponse As System.Net.HttpWebResponse = DP_objRequest.GetResponse()


            Dim StreamReader As System.IO.StreamReader
            StreamReader = New System.IO.StreamReader(DP_IAM_objResponse.GetResponseStream())
            Dim réponse As String = StreamReader.ReadToEnd.ToString
            If réponse = "ERREUR_TECHNIQUE" Then
                BDD.DP_ReqTableAdapter.Insert("", X_DP_ReqId, "A_REEMETTRE", Now.AddMinutes(60), 1, "IAM", "IAM")
                Write_Trace_Tech(X_DP_ReqId, "REP_ALIMENTATION_IAM", "ERREUR_TECHNIQUE")
                RichTextBox1.AppendText("A_REEMETTRE" & vbCrLf)
            ElseIf réponse = "" Then
                BDD.DP_ReqTableAdapter.Insert("", X_DP_ReqId, "OK", Now, 1, "IAM", "IAM")
                Write_Trace_Tech(X_DP_ReqId, "REP_ALIMENTATION_IAM", "OK")
                RichTextBox1.AppendText("OK" & vbCrLf)
            Else
                BDD.DP_ReqTableAdapter.Insert("", X_DP_ReqId, réponse, Now, 1, "IAM", "IAM")
                Write_Trace_Tech(X_DP_ReqId, "REP_ALIMENTATION_IAM", réponse)
                RichTextBox1.AppendText(réponse & vbCrLf)
            End If


        Catch wex As System.Net.WebException
            RichTextBox1.AppendText(wex.Message & vbCrLf)
            BDD.DP_ReqTableAdapter.Insert("", X_DP_ReqId, "A_REEMETTRE", Now.AddMinutes(60), 1, "IAM", "IAM")
            If Not wex.Response Is Nothing Then
                Dim StreamReader As System.IO.StreamReader
                StreamReader = New System.IO.StreamReader(wex.Response.GetResponseStream)

                Write_Trace_Tech(X_DP_ReqId, "REP_ALIMENTATION_IAM", CType(wex.Response, System.Net.HttpWebResponse).StatusCode & "|" & StreamReader.ReadToEnd.ToString)
                StreamReader.Close()
            Else
                Write_Trace_Tech(X_DP_ReqId, "REP_ALIMENTATION_IAM", wex.Message.ToString)
                reset_connection()
            End If
        Catch ex As Exception
            RichTextBox1.AppendText(ex.Message & vbCrLf)
            Write_Trace_Tech(X_DP_ReqId, "REP_ALIMENTATION_IAM", ex.Message.ToString)
        End Try

    End Sub

    Public Async Sub send_AR_MSG()

debut:
        Await Task.Delay(180000)
        Dim data = BDD.DP_MsgTableAdapter.GetData_where_AR_must_be_send(Now)
        If data.Rows.Count > 0 Then
            AR_MSG(data.Item(0).MsgRef)
        End If

        GoTo debut
    End Sub


    Public Sub LECTURE_MSG(ByRef MsgRef As String)

        Dim X_DP_ReqId As String = System.Guid.NewGuid.ToString
        Write_Trace_Tech(X_DP_ReqId, "LECTURE_MSG", MsgRef)

        Try



            Dim objRequest As System.Net.HttpWebRequest


            objRequest = System.Net.HttpWebRequest.CreateHttp(Config.DP_URI & Config.DP_EtaTyp & "/" & Config.DP_EtaIdent & "/lecture_msg/" & MsgRef)
            'objRequest = System.Net.HttpWebRequest.CreateHttp("http://127.0.0.1:13000")
            'RichTextBox1.AppendText(objRequest.RequestUri.ToString + Chr(10))
            objRequest.Method = "POST"
            objRequest.Timeout = 30000

            objRequest.ClientCertificates.Add(DP_get_certif)

            objRequest.UserAgent = Config.DP_EtaTyp & "-" & Config.DP_EtaIdent & "-" & Config.DP_LogValid & "-" & Config.DP_LogVers & "-" & Config.DP_LogVDP

            'objRequest.ContentType = "text/plain"


            objRequest.Headers.Add("X-DP-ReqId", X_DP_ReqId)

            Dim objResponse As System.Net.HttpWebResponse = objRequest.GetResponse()
            Dim StreamReader As System.IO.StreamReader
            StreamReader = New System.IO.StreamReader(objResponse.GetResponseStream())


            My.Computer.FileSystem.WriteAllText(Config.DP_Directory & "Msg\" & MsgRef, StreamReader.ReadToEnd.ToString, False)
            StreamReader.Close()

            Dim xmldoc As New XmlDocument
            'xmldoc.Load(Config.LocalNetwork_ServerName & "\DP\Msg\" & MsgRef)
            xmldoc.Load(Config.DP_Directory & "Msg\" & MsgRef)
            BDD.DP_MsgTableAdapter.Insert(xmldoc.GetElementsByTagName("ref").Item(0).InnerText, xmldoc.GetElementsByTagName("type").Item(0).InnerText, _
                                         xmldoc.GetElementsByTagName("dateLecture").Item(0).InnerText, xmldoc.GetElementsByTagName("dateEmission").Item(0).InnerText, _
                                         xmldoc.GetElementsByTagName("dateExpiration").Item(0).InnerText, "", False, "", 0, Now, _
                                         xmldoc.GetElementsByTagName("emetteur").Item(0).InnerText, xmldoc.GetElementsByTagName("titre").Item(0).InnerText)
            '                             xmldoc.GetElementsByTagName("dateLecture").Item(0).InnerText + Chr(10) + xmldoc.GetElementsByTagName("dateEmission").Item(0).InnerText + Chr(10) + _
            '                             xmldoc.GetElementsByTagName("dateExpiration").Item(0).InnerText + Chr(10) + Now.ToLongDateString + Chr(10) + _
            '                             xmldoc.GetElementsByTagName("emetteur").Item(0).InnerText + Chr(10) + xmldoc.GetElementsByTagName("titre").Item(0).InnerText)

            DP_ALERTE_PRODUIT_insert(xmldoc)

            'If xmldoc.GetElementsByTagName("ref").Count > 0 Then
            'MsgRef = Mid(xmldoc.GetElementsByTagName("ref").Item(0).Value, InStrRev(xmldoc.GetElementsByTagName("ref").Item(0).Value, "/") + 1)
            'write_Trace_Tech(X_DP_ReqId, "REP_LECTURE_MSG", "MESSAGE:" & MsgRef)
            Write_Trace_Tech(X_DP_ReqId, "REP_LECTURE_MSG", "MESSAGE:" & MsgRef)
            'Else
            '    MsgRef = ""
            '    write_Trace_Tech(X_DP_ReqId, "REP_LECTURE_MSG", "OK")
            'End If



        Catch wex As System.Net.WebException
            If Not wex.Response Is Nothing Then
                Dim StreamReader As System.IO.StreamReader
                StreamReader = New System.IO.StreamReader(wex.Response.GetResponseStream)
                My.Computer.FileSystem.WriteAllText(Config.LocalNetwork_ServerName & "\DP\XML\log\Réponse\temp", StreamReader.ReadToEnd.ToString, False)
                StreamReader.Close()
                Dim xml_retour As New XmlDocument
                xml_retour.Load(Config.LocalNetwork_ServerName & "\DP\XML\log\Réponse\temp")
                Dim XMLelementliste As XmlNodeList
                XMLelementliste = xml_retour.GetElementsByTagName("acknowledgementDetail")
                If XMLelementliste.Count > 0 Then
                    Write_Trace_Tech(X_DP_ReqId, "REP_LECTURE_MSG", XMLelementliste.Item(0).Item("code").GetAttribute("code") & "|" & XMLelementliste.Item(0).Item("text").InnerText)
                Else
                    Write_Trace_Tech(X_DP_ReqId, "REP_LECTURE_MSG", wex.Message.ToString)
                End If
            Else
                Write_Trace_Tech(X_DP_ReqId, "REP_LECTURE_MSG", wex.Message.ToString)
            End If


        End Try



    End Sub
    Public Sub DP_ALERTE_PRODUIT_insert(ByVal Msg As XmlDocument)

        If Msg.GetElementsByTagName("type").Item(0).InnerText <> "ALERTE_PRODUIT" Then
            Exit Sub
        End If

        If Msg.GetElementsByTagName("produits").Count > 0 Then
            For Each produit As XmlElement In Msg.GetElementsByTagName("produits").Item(0).ChildNodes
                If produit.GetElementsByTagName("lots").Count > 0 Then
                    If Not produit.GetElementsByTagName("lots").Item(0).Attributes.GetNamedItem("ensemble") Is Nothing Then
                        If produit.GetElementsByTagName("lots").Item(0).Attributes.GetNamedItem("ensemble").Value = "LISTE" Then
                            For Each lot As XmlElement In produit.GetElementsByTagName("lots").Item(0).ChildNodes
                                If BDD.DP_ALERTE_PRODUITTableAdapter.GetData_unique(produit.GetElementsByTagName("code").Item(0).InnerText, Msg.GetElementsByTagName("ref").Item(0).InnerText, lot.GetAttribute("num")).Rows.Count = 0 Then
                                    BDD.DP_ALERTE_PRODUITTableAdapter.Insert(produit.GetElementsByTagName("code").Item(0).InnerText, Msg.GetElementsByTagName("ref").Item(0).InnerText, lot.GetAttribute("num"), False)
                                End If
                            Next
                        Else
                            If BDD.DP_ALERTE_PRODUITTableAdapter.GetData_unique(produit.GetElementsByTagName("code").Item(0).InnerText, Msg.GetElementsByTagName("ref").Item(0).InnerText, "*").Rows.Count = 0 Then
                                BDD.DP_ALERTE_PRODUITTableAdapter.Insert(produit.GetElementsByTagName("code").Item(0).InnerText, Msg.GetElementsByTagName("ref").Item(0).InnerText, "*", False)
                            End If
                        End If
                    Else
                        If BDD.DP_ALERTE_PRODUITTableAdapter.GetData_unique(produit.GetElementsByTagName("code").Item(0).InnerText, Msg.GetElementsByTagName("ref").Item(0).InnerText, "*").Rows.Count = 0 Then
                            BDD.DP_ALERTE_PRODUITTableAdapter.Insert(produit.GetElementsByTagName("code").Item(0).InnerText, Msg.GetElementsByTagName("ref").Item(0).InnerText, "*", False)
                        End If
                    End If
                Else
                    If BDD.DP_ALERTE_PRODUITTableAdapter.GetData_unique(produit.GetElementsByTagName("code").Item(0).InnerText, Msg.GetElementsByTagName("ref").Item(0).InnerText, "*").Rows.Count = 0 Then
                        BDD.DP_ALERTE_PRODUITTableAdapter.Insert(produit.GetElementsByTagName("code").Item(0).InnerText, Msg.GetElementsByTagName("ref").Item(0).InnerText, "*", False)
                    End If
                End If
            Next
        End If
    End Sub

    Public Sub AR_MSG(ByVal MsgRef As String)
        Dim DP_msg = BDD.DP_MsgTableAdapter.GetDataBy_MsgRef(MsgRef).Item(0)

        Dim X_DP_ReqId As String = System.Guid.NewGuid.ToString



        Try
            Dim objRequest As System.Net.HttpWebRequest


            objRequest = System.Net.HttpWebRequest.CreateHttp(Config.DP_URI & Config.DP_EtaTyp & "/" & Config.DP_EtaIdent & "/ar_msg/" & MsgRef)
            If Val(DP_msg.AR_nbr_transmission) = 0 Then
                Write_Trace_Tech(X_DP_ReqId, "AR_MSG", X_DP_ReqId)
            Else
                Write_Trace_Tech("", "REQUETE_EN_ATTENTE_RENVOYEE", "AR " & MsgRef)
                objRequest.Headers.Add("X-DP-ASyncReq", "AR-MSG")
            End If
            'objRequest = System.Net.HttpWebRequest.CreateHttp("http://127.0.0.1:13000")
            Dim postdata As String = Format(Now, "yyyy-MM-dd") & "T" & Format(Now, "HH:mm:ss") & ".000Z"

            Dim byteArray As Byte() = Encoding.UTF8.GetBytes(postdata)
            objRequest.ContentLength = byteArray.Length
            objRequest.Method = "POST"
            objRequest.Timeout = 30000

            objRequest.ClientCertificates.Add(DP_get_certif)

            objRequest.UserAgent = Config.DP_EtaTyp & "-" & Config.DP_EtaIdent & "-" & Config.DP_LogValid & "-" & Config.DP_LogVers & "-" & Config.DP_LogVDP

            objRequest.ContentType = "application/x-www-form-urlencoded"


            objRequest.Headers.Add("X-DP-ReqId", X_DP_ReqId)


            ' Get the request stream.
            Dim dataStream As Stream = objRequest.GetRequestStream
            ' Write the data to the request stream.
            dataStream.Write(byteArray, 0, byteArray.Length)
            ' Close the Stream object.
            dataStream.Close()


            Dim objResponse As System.Net.HttpWebResponse = objRequest.GetResponse()
            Dim StreamReader As System.IO.StreamReader
            StreamReader = New System.IO.StreamReader(objResponse.GetResponseStream())

            My.Computer.FileSystem.WriteAllText(Config.LocalNetwork_ServerName & "\DP\XML\log\Réponse\" & X_DP_ReqId, StreamReader.ReadToEnd, True)

            StreamReader.Close()

            BDD.DP_MsgTableAdapter.Update_by_MsgRef(DP_msg.Reader, True, "OK", DP_msg.AR_nbr_transmission + 1, Now, MsgRef)

            Write_Trace_Tech(X_DP_ReqId, "REP_AR_MSG", "OK")

        Catch wex As System.Net.WebException
            If Not wex.Response Is Nothing Then
                Dim StreamReader As System.IO.StreamReader
                StreamReader = New System.IO.StreamReader(wex.Response.GetResponseStream)
                My.Computer.FileSystem.WriteAllText(Config.LocalNetwork_ServerName & "\DP\XML\log\Réponse\temp", StreamReader.ReadToEnd.ToString, False)
                StreamReader.Close()
                Dim xml_retour As New XmlDocument
                xml_retour.Load(Config.LocalNetwork_ServerName & "\DP\XML\log\Réponse\temp")
                Dim XMLelementliste As XmlNodeList
                XMLelementliste = xml_retour.GetElementsByTagName("acknowledgementDetail")
                If XMLelementliste.Count > 0 Then
                    Write_Trace_Tech(X_DP_ReqId, "REP_AR_MSG", XMLelementliste.Item(0).Item("code").GetAttribute("code") & "|" & XMLelementliste.Item(0).Item("text").InnerText)
                    Dim next_trans_time As Date = Now
                    Dim Generator As System.Random = New System.Random()
                    next_trans_time = next_trans_time.AddMinutes(45 + Generator.Next(0, 30))
                    BDD.DP_MsgTableAdapter.Update_by_MsgRef(DP_msg.Reader, True, XMLelementliste.Item(0).Item("code").GetAttribute("code"), DP_msg.AR_nbr_transmission + 1, next_trans_time, MsgRef)
                    If DP_msg.AR_nbr_transmission + 1 < 2 Then
                        Write_Trace_Tech("", "REQUETE_EN_ATTENTE", "AR " & MsgRef)
                    End If
                Else
                    Write_Trace_Tech(X_DP_ReqId, "REP_AR_MSG", wex.Message.ToString)
                    Dim next_trans_time As Date = Now
                    Dim Generator As System.Random = New System.Random()
                    next_trans_time = next_trans_time.AddMinutes(Generator.Next(0, 59))
                    BDD.DP_MsgTableAdapter.Update_by_MsgRef(DP_msg.Reader, True, wex.Message, DP_msg.AR_nbr_transmission + 1, next_trans_time, MsgRef)
                    If DP_msg.AR_nbr_transmission < 2 Then
                        Write_Trace_Tech("", "REQUETE_EN_ATTENTE", "AR " & MsgRef)
                    End If
                End If
            Else
                Write_Trace_Tech(X_DP_ReqId, "REP_AR_MSG", wex.Message.ToString)
                Dim next_trans_time As Date = Now
                Dim Generator As System.Random = New System.Random()
                next_trans_time = next_trans_time.AddMinutes(Generator.Next(0, 59))
                BDD.DP_MsgTableAdapter.Update_by_MsgRef(DP_msg.Reader, True, wex.Message, DP_msg.AR_nbr_transmission + 1, next_trans_time, MsgRef)
                If DP_msg.AR_nbr_transmission < 2 Then
                    Write_Trace_Tech("", "REQUETE_EN_ATTENTE", "AR " & MsgRef)
                End If
            End If
        Catch ex As Exception
            Write_Trace_Tech(X_DP_ReqId, "REP_AR_MSG", ex.Message.ToString)
            Dim next_trans_time As Date = Now
            Dim Generator As System.Random = New System.Random()
            next_trans_time = next_trans_time.AddMinutes(Generator.Next(0, 59))
            BDD.DP_MsgTableAdapter.Update_by_MsgRef(DP_msg.Reader, True, ex.Message, DP_msg.AR_nbr_transmission + 1, next_trans_time, MsgRef)
            If DP_msg.AR_nbr_transmission < 2 Then
                Write_Trace_Tech("", "REQUETE_EN_ATTENTE", "AR " & MsgRef)
            End If
        End Try

    End Sub






    Private Sub NotifyIcon1_Click(sender As Object, e As EventArgs) Handles NotifyIcon1.Click
        If Me.WindowState = FormWindowState.Normal Then
            Me.WindowState = FormWindowState.Minimized

        Else
            Me.WindowState = FormWindowState.Normal

        End If

    End Sub

    Public Sub My_move_file(ByVal fichier As String, ByVal destination As String, ByVal overwrtite As Boolean)
        My.Computer.FileSystem.MoveFile(fichier, destination, overwrtite)
    End Sub

    Private Sub Button2_Click(sender As Object, e As EventArgs) Handles Button2.Click
        start()
    End Sub
End Class