Exemplo n.º 1
0
        private static string ExtractReportFromHL7(string hl7)
        {
            JObject       obj     = HL7ToXmlConverter.ConvertToJObject(hl7);
            string        msgtype = obj["hl7message"]["MSH"]["MSH.9"].GetFirstField();
            StringBuilder builder = new StringBuilder();

            if (msgtype.Equals("ORU") || msgtype.Equals("MDM"))
            {
                if (obj["hl7message"]["OBX"] is JArray)
                {
                    foreach (var obx in obj["hl7message"]["OBX"])
                    {
                        if (Utilities.getFirstField(obx["OBX.2"]).Equals("TX") || Utilities.getFirstField(obx["OBX.2"]).Equals("FT"))
                        {
                            builder.Append(Utilities.getFirstField(obx["OBX.5"]).UnEscapeHL7());
                        }
                    }
                }
                else
                {
                    if (Utilities.getFirstField(obj["hl7message"]["OBX"]["OBX.2"]).Equals("TX") || Utilities.getFirstField(obj["hl7message"]["OBX"]["OBX.2"]).Equals("FT"))
                    {
                        builder.Append(Utilities.getFirstField(obj["hl7message"]["OBX"]["OBX.5"]).UnEscapeHL7());
                    }
                }
            }
            return(builder.ToString());
        }
        // <span class="code-SummaryComment"><summary></span>
        /// Converts an HL7 message into a JSON Object from it's XML representation of the same message.
        /// <span class="code-SummaryComment"></summary></span>
        /// <span class="code-SummaryComment"><param name="sHL7">The HL7 to convert</param></span>
        /// <span class="code-SummaryComment"><returns></returns></span>
        public static string ConvertToJSON(string sHL7, JObject hl7metadata = null)
        {
            JObject o = HL7ToXmlConverter.ConvertToJObject(sHL7, hl7metadata);

            if (o == null)
            {
                return(null);
            }
            return(JsonConvert.SerializeObject(o["hl7message"]));
        }
        // <span class="code-SummaryComment"><summary></span>
        /// Converts an HL7 message into a JOject Object from it's XML representation of the same message.
        /// <span class="code-SummaryComment"></summary></span>
        /// <span class="code-SummaryComment"><param name="sHL7">The HL7 to convert</param></span>
        /// <span class="code-SummaryComment"><returns>JObject with root of hl7message</returns></span>
        public static JObject ConvertToJObject(string sHL7, JObject hl7metadata = null)
        {
            var xmld = HL7ToXmlConverter.ConvertToXmlDocument(sHL7, hl7metadata);

            if (xmld != null)
            {
                string  json = JsonConvert.SerializeXmlNode(xmld);
                JObject o    = JObject.Parse(json);
                return(o);
            }
            return(null);
        }
Exemplo n.º 4
0
        public static async Task <IActionResult> Run(
            [HttpTrigger(AuthorizationLevel.Function, "post", Route = null)] HttpRequest req,
            [CosmosDB(
                 databaseName: "%CosmosDBNAME%",
                 collectionName: "%CosmosHL7Collection%",
                 ConnectionStringSetting = "CosmosDBConnection")] DocumentClient client,
            ClaimsPrincipal claimsPrincipal,
            ILogger log)
        {
            string contenttype = string.IsNullOrEmpty(req.ContentType) ? "application/hl7-v2+er7; charset=utf-8" : req.ContentType;

            log.LogInformation("C# TransformSaveToDB HTTP trigger function fired");
            string coid = req.Query["id"];

            if (coid == null)
            {
                coid = Guid.NewGuid().ToString();
            }
            string requestBody = await new StreamReader(req.Body).ReadToEndAsync();

            JObject jobj = null;

            try
            {
                jobj = HL7ToXmlConverter.ConvertToJObject(requestBody);
                string rhm = determinerhm(jobj);
                jobj["id"]       = coid;
                jobj["rhm"]      = rhm;
                jobj["location"] = req.GetIPAddress() ?? "";
                Uri collection = UriFactory.CreateDocumentCollectionUri(Utilities.GetEnvironmentVariable("CosmosDBNAME", "hl7json"), Utilities.GetEnvironmentVariable("CosmosHL7Collection", "messages"));
                var inserted   = await client.UpsertDocumentAsync(collection, jobj);

                Utilities.TraceAccess(log, claimsPrincipal, client, collection, Utilities.ACTION.UPSERT, coid);
                var retVal = new ContentResult();
                retVal.ContentType = contenttype;
                retVal.Content     = Utilities.GenerateACK(jobj);
                return(retVal);
            }
            catch (Exception e)
            {
                log.LogError(e, e.Message);
                var retVal = new ContentResult();
                retVal.ContentType = "text/plain";
                retVal.Content     = e.Message;
                retVal.StatusCode  = 500;
                return(retVal);
            }
        }
        private static async Task <bool> processMessage(string message, DocumentClient client, ILogger logger, string id = null, string location = null)
        {
            //if (true) return true;
            if (string.IsNullOrEmpty(message))
            {
                return(false);
            }
            string coid   = (id ?? Guid.NewGuid().ToString());
            int    dirend = coid.LastIndexOf("/");

            if (dirend > -1)
            {
                coid = coid.Substring(dirend + 1);
            }
            int extbegin = coid.LastIndexOf(".");

            if (extbegin > -1)
            {
                coid = coid.Substring(0, extbegin);
            }
            JObject jobj = null;

            //var metadata = HL7MetaDataLoader.Instance.GetMetaDataFromMessage(message);
            try
            {
                jobj = HL7ToXmlConverter.ConvertToJObject(message);
                if (jobj == null)
                {
                    return(false);
                }
                string rhm = determinerhm(jobj);
                jobj["id"]  = coid;
                jobj["rhm"] = rhm;
                if (location != null)
                {
                    jobj["location"] = location;
                }
                var inserted = await client.UpsertDocumentAsync(UriFactory.CreateDocumentCollectionUri("hl7json", "messages"), jobj);

                //logger.LogTrace($"Message id {coid} from {rhm} added to Database");
                return(true);
            }
            catch (Exception e)
            {
                logger.LogError(e, e.Message);
                return(false);
            }
        }
Exemplo n.º 6
0
        public static async Task <IActionResult> Run(
            [HttpTrigger(AuthorizationLevel.Function, "post", Route = null)] HttpRequest req,
            ILogger log)
        {
            log.LogInformation("C# HL7toJSON HTTP trigger function fired");
            string requestBody = await new StreamReader(req.Body).ReadToEndAsync();

            try
            {
                var     metadata = HL7MetaDataLoader.Instance.GetMetaDataFromMessage(requestBody);
                JObject o        = HL7ToXmlConverter.ConvertToJObject(requestBody, metadata);
                return(new JsonResult(o["hl7message"]));
            } catch (Exception e)
            {
                log.LogError(e, e.Message);
                return(new BadRequestObjectResult("Error: " + e.Message));
            }
        }
Exemplo n.º 7
0
        public static async Task <IActionResult> Run(
            [HttpTrigger(AuthorizationLevel.Function, "post", Route = null)] HttpRequest req,
            [Blob("%StorageAccountBlob%", Connection = "StorageAccount")] CloudBlobContainer container, ILogger log)
        {
            string contenttype = req.ContentType;

            log.LogInformation("C# TransformSaveToBlob HTTP trigger function fired");
            string coid = req.Query["id"];

            if (coid == null)
            {
                coid = Guid.NewGuid().ToString();
            }
            bool raw = req.Query.ContainsKey("raw");

            string requestBody = await new StreamReader(req.Body).ReadToEndAsync();

            JObject jobj = null;

            try
            {
                jobj = HL7ToXmlConverter.ConvertToJObject(requestBody);
                DateTime now     = DateTime.Now;
                string   msgtype = (string)jobj["hl7message"]["MSH"]["MSH.9"]["MSH.9.1"];
                string   ds      = now.Year.ToString() + "/" + now.Month.ToString("D2") + "/" + now.Day.ToString("D2") + "/" + now.Hour.ToString("D2");
                await container.CreateIfNotExistsAsync();

                CloudBlockBlob blockBlob = container.GetBlockBlobReference(msgtype.ToLower() + "/" + ds + "/" + coid.ToLower() + (raw ? ".hl7" : ".json"));
                using (var stream = new MemoryStream(System.Text.Encoding.UTF8.GetBytes((raw ? requestBody : HL7ToXmlConverter.ConvertToJSON(jobj))), writable: false))
                {
                    await blockBlob.UploadFromStreamAsync(stream);
                }
                var retVal = new ContentResult();
                retVal.ContentType = contenttype;
                retVal.Content     = Utilities.GenerateACK(jobj);
                return(retVal);
            }
            catch (Exception e)
            {
                log.LogError(e, req.ContentType + "**" + e.Message + "**" + e.StackTrace);
                //return new System.Web.Http.InternalServerErrorResult();
                return(new BadRequestObjectResult("Error: " + req.ContentType + "**" + e.Message + "**" + e.StackTrace));
            }
        }
 /// <span class="code-SummaryComment"><summary></span>
 /// Converts an HL7 message into an XML representation of the same message.
 /// <span class="code-SummaryComment"></summary></span>
 /// <span class="code-SummaryComment"><param name="sHL7">The HL7 to convert</param></span>
 /// <span class="code-SummaryComment"><returns>XML String with root of hl7message</returns></span>
 public static string ConvertToXml(string sHL7, JObject hl7metadata = null)
 {
     return(HL7ToXmlConverter.ConvertToXmlDocument(sHL7, hl7metadata).OuterXml);
 }
        /// <span class="code-SummaryComment"><summary></span>
        /// Converts an HL7 message into an XMLDocument representation of the same message.
        /// <span class="code-SummaryComment"></summary></span>
        /// <span class="code-SummaryComment"><param name="sHL7">The HL7 to convert</param></span>
        /// <span class="code-SummaryComment"><returns>XMLDocument with root of hl7message</returns></span>
        public static XmlDocument ConvertToXmlDocument(string sHL7, JObject metadata = null)
        {
            try
            {
                if (string.IsNullOrEmpty(sHL7) || !sHL7.StartsWith("MSH"))
                {
                    return(null);
                }
                XmlDocument _xmlDoc = null;
                // Go and create the base XML
                _xmlDoc = CreateXmlDoc();

                // HL7 message segments are terminated by carriage returns,
                // so to get an array of the message segments, split on carriage return
                string[] sHL7Lines = sHL7.Split('\r');

                // Now we want to replace any other unprintable control
                // characters with whitespace otherwise they'll break the XML
                for (int i = 0; i < sHL7Lines.Length; i++)
                {
                    sHL7Lines[i] = Regex.Replace(sHL7Lines[i], @"[^ -~]", "");
                }

                /// Go through each segment in the message
                /// and first get the fields, separated by pipe (|),
                /// then for each of those, get the field components,
                /// separated by carat (^), and check for
                /// repetition (~) and also check each component
                /// for subcomponents, and repetition within them too.
                for (int i = 0; i < sHL7Lines.Length; i++)
                {
                    string fs = null;
                    // Don't care about empty lines
                    if (sHL7Lines[i] != string.Empty)
                    {
                        // Get the line and get the line's segments
                        string sHL7Line = sHL7Lines[i];
                        if (fs == null)
                        {
                            fs = GetFieldSeparator(sHL7Line);
                        }
                        string[] sFields = HL7ToXmlConverter.GetMessgeFields(sHL7Line, fs);
                        // Create a new element in the XML for the line
                        var        segmentextract = LookUpSegmentName(metadata, sFields[0]);
                        XmlElement el             = _xmlDoc.CreateElement(segmentextract.ExtractedName);
                        if (segmentextract.Repeats)
                        {
                            var attribute = _xmlDoc.CreateAttribute("json", "Array", "http://james.newtonking.com/projects/json");
                            attribute.InnerText = "true";
                            el.Attributes.Append(attribute);
                        }
                        _xmlDoc.DocumentElement.AppendChild(el);
                        XmlElement sq = _xmlDoc.CreateElement("msgseq");
                        sq.InnerText = (i + 1).ToString();
                        el.AppendChild(sq);
                        // For each field in the line of HL7
                        for (int a = 1; a < sFields.Length; a++)
                        {
                            var fieldextract = LookUpFieldName(metadata, sFields[0], a.ToString());
                            // Create a new element
                            XmlElement fieldEl = _xmlDoc.CreateElement(fieldextract.ExtractedName);
                            if (fieldextract.Repeats)
                            {
                                var attribute = _xmlDoc.CreateAttribute("json", "Array", "http://james.newtonking.com/projects/json");
                                attribute.InnerText = "true";
                                fieldEl.Attributes.Append(attribute);
                            }
                            /// Part of the HL7 specification is that part
                            /// of the message header defines which characters
                            /// are going to be used to delimit the message
                            /// and since we want to capture the field that
                            /// contains those characters we need
                            /// to just capture them and stick them in an element.
                            if (sFields[a] != @"^~\&")
                            {
                                /// Get the components within this field, separated by carats (^)
                                /// If there are more than one, go through and create an element for
                                /// each, then check for subcomponents, and repetition in both.
                                string[] sRepeatingComponent = HL7ToXmlConverter.GetRepetitions(sFields[a]);
                                int      rc = 0;

                                foreach (string r in sRepeatingComponent)
                                {
                                    XmlElement repeatelement = null;
                                    if (sRepeatingComponent.Length > 1)
                                    {
                                        repeatelement = _xmlDoc.CreateElement(fieldextract.ExtractedName);
                                    }
                                    string[] sComponents = HL7ToXmlConverter.GetComponents(r);
                                    if (sComponents.Length > 1)
                                    {
                                        for (int b = 0; b < sComponents.Length; b++)
                                        {
                                            XmlElement componentEl = _xmlDoc.CreateElement(fieldextract.ExtractedName +
                                                                                           "." + (b + 1).ToString());



                                            string[] subComponents = GetSubComponents(sComponents[b]);
                                            if (subComponents.Length > 1)
                                            // There were subcomponents
                                            {
                                                for (int c = 0; c < subComponents.Length; c++)
                                                {
                                                    // Check for repetition
                                                    string[] subComponentRepetitions =
                                                        GetRepetitions(subComponents[c]);
                                                    if (subComponentRepetitions.Length > 1)
                                                    {
                                                        for (int d = 0;
                                                             d < subComponentRepetitions.Length;
                                                             d++)
                                                        {
                                                            XmlElement subComponentRepEl =
                                                                _xmlDoc.CreateElement(fieldextract.ExtractedName +
                                                                                      "." + (b + 1).ToString() +
                                                                                      "." + (c + 1).ToString() +
                                                                                      "." + (d + 1).ToString());
                                                            subComponentRepEl.InnerText =
                                                                subComponentRepetitions[d].UnEscapeHL7();
                                                            componentEl.AppendChild(subComponentRepEl);
                                                        }
                                                    }
                                                    else
                                                    {
                                                        XmlElement subComponentEl =
                                                            _xmlDoc.CreateElement(fieldextract.ExtractedName +
                                                                                  "." + (b + 1).ToString() + "." + (c + 1).ToString());
                                                        subComponentEl.InnerText = subComponents[c].UnEscapeHL7();
                                                        componentEl.AppendChild(subComponentEl);
                                                    }
                                                }
                                                if (sRepeatingComponent.Length > 1)
                                                {
                                                    repeatelement.AppendChild(componentEl);
                                                    fieldEl.AppendChild(repeatelement);
                                                }
                                                else
                                                {
                                                    fieldEl.AppendChild(componentEl);
                                                }
                                            }
                                            else // There were no subcomponents
                                            {
                                                string[] sRepetitions =
                                                    HL7ToXmlConverter.GetRepetitions(sComponents[b]);
                                                if (sRepetitions.Length > 1)
                                                {
                                                    XmlElement repetitionEl = null;
                                                    for (int c = 0; c < sRepetitions.Length; c++)
                                                    {
                                                        repetitionEl =
                                                            _xmlDoc.CreateElement(sFields[0] + "." + (sRepeatingComponent.Length > 1 ? "." + rc.ToString() : ".") +
                                                                                  a.ToString() + "." + (b + 1).ToString() +
                                                                                  "." + (c + 1).ToString());
                                                        repetitionEl.InnerText = sRepetitions[c].UnEscapeHL7();
                                                        componentEl.AppendChild(repetitionEl);
                                                    }
                                                    fieldEl.AppendChild(componentEl);
                                                    el.AppendChild(fieldEl);
                                                }
                                                else
                                                {
                                                    componentEl.InnerText = sComponents[b].UnEscapeHL7();
                                                    if (sRepeatingComponent.Length > 1)
                                                    {
                                                        repeatelement.AppendChild(componentEl);
                                                        el.AppendChild(repeatelement);
                                                    }
                                                    else
                                                    {
                                                        fieldEl.AppendChild(componentEl);
                                                        el.AppendChild(fieldEl);
                                                    }
                                                }
                                            }
                                        }

                                        //el.AppendChild(fieldEl);
                                    }
                                    else
                                    {
                                        if (sRepeatingComponent.Length > 1)
                                        {
                                            repeatelement.InnerText = sFields[a].UnEscapeHL7();
                                            el.AppendChild(repeatelement);
                                        }
                                        else
                                        {
                                            fieldEl.InnerText = sFields[a].UnEscapeHL7();
                                            el.AppendChild(fieldEl);
                                        }
                                    }
                                    rc++;
                                }
                            }
                            else
                            {
                                fieldEl.InnerText = sFields[a].UnEscapeHL7();
                                el.AppendChild(fieldEl);
                            }
                        }
                    }
                }

                return(_xmlDoc);
            }
            catch (Exception exp)
            {
                Console.WriteLine(exp.Message);
                return(null);
            }
        }