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


Public Class DP
    Public DP_ConTyp As String
    Public DP_drawstring As String
    Public RefNbr As Integer 'nombre de refus de création
    Public RefDate As Date 'date dernier refus de création
    Public SupprDate As Date 'date suppression DP
    'Public Consultation_CodeErreur As String 'utiliser pour tester les cas où il faut proposer, ou non, une création automatique du DP.



 
    Private Print_num_page As Integer
    Private Print_current_row As Integer

    'attestations
   
    Public je_soussigné As String
    Public pharmacie As String
    Public fait_a As String
    Public reprleg_nom_prénom As String
    Public reprleg_qualité As String
    Public reprleg_adresse As String

    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 & "|" & current_User.ID & 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 & "|" & current_User.ID & Chr(10), True)
    End Sub

    Public Function Identifiant_patient_function() As String

        If CurrentBenéficiaire.G104C9 <> "" Then
            Return CurrentBenéficiaire.G104C1 & "_" & CurrentBenéficiaire.G104C3 & "_" & CurrentBenéficiaire.G104C9
        Else
            Return CurrentBenéficiaire.G104C1 & "_" & CurrentBenéficiaire.G104C3 & "_" & CurrentBenéficiaire.G101C8
        End If
    End Function
    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
        '       Replace(UCase(Config.DP_Certif), " ", "") & " " & Replace(UCase(Config.DP_Certif), " ", "").Length)
        For Each c In certCollection
       
            If Replace(UCase(c.SerialNumber.ToString), " ", "") = Replace(UCase(Config.DP_Certif), " ", "") Then '"4C8CC5" Then
                certificate = c
                Exit For
            End If
            'End If
        Next c
        If certificate Is Nothing Then
            MyMsg_Box.Presentation("Officine", "ERREUR: PAS DE CERTIFICAT X509 POUR DP", False, "", False, "", True, "OK")
            MyMsg_Box.ShowDialog()
        End If
        'If PhaIdent_DP = "" Then
        '    PhaIdent_DP = certificate.GetNameInfo(X509NameType.SimpleName, False)
        'End If
        Return certificate
    End Function


    Public Function PatNDP(ByVal NIR_assuré As String, ByVal Clé_NIR_assuré As String, ByVal NIR_ayantdroit As String, ByVal Clé_NIR_ayantdroit As String, ByVal Qualité_Bénéficiaire As String) As String
        Dim Clé_NDP_Return As String
        Dim C1C2 As String = Clé_NIR_assuré

        Dim X1 As Integer = Val(Mid(NIR_assuré, 8, 1))
        Dim Y1 As Integer = Val(Mid(NIR_assuré, 9, 1))
        Dim Z1 As Integer = Val(Mid(NIR_assuré, 10, 1))
        Dim C3C4 As String = (((X1 + 1) * (Y1 + 1) * (Z1 + 1)) Mod 100).ToString
        While C3C4.Length < 2
            C3C4 = "0" & C3C4
        End While

        Dim X2 As Integer = Val(Mid(NIR_assuré, 11, 1))
        Dim Y2 As Integer = Val(Mid(NIR_assuré, 12, 1))
        Dim Z2 As Integer = Val(Mid(NIR_assuré, 13, 1))
        Dim C5C6 As String = (((X2 + 1) * (Y2 + 1) * (Z2 + 1)) Mod 100).ToString
        While C5C6.Length < 2
            C5C6 = "0" & C5C6
        End While

        Dim C7C8 As String = Clé_NIR_ayantdroit

        Dim X5 As Integer = Val(Mid(NIR_ayantdroit, 8, 1))
        Dim Y5 As Integer = Val(Mid(NIR_ayantdroit, 9, 1))
        Dim Z5 As Integer = Val(Mid(NIR_ayantdroit, 10, 1))
        Dim C9C10 As String = (((X5 + 1) * (Y5 + 1) * (Z5 + 1)) Mod 100).ToString
        While C9C10.Length < 2
            C9C10 = "0" & C9C10
        End While

        Dim X6 As Integer = Val(Mid(NIR_ayantdroit, 11, 1))
        Dim Y6 As Integer = Val(Mid(NIR_ayantdroit, 12, 1))
        Dim Z6 As Integer = Val(Mid(NIR_ayantdroit, 13, 1))
        Dim C11C12 As String = (((X6 + 1) * (Y6 + 1) * (Z6 + 1)) Mod 100).ToString
        While C11C12.Length < 2
            C11C12 = "0" & C11C12
        End While

        Dim C13C14 As String = Qualité_Bénéficiaire
        While C13C14.Length < 2
            C13C14 = "0" & C13C14
        End While

        Clé_NDP_Return = C1C2 & C3C4 & C5C6 & C7C8 & C9C10 & C11C12 & C13C14

        Return Clé_NDP_Return

    End Function

#Region "INS-C"
    Public Function normaliser_prenom_INS_C(ByVal prenom As String) As String
        Dim retour As String = UCase(Replace(prenom, " ", ""))
        retour = UCase(Replace(retour, "-", ""))
        While retour.Length < 10
            retour = retour & " "
        End While
        Return retour
    End Function

    Public Function former_graine(ByVal prenom As String, datenaissance As String, nir As String) As String
        'datenaissance AAMMJJ
        Return normaliser_prenom_INS_C(prenom) & datenaissance & nir

    End Function

    Public Function ShaINSC(ByVal graine As String) As String

        Dim md As System.Security.Cryptography.SHA256 = System.Security.Cryptography.SHA256Managed.Create()
        Dim gr() As Byte = Encoding.UTF8.GetBytes(graine)
        Dim hash() As Byte = md.ComputeHash(gr)
        Dim result As New StringBuilder
        For i = 0 To hash.Length - 1
            result.Append(hash(i).ToString("x2"))
        Next
        Return result.ToString
    End Function

    Public Function FormerINSC(ByVal shaHex As String) As String
        shaHex = shaHex.Substring(0, 16)
        Dim dix As ULong = ULong.Parse(shaHex, System.Globalization.NumberStyles.HexNumber)

        Dim temp As ULong = dix Mod 97
        Dim maCle As Int16 = 97 - temp
        Dim maClestring As String = maCle.ToString
        While maClestring.Length < 2
            maClestring = "0" & maClestring
        End While

        Return dix.ToString & maClestring

    End Function


#End Region

#Region "Création"
    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.")

        Catch ex As CryptographicException
            MyMsg_Box.Presentation("Officine", ex.ToString, False, "", False, "", True, "OK")
            MyMsg_Box.ShowDialog()
            'Console.WriteLine(ex.Message)
        End Try

    End Sub

    Public Sub Création()
        Bandeau_info_bas_show("Création du DP...")

        Application.DoEvents()
        Dim X_DP_ReqId As String = System.Guid.NewGuid.ToString
        Dim statut_retour As String

        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 & "/creation")

            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)

            Dim postdata As String = System.IO.File.ReadAllText(Config.LocalNetwork_ServerName & "\DP\XML\model\DP_Création.xml")

            postdata = Replace(postdata, "${ReqId}", X_DP_ReqId)

            postdata = Replace(postdata, "${CreDate}", Format(DateTime.UtcNow, "yyyyMMddHHmmss"))

            postdata = Replace(postdata, "${ReqProd}", Config.DP_ReqProd)

            postdata = Replace(postdata, "${AttVers}", "DP-ACRE-130705")

            'postdata = Replace(postdata, "${PatNDP}", "MARTINQUATREVINGTNEUF|PAUL|19600111|1|469716600|" & PatNDP("1600134079089", "51", "1600134079089", "51", "00"))
            'Nom|Prénom|DateNaissance|RangGémellaire|NumSérieCarteVitale|Clé
            Dim qualité As String = CurrentBenéficiaire.G104C14
            While qualité.Length < 2
                qualité = "0" & qualité
            End While
            If CurrentBenéficiaire.G104C9 <> "" Then
                postdata = Replace(postdata, "${PatNDP}", CurrentBenéficiaire.G104C1 & "|" & CurrentBenéficiaire.G104C3 & "|" & Mid(CurrentBenéficiaire.G104C12, 1, 8) & "|" & _
                                  CurrentBenéficiaire.G104C13 & "|" & CurrentBenéficiaire.G101C2 & "|" & _
                                  PatNDP(CurrentBenéficiaire.G101C8, CurrentBenéficiaire.G101C9, CurrentBenéficiaire.G104C9, CurrentBenéficiaire.G104C10, qualité))
            Else
                postdata = Replace(postdata, "${PatNDP}", CurrentBenéficiaire.G104C1 & "|" & CurrentBenéficiaire.G104C3 & "|" & Mid(CurrentBenéficiaire.G104C12, 1, 8) & "|" & _
                                  CurrentBenéficiaire.G104C13 & "|" & CurrentBenéficiaire.G101C2 & "|" & _
                                  PatNDP(CurrentBenéficiaire.G101C8, CurrentBenéficiaire.G101C9, CurrentBenéficiaire.G101C8, CurrentBenéficiaire.G101C9, qualité))
            End If

            'postdata = Replace(postdata, "${PatINSC}", FormerINSC(ShaINSC(former_graine("PAUL", "600111", "1600134079089"))))
            If CurrentBenéficiaire.G104C9 <> "" Then
                postdata = Replace(postdata, "${PatINSC}", FormerINSC(ShaINSC(former_graine(CurrentBenéficiaire.G104C3, Mid(CurrentBenéficiaire.G104C12, 3, 6), CurrentBenéficiaire.G104C9))))
            Else
                postdata = Replace(postdata, "${PatINSC}", FormerINSC(ShaINSC(former_graine(CurrentBenéficiaire.G104C3, Mid(CurrentBenéficiaire.G104C12, 3, 6), CurrentBenéficiaire.G101C8))))
            End If

            'postdata = Replace(postdata, "${PatNDP->nom(champ1)}", "MARTINQUATREVINGTNEUF")
            'postdata = Replace(postdata, "${PatNDP->prenom(champ2)}", "PAUL")
            postdata = Replace(postdata, "${PatNDP->nom(champ1)}", CurrentBenéficiaire.G104C1)
            postdata = Replace(postdata, "${PatNDP->prenom(champ2)}", CurrentBenéficiaire.G104C3)

            'postdata = Replace(postdata, "${PatSexe}", "M")
            If CurrentBenéficiaire.G104C9 <> "" Then
                If Mid(CurrentBenéficiaire.G104C9, 1, 1) = "1" Then
                    postdata = Replace(postdata, "${PatSexe}", "M")
                ElseIf Mid(CurrentBenéficiaire.G104C9, 1, 1) = "2" Then
                    postdata = Replace(postdata, "${PatSexe}", "F")
                Else
                    postdata = Replace(postdata, "${PatSexe}", "U")
                End If
            Else
                If Mid(CurrentBenéficiaire.G101C8, 1, 1) = "1" Then
                    postdata = Replace(postdata, "${PatSexe}", "M")
                ElseIf Mid(CurrentBenéficiaire.G101C8, 1, 1) = "2" Then
                    postdata = Replace(postdata, "${PatSexe}", "F")
                Else
                    postdata = Replace(postdata, "${PatSexe}", "U")
                End If
            End If

            'postdata = Replace(postdata, "${PhaIdent}", "99900008626")
            ValeurChamp = "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
            TailleMax = 30
            SGD_LireChamp(NumeroSessionCPS, 1, 1, 3, ValeurChamp, TailleMax)
            postdata = Replace(postdata, "${PhaIdent}", Mid(ValeurChamp, 1, TailleMax))

            'postdata = Replace(postdata, "${EtaIdent}", "111111190")
            postdata = Replace(postdata, "${EtaIdent}", Config.DP_EtaIdent)

            My.Computer.FileSystem.WriteAllText(Config.LocalNetwork_ServerName & "\DP\XML\log\" & X_DP_ReqId & ".xml", postdata, False)

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

            Dim dataStream As Stream = DP_objRequest.GetRequestStream

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

            dataStream.Close()

            Write_Trace_Tech(X_DP_ReqId, "CREATION", Identifiant_patient_function)

            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
            DP_Connect.HEARTBEAT_variables.calcul_moyenne(DP_Connect.HEARTBEAT_variables.MetNbCr, DP_Connect.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\XML\log\Réponse\REP_CREATION_" & Format(Now, "yyyyMMddHHmmss") & "_" & X_DP_ReqId & ".xml", StreamReader.ReadToEnd.ToString, False)

            Write_Trace_Fonc("Création du DP effectuée", "", "", Identifiant_patient_function)
            Write_Trace_Tech(X_DP_ReqId, "REP_CREATION", "OK")

            COMPTOIR_MAIN.DP_affichage_statut("DP existant")

            MyMsg_Box.Presentation("Officine", "DP créé pour ce patient." + Chr(10) + "Une attestation de création va être imprimée." + Chr(10) + "Elle doit être remise au patient", False, "", False, "", True, "OK")
            MyMsg_Box.ShowDialog()

            Bandeau_info_bas_hide() 'Bandeau_info_bas_show_thread)

            imprim_Attestation_Création()


            statut_retour = "OK"
            'Me.DP_ReqTableAdapter.Insert(X_DP_Sequence_Number.ToString, X_DP_ReqId, "OK", 1, Now, Identifiant_patient_function, "CREATION")

            Next_Sequence_Number(objResponse)
            Missing_Sequence_Number(objResponse, X_DP_ReqId)

            Me.Visible = False

        Catch ex As System.Net.WebException
            Bandeau_info_bas_hide() 'Bandeau_info_bas_show_thread)
            Write_Trace_Tech(X_DP_ReqId, "CREATION_ECHEC", CurrentBenéficiaire.G104C1 & " " & CurrentBenéficiaire.G104C3 & " " & ex.ToString)
            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.Count > 0 Then
                    MyMsg_Box.Presentation("Officine", "Échec de création du DP" + Chr(10) + XMLelementliste.Item(0).Item("code").GetAttribute("code") + Chr(10) + XMLelementliste.Item(0).Item("text").InnerText, False, "", False, "", True, "OK")
                    MyMsg_Box.ShowDialog()
                    Write_Trace_Fonc("Échec de création du DP", "", XMLelementliste.Item(0).Item("text").InnerText, Identifiant_patient_function)
                    Write_Trace_Tech(X_DP_ReqId, "REP_CREATION", XMLelementliste.Item(0).Item("code").GetAttribute("code") & "|" & XMLelementliste.Item(0).Item("text").InnerText)
                    statut_retour = XMLelementliste.Item(0).Item("code").GetAttribute("code")
                Else
                    Write_Trace_Fonc("Échec de création du DP", "", ex.Message, Identifiant_patient_function)
                    Write_Trace_Tech(X_DP_ReqId, "REP_CREATION", ex.Message)
                    MyMsg_Box.Presentation("Officine", "Un problème technique est survenu. Il faudra créer le DP de ce patient une autre fois. Vous pouvez contacter votre centre de support. Détail de l’erreur :" + ex.Message.ToString, False, "", False, "", True, "OK")
                    MyMsg_Box.ShowDialog()
                    statut_retour = ex.Message
                End If
                XMLelementliste = xml_retour.GetElementsByTagName("PRPA_IN201312UV02")
                If XMLelementliste.Count > 0 Then
                    xml_retour.Save(Config.LocalNetwork_ServerName & "\DP\XML\log\Réponse\" & XMLelementliste.Item(0).Item("interactionId").GetAttribute("extension") & "_ECHEC_" & XMLelementliste.Item(0).Item("creationTime").GetAttribute("value") & "_" & X_DP_ReqId & ".xml")

                End If
            Else
                Write_Trace_Tech(X_DP_ReqId, "REP_CREATION", ex.Message)
                Write_Trace_Fonc("Échec de création du DP", "", ex.Message, Identifiant_patient_function)
                MyMsg_Box.Presentation("Officine", "L’opération est pour l’instant impossible : il n’y a plus de connexion avec le DP.", False, "", False, "", True, "OK")
                MyMsg_Box.ShowDialog()
                COMPTOIR_MAIN.DP_affichage_statut("Pas de connexion DP")
                statut_retour = ex.Message
                reset_connection()

            End If
        End Try


        'message.Dispose()
        Me.DP_ReqTableAdapter.Insert(X_DP_Sequence_Number.ToString, X_DP_ReqId, statut_retour, 1, Now, Identifiant_patient_function, "CREATION")

    End Sub

    Public Sub Refus_Création()



        Dim X_DP_ReqId As String = System.Guid.NewGuid.ToString
        Dim statut_retour As String
        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 & "/refus_creation")

            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)

            Dim postdata As String = System.IO.File.ReadAllText(Config.LocalNetwork_ServerName & "\DP\XML\model\DP_Refus_Création.xml")

            postdata = Replace(postdata, "${ReqId}", X_DP_ReqId)

            postdata = Replace(postdata, "${RefDate}", Format(DateTime.UtcNow, "yyyyMMddHHmmss"))

            postdata = Replace(postdata, "${ReqProd}", Config.DP_ReqProd)


            'postdata = Replace(postdata, "${PatNDP}", "MARTINQUATREVINGTNEUF|PAUL|19600111|1|469716600|" & PatNDP("1600134079089", "51", "1600134079089", "51", "00"))
            'Nom|Prénom|DateNaissance|RangGémellaire|NumSérieCarteVitale|Clé
            Dim qualité As String = CurrentBenéficiaire.G104C14
            While qualité.Length < 2
                qualité = "0" & qualité
            End While
            If CurrentBenéficiaire.G104C9 <> "" Then
                postdata = Replace(postdata, "${PatNDP}", CurrentBenéficiaire.G104C1 & "|" & CurrentBenéficiaire.G104C3 & "|" & Mid(CurrentBenéficiaire.G104C12, 1, 8) & "|" & _
                                  CurrentBenéficiaire.G104C13 & "|" & CurrentBenéficiaire.G101C2 & "|" & _
                                  PatNDP(CurrentBenéficiaire.G101C8, CurrentBenéficiaire.G101C9, CurrentBenéficiaire.G104C9, CurrentBenéficiaire.G104C10, qualité))
            Else
                postdata = Replace(postdata, "${PatNDP}", CurrentBenéficiaire.G104C1 & "|" & CurrentBenéficiaire.G104C3 & "|" & Mid(CurrentBenéficiaire.G104C12, 1, 8) & "|" & _
                                  CurrentBenéficiaire.G104C13 & "|" & CurrentBenéficiaire.G101C2 & "|" & _
                                  PatNDP(CurrentBenéficiaire.G101C8, CurrentBenéficiaire.G101C9, CurrentBenéficiaire.G101C8, CurrentBenéficiaire.G101C9, qualité))
            End If

            'postdata = Replace(postdata, "${PatINSC}", FormerINSC(ShaINSC(former_graine("PAUL", "600111", "1600134079089"))))
            If CurrentBenéficiaire.G104C9 <> "" Then
                postdata = Replace(postdata, "${PatINSC}", FormerINSC(ShaINSC(former_graine(CurrentBenéficiaire.G104C3, Mid(CurrentBenéficiaire.G104C12, 3, 6), CurrentBenéficiaire.G104C9))))
            Else
                postdata = Replace(postdata, "${PatINSC}", FormerINSC(ShaINSC(former_graine(CurrentBenéficiaire.G104C3, Mid(CurrentBenéficiaire.G104C12, 3, 6), CurrentBenéficiaire.G101C8))))
            End If

            'postdata = Replace(postdata, "${PatNDP->nom(champ1)}", "MARTINQUATREVINGTNEUF")
            'postdata = Replace(postdata, "${PatNDP->prenom(champ2)}", "PAUL")
            postdata = Replace(postdata, "${PatNDP->nom(champ1)}", CurrentBenéficiaire.G104C1)
            postdata = Replace(postdata, "${PatNDP->prenom(champ2)}", CurrentBenéficiaire.G104C3)

            'postdata = Replace(postdata, "${PatSexe}", "M")
            If CurrentBenéficiaire.G104C9 <> "" Then
                If Mid(CurrentBenéficiaire.G104C9, 1, 1) = "1" Then
                    postdata = Replace(postdata, "${PatSexe}", "M")
                ElseIf Mid(CurrentBenéficiaire.G104C9, 1, 1) = "2" Then
                    postdata = Replace(postdata, "${PatSexe}", "F")
                Else
                    postdata = Replace(postdata, "${PatSexe}", "U")
                End If
            Else
                If Mid(CurrentBenéficiaire.G101C8, 1, 1) = "1" Then
                    postdata = Replace(postdata, "${PatSexe}", "M")
                ElseIf Mid(CurrentBenéficiaire.G101C8, 1, 1) = "2" Then
                    postdata = Replace(postdata, "${PatSexe}", "F")
                Else
                    postdata = Replace(postdata, "${PatSexe}", "U")
                End If
            End If

            'postdata = Replace(postdata, "${PhaIdent}", "99900008626")
            ValeurChamp = "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
            TailleMax = 30
            SGD_LireChamp(NumeroSessionCPS, 1, 1, 3, ValeurChamp, TailleMax)
            postdata = Replace(postdata, "${PhaIdent}", Mid(ValeurChamp, 1, TailleMax))

            'postdata = Replace(postdata, "${EtaIdent}", "111111190")
            postdata = Replace(postdata, "${EtaIdent}", Config.DP_EtaIdent)

            RefNbr = RefNbr + 1
            postdata = Replace(postdata, "${RefNbr}", RefNbr)

            My.Computer.FileSystem.WriteAllText(Config.LocalNetwork_ServerName & "\DP\XML\log\" & X_DP_ReqId & ".xml", postdata, False)

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

            Dim dataStream As Stream = DP_objRequest.GetRequestStream

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

            dataStream.Close()

            Write_Trace_Tech(X_DP_ReqId, "REFUS_CREATION", Identifiant_patient_function)
            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
            'DP_Connect.HEARTBEAT_variables.calcul_moyenne(DP_Connect.HEARTBEAT_variables.MetNbCr, DP_Connect.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\XML\log\Réponse\REP_REFUS_CREATION_" & Format(Now, "yyyyMMddHHmmss") & "_" & X_DP_ReqId & ".xml", StreamReader.ReadToEnd.ToString, False)

            Write_Trace_Tech(X_DP_ReqId, "REFUS_CREATION", "OK")
            Write_Trace_Fonc("Refus de création du DP", "", "", Identifiant_patient_function)
            RefDate = Now
            COMPTOIR_MAIN.DP_affichage_statut("DP refusé")


            statut_retour = "OK"

            Next_Sequence_Number(objResponse)
            Missing_Sequence_Number(objResponse, X_DP_ReqId)

            Me.Visible = False

        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()

                Try
                    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
                        MyMsg_Box.Presentation("Officine", XMLelementliste.Item(0).Item("code").GetAttribute("code") + Chr(10) + XMLelementliste.Item(0).Item("text").InnerText, False, "", False, "", True, "OK")
                        MyMsg_Box.ShowDialog()
                        Write_Trace_Tech(X_DP_ReqId, "REFUS_CREATION", XMLelementliste.Item(0).Item("code").GetAttribute("code") & "|" & XMLelementliste.Item(0).Item("text").InnerText)
                        statut_retour = XMLelementliste.Item(0).Item("code").GetAttribute("code")
                    Else
                        Write_Trace_Tech(X_DP_ReqId, "REFUS_CREATION", ex.Message)
                        statut_retour = ex.Message
                    End If
                    XMLelementliste = xml_retour.GetElementsByTagName("PRPA_IN201312UV02")
                    If XMLelementliste.Count > 0 Then
                        xml_retour.Save(Config.LocalNetwork_ServerName & "\DP\XML\log\Réponse\" & XMLelementliste.Item(0).Item("interactionId").GetAttribute("extension") & "_ECHEC_" & XMLelementliste.Item(0).Item("creationTime").GetAttribute("value") & "_" & X_DP_ReqId & ".xml")

                    End If
                Catch ex2 As Exception
                    Write_Trace_Tech(X_DP_ReqId, "REFUS_CREATION", ex.Message)
                    statut_retour = ex.Message
                End Try

            Else



                Write_Trace_Tech(X_DP_ReqId, "REFUS_CREATION", ex.Message)
                Write_Trace_Fonc("Échec de refus de création du DP", "", ex.Message, Identifiant_patient_function)
                MyMsg_Box.Presentation("Officine", "L’opération est pour l’instant impossible : il n’y a plus de connexion avec le DP.", False, "", False, "", True, "OK")
                MyMsg_Box.ShowDialog()
                statut_retour = ex.Message
                COMPTOIR_MAIN.DP_affichage_statut("Pas de connexion DP")
                reset_connection()
            End If
        End Try

        Me.DP_ReqTableAdapter.Insert(X_DP_Sequence_Number.ToString, X_DP_ReqId, statut_retour, 1, Now, Identifiant_patient_function, "REFUS_CREATION")

    End Sub

    Public Sub Création_Client()
        Bandeau_info_bas_show("Création du DP...")

        Application.DoEvents()
        Dim X_DP_ReqId As String = System.Guid.NewGuid.ToString
        Dim statut_retour As String = ""

        Dim postdata As String = System.IO.File.ReadAllText(Config.LocalNetwork_ServerName & "\DP\XML\model\DP_Création.xml")

        postdata = Replace(postdata, "${ReqId}", X_DP_ReqId)

        postdata = Replace(postdata, "${CreDate}", Format(DateTime.UtcNow, "yyyyMMddHHmmss"))

        postdata = Replace(postdata, "${ReqProd}", Config.DP_ReqProd)

        postdata = Replace(postdata, "${AttVers}", "DP-ACRE-130705")

        Dim qualité As String = CurrentBenéficiaire.G104C14
        While qualité.Length < 2
            qualité = "0" & qualité
        End While
        If CurrentBenéficiaire.G104C9 <> "" Then
            postdata = Replace(postdata, "${PatNDP}", CurrentBenéficiaire.G104C1 & "|" & CurrentBenéficiaire.G104C3 & "|" & Mid(CurrentBenéficiaire.G104C12, 1, 8) & "|" & _
                              CurrentBenéficiaire.G104C13 & "|" & CurrentBenéficiaire.G101C2 & "|" & _
                              PatNDP(CurrentBenéficiaire.G101C8, CurrentBenéficiaire.G101C9, CurrentBenéficiaire.G104C9, CurrentBenéficiaire.G104C10, qualité))
        Else
            postdata = Replace(postdata, "${PatNDP}", CurrentBenéficiaire.G104C1 & "|" & CurrentBenéficiaire.G104C3 & "|" & Mid(CurrentBenéficiaire.G104C12, 1, 8) & "|" & _
                              CurrentBenéficiaire.G104C13 & "|" & CurrentBenéficiaire.G101C2 & "|" & _
                              PatNDP(CurrentBenéficiaire.G101C8, CurrentBenéficiaire.G101C9, CurrentBenéficiaire.G101C8, CurrentBenéficiaire.G101C9, qualité))
        End If

        If CurrentBenéficiaire.G104C9 <> "" Then
            postdata = Replace(postdata, "${PatINSC}", FormerINSC(ShaINSC(former_graine(CurrentBenéficiaire.G104C3, Mid(CurrentBenéficiaire.G104C12, 3, 6), CurrentBenéficiaire.G104C9))))
        Else
            postdata = Replace(postdata, "${PatINSC}", FormerINSC(ShaINSC(former_graine(CurrentBenéficiaire.G104C3, Mid(CurrentBenéficiaire.G104C12, 3, 6), CurrentBenéficiaire.G101C8))))
        End If

        postdata = Replace(postdata, "${PatNDP->nom(champ1)}", CurrentBenéficiaire.G104C1)
        postdata = Replace(postdata, "${PatNDP->prenom(champ2)}", CurrentBenéficiaire.G104C3)

        If CurrentBenéficiaire.G104C9 <> "" Then
            If Mid(CurrentBenéficiaire.G104C9, 1, 1) = "1" Then
                postdata = Replace(postdata, "${PatSexe}", "M")
            ElseIf Mid(CurrentBenéficiaire.G104C9, 1, 1) = "2" Then
                postdata = Replace(postdata, "${PatSexe}", "F")
            Else
                postdata = Replace(postdata, "${PatSexe}", "U")
            End If
        Else
            If Mid(CurrentBenéficiaire.G101C8, 1, 1) = "1" Then
                postdata = Replace(postdata, "${PatSexe}", "M")
            ElseIf Mid(CurrentBenéficiaire.G101C8, 1, 1) = "2" Then
                postdata = Replace(postdata, "${PatSexe}", "F")
            Else
                postdata = Replace(postdata, "${PatSexe}", "U")
            End If
        End If

        ValeurChamp = "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
        TailleMax = 30
        SGD_LireChamp(NumeroSessionCPS, 1, 1, 3, ValeurChamp, TailleMax)
        postdata = Replace(postdata, "${PhaIdent}", Mid(ValeurChamp, 1, TailleMax))

        postdata = Replace(postdata, "${EtaIdent}", Config.DP_EtaIdent)

        Dim byteArray As Byte() = Encoding.UTF8.GetBytes(postdata)
        My.Computer.FileSystem.WriteAllBytes(Config.LocalNetwork_ServerName & "\DPclients\" & X_DP_ReqId & ".xml", byteArray, False)
        Write_Trace_Tech(X_DP_ReqId, "CREATION", Identifiant_patient_function)

        '________________________________________________________________________________________________________________________
        '________________________________________________________________________________________________________________________
        '________________________________________________________________________________________________________________________
        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
            COMPTOIR_MAIN.DP_affichage_statut("serveur local: création échouée")
            Exit Sub
        End If
        response_file = Config.LocalNetwork_ServerName & "\DPclients\" & response_file
        '________________________________________________________________________________________________________________________
        Bandeau_info_bas_hide() 'Bandeau_info_bas_show_thread)
        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")
                    MyMsg_Box.Presentation("Officine", "échec de création du dp" + Chr(10) + xmlelementliste.Item(0).Item("code").GetAttribute("code") + Chr(10) + xmlelementliste.Item(0).Item("text").InnerText, False, "", False, "", True, "OK")
                    MyMsg_Box.ShowDialog()
                    Write_Trace_Fonc("échec de création du dp", "", xmlelementliste.Item(0).Item("text").InnerText, Identifiant_patient_function)
                    Write_Trace_Tech(X_DP_ReqId, "rep_creation", xmlelementliste.Item(0).Item("code").GetAttribute("code") & "|" & xmlelementliste.Item(0).Item("text").InnerText)
                Else


                    Write_Trace_Fonc("Création du DP effectuée", "", "", Identifiant_patient_function)
                    Write_Trace_Tech(X_DP_ReqId, "REP_CREATION", "OK")
                    COMPTOIR_MAIN.DP_affichage_statut("DP existant")
                    statut_retour = "OK"

                    MyMsg_Box.Presentation("Officine", "DP créé pour ce patient." + Chr(10) + "Une attestation de création va être imprimée." + Chr(10) + "Elle doit être remise au patient", False, "", False, "", True, "OK")
                    MyMsg_Box.ShowDialog()



                    imprim_Attestation_Création()
                End If
                Me.Visible = False


            Case "_error"

                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")
                    MyMsg_Box.Presentation("Officine", "échec de création du dp" + Chr(10) + xmlelementliste.Item(0).Item("code").GetAttribute("code") + Chr(10) + xmlelementliste.Item(0).Item("text").InnerText, False, "", False, "", True, "OK")
                    MyMsg_Box.ShowDialog()
                    Write_Trace_Fonc("échec de création du dp", "", xmlelementliste.Item(0).Item("text").InnerText, Identifiant_patient_function)
                    Write_Trace_Tech(X_DP_ReqId, "rep_creation", xmlelementliste.Item(0).Item("code").GetAttribute("code") & "|" & xmlelementliste.Item(0).Item("text").InnerText)
                Else
                    statut_retour = My.Computer.FileSystem.ReadAllText(response_file)
                    Write_Trace_Fonc("échec de création du dp", "", My.Computer.FileSystem.ReadAllText(response_file), Identifiant_patient_function)
                    Write_Trace_Tech(X_DP_ReqId, "rep_creation", My.Computer.FileSystem.ReadAllText(response_file))
                    MyMsg_Box.Presentation("Officine", "un problème technique est survenu. il faudra créer le dp de ce patient une autre fois. vous pouvez contacter votre centre de support. détail de l’erreur :" + My.Computer.FileSystem.ReadAllText(response_file), False, "", False, "", True, "OK")
                    MyMsg_Box.ShowDialog()
                End If

            Case "_ko"

                statut_retour = My.Computer.FileSystem.ReadAllText(response_file)
                Write_Trace_Tech(X_DP_ReqId, "REP_CREATION", My.Computer.FileSystem.ReadAllText(response_file))
                Write_Trace_Fonc("Échec de création du DP", "", My.Computer.FileSystem.ReadAllText(response_file), Identifiant_patient_function)
                MyMsg_Box.Presentation("Officine", "L’opération est pour l’instant impossible : il n’y a plus de connexion avec le DP.", False, "", False, "", True, "OK")
                MyMsg_Box.ShowDialog()
                COMPTOIR_MAIN.DP_affichage_statut("Pas de connexion DP")
        End Select

        Dim row_ = Me.DP_ReqTableAdapter.GetDataBy_ReqId(X_DP_ReqId).Item(0)
        Me.DP_ReqTableAdapter.Update_byReqID(row_.Sequence_Number, statut_retour, row_.nbr_trans, row_.next_trans_time, Identifiant_patient_function, "CREATION", X_DP_ReqId)

    End Sub

    Public Sub Refus_Création_Client()

        Bandeau_info_bas_show("Refus Création du DP...")

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

        Dim postdata As String = System.IO.File.ReadAllText(Config.LocalNetwork_ServerName & "\DP\XML\model\DP_Refus_Création.xml")

        postdata = Replace(postdata, "${ReqId}", X_DP_ReqId)

        postdata = Replace(postdata, "${RefDate}", Format(DateTime.UtcNow, "yyyyMMddHHmmss"))

        postdata = Replace(postdata, "${ReqProd}", Config.DP_ReqProd)


        'postdata = Replace(postdata, "${PatNDP}", "MARTINQUATREVINGTNEUF|PAUL|19600111|1|469716600|" & PatNDP("1600134079089", "51", "1600134079089", "51", "00"))
        'Nom|Prénom|DateNaissance|RangGémellaire|NumSérieCarteVitale|Clé
        Dim qualité As String = CurrentBenéficiaire.G104C14
        While qualité.Length < 2
            qualité = "0" & qualité
        End While
        If CurrentBenéficiaire.G104C9 <> "" Then
            postdata = Replace(postdata, "${PatNDP}", CurrentBenéficiaire.G104C1 & "|" & CurrentBenéficiaire.G104C3 & "|" & Mid(CurrentBenéficiaire.G104C12, 1, 8) & "|" & _
                              CurrentBenéficiaire.G104C13 & "|" & CurrentBenéficiaire.G101C2 & "|" & _
                              PatNDP(CurrentBenéficiaire.G101C8, CurrentBenéficiaire.G101C9, CurrentBenéficiaire.G104C9, CurrentBenéficiaire.G104C10, qualité))
        Else
            postdata = Replace(postdata, "${PatNDP}", CurrentBenéficiaire.G104C1 & "|" & CurrentBenéficiaire.G104C3 & "|" & Mid(CurrentBenéficiaire.G104C12, 1, 8) & "|" & _
                              CurrentBenéficiaire.G104C13 & "|" & CurrentBenéficiaire.G101C2 & "|" & _
                              PatNDP(CurrentBenéficiaire.G101C8, CurrentBenéficiaire.G101C9, CurrentBenéficiaire.G101C8, CurrentBenéficiaire.G101C9, qualité))
        End If

        'postdata = Replace(postdata, "${PatINSC}", FormerINSC(ShaINSC(former_graine("PAUL", "600111", "1600134079089"))))
        If CurrentBenéficiaire.G104C9 <> "" Then
            postdata = Replace(postdata, "${PatINSC}", FormerINSC(ShaINSC(former_graine(CurrentBenéficiaire.G104C3, Mid(CurrentBenéficiaire.G104C12, 3, 6), CurrentBenéficiaire.G104C9))))
        Else
            postdata = Replace(postdata, "${PatINSC}", FormerINSC(ShaINSC(former_graine(CurrentBenéficiaire.G104C3, Mid(CurrentBenéficiaire.G104C12, 3, 6), CurrentBenéficiaire.G101C8))))
        End If

        'postdata = Replace(postdata, "${PatNDP->nom(champ1)}", "MARTINQUATREVINGTNEUF")
        'postdata = Replace(postdata, "${PatNDP->prenom(champ2)}", "PAUL")
        postdata = Replace(postdata, "${PatNDP->nom(champ1)}", CurrentBenéficiaire.G104C1)
        postdata = Replace(postdata, "${PatNDP->prenom(champ2)}", CurrentBenéficiaire.G104C3)

        'postdata = Replace(postdata, "${PatSexe}", "M")
        If CurrentBenéficiaire.G104C9 <> "" Then
            If Mid(CurrentBenéficiaire.G104C9, 1, 1) = "1" Then
                postdata = Replace(postdata, "${PatSexe}", "M")
            ElseIf Mid(CurrentBenéficiaire.G104C9, 1, 1) = "2" Then
                postdata = Replace(postdata, "${PatSexe}", "F")
            Else
                postdata = Replace(postdata, "${PatSexe}", "U")
            End If
        Else
            If Mid(CurrentBenéficiaire.G101C8, 1, 1) = "1" Then
                postdata = Replace(postdata, "${PatSexe}", "M")
            ElseIf Mid(CurrentBenéficiaire.G101C8, 1, 1) = "2" Then
                postdata = Replace(postdata, "${PatSexe}", "F")
            Else
                postdata = Replace(postdata, "${PatSexe}", "U")
            End If
        End If

        'postdata = Replace(postdata, "${PhaIdent}", "99900008626")
        ValeurChamp = "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
        TailleMax = 30
        SGD_LireChamp(NumeroSessionCPS, 1, 1, 3, ValeurChamp, TailleMax)
        postdata = Replace(postdata, "${PhaIdent}", Mid(ValeurChamp, 1, TailleMax))

        'postdata = Replace(postdata, "${EtaIdent}", "111111190")
        postdata = Replace(postdata, "${EtaIdent}", Config.DP_EtaIdent)

        RefNbr = RefNbr + 1
        postdata = Replace(postdata, "${RefNbr}", RefNbr)

        Dim byteArray As Byte() = Encoding.UTF8.GetBytes(postdata)
        My.Computer.FileSystem.WriteAllBytes(Config.LocalNetwork_ServerName & "\DPclients\" & X_DP_ReqId & ".xml", byteArray, False)
        Write_Trace_Tech(X_DP_ReqId, "REFUS_CREATION", Identifiant_patient_function)

        '________________________________________________________________________________________________________________________
        '________________________________________________________________________________________________________________________
        '________________________________________________________________________________________________________________________
        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
            COMPTOIR_MAIN.DP_affichage_statut("Pas de connexion au serveur local pour DP")
            Exit Sub
        End If
        response_file = Config.LocalNetwork_ServerName & "\DPclients\" & response_file
        '________________________________________________________________________________________________________________________
        '________________________________________________________________________________________________________________________
        '________________________________________________________________________________________________________________________
        Bandeau_info_bas_hide() 'Bandeau_info_bas_show_thread)
        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")
                    MyMsg_Box.Presentation("Officine", xmlelementliste.Item(0).Item("code").GetAttribute("code") + Chr(10) + xmlelementliste.Item(0).Item("text").InnerText, False, "", False, "", True, "OK")
                    MyMsg_Box.ShowDialog()
                    Write_Trace_Tech(X_DP_ReqId, "REFUS_CREATION", xmlelementliste.Item(0).Item("code").GetAttribute("code") & "|" & xmlelementliste.Item(0).Item("text").InnerText)
                Else
                    Write_Trace_Tech(X_DP_ReqId, "REFUS_CREATION", "OK")
                    statut_retour = "OK"
                    Write_Trace_Fonc("Refus de création du DP", "", "", Identifiant_patient_function)
                    RefDate = Now
                    COMPTOIR_MAIN.DP_affichage_statut("DP refusé")
                End If
                Me.Visible = False

            Case "_error"
                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")
                    MyMsg_Box.Presentation("Officine", xmlelementliste.Item(0).Item("code").GetAttribute("code") + Chr(10) + xmlelementliste.Item(0).Item("text").InnerText, False, "", False, "", True, "OK")
                    MyMsg_Box.ShowDialog()
                    Write_Trace_Tech(X_DP_ReqId, "REFUS_CREATION", xmlelementliste.Item(0).Item("code").GetAttribute("code") & "|" & xmlelementliste.Item(0).Item("text").InnerText)
                Else
                    statut_retour = My.Computer.FileSystem.ReadAllText(response_file)
                    Write_Trace_Tech(X_DP_ReqId, "REFUS_CREATION", My.Computer.FileSystem.ReadAllText(response_file))
                End If

            Case "_ko"

                MyMsg_Box.Presentation("Officine", "L’opération est pour l’instant impossible : il n’y a plus de connexion avec le DP.", False, "", False, "", True, "OK")
                MyMsg_Box.ShowDialog()
                COMPTOIR_MAIN.DP_affichage_statut("Pas de connexion DP")
                statut_retour = My.Computer.FileSystem.ReadAllText(response_file)
                Write_Trace_Tech(X_DP_ReqId, "REFUS_CREATION", My.Computer.FileSystem.ReadAllText(response_file))
                Write_Trace_Fonc("Échec de refus de création du DP", "", My.Computer.FileSystem.ReadAllText(response_file), Identifiant_patient_function)
        End Select

        Dim row_ = Me.DP_ReqTableAdapter.GetDataBy_ReqId(X_DP_ReqId).Item(0)
        Me.DP_ReqTableAdapter.Update_byReqID(row_.Sequence_Number, statut_retour, row_.nbr_trans, row_.next_trans_time, Identifiant_patient_function, "REFUS_CREATION", X_DP_ReqId)
        Me.Visible = False





    End Sub
#End Region

#Region "Affichage"

    Public Sub Affichage_histo_local()
        Histo_DP_DataGridView.Rows.Clear()
        Dim NIR, Nom, Prénom As String
        If CurrentBenéficiaire.G104C9 <> "" Then
            NIR = CurrentBenéficiaire.G104C9
        Else
            NIR = CurrentBenéficiaire.G101C8
        End If


        Nom = CurrentBenéficiaire.G104C1
        Prénom = CurrentBenéficiaire.G104C3
        If NIR <> "" Then


            Dim datatable = COMPTOIR_MAIN.ActesTableAdapter.GetDataBy_bénéficiaire(NIR, Nom, Prénom)
            If datatable.Rows.Count > 0 Then
                Dim r_datagridview As Integer = 0

                For r_datatable = 0 To datatable.Rows.Count - 1
                    Histo_DP_DataGridView.Rows.Add()
                    If datatable.Item(r_datatable).EAN13 <> "" Then
                        Histo_DP_DataGridView.Item(CIP_Histo_DP.Index, r_datagridview).Value = datatable.Item(r_datatable).EAN13
                    ElseIf datatable.Item(r_datatable).CIP <> "" Then
                        Histo_DP_DataGridView.Item(CIP_Histo_DP.Index, r_datagridview).Value = datatable.Item(r_datatable).CIP
                    End If
                    Histo_DP_DataGridView.Item(DC_Histo_DP.Index, r_datagridview).Value = datatable.Item(r_datatable).Désignation
                    Histo_DP_DataGridView.Item(QteC_Histo_DP.Index, r_datagridview).Value = datatable.Item(r_datatable).Quantité

                    '''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''
                    'Histo_DP_DataGridView.Item(DisDate_Histo_DP.Index, r_datagridview).Value = datatable.Item(r_datatable)._Date
                    Dim adate As Date

                    DateTime.SpecifyKind(adate, DateTimeKind.Utc)
                    DateTime.TryParseExact(datatable.Item(r_datatable)._Date, "yyyyMMddHHmmss", Nothing, Globalization.DateTimeStyles.None, adate)
                    Histo_DP_DataGridView.Item(DisDate_Histo_DP.Index, r_datagridview).Value = adate

                    '''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''
                    Histo_DP_DataGridView.Item(Origine_Histo_DP.Index, r_datagridview).Value = "local"
                    Histo_DP_DataGridView.Item(PrdPoso_Histo_DP.Index, r_datagridview).Value = datatable.Item(r_datatable).DP_Poso
                    Histo_DP_DataGridView.Item(PrdRect_Histo_DP.Index, r_datagridview).Value = datatable.Item(r_datatable).DP_Rect

                    r_datagridview = r_datagridview + 1
                Next

                Histo_DP_DataGridView.Sort(DisDate_Histo_DP, ComponentModel.ListSortDirection.Ascending)

            End If

        End If

    End Sub
    Public Sub Affichage_serveur(ByVal ConTyp As String)

debut:
        If ConTyp <> "EDITION" Then
            COMPTOIR_MAIN.DP_affichage_statut("Accès au DP en cours")
        Else
            Edition_DP_DataGridView.Rows.Clear()
        End If
        'Histo_DP_DataGridView.Rows.Clear()

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

        If ConTyp = "REFUS_CONSULTATION" Then
            Write_Trace_Tech(X_DP_ReqId, "CONSULTATION", "(REFUSEE)" & Identifiant_patient_function())
        Else
            Write_Trace_Tech(X_DP_ReqId, "CONSULTATION", Identifiant_patient_function)
        End If




        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




            Dim postdata As String = System.IO.File.ReadAllText(Config.LocalNetwork_ServerName & "\DP\xml\model\DP_Consultation.xml")
            postdata = Replace(postdata, "${ReqId}", X_DP_ReqId)
            postdata = Replace(postdata, "${ConDate}", Format(DateTime.UtcNow, "yyyyMMddhhmmss"))
            postdata = Replace(postdata, "${ReqProd}", Config.DP_ReqProd)
            ValeurChamp = "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
            TailleMax = 30
            SGD_LireChamp(NumeroSessionCPS, 1, 1, 3, ValeurChamp, TailleMax)
            postdata = Replace(postdata, "${PhaIdent}", Mid(ValeurChamp, 1, TailleMax))
            postdata = Replace(postdata, "${EtaIdent}", Config.DP_EtaIdent)
            Dim qualité As String = CurrentBenéficiaire.G104C14
            While qualité.Length < 2
                qualité = "0" & qualité
            End While
            If CurrentBenéficiaire.G104C9 <> "" Then
                postdata = Replace(postdata, "${PatNDP}", CurrentBenéficiaire.G104C1 & "|" & CurrentBenéficiaire.G104C3 & "|" & Mid(CurrentBenéficiaire.G104C12, 1, 8) & "|" & _
                                  CurrentBenéficiaire.G104C13 & "|" & CurrentBenéficiaire.G101C2 & "|" & _
                                  PatNDP(CurrentBenéficiaire.G101C8, CurrentBenéficiaire.G101C9, CurrentBenéficiaire.G104C9, CurrentBenéficiaire.G104C10, qualité))
            Else
                postdata = Replace(postdata, "${PatNDP}", CurrentBenéficiaire.G104C1 & "|" & CurrentBenéficiaire.G104C3 & "|" & Mid(CurrentBenéficiaire.G104C12, 1, 8) & "|" & _
                                  CurrentBenéficiaire.G104C13 & "|" & CurrentBenéficiaire.G101C2 & "|" & _
                                  PatNDP(CurrentBenéficiaire.G101C8, CurrentBenéficiaire.G101C9, CurrentBenéficiaire.G101C8, CurrentBenéficiaire.G101C9, qualité))
            End If
            If CurrentBenéficiaire.G104C9 <> "" Then
                postdata = Replace(postdata, "${PatINSC}", FormerINSC(ShaINSC(former_graine(CurrentBenéficiaire.G104C3, Mid(CurrentBenéficiaire.G104C12, 3, 6), CurrentBenéficiaire.G104C9))))
            Else
                postdata = Replace(postdata, "${PatINSC}", FormerINSC(ShaINSC(former_graine(CurrentBenéficiaire.G104C3, Mid(CurrentBenéficiaire.G104C12, 3, 6), CurrentBenéficiaire.G101C8))))
            End If
            postdata = Replace(postdata, "${ConTyp}", ConTyp)

            Dim byteArray As Byte() = Encoding.UTF8.GetBytes(postdata)
            My.Computer.FileSystem.WriteAllBytes(Config.LocalNetwork_ServerName & "\DP\xml\log\" & X_DP_ReqId & ".xml", byteArray, False)


            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

            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)

            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"
                    DP_Connect.HEARTBEAT_variables.calcul_moyenne(DP_Connect.HEARTBEAT_variables.MetNbEd, DP_Connect.HEARTBEAT_variables.MetEdi, request_time_debut, request_time_fin)
                Case "CONSULTATION_TOUT", "CONSULTATION"
                    DP_Connect.HEARTBEAT_variables.calcul_moyenne(DP_Connect.HEARTBEAT_variables.MetNbCs, DP_Connect.HEARTBEAT_variables.MetCon, request_time_debut, request_time_fin)
            End Select



            Select Case ConTyp
                Case "CONSULTATION_TOUT", "CONSULTATION"
                    COMPTOIR_MAIN.DP_affichage_statut("DP existant")
                Case "REFUS_CONSULTATION"
                    COMPTOIR_MAIN.DP_affichage_statut("DP en alimentation")
            End Select

            Dim StreamReader As System.IO.StreamReader

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

                histo_dp.LoadXml(StreamReader.ReadToEnd.ToString)
                histo_dp.Save(Config.LocalNetwork_ServerName & "\DP\XML\log\Réponse\test.xml")
                StreamReader.Close()
                Dim clinicalDocuments = histo_dp.GetElementsByTagName("clinicalDocument")

                'Dim r As Integer=0
                Dim r As Integer = Histo_DP_DataGridView.RowCount
                Dim rr As Integer = Edition_DP_DataGridView.RowCount

                For i = 0 To clinicalDocuments.Count - 1

                    Dim entries = clinicalDocuments(i).Item("component").Item("structuredBody").Item("component").Item("section").ChildNodes

                    For s = 0 To entries.Count - 1
                        If ConTyp <> "EDITION" Then
                            Try

                                Histo_DP_DataGridView.Rows.Add()

                                '''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''
                                'Histo_DP_DataGridView.Item(DisDate_Histo_DP.Index, r).Value = clinicalDocuments(i)("effectiveTime").GetAttribute("value")
                                Dim adate As Date
                                DateTime.SpecifyKind(adate, DateTimeKind.Utc)
                                DateTime.TryParseExact(clinicalDocuments(i)("effectiveTime").GetAttribute("value"), "yyyyMMddhhmmss", Nothing, Globalization.DateTimeStyles.None, adate)
                                Histo_DP_DataGridView.Item(DisDate_Histo_DP.Index, r).Value = adate.ToLocalTime

                                '''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''
                                Histo_DP_DataGridView.Item(EtaTyp_Histo_DP.Index, r).Value = clinicalDocuments(i).Item("author").Item("assignedAuthor").Item("representedOrganization").Item("typeId").GetAttribute("extension")
                                Select Case UCase(Histo_DP_DataGridView.Item(EtaTyp_Histo_DP.Index, r).Value)
                                    Case "OFFICINE"
                                        Histo_DP_DataGridView.Rows.Item(r).DefaultCellStyle.BackColor = Color.LightGreen
                                    Case "PUI"
                                        Histo_DP_DataGridView.Rows.Item(r).DefaultCellStyle.BackColor = Color.LightBlue
                                    Case "DISTRIBUTEUR"
                                        Histo_DP_DataGridView.Rows.Item(r).DefaultCellStyle.BackColor = Color.LightYellow
                                End Select
                                Histo_DP_DataGridView.Item(PrdPoso_Histo_DP.Index, r).Value = entries(s).Item("substanceAdministration").Item("text").InnerText
                                Histo_DP_DataGridView.Item(QteC_Histo_DP.Index, r).Value = entries(s).Item("substanceAdministration").Item("doseQuantity").GetAttribute("value")
                                If entries(s).Item("substanceAdministration").Item("doseQuantity").ChildNodes.Count > 0 Then
                                    Histo_DP_DataGridView.Item(QteU_Histo_DP.Index, r).Value = entries(s).Item("substanceAdministration").Item("doseQuantity").Item("translation").GetAttribute("value")
                                End If

                                Dim manufacturedProduct_childnodes = entries(s).Item("substanceAdministration").Item("consumable").Item("manufacturedProduct").ChildNodes

                                For c = 0 To manufacturedProduct_childnodes.Count - 1
                                    If manufacturedProduct_childnodes(c).Name = "id" Then
                                        Dim root, extension As String
                                        root = ""
                                        extension = ""
                                        For attrb_indx = 0 To manufacturedProduct_childnodes(c).Attributes.Count - 1
                                            If manufacturedProduct_childnodes(c).Attributes.ItemOf(attrb_indx).Name = "extension" Then
                                                extension = manufacturedProduct_childnodes(c).Attributes.ItemOf(attrb_indx).Value
                                            ElseIf manufacturedProduct_childnodes(c).Attributes.ItemOf(attrb_indx).Name = "root" Then
                                                root = manufacturedProduct_childnodes(c).Attributes.ItemOf(attrb_indx).Value
                                            End If
                                        Next
                                        Select Case root
                                            Case "2.16.840.1.113883.2.8.1.11"
                                                Histo_DP_DataGridView.Item(CIP_Histo_DP.Index, r).Value = extension
                                            Case "2.16.840.1.113883.2.8.1.12"
                                                Histo_DP_DataGridView.Item(UCD_Histo_DP.Index, r).Value = extension
                                            Case "2.16.840.1.113883.2.8.1.13"
                                                Histo_DP_DataGridView.Item(CIS_Histo_DP.Index, r).Value = extension
                                            Case "2.16.840.1.113883.2.8.1.14"
                                                Histo_DP_DataGridView.Item(DC_Histo_DP.Index, r).Value = extension
                                            Case "2.16.840.1.113883.2.8.1.15"
                                                Histo_DP_DataGridView.Item(ATC_Histo_DP.Index, r).Value = extension
                                        End Select
                                    ElseIf manufacturedProduct_childnodes(c).Name = "manufacturedMaterial" And Histo_DP_DataGridView.Item(DC_Histo_DP.Index, r).Value Is Nothing Then
                                        Histo_DP_DataGridView.Item(DC_Histo_DP.Index, r).Value = manufacturedProduct_childnodes(c).ChildNodes.Item(0).InnerText
                                    End If
                                Next
                                Histo_DP_DataGridView.Item(PrdRect_Histo_DP.Index, r).Value = clinicalDocuments(i).Item("component").Item("structuredBody").Item("component").Item("section").Item("entry").Item("substanceAdministration").Item("entryRelationship").Item("observation").Item("text").InnerText
                                Histo_DP_DataGridView.Item(Origine_Histo_DP.Index, r).Value = "DP"

                                If Val(Histo_DP_DataGridView.Item(CIP_Histo_DP.Index, r).Value) = 0 Then
                                    Histo_DP_DataGridView.Rows.RemoveAt(r)
                                    Me.Text = "DP « incomplet »"
                                    COMPTOIR_MAIN.DP_affichage_statut("DP incomplet")
                                    r = r - 1
                                End If
                                r = r + 1


                            Catch ex_entry As Exception
                                MyMsg_Box.Presentation("Officine", ex_entry.ToString, False, "", False, "", True, "OK")
                                MyMsg_Box.ShowDialog()
                                COMPTOIR_MAIN.DP_affichage_statut("Erreur technique")
                            End Try

                        ElseIf ConTyp = "EDITION" Then
                            Try

                                Edition_DP_DataGridView.Rows.Add()


                                '''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''
                                'Edition_DP_DataGridView.Item(DisDate_Histo_DP.Index, rr).Value = clinicalDocuments(i)("effectiveTime").GetAttribute("value")
                                Dim adate As Date
                                DateTime.SpecifyKind(adate, DateTimeKind.Utc)
                                DateTime.TryParseExact(clinicalDocuments(i)("effectiveTime").GetAttribute("value"), "yyyyMMddhhmmss", Nothing, Globalization.DateTimeStyles.None, adate)
                                Edition_DP_DataGridView.Item(DataGridViewTextBoxColumn8.Index, rr).Value = adate.ToLocalTime

                                '''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''
                                Edition_DP_DataGridView.Item(EtaTyp_Histo_DP.Index, rr).Value = clinicalDocuments(i).Item("author").Item("assignedAuthor").Item("representedOrganization").Item("typeId").GetAttribute("extension")
                                Select Case UCase(Edition_DP_DataGridView.Item(EtaTyp_Histo_DP.Index, rr).Value)
                                    Case "OFFICINE"
                                        Edition_DP_DataGridView.Rows.Item(rr).DefaultCellStyle.BackColor = Color.LightGreen
                                    Case "PUI"
                                        Edition_DP_DataGridView.Rows.Item(rr).DefaultCellStyle.BackColor = Color.LightBlue
                                    Case "DISTRIBUTEUR"
                                        Edition_DP_DataGridView.Rows.Item(rr).DefaultCellStyle.BackColor = Color.LightYellow
                                End Select
                                Edition_DP_DataGridView.Item(PrdPoso_Histo_DP.Index, rr).Value = entries(s).Item("substanceAdministration").Item("text").InnerText
                                Edition_DP_DataGridView.Item(QteC_Histo_DP.Index, rr).Value = entries(s).Item("substanceAdministration").Item("doseQuantity").GetAttribute("value")
                                If entries(s).Item("substanceAdministration").Item("doseQuantity").ChildNodes.Count > 0 Then
                                    Edition_DP_DataGridView.Item(QteU_Histo_DP.Index, rr).Value = entries(s).Item("substanceAdministration").Item("doseQuantity").Item("translation").GetAttribute("value")
                                End If

                                Dim manufacturedProduct_childnodes = entries(s).Item("substanceAdministration").Item("consumable").Item("manufacturedProduct").ChildNodes

                                For c = 0 To manufacturedProduct_childnodes.Count - 1
                                    If manufacturedProduct_childnodes(c).Name = "id" Then
                                        Dim root, extension As String
                                        root = ""
                                        extension = ""
                                        For attrb_indx = 0 To manufacturedProduct_childnodes(c).Attributes.Count - 1
                                            If manufacturedProduct_childnodes(c).Attributes.ItemOf(attrb_indx).Name = "extension" Then
                                                extension = manufacturedProduct_childnodes(c).Attributes.ItemOf(attrb_indx).Value
                                            ElseIf manufacturedProduct_childnodes(c).Attributes.ItemOf(attrb_indx).Name = "root" Then
                                                root = manufacturedProduct_childnodes(c).Attributes.ItemOf(attrb_indx).Value
                                            End If
                                        Next
                                        Select Case root
                                            Case "2.16.840.1.113883.2.8.1.11"
                                                Edition_DP_DataGridView.Item(CIP_Histo_DP.Index, rr).Value = extension
                                            Case "2.16.840.1.113883.2.8.1.12"
                                                Edition_DP_DataGridView.Item(UCD_Histo_DP.Index, rr).Value = extension
                                            Case "2.16.840.1.113883.2.8.1.13"
                                                Edition_DP_DataGridView.Item(CIS_Histo_DP.Index, rr).Value = extension
                                            Case "2.16.840.1.113883.2.8.1.14"
                                                Edition_DP_DataGridView.Item(DC_Histo_DP.Index, rr).Value = extension
                                            Case "2.16.840.1.113883.2.8.1.15"
                                                Edition_DP_DataGridView.Item(ATC_Histo_DP.Index, rr).Value = extension
                                        End Select
                                    ElseIf manufacturedProduct_childnodes(c).Name = "manufacturedMaterial" And Edition_DP_DataGridView.Item(DC_Histo_DP.Index, rr).Value Is Nothing Then
                                        Edition_DP_DataGridView.Item(DC_Histo_DP.Index, rr).Value = manufacturedProduct_childnodes(c).ChildNodes.Item(0).InnerText
                                    End If
                                Next
                                Edition_DP_DataGridView.Item(PrdRect_Histo_DP.Index, rr).Value = clinicalDocuments(i).Item("component").Item("structuredBody").Item("component").Item("section").Item("entry").Item("substanceAdministration").Item("entryRelationship").Item("observation").Item("text").InnerText
                                Edition_DP_DataGridView.Item(Origine_Histo_DP.Index, rr).Value = "DP"

                                If Val(Edition_DP_DataGridView.Item(CIP_Histo_DP.Index, rr).Value) = 0 Then
                                    Edition_DP_DataGridView.Rows.RemoveAt(rr)
                                    Me.Text = "DP « incomplet »"
                                    COMPTOIR_MAIN.DP_affichage_statut("DP incomplet")
                                    rr = rr - 1
                                End If
                                rr = rr + 1


                            Catch ex_entry As Exception
                                MyMsg_Box.Presentation("Officine", ex_entry.ToString, False, "", False, "", True, "OK")
                                MyMsg_Box.ShowDialog()
                                COMPTOIR_MAIN.DP_affichage_statut("Erreur technique")
                            End Try
                        End If

                    Next

                Next

                Histo_DP_DataGridView.Sort(DisDate_Histo_DP, ComponentModel.ListSortDirection.Ascending)
                Edition_DP_DataGridView.Sort(DataGridViewTextBoxColumn8, ComponentModel.ListSortDirection.Ascending)
            Catch ex As Exception

                DP_ConTyp = "SANS_CONSULTATION"
                MyMsg_Box.Presentation("Officine", "ERREUR DE CONSULTATION DU DP:" + Chr(10) + ex.ToString, False, "", False, "", True, "OK")
                MyMsg_Box.ShowDialog()
            End Try

            Write_Trace_Tech(X_DP_ReqId, "REP_" & ConTyp, "OK")
            If DP_ConTyp <> "REFUS_CONSULTATION" Then
                Write_Trace_Fonc("Accès au DP effectué", "", "Historique DP utilisé pour la dispensation", Identifiant_patient_function)
            Else
                Write_Trace_Fonc("Accès au DP effectué", "", "Accès à l’historique refusé par le patient", Identifiant_patient_function)
            End If
        Catch ex As System.Net.WebException
            If Not ex.Response Is Nothing Then
                COMPTOIR_MAIN.DP_affichage_statut("Erreur technique")
                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.Count > 0 Then
                    Select Case XMLelementliste.Item(0).Item("code").GetAttribute("code")

                        Case "DP_REFUSE"
                            RefNbr = Val(Mid(XMLelementliste.Item(0).Item("text").InnerText, InStr(XMLelementliste.Item(0).Item("text").InnerText, ":") + 1, InStr(XMLelementliste.Item(0).Item("text").InnerText, ",") - InStr(XMLelementliste.Item(0).Item("text").InnerText, ":")))
                            RefDate = Convert.ToDateTime(Mid(XMLelementliste.Item(0).Item("text").InnerText, InStrRev(XMLelementliste.Item(0).Item("text").InnerText, ":") + 2, 10))
                            Write_Trace_Fonc("Accès au DP non effectué", Now.ToShortDateString, "DP refusé", Identifiant_patient_function)
                            COMPTOIR_MAIN.DP_affichage_statut("DP refusé")
                        Case "DP_SUPPRIME"
                            SupprDate = Convert.ToDateTime(Mid(XMLelementliste.Item(0).Item("text").InnerText, InStrRev(XMLelementliste.Item(0).Item("text").InnerText, ":") + 2, 10))
                            Write_Trace_Fonc("Accès au DP non effectué", Now.ToShortDateString, "DP supprimé", Identifiant_patient_function)
                            COMPTOIR_MAIN.DP_affichage_statut("DP supprimé")
                        Case "IDENTIFIANT_INCONNU"
                            Write_Trace_Fonc("Accès au DP non effectué", Now.ToShortDateString, "DP inexistant", Identifiant_patient_function)
                            COMPTOIR_MAIN.DP_affichage_statut("DP inexistant")
                        Case Else
                            Write_Trace_Fonc("Accès au DP non effectué", Now.ToShortDateString, "Problème technique", Identifiant_patient_function)
                            COMPTOIR_MAIN.DP_affichage_statut("Erreur technique")
                            MyMsg_Box.Presentation("Officine", "Connexion au DP échouée, contactez support technique.", False, "", False, "", True, "OK")
                            MyMsg_Box.ShowDialog()
                    End Select
                    Write_Trace_Tech(X_DP_ReqId, "REP_" & ConTyp, XMLelementliste.Item(0).Item("code").GetAttribute("code") & "|" & XMLelementliste.Item(0).Item("text").InnerText)
                Else
                    Write_Trace_Fonc("Accès au DP non effectué", Now.ToShortDateString, "Problème technique", Identifiant_patient_function)
                    Write_Trace_Tech(X_DP_ReqId, "REP_" & ConTyp, ex.Message.ToString)
                    MyMsg_Box.Presentation("Officine", "Connexion au DP échouée, contactez support technique." + Chr(10) + ex.Message.ToString, False, "", False, "", True, "OK")
                    MyMsg_Box.ShowDialog()
                End If

            Else
                Write_Trace_Fonc("Accès au DP non effectué", Now.ToShortDateString, "Pas de connexion DP", Identifiant_patient_function)
                COMPTOIR_MAIN.DP_affichage_statut("Pas de connexion DP")
                Write_Trace_Tech(X_DP_ReqId, "REP_" & ConTyp, ex.Message.ToString)
                ''_________________________________________________________________________________
                If ConTyp = "EDITION" Then
                    MyMsg_Box.Presentation("Officine", "L’opération est pour l’instant impossible : il n’y a plus de connexion avec le DP.", False, "", False, "", True, "OK")
                    MyMsg_Box.ShowDialog()
                ElseIf Config.DP_Consulatation_reconnect = False Then
                    Config.DP_Consulatation_reconnect = True
                    MyMsg_Box.Presentation("Officine", "Connexion au DP échouée, voulez-vous tenter à nouveau?" + Chr(10) + "(sinon continuer sans connexion au DP)", True, "OUI", True, "NON", False, "")
                    If MyMsg_Box.ShowDialog() = MsgBoxResult.Yes Then
                        GoTo debut
                    End If
                Else
                    MyMsg_Box.Presentation("Officine", "Connexion au DP échouée, contactez support technique.", False, "", False, "", True, "OK")
                    MyMsg_Box.ShowDialog()
                End If
                '_________________________________________________________________________________
                reset_connection()
            End If
        End Try

    End Sub
    Public Sub Affichage_client(ByVal ConTyp As String)
debut:

        If ConTyp <> "EDITION" Then
            COMPTOIR_MAIN.DP_affichage_statut("Accès au DP en cours")
        Else
            Edition_DP_DataGridView.Rows.Clear()
        End If
        'Histo_DP_DataGridView.Rows.Clear()


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

        If ConTyp = "REFUS_CONSULTATION" Then
            Write_Trace_Tech(X_DP_ReqId, "CONSULTATION", "(REFUSEE)" & Identifiant_patient_function())
        Else
            Write_Trace_Tech(X_DP_ReqId, "CONSULTATION", Identifiant_patient_function)
        End If

        Dim statut_retour As String = ""

        Dim postdata As String = System.IO.File.ReadAllText(Config.LocalNetwork_ServerName & "\DP\xml\model\DP_Consultation.xml")
        postdata = Replace(postdata, "${ReqId}", X_DP_ReqId)
        postdata = Replace(postdata, "${ConDate}", Format(DateTime.UtcNow, "yyyyMMddhhmmss"))
        postdata = Replace(postdata, "${ReqProd}", Config.DP_ReqProd)
        ValeurChamp = "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
        TailleMax = 30
        SGD_LireChamp(NumeroSessionCPS, 1, 1, 3, ValeurChamp, TailleMax)
        postdata = Replace(postdata, "${PhaIdent}", Mid(ValeurChamp, 1, TailleMax))
        postdata = Replace(postdata, "${EtaIdent}", Config.DP_EtaIdent)
        Dim qualité As String = CurrentBenéficiaire.G104C14
        While qualité.Length < 2
            qualité = "0" & qualité
        End While
        If CurrentBenéficiaire.G104C9 <> "" Then
            postdata = Replace(postdata, "${PatNDP}", CurrentBenéficiaire.G104C1 & "|" & CurrentBenéficiaire.G104C3 & "|" & Mid(CurrentBenéficiaire.G104C12, 1, 8) & "|" & _
                              CurrentBenéficiaire.G104C13 & "|" & CurrentBenéficiaire.G101C2 & "|" & _
                              PatNDP(CurrentBenéficiaire.G101C8, CurrentBenéficiaire.G101C9, CurrentBenéficiaire.G104C9, CurrentBenéficiaire.G104C10, qualité))
        Else
            postdata = Replace(postdata, "${PatNDP}", CurrentBenéficiaire.G104C1 & "|" & CurrentBenéficiaire.G104C3 & "|" & Mid(CurrentBenéficiaire.G104C12, 1, 8) & "|" & _
                              CurrentBenéficiaire.G104C13 & "|" & CurrentBenéficiaire.G101C2 & "|" & _
                              PatNDP(CurrentBenéficiaire.G101C8, CurrentBenéficiaire.G101C9, CurrentBenéficiaire.G101C8, CurrentBenéficiaire.G101C9, qualité))
        End If
        If CurrentBenéficiaire.G104C9 <> "" Then
            postdata = Replace(postdata, "${PatINSC}", FormerINSC(ShaINSC(former_graine(CurrentBenéficiaire.G104C3, Mid(CurrentBenéficiaire.G104C12, 3, 6), CurrentBenéficiaire.G104C9))))
        Else
            postdata = Replace(postdata, "${PatINSC}", FormerINSC(ShaINSC(former_graine(CurrentBenéficiaire.G104C3, Mid(CurrentBenéficiaire.G104C12, 3, 6), CurrentBenéficiaire.G101C8))))
        End If
        postdata = Replace(postdata, "${ConTyp}", ConTyp)

        Dim byteArray As Byte() = Encoding.UTF8.GetBytes(postdata)
        My.Computer.FileSystem.WriteAllBytes(Config.LocalNetwork_ServerName & "\DPclients\" & X_DP_ReqId & ".xml", byteArray, False)

        '________________________________________________________________________________________________________________________
        '________________________________________________________________________________________________________________________
        '________________________________________________________________________________________________________________________

        Dim response_file As String = Dir(Config.LocalNetwork_ServerName & "\DPclients\" & X_DP_ReqId & "_*")
        Dim tentative = 0
        While response_file = "" And tentative < 100
            System.Threading.Thread.Sleep(100)
            response_file = Dir(Config.LocalNetwork_ServerName & "\DPclients\" & X_DP_ReqId & "_*")
            tentative = tentative + 1
        End While
        If tentative = 200 Then
            COMPTOIR_MAIN.DP_affichage_statut("Pas de connexion DP")
            Exit Sub
        End If
        response_file = Config.LocalNetwork_ServerName & "\DPclients\" & response_file
        '________________________________________________________________________________________________________________________
        '________________________________________________________________________________________________________________________
        '________________________________________________________________________________________________________________________


        Select Case Mid(response_file, InStrRev(response_file, "_"))

            Case "_ok"
                statut_retour = "OK"
                Select Case ConTyp
                    Case "CONSULTATION_TOUT", "CONSULTATION"
                        COMPTOIR_MAIN.DP_affichage_statut("DP existant")
                    Case "REFUS_CONSULTATION"
                        COMPTOIR_MAIN.DP_affichage_statut("DP en alimentation")
                End Select

                Dim histo_dp As New XmlDocument
                histo_dp.Load(Config.LocalNetwork_ServerName & "\DPclients\" & X_DP_ReqId & "_ok")
                Dim XMLelementliste As XmlNodeList
                XMLelementliste = histo_dp.GetElementsByTagName("acknowledgementDetail")
                If XMLelementliste.Count > 0 Then
                    statut_retour = XMLelementliste.Item(0).Item("code").GetAttribute("code")

                    Select Case XMLelementliste.Item(0).Item("code").GetAttribute("code")

                        Case "DP_REFUSE"
                            RefNbr = Val(Mid(XMLelementliste.Item(0).Item("text").InnerText, InStr(XMLelementliste.Item(0).Item("text").InnerText, ":") + 1, InStr(XMLelementliste.Item(0).Item("text").InnerText, ",") - InStr(XMLelementliste.Item(0).Item("text").InnerText, ":")))
                            RefDate = Convert.ToDateTime(Mid(XMLelementliste.Item(0).Item("text").InnerText, InStrRev(XMLelementliste.Item(0).Item("text").InnerText, ":") + 2, 10))
                            Write_Trace_Fonc("Accès au DP non effectué", Now.ToShortDateString, "DP refusé", Identifiant_patient_function)
                            COMPTOIR_MAIN.DP_affichage_statut("DP refusé")
                        Case "DP_SUPPRIME"
                            SupprDate = Convert.ToDateTime(Mid(XMLelementliste.Item(0).Item("text").InnerText, InStrRev(XMLelementliste.Item(0).Item("text").InnerText, ":") + 2, 10))
                            Write_Trace_Fonc("Accès au DP non effectué", Now.ToShortDateString, "DP supprimé", Identifiant_patient_function)
                            COMPTOIR_MAIN.DP_affichage_statut("DP supprimé")
                        Case "IDENTIFIANT_INCONNU"
                            Write_Trace_Fonc("Accès au DP non effectué", Now.ToShortDateString, "DP inexistant", Identifiant_patient_function)
                            COMPTOIR_MAIN.DP_affichage_statut("DP inexistant")
                        Case Else
                            Write_Trace_Fonc("Accès au DP non effectué", Now.ToShortDateString, "Problème technique", Identifiant_patient_function)
                            COMPTOIR_MAIN.DP_affichage_statut("Erreur technique")
                            MyMsg_Box.Presentation("Officine", "Connexion au DP échouée, contactez support technique.", False, "", False, "", True, "OK")
                            MyMsg_Box.ShowDialog()
                    End Select
                End If
                ''''''''''''''''''''''
                ''''''''''''''''''''''''
                Try


                    Dim clinicalDocuments = histo_dp.GetElementsByTagName("clinicalDocument")

                    'Dim r As Integer=0
                    Dim r As Integer = Histo_DP_DataGridView.RowCount
                    Dim rr As Integer = Edition_DP_DataGridView.RowCount

                    For i = 0 To clinicalDocuments.Count - 1

                        Dim entries = clinicalDocuments(i).Item("component").Item("structuredBody").Item("component").Item("section").ChildNodes

                        For s = 0 To entries.Count - 1
                            If ConTyp <> "EDITION" Then
                                Try

                                    Histo_DP_DataGridView.Rows.Add()
                                    '''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''
                                    'Histo_DP_DataGridView.Item(DisDate_Histo_DP.Index, r).Value = clinicalDocuments(i)("effectiveTime").GetAttribute("value")
                                    Dim adate As Date
                                    DateTime.SpecifyKind(adate, DateTimeKind.Utc)
                                    DateTime.TryParseExact(clinicalDocuments(i)("effectiveTime").GetAttribute("value"), "yyyyMMddhhmmss", Nothing, Globalization.DateTimeStyles.None, adate)
                                    Histo_DP_DataGridView.Item(DisDate_Histo_DP.Index, r).Value = adate.ToLocalTime

                                    '''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''
                                    Histo_DP_DataGridView.Item(EtaTyp_Histo_DP.Index, r).Value = clinicalDocuments(i).Item("author").Item("assignedAuthor").Item("representedOrganization").Item("typeId").GetAttribute("extension")
                                    Select Case UCase(Histo_DP_DataGridView.Item(EtaTyp_Histo_DP.Index, r).Value)
                                        Case "OFFICINE"
                                            Histo_DP_DataGridView.Rows.Item(r).DefaultCellStyle.BackColor = Color.LightGreen
                                        Case "PUI"
                                            Histo_DP_DataGridView.Rows.Item(r).DefaultCellStyle.BackColor = Color.LightBlue
                                        Case "DISTRIBUTEUR"
                                            Histo_DP_DataGridView.Rows.Item(r).DefaultCellStyle.BackColor = Color.LightYellow
                                    End Select
                                    Histo_DP_DataGridView.Item(PrdPoso_Histo_DP.Index, r).Value = entries(s).Item("substanceAdministration").Item("text").InnerText
                                    Histo_DP_DataGridView.Item(QteC_Histo_DP.Index, r).Value = entries(s).Item("substanceAdministration").Item("doseQuantity").GetAttribute("value")
                                    If entries(s).Item("substanceAdministration").Item("doseQuantity").ChildNodes.Count > 0 Then
                                        Histo_DP_DataGridView.Item(QteU_Histo_DP.Index, r).Value = entries(s).Item("substanceAdministration").Item("doseQuantity").Item("translation").GetAttribute("value")
                                    End If

                                    Dim manufacturedProduct_childnodes = entries(s).Item("substanceAdministration").Item("consumable").Item("manufacturedProduct").ChildNodes

                                    For c = 0 To manufacturedProduct_childnodes.Count - 1
                                        If manufacturedProduct_childnodes(c).Name = "id" Then
                                            Dim root, extension As String
                                            root = ""
                                            extension = ""
                                            For attrb_indx = 0 To manufacturedProduct_childnodes(c).Attributes.Count - 1
                                                If manufacturedProduct_childnodes(c).Attributes.ItemOf(attrb_indx).Name = "extension" Then
                                                    extension = manufacturedProduct_childnodes(c).Attributes.ItemOf(attrb_indx).Value
                                                ElseIf manufacturedProduct_childnodes(c).Attributes.ItemOf(attrb_indx).Name = "root" Then
                                                    root = manufacturedProduct_childnodes(c).Attributes.ItemOf(attrb_indx).Value
                                                End If
                                            Next
                                            Select Case root
                                                Case "2.16.840.1.113883.2.8.1.11"
                                                    Histo_DP_DataGridView.Item(CIP_Histo_DP.Index, r).Value = extension
                                                Case "2.16.840.1.113883.2.8.1.12"
                                                    Histo_DP_DataGridView.Item(UCD_Histo_DP.Index, r).Value = extension
                                                Case "2.16.840.1.113883.2.8.1.13"
                                                    Histo_DP_DataGridView.Item(CIS_Histo_DP.Index, r).Value = extension
                                                Case "2.16.840.1.113883.2.8.1.14"
                                                    Histo_DP_DataGridView.Item(DC_Histo_DP.Index, r).Value = extension
                                                Case "2.16.840.1.113883.2.8.1.15"
                                                    Histo_DP_DataGridView.Item(ATC_Histo_DP.Index, r).Value = extension
                                            End Select
                                        ElseIf manufacturedProduct_childnodes(c).Name = "manufacturedMaterial" And Histo_DP_DataGridView.Item(DC_Histo_DP.Index, r).Value Is Nothing Then
                                            Histo_DP_DataGridView.Item(DC_Histo_DP.Index, r).Value = manufacturedProduct_childnodes(c).ChildNodes.Item(0).InnerText
                                        End If
                                    Next
                                    Histo_DP_DataGridView.Item(PrdRect_Histo_DP.Index, r).Value = clinicalDocuments(i).Item("component").Item("structuredBody").Item("component").Item("section").Item("entry").Item("substanceAdministration").Item("entryRelationship").Item("observation").Item("text").InnerText

                                    Histo_DP_DataGridView.Item(Origine_Histo_DP.Index, r).Value = "DP"

                                    If Val(Histo_DP_DataGridView.Item(CIP_Histo_DP.Index, r).Value) = 0 Then
                                        Histo_DP_DataGridView.Rows.RemoveAt(r)
                                        Me.Text = "DP « incomplet »"
                                        COMPTOIR_MAIN.DP_affichage_statut("DP incomplet")
                                        r = r - 1
                                    End If
                                    r = r + 1


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

                                    COMPTOIR_MAIN.DP_affichage_statut("Erreur technique")
                                End Try

                            ElseIf ConTyp = "EDITION" Then
                                Try

                                    Edition_DP_DataGridView.Rows.Add()
                                    '''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''
                                    'Edition_DP_DataGridView.Item(DisDate_Histo_DP.Index, rr).Value = clinicalDocuments(i)("effectiveTime").GetAttribute("value")
                                    Dim adate As Date
                                    DateTime.SpecifyKind(adate, DateTimeKind.Utc)
                                    DateTime.TryParseExact(clinicalDocuments(i)("effectiveTime").GetAttribute("value"), "yyyyMMddhhmmss", Nothing, Globalization.DateTimeStyles.None, adate)
                                    Edition_DP_DataGridView.Item(DataGridViewTextBoxColumn8.Index, rr).Value = adate.ToLocalTime

                                    '''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''
                                    Edition_DP_DataGridView.Item(EtaTyp_Histo_DP.Index, rr).Value = clinicalDocuments(i).Item("author").Item("assignedAuthor").Item("representedOrganization").Item("typeId").GetAttribute("extension")
                                    Select Case UCase(Edition_DP_DataGridView.Item(EtaTyp_Histo_DP.Index, rr).Value)
                                        Case "OFFICINE"
                                            Edition_DP_DataGridView.Rows.Item(rr).DefaultCellStyle.BackColor = Color.LightGreen
                                        Case "PUI"
                                            Edition_DP_DataGridView.Rows.Item(rr).DefaultCellStyle.BackColor = Color.LightBlue
                                        Case "DISTRIBUTEUR"
                                            Edition_DP_DataGridView.Rows.Item(rr).DefaultCellStyle.BackColor = Color.LightYellow
                                    End Select
                                    Edition_DP_DataGridView.Item(PrdPoso_Histo_DP.Index, rr).Value = entries(s).Item("substanceAdministration").Item("text").InnerText
                                    Edition_DP_DataGridView.Item(QteC_Histo_DP.Index, rr).Value = entries(s).Item("substanceAdministration").Item("doseQuantity").GetAttribute("value")
                                    If entries(s).Item("substanceAdministration").Item("doseQuantity").ChildNodes.Count > 0 Then
                                        Edition_DP_DataGridView.Item(QteU_Histo_DP.Index, rr).Value = entries(s).Item("substanceAdministration").Item("doseQuantity").Item("translation").GetAttribute("value")
                                    End If

                                    Dim manufacturedProduct_childnodes = entries(s).Item("substanceAdministration").Item("consumable").Item("manufacturedProduct").ChildNodes

                                    For c = 0 To manufacturedProduct_childnodes.Count - 1
                                        If manufacturedProduct_childnodes(c).Name = "id" Then
                                            Dim root, extension As String
                                            root = ""
                                            extension = ""
                                            For attrb_indx = 0 To manufacturedProduct_childnodes(c).Attributes.Count - 1
                                                If manufacturedProduct_childnodes(c).Attributes.ItemOf(attrb_indx).Name = "extension" Then
                                                    extension = manufacturedProduct_childnodes(c).Attributes.ItemOf(attrb_indx).Value
                                                ElseIf manufacturedProduct_childnodes(c).Attributes.ItemOf(attrb_indx).Name = "root" Then
                                                    root = manufacturedProduct_childnodes(c).Attributes.ItemOf(attrb_indx).Value
                                                End If
                                            Next
                                            Select Case root
                                                Case "2.16.840.1.113883.2.8.1.11"
                                                    Edition_DP_DataGridView.Item(CIP_Histo_DP.Index, rr).Value = extension
                                                Case "2.16.840.1.113883.2.8.1.12"
                                                    Edition_DP_DataGridView.Item(UCD_Histo_DP.Index, rr).Value = extension
                                                Case "2.16.840.1.113883.2.8.1.13"
                                                    Edition_DP_DataGridView.Item(CIS_Histo_DP.Index, rr).Value = extension
                                                Case "2.16.840.1.113883.2.8.1.14"
                                                    Edition_DP_DataGridView.Item(DC_Histo_DP.Index, rr).Value = extension
                                                Case "2.16.840.1.113883.2.8.1.15"
                                                    Edition_DP_DataGridView.Item(ATC_Histo_DP.Index, rr).Value = extension
                                            End Select
                                        ElseIf manufacturedProduct_childnodes(c).Name = "manufacturedMaterial" And Edition_DP_DataGridView.Item(DC_Histo_DP.Index, rr).Value Is Nothing Then
                                            Edition_DP_DataGridView.Item(DC_Histo_DP.Index, rr).Value = manufacturedProduct_childnodes(c).ChildNodes.Item(0).InnerText
                                        End If
                                    Next
                                    Edition_DP_DataGridView.Item(PrdRect_Histo_DP.Index, rr).Value = clinicalDocuments(i).Item("component").Item("structuredBody").Item("component").Item("section").Item("entry").Item("substanceAdministration").Item("entryRelationship").Item("observation").Item("text").InnerText
                                    Edition_DP_DataGridView.Item(Origine_Histo_DP.Index, rr).Value = "DP"

                                    If Val(Edition_DP_DataGridView.Item(CIP_Histo_DP.Index, rr).Value) = 0 Then
                                        Edition_DP_DataGridView.Rows.RemoveAt(rr)
                                        Me.Text = "DP « incomplet »"
                                        COMPTOIR_MAIN.DP_affichage_statut("DP incomplet")
                                        rr = rr - 1
                                    End If
                                    rr = rr + 1


                                Catch ex_entry As Exception
                                    MyMsg_Box.Presentation("Officine", ex_entry.ToString, False, "", False, "", True, "OK")
                                    MyMsg_Box.ShowDialog()
                                    COMPTOIR_MAIN.DP_affichage_statut("Erreur technique")
                                End Try
                            End If

                        Next

                    Next
                    Histo_DP_DataGridView.Sort(DisDate_Histo_DP, ComponentModel.ListSortDirection.Ascending)
                    Edition_DP_DataGridView.Sort(DataGridViewTextBoxColumn8, ComponentModel.ListSortDirection.Ascending)
                Catch ex As Exception

                    DP_ConTyp = "SANS_CONSULTATION"
                    MyMsg_Box.Presentation("Officine", "ERREUR DE CONSULTATION DU DP:" + Chr(10) + ex.ToString, False, "", False, "", True, "OK")
                    MyMsg_Box.ShowDialog()
                End Try

                Write_Trace_Tech(X_DP_ReqId, "REP_" & ConTyp, "OK")
                If DP_ConTyp <> "REFUS_CONSULTATION" Then
                    Write_Trace_Fonc("Accès au DP effectué", "", "Historique DP utilisé pour la dispensation", Identifiant_patient_function)
                Else
                    Write_Trace_Fonc("Accès au DP effectué", "", "Accès à l’historique refusé par le patient", Identifiant_patient_function)
                End If



            Case "_error"
                COMPTOIR_MAIN.DP_affichage_statut("Erreur technique")

                Dim xml_retour As New XmlDocument
                xml_retour.Load(Config.LocalNetwork_ServerName & "\DPclients\" & X_DP_ReqId & "_error")
                Dim XMLelementliste As XmlNodeList
                XMLelementliste = xml_retour.GetElementsByTagName("acknowledgementDetail")
                If XMLelementliste.Count > 0 Then
                    statut_retour = XMLelementliste.Item(0).Item("code").GetAttribute("code")

                    Select Case XMLelementliste.Item(0).Item("code").GetAttribute("code")

                        Case "DP_REFUSE"
                            RefNbr = Val(Mid(XMLelementliste.Item(0).Item("text").InnerText, InStr(XMLelementliste.Item(0).Item("text").InnerText, ":") + 1, InStr(XMLelementliste.Item(0).Item("text").InnerText, ",") - InStr(XMLelementliste.Item(0).Item("text").InnerText, ":")))
                            RefDate = Convert.ToDateTime(Mid(XMLelementliste.Item(0).Item("text").InnerText, InStrRev(XMLelementliste.Item(0).Item("text").InnerText, ":") + 2, 10))
                            Write_Trace_Fonc("Accès au DP non effectué", Now.ToShortDateString, "DP refusé", Identifiant_patient_function)
                            COMPTOIR_MAIN.DP_affichage_statut("DP refusé")
                        Case "DP_SUPPRIME"
                            SupprDate = Convert.ToDateTime(Mid(XMLelementliste.Item(0).Item("text").InnerText, InStrRev(XMLelementliste.Item(0).Item("text").InnerText, ":") + 2, 10))
                            Write_Trace_Fonc("Accès au DP non effectué", Now.ToShortDateString, "DP supprimé", Identifiant_patient_function)
                            COMPTOIR_MAIN.DP_affichage_statut("DP supprimé")
                        Case "IDENTIFIANT_INCONNU"
                            Write_Trace_Fonc("Accès au DP non effectué", Now.ToShortDateString, "DP inexistant", Identifiant_patient_function)
                            COMPTOIR_MAIN.DP_affichage_statut("DP inexistant")
                        Case Else
                            Write_Trace_Fonc("Accès au DP non effectué", Now.ToShortDateString, "Problème technique", Identifiant_patient_function)
                            COMPTOIR_MAIN.DP_affichage_statut("Erreur technique")
                            MyMsg_Box.Presentation("Officine", "Connexion au DP échouée, contactez support technique.", False, "", False, "", True, "OK")
                            MyMsg_Box.ShowDialog()
                    End Select
                End If

                Write_Trace_Tech(X_DP_ReqId, "REP_" & ConTyp, XMLelementliste.Item(0).Item("code").GetAttribute("code") & "|" & XMLelementliste.Item(0).Item("text").InnerText)
            Case "_ko"
                Write_Trace_Fonc("Accès au DP non effectué", Now.ToShortDateString, "Pas de connexion DP", Identifiant_patient_function)
                statut_retour = My.Computer.FileSystem.ReadAllText(response_file)
                COMPTOIR_MAIN.DP_affichage_statut("Pas de connexion DP")
                ''_________________________________________________________________________________
                If ConTyp = "EDITION" Then
                    MyMsg_Box.Presentation("Officine", "L’opération est pour l’instant impossible : il n’y a plus de connexion avec le DP.", False, "", False, "", True, "OK")
                    MyMsg_Box.ShowDialog()
                ElseIf Config.DP_Consulatation_reconnect = False Then
                    Config.DP_Consulatation_reconnect = True
                    MyMsg_Box.Presentation("Officine", "Connexion au DP échouée, voulez-vous tenter à nouveau?" + Chr(10) + "(sinon continuer sans connexion au DP)", True, "OUI", True, "NON", False, "")
                    If MyMsg_Box.ShowDialog() = MsgBoxResult.Yes Then
                        GoTo debut
                    End If
                Else
                    MyMsg_Box.Presentation("Officine", "Connexion au DP échouée, contactez support technique.", False, "", False, "", True, "OK")
                    MyMsg_Box.ShowDialog()
                End If
                Write_Trace_Tech(X_DP_ReqId, "REP_" & ConTyp, My.Computer.FileSystem.ReadAllText(Config.LocalNetwork_ServerName & "\DPclients\" & X_DP_ReqId & "_ko"))
        End Select



        Dim row_ = Me.DP_ReqTableAdapter.GetDataBy_ReqId(X_DP_ReqId).Item(0)
        Me.DP_ReqTableAdapter.Update_byReqID(row_.Sequence_Number, statut_retour, row_.nbr_trans, row_.next_trans_time, Identifiant_patient_function, "CONSULTATION", X_DP_ReqId)



    End Sub



#End Region

#Region "Suppression"
    Public Sub Suppression()
        Bandeau_info_bas_show("Suppression du DP...")

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

        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 & "/suppression")

            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_ReqId)

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

            Dim postdata As String = System.IO.File.ReadAllText(Config.LocalNetwork_ServerName & "\DP\XML\model\DP_Suppression.xml")

            postdata = Replace(postdata, "${ReqId}", X_DP_ReqId)

            postdata = Replace(postdata, "${SupDate}", Format(DateTime.UtcNow, "yyyyMMddHHmmss"))

            postdata = Replace(postdata, "${ReqProd}", Config.DP_ReqProd)

            postdata = Replace(postdata, "${AttVers}", "DP-ACRE-130705")

            Dim qualité As String = CurrentBenéficiaire.G104C14
            While qualité.Length < 2
                qualité = "0" & qualité
            End While
            If CurrentBenéficiaire.G104C9 <> "" Then
                postdata = Replace(postdata, "${PatNDP}", CurrentBenéficiaire.G104C1 & "|" & CurrentBenéficiaire.G104C3 & "|" & Mid(CurrentBenéficiaire.G104C12, 1, 8) & "|" & _
                                  CurrentBenéficiaire.G104C13 & "|" & CurrentBenéficiaire.G101C2 & "|" & _
                                  PatNDP(CurrentBenéficiaire.G101C8, CurrentBenéficiaire.G101C9, CurrentBenéficiaire.G104C9, CurrentBenéficiaire.G104C10, qualité))
            Else
                postdata = Replace(postdata, "${PatNDP}", CurrentBenéficiaire.G104C1 & "|" & CurrentBenéficiaire.G104C3 & "|" & Mid(CurrentBenéficiaire.G104C12, 1, 8) & "|" & _
                                  CurrentBenéficiaire.G104C13 & "|" & CurrentBenéficiaire.G101C2 & "|" & _
                                  PatNDP(CurrentBenéficiaire.G101C8, CurrentBenéficiaire.G101C9, CurrentBenéficiaire.G101C8, CurrentBenéficiaire.G101C9, qualité))
            End If

            'postdata = Replace(postdata, "${PatINSC}", FormerINSC(ShaINSC(former_graine("PAUL", "600111", "1600134079089"))))
            If CurrentBenéficiaire.G104C9 <> "" Then
                postdata = Replace(postdata, "${PatINSC}", FormerINSC(ShaINSC(former_graine(CurrentBenéficiaire.G104C3, Mid(CurrentBenéficiaire.G104C12, 3, 6), CurrentBenéficiaire.G104C9))))
            Else
                postdata = Replace(postdata, "${PatINSC}", FormerINSC(ShaINSC(former_graine(CurrentBenéficiaire.G104C3, Mid(CurrentBenéficiaire.G104C12, 3, 6), CurrentBenéficiaire.G101C8))))
            End If

            'postdata = Replace(postdata, "${PatNDP->nom(champ1)}", "MARTINQUATREVINGTNEUF")
            'postdata = Replace(postdata, "${PatNDP->prenom(champ2)}", "PAUL")
            postdata = Replace(postdata, "${PatNDP->nom(champ1)}", CurrentBenéficiaire.G104C1)
            postdata = Replace(postdata, "${PatNDP->prenom(champ2)}", CurrentBenéficiaire.G104C3)

            If CurrentBenéficiaire.G104C9 <> "" Then
                If Mid(CurrentBenéficiaire.G104C9, 1, 1) = "1" Then
                    postdata = Replace(postdata, "${PatSexe}", "M")
                ElseIf Mid(CurrentBenéficiaire.G104C9, 1, 1) = "2" Then
                    postdata = Replace(postdata, "${PatSexe}", "F")
                Else
                    postdata = Replace(postdata, "${PatSexe}", "U")
                End If
            Else
                If Mid(CurrentBenéficiaire.G101C8, 1, 1) = "1" Then
                    postdata = Replace(postdata, "${PatSexe}", "M")
                ElseIf Mid(CurrentBenéficiaire.G101C8, 1, 1) = "2" Then
                    postdata = Replace(postdata, "${PatSexe}", "F")
                Else
                    postdata = Replace(postdata, "${PatSexe}", "U")
                End If
            End If

            'postdata = Replace(postdata, "${PhaIdent}", "99900008626")
            ValeurChamp = "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
            TailleMax = 30
            SGD_LireChamp(NumeroSessionCPS, 1, 1, 3, ValeurChamp, TailleMax)
            postdata = Replace(postdata, "${PhaIdent}", Mid(ValeurChamp, 1, TailleMax))

            postdata = Replace(postdata, "${EtaIdent}", Config.DP_EtaIdent)

            My.Computer.FileSystem.WriteAllText(Config.LocalNetwork_ServerName & "\DP\XML\log\" & X_DP_ReqId & ".xml", postdata, False)



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

            Dim dataStream As Stream = DP_objRequest.GetRequestStream

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

            dataStream.Close()


            Write_Trace_Tech(X_DP_ReqId, "SUPPRESSION", Identifiant_patient_function)
            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
            DP_Connect.HEARTBEAT_variables.calcul_moyenne(DP_Connect.HEARTBEAT_variables.MetNbSu, DP_Connect.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\XML\log\Réponse\REP_SUPPRESSION_" & Format(Now, "yyyyMMddHHmmss") & "_" & X_DP_ReqId & ".xml", StreamReader.ReadToEnd.ToString, False)

            Write_Trace_Fonc("Suppression du DP effectuée", "", "", Identifiant_patient_function)
            SupprDate = Now
            COMPTOIR_MAIN.DP_affichage_statut("DP supprimé")

            Write_Trace_Tech(X_DP_ReqId, "SUPPRESSION", "OK")
            Bandeau_info_bas_hide() 'Bandeau_info_bas_show_thread)
            MyMsg_Box.Presentation("Officine", "DP supprimé pour ce patient." + Chr(10) + "Une attestation de suppression va être imprimée." + Chr(10) + "Elle doit être remise au patient.", False, "", False, "", True, "OK")
            MyMsg_Box.ShowDialog()
            imprim_Attestation_Suppression()
            statut_retour = "OK"

            Next_Sequence_Number(objResponse)
            Missing_Sequence_Number(objResponse, X_DP_ReqId)

            Me.Visible = False

        Catch ex As System.Net.WebException
            Bandeau_info_bas_hide() 'Bandeau_info_bas_show_thread)
            Write_Trace_Tech(X_DP_ReqId, "SUPPRESSION_ECHEC", CurrentBenéficiaire.G104C1 & " " & CurrentBenéficiaire.G104C3 & " " & ex.Message.ToString)
            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.Count > 0 Then
                    Write_Trace_Tech(X_DP_ReqId, "SUPPRESSION", XMLelementliste.Item(0).Item("code").GetAttribute("code") & "|" & XMLelementliste.Item(0).Item("text").InnerText)
                    statut_retour = XMLelementliste.Item(0).Item("code").GetAttribute("code")
                    Select Case XMLelementliste.Item(0).Item("code").GetAttribute("code")
                        Case "DP_SUPPRIME"
                            Write_Trace_Fonc("Échec de suppression du DP", "", "DP déjà supprimé", Identifiant_patient_function)
                            MyMsg_Box.Presentation("Officine", "Échec de suppression du DP: DP déjà supprimé", False, "", False, "", True, "OK")
                            MyMsg_Box.ShowDialog()
                        Case "DP_REFUSE"
                            Write_Trace_Fonc("Échec de suppression du DP", "", "Ce patient a refusé la création d’un DP", Identifiant_patient_function)
                            MyMsg_Box.Presentation("Officine", "Suppression inappropriée : ce patient a refusé la création de son DP.", False, "", False, "", True, "OK")
                            MyMsg_Box.ShowDialog()
                        Case "DENTIFIANT_INCONNU"
                            Write_Trace_Fonc("Échec de suppression du DP", "", "Ce patient n’a pas de DP", Identifiant_patient_function)
                            MyMsg_Box.Presentation("Officine", "Suppression inappropriée : ce patient n’a pas de DP.", False, "", False, "", True, "OK")
                            MyMsg_Box.ShowDialog()
                        Case Else
                            Write_Trace_Fonc("Échec de suppression du DP", "", XMLelementliste.Item(0).Item("code").GetAttribute("code") & " " & XMLelementliste.Item(0).Item("text").InnerText, Identifiant_patient_function)
                            MyMsg_Box.Presentation("Officine", "Échec de suppression du DP" + Chr(10) + XMLelementliste.Item(0).Item("code").GetAttribute("code") & " " & XMLelementliste.Item(0).Item("text").InnerText, False, "", False, "", True, "OK")
                            MyMsg_Box.ShowDialog()
                    End Select

                Else
                    Write_Trace_Fonc("Échec de suppression du DP", "", ex.Message, Identifiant_patient_function)
                    Write_Trace_Tech(X_DP_ReqId, "SUPPRESSION", ex.Message)
                    statut_retour = ex.Message
                    MyMsg_Box.Presentation("Officine", "Un problème technique est survenu. Il faudra supprimer le DP de ce patient une autre fois." + Chr(10) + "Vous pouvez contacter votre centre de support. Détail de l’erreur :" + Chr(10) + ex.Message, False, "", False, "", True, "OK")
                    MyMsg_Box.ShowDialog()
                End If
                XMLelementliste = xml_retour.GetElementsByTagName("PRPA_IN201315UV02")
                If XMLelementliste.Count > 0 Then
                    xml_retour.Save(Config.LocalNetwork_ServerName & "\DP\XML\log\Réponse\" & XMLelementliste.Item(0).Item("interactionId").GetAttribute("extension") & "_ECHEC_" & XMLelementliste.Item(0).Item("creationTime").GetAttribute("value") & "_" & X_DP_ReqId & ".xml")

                End If


            Else
                Write_Trace_Fonc("Échec de suppression du DP", "", ex.Message, Identifiant_patient_function)
                Write_Trace_Tech(X_DP_ReqId, "SUPPRESSION", ex.Message)
                statut_retour = ex.Message
                COMPTOIR_MAIN.DP_affichage_statut("Pas de connexion DP")
                MyMsg_Box.Presentation("Officine", "L’opération est pour l’instant impossible : il n’y a plus de connexion avec le DP.", False, "", False, "", True, "OK")
                MyMsg_Box.ShowDialog()
                reset_connection()
            End If
        End Try
        Me.DP_ReqTableAdapter.Insert(X_DP_Sequence_Number.ToString, X_DP_ReqId, statut_retour, 1, Now, Identifiant_patient_function, "SUPPRESSION")

    End Sub
    Public Sub Suppression_client()
        Bandeau_info_bas_show("Suppression du DP...")


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


        Dim postdata As String = System.IO.File.ReadAllText(Config.LocalNetwork_ServerName & "\DP\XML\model\DP_Suppression.xml")

        postdata = Replace(postdata, "${ReqId}", X_DP_ReqId)

        postdata = Replace(postdata, "${SupDate}", Format(DateTime.UtcNow, "yyyyMMddHHmmss"))

        postdata = Replace(postdata, "${ReqProd}", Config.DP_ReqProd)

        postdata = Replace(postdata, "${AttVers}", "DP-ACRE-130705")

        Dim qualité As String = CurrentBenéficiaire.G104C14
        While qualité.Length < 2
            qualité = "0" & qualité
        End While
        If CurrentBenéficiaire.G104C9 <> "" Then
            postdata = Replace(postdata, "${PatNDP}", CurrentBenéficiaire.G104C1 & "|" & CurrentBenéficiaire.G104C3 & "|" & Mid(CurrentBenéficiaire.G104C12, 1, 8) & "|" & _
                              CurrentBenéficiaire.G104C13 & "|" & CurrentBenéficiaire.G101C2 & "|" & _
                              PatNDP(CurrentBenéficiaire.G101C8, CurrentBenéficiaire.G101C9, CurrentBenéficiaire.G104C9, CurrentBenéficiaire.G104C10, qualité))
        Else
            postdata = Replace(postdata, "${PatNDP}", CurrentBenéficiaire.G104C1 & "|" & CurrentBenéficiaire.G104C3 & "|" & Mid(CurrentBenéficiaire.G104C12, 1, 8) & "|" & _
                              CurrentBenéficiaire.G104C13 & "|" & CurrentBenéficiaire.G101C2 & "|" & _
                              PatNDP(CurrentBenéficiaire.G101C8, CurrentBenéficiaire.G101C9, CurrentBenéficiaire.G101C8, CurrentBenéficiaire.G101C9, qualité))
        End If

        'postdata = Replace(postdata, "${PatINSC}", FormerINSC(ShaINSC(former_graine("PAUL", "600111", "1600134079089"))))
        If CurrentBenéficiaire.G104C9 <> "" Then
            postdata = Replace(postdata, "${PatINSC}", FormerINSC(ShaINSC(former_graine(CurrentBenéficiaire.G104C3, Mid(CurrentBenéficiaire.G104C12, 3, 6), CurrentBenéficiaire.G104C9))))
        Else
            postdata = Replace(postdata, "${PatINSC}", FormerINSC(ShaINSC(former_graine(CurrentBenéficiaire.G104C3, Mid(CurrentBenéficiaire.G104C12, 3, 6), CurrentBenéficiaire.G101C8))))
        End If

        'postdata = Replace(postdata, "${PatNDP->nom(champ1)}", "MARTINQUATREVINGTNEUF")
        'postdata = Replace(postdata, "${PatNDP->prenom(champ2)}", "PAUL")
        postdata = Replace(postdata, "${PatNDP->nom(champ1)}", CurrentBenéficiaire.G104C1)
        postdata = Replace(postdata, "${PatNDP->prenom(champ2)}", CurrentBenéficiaire.G104C3)

        'postdata = Replace(postdata, "${PatSexe}", "M")
        If CurrentBenéficiaire.G104C9 <> "" Then
            If Mid(CurrentBenéficiaire.G104C9, 1, 1) = "1" Then
                postdata = Replace(postdata, "${PatSexe}", "M")
            ElseIf Mid(CurrentBenéficiaire.G104C9, 1, 1) = "2" Then
                postdata = Replace(postdata, "${PatSexe}", "F")
            Else
                postdata = Replace(postdata, "${PatSexe}", "U")
            End If
        Else
            If Mid(CurrentBenéficiaire.G101C8, 1, 1) = "1" Then
                postdata = Replace(postdata, "${PatSexe}", "M")
            ElseIf Mid(CurrentBenéficiaire.G101C8, 1, 1) = "2" Then
                postdata = Replace(postdata, "${PatSexe}", "F")
            Else
                postdata = Replace(postdata, "${PatSexe}", "U")
            End If
        End If

        'postdata = Replace(postdata, "${PhaIdent}", "99900008626")
        ValeurChamp = "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
        TailleMax = 30
        SGD_LireChamp(NumeroSessionCPS, 1, 1, 3, ValeurChamp, TailleMax)
        postdata = Replace(postdata, "${PhaIdent}", Mid(ValeurChamp, 1, TailleMax))

        'postdata = Replace(postdata, "${EtaIdent}", "111111190")
        postdata = Replace(postdata, "${EtaIdent}", Config.DP_EtaIdent)

        Dim byteArray As Byte() = Encoding.UTF8.GetBytes(postdata)
        My.Computer.FileSystem.WriteAllBytes(Config.LocalNetwork_ServerName & "\DPclients\" & X_DP_ReqId & ".xml", byteArray, False)
        Write_Trace_Tech(X_DP_ReqId, "SUPPRESSION", Identifiant_patient_function)

        '________________________________________________________________________________________________________________________
        '________________________________________________________________________________________________________________________
        '________________________________________________________________________________________________________________________

        Dim response_file As String = Dir(Config.LocalNetwork_ServerName & "\DPclients\" & X_DP_ReqId & "_*")
        Dim tentative = 0
        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
            MyMsg_Box.Presentation("Officine", "Echec suppression: pas de réponse serveur local", False, "", False, "", True, "OK")
            MyMsg_Box.ShowDialog()
            Exit Sub
        End If
        response_file = Config.LocalNetwork_ServerName & "\DPclients\" & response_file

        '________________________________________________________________________________________________________________________
        '________________________________________________________________________________________________________________________
        '________________________________________________________________________________________________________________________

        Bandeau_info_bas_hide() 'Bandeau_info_bas_show_thread)
        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")
                    Write_Trace_Tech(X_DP_ReqId, "REP_SUPPRESSION", xmlelementliste.Item(0).Item("code").GetAttribute("code") & "|" & xmlelementliste.Item(0).Item("text").InnerText)
                    Select Case xmlelementliste.Item(0).Item("code").GetAttribute("code")
                        Case "DP_SUPPRIME"
                            Write_Trace_Fonc("Échec de suppression du DP", "", "DP déjà supprimé", Identifiant_patient_function)
                            MyMsg_Box.Presentation("Officine", "Échec de suppression du DP: DP déjà supprimé", False, "", False, "", True, "OK")
                            MyMsg_Box.ShowDialog()
                        Case "DP_REFUSE"
                            Write_Trace_Fonc("Échec de suppression du DP", "", "Ce patient a refusé la création d’un DP", Identifiant_patient_function)
                            MyMsg_Box.Presentation("Officine", "Suppression inappropriée : ce patient a refusé la création de son DP.", False, "", False, "", True, "OK")
                            MyMsg_Box.ShowDialog()
                        Case "DENTIFIANT_INCONNU"
                            Write_Trace_Fonc("Échec de suppression du DP", "", "Ce patient n’a pas de DP", Identifiant_patient_function)
                            MyMsg_Box.Presentation("Officine", "Suppression inappropriée : ce patient n’a pas de DP.", False, "", False, "", True, "OK")
                            MyMsg_Box.ShowDialog()
                        Case Else
                            Write_Trace_Fonc("Échec de suppression du DP", "", xmlelementliste.Item(0).Item("code").GetAttribute("code") & " " & xmlelementliste.Item(0).Item("text").InnerText, Identifiant_patient_function)
                            MyMsg_Box.Presentation("Officine", "Échec de suppression du DP" + Chr(10) + xmlelementliste.Item(0).Item("code").GetAttribute("code") & " " & xmlelementliste.Item(0).Item("text").InnerText, False, "", False, "", True, "OK")
                            MyMsg_Box.ShowDialog()
                    End Select
                Else
                    statut_retour = "OK"
                    Write_Trace_Fonc("Suppression du DP effectuée", "", "", Identifiant_patient_function)
                    SupprDate = Now
                    COMPTOIR_MAIN.DP_affichage_statut("DP supprimé")

                    Write_Trace_Tech(X_DP_ReqId, "REP_SUPPRESSION", "OK")
                    MyMsg_Box.Presentation("Officine", "DP supprimé pour ce patient." + Chr(10) + "Une attestation de suppression va être imprimée." + Chr(10) + "Elle doit être remise au patient.", False, "", False, "", True, "OK")
                    MyMsg_Box.ShowDialog()

                    imprim_Attestation_Suppression()
                End If
                Me.Visible = False


            Case "_error"
                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")
                    Write_Trace_Tech(X_DP_ReqId, "REP_SUPPRESSION", xmlelementliste.Item(0).Item("code").GetAttribute("code") & "|" & xmlelementliste.Item(0).Item("text").InnerText)
                    Select Case xmlelementliste.Item(0).Item("code").GetAttribute("code")
                        Case "DP_SUPPRIME"
                            Write_Trace_Fonc("Échec de suppression du DP", "", "DP déjà supprimé", Identifiant_patient_function)
                            MyMsg_Box.Presentation("Officine", "Échec de suppression du DP: DP déjà supprimé", False, "", False, "", True, "OK")
                            MyMsg_Box.ShowDialog()
                        Case "DP_REFUSE"
                            Write_Trace_Fonc("Échec de suppression du DP", "", "Ce patient a refusé la création d’un DP", Identifiant_patient_function)
                            MyMsg_Box.Presentation("Officine", "Suppression inappropriée : ce patient a refusé la création de son DP.", False, "", False, "", True, "OK")
                            MyMsg_Box.ShowDialog()
                        Case "DENTIFIANT_INCONNU"
                            Write_Trace_Fonc("Échec de suppression du DP", "", "Ce patient n’a pas de DP", Identifiant_patient_function)
                            MyMsg_Box.Presentation("Officine", "Suppression inappropriée : ce patient n’a pas de DP.", False, "", False, "", True, "OK")
                            MyMsg_Box.ShowDialog()
                        Case Else
                            Write_Trace_Fonc("Échec de suppression du DP", "", xmlelementliste.Item(0).Item("code").GetAttribute("code") & " " & xmlelementliste.Item(0).Item("text").InnerText, Identifiant_patient_function)
                            MyMsg_Box.Presentation("Officine", "Échec de suppression du DP" + Chr(10) + xmlelementliste.Item(0).Item("code").GetAttribute("code") & " " & xmlelementliste.Item(0).Item("text").InnerText, False, "", False, "", True, "OK")
                            MyMsg_Box.ShowDialog()
                    End Select
                Else
                    statut_retour = My.Computer.FileSystem.ReadAllText(response_file)
                    Write_Trace_Fonc("Échec de suppression du DP", "", My.Computer.FileSystem.ReadAllText(response_file), Identifiant_patient_function)
                    Write_Trace_Tech(X_DP_ReqId, "REP_SUPPRESSION", My.Computer.FileSystem.ReadAllText(response_file))
                    MyMsg_Box.Presentation("Officine", "Un problème technique est survenu. Il faudra supprimer le DP de ce patient une autre fois." + Chr(10) + "Vous pouvez contacter votre centre de support. Détail de l’erreur :" + Chr(10) + My.Computer.FileSystem.ReadAllText(response_file), False, "", False, "", True, "OK")
                    MyMsg_Box.ShowDialog()
                End If

            Case "_ko"
                statut_retour = My.Computer.FileSystem.ReadAllText(response_file)
                Write_Trace_Tech(X_DP_ReqId, "REP_SUPPRESSION", My.Computer.FileSystem.ReadAllText(response_file))
                Write_Trace_Fonc("Échec de suppression du DP", "", My.Computer.FileSystem.ReadAllText(response_file), Identifiant_patient_function)
                MyMsg_Box.Presentation("Officine", "L’opération est pour l’instant impossible : il n’y a plus de connexion avec le DP.", False, "", False, "", True, "OK")
                MyMsg_Box.ShowDialog()
                COMPTOIR_MAIN.DP_affichage_statut("Pas de connexion DP")
        End Select

        Dim row_ = Me.DP_ReqTableAdapter.GetDataBy_ReqId(X_DP_ReqId).Item(0)
        Me.DP_ReqTableAdapter.Update_byReqID(row_.Sequence_Number, statut_retour, row_.nbr_trans, row_.next_trans_time, Identifiant_patient_function, "SUPPRESSION", X_DP_ReqId)

    End Sub
#End Region


#Region "Dispensation"
    Private Sub Dispensation_Button_Click(sender As Object, e As EventArgs) Handles Dispensation_Button.Click
        Dim PreTyp_M, PreTyp_O As Boolean
        For r = 0 To (Dispensation_DataGridView.RowCount - 1)
            If UCase(Dispensation_DataGridView.Item(PreTyp_disp.Index, r).Value) = "PRESCRIT" Then
                PreTyp_M = True
            ElseIf UCase(Dispensation_DataGridView.Item(PreTyp_disp.Index, r).Value) = "CONSEIL" Then
                PreTyp_O = True
            Else
                MyMsg_Box.Presentation("Officine", "RENSEIGNEZ TYPE PRESCRIPTION", False, "", False, "", True, "OK")
                MyMsg_Box.ShowDialog()
                Exit Sub
            End If
        Next

        For r = 0 To (Dispensation_DataGridView.RowCount - 1)
            COMPTOIR_MAIN.ActesTableAdapter.Update_DP_Poso_DP_Rect_by_NumActe(Dispensation_DataGridView.Item(PrdPoso_disp.Index, r).Value, Dispensation_DataGridView.Item(PrdRect_disp.Index, r).Value, Dispensation_DataGridView.Item(NumActe_disp.Index, r).Value)
        Next
        If PreTyp_M = True Then
            If Config.DP_is_local_client = True Then
                Dispensation_client("M")
            Else
                Dispensation("M")
            End If
        End If
        If PreTyp_O = True Then
            If Config.DP_is_local_client = True Then
                Dispensation_client("O")
            Else
                Dispensation("O")
            End If
        End If
        Me.Close()
    End Sub
    Public Structure produit
        Dim PrdCIP As String 'Code CIP 7 ou 13
        Dim PrdUCD As String 'Code UCD 
        Dim PrdCIS As String 'Code CIS 
        Dim PrdATC As String 'Code ATC
        Dim PrdDC As String 'Dénomination commune
        Dim PrdLib As String 'Libellé produit
        Dim PrdQteC As Integer 'Quantité de boîtes
        Dim PrdQtéU As Integer 'Quantité d’unités de dispensation
    End Structure
    Public produits() As produit


    Public Sub Dispensation(ByVal PreTyp As String)
        Bandeau_info_bas_show("Alimentation du DP...")
        Dim X_DP_ReqId As String = System.Guid.NewGuid.ToString
        Dim référence_interne As String = "FSV:" & CurrentFactureVitale.num.ToString & "  FVD:" & CurrentFactureVenteDirecte.NumVenteDirecte.ToString
        Dim statut_retour As String


        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



            Dim postdata As String = System.IO.File.ReadAllText(Config.LocalNetwork_ServerName & "\DP\XML\model\DP_Dispensation.txt")

            postdata = Replace(postdata, "${ReqId}", X_DP_ReqId)

            postdata = Replace(postdata, "${DisDate}", Format(DateTime.UtcNow, "yyyyMMddHHmmss"))

            postdata = Replace(postdata, "${ReqProd}", Config.DP_ReqProd)

            postdata = Replace(postdata, "${AttVers}", "DP-ACRE-130705")

            postdata = Replace(postdata, "${ConTyp}", DP_ConTyp) ' DP_struct.ConTyp)


            Dim qualité As String = CurrentBenéficiaire.G104C14
            While qualité.Length < 2
                qualité = "0" & qualité
            End While

            Dim PatNDP_clinicalDocument As String
            If CurrentBenéficiaire.G104C9 <> "" Then
                PatNDP_clinicalDocument = CurrentBenéficiaire.G104C1 & "|" & CurrentBenéficiaire.G104C3 & "|" & Mid(CurrentBenéficiaire.G104C12, 1, 8) & "|" & _
                                  CurrentBenéficiaire.G104C13 & "|" & CurrentBenéficiaire.G101C2 & "|" & _
                                  PatNDP(CurrentBenéficiaire.G101C8, CurrentBenéficiaire.G101C9, CurrentBenéficiaire.G104C9, CurrentBenéficiaire.G104C10, qualité)
            Else
                PatNDP_clinicalDocument = CurrentBenéficiaire.G104C1 & "|" & CurrentBenéficiaire.G104C3 & "|" & Mid(CurrentBenéficiaire.G104C12, 1, 8) & "|" & _
                                  CurrentBenéficiaire.G104C13 & "|" & CurrentBenéficiaire.G101C2 & "|" & _
                                  PatNDP(CurrentBenéficiaire.G101C8, CurrentBenéficiaire.G101C9, CurrentBenéficiaire.G101C8, CurrentBenéficiaire.G101C9, qualité)
            End If

            Dim PatINSC_clinicalDocument As String
            If CurrentBenéficiaire.G104C9 <> "" Then
                PatINSC_clinicalDocument = FormerINSC(ShaINSC(former_graine(CurrentBenéficiaire.G104C3, Mid(CurrentBenéficiaire.G104C12, 3, 6), CurrentBenéficiaire.G104C9)))
            Else
                PatINSC_clinicalDocument = FormerINSC(ShaINSC(former_graine(CurrentBenéficiaire.G104C3, Mid(CurrentBenéficiaire.G104C12, 3, 6), CurrentBenéficiaire.G101C8)))
            End If



            ''''''''''''''''''''''''

            Dim clinicalDocument_strg As String = System.IO.File.ReadAllText(Config.LocalNetwork_ServerName & "\DP\XML\model\DP_Dispensation_clinicalDocument.txt")

            clinicalDocument_strg = Replace(clinicalDocument_strg, "${DisId}", System.Guid.NewGuid.ToString)

            clinicalDocument_strg = Replace(clinicalDocument_strg, "${PatNDP}", PatNDP_clinicalDocument)
            clinicalDocument_strg = Replace(clinicalDocument_strg, "${PatINSC}", PatINSC_clinicalDocument)
            clinicalDocument_strg = Replace(clinicalDocument_strg, "${PatNDP->nom(champ1)}", CurrentBenéficiaire.G104C1)
            clinicalDocument_strg = Replace(clinicalDocument_strg, "${PatNDP->prenom(champ2)}", CurrentBenéficiaire.G104C3)
            If CurrentBenéficiaire.G104C9 <> "" Then
                If Mid(CurrentBenéficiaire.G104C9, 1, 1) = "1" Then
                    clinicalDocument_strg = Replace(clinicalDocument_strg, "${PatSexe}", "M")
                ElseIf Mid(CurrentBenéficiaire.G104C9, 1, 1) = "2" Then
                    clinicalDocument_strg = Replace(clinicalDocument_strg, "${PatSexe}", "F")
                Else
                    clinicalDocument_strg = Replace(clinicalDocument_strg, "${PatSexe}", "U")
                End If
            Else
                If Mid(CurrentBenéficiaire.G101C8, 1, 1) = "1" Then
                    clinicalDocument_strg = Replace(clinicalDocument_strg, "${PatSexe}", "M")
                ElseIf Mid(CurrentBenéficiaire.G101C8, 1, 1) = "2" Then
                    clinicalDocument_strg = Replace(clinicalDocument_strg, "${PatSexe}", "F")
                Else
                    clinicalDocument_strg = Replace(clinicalDocument_strg, "${PatSexe}", "U")
                End If
            End If
            'clinicalDocument_strg = Replace(clinicalDocument_strg, "${PhaIdent}", PhaIdent_DP)
            ValeurChamp = "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
            TailleMax = 30
            SGD_LireChamp(NumeroSessionCPS, 1, 1, 3, ValeurChamp, TailleMax)
            clinicalDocument_strg = Replace(clinicalDocument_strg, "${PhaIdent}", Mid(ValeurChamp, 1, TailleMax))

            clinicalDocument_strg = Replace(clinicalDocument_strg, "${EtaIdent}", Config.DP_EtaIdent)

            If PreTyp = "M" And CurrentBenéficiaire.Prescripteur_CodeSpécialité <> "" Then
                clinicalDocument_strg = Replace(clinicalDocument_strg, "{PreCateg(1)}", CurrentBenéficiaire.Prescripteur_CodeSpécialité)
            Else
                clinicalDocument_strg = Replace(clinicalDocument_strg, "{PreCateg(1)}", "50") 'prescripteur
            End If

            clinicalDocument_strg = Replace(clinicalDocument_strg, "${DisDate(1)}", Format(DateTime.UtcNow, "yyyyMMddHHmmss")) 'date delivrance
            clinicalDocument_strg = Replace(clinicalDocument_strg, "${PreTyp}", PreTyp) 'M pour prescrit, O pour conseil pharmacien



            postdata = postdata & clinicalDocument_strg

            Dim prescription As String = ""
            If PreTyp = "M" Then
                prescription = "PRESCRIT"
            ElseIf PreTyp = "O" Then
                prescription = "CONSEIL"
            End If

            For r = 0 To (Dispensation_DataGridView.RowCount - 1)


                If UCase(Dispensation_DataGridView.Item(PreTyp_disp.Index, r).Value) = prescription Then
                    If Dispensation_DataGridView.Item(Transmettre_Disp.Index, r).Value = True Then
                        Dim clinicalDocument_entry_strg As String = System.IO.File.ReadAllText(Config.LocalNetwork_ServerName & "\DP\XML\model\DP_Dispensation_clinicalDocument_entry.txt")
                        clinicalDocument_entry_strg = Replace(clinicalDocument_entry_strg, "${PrdPoso(1,1)}", Dispensation_DataGridView.Item(PrdPoso_disp.Index, r).Value) 'Posologie Zone de texte libre saisie par le pharmacien ou renseignée par le logiciel pour indiquer la posologie du produit


                        'date peremption produit
                        If Dispensation_DataGridView.Item(peremption_disp.Index, r).Value <> "" Then
                            clinicalDocument_entry_strg = Replace(clinicalDocument_entry_strg, "${PrdPere(1,1)}", Mid(Dispensation_DataGridView.Item(peremption_disp.Index, r).Value, 7, 4) & _
                                                                  Mid(Dispensation_DataGridView.Item(peremption_disp.Index, r).Value, 4, 2) & _
                                                                  Mid(Dispensation_DataGridView.Item(peremption_disp.Index, r).Value, 1, 2))
                        Else
                            clinicalDocument_entry_strg = Replace(clinicalDocument_entry_strg, "${PrdPere(1,1)}", "")
                        End If



                        clinicalDocument_entry_strg = Replace(clinicalDocument_entry_strg, "${PrdQteC(1,1)}", Dispensation_DataGridView.Item(PrdQteC_Disp.Index, r).Value)
                        clinicalDocument_entry_strg = Replace(clinicalDocument_entry_strg, "${PrdQteU(1,1)}", Dispensation_DataGridView.Item(PrdQtéU_Disp.Index, r).Value)

                        clinicalDocument_entry_strg = Replace(clinicalDocument_entry_strg, "${PrdCIP(1,1)}", Dispensation_DataGridView.Item(PrdCIP_disp.Index, r).Value)
                        clinicalDocument_entry_strg = Replace(clinicalDocument_entry_strg, "${PrdUCD(1,1)}", Dispensation_DataGridView.Item(PrdUCD_Disp.Index, r).Value)
                        clinicalDocument_entry_strg = Replace(clinicalDocument_entry_strg, "${PrdCIS(1,1)}", Dispensation_DataGridView.Item(PrdCIS_Disp.Index, r).Value)
                        clinicalDocument_entry_strg = Replace(clinicalDocument_entry_strg, "${PrdDC(1,1)}", Dispensation_DataGridView.Item(PrdDC_Disp.Index, r).Value)
                        clinicalDocument_entry_strg = Replace(clinicalDocument_entry_strg, "${PrdATC(1,1)}", Dispensation_DataGridView.Item(PrdATC_Disp.Index, r).Value)

                        clinicalDocument_entry_strg = Replace(clinicalDocument_entry_strg, "${PrdLib(1,1)}", Dispensation_DataGridView.Item(PrdDC_Disp.Index, r).Value) 'denomination

                        'Numéro de lot du conditionnement produit
                        clinicalDocument_entry_strg = Replace(clinicalDocument_entry_strg, "${PrdLot(1,1)}", Dispensation_DataGridView.Item(lot_disp.Index, r).Value)

                        clinicalDocument_entry_strg = Replace(clinicalDocument_entry_strg, "${PrdRect(1,1)}", Dispensation_DataGridView.Item(PrdRect_disp.Index, r).Value)

                        postdata = postdata & clinicalDocument_entry_strg

                    Else
                        Dim clinicalDocument_entry_strg As String = System.IO.File.ReadAllText(Config.LocalNetwork_ServerName & "\DP\XML\model\DP_Dispensation_clinicalDocument_entry.txt")
                        clinicalDocument_entry_strg = Replace(clinicalDocument_entry_strg, "${PrdPoso(1,1)}", Dispensation_DataGridView.Item(PrdPoso_disp.Index, r).Value) 'Posologie Zone de texte libre saisie par le pharmacien ou renseignée par le logiciel pour indiquer la posologie du produit

                        ''date peremption produit
                        'If Dispensation_DataGridView.Item(peremption_disp.Index, r).Value <> "" Then
                        '    clinicalDocument_entry_strg = Replace(clinicalDocument_entry_strg, "${PrdPere(1,1)}", Mid(Dispensation_DataGridView.Item(peremption_disp.Index, r).Value, 7, 4) & _
                        '                                          Mid(Dispensation_DataGridView.Item(peremption_disp.Index, r).Value, 4, 2) & _
                        '                                          Mid(Dispensation_DataGridView.Item(peremption_disp.Index, r).Value, 1, 2))
                        'Else
                        clinicalDocument_entry_strg = Replace(clinicalDocument_entry_strg, "${PrdPere(1,1)}", "")
                        'End If


                        clinicalDocument_entry_strg = Replace(clinicalDocument_entry_strg, "${PrdQteC(1,1)}", "0") ' Dispensation_DataGridView.Item(PrdQteC_Disp.Index, r).Value)
                        clinicalDocument_entry_strg = Replace(clinicalDocument_entry_strg, "${PrdQteU(1,1)}", "0") ' Dispensation_DataGridView.Item(PrdQtéU_Disp.Index, r).Value)

                        clinicalDocument_entry_strg = Replace(clinicalDocument_entry_strg, "${PrdCIP(1,1)}", "0") 'Dispensation_DataGridView.Item(PrdCIP_disp.Index, r).Value)
                        clinicalDocument_entry_strg = Replace(clinicalDocument_entry_strg, "${PrdUCD(1,1)}", "0") 'Dispensation_DataGridView.Item(PrdUCD_Disp.Index, r).Value)
                        clinicalDocument_entry_strg = Replace(clinicalDocument_entry_strg, "${PrdCIS(1,1)}", "0") 'Dispensation_DataGridView.Item(PrdCIS_Disp.Index, r).Value)
                        clinicalDocument_entry_strg = Replace(clinicalDocument_entry_strg, "${PrdDC(1,1)}", "0") 'Dispensation_DataGridView.Item(PrdDC_Disp.Index, r).Value)
                        clinicalDocument_entry_strg = Replace(clinicalDocument_entry_strg, "${PrdATC(1,1)}", "0") 'Dispensation_DataGridView.Item(PrdATC_Disp.Index, r).Value)

                        'denomination
                        clinicalDocument_entry_strg = Replace(clinicalDocument_entry_strg, "${PrdLib(1,1)}", "0") 'Dispensation_DataGridView.Item(PrdDC_Disp.Index, r).Value)

                        'Numéro de lot du conditionnement produit
                        clinicalDocument_entry_strg = Replace(clinicalDocument_entry_strg, "${PrdLot(1,1)}", "") 'Dispensation_DataGridView.Item(lot_disp.Index, r).Value)

                        clinicalDocument_entry_strg = Replace(clinicalDocument_entry_strg, "${PrdRect(1,1)}", Dispensation_DataGridView.Item(PrdRect_disp.Index, r).Value)

                        postdata = postdata & clinicalDocument_entry_strg
                    End If
                End If
            Next

            ''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''
            postdata = postdata & "</section></component></structuredBody></component></clinicalDocument></subject></controlActProcess></RCMR_IN000002UV02>"

            My.Computer.FileSystem.WriteAllText(Config.LocalNetwork_ServerName & "\DP\XML\log\" & X_DP_ReqId & ".xml", postdata, False)

            '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 xmldoc As New XmlDocument
            xmldoc.Load(Config.LocalNetwork_ServerName & "\DP\XML\log\" & X_DP_ReqId & ".signed")

            Dim postdata_signed As String = xmldoc.OuterXml

            'xmldoc.Load(Config.LocalNetwork_ServerName & "\DP\XML\log\creation DP.xml")
            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)
            Dim dataStream As Stream = DP_objRequest.GetRequestStream

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

            dataStream.Close()



            Write_Trace_Tech(X_DP_ReqId, "ALIMENTATION", Identifiant_patient_function() & "| " & référence_interne)

            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
            DP_Connect.HEARTBEAT_variables.calcul_moyenne(DP_Connect.HEARTBEAT_variables.MetNbAl, DP_Connect.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_function)

            For i = 0 To Dispensation_DataGridView.Rows.Count - 1
                If Dispensation_DataGridView.Item(Transmettre_Disp.Index, i).Value = False Then
                    imprim_Attestation_Refus_Alimentation()
                    Write_Trace_Fonc("Refus d’alimenter des médicaments", référence_interne, "", Identifiant_patient_function)
                    Exit For
                End If
            Next
            Write_Trace_Tech(X_DP_ReqId, "REP_ALIMENTATION", "OK")
            statut_retour = "OK"

            Next_Sequence_Number(objResponse)
            Missing_Sequence_Number(objResponse, X_DP_ReqId)


        Catch ex As System.Net.WebException
            Bandeau_info_bas_hide() 'Bandeau_info_bas_show_thread)
            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")
                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", référence_interne, "Alimentation non effectuée suite à un problème technique", Identifiant_patient_function)
                    MyMsg_Box.Presentation("Officine", "Échec de l’alimentation du DP: Alimentation non effectuée suite à un problème technique", False, "", False, "", True, "OK")
                    MyMsg_Box.ShowDialog()
                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", référence_interne, "Problème technique : l'alimentation est mise en file d’attente", Identifiant_patient_function)
                    MyMsg_Box.Presentation("Officine", "Échec de l’alimentation du DP" + Chr(10) + "Problème technique : l'alimentation est mise en file d’attente", False, "", False, "", True, "OK")
                    MyMsg_Box.ShowDialog()
                End If

            Else
                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", 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_function)
                statut_retour = ex.Message
                MyMsg_Box.Presentation("Officine", "Dispensation placée en file d'attente pour alimentation du DP ultérieure.", False, "", False, "", True, "OK")
                MyMsg_Box.ShowDialog()

                COMPTOIR_MAIN.DP_affichage_statut("Pas de connexion DP")
                reset_connection()
            End If

        End Try
        Me.DP_ReqTableAdapter.Insert(X_DP_Sequence_Number.ToString, X_DP_ReqId, statut_retour, 1, Now, Identifiant_patient_function, "ALIMENTATION")
        Bandeau_info_bas_hide() 'Bandeau_info_bas_show_thread)
    End Sub

    Public Sub Dispensation_client(ByVal PreTyp As String)

        Bandeau_info_bas_show("Alimentation du DP...")

        Dim X_DP_ReqId As String = System.Guid.NewGuid.ToString
        Dim référence_interne As String = "FSV:" & CurrentFactureVitale.num.ToString & "  FVD:" & CurrentFactureVenteDirecte.NumVenteDirecte.ToString
        Dim statut_retour As String = ""

        Dim postdata As String = System.IO.File.ReadAllText(Config.LocalNetwork_ServerName & "\DP\XML\model\DP_Dispensation.txt")

        postdata = Replace(postdata, "${ReqId}", X_DP_ReqId)

        postdata = Replace(postdata, "${DisDate}", Format(DateTime.UtcNow, "yyyyMMddHHmmss"))

        postdata = Replace(postdata, "${ReqProd}", Config.DP_ReqProd)

        postdata = Replace(postdata, "${AttVers}", "DP-ACRE-130705")

        postdata = Replace(postdata, "${ConTyp}", DP_ConTyp) ' DP_struct.ConTyp)


        Dim qualité As String = CurrentBenéficiaire.G104C14
        While qualité.Length < 2
            qualité = "0" & qualité
        End While

        Dim PatNDP_clinicalDocument As String
        If CurrentBenéficiaire.G104C9 <> "" Then
            PatNDP_clinicalDocument = CurrentBenéficiaire.G104C1 & "|" & CurrentBenéficiaire.G104C3 & "|" & Mid(CurrentBenéficiaire.G104C12, 1, 8) & "|" & _
                              CurrentBenéficiaire.G104C13 & "|" & CurrentBenéficiaire.G101C2 & "|" & _
                              PatNDP(CurrentBenéficiaire.G101C8, CurrentBenéficiaire.G101C9, CurrentBenéficiaire.G104C9, CurrentBenéficiaire.G104C10, qualité)
        Else
            PatNDP_clinicalDocument = CurrentBenéficiaire.G104C1 & "|" & CurrentBenéficiaire.G104C3 & "|" & Mid(CurrentBenéficiaire.G104C12, 1, 8) & "|" & _
                              CurrentBenéficiaire.G104C13 & "|" & CurrentBenéficiaire.G101C2 & "|" & _
                              PatNDP(CurrentBenéficiaire.G101C8, CurrentBenéficiaire.G101C9, CurrentBenéficiaire.G101C8, CurrentBenéficiaire.G101C9, qualité)
        End If

        Dim PatINSC_clinicalDocument As String
        If CurrentBenéficiaire.G104C9 <> "" Then
            PatINSC_clinicalDocument = FormerINSC(ShaINSC(former_graine(CurrentBenéficiaire.G104C3, Mid(CurrentBenéficiaire.G104C12, 3, 6), CurrentBenéficiaire.G104C9)))
        Else
            PatINSC_clinicalDocument = FormerINSC(ShaINSC(former_graine(CurrentBenéficiaire.G104C3, Mid(CurrentBenéficiaire.G104C12, 3, 6), CurrentBenéficiaire.G101C8)))
        End If



        ''''''''''''''''''''''''

        Dim clinicalDocument_strg As String = System.IO.File.ReadAllText(Config.LocalNetwork_ServerName & "\DP\XML\model\DP_Dispensation_clinicalDocument.txt")

        clinicalDocument_strg = Replace(clinicalDocument_strg, "${DisId}", System.Guid.NewGuid.ToString)

        clinicalDocument_strg = Replace(clinicalDocument_strg, "${PatNDP}", PatNDP_clinicalDocument)
        clinicalDocument_strg = Replace(clinicalDocument_strg, "${PatINSC}", PatINSC_clinicalDocument)
        clinicalDocument_strg = Replace(clinicalDocument_strg, "${PatNDP->nom(champ1)}", CurrentBenéficiaire.G104C1)
        clinicalDocument_strg = Replace(clinicalDocument_strg, "${PatNDP->prenom(champ2)}", CurrentBenéficiaire.G104C3)
        If CurrentBenéficiaire.G104C9 <> "" Then
            If Mid(CurrentBenéficiaire.G104C9, 1, 1) = "1" Then
                clinicalDocument_strg = Replace(clinicalDocument_strg, "${PatSexe}", "M")
            ElseIf Mid(CurrentBenéficiaire.G104C9, 1, 1) = "2" Then
                clinicalDocument_strg = Replace(clinicalDocument_strg, "${PatSexe}", "F")
            Else
                clinicalDocument_strg = Replace(clinicalDocument_strg, "${PatSexe}", "U")
            End If
        Else
            If Mid(CurrentBenéficiaire.G101C8, 1, 1) = "1" Then
                clinicalDocument_strg = Replace(clinicalDocument_strg, "${PatSexe}", "M")
            ElseIf Mid(CurrentBenéficiaire.G101C8, 1, 1) = "2" Then
                clinicalDocument_strg = Replace(clinicalDocument_strg, "${PatSexe}", "F")
            Else
                clinicalDocument_strg = Replace(clinicalDocument_strg, "${PatSexe}", "U")
            End If
        End If
        'clinicalDocument_strg = Replace(clinicalDocument_strg, "${PhaIdent}", PhaIdent_DP)
        ValeurChamp = "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
        TailleMax = 30
        SGD_LireChamp(NumeroSessionCPS, 1, 1, 3, ValeurChamp, TailleMax)
        clinicalDocument_strg = Replace(clinicalDocument_strg, "${PhaIdent}", Mid(ValeurChamp, 1, TailleMax))
        clinicalDocument_strg = Replace(clinicalDocument_strg, "${EtaIdent}", Config.DP_EtaIdent)

        If PreTyp = "M" And CurrentBenéficiaire.Prescripteur_CodeSpécialité <> "" Then
            clinicalDocument_strg = Replace(clinicalDocument_strg, "{PreCateg(1)}", CurrentBenéficiaire.Prescripteur_CodeSpécialité)
        Else
            clinicalDocument_strg = Replace(clinicalDocument_strg, "{PreCateg(1)}", "50") 'prescripteur
        End If

        clinicalDocument_strg = Replace(clinicalDocument_strg, "${DisDate(1)}", Format(DateTime.UtcNow, "yyyyMMddHHmmss")) 'date delivrance
        clinicalDocument_strg = Replace(clinicalDocument_strg, "${PreTyp}", PreTyp) 'M pour prescrit, O pour conseil pharmacien

        postdata = postdata & clinicalDocument_strg

        Dim prescription As String = ""
        If PreTyp = "M" Then
            prescription = "PRESCRIT"
        ElseIf PreTyp = "O" Then
            prescription = "CONSEIL"
        End If



        For r = 0 To (Dispensation_DataGridView.RowCount - 1)

            If UCase(Dispensation_DataGridView.Item(PreTyp_disp.Index, r).Value) = prescription Then
                If Dispensation_DataGridView.Item(Transmettre_Disp.Index, r).Value = True Then
                    Dim clinicalDocument_entry_strg As String = System.IO.File.ReadAllText(Config.LocalNetwork_ServerName & "\DP\XML\model\DP_Dispensation_clinicalDocument_entry.txt")
                    clinicalDocument_entry_strg = Replace(clinicalDocument_entry_strg, "${PrdPoso(1,1)}", Dispensation_DataGridView.Item(PrdPoso_disp.Index, r).Value) 'Posologie Zone de texte libre saisie par le pharmacien ou renseignée par le logiciel pour indiquer la posologie du produit


                    'date peremption produit
                    If Dispensation_DataGridView.Item(peremption_disp.Index, r).Value <> "" Then
                        clinicalDocument_entry_strg = Replace(clinicalDocument_entry_strg, "${PrdPere(1,1)}", Mid(Dispensation_DataGridView.Item(peremption_disp.Index, r).Value, 7, 4) & _
                                                              Mid(Dispensation_DataGridView.Item(peremption_disp.Index, r).Value, 4, 2) & _
                                                              Mid(Dispensation_DataGridView.Item(peremption_disp.Index, r).Value, 1, 2))
                    Else
                        clinicalDocument_entry_strg = Replace(clinicalDocument_entry_strg, "${PrdPere(1,1)}", "")
                    End If


                    clinicalDocument_entry_strg = Replace(clinicalDocument_entry_strg, "${PrdQteC(1,1)}", Dispensation_DataGridView.Item(PrdQteC_Disp.Index, r).Value)
                    clinicalDocument_entry_strg = Replace(clinicalDocument_entry_strg, "${PrdQteU(1,1)}", Dispensation_DataGridView.Item(PrdQtéU_Disp.Index, r).Value)

                    clinicalDocument_entry_strg = Replace(clinicalDocument_entry_strg, "${PrdCIP(1,1)}", Dispensation_DataGridView.Item(PrdCIP_disp.Index, r).Value)
                    If Val(Dispensation_DataGridView.Item(PrdQtéU_Disp.Index, r).Value) > 0 Then
                        clinicalDocument_entry_strg = Replace(clinicalDocument_entry_strg, "${PrdUCD(1,1)}", Dispensation_DataGridView.Item(PrdUCD_Disp.Index, r).Value)
                    Else
                        clinicalDocument_entry_strg = Replace(clinicalDocument_entry_strg, "${PrdUCD(1,1)}", "")
                    End If

                    clinicalDocument_entry_strg = Replace(clinicalDocument_entry_strg, "${PrdCIS(1,1)}", Dispensation_DataGridView.Item(PrdCIS_Disp.Index, r).Value)
                    clinicalDocument_entry_strg = Replace(clinicalDocument_entry_strg, "${PrdDC(1,1)}", Dispensation_DataGridView.Item(PrdDC_Disp.Index, r).Value)
                    clinicalDocument_entry_strg = Replace(clinicalDocument_entry_strg, "${PrdATC(1,1)}", Dispensation_DataGridView.Item(PrdATC_Disp.Index, r).Value)

                    clinicalDocument_entry_strg = Replace(clinicalDocument_entry_strg, "${PrdLib(1,1)}", Dispensation_DataGridView.Item(PrdDC_Disp.Index, r).Value) 'denomination

                    'Numéro de lot du conditionnement produit
                    clinicalDocument_entry_strg = Replace(clinicalDocument_entry_strg, "${PrdLot(1,1)}", Dispensation_DataGridView.Item(lot_disp.Index, r).Value)

                    clinicalDocument_entry_strg = Replace(clinicalDocument_entry_strg, "${PrdRect(1,1)}", Dispensation_DataGridView.Item(PrdRect_disp.Index, r).Value)

                    postdata = postdata & clinicalDocument_entry_strg

                Else
                    Dim clinicalDocument_entry_strg As String = System.IO.File.ReadAllText(Config.LocalNetwork_ServerName & "\DP\XML\model\DP_Dispensation_clinicalDocument_entry.txt")
                    clinicalDocument_entry_strg = Replace(clinicalDocument_entry_strg, "${PrdPoso(1,1)}", Dispensation_DataGridView.Item(PrdPoso_disp.Index, r).Value) 'Posologie Zone de texte libre saisie par le pharmacien ou renseignée par le logiciel pour indiquer la posologie du produit

                    ''date peremption produit
                    'If Dispensation_DataGridView.Item(peremption_disp.Index, r).Value <> "" Then
                    '    clinicalDocument_entry_strg = Replace(clinicalDocument_entry_strg, "${PrdPere(1,1)}", Mid(Dispensation_DataGridView.Item(peremption_disp.Index, r).Value, 7, 4) & _
                    '                                          Mid(Dispensation_DataGridView.Item(peremption_disp.Index, r).Value, 4, 2) & _
                    '                                          Mid(Dispensation_DataGridView.Item(peremption_disp.Index, r).Value, 1, 2))
                    'Else
                    clinicalDocument_entry_strg = Replace(clinicalDocument_entry_strg, "${PrdPere(1,1)}", "")
                    'End If


                    clinicalDocument_entry_strg = Replace(clinicalDocument_entry_strg, "${PrdQteC(1,1)}", "0") ' Dispensation_DataGridView.Item(PrdQteC_Disp.Index, r).Value)
                    clinicalDocument_entry_strg = Replace(clinicalDocument_entry_strg, "${PrdQteU(1,1)}", "0") ' Dispensation_DataGridView.Item(PrdQtéU_Disp.Index, r).Value)

                    clinicalDocument_entry_strg = Replace(clinicalDocument_entry_strg, "${PrdCIP(1,1)}", "0") 'Dispensation_DataGridView.Item(PrdCIP_disp.Index, r).Value)
                    clinicalDocument_entry_strg = Replace(clinicalDocument_entry_strg, "${PrdUCD(1,1)}", "0") 'Dispensation_DataGridView.Item(PrdUCD_Disp.Index, r).Value)
                    clinicalDocument_entry_strg = Replace(clinicalDocument_entry_strg, "${PrdCIS(1,1)}", "0") 'Dispensation_DataGridView.Item(PrdCIS_Disp.Index, r).Value)
                    clinicalDocument_entry_strg = Replace(clinicalDocument_entry_strg, "${PrdDC(1,1)}", "0") 'Dispensation_DataGridView.Item(PrdDC_Disp.Index, r).Value)
                    clinicalDocument_entry_strg = Replace(clinicalDocument_entry_strg, "${PrdATC(1,1)}", "0") 'Dispensation_DataGridView.Item(PrdATC_Disp.Index, r).Value)

                    'denomination
                    clinicalDocument_entry_strg = Replace(clinicalDocument_entry_strg, "${PrdLib(1,1)}", "0") 'Dispensation_DataGridView.Item(PrdDC_Disp.Index, r).Value)

                    'Numéro de lot du conditionnement produit
                    clinicalDocument_entry_strg = Replace(clinicalDocument_entry_strg, "${PrdLot(1,1)}", "") 'Dispensation_DataGridView.Item(lot_disp.Index, r).Value)

                    clinicalDocument_entry_strg = Replace(clinicalDocument_entry_strg, "${PrdRect(1,1)}", Dispensation_DataGridView.Item(PrdRect_disp.Index, r).Value)

                    postdata = postdata & clinicalDocument_entry_strg
                End If
            End If
        Next

        ''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''
        postdata = postdata & "</section></component></structuredBody></component></clinicalDocument></subject></controlActProcess></RCMR_IN000002UV02>"
        Dim byteArray As Byte() = Encoding.UTF8.GetBytes(postdata)
        My.Computer.FileSystem.WriteAllBytes(Config.LocalNetwork_ServerName & "\DPclients\" & X_DP_ReqId & ".xml", byteArray, False)
        Write_Trace_Tech(X_DP_ReqId, "ALIMENTATION", Identifiant_patient_function() & "| " & référence_interne)
        ''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''
        For i = 0 To Dispensation_DataGridView.Rows.Count - 1
            If Dispensation_DataGridView.Item(Transmettre_Disp.Index, i).Value = False Then
                imprim_Attestation_Refus_Alimentation()
                Write_Trace_Fonc("Refus d’alimenter des médicaments", référence_interne, "", Identifiant_patient_function)
                Exit For
            End If
        Next

        ''________________________________________________________________________________________________________________________
        ''________________________________________________________________________________________________________________________
        ''________________________________________________________________________________________________________________________
        '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
        '    COMPTOIR_MAIN.DP_affichage_statut("serveur local: DP non renseigné")
        '    Exit Sub
        'End If
        'response_file = Config.LocalNetwork_ServerName & "\DPclients\" & response_file

        ''________________________________________________________________________________________________________________________
        ''________________________________________________________________________________________________________________________
        ''________________________________________________________________________________________________________________________
        '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", référence_interne, "Alimentation non effectuée suite à un problème technique", Identifiant_patient_function)
        '                MyMsg_Box.Presentation("Officine", "Échec de l’alimentation du DP: Alimentation non effectuée suite à un problème technique", False, "", False, "", True, "OK")
        '                MyMsg_Box.ShowDialog()
        '            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", référence_interne, "Problème technique : l'alimentation est mise en file d’attente", Identifiant_patient_function)
        '                MyMsg_Box.Presentation("Officine", "Échec de l’alimentation du DP" + Chr(10) + "Problème technique : l'alimentation est mise en file d’attente", False, "", False, "", True, "OK")
        '                MyMsg_Box.ShowDialog()
        '            End If
        '        Else
        '            statut_retour = "OK"
        '            Write_Trace_Fonc("Alimentation du DP effectuée", référence_interne, "", Identifiant_patient_function)

        '            For i = 0 To Dispensation_DataGridView.Rows.Count - 1
        '                If Dispensation_DataGridView.Item(Transmettre_Disp.Index, i).Value = False Then
        '                    imprim_Attestation_Refus_Alimentation()
        '                    Write_Trace_Fonc("Refus d’alimenter des médicaments", référence_interne, "", Identifiant_patient_function)
        '                    Exit For
        '                End If
        '            Next
        '            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", référence_interne, "Alimentation non effectuée suite à un problème technique", Identifiant_patient_function)
        '            MyMsg_Box.Presentation("Officine", "Échec de l’alimentation du DP: Alimentation non effectuée suite à un problème technique", False, "", False, "", True, "OK")
        '            MyMsg_Box.ShowDialog()
        '        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", référence_interne, "Problème technique : l'alimentation est mise en file d’attente", Identifiant_patient_function)
        '            MyMsg_Box.Presentation("Officine", "Échec de l’alimentation du DP" + Chr(10) + "Problème technique : l'alimentation est mise en file d’attente", False, "", False, "", True, "OK")
        '            MyMsg_Box.ShowDialog()
        '        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", référence_interne, "Problème technique : l'alimentation est mise en file d’attente", Identifiant_patient_function)
        '        MyMsg_Box.Presentation("Officine", "Dispensation placée en file d'attente pour alimentation du DP ultérieure.", False, "", False, "", True, "OK")
        '        MyMsg_Box.ShowDialog()

        '        COMPTOIR_MAIN.DP_affichage_statut("Pas de connexion DP")
        'End Select
        'Dim row_ = Me.DP_ReqTableAdapter.GetDataBy_ReqId(X_DP_ReqId).Item(0)
        'Me.DP_ReqTableAdapter.Update_byReqID(row_.Sequence_Number, statut_retour, row_.nbr_trans, row_.next_trans_time, Identifiant_patient_function, référence_interne, X_DP_ReqId)
        Bandeau_info_bas_hide() 'Bandeau_info_bas_show_thread)
    End Sub
#End Region

    Private Sub DP_Load(sender As Object, e As EventArgs) Handles Me.Load

        Histo_DP_DataGridView.Columns(DisDate_Histo_DP.Index).ValueType = GetType(Date)
        Edition_DP_DataGridView.Columns(DisDate_Histo_DP.Index).ValueType = GetType(Date)
        'dp_ConTyp = "SANS_CONSULTATION"
        'DP_struct.Load_Config()
        Fill_Dispensation_DataGridView()
        'Affichage("CONSULTATION_TOUT")


    End Sub
    Public Sub Fill_Dispensation_DataGridView()

        Dispensation_DataGridView.Rows.Clear()

        Dim compteur As Integer = 0
        For r = 0 To COMPTOIR_MAIN.Vente.RowCount - 2


            If COMPTOIR_MAIN.Vente.Item(COMPTOIR_MAIN.VenteEAN13.Index, r).Value.ToString <> "" And _
             Me.BdM_CIPTableAdapter1.GetDataBy_cip_ean13(COMPTOIR_MAIN.Vente.Item(COMPTOIR_MAIN.VenteEAN13.Index, r).Value.ToString).Rows.Count > 0 Then
                Dispensation_DataGridView.Rows.Add()
                Dispensation_DataGridView.Item(PrdCIP_disp.Index, compteur).Value = COMPTOIR_MAIN.Vente.Item(COMPTOIR_MAIN.VenteEAN13.Index, r).Value
                Dim row = Me.BdM_CIPTableAdapter1.GetDataBy_cip_ean13(Dispensation_DataGridView.Item(PrdCIP_disp.Index, compteur).Value).Item(0)
                If tab_Lignes_Vente(r).deconditionement = True Then
                    Dispensation_DataGridView.Item(PrdQteC_Disp.Index, compteur).Value = tab_Lignes_Vente(r).deconditionement_NmbreBoites.ToString
                    Dispensation_DataGridView.Item(PrdUCD_Disp.Index, compteur).Value = row.CIP_UCD
                    Dispensation_DataGridView.Item(PrdQtéU_Disp.Index, compteur).Value = tab_Lignes_Vente(r).deconditionement_quantité.ToString
                Else
                    Dispensation_DataGridView.Item(PrdQteC_Disp.Index, compteur).Value = COMPTOIR_MAIN.Vente.Item(COMPTOIR_MAIN.VenteQuantité.Index, r).Value
                    Dispensation_DataGridView.Item(PrdUCD_Disp.Index, compteur).Value = row.CIP_UCD
                    If Val(Dispensation_DataGridView.Item(PrdUCD_Disp.Index, compteur).Value) <> 0 Then
                        Dispensation_DataGridView.Item(PrdQtéU_Disp.Index, compteur).Value = Val(row.NB_UNITES) * Val(Dispensation_DataGridView.Item(PrdQteC_Disp.Index, compteur).Value)
                    End If
                End If
                Dispensation_DataGridView.Item(PrdCIS_Disp.Index, compteur).Value = COMPTOIR_MAIN.ProduitsTableAdapter.GetDataByCIP_or_EAN13_or_CAB(COMPTOIR_MAIN.Vente.Item(COMPTOIR_MAIN.VenteEAN13.Index, r).Value).Item(0).CIS
                Dispensation_DataGridView.Item(PrdATC_Disp.Index, compteur).Value = row.CODE_ATC
                Dispensation_DataGridView.Item(PrdDC_Disp.Index, compteur).Value = row.NOM_COURT

                Dispensation_DataGridView.Item(Transmettre_Disp.Index, compteur).Value = True

                If UCase(COMPTOIR_MAIN.Vente.Item(COMPTOIR_MAIN.VenteType.Index, r).Value) = "VENTE DIRECTE" Then
                    Dispensation_DataGridView.Item(PreTyp_disp.Index, compteur).Value = "Conseil"
                Else
                    Dispensation_DataGridView.Item(PreTyp_disp.Index, compteur).Value = "Prescrit"
                End If

                Dispensation_DataGridView.Item(PrdPoso_disp.Index, compteur).Value = COMPTOIR_MAIN.DP_Poso(r)
                Dispensation_DataGridView.Item(PrdRect_disp.Index, compteur).Value = COMPTOIR_MAIN.DP_Rect(r)
                If Not COMPTOIR_MAIN.Vente.Item(COMPTOIR_MAIN.Vente_NumActe.Index, r).Value Is Nothing Then
                    Dispensation_DataGridView.Item(NumActe_disp.Index, compteur).Value = COMPTOIR_MAIN.Vente.Item(COMPTOIR_MAIN.Vente_NumActe.Index, r).Value.ToString
                End If

                Dispensation_DataGridView.Item(peremption_disp.Index, compteur).Value = COMPTOIR_MAIN.Vente.Item(COMPTOIR_MAIN.Vente_Peremption.Index, r).Value
                Dispensation_DataGridView.Item(lot_disp.Index, compteur).Value = COMPTOIR_MAIN.Vente.Item(COMPTOIR_MAIN.Vente_lot.Index, r).Value

                compteur = compteur + 1

            ElseIf COMPTOIR_MAIN.Vente.Item(COMPTOIR_MAIN.VenteCIP.Index, r).Value.ToString <> "" And _
               Me.BdM_CIPTableAdapter1.GetDataBy_cip_ean13(COMPTOIR_MAIN.Vente.Item(COMPTOIR_MAIN.VenteCIP.Index, r).Value.ToString).Rows.Count > 0 Then
                Dispensation_DataGridView.Rows.Add()
                Dispensation_DataGridView.Item(PrdCIP_disp.Index, compteur).Value = COMPTOIR_MAIN.Vente.Item(COMPTOIR_MAIN.VenteCIP.Index, r).Value
                Dispensation_DataGridView.Item(PrdQteC_Disp.Index, compteur).Value = COMPTOIR_MAIN.Vente.Item(COMPTOIR_MAIN.VenteQuantité.Index, r).Value
                Dim row = Me.BdM_CIPTableAdapter1.GetDataBy_cip_ean13(Dispensation_DataGridView.Item(PrdCIP_disp.Index, compteur).Value).Item(0)
                Dispensation_DataGridView.Item(PrdUCD_Disp.Index, compteur).Value = row.CIP_UCD
                If Val(Dispensation_DataGridView.Item(PrdUCD_Disp.Index, compteur).Value) <> 0 Then
                    Dispensation_DataGridView.Item(PrdQtéU_Disp.Index, compteur).Value = Val(row.NB_UNITES) * Val(Dispensation_DataGridView.Item(PrdQteC_Disp.Index, compteur).Value)
                End If

                Dispensation_DataGridView.Item(PrdCIS_Disp.Index, compteur).Value = "" 'A TROUVER code CIS????
                Dispensation_DataGridView.Item(PrdATC_Disp.Index, compteur).Value = row.CODE_ATC
                Dispensation_DataGridView.Item(PrdDC_Disp.Index, compteur).Value = row.NOM_COURT

                Dispensation_DataGridView.Item(Transmettre_Disp.Index, compteur).Value = True

                If UCase(COMPTOIR_MAIN.Vente.Item(COMPTOIR_MAIN.VenteType.Index, r).Value) = "VENTE DIRECTE" Then
                    Dispensation_DataGridView.Item(PreTyp_disp.Index, compteur).Value = "Conseil"
                Else
                    Dispensation_DataGridView.Item(PreTyp_disp.Index, compteur).Value = "Prescrit"
                End If

                Dispensation_DataGridView.Item(PrdPoso_disp.Index, compteur).Value = COMPTOIR_MAIN.DP_Poso(r)
                Dispensation_DataGridView.Item(PrdRect_disp.Index, compteur).Value = COMPTOIR_MAIN.DP_Rect(r)
                If Not COMPTOIR_MAIN.Vente.Item(COMPTOIR_MAIN.Vente_NumActe.Index, r).Value Is Nothing Then
                    Dispensation_DataGridView.Item(NumActe_disp.Index, compteur).Value = COMPTOIR_MAIN.Vente.Item(COMPTOIR_MAIN.Vente_NumActe.Index, r).Value.ToString
                End If

                Dispensation_DataGridView.Item(peremption_disp.Index, compteur).Value = COMPTOIR_MAIN.Vente.Item(COMPTOIR_MAIN.Vente_Peremption.Index, r).Value
                Dispensation_DataGridView.Item(lot_disp.Index, compteur).Value = COMPTOIR_MAIN.Vente.Item(COMPTOIR_MAIN.Vente_lot.Index, r).Value

                compteur = compteur + 1

            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))
                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 Me.DP_ReqTableAdapter.GetDataBy_Sequence_Number(DP_Missing_Sequence_Numbers(i)).Rows.Count > 0 Then

                Dim reqrow = Me.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")
                    interactionId = xmlreq.FirstChild.Item("interactionId").GetAttribute("extension")
                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)

        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")

            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 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


            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", "")

            'Me.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
            DP_Connect.HEARTBEAT_variables.calcul_moyenne(DP_Connect.HEARTBEAT_variables.MetNbAl, DP_Connect.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")
            Me.DP_ReqTableAdapter.Update_byReqID(X_DP_Sequence_Number.ToString, "OK", 1, Now, Identifiant_patient, "ALIMENTATION", X_DP_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
                    Me.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)
                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.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)
                End If

            Else
                Me.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)

                COMPTOIR_MAIN.DP_affichage_statut("Pas de connexion DP")
                reset_connection()
            End If

        End Try
    End Sub
#End Region

    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 "Interactions"
    Public Structure interaction
        Dim cip1, libellé1, cip2, libellé2, code As String

    End Structure
    Public Function Interactions(ByVal Cip_list As List(Of String)) As List(Of interaction)

        Dim listretour As New List(Of interaction)

        While Cip_list.Count > 1

            Dim cip1 = Cip_list(0)

            For i = 1 To Cip_list.Count - 1

                If Me.BDM_interactionTableAdapter.GetDataBy_Cip1Cip2(cip1, Cip_list(i)).Rows.Count > 0 Then
                    Dim datas = Me.BDM_interactionTableAdapter.GetDataBy_Cip1Cip2(cip1, Cip_list(i)).Item(0)
                    Dim inter_found As interaction
                    inter_found.cip1 = datas.CIP1
                    inter_found.cip2 = datas.CIP2
                    inter_found.libellé1 = datas.libellé1
                    inter_found.libellé2 = datas.libellé2
                    inter_found.code = datas.code
                    listretour.Add(inter_found)
                End If

            Next

            Cip_list.RemoveAt(0)

        End While

        Return listretour

    End Function
#End Region

    Private Sub Back_Button_Click(sender As Object, e As EventArgs) Handles Back_Button.Click
        Me.Visible = False
    End Sub

#Region "Attestations"

    Public Function DP_drawstring_Refus_consultations() As String
        Dim infos As New DP_Attestation_info
        infos.TopMost = True
        Me.Visible = False
        infos.ShowDialog()
        Me.Visible = True
        Dim retour As String
        infos.ShowDialog()

        retour = "ATTESTATION DE REFUS DE CONSULTATION D'UN DOSSIER PHARMACEUTIQUE" + Chr(10) + Chr(10) + _
                    "Je, soussigné(e) :" + COMPTOIR_MAIN.DP_form.je_soussigné + Chr(10) + _
                    "Pharmacie :" + COMPTOIR_MAIN.DP_form.pharmacie + Chr(10) + Chr(10) + _
                     "déclare que :" + Chr(10) + Chr(10) + _
                     COMPTOIR_MAIN.ComboBoxLECTURE_VITALE.Text + "(1) m’a fait connaître ce jour son opposition à ce que je consulte le" + Chr(10) + _
                     "Dossier pharmaceutique établi à son nom." + Chr(10) + _
                    "Je l’ai informé(e) que cette décision ne me permettra pas d’effectuer une analyse pharmaceutique" + Chr(10) + _
                    "complète de ses traitements et que son Dossier pharmaceutique mentionnera ce refus de" + Chr(10) + _
                    "consultation. Je lui ai remis un exemplaire de la présente attestation." + Chr(10) + Chr(10) + Chr(10) + _
                    "En cochant la case ci-après, je certifie l'exactitude de cette déclaration ⌧" + Chr(10) + Chr(10) + _
                    "Fait à :" + COMPTOIR_MAIN.DP_form.fait_a + Chr(10) + _
                    "Le (date) :" + Format(Now, "dd/MM/yyyy") + Chr(10) + Chr(10) + Chr(10) + "______________________________________________" + Chr(10) + _
                "(1) ou, pour un mineur âgé de moins de 15 ans ou majeur sous tutelle, à son représentant légal, qui a justifié de son" + Chr(10) + _
        "identité :" + Chr(10) + _
        "Nom et prénoms du représentant légal :" + COMPTOIR_MAIN.DP_form.reprleg_nom_prénom + Chr(10) + _
                  "______________________________________________" + Chr(10) + _
                  "Les données personnelles recueillies sur cette attestation sont traitées par cette pharmacie pour les besoins de sa gestion" + " " + _
                  "administrative et du suivi du patient. Celle-ci s’engage à respecter les principes de protection des données à caractère personnel" + " " + _
                  "conformément au Règlement (UE) 2016/679 du Parlement européen et du Conseil du 27 avril 2016 (RGPD) et à la loi Informatique" + " " + _
                  "et Libertés modifiée. Vous disposez ainsi d'un droit d'accès, de rectification, d’effacement et de portabilité des informations qui" + " " + _
                  "vous concernent. Vous pouvez également demander une limitation ou vous opposer au traitement de vos données." + " " + _
                "Cette attestation sera conservée par votre pharmacien dans les conditions décrites dans le dépliant d’information relatif au Dossier" + " " + _
                "Pharmaceutique." + " " + _
                "Vous pouvez exercer ces droits en envoyant un courrier à l'adresse indiquée ci-dessus ou par email ou par téléphone." + " " + _
                "Le CNOP assurant la mise en œuvre du dossier pharmaceutique, vous pouvez également exercer vos droits auprès de l’Ordre" + " " + _
                "Direction des Technologies en Santé – 4 avenue Ruysdaël, TSA 90014, 75379 PARIS CEDEX 08 ou auprès de son Délégué" + " " + _
                "à la protection des données à l’adresse dpo@ordre.pharmacien.fr ou au 01.81.69.47.43" + " " + _
                "Vous disposez également, le cas échéant, du droit d’introduire une réclamation auprès de la Commission Nationale de" + " " + _
                "l'Informatique et des Libertés. " + Chr(10) + Chr(10) + _
                  "DP-ARCO-2019-06-18_v2.0.DOC"

        Return retour
    End Function

    Public Function DP_drawstring_création() As String
        Dim infos As New DP_Attestation_info
        infos.TopMost = True
        Me.Visible = False
        infos.ShowDialog()
        Me.Visible = True
        Dim retour As String


        retour = "ATTESTATION DE CREATION D’UN DOSSIER PHARMACEUTIQUE" + Chr(10) + Chr(10) + Chr(10) + _
"Je, soussigné(e) :" + COMPTOIR_MAIN.DP_form.je_soussigné + Chr(10) + _
                    "Pharmacie :" + COMPTOIR_MAIN.DP_form.pharmacie + Chr(10) + Chr(10) + _
            "Déclare :" + Chr(10) + Chr(10) + _
            "Avoir remis à " + COMPTOIR_MAIN.ComboBoxLECTURE_VITALE.Text + ", né(e) le :" + Mid(CurrentBenéficiaire.G104C12, 7, 2) + "/" + Mid(CurrentBenéficiaire.G104C12, 5, 2) + "/" + Mid(CurrentBenéficiaire.G104C12, 1, 4) + "(1), qui reconnait" + Chr(10) + _
            "en avoir pris connaissance, le dépliant d'information relatif au Dossier pharmaceutique." + Chr(10) + _
            "Informé(e) de ses droits et après avoir recueilli son consentement, j’ai procédé à la création de son" + Chr(10) + _
            "dossier pharmaceutique et lui ai remis un exemplaire de la présente attestation." + Chr(10) + Chr(10) + _
            "En cochant la case ci-après, je certifie l'exactitude de cette déclaration ⌧" + Chr(10) + Chr(10) + _
           "Fait à :" + COMPTOIR_MAIN.DP_form.fait_a + Chr(10) + _
            "Le (date) :" + Format(Now, "dd/MM/yyyy") + Chr(10) + Chr(10) + Chr(10) + _
            "______________________________________________" + Chr(10) + _
       "(1) ou, pour un mineur âgé de moins de 16 ans ou majeur sous tutelle, à son représentant légal, qui a justifié de son identité :" + Chr(10) + _
        "Nom et prénoms du représentant légal :" + COMPTOIR_MAIN.DP_form.reprleg_nom_prénom + Chr(10) + _
        "Qualité (père, mère, tuteur) :" + COMPTOIR_MAIN.DP_form.reprleg_qualité + Chr(10) + _
       "______________________________________________" + Chr(10) + _
      "Les données personnelles recueillies sur cette attestation sont traitées par cette pharmacie pour les besoins de sa gestion" + _
      " administrative et du suivi du patient. Celle-ci s’engage à respecter les principes de protection des données à caractère personnel conformément" + _
      " au Règlement (UE) 2016/679 du Parlement européen et du Conseil du 27 avril 2016 (RGPD) et à la loi Informatique" + _
      " et Libertés modifiée. Vous disposez ainsi d'un droit d'accès, de rectification, d’effacement et de portabilité des informations qui" + _
      " vous concernent. Vous pouvez également demander une limitation ou vous opposer au traitement de vos données." + _
    "Cette attestation sera conservée par votre pharmacien dans les conditions décrites dans le dépliant d’information relatif au Dossier Pharmaceutique." + _
    "Vous pouvez exercer ces droits en envoyant un courrier à l'adresse indiquée ci-dessus ou par email ou par téléphone." + _
    "Le CNOP assurant la mise en œuvre du dossier pharmaceutique, vous pouvez également exercer vos droits auprès de l’Ordre" + _
    "Direction des Technologies en Santé – 4 avenue Ruysdaël, TSA 90014, 75379 PARIS CEDEX 08 ou auprès de son Délégué à" + _
    " la protection des données à l’adresse dpo@ordre.pharmacien.fr ou au 01.81.69.47.43" + _
    "Vous disposez également, le cas échéant, du droit d’introduire une réclamation auprès de la Commission Nationale de l’Informatique" + _
    " et des Libertés." + Chr(10) + Chr(10) + _
"DP-ACRE-2019-06-18_v2.0.DOC"


        Return retour
    End Function

    Public Function DP_drawstring_Suppression() As String
        Dim infos As New DP_Attestation_info
        infos.TopMost = True
        Me.Visible = False
        infos.ShowDialog()
        Me.Visible = True
        Dim retour As String



        retour = "ATTESTATION DE CLOTURE D’UN DOSSIER PHARMACEUTIQUE" + Chr(10) + Chr(10) + _
       "Je, soussigné(e) :" + COMPTOIR_MAIN.DP_form.je_soussigné + Chr(10) + _
                    "Pharmacie :" + COMPTOIR_MAIN.DP_form.pharmacie + Chr(10) + Chr(10) + _
        "déclare que :" + Chr(10) + Chr(10) + _
        "À la demande de" + COMPTOIR_MAIN.ComboBoxLECTURE_VITALE.Text + ", né(e) le" + Mid(CurrentBenéficiaire.G104C12, 7, 2) + "/" + Mid(CurrentBenéficiaire.G104C12, 5, 2) + "/" + Mid(CurrentBenéficiaire.G104C12, 1, 4) + "(1), j’ai clos" + Chr(10) + _
        "ce jour le Dossier pharmaceutique établi à son nom." + Chr(10) + _
        "Si cette opération entraîne l’effacement total et définitif de toutes les données contenues dans le" + Chr(10) + _
        "Dossier, elle n’empêchera pas la personne de créer un nouveau Dossier pharmaceutique." + Chr(10) + _
        "Je lui ai remis un exemplaire de la présente attestation." + Chr(10) + Chr(10) + _
        "En cochant la case ci-après, je certifie l'exactitude de cette déclaration ⌧" + Chr(10) + Chr(10) + _
       "Fait à :" + COMPTOIR_MAIN.DP_form.fait_a + Chr(10) + _
        "Le (date) :" + Format(Now, "dd/MM/yyyy") + Chr(10) + Chr(10) + Chr(10) + "______________________________________________" + Chr(10) + _
        "(1) ou, pour un mineur âgé de moins de 15 ans ou majeur sous tutelle, à son représentant légal, qui a justifié de son " + Chr(10) + _
        "identité :" + Chr(10) + _
        "Nom et prénoms du représentant légal :" + COMPTOIR_MAIN.DP_form.reprleg_nom_prénom + Chr(10) + _
        "Qualité (père, mère, tuteur) :" + COMPTOIR_MAIN.DP_form.reprleg_qualité + Chr(10) + _
   "______________________________________________" + Chr(10) + _
      "Les données personnelles recueillies sur cette attestation sont traitées par cette pharmacie pour les besoins de sa gestion" + " " + _
      "administrative et du suivi du patient. Celle-ci s’engage à respecter les principes de protection des données à caractère personnel" + " " + _
      "conformément au Règlement (UE) 2016/679 du Parlement européen et du Conseil du 27 avril 2016 (RGPD) et à la loi Informatique" + " " + _
      "et Libertés modifiée. Vous disposez ainsi d'un droit d'accès, de rectification, d’effacement et de portabilité des informations qui" + " " + _
      "vous concernent. Vous pouvez également demander une limitation ou vous opposer au traitement de vos données." + " " + _
    "Cette attestation sera conservée par votre pharmacien dans les conditions décrites dans le dépliant d’information relatif au Dossier" + " " + _
    "Pharmaceutique." + " " + _
    "Vous pouvez exercer ces droits en envoyant un courrier à l'adresse indiquée ci-dessus ou par email ou par téléphone." + " " + _
    "Le CNOP assurant la mise en œuvre du dossier pharmaceutique, vous pouvez également exercer vos droits auprès de l’Ordre" + " " + _
    "Direction des Technologies en Santé – 4 avenue Ruysdaël, TSA 90014, 75379 PARIS CEDEX 08 ou auprès de son Délégué à" + " " + _
    "la protection des données à l’adresse dpo@ordre.pharmacien.fr ou au 01.81.69.47.43" + " " + _
    "Vous disposez également, le cas échéant, du droit d’introduire une réclamation auprès de la Commission Nationale de l’Informatique" + " " + _
    "et des Libertés." + Chr(10) + Chr(10) + _
"DP-ASUP-2019-06-18_v2.0.DOC"


        Return retour
    End Function

    Public Function DP_drawstring_Refus_Alimentation() As String
        Dim infos As New DP_Attestation_info
        infos.TopMost = True
        Me.Visible = False
        infos.ShowDialog()
        Me.Visible = True
        Dim retour As String


        retour = "ATTESTATION DE REFUS D’ALIMENTATION D’UN DOSSIER PHARMACEUTIQUE" + Chr(10) + Chr(10) + _
 "Je, soussigné(e) :" + COMPTOIR_MAIN.DP_form.je_soussigné + Chr(10) + _
                    "Pharmacie :" + COMPTOIR_MAIN.DP_form.pharmacie + Chr(10) + Chr(10) + _
        "déclare que :" + Chr(10) + Chr(10) + _
        COMPTOIR_MAIN.ComboBoxLECTURE_VITALE.Text + "(1) m’a fait connaître son opposition à ce que j’inscrive dans le" + " " + _
        "Dossier pharmaceutique établi à son nom certains médicaments que je lui ai délivrés ce jour." + " " + _
        "Je l 'ai informé(e) que cette décision ne me permettra pas d’assurer une analyse pharmaceutique" + " " + _
        "complète de ses traitements et lui ai indiqué que son Dossier pharmaceutique portera pendant quatre mois la mention « dossier incomplet »." + Chr(10) + _
        "Je lui ai remis un exemplaire de la présente attestation." + Chr(10) + Chr(10) + _
        "En cochant la case ci-après, je certifie l'exactitude de cette déclaration ⌧" + Chr(10) + Chr(10) + _
        "Fait à :" + COMPTOIR_MAIN.DP_form.fait_a + Chr(10) + _
        "Le (date) :" + Format(Now, "dd/MM/yyyy") + Chr(10) + Chr(10) + Chr(10) + "______________________________________________" + Chr(10) + _
        "(1) ou, pour un mineur âgé de moins de 15 ans ou majeur sous tutelle, à son représentant légal, qui a justifié de son " + Chr(10) + _
        "identité :" + Chr(10) + _
        "Nom et prénoms du représentant légal :" + COMPTOIR_MAIN.DP_form.reprleg_nom_prénom + Chr(10) + _
        "Qualité (père, mère, tuteur) :" + COMPTOIR_MAIN.DP_form.reprleg_qualité + Chr(10) + _
    "______________________________________________" + Chr(10) + _
      "Les données personnelles recueillies sur cette attestation sont traitées par cette pharmacie pour les besoins de sa gestion" + " " + _
      "administrative et du suivi du patient. Celle-ci s’engage à respecter les principes de protection des données à caractère personnel" + " " + _
      "conformément au Règlement (UE) 2016/679 du Parlement européen et du Conseil du 27 avril 2016 (RGPD) et à la loi Informatique" + " " + _
      "et Libertés modifiée. Vous disposez ainsi d'un droit d'accès, de rectification, d’effacement et de portabilité des informations qui" + " " + _
      "vous concernent. Vous pouvez également demander une limitation ou vous opposer au traitement de vos données." + " " + _
    "Cette attestation sera conservée par votre pharmacien dans les conditions décrites dans le dépliant d’information relatif au Dossier" + " " + _
    "Pharmaceutique." + " " + _
    "Vous pouvez exercer ces droits en envoyant un courrier à l'adresse indiquée ci-dessus ou par email ou par téléphone." + " " + _
    "Le CNOP assurant la mise en œuvre du dossier pharmaceutique, vous pouvez également exercer vos droits auprès de l’Ordre" + " " + _
    "Direction des Technologies en Santé – 4 avenue Ruysdaël, TSA 90014, 75379 PARIS CEDEX 08 ou auprès de son Délégué à" + " " + _
    "la protection des données à l’adresse dpo@ordre.pharmacien.fr ou au 01.81.69.47.43" + " " + _
    "Vous disposez également, le cas échéant, du droit d’introduire une réclamation auprès de la Commission Nationale de l’Informatique" + " " + _
    "et des Libertés." + Chr(10) + Chr(10) + _
"DP-ARAL-2019-06-18_v2.0.DOC"


        Return retour
    End Function

    Public Function DP_drawstring_edition() As String
        Dim infos As New DP_Attestation_info
        infos.TopMost = True
        Me.Visible = False
        infos.ShowDialog()
        Me.Visible = True
        Dim retour As String


        retour = "ATTESTATION DE REMISE D’UNE COPIE DE DOSSIER PHARMACEUTIQUE" + Chr(10) + Chr(10) + Chr(10) + _
     "Je, soussigné(e) :" + COMPTOIR_MAIN.DP_form.je_soussigné + Chr(10) + _
                    "Pharmacie :" + COMPTOIR_MAIN.DP_form.pharmacie + Chr(10) + Chr(10) + _
        "déclare :" + Chr(10) + Chr(10) + _
        "Avoir remis à sa demande à " + COMPTOIR_MAIN.ComboBoxLECTURE_VITALE.Text + ", né(e) le" + Mid(CurrentBenéficiaire.G104C12, 7, 2) + "/" + Mid(CurrentBenéficiaire.G104C12, 5, 2) + "/" + Mid(CurrentBenéficiaire.G104C12, 1, 4) + "(1)" + Chr(10) + _
        "une copie sur support papier de son Dossier pharmaceutique accompagnée d’un" + Chr(10) + _
        "exemplaire de la présente attestation." + Chr(10) + Chr(10) + _
        "En cochant la case ci-après, je certifie l'exactitude de cette déclaration ⌧" + Chr(10) + Chr(10) + _
       "Fait à :" + COMPTOIR_MAIN.DP_form.fait_a + Chr(10) + _
        "Le (date) :" + Format(Now, "dd/MM/yyyy") + Chr(10) + Chr(10) + Chr(10) + "______________________________________________" + Chr(10) + _
         "(1) ou, pour un mineur âgé de moins de 15 ans ou majeur sous tutelle, à son représentant légal, qui a justifié de son " + Chr(10) + _
        "identité :" + Chr(10) + _
        "Nom et prénoms du représentant légal :" + COMPTOIR_MAIN.DP_form.reprleg_nom_prénom + Chr(10) + _
        "Qualité (père, mère, tuteur) :" + COMPTOIR_MAIN.DP_form.reprleg_qualité + Chr(10) + _
    "______________________________________________" + Chr(10) + _
      "Les données personnelles recueillies sur cette attestation sont traitées par cette pharmacie pour les besoins de sa gestion" + " " + _
      "administrative et du suivi du patient. Celle-ci s’engage à respecter les principes de protection des données à caractère personnel" + " " + _
      "conformément au Règlement (UE) 2016/679 du Parlement européen et du Conseil du 27 avril 2016 (RGPD) et à la loi Informatique" + " " + _
      "et Libertés modifiée. Vous disposez ainsi d'un droit d'accès, de rectification, d’effacement et de portabilité des informations qui" + " " + _
      "vous concernent. Vous pouvez également demander une limitation ou vous opposer au traitement de vos données." + " " + _
    "Cette attestation sera conservée par votre pharmacien dans les conditions décrites dans le dépliant d’information relatif au Dossier" + " " + _
    "Pharmaceutique." + " " + _
    "Vous pouvez exercer ces droits en envoyant un courrier à l'adresse indiquée ci-dessus ou par email ou par téléphone." + " " + _
    "Le CNOP assurant la mise en œuvre du dossier pharmaceutique, vous pouvez également exercer vos droits auprès de l’Ordre" + " " + _
    "Direction des Technologies en Santé – 4 avenue Ruysdaël, TSA 90014, 75379 PARIS CEDEX 08 ou auprès de son Délégué à" + " " + _
    "la protection des données à l’adresse dpo@ordre.pharmacien.fr ou au 01.81.69.47.43" + " " + _
    "Vous disposez également, le cas échéant, du droit d’introduire une réclamation auprès de la Commission Nationale de l’Informatique" + " " + _
    "et des Libertés." + Chr(10) + Chr(10) + Chr(10) + _
"DP-AEDI-2019-06-18_v2.0.DOC"


        Return retour
    End Function

    Public Sub imprim_Attestation_Création()

        Bandeau_info_bas_show("Impression de l’attestation de création du DP")

        DP_drawstring = DP_drawstring_création()
        PrintDialog1.Document = PrintDocument1
impression_obligatoire:
        If PrintDialog1.ShowDialog = Windows.Forms.DialogResult.OK Then
            Dim attestation_ref As String = "Création_" + Identifiant_patient_function() + "_" + Format(Now, "yyyyMMddHHmmss")
            My.Computer.FileSystem.WriteAllText(Config.LocalNetwork_ServerName & "\DP\attestations\" + attestation_ref, DP_drawstring, False)
            PrintDocument1.Print()
            Write_Trace_Fonc("Impression et remise de l’attestation de création", attestation_ref, "", Identifiant_patient_function)
        Else
            MyMsg_Box.Presentation("Officine", "IMPRESSION OBLIGATOIRE", False, "", False, "", True, "OK")
            MyMsg_Box.ShowDialog()
            GoTo impression_obligatoire
        End If
        Bandeau_info_bas_hide() 'Bandeau_info_bas_show_thread)
    End Sub

    Public Sub imprim_Attestation_Suppression()
        Bandeau_info_bas_show("Impression de l’attestation de suppression du DP")
        DP_drawstring = DP_drawstring_Suppression()
        PrintDialog1.Document = PrintDocument1
impression_obligatoire:
        If PrintDialog1.ShowDialog = Windows.Forms.DialogResult.OK Then
            Dim attestation_ref As String = "Suppression_" + Identifiant_patient_function() + "_" + Format(Now, "yyyyMMddHHmmss")
            My.Computer.FileSystem.WriteAllText(Config.LocalNetwork_ServerName & "\DP\attestations\" & attestation_ref, DP_drawstring, False)
            PrintDocument1.Print()
            Write_Trace_Fonc("Impression et remise de l’attestation de suppression", attestation_ref, "", Identifiant_patient_function)
        Else
            MyMsg_Box.Presentation("Officine", "IMPRESSION OBLIGATOIRE", False, "", False, "", True, "OK")
            MyMsg_Box.ShowDialog()
            GoTo impression_obligatoire
        End If
        Bandeau_info_bas_hide() 'Bandeau_info_bas_show_thread)
    End Sub

    Public Sub imprim_Attestation_Refus_Alimentation()
        Bandeau_info_bas_show("Impression de l’attestation de refus d'alimentation du DP")
        DP_drawstring = DP_drawstring_Refus_Alimentation()
        PrintDialog1.Document = PrintDocument1
impression_obligatoire:
        If PrintDialog1.ShowDialog = Windows.Forms.DialogResult.OK Then
            My.Computer.FileSystem.WriteAllText(Config.LocalNetwork_ServerName & "\DP\attestations\Refus_Alimentation_" + Identifiant_patient_function() + "_" + Format(Now, "yyyyMMddHHmmss"), DP_drawstring, False)
            PrintDocument1.Print()
            Write_Trace_Fonc("Impression et remise de l’attestation de refus d’alimentation", "Refus_Alimentation_" + Format(Now, "yyyyMMddHHmmss"), "", Identifiant_patient_function)
        Else
            MyMsg_Box.Presentation("Officine", "IMPRESSION OBLIGATOIRE", False, "", False, "", True, "OK")
            MyMsg_Box.ShowDialog()
            GoTo impression_obligatoire
        End If
        Bandeau_info_bas_hide() 'Bandeau_info_bas_show_thread)
    End Sub
    Private Sub PrintDocument1_PrintPage(ByVal sender As Object, ByVal e As System.Drawing.Printing.PrintPageEventArgs) Handles PrintDocument1.PrintPage
        Dim drawFont As New Font("Century Gothic", 10)
        Dim drawBrush As New SolidBrush(Color.Black)
        'e.Graphics.DrawString(DP_drawstring, drawFont, drawBrush, 10, 10)

        Dim charactersOnPage As Integer = 0
        Dim linesPerPage As Integer = 0

        ' Sets the value of charactersOnPage to the number of characters 
        ' of stringToPrint that will fit within the bounds of the page.
        e.Graphics.MeasureString(DP_drawstring, drawFont, e.MarginBounds.Size, _
            StringFormat.GenericTypographic, charactersOnPage, linesPerPage)

        ' Draws the string within the bounds of the page
        e.Graphics.DrawString(DP_drawstring, Me.Font, Brushes.Black, _
            e.MarginBounds, StringFormat.GenericTypographic)

        ' Remove the portion of the string that has been printed.
        DP_drawstring = DP_drawstring.Substring(charactersOnPage)

        ' Check to see if more pages are to be printed.
        e.HasMorePages = DP_drawstring.Length > 0

    End Sub

    Public Sub imprim_Attestation_Edition()

        Bandeau_info_bas_show("Impression de l’attestation d'édition du DP")


        DP_drawstring = DP_drawstring_edition()
        PrintDialog1.Document = PrintDocument1
impression_obligatoire:
        If PrintDialog1.ShowDialog = Windows.Forms.DialogResult.OK Then
            Dim attestation_ref As String = "Edition_" + Identifiant_patient_function() + "_" + Format(Now, "yyyyMMddHHmmss")
            My.Computer.FileSystem.WriteAllText(Config.LocalNetwork_ServerName & "\DP\attestations\" + attestation_ref, DP_drawstring, False)
            PrintDocument1.Print()
            Write_Trace_Fonc("Impression et remise de l’attestation de remise de copîe du DP", attestation_ref, "", Identifiant_patient_function)
        Else
            MyMsg_Box.Presentation("Officine", "IMPRESSION OBLIGATOIRE", False, "", False, "", True, "OK")
            MyMsg_Box.ShowDialog()
            GoTo impression_obligatoire
        End If

        Bandeau_info_bas_hide() 'Bandeau_info_bas_show_thread)
    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
        If DP_objRequest Is Nothing Then
            If Config.DP_is_local_client = False Then
                If Not DP_local_server_thread Is Nothing Then DP_local_server_thread.Abort()
                DP_Connection_reseted = True
                If Not DP_Connect_thread Is Nothing Then DP_Connect_thread.Abort()
                DP_Connect_thread = New Thread(New ThreadStart(AddressOf DP_Connect.connect))
                DP_Connect_thread.Start()
            End If
        ElseIf DP_objRequest.ServicePoint.CurrentConnections = 0 Then

            If Config.DP_is_local_client = False Then
                If Not DP_local_server_thread Is Nothing Then DP_local_server_thread.Abort()
                DP_Connection_reseted = True
                If Not DP_Connect_thread Is Nothing Then DP_Connect_thread.Abort()
                DP_Connect_thread = New Thread(New ThreadStart(AddressOf DP_Connect.connect))
                DP_Connect_thread.Start()
            End If
        End If
    End Sub


#Region "impression DP"
    Private Sub Edition_Button_Click(sender As Object, e As EventArgs) Handles Edition_Button.Click
        Bandeau_info_bas_show("Edition du DP")
        Me.TopMost = False
        impr_DP()
        Me.TopMost = True
        Bandeau_info_bas_hide() 'Bandeau_info_bas_show_thread)
    End Sub

    Public Sub impr_DP()
        If COMPTOIR_MAIN.DP_LinkLabel.Text = "DP supprimé" Then
            MyMsg_Box.Presentation("Officine", "Ce DP a été supprimé", False, "", False, "", True, "OK")
            MyMsg_Box.ShowDialog()
            Exit Sub
        ElseIf COMPTOIR_MAIN.DP_LinkLabel.Text = "DP refusé" Then
            MyMsg_Box.Presentation("Officine", "Ce patient n’a pas de DP : il a refusé sa création.", False, "", False, "", True, "OK")
            MyMsg_Box.ShowDialog()
            Exit Sub
        End If
        Dim answer As DialogResult
        Dim confirmation As New DP_Confirmation
        confirmation.label_text = "Confirmez-vous la demande du patient pour l’édition de son DP ?"
        answer = confirmation.ShowDialog
        If answer = Windows.Forms.DialogResult.No Then
            Exit Sub
        End If
        If COMPTOIR_MAIN.DP_LinkLabel.Text <> "DP existant" And COMPTOIR_MAIN.DP_LinkLabel.Text <> "DP incomplet" And COMPTOIR_MAIN.DP_LinkLabel.Text <> "DP en alimentation" Then
            MyMsg_Box.Presentation("Officine", "Pas de DP à editer", False, "", False, "", True, "OK")
            MyMsg_Box.ShowDialog()
            Exit Sub
        End If

        If Config.DP_is_local_client = False Then
            Affichage_serveur("EDITION")
        Else
            Affichage_client("EDITION")
        End If

        If COMPTOIR_MAIN.DP_LinkLabel.Text = "Pas de connexion DP" Then Exit Sub 'en cas d'echec de connexion(exemple test timeout edition)

        PrintDialog3.Document = PrintDocument3
        If PrintDialog3.ShowDialog = Windows.Forms.DialogResult.OK Then
            Print_num_page = 1
            PrintDocument3.Print()
            imprim_Attestation_Edition()
        End If

    End Sub

    Private Sub PrintDocument3_PrintPage(ByVal sender As System.Object, ByVal e As System.Drawing.Printing.PrintPageEventArgs) Handles PrintDocument3.PrintPage

        e.Graphics.DrawString("page " & Print_num_page.ToString, New Font("Century Gothic", 6), Brushes.Black, New Point(1, 1))
        Dim nbr_tot_l As Integer = 0 'nombre_total_de_lignes_imprimées (cellules multilignes)
        If Print_num_page = 1 Then


            e.Graphics.DrawString("COPIE DU DOSSIER PHARMACEUTIQUE" & Chr(10) & Now.ToLongDateString & "  " & Now.ToLongTimeString & Chr(10) & Chr(10) & Chr(10) & Config.Titulaire_raison_sociale & Chr(10) & Chr(10) & Chr(10) _
                 & CurrentBenéficiaire.G104C1 & " " & CurrentBenéficiaire.G104C3 & Chr(10) & _
                 "né(e) le " & Mid(CurrentBenéficiaire.G104C12, 7, 2) & "/" & Mid(CurrentBenéficiaire.G104C12, 5, 2) & "/" & Mid(CurrentBenéficiaire.G104C12, 1, 4) & Chr(10) _
                 & "adresse: " & CurrentBenéficiaire.G104C4 & " " & CurrentBenéficiaire.G104C5 & " " & CurrentBenéficiaire.G104C6 & " " & CurrentBenéficiaire.G104C7 & " " & CurrentBenéficiaire.G104C8 & Chr(10) & Chr(10), _
                  New Font("Century Gothic", 10), Brushes.Black, New Point(50, 50))

            If COMPTOIR_MAIN.DP_LinkLabel.Text = "DP incomplet" Then
                e.Graphics.DrawString("DP INCOMPLET : conformément à la demande du patient," + Chr(10) + "un ou plusieurs produits dispensés n’apparaissent pas dans cet historique.", New Font("Century Gothic", 10), Brushes.Red, New Point(50, 10))
            End If
            If Config.DP_is_local_client = False Then
                Affichage_serveur("EDITION")
            Else
                Affichage_client("EDITION")
            End If

            e.Graphics.DrawRectangle(Pens.Black, New Rectangle(50, 300, 65, 20))
            e.Graphics.DrawString("Date", New Font("Century Gothic", 10), Brushes.Black, New Point(52, 302))
            e.Graphics.DrawRectangle(Pens.Black, New Rectangle(115, 300, 85, 20))
            e.Graphics.DrawString("CIP", New Font("Century Gothic", 10), Brushes.Black, New Point(117, 302))
            e.Graphics.DrawRectangle(Pens.Black, New Rectangle(200, 300, 200, 20))
            e.Graphics.DrawString("Libellé", New Font("Century Gothic", 10), Brushes.Black, New Point(202, 302))
            e.Graphics.DrawRectangle(Pens.Black, New Rectangle(400, 300, 30, 20))
            e.Graphics.DrawString("Qté", New Font("Century Gothic", 10), Brushes.Black, New Point(402, 302))
            e.Graphics.DrawRectangle(Pens.Black, New Rectangle(430, 300, 175, 20))
            e.Graphics.DrawString("rectification", New Font("Century Gothic", 10), Brushes.Black, New Point(432, 302))
            e.Graphics.DrawRectangle(Pens.Black, New Rectangle(605, 300, 175, 20))
            e.Graphics.DrawString("posologie", New Font("Century Gothic", 10), Brushes.Black, New Point(607, 302))


            Print_current_row = 0
            While nbr_tot_l < 40 And Print_current_row < Edition_DP_DataGridView.RowCount
                Dim X = 50
                Dim nbr_max_l As Integer = 1 'nombre_max_de_lignes_dans_les_cellules_multilignes_de_cette_ligne
                'Draw_cell(X, 65, Mid(Edition_DP_DataGridView.Item(DisDate_Histo_DP.Index, Print_current_row).Value, 7, 2) & "/" & _
                '          Mid(Edition_DP_DataGridView.Item(DisDate_Histo_DP.Index, Print_current_row).Value, 5, 2) & "/" & _
                '          Mid(Edition_DP_DataGridView.Item(DisDate_Histo_DP.Index, Print_current_row).Value, 1, 4), e, Print_current_row, nbr_tot_l, nbr_max_l)
                Dim adate As Date = Edition_DP_DataGridView.Item(DisDate_Histo_DP.Index, Print_current_row).Value
                Draw_cell(X, 65, adate.ToShortDateString, e, Print_current_row, nbr_tot_l, nbr_max_l)
                Draw_cell(X, 85, Edition_DP_DataGridView.Item(CIP_Histo_DP.Index, Print_current_row).Value, e, Print_current_row, nbr_tot_l, nbr_max_l)
                Draw_cell(X, 200, Edition_DP_DataGridView.Item(DC_Histo_DP.Index, Print_current_row).Value, e, Print_current_row, nbr_tot_l, nbr_max_l)
                Draw_cell(X, 30, Edition_DP_DataGridView.Item(QteC_Histo_DP.Index, Print_current_row).Value, e, Print_current_row, nbr_tot_l, nbr_max_l)
                Draw_cell(X, 175, Edition_DP_DataGridView.Item(PrdRect_Histo_DP.Index, Print_current_row).Value, e, Print_current_row, nbr_tot_l, nbr_max_l)
                Draw_cell(X, 175, Edition_DP_DataGridView.Item(PrdPoso_Histo_DP.Index, Print_current_row).Value, e, Print_current_row, nbr_tot_l, nbr_max_l)
                nbr_tot_l = nbr_tot_l + nbr_max_l
                Print_current_row = Print_current_row + 1
            End While
            If Print_current_row < Edition_DP_DataGridView.RowCount - 1 Then
                Print_num_page = 2
                e.HasMorePages = True
            End If

        Else
            nbr_tot_l = 0
            While nbr_tot_l < 50 And Print_current_row < Edition_DP_DataGridView.RowCount
                Dim X = 50
                Dim nbr_max_l As Integer = 1 'nombre_max_de_lignes_dans_les_cellules_multilignes_de_cette_ligne
                'Draw_cell(X, 65, Mid(Edition_DP_DataGridView.Item(DisDate_Histo_DP.Index, Print_current_row).Value, 7, 2) & "/" & _
                '          Mid(Edition_DP_DataGridView.Item(DisDate_Histo_DP.Index, Print_current_row).Value, 5, 2) & "/" & _
                '          Mid(Edition_DP_DataGridView.Item(DisDate_Histo_DP.Index, Print_current_row).Value, 1, 4), e, Print_current_row, nbr_tot_l, nbr_max_l)
                Dim adate As Date = Edition_DP_DataGridView.Item(DisDate_Histo_DP.Index, Print_current_row).Value
                Draw_cell(X, 65, adate.ToShortDateString, e, Print_current_row, nbr_tot_l, nbr_max_l)
                Draw_cell(X, 85, Edition_DP_DataGridView.Item(CIP_Histo_DP.Index, Print_current_row).Value, e, Print_current_row, nbr_tot_l, nbr_max_l)
                Draw_cell(X, 200, Edition_DP_DataGridView.Item(DC_Histo_DP.Index, Print_current_row).Value, e, Print_current_row, nbr_tot_l, nbr_max_l)
                Draw_cell(X, 30, Edition_DP_DataGridView.Item(QteC_Histo_DP.Index, Print_current_row).Value, e, Print_current_row, nbr_tot_l, nbr_max_l)
                Draw_cell(X, 175, Edition_DP_DataGridView.Item(PrdRect_Histo_DP.Index, Print_current_row).Value, e, Print_current_row, nbr_tot_l, nbr_max_l)
                Draw_cell(X, 175, Edition_DP_DataGridView.Item(PrdPoso_Histo_DP.Index, Print_current_row).Value, e, Print_current_row, nbr_tot_l, nbr_max_l)
                nbr_tot_l = nbr_tot_l + nbr_max_l
                Print_current_row = Print_current_row + 1
            End While
            If Print_current_row < Edition_DP_DataGridView.RowCount - 1 Then
                Print_num_page = Print_num_page + 1
                e.HasMorePages = True
            End If
        End If


    End Sub

    Public Sub Draw_cell(ByRef X As Integer, ByVal cell_width As Integer, ByVal thestring As String, ByVal e As System.Drawing.Printing.PrintPageEventArgs, _
                          ByVal r As Integer, ByRef nbr_tot_l As Integer, ByRef nbr_max_l As Integer)
        Dim nombre_lignes_pour_la_cellule As Integer
        Dim myfont As New Font("Century Gothic", 6)
        Dim stringSize As New SizeF
        stringSize = e.Graphics.MeasureString(thestring, myfont)

        nombre_lignes_pour_la_cellule = Int((Convert.ToInt32(stringSize.Width) / cell_width)) + 1
        If nombre_lignes_pour_la_cellule > nbr_max_l Then
            nbr_max_l = nombre_lignes_pour_la_cellule
        End If

        Dim Y As Integer
        If Print_num_page = 1 Then
            Y = 320 + (nbr_tot_l * 20)
        Else
            Y = 50 + (nbr_tot_l * 20)
        End If

        e.Graphics.DrawRectangle(Pens.Black, New Rectangle(X, Y, cell_width, nombre_lignes_pour_la_cellule * 20))



        If nombre_lignes_pour_la_cellule = 1 Then
            e.Graphics.DrawString(thestring, myfont, Brushes.Black, New Point(X + 2, Y + 3))
        Else
            Dim debut_string, string_restant As String
            string_restant = thestring
            For l = 0 To nombre_lignes_pour_la_cellule - 1
                debut_string = string_restant
                While e.Graphics.MeasureString(debut_string, myfont).Width > cell_width
                    debut_string = Mid(debut_string, 1, debut_string.Length - 1)
                End While
                e.Graphics.DrawString(debut_string, myfont, Brushes.Black, New Point(X + 2, Y + 3 + (l * 20)))
                string_restant = Mid(string_restant, debut_string.Length + 1)

            Next

        End If
        X = X + cell_width
    End Sub

#End Region

    Private Sub DP_Shown(sender As Object, e As EventArgs) Handles Me.Shown
        Me.TopMost = True
        Me.BringToFront()
        Me.Select()
        Me.Activate()
    End Sub
End Class