Imports System
Imports System.Net
Imports System.Web.Services.Protocols
Imports PatientDemographicsSampleCode.PatientDemographicsWebService

' Class PatientDemographicsSample submits demographic information (HL7 ADT messages) 
' to the MedPlus Hub platform.
'
' Upon its construction, this class will exercise the functions relating to the
' Demographics Service, which includes:
'
' 1. Sending a real time ADT message.
' 2. Sending a batch mode ADT message.

Public Class PatientDemographicsSample
    ' USERNAME designates the Hub user name used to
    ' authenticate to the Hub web service
    Private Const USERNAME As String = "test"

    ' PASSWORD designates the password associated with
    ' the Hub user when authenticating to the web service
    Private Const PASSWORD As String = "customer1"

    ' WEB_SERVICE_URL designates the end point used to
    ' connect to the Hub's Demographics web service
    Private Const WEB_SERVICE_URL As String = "https://cert.hub.care360.com/demographic/service"

    ' SENDING_APPLICATION designates the application that 
    ' is sending the ADT message to Hub
    Private Const SENDING_APPLICATION As String = "HUBWS"

    ' SENDING_FACILITY designates the account number provided to you 
    ' by Quest for the businessunit you are sending demographics for
    Private Const SENDING_FACILITY As String = "1594"

    ' RECEIVING_FACILITY designates the business unit 
    ' within Quest which the demographics are for
    Private Const RECEIVING_FACILITY As String = "2135800"

    ' The HL7 ADT message template - The following "template" is used in
    ' constucting the Demographic message.
    ' 
    ' 0 = sending application (field 3) 
    ' 1 = sending facility (field 4) represents the account with Quest Diagnostics 
    ' 2 = receiving facility (field 6) The Quest Business Unit for above account 
    ' 3 = date time (field 7) 
    ' 4 = message control id (field 10) Unique Number identifying this ADT message
    Private Shared ADT_MESSAGE As String = "MSH|^~\&|{0}|{1}||{2}|{3:yyyyMMddHHmmssss}||ADT^A28|{4}|P|2.3" + Chr(13) + _
                                           "EVN|A28|199608190820" + Chr(13) + _
                                           "PID|1|pid123|^^^LH||Wally^SHERRY^M||20000101|F|PETRY^SHERRY||4690 Parkway Dr.^address line 2^Mason^OH^45040^USA|a2|^^^^86^999^9999999^99999|513-999-9999|a5|||1-FOUND|444-66-9999" + Chr(13) + _
                                           "PV1|1|O" + Chr(13) + _
                                           "GT1|1|88|Smith^John^M^JR^DR^MD||3710 Emery Lake Ln^Street line2^Cincinnati^OH^45010|^^^^1^513^8888888^1234|^^^^1^238^4444444^5678|19960708112233|M|I|8|287889999||||ABC Inc.^Limited^M |4567 Kelly Drive^address line 2^Oxford^OH^45068|55566677777|4556|FT|Guarantor Organization" + Chr(13) + _
                                           "IN1|1|INSID123^Insurance Plan ABC|INSCOID123|insuranceco|1800 Insurance Rd.^^Detroit^MI^45777||^^^^1^555^6667777^1234|3433|name|||||^19960707|||||||||||||||||||||||||||||||||T" + Chr(13)

    Public Sub New()
        Try
            ' calling sendRealTimeADTMessage will send the demographic request in
            ' real time
            Console.WriteLine("Calling submitRealTimeADTMessage...")
            sendADTMessage(True)

            ' calling sendBatchADTMessage will send the demographic request in
            ' batch mode
            Console.WriteLine("Calling sendBatchADTMessage...")
            sendADTMessage(False)

        Catch ex As Exception
            Console.WriteLine(ex.Message)

        End Try
    End Sub

    ' The sendADTMessage function handles the interactions with the Hub’s SOAP interface
    Public Sub sendADTMessage(ByVal realTime As Boolean)
        Dim webService As DemographicService = Nothing

        Try
            '-------------------------------------------------------
            'STEP 1: CREATE WEB SERVICE REFS, SET PARAMS
            '-------------------------------------------------------
            webService = New DemographicService
        Catch except As Exception
            Console.Write(except.StackTrace)
            webService = Nothing
        End Try

        If Not (webService Is Nothing) Then
            Dim response As DemographicResponse = Nothing
            Dim request As DemographicRequest = Nothing

            Try
                '------------------------------------------------------------------
                'STEP 2: CREATE CREDENTIALS OBJECT CONTAINING USERNAME AND PASSWORD
                '------------------------------------------------------------------
                webService.Credentials = New NetworkCredential(USERNAME, PASSWORD)

                ' By default the client will attempt to call the web service without 
                ' sending the credentials. If the server returns a 401 HTTP response, 
                ' the client makes the call again with the credentials. If we set 
                ' PreAuthenticate to True, the client will include the credentials on 
                ' the initial call and eliminate this extra processing.
                '
                ' This should probably be set in the web service object's constructor,
                ' but has been included here to demonstrate.
                webService.PreAuthenticate = True

                If WEB_SERVICE_URL.Length > 0 Then
                    webService.Url = WEB_SERVICE_URL
                End If

                '--------------------------------------------------------------------------------
                'STEP 3: call function that will create the WebService Demographic Request Object
                '--------------------------------------------------------------------------------
                request = getWebServiceDemographicRequest()

                '----------------------------------------------------------------------------
                'STEP 4: call WebService function that submits demographic request to the Hub
                '----------------------------------------------------------------------------
                If realTime Then
                    response = webService.submitRealTimeADTMessage(request)
                Else
                    response = webService.submitBatchADTMessage(request)
                End If

            Catch soapEx As SoapException
                Dim exceptionMessage As String = soapEx.Detail.InnerText.Replace("" & _
                Microsoft.VisualBasic.Chr(10) & "", "" & Microsoft.VisualBasic.Chr(13) & "" & _
                Microsoft.VisualBasic.Chr(10) & "")
                Console.Write(exceptionMessage)
            End Try

            If Not (response Is Nothing) Then
                '------------------------------------------------
                'STEP 5: Examine response coming back for the Hub
                '------------------------------------------------
                Console.WriteLine("Status: <{0}>.", response.status)
                Console.WriteLine("Transaction Id: <{0}>.", response.hubTransactionUid)
                Console.WriteLine("Message Control Id: <{0}>.", response.messageControlUid)

                If Not (response.errors Is Nothing) Then
                    Dim valErr As String
                    For Each valErr In response.errors
                        Console.WriteLine("Validation Error: <{0}>.", valErr)
                    Next
                End If
            Else
                Console.WriteLine("Failed to properly call submitADTMessage WebService method.")
            End If
        End If
    End Sub

    ' the getWebServiceDemographicRequest function creates a proper DemographicRequest object 
    ' that will be submitted to the Hub
    Private Function getWebServiceDemographicRequest() As DemographicRequest
        Dim retval As New DemographicRequest
        Dim ADTMessage As String = Nothing
        Dim ADTMessageByteArray As Byte()

        ' Create ADT Message by passing in facility information
        ADTMessage = buildADTMessage(SENDING_APPLICATION, SENDING_FACILITY, RECEIVING_FACILITY)

        ' Convert String to a Byte array and return in an DemographicRequest object
        ADTMessageByteArray = System.Text.Encoding.ASCII.GetBytes(ADTMessage)
        retval.ADTMessage = ADTMessageByteArray
        Return retval
    End Function

    'the buildADTMessage function replaces values in the ADT_MESSAGE template to create
    'a valid HL7 ADT message
    Private Function buildADTMessage(ByVal sendingApplication As String, _
                                     ByVal sendingFacility As String, _
                                     ByVal receivingFacility As String) As String
        ' 'now' is used for 2 purposes here
        ' 1 to specify the time that the message was created
        ' 2 to create a unique message control ID
        Dim now As System.DateTime = System.DateTime.Now
        ' parameters for replacement in the template
        Dim msgParams(5) As Object

        msgParams(0) = sendingApplication
        msgParams(1) = sendingFacility
        msgParams(2) = receivingFacility
        msgParams(3) = now
        msgParams(4) = now.Ticks
        Return String.Format(ADT_MESSAGE, msgParams)
    End Function
End Class
