/// <summary>
        /// Sends HL7v2 messages using SSL.
        /// </summary>
        /// <param name="message">The message.</param>
        /// <param name="addresses">The addresses.</param>
        /// <param name="thumbprint">The thumbprint.</param>
        /// <returns>Returns a list of sent messages.</returns>
        public static IEnumerable <IMessage> Sendv2MessagesBySsl(IMessage message, IEnumerable <LlpEndpoint> addresses, string thumbprint)
        {
            var messages = new List <IMessage>();

            foreach (var endpoint in addresses)
            {
                var sender = new SslMessageSender(new Uri(endpoint.Address));

                var parser = new PipeParser();

                var parsedMessage = parser.Encode(message);

                traceSource.TraceEvent(TraceEventType.Verbose, 0, "Request: " + Environment.NewLine);
                traceSource.TraceEvent(TraceEventType.Verbose, 0, parsedMessage);

                traceSource.TraceEvent(TraceEventType.Verbose, 0, "Sending to endpoint: " + endpoint);

                var response = sender.SendAndReceive(message, thumbprint);

                var parsedResponse = parser.Encode(response);

                traceSource.TraceEvent(TraceEventType.Verbose, 0, "Response: " + Environment.NewLine);
                traceSource.TraceEvent(TraceEventType.Verbose, 0, parsedResponse);

                messages.Add(response);
            }

            return(messages);
        }
Beispiel #2
0
        private static int PORT_NUMBER = 57550;// change this to whatever your port number is
        public static void Main(String[] args)
        {
            try
            {
                // create the HL7 message
                // this OruMessageFactory class is not from NHAPI but my own wrapper class
                // check my GitHub page or see my earlier article for reference
                var oruMessage = OruMessageFactory.CreateMessage();

                // create a new MLLP client over the specified port (note this class is from NHAPI Tools)
                //Note that using higher level encodings such as UTF-16 is not recommended due to conflict with
                //MLLP wrapping characters

                var connection = new SimpleMLLPClient("localhost", PORT_NUMBER, Encoding.UTF8);

                // send the previously created HL7 message over the connection established
                var parser = new PipeParser();
                LogToDebugConsole("Sending ORU R01 message:" + "\n" + parser.Encode(oruMessage));
                var response = connection.SendHL7Message(oruMessage);

                // display the message response received from the remote party
                var responseString = parser.Encode(response);
                LogToDebugConsole("Received response:\n" + responseString);
            }
            catch (Exception e)
            {
                LogToDebugConsole($"Error occured while creating and transmitting HL7 message {e.Message}");
            }
        }
Beispiel #3
0
        /// <summary>
        /// Adds a method to check equality between to segment objects
        /// </summary>
        /// <param name="a">First segment</param>
        /// <param name="b">Second segment</param>
        /// <returns>True if the segments are equal</returns>
        public static bool IsEqual(this ISegment a, ISegment b)
        {
            bool result = true;

            string structName = a.GetStructureName();

            if (structName != b.GetStructureName())
            {
                result = false;
            }
            else
            {
                PipeParser p        = new PipeParser();
                string     aMessage = p.Encode(a.Message);
                string     bMessage = p.Encode(b.Message);

                int aIndex = aMessage.IndexOf(structName);
                int bIndex = bMessage.IndexOf(structName);

                if (aIndex == -1 || bIndex == -1)
                {
                    result = false;
                }

                if (result)
                {
                    string aStruct = aMessage.Substring(aIndex, aMessage.IndexOf("\r", aIndex) - aIndex);
                    string bStruct = bMessage.Substring(bIndex, bMessage.IndexOf("\r", bIndex) - bIndex);

                    result = (string.Compare(aStruct, bStruct) == 0);
                }
            }

            return(result);
        }
Beispiel #4
0
        public Task <string> Handle(Hl7Message message)
        {
            var ack = new ACK();
            var hl7 = _parser.Encode(ack);

            return(Task.FromResult(hl7));
        }
Beispiel #5
0
        public void Parse_UnknownMessageType_ReturnsGenericMessage(string version, Type expectedType)
        {
            // Arrange
            // a valid ORU_R01 message in which MSH-9 has been changed
            var input = $"MSH|^~\\&|LABGL1||DMCRES||19951002185200||ZZZ^ZZZ|LABGL1199510021852632|P|{version}\r"
                        + "PID|||T12345||TEST^PATIENT^P||19601002|M||||||||||123456\r"
                        + "PV1|||NER|||||||GSU||||||||E||||||||||||||||||||||||||19951002174900|19951006\r"
                        + "OBR|1||09527539437000040|7000040^ETHANOL^^^ETOH|||19951002180500|||||||19951002182500||||1793561||0952753943||19951002185200||100|F||^^^^^RT\r"
                        + "OBX||NM|7000040^ETHANOL^^^ETOH|0001|224|mg/dL|||||F|||19951002185200||182\r"
                        + "NTE|||          Reference Ranges\r" + "NTE|||          ****************\r"
                        + "NTE|||           Normal:              Negative\r"
                        + "NTE|||           Toxic Concentration: >80 mg/dL\r";

            var expectedMsh5 = "DMCRES";
            var expectedObx2 = "NM";

            var sut = new PipeParser();

            // Act
            var message = sut.Parse(input);

            sut.Encode(message);

            var terser = new Terser(message);

            // Assert
            Assert.AreEqual(expectedType, message.GetType());
            Assert.AreEqual(expectedMsh5, terser.Get("/MSH-5"));
            Assert.AreEqual(expectedObx2, terser.Get("/OBX-2"));
        }
Beispiel #6
0
        /// <summary>
        /// Validate the message
        /// </summary>
        internal static void Validate(IMessage message, ISystemConfigurationService config, List <IResultDetail> dtls, IServiceProvider context)
        {
            // Structure validation
            PipeParser pp = new PipeParser()
            {
                ValidationContext = new DefaultValidation()
            };

            try
            {
                pp.Encode(message);
            }
            catch (Exception e)
            {
                dtls.Add(new ValidationResultDetail(ResultDetailType.Error, e.Message, e));
            }

            // Validation of sending application
            try
            {
                Terser msgTerser = new Terser(message);
                object obj       = msgTerser.getSegment("MSH") as NHapi.Model.V25.Segment.MSH;
                if (obj != null)
                {
                    var msh      = obj as NHapi.Model.V25.Segment.MSH;
                    var domainId = new ComponentUtility()
                    {
                        Context = context
                    }.CreateDomainIdentifier(msh.SendingApplication, dtls);
                    if (!config.IsRegisteredDevice(domainId))
                    {
                        dtls.Add(new UnrecognizedSenderResultDetail(domainId));
                    }
                }
                else
                {
                    obj = msgTerser.getSegment("MSH") as NHapi.Model.V231.Segment.MSH;
                    if (obj != null)
                    {
                        var msh      = obj as NHapi.Model.V231.Segment.MSH;
                        var domainId = new ComponentUtility()
                        {
                            Context = context
                        }.CreateDomainIdentifier(msh.SendingApplication, dtls);
                        if (!config.IsRegisteredDevice(domainId))
                        {
                            dtls.Add(new UnrecognizedSenderResultDetail(domainId));
                        }
                    }
                    else
                    {
                        dtls.Add(new MandatoryElementMissingResultDetail(ResultDetailType.Error, "Missing MSH", "MSH"));
                    }
                }
            }
            catch (Exception e)
            {
                dtls.Add(new ResultDetail(ResultDetailType.Error, e.Message, e));
            }
        }
Beispiel #7
0
        /// Create an Ack message based on a received message///
        /// received message///
        /// Acknowlegde code///
        /// Message to be created///
        /// Created message
        public string MakeACK(string AckHead, string version, string ackCode, IMessage ackMessage)
        {
            // Create a Terser instance for the outbound message (the ACK).
            Terser terser = new Terser(ackMessage);

            // Populate outbound MSH fields using data from inbound message


            // Now set the message type, HL7 version number, acknowledgement code
            // and message control ID fields:
            string sendingApp = terser.Get("/MSH-3");
            string sendingEnv = terser.Get("/MSH-4");
            string CommunicationNameOfThisApplication     = string.Empty;
            string EnvironmentIdentifierOfThisApplication = string.Empty;

            terser.Set("/MSH-3", CommunicationNameOfThisApplication);
            terser.Set("/MSH-4", EnvironmentIdentifierOfThisApplication);
            terser.Set("/MSH-5", sendingApp);
            terser.Set("/MSH-6", sendingEnv);
            terser.Set("/MSH-7", DateTime.Now.ToString("yyyyMMddmmhh"));
            terser.Set("/MSH-9", "ACK");
            terser.Set("/MSH-12", version);
            // The ackCode should be "AA" if the message was correctly handled and "AE" if there was an error
            terser.Set("/MSA-1", ackCode == null ? "AA" : ackCode);
            terser.Set("/MSA-2", AckHead);


            return(PipeParser.Encode(ackMessage, new EncodingCharacters('|', '^', '~', '\\', '&')));
        }
Beispiel #8
0
        public void TestSpecialCharacterEntryEndingSlash()
        {
            PipeParser parser = new PipeParser();
            ORU_R01    oru    = new ORU_R01();

            oru.MSH.MessageType.MessageType.Value  = "ORU";
            oru.MSH.MessageType.TriggerEvent.Value = "R01";
            oru.MSH.EncodingCharacters.Value       = @"^~\&";
            oru.MSH.VersionID.VersionID.Value      = "2.3.1";
            oru.GetPATIENT_RESULT(0).GetORDER_OBSERVATION(0).GetOBSERVATION(0).OBX.ValueType.Value = "FT";
            oru.GetPATIENT_RESULT(0).GetORDER_OBSERVATION(0).OBR.SetIDOBR.Value = "1";
            Varies v =
                oru.GetPATIENT_RESULT(0).GetORDER_OBSERVATION(0).GetOBSERVATION(0).OBX.GetObservationValue(0);
            ST text = new ST(oru);

            text.Value = @"This\.br\is\.br\A Test~";
            v.Data     = text;


            string   encodedData = parser.Encode(oru);
            IMessage msg         = parser.Parse(encodedData);

            oru = (ORU_R01)msg;
            FT data = (FT)oru.GetPATIENT_RESULT(0).GetORDER_OBSERVATION(0).GetOBSERVATION(0).OBX.GetObservationValue(0).Data;

            Assert.AreEqual(@"This\.br\is\.br\A Test~", data.Value);
        }
        /// <summary>
        /// Unwraps the originally parsed message and tries to copy any information
        /// to it.
        /// </summary>
        /// <returns>Unwrapped message</returns>
        public IMessage Unwrap()
        {
            PipeParser p = new PipeParser();
            string     m = p.Encode(this);

            return(p.Parse(m));
        }
Beispiel #10
0
        public void CreateData(string Type)
        {
            if (Type == Utility.Constants.Patient_details_fileName)
            {
                DataAccess da             = new DataAccess();
                PipeParser parser         = new PipeParser();
                DataSet    data           = da.GetPatientData();
                string     messagePath    = Utility.Utility.GetAppConfigValues("GeneratePath") + Utility.Constants.Patient_details_fileName;
                ADT_A01    encodedMessage = new ADT_A01();
                encodedMessage.MSH.FieldSeparator.Value                   = "|";
                encodedMessage.MSH.EncodingCharacters.Value               = @"^~\&";
                encodedMessage.MSH.VersionID.VersionID.Value              = "2.5.1";
                encodedMessage.MSH.SendingApplication.NamespaceID.Value   = "NurseApp";
                encodedMessage.MSH.ReceivingApplication.NamespaceID.Value = "HIS";
                encodedMessage.MSH.MessageType.MessageStructure.Value     = "ADT_A01";
                encodedMessage.MSH.DateTimeOfMessage.Time.Value           = System.DateTime.Now.ToFileTime().ToString();
                encodedMessage.MSH.PrincipalLanguageOfMessage.Text.Value  = "EN";

                encodedMessage.PID.PatientID.IDNumber.Value   = data.Tables[0].Rows[0]["PatientId"].ToString();
                encodedMessage.PID.AdministrativeSex.Value    = data.Tables[0].Rows[0]["Gender"].ToString();
                encodedMessage.PID.DateTimeOfBirth.Time.Value = data.Tables[0].Rows[0]["DoB"].ToString();
                encodedMessage.PID.GetPatientName(0).FamilyName.Surname.Value = data.Tables[0].Rows[0]["Pateint_LastName"].ToString();
                encodedMessage.PID.GetPatientName(0).GivenName.Value          = data.Tables[0].Rows[0]["Patient_FirstName"].ToString();
                //encodedMessage.PID..Time.Value = data.Tables[0].Rows[0]["AdmittedDate"].ToString();

                string msgContent = parser.Encode(encodedMessage);
                Utility.Utility.WriteFile(messagePath, msgContent);
            }
        }
Beispiel #11
0
        public void CreateMFR_M01withZIS()
        {
            var mfr_m01 = new MFR_M01();

            PopulateMessageHeaders(mfr_m01.MSH, nameof(MFR_M01));

            var zisGroup = mfr_m01.AddZIS();

            var zis = zisGroup.ZIS;

            zis.Identifier.Identifier.Value         = "1234";
            zis.Identifier.Text.Value               = "PIR";
            zis.Identifier.NameOfCodingSystem.Value = "Hemo";

            zis.DateTimeOfCreation.TimeOfAnEvent.SetLongDateWithSecond(_fixedDate);

            zisGroup.ZIS.Procedure.Value = "TOT";

            var parser        = new PipeParser();
            var encodedString = parser.Encode(mfr_m01);
            var escapedString = Escape.unescape(encodedString, new EncodingCharacters('|', '^', '~', '\\', '&'));

            Assert.AreEqual(escapedString,
                            "MSH|^~\\&|TEST|Test Facility|VIP||20160701124512||MFR_M01|636139528780284680|P|2.4\rZIS|1234^PIR^Hemo|20160701124512|TOT\r");
        }
Beispiel #12
0
        private string CreatACKQ03(string device)
        {
            PipeParser Parser = new PipeParser();
            ACK        ack    = new ACK();

            ack.MSH.FieldSeparator.Value                 = "|";
            ack.MSH.EncodingCharacters.Value             = @"^~\&";
            ack.MSH.SendingApplication.NamespaceID.Value = GlobalVariable.Manufacturer; //仪器供应商
            ack.MSH.SendingFacility.NamespaceID.Value    = device;
            ack.MSH.DateTimeOfMessage.TimeOfAnEvent.SetLongDate(DateTime.Now);          //当前时间
            ack.MSH.MessageType.MessageType.Value   = "ACK";
            ack.MSH.MessageType.TriggerEvent.Value  = "Q03";
            ack.MSH.MessageControlID.Value          = "1";
            ack.MSH.ProcessingID.ProcessingID.Value = "P";
            ack.MSH.VersionID.VersionID.Value       = "2.3.1";
            ack.MSH.GetCharacterSet(0).Value        = GlobalVariable.SocketCode ? "ASCII" : "UTF8";

            ack.MSA.AcknowledgementCode.Value       = "AA";
            ack.MSA.MessageControlID.Value          = "1";
            ack.MSA.TextMessage.Value               = "Message accepted";
            ack.MSA.ErrorCondition.Identifier.Value = "0";

            ack.ERR.GetErrorCodeAndLocation(0).SegmentID.Value = "0";

            return(Parser.Encode(ack));
        }
        public override bool Send(IMessage msg)
        {
            bool result = true;

            EditMessageHeader(msg);

            try
            {
                PipeParser    parser     = new PipeParser();
                string        res        = SendRequest(parser.Encode(msg));
                IMessage      response   = parser.Parse(res);
                HLMessageToDB hl7message = new HLMessageToDB();
                hl7message.HL7MessageToDB(Convert.ToString(msg));
                Terser terser  = new Terser(response);
                string ackCode = terser.Get("/MSA-1");
                result = (ackCode == "AA");
            }
            catch (Exception ex)
            {
                Logger.ErrorFormat("Error in delivering message '{0}' to Http endpoint with uri '{1}'. Error: {2}", msg.GetStructureName(), serverUri, ex.Message);
                result = false;
            }

            return(result);
        }
Beispiel #14
0
        public void Obx5DataTypeIsSetFromObx2_WhenObx2IsEmptyAndDefaultOptionIsSet_DefaultTypeIsUsed()
        {
            var message =
                "MSH|^~\\&|XPress Arrival||||200610120839||ORU^R01|EBzH1711114101206|P|2.3|||AL|||ASCII\r"
                + "PID|1||1711114||Appt^Test||19720501||||||||||||001020006\r"
                + "ORC|||||F\r"
                + "OBR|1|||ehipack^eHippa Acknowlegment|||200610120839|||||||||00002^eProvider^Electronic|||||||||F\r"
                + "OBX|1||||STValue||||||F\r";

            var expectedEncodedMessage =
                "MSH|^~\\&|XPress Arrival||||200610120839||ORU^R01|EBzH1711114101206|P|2.3|||AL|||ASCII\r"
                + "PID|1||1711114||Appt^Test||19720501||||||||||||001020006\r"
                + "ORC|||||F\r"
                + "OBR|1|||ehipack^eHippa Acknowlegment|||200610120839|||||||||00002^eProvider^Electronic|||||||||F\r"
                + "OBX|1|ST|||STValue||||||F\r";

            var parser  = new PipeParser();
            var options = new ParserOptions {
                DefaultObx2Type = "ST"
            };

            var parsed         = parser.Parse(message, options);
            var encodedMessage = parser.Encode(parsed);

            Assert.AreEqual(expectedEncodedMessage, encodedMessage);
        }
Beispiel #15
0
        public void TestSpecialCharacterEntry()
        {
            var parser = new PipeParser();
            var oru    = new ORU_R01();

            oru.MSH.MessageType.MessageType.Value  = "ORU";
            oru.MSH.MessageType.TriggerEvent.Value = "R01";
            oru.MSH.EncodingCharacters.Value       = @"^~\&";
            oru.MSH.VersionID.VersionID.Value      = "2.3.1";
            oru.GetPATIENT_RESULT(0).GetORDER_OBSERVATION(0).GetOBSERVATION(0).OBX.ValueType.Value = "FT";
            oru.GetPATIENT_RESULT(0).GetORDER_OBSERVATION(0).OBR.SetIDOBR.Value = "1";
            var v =
                oru.GetPATIENT_RESULT(0).GetORDER_OBSERVATION(0).GetOBSERVATION(0).OBX.GetObservationValue(0);
            var text = new ST(oru);

            text.Value = @"This\.br\is\.br\A Test";
            v.Data     = text;

            var encodedData = parser.Encode(oru);

            Console.WriteLine(encodedData);
            var msg = parser.Parse(encodedData);

            Console.WriteLine(msg.GetStructureName());
            oru = (ORU_R01)msg;
            var data = (FT)oru.GetPATIENT_RESULT(0).GetORDER_OBSERVATION(0).GetOBSERVATION(0).OBX.GetObservationValue(0).Data;

            Assert.AreEqual(@"This\.br\is\.br\A Test", data.Value);
        }
        public void WhenMessageParsedAndEscaped_ThenEncodedAndUnescaped_MessageIsIdentical_Concurrent()
        {
            // Arrange
            var expected
                = "MSH|^~\\&|ULTRA|TML|OLIS|OLIS|200911231509||ORU^R01|5951|T|2.3\r" +
                  "PID|||7005728^^^TML^MR||LEIGHTON^RACHEL^DIAMOND||19310313|F|||200 ANYWHERE ST^^TORONTO^ON^M6H 2T9||(416)888-8888||||||1014071185^KR\r" +
                  "PV1|1||OLIS||||OLIST^BLAKE^DONALD^THOR^^^^^921379^^^^OLIST|||||||||^N\r" +
                  "ORC|RE||T09-106575-CHO-0^^OLIS_Site_ID^ISO|||||||||OLIST^BLAKE^DONALD^THOR^^^^L^921379\r" +
                  "OBR|0||T09-106575-CHO-0^^OLIS_Site_ID^ISO|CHO^CHOLESTEROL (SERUM)^HL79901 literal|||200911231455|||||||200911231455||OLIST^BLAKE^DONALD^THOR^^^^L^921379||10015716|10015716|T09-106575|MOHLTC|200911231509||B1|F||1^^^200911231455^^R\r" +
                  "NTE|1|L|\\.br\\                  Lipid - Target Levels for Treatment \\.br\\\\.br\\  ****************************************************************\\.br\\  \\F\\  Risk   \\F\\                  \\F\\                                 \\F\\\\.br\\  \\F\\ Level   \\F\\ 10-year CAD risk \\F\\         Recommendations         \\F\\\\.br\\  \\F\\---------\\F\\------------------\\F\\---------------------------------\\F\\\\.br\\  \\F\\         \\F\\                  \\F\\Treatment targets:               \\F\\\\.br\\  \\F\\High*    \\F\\      >=20%       \\F\\ Primary:   LDL-C    <2.0 mmol/L \\F\\\\.br\\  \\F\\         \\F\\                  \\F\\ Secondary: TC/HDL-C <4.0        \\F\\\\.br\\  \\F\\---------\\F\\------------------\\F\\---------------------------------\\F\\\\.br\\  \\F\\         \\F\\                  \\F\\Treat when:                      \\F\\\\.br\\  \\F\\Moderate \\F\\    10 - 19 %     \\F\\            LDL-C    >=3.5 mmol/L\\F\\\\.br\\  \\F\\         \\F\\                  \\F\\         or TC/HDL-C >=5.0       \\F\\\\.br\\  \\F\\---------\\F\\------------------\\F\\---------------------------------\\F\\\\.br\\  \\F\\         \\F\\                  \\F\\Treat when:                      \\F\\\\.br\\  \\F\\Low      \\F\\      <10%        \\F\\            LDL-C    >=5.0 mmol/L\\F\\\\.br\\  \\F\\         \\F\\                  \\F\\         or TC/HDL-C >=6.0       \\F\\\\.br\\****************************************************************\\.br\\  Notes:\\.br\\  *  10-year coronary artery disease (CAD) risk is accessed by\\.br\\     Framingham risk estimate tables.\\.br\\  *  *High risk includes CAD, peripheral artery disease, cerebro-\\.br\\     vascular disease (CVD) and most patients with chronic kidney\\.br\\     disease or established diabetes mellitus.\\.br\\  *  The patient must have been fasting for at least 12 hours prior\\.br\\     to taking ablood sample.\\.br\\  *  Calculation:  LDL-C (mmol/L) = Chol - (HDL-C + 0.46 x TG).\\.br\\     Calculation is invalid if TG exceed 4.5 mmol/L.\\.br\\  Ref:  McPherson R et al. Can J Cardiol. 2006 Sep;22(11):913-27\r" +
                  "OBX|1|NM|Z049107^Cholesterol-serum^L||2.30|mmol/L|||||F|||200911231508|STP\r" +
                  "OBX|2|FT|Z101068^Tech Comment^L||Lab STP||||||F|||200911231508|STP\r";

            var parser = new PipeParser {
                ValidationContext = new DefaultValidation()
            };

            ORU_R01 oruR01;
            string  actual;

            Parallel.For(0, 10, _ =>
            {
                // Arrange
                // Act
                oruR01 = (ORU_R01)parser.Parse(expected);
                actual = parser.Encode(oruR01);

                // Assert
                Assert.AreEqual(expected, actual);
            });
        }
        public void CreateBlankMessage()
        {
            var a01       = new ADT_A01();
            var birthDate = new DateTime(1980, 4, 1);

            a01.MSH.SendingApplication.UniversalID.Value   = "ThisOne";
            a01.MSH.ReceivingApplication.UniversalID.Value = "COHIE";
            a01.PID.PatientIDExternalID.ID.Value           = "123456";
            a01.PV1.GetAttendingDoctor(0).FamilyName.Value = "Jones";
            a01.PV1.GetAttendingDoctor(0).GivenName.Value  = "Mike";
            a01.PID.DateOfBirth.TimeOfAnEvent.SetShortDate(birthDate);

            var parser = new PipeParser();

            var pipeMessage = parser.Encode(a01);

            Assert.IsNotNull(pipeMessage);

            var test    = parser.Parse(pipeMessage);
            var a01Test = test as ADT_A01;

            Assert.IsNotNull(a01Test);

            Assert.AreEqual(a01Test.MSH.ReceivingApplication.UniversalID.Value, "COHIE");
            Assert.AreEqual(a01Test.PID.PatientIDExternalID.ID.Value, "123456");

            Assert.AreEqual(a01Test.PID.DateOfBirth.TimeOfAnEvent.GetAsDate().ToShortDateString(), birthDate.ToShortDateString());

            Assert.AreEqual(a01Test.PV1.GetAttendingDoctor(0).FamilyName.Value, "Jones");
            Assert.AreEqual(a01Test.MSH.MessageType.MessageType.Value, "ADT");
            Assert.AreEqual(a01Test.MSH.MessageType.TriggerEvent.Value, "A01");
        }
Beispiel #18
0
        public void TestValidHl7Data()
        {
            PipeParser parser = new PipeParser();
            ORU_R01    oru    = new ORU_R01();

            oru.MSH.MessageType.MessageType.Value  = "ORU";
            oru.MSH.MessageType.TriggerEvent.Value = "R01";
            oru.MSH.EncodingCharacters.Value       = @"^~\&";
            oru.MSH.VersionID.VersionID.Value      = "2.3.1";
            oru.GetPATIENT_RESULT(0).GetORDER_OBSERVATION(0).GetOBSERVATION(0).OBX.ValueType.Value = "FT";
            oru.GetPATIENT_RESULT(0).GetORDER_OBSERVATION(0).OBR.SetIDOBR.Value = "1";
            Varies v =
                oru.GetPATIENT_RESULT(0).GetORDER_OBSERVATION(0).GetOBSERVATION(0).OBX.GetObservationValue(0);
            ST text = new ST(oru);

            text.Value = @"Th&is\.br\is\.br\A T|est\";
            v.Data     = text;


            string encodedData = parser.Encode(oru);

            //Console.WriteLine(encodedData);
            string[] segs   = encodedData.Split('\r');
            string[] fields = segs[2].Split('|');
            string   data   = fields[5];

            Assert.AreEqual(@"Th\T\is\.br\is\.br\A T\F\est\E\", data);
        }
Beispiel #19
0
        private string ParseHL7Message(string message)
        {
            IMessage   ackMessage = null;
            string     result     = string.Empty;
            PipeParser parser     = new PipeParser();

            try
            {
                IMessage hl7Message = parser.Parse(message);

                string errorCode    = "AA";
                string errorMessage = null;
                if (!ProcessMessage(hl7Message, out errorMessage))
                {
                    errorCode = "AE";
                }

                // Create a response message
                ackMessage = CreateACK(hl7Message, errorCode, errorMessage);
                result     = parser.Encode(ackMessage);
            }
            catch (HL7Exception ex)
            {
                Console.WriteLine("Error while parsing: {0}", ex.Message);
            }

            return(result);
        }
Beispiel #20
0
        public static void Main(string[] args)
        {
            try
            {
                // instantiate a PipeParser, which handles the "traditional or default encoding"
                var ourPipeParser = new PipeParser();
                // parse the string format message into a Java message object
                var hl7Message = ourPipeParser.Parse(File.ReadAllText(OruR01MessageWithBase64EncodedPdfReportIncluded, Encoding.UTF8));

                //cast to message to an ORU R01 message in order to get access to the message data
                var oruR01Message = hl7Message as ORU_R01;
                if (oruR01Message != null)
                {
                    // Display the updated HL7 message using Pipe delimited format
                    LogToDebugConsole("Parsed HL7 Message:");
                    LogToDebugConsole(ourPipeParser.Encode(hl7Message));

                    var encapsulatedPdfDataInBase64Format = ExtractEncapsulatedPdfDataInBase64Format(oruR01Message);

                    //if no encapsulated data was found, you can cease operation
                    if (encapsulatedPdfDataInBase64Format == null)
                    {
                        return;
                    }

                    var extractedPdfByteData = GetBase64DecodedPdfByteData(encapsulatedPdfDataInBase64Format);

                    WriteExtractedPdfByteDataToFile(extractedPdfByteData);
                }
            }
            catch (Exception e)
            {
                LogToDebugConsole($"Error occured during Order Response PDF extraction operation -> {e.StackTrace}");
            }
        }
Beispiel #21
0
        /// <summary>
        /// Encode the specified message
        /// </summary>
        public static String EncodeMessage(IMessage response, string originalVersion)
        {
            // Rewrite back to original version
            (response.GetStructure("MSH") as MSH).VersionID.VersionID.Value = originalVersion.Trim();
            var pp = new PipeParser();

            return(pp.Encode(response));
        }
        /// <summary>
        /// Send a HL7 message
        /// </summary>
        /// <param name="message">Message to send</param>
        /// <returns>Reply message</returns>
        public IMessage SendHL7Message(IMessage message)
        {
            PipeParser parser = new PipeParser();
            string msg = parser.Encode(message);

            string reply = SendHL7Message(msg);
            return parser.Parse(reply);
        }
        public string GetAcknowlegement(IMessage message)
        {
            var ackMessage = (ACK)MakeACK(message, "AA");

            var parser = new PipeParser();

            return(parser.Encode(ackMessage));
        }
Beispiel #24
0
        private static void TerserMessageHL7()
        {
            var stringMessage = File.ReadAllText(
                @"N:\hl7-master\hl7-master\Test HL7 Message Files\FileWithObservationResultMessage.txt");

            // instantiate a PipeParser, which handles the normal HL7 encoding
            var pipeParser = new PipeParser();

            // parse the message string into a message object
            var orderResultHl7Message = pipeParser.Parse(stringMessage);

            // create a terser object instance by wrapping it around the message object
            var terser = new Terser(orderResultHl7Message);

            var terserHelper = new TerserHelper(terser);

            var terserExpression = "/.MSH-6";
            var dataRetrieved    = terserHelper.GetData(terserExpression);

            LogToDebugConsole($"Field 6 of MSH segment using expression '{terserExpression}' was '{dataRetrieved}'");

            terserExpression = "/.PID-5-2"; // notice the /. to indicate relative position to root node
            dataRetrieved    = terserHelper.GetData(terserExpression);
            LogToDebugConsole($"Field 5 and Component 2 of the PID segment using expression '{terserExpression}' was {dataRetrieved}'");

            terserExpression = "/.*ID-5-2";
            dataRetrieved    = terserHelper.GetData(terserExpression);
            LogToDebugConsole($"Field 5 and Component 2 of the PID segment using wildcard-based expression '{terserExpression}' was '{dataRetrieved}'");

            terserExpression = "/.P?D-5-2";
            dataRetrieved    = terserHelper.GetData(terserExpression);
            LogToDebugConsole($"Field 5 and Component 2 of the PID segment using another wildcard-based expression '{terserExpression}' was '{dataRetrieved}'");


            terserExpression = "/.PV1-9(1)"; // note: field repetitions are zero-indexed
            dataRetrieved    = terserHelper.GetData(terserExpression);
            LogToDebugConsole($"2nd repetition of Field 9 and Component 1 for it in the PV1 segment using expression '{terserExpression}' was '{dataRetrieved}'");

            terserExpression = "/RESPONSE/PATIENT/PID-5-1";
            dataRetrieved    = terserHelper.GetData(terserExpression);
            LogToDebugConsole($"Terser expression  '{terserExpression}' yielded '{dataRetrieved}'");

            terserExpression = "/RESPONSE/PATIENT/VISIT/PV1-9-3";
            dataRetrieved    = terserHelper.GetData(terserExpression);
            LogToDebugConsole($"Terser expression '{terserExpression}' yielded '{dataRetrieved}'");

            terserExpression = "/RESPONSE/ORDER_OBSERVATION(0)/ORC-12-3";
            dataRetrieved    = terserHelper.GetData(terserExpression);
            LogToDebugConsole($"Terser expression '{terserExpression}' yielded '{dataRetrieved}'");

            //let us now try a set operation using the terser
            terserExpression = "/.OBSERVATION(0)/NTE-3";
            terserHelper.SetData(terserExpression, "This is our override value using the setter");
            LogToDebugConsole("Set the data for second repetition of the NTE segment and its Third field..");

            LogToDebugConsole("\nWill display our modified message below \n");
            LogToDebugConsole(pipeParser.Encode(orderResultHl7Message));
        }
Beispiel #25
0
        public string Encode(IHL7Message hl7Message, HL7Encoding encoding, bool validate)
        {
            if (HL7Encoding.XML == encoding)
            {
                return(xmlParser.Encode(hl7Message.Message));
            }

            return(pipeParser.Encode(hl7Message.Message));
        }
Beispiel #26
0
        /// <summary>
        /// Validates a message.
        /// </summary>
        /// <param name="message">The message to be validated.</param>
        /// <param name="details">The result details for storing the message validation results.</param>
        /// <returns>Returns a list of validation results.</returns>
        public static List <IResultDetail> Validate(IMessage message, List <IResultDetail> details)
        {
            var pipeParser = new PipeParser()
            {
                ValidationContext = new DefaultValidation()
            };

            try
            {
                pipeParser.Encode(message);
            }
            catch (Exception e)
            {
                details.Add(new ValidationResultDetail(ResultDetailType.Error, e.Message, e));
            }

            try
            {
                var terser = new Terser(message);

                var msh = terser.getSegment("MSH");

                if (msh is MSH)
                {
                    var v231Msh = (MSH)msh;

                    var result = ConvertAssigningAuthority(v231Msh.SendingApplication, details);

                    if (result == null)
                    {
                        details.Add(new UnrecognizedSenderResultDetail(ResultDetailType.Error, v231Msh.SendingApplication.NamespaceID.Value, "MSH^3"));
                    }
                }
                else if (msh is NHapi.Model.V25.Segment.MSH)
                {
                    var v25Msh = (NHapi.Model.V25.Segment.MSH)msh;

                    var result = ConvertAssigningAuthority(v25Msh.SendingApplication, details);

                    if (result == null)
                    {
                        details.Add(new UnrecognizedSenderResultDetail(ResultDetailType.Error, v25Msh.SendingApplication.NamespaceID.Value, "MSH^3"));
                    }
                }
                else
                {
                    details.Add(new MandatoryElementMissingResultDetail(ResultDetailType.Error, "Missing MSH", "MSH"));
                }
            }
            catch (Exception e)
            {
                details.Add(new ResultDetail(ResultDetailType.Error, e.Message, e));
            }

            return(details);
        }
Beispiel #27
0
        /// <summary>
        /// Adds a method to check equality between to message objects
        /// </summary>
        /// <param name="a">First message</param>
        /// <param name="b">Second message</param>
        /// <param name="completeCompare">Besides checking the structure name, version, event type and message ID, if this is true the complete textual version of the two messages will be compared.</param>
        /// <returns>True if the messages are equal</returns>
        public static bool IsEqual(this IMessage a, IMessage b, bool completeCompare)
        {
            bool result = true;

            if (a.GetStructureName() != b.GetStructureName())
            {
                result = false;
            }

            if (result && (a.Version != b.Version))
            {
                result = false;
            }

            if (result)
            {
                Terser terserA = new Terser(a);
                Terser terserB = new Terser(b);

                string eventTypeA = terserA.Get("MSH-9-2");
                string eventTypeB = terserB.Get("MSH-9-2");
                result = (eventTypeA == eventTypeB);

                if (result)
                {
                    string messageIdA = terserA.Get("MSH-10-1");
                    string messageIdB = terserB.Get("MSH-10-1");
                    result = (messageIdA == messageIdB);
                }
            }

            if (result && completeCompare)
            {
                PipeParser p    = new PipeParser();
                string     msgA = p.Encode(a);
                string     msgB = p.Encode(b);

                result = (string.Compare(msgA, msgB) == 0);
            }

            return(result);
        }
    static void Main(string[] args)
    {
        EncodingCharacters enchars    = new EncodingCharacters('|', "^~\\&");
        IModelClassFactory theFactory = new DefaultModelClassFactory();

        NHapi.Model.V251.Segment.RXA rxa = new NHapi.Model.V251.Segment.RXA(new VXU_V04(theFactory), theFactory);
        IType[] t = rxa.GetSubstanceManufacturerName(0).Components;
        SetRXA(t);
        Debug.Print(PipeParser.Encode(rxa, enchars));
        Console.Read();
    }
        public void TestMSH3Set()
        {
            ADT_A01 a01 = new ADT_A01();

            a01.MSH.SendingApplication.UniversalID.Value = "TEST";

            PipeParser parser = new PipeParser();
            string     hl7    = parser.Encode(a01);

            string[] data = hl7.Split('|');
            Assert.AreEqual("ADT^A01", data[8]);
        }
Beispiel #30
0
        private static void SendMessageHL7()
        {
            // create the HL7 message
            // this AdtMessageFactory class is not from NHAPI but my own wrapper
            LogToDebugConsole("Creating ADT A01 message...");
            var adtMessage = AdtMessageFactory.CreateMessage("A01");

            // create a new MLLP client over the specified port (note this class is from NHAPI Tools)
            //Note that using higher level encodings such as UTF-16 is not recommended due to conflict with
            //MLLP wrapping characters
            var connection = new SimpleMLLPClient("localhost", PORT_NUMBER, Encoding.UTF8);

            var parser = new PipeParser();

            LogToDebugConsole("Sending message:" + "\n" + parser.Encode(adtMessage));
            var response = connection.SendHL7Message(adtMessage);

            var responseString = parser.Encode(response);

            LogToDebugConsole("Received response:\n" + responseString);
        }