예제 #1
0
        public void ParseADT_A08()
        {
            //this is some fictive data
            string message = @"MSH|^~\&|SUNS1|OVI02|AZIS|CMD|200606221348||ADT^A08|1049691900|P|2.2
EVN|A08|200601060800
PID||8912716038^^^51276|0216128^^^51276||BARDOUN^LEA SACHA||19981201|F|||AVENUE FRANC GOLD 8^^LUXEMBOURGH^^6780^150||053/12456789||N|S|||99120162652||^^^|||||B
PV1||O|^^|U|||07632^MORTELO^POL^^^DR.|^^^^^|||||N||||||0200001198
PV2|||^^AZIS||N|||200601060800
IN1|0001|2|314000|||||||||19800101|||1|BARDOUN^LEA SACHA|1|19981201|AVENUE FRANC GOLD 8^^LUXEMBOURGH^^6780^150|||||||||||||||||
ZIN|0164652011399|0164652011399|101|101|45789^Broken bone";


            /*	**********************************************************
             *  YOU NEED TO ADD THIS CHAINED CONSTRUCTOR TO THE PiperParser CLASS!!!
             *
             *  public PipeParser(IModelClassFactory theFactory) : base(theFactory)
             *	{
             *	}
             *
             *  ***********************************************************/
            NHapi.Base.Parser.PipeParser parser = new NHapi.Base.Parser.PipeParser();

            NHapi.Base.Model.IMessage m = parser.Parse(message, NHapi.Model.V22_ZSegments.Constants.VERSION);

            Assert.IsNotNull(m);

            Console.WriteLine("Type: " + m.GetType().ToString());

            NHapi.Model.V22_ZSegments.Message.ADT_A08 adtA08 =
                m as NHapi.Model.V22_ZSegments.Message.ADT_A08;
            //verify some Z segment data
            Assert.AreEqual("45789", adtA08.ZIN.AccidentData.Id.Value);
            Assert.AreEqual("Broken bone", adtA08.ZIN.AccidentData.Text.Value);
        }
예제 #2
0
        public void ParseADT_A08()
        {
            //this is some fictive data
            string message = @"MSH|^~\&|SUNS1|OVI02|AZIS|CMD|200606221348||ADT^A08|1049691900|P|2.2
            EVN|A08|200601060800
            PID||8912716038^^^51276|0216128^^^51276||BARDOUN^LEA SACHA||19981201|F|||AVENUE FRANC GOLD 8^^LUXEMBOURGH^^6780^150||053/12456789||N|S|||99120162652||^^^|||||B
            PV1||O|^^|U|||07632^MORTELO^POL^^^DR.|^^^^^|||||N||||||0200001198
            PV2|||^^AZIS||N|||200601060800
            IN1|0001|2|314000|||||||||19800101|||1|BARDOUN^LEA SACHA|1|19981201|AVENUE FRANC GOLD 8^^LUXEMBOURGH^^6780^150|||||||||||||||||
            ZIN|0164652011399|0164652011399|101|101|45789^Broken bone";

            /*	**********************************************************
             * 	YOU NEED TO ADD THIS CHAINED CONSTRUCTOR TO THE PiperParser CLASS!!!
             *
             * 	public PipeParser(IModelClassFactory theFactory) : base(theFactory)
             *	{
             *	}
             *
             * 	***********************************************************/
            NHapi.Base.Parser.PipeParser parser = new NHapi.Base.Parser.PipeParser();

            NHapi.Base.Model.IMessage m = parser.Parse(message, NHapi.Model.V22_ZSegments.Constants.VERSION);

            Assert.IsNotNull(m);

            Console.WriteLine("Type: " + m.GetType().ToString());

            NHapi.Model.V22_ZSegments.Message.ADT_A08 adtA08 =
                m as NHapi.Model.V22_ZSegments.Message.ADT_A08;
            //verify some Z segment data
            Assert.AreEqual("45789", adtA08.ZIN.AccidentData.Id.Value);
            Assert.AreEqual("Broken bone", adtA08.ZIN.AccidentData.Text.Value);
        }
예제 #3
0
        public HL7Parser2X(string HL7Message)
        {
            NHapi.Base.Parser.XMLParser xmlp = new NHapi.Base.Parser.DefaultXMLParser();
            //NHapi.Base.Model.IMessage imess =  xmlp.Parse(HL7Message);

            NHapi.Base.Parser.PipeParser pp    = new NHapi.Base.Parser.PipeParser();
            NHapi.Base.Model.IMessage    imess = pp.Parse(HL7Message, "2.3");

            NHapi.Model.V23.Message.ORU_R01 orm;
            orm = imess as NHapi.Model.V23.Message.ORU_R01;

            XmlDocument MessageXML = new XmlDocument();

            if (orm != null)
            {
                MessageXML = xmlp.EncodeDocument(orm);
            }
            NHapi.Base.Model.IStructure[] seg = imess.GetAll("MSH");
            report.ReportXML = MessageXML;

            //testFunction(MessageXML);


            report.PatientID   = GetPatientID(report.ReportXML);
            report.Patientname = GetPatientName(report.ReportXML);
            string date = string.Empty;

            report.ReportDateTime  = GetDateTime(GetStudyDate(report.ReportXML), "yyyyMMddHHmm", out date);
            report.DOB             = GetDateTime(GetPatientDOB(report.ReportXML), "yyyyMMdd", out date);
            report.AccessionNumber = GetAccessioNnumber(report.ReportXML);
        }
예제 #4
0
        /// <summary>
        /// Receive and process message
        /// </summary>
        private void ReceiveMessage(object client)
        {
            TcpClient     tcpClient = client as TcpClient;
            NetworkStream stream    = tcpClient.GetStream();

            try
            {
                // Now read to a string
                NHapi.Base.Parser.PipeParser parser = new NHapi.Base.Parser.PipeParser();

                StringBuilder messageData = new StringBuilder();
                byte[]        buffer      = new byte[1024];
                while (stream.DataAvailable)
                {
                    int br = stream.Read(buffer, 0, 1024);
                    messageData.Append(Encoding.ASCII.GetString(buffer, 0, br));
                }

                var message        = parser.Parse(messageData.ToString());
                var localEp        = tcpClient.Client.LocalEndPoint as IPEndPoint;
                var remoteEp       = tcpClient.Client.RemoteEndPoint as IPEndPoint;
                Uri localEndpoint  = new Uri(String.Format("tcp://{0}:{1}", localEp.Address, localEp.Port));
                Uri remoteEndpoint = new Uri(String.Format("tcp://{0}:{1}", remoteEp.Address, remoteEp.Port));
                var messageArgs    = new Hl7MessageReceivedEventArgs(message, localEndpoint, remoteEndpoint, DateTime.Now);
                HL7OperationContext.Current = new HL7OperationContext(messageArgs);

                this.MessageReceived(this, messageArgs);

                // Send the response back
                StreamWriter writer = new StreamWriter(stream);
                if (messageArgs.Response != null)
                {
                    writer.Write(parser.Encode(messageArgs.Response));
                    writer.Flush();
                }
            }
            catch (Exception e)
            {
                this.m_traceSource.TraceEvent(EventLevel.Error, e.ToString());
                // TODO: NACK
            }
            finally
            {
                stream.Close();
                HL7OperationContext.Current = null;
            }
        }
예제 #5
0
        /// <summary>
        /// Receive a message
        /// </summary>
        protected override void OnReceiveMessage(object client)
        {
            TcpClient tcpClient = client as TcpClient;
            SslStream stream    = new SslStream(tcpClient.GetStream(), false, new RemoteCertificateValidationCallback(RemoteCertificateValidation));

            try
            {
                // Setup local and remote receive endpoint data for auditing
                var localEp        = tcpClient.Client.LocalEndPoint as IPEndPoint;
                var remoteEp       = tcpClient.Client.RemoteEndPoint as IPEndPoint;
                Uri localEndpoint  = new Uri(String.Format("sllp://{0}:{1}", localEp.Address, localEp.Port));
                Uri remoteEndpoint = new Uri(String.Format("sllp://{0}:{1}", remoteEp.Address, remoteEp.Port));
                Trace.TraceInformation("Accepted TCP connection from {0} > {1}", remoteEndpoint, localEndpoint);

                stream.AuthenticateAsServer(this.m_configuration.ServerCertificate, this.m_configuration.EnableClientCertNegotiation, System.Security.Authentication.SslProtocols.Tls, this.m_configuration.CheckCrl);

                // Now read to a string
                NHapi.Base.Parser.PipeParser parser = new NHapi.Base.Parser.PipeParser();

                DateTime lastReceive = DateTime.Now;

                while (this.m_timeout == TimeSpan.Zero || DateTime.Now.Subtract(lastReceive) < this.m_timeout)
                {
                    int llpByte = 0;
                    // Read LLP head byte
                    try
                    {
                        llpByte = stream.ReadByte();
                    }
                    catch (SocketException)
                    {
                        break;
                    }

                    if (llpByte != START_TX) // first byte must be HT
                    {
                        Trace.TraceWarning("Invalid LLP First Byte expected 0x{0:x} got 0x{1:x} from {2}", START_TX, llpByte, remoteEndpoint);
                        break;
                    }
//                        throw new InvalidOperationException("Invalid LLP First Byte");

                    // Standard stream stuff, read until the stream is exhausted
                    StringBuilder messageData = new StringBuilder();
                    byte[]        buffer = new byte[1024];
                    bool          receivedEOF = false, scanForCr = false;

                    while (!receivedEOF)
                    {
                        int br = stream.Read(buffer, 0, 1024);
                        messageData.Append(System.Text.Encoding.UTF8.GetString(buffer, 0, br));

                        // Need to check for CR?
                        if (scanForCr)
                        {
                            receivedEOF = buffer[0] == END_TXNL;
                        }
                        else
                        {
                            // Look for FS
                            int fsPos = Array.IndexOf(buffer, END_TX);

                            if (fsPos == -1) // not found
                            {
                                continue;
                            }
                            else if (fsPos < buffer.Length - 1) // more room to read
                            {
                                receivedEOF = buffer[fsPos + 1] == END_TXNL;
                            }
                            else
                            {
                                scanForCr = true; // Cannot check the end of message for CR because there is no more room in the message buffer
                            }
                            // so need to check on the next loop
                        }

                        // TODO: Timeout for this
                    }


                    // Use the nHAPI parser to process the data
                    Hl7MessageReceivedEventArgs messageArgs = null;
                    try
                    {
                        var message = parser.Parse(messageData.ToString());

#if DEBUG
                        Trace.TraceInformation("Received message from sllp://{0} : {1}", tcpClient.Client.RemoteEndPoint, messageData.ToString());
#endif


                        messageArgs = new Hl7MessageReceivedEventArgs(message, localEndpoint, remoteEndpoint, DateTime.Now);

                        // Call any bound event handlers that there is a message available
                        OnMessageReceived(messageArgs);
                    }
                    finally
                    {
                        // Send the response back
                        using (MemoryStream memoryWriter = new MemoryStream())
                        {
                            using (StreamWriter streamWriter = new StreamWriter(memoryWriter))
                            {
                                memoryWriter.Write(new byte[] { START_TX }, 0, 1); // header
                                if (messageArgs != null && messageArgs.Response != null)
                                {
                                    var strMessage = parser.Encode(messageArgs.Response);
#if DEBUG
                                    Trace.TraceInformation("Sending message to sllp://{0} : {1}", tcpClient.Client.RemoteEndPoint, strMessage);
#endif
                                    // Since nHAPI only emits a string we just send that along the stream
                                    streamWriter.Write(strMessage);
                                    streamWriter.Flush();
                                }
                                memoryWriter.Write(new byte[] { END_TX, END_TXNL }, 0, 2); // Finish the stream with FSCR
                                stream.Write(memoryWriter.ToArray(), 0, (int)memoryWriter.Position);
                                stream.Flush();
                            }
                        }

                        lastReceive = DateTime.Now; // Update the last receive time so the timeout function works
                    }

                    if (this.m_timeout == TimeSpan.Zero)
                    {
                        break;
                    }
                }
            }
            catch (AuthenticationException e)
            {
                // Trace authentication error
                AuditData ad = new AuditData(
                    DateTime.Now,
                    ActionType.Execute,
                    OutcomeIndicator.MinorFail,
                    EventIdentifierType.ApplicationActivity,
                    new CodeValue("110113", "DCM")
                {
                    DisplayName = "Security Alert"
                }
                    );
                ad.Actors = new List <AuditActorData>()
                {
                    new AuditActorData()
                    {
                        NetworkAccessPointId   = Dns.GetHostName(),
                        NetworkAccessPointType = SVC.Core.DataTypes.NetworkAccessPointType.MachineName,
                        UserName        = Environment.UserName,
                        UserIsRequestor = false
                    },
                    new AuditActorData()
                    {
                        NetworkAccessPointId   = String.Format("sllp://{0}", tcpClient.Client.RemoteEndPoint.ToString()),
                        NetworkAccessPointType = NetworkAccessPointType.MachineName,
                        UserIsRequestor        = true
                    }
                };
                ad.AuditableObjects = new List <AuditableObject>()
                {
                    new AuditableObject()
                    {
                        Type       = AuditableObjectType.SystemObject,
                        Role       = AuditableObjectRole.SecurityResource,
                        IDTypeCode = AuditableObjectIdType.Uri,
                        ObjectId   = String.Format("sllp://{0}", this.m_listener.LocalEndpoint)
                    }
                };

                var auditService = ApplicationContext.CurrentContext.GetService(typeof(IAuditorService)) as IAuditorService;
                if (auditService != null)
                {
                    auditService.SendAudit(ad);
                }
                Trace.TraceError(e.ToString());
            }
            catch (Exception e)
            {
                Trace.TraceError(e.ToString());
                // TODO: NACK
            }
            finally
            {
                stream.Close();
                tcpClient.Close();
            }
        }
예제 #6
0
        /// <summary>
        /// Receive and process message
        /// </summary>
        protected virtual void OnReceiveMessage(object client)
        {
            TcpClient     tcpClient = client as TcpClient;
            NetworkStream stream    = tcpClient.GetStream();

            try
            {
                // Now read to a string
                NHapi.Base.Parser.PipeParser parser = new NHapi.Base.Parser.PipeParser();

                DateTime lastReceive = DateTime.Now;

                while (DateTime.Now.Subtract(lastReceive) < this.m_timeout)
                {
                    if (!stream.DataAvailable)
                    {
                        Thread.Sleep(10);
                        continue;
                    }

                    // Read LLP head byte
                    int llpByte = stream.ReadByte();
                    if (llpByte != START_TX)                     // first byte must be HT
                    {
                        throw new InvalidOperationException("Invalid LLP First Byte");
                    }

                    // Standard stream stuff, read until the stream is exhausted
                    StringBuilder messageData = new StringBuilder();
                    byte[]        buffer = new byte[1024];
                    bool          receivedEOF = false, scanForCr = false;

                    while (!receivedEOF)
                    {
                        if (DateTime.Now.Subtract(lastReceive) > this.m_timeout)
                        {
                            throw new TimeoutException("Data not received in the specified amount of time. Increase the timeout or check the network connection");
                        }

                        if (!stream.DataAvailable)
                        {
                            Thread.Sleep(10);
                            continue;
                        }

                        int br = stream.Read(buffer, 0, 1024);
                        messageData.Append(System.Text.Encoding.UTF8.GetString(buffer, 0, br));

                        // Need to check for CR?
                        if (scanForCr)
                        {
                            receivedEOF = buffer[0] == END_TXNL;
                        }
                        else
                        {
                            // Look for FS
                            int fsPos = Array.IndexOf(buffer, (byte)END_TX);

                            if (fsPos == -1)                             // not found
                            {
                                continue;
                            }
                            else if (fsPos < buffer.Length - 1)                             // more room to read
                            {
                                receivedEOF = buffer[fsPos + 1] == END_TXNL;
                            }
                            else
                            {
                                scanForCr = true;                                 // Cannot check the end of message for CR because there is no more room in the message buffer
                            }
                            // so need to check on the next loop
                        }
                    }

                    // Use the nHAPI parser to process the data
                    Hl7MessageReceivedEventArgs messageArgs = null;

                    try
                    {
                        // Setup local and remote receive endpoint data for auditing
                        var localEp        = tcpClient.Client.LocalEndPoint as IPEndPoint;
                        var remoteEp       = tcpClient.Client.RemoteEndPoint as IPEndPoint;
                        Uri localEndpoint  = new Uri(String.Format("llp://{0}:{1}", localEp.Address, localEp.Port));
                        Uri remoteEndpoint = new Uri(String.Format("llp://{0}:{1}", remoteEp.Address, remoteEp.Port));

#if DEBUG
                        Trace.TraceInformation("Received message from llp://{0}:{1} : {2}", remoteEp.Address, remoteEp.Port, messageData);
#endif

                        // HACK: nHAPI doesn't like URLs ... Will fix this later
                        string messageString = messageData.ToString().Replace("|URL|", "|ST|");
                        var    message       = parser.Parse(messageString);
                        messageArgs = new Hl7MessageReceivedEventArgs(message, localEndpoint, remoteEndpoint, DateTime.Now);

                        // Call any bound event handlers that there is a message available
                        OnMessageReceived(messageArgs);
                    }
                    finally
                    {
                        // Send the response back
                        using (MemoryStream memoryWriter = new MemoryStream())
                        {
                            using (StreamWriter streamWriter = new StreamWriter(memoryWriter))
                            {
                                memoryWriter.Write(new byte[] { START_TX }, 0, 1);                                 // header
                                if (messageArgs != null && messageArgs.Response != null)
                                {
                                    var strMessage = parser.Encode(messageArgs.Response);
#if DEBUG
                                    Trace.TraceInformation("Sending message to llp://{0} : {1}", tcpClient.Client.RemoteEndPoint, strMessage);
#endif
                                    // Since nHAPI only emits a string we just send that along the stream
                                    streamWriter.Write(strMessage);
                                    streamWriter.Flush();
                                }
                                memoryWriter.Write(new byte[] { END_TX, END_TXNL }, 0, 2);                                 // Finish the stream with FSCR
                                stream.Write(memoryWriter.ToArray(), 0, (int)memoryWriter.Position);
                                stream.Flush();
                            }
                        }
                        lastReceive = DateTime.Now;                         // Update the last receive time so the timeout function works
                    }
                }
            }
            catch (Exception e)
            {
                Trace.TraceError(e.ToString());
            }
            finally
            {
                stream.Close();
                tcpClient.Close();
            }
        }
예제 #7
0
        /// <summary>
        /// Transport has received a message!
        /// </summary>
        private void m_transport_MessageReceived(object sender, Hl7MessageReceivedEventArgs e)
        {
            IMessagePersistenceService messagePersister = ApplicationServiceContext.Current.GetService(typeof(IMessagePersistenceService)) as IMessagePersistenceService;

            // Find the message that supports the type
            Terser msgTerser   = new Terser(e.Message);
            string messageType = String.Format("{0}^{1}", msgTerser.Get("/MSH-9-1"), msgTerser.Get("/MSH-9-2"));
            string messageId   = msgTerser.Get("/MSH-10");

            // Find a handler
            HandlerDefinition handler        = m_serviceDefinition.MessageHandlers.Find(o => o.Types.Exists(a => a.Name == messageType)),
                              defaultHandler = m_serviceDefinition.MessageHandlers.Find(o => o.Types.Exists(a => a.Name == "*"));

            if (handler != null && handler.Types.Find(o => o.Name == messageType).IsQuery ||
                defaultHandler != null && defaultHandler.Types.Find(o => o.Name == "*").IsQuery)
            {
                messagePersister = null;
            }

            // Have we already processed this message?
            MessageState msgState = MessageState.New;

            if (messagePersister != null)
            {
                msgState = messagePersister.GetMessageState(messageId);
            }

            switch (msgState)
            {
            case MessageState.New:

                if (messagePersister != null)
                {
                    messagePersister.PersistMessage(messageId, CreateMessageStream(e.Message));
                }

                if (handler == null && defaultHandler == null)
                {
                    throw new InvalidOperationException(String.Format("Cannot find message handler for '{0}'", messageType));
                }

                e.Response = (handler ?? defaultHandler).Handler.HandleMessage(e);
                if (e.Response == null)
                {
                    throw new InvalidOperationException("Couldn't process message");
                }

                msgTerser = new Terser(e.Response);
                if (messagePersister != null)
                {
                    messagePersister.PersistResultMessage(msgTerser.Get("/MSH-10"), messageId, CreateMessageStream(e.Response));
                }
                break;

            case MessageState.Active:
                throw new InvalidOperationException("Message already in progress");

            case MessageState.Complete:
                NHapi.Base.Parser.PipeParser pp = new NHapi.Base.Parser.PipeParser();
                using (var rdr = new StreamReader(messagePersister.GetMessageResponseMessage(messageId)))
                    e.Response = pp.Parse(rdr.ReadToEnd());
                break;
            }
        }