Exemplo n.º 1
0
        internal IHL7Message DoParse(IMessage message)
        {
            if (message == null)
            {
                throw new HL7apiException("Cannot parse an invalid message");
            }

            IHL7Message ret = null;

            Terser t = new Terser(message);


            string messageID = t.Get("/MSH-21(0)-1-1");

            if (string.IsNullOrEmpty(messageID))
            {
                messageID = GetMessageIDFromMessageType(message.GetMessageType(), message.Version);
                if (string.IsNullOrEmpty(messageID))
                {
                    throw new HL7apiException("Invalid Message type");
                }
            }

            ret = (IHL7Message)InstantiateMessage(messageID, message.Version, message);

            return(ret);
        }
Exemplo n.º 2
0
        internal IHL7Message InstantiateMessage(string messageID, string version)
        {
            string assemblyName = $"HL7api.V{version.Replace(".", "")}";//.HL7api.V251
            string className    = $"{assemblyName}.Message.{messageID}";

            IHL7Message message     = null;
            Type        messageType = null;

            String classToTry = $"{className},{assemblyName}";

            messageType = Type.GetType(classToTry); //GetType from the specified assembly
            if (messageType == null)
            {
                messageType = Type.GetType(className); //try in the current assembly
            }
            if (messageType == null)
            {
                throw new Exception();
            }
            try
            {
                message = Activator.CreateInstance(messageType) as IHL7Message;
            }
            catch (Exception e)
            {
                throw new HL7apiException("Unable to instantiate the class" + messageID, e);
            }
            return(message);
        }
Exemplo n.º 3
0
        /// <summary>
        ///
        /// </summary>
        /// <param name="ack"></param>
        /// <returns></returns>
        private void ProcessIncomingAck(IHL7Message ack)
        {
            HL7Request req = null;

            var v = m_OutgoingRequests.Where((request, b) =>
            {
                if (ack.IsAckForRequest(request.Request) && request.Acknowledgment == null)
                {
                    request.Acknowledgment = ack as IHL7Message;

                    return(true);
                }
                else
                {
                    return(false);
                }
            }).ToList();

            if (v.Count() == 0)
            {
                string log = "Unexpected ack received or ack received to late";
                m_HL7Server.Logger.Error(log);
            }
            else if (v.Count() > 1)
            {
                string log = "each ack should be bount to a single request";
                throw new HL7InterfaceException(log);
            }
            else
            {
                req = v.FirstOrDefault();

                req.AckReceivedEvent.Set();
            }
        }
Exemplo n.º 4
0
        internal ParserResult Validate(String messageString)
        {
            IMessage messageObject = null;

            try
            {
                messageObject = contextParser.Parse(messageString);
            }
            catch (System.Exception se)
            {
                return(SystemExceptionHandler(se, messageString));
            }

            parsedMessage = hl7Parser.DoParse(messageObject);

            if (parsedMessage.IsAcknowledge)
            {
                return(new ParserResult(parsedMessage, null, true, true, ""));
            }

            hl7Ack = hl7Parser.GetAckForMessage(parsedMessage);

            SetACK(AckTypes.AA, messageString, parsedMessage.Message);

            return(new ParserResult(parsedMessage, hl7Ack, true, false, ""));
        }
Exemplo n.º 5
0
        public IHL7Message GetAckForMessage(IHL7Message hl7Message)
        {
            string ackName = hl7Message.ExpectedAckID;
            string version = hl7Message.HL7Version;

            return(InstantiateMessage(ackName, version));
        }
Exemplo n.º 6
0
 public HL7Request(IHL7Message message)
 {
     Request = message;
     ResponseReceivedEvent    = new AutoResetEvent(false);
     AckReceivedEvent         = new AutoResetEvent(false);
     RequestCompletedEvent    = new AutoResetEvent(false);
     RequestCancellationToken = new CancellationTokenSource();
 }
Exemplo n.º 7
0
        public virtual bool IsAckForRequest(IHL7Message request)
        {
            if (!this.IsAcknowledge)
            {
                return(false);
            }

            return(HL7Parser.IsAckForRequest(request, this));
        }
Exemplo n.º 8
0
        public string Encode(IHL7Message hl7Message, HL7Encoding encoding, bool validate)
        {
            if (HL7Encoding.XML == encoding)
            {
                return(xmlParser.Encode(hl7Message.Message));
            }

            return(pipeParser.Encode(hl7Message.Message));
        }
Exemplo n.º 9
0
        public static bool IsAckForRequest(IHL7Message request, IHL7Message ack)
        {
            if (request == null)
            {
                throw new ArgumentNullException("Please provide a non-null value for the request");
            }

            if (ack == null)
            {
                return(false);
            }

            if (string.IsNullOrEmpty(request.ExpectedAckID))
            {
                throw new HL7apiException("The request should not be an acknowledgment");
            }

            if (!string.IsNullOrEmpty(ack.ExpectedAckID))
            {
                throw new HL7apiException("The ack should be an acknowledgment");
            }

            string msa2  = ack.GetValue("/MSA-2");
            string msh10 = request.ControlID;

            if (string.IsNullOrEmpty(msa2) || string.IsNullOrEmpty(msh10))
            {
                throw new HL7apiException("The MSH-10 and MSA-2 are mandatory in the messages:"
                                          + request.MessageID + "and" + ack.MessageID);
            }

            if (String.Compare(msa2, msh10) != 0)
            {
                return(false);
            }

            //if the trigger event is provided then check aigain
            if (!string.IsNullOrEmpty(ack.TriggerEvent))
            {
                if (!request.ExpectedAckType.Equals($"{ack.MessageCode}_{ack.TriggerEvent}"))
                {
                    return(false);
                }
            }
            else
            {
                if (!ack.MessageCode.Equals("ACK"))
                {
                    return(false);
                }
            }
            return(true);
        }
Exemplo n.º 10
0
        public override bool IsResponseForRequest(IHL7Message request)
        {
            if (request == null)
            {
                throw new ArgumentNullException("the request and the response should be both non-null");
            }

            if (string.IsNullOrEmpty(request.ExpectedResponseType))
            {
                throw new ArgumentException("the request cannot be a type of response message or acknowledgment");
            }

            if (string.IsNullOrEmpty(this.TriggerEvent) || string.IsNullOrEmpty(this.MessageCode))
            {
                throw new HL7apiException($"The message code and trigger event of the message: " +
                                          $" {this.MessageID} are mandatory fields");
            }

            // to avoid situation in which response is actually a request
            if (!string.IsNullOrEmpty(this.ExpectedResponseType))
            {
                return(false);
            }

            if (request.ExpectedResponseType != $"{this.MessageCode}_{this.TriggerEvent}")
            {
                return(false);
            }

            if ((request.ExpectedResponseID != this.MessageID))
            {
                return(false);
            }

            if (request is EquipmentCommandRequest)
            {
                //if (!(this is EquipmentCommandResponse))
                //    return false;

                //if (request.GetValue("COMMAND(0)/ECD-2-1")
                //    != this.GetValue("COMMAND_RESPONSE(0)/ECD-2-1"))
                //    return false;

                //if (request.GetValue("COMMAND(0)/SPECIMEN_CONTAINER/SAC-3-1")
                //    != this.GetValue("COMMAND_RESPONSE(0)/SPECIMEN_CONTAINER/SAC-3-1"))
                //    return false;
            }
            return(true);
        }
Exemplo n.º 11
0
        public async Task <HL7Request> SendHL7MessageAsync(IHL7Message message)
        {
            HL7Request hl7Request = new HL7Request(message);

            if (!m_OutgoingRequests1.TryAdd(message.ControlID, hl7Request))
            {
                throw new HL7InterfaceException("m_OutgoingRequests");
            }

            m_OutgoingRequests.Add(hl7Request);

            TaskCompletionSource <HL7Request> senderTaskCompletionSource = new TaskCompletionSource <HL7Request>();

            hl7Request.SenderTask = Task.Run(() =>
            {
                bool success = false;

                int responseRetries = m_HL7Protocol.Config.MaxResponseRetriesNumber;

                try
                {
                    do
                    {
                        success = SendMessageOne(hl7Request, ref responseRetries);
                    }while (!success);
                }
                catch (Exception ex)
                {
                    if (ex is HL7InterfaceException)
                    {
                        throw ex;
                    }
                }
                finally { hl7Request.RequestCompletedEvent.Set(); }

                return(hl7Request);
            }, hl7Request.RequestCancellationToken.Token);

            return(await hl7Request.SenderTask); //.ConfigureAwait(false);
        }
Exemplo n.º 12
0
        internal IHL7Message InstantiateMessage(string messageID, string version, IMessage message)
        {
            string assemblyName = $"HL7api.V{version.Replace(".", "")}"; //.HL7api.V251

            string className = $"{assemblyName}.Message.{messageID}";

            IHL7Message hl7Message = null;

            Type   messageType = null;
            String classToTry  = $"{className},{assemblyName}";

            messageType = Type.GetType(classToTry); //GetType from the specified assembly

            if (messageType == null)
            {
                messageType = Type.GetType(className); //try in the current assembly
            }
            if (messageType == null)
            {
                throw new HL7apiException();
            }
            try
            {
                ConstructorInfo[] cis = messageType.GetConstructors(BindingFlags.NonPublic | BindingFlags.Instance);

                hl7Message = (IHL7Message)Activator.CreateInstance(
                    messageType, BindingFlags.NonPublic | BindingFlags.Instance,
                    null,
                    new object[] { message },
                    null);
            }
            catch (Exception ex)
            {
                throw new HL7apiException("Unable to instantiate the class " + messageID, ex);
            }
            return(hl7Message);
        }
Exemplo n.º 13
0
 public override bool IsResponseForRequest(IHL7Message request)
 {
     throw new NotImplementedException();
 }
Exemplo n.º 14
0
        //public static IHL7Protocol GetMessageProtocol()
        //{
        //    //IHL7Protocol p = null;
        //    //string messageProtocolTypeName = ConfigurationManager.AppSettings["MessageProtocol"];
        //    //if (messageProtocolTypeName == null)
        //    //    p = new DefaultProtocol();
        //    //else
        //    //{
        //    //    try
        //    //    {
        //    //        Type t = Type.GetType(messageProtocolTypeName);
        //    //        p = Activator.CreateInstance(t) as IHL7Protocol;
        //    //    }
        //    //    catch (Exception e)
        //    //    {
        //    //        throw new HL7InterfaceException
        //    //            ("Unable to instantiate the Message Protocol class from the assembly name provided", e);
        //    //    }
        //    //}
        //    //return p;
        //}

        #region IProtocol Interface
        public virtual byte[] Encode(IHL7Message hl7Message)
        {
            string mllpMessage = HL7api.Util.MLLP.CreateMLLPMessage(hl7Message.Encode());

            return(Encoding.ASCII.GetBytes(mllpMessage));
        }
 public override bool IsResponseForRequest(IHL7Message request)
 {
     return(false);
 }
Exemplo n.º 16
0
 public abstract bool IsResponseForRequest(IHL7Message request);
Exemplo n.º 17
0
        private ParserResult SystemExceptionHandler(Exception se, string messageString)
        {
            if (string.IsNullOrEmpty(messageString))
            {
                return(new ParserResult(null, null, false, null, se.Message));
            }

            //Do not handle configuration Exceptions
            if (se is ConfigurationException)
            {
                throw (ConfigurationException)se;
            }

            if (typeof(System.Configuration.ConfigurationException).IsAssignableFrom(se.GetType()))
            {
                throw (ConfigurationException)se;
            }

            _errorMessage.AppendLine(se.Message);

            if (se.InnerException != null)
            {
                _errorMessage.AppendLine(se.InnerException.Message);
            }

            string messageType = null;

            string version = null;

            ISegment criticalSegment = null;

            try
            {
                criticalSegment = TryToRecoverCriticalDataFromMessage(messageString);
                if (criticalSegment == null)
                {
                    version     = TryToRecoverTheVersion(messageString);
                    messageType = TryTorecoverTheMessageType(messageString);
                }
                else
                {
                    version     = Terser.Get(criticalSegment, 12, 0, 1, 1);
                    messageType = $"{Terser.Get(criticalSegment, 9, 0, 1, 1)}" +
                                  $"_{Terser.Get(criticalSegment, 9, 0, 2, 1)}";
                }

                if (messageType == null)
                {
                    return(new ParserResult(null, null, false, null, _errorMessage.ToString()));
                }

                //the messageType is not null!
                if (version == null)
                {
                    version = "2.5.1";
                }


                string responseType = HL7Parser.GetMessageIDFromMessageType(messageType, version);
                if (responseType == null)
                {
                    //the incoming message is an ack, the acknowledgment should not be aknoledged
                    return(new ParserResult(null, null, false, true, _errorMessage.ToString()));
                }


                hl7Ack = hl7Parser.InstantiateMessage(responseType, version);

                ISegment err = (ISegment)hl7Ack.Message.GetStructure("ERR", 0);
                if ((se.InnerException != null) && typeof(HL7Exception).IsAssignableFrom(se.InnerException.GetType()))
                {
                    HL7Exception he = (HL7Exception)se.InnerException;
                    he.populate(err);
                }

                //if (typeof(HL7Exception).IsAssignableFrom(se.GetType()))
                //{
                //    HL7Exception he = (HL7Exception)se;
                //    he.populate(err);
                //    Debug.Print((new PipeParser()).Encode(ack));
                //}

                SetACK(AckTypes.AR, messageString);
            }
            catch (Exception e)
            {
                _errorMessage.AppendLine(e.Message);
                return(new ParserResult(parsedMessage, hl7Ack, false, null, _errorMessage.ToString()));
            }
            return(new ParserResult(parsedMessage, hl7Ack, false, parsedMessage.IsAcknowledge, _errorMessage.ToString()));
        }
Exemplo n.º 18
0
 public string Encode(IHL7Message message)
 {
     return(Encode(message, HL7Encoding.ER7, true));
 }