Esempio n. 1
0
        protected Boolean ProcessResults(String[] resourcePaths, String validationPath)
        {
            if (resourcePaths is null)
            {
                throw new ArgumentNullException(nameof(resourcePaths));
            }

            FhirXmlParser parser = new FhirXmlParser();
            bool          retVal = true;

            if (resourcePaths.Length == 1)
            {
                OperationOutcome results      = parser.Parse <OperationOutcome>(File.ReadAllText(validationPath));
                String           resourceName = Path.GetFileName(resourcePaths[0]);
                this.ProcessOutcome(results, resourceName, this.FailOnWarnings, ref retVal);
            }
            else
            {
                Bundle resultsBundle = parser.Parse <Bundle>(File.ReadAllText(validationPath));
                foreach (Bundle.EntryComponent item in resultsBundle.Entry)
                {
                    OperationOutcome results      = item.Resource as OperationOutcome;
                    Extension        e            = results.GetExtension("http://hl7.org/fhir/StructureDefinition/operationoutcome-file");
                    String           resourceName = Path.GetFileName(((FhirString)e.Value).Value);
                    this.ProcessOutcome(results, resourceName, this.FailOnWarnings, ref retVal);
                }
            }
            return(retVal);
        }
Esempio n. 2
0
        public void EdgecaseRoundtrip()
        {
            string json     = TestDataHelper.ReadTestData("json-edge-cases.json");
            var    tempPath = Path.GetTempPath();

            var poco = FhirJsonParser.Parse <Resource>(json);

            Assert.IsNotNull(poco);
            var xml = FhirXmlSerializer.SerializeToString(poco);

            Assert.IsNotNull(xml);
            File.WriteAllText(Path.Combine(tempPath, "edgecase.xml"), xml);

            poco = FhirXmlParser.Parse <Resource>(xml);
            Assert.IsNotNull(poco);
            var json2 = FhirJsonSerializer.SerializeToString(poco);

            Assert.IsNotNull(json2);
            File.WriteAllText(Path.Combine(tempPath, "edgecase.json"), json2);

            List <string> errors = new List <string>();

            JsonAssert.AreSame("edgecase.json", json, json2, errors);
            Console.WriteLine(String.Join("\r\n", errors));
            Assert.AreEqual(0, errors.Count, "Errors were encountered comparing converted content");
        }
Esempio n. 3
0
        public void RequiresHl7Namespace()
        {
            var xml    = "<Patient><active value='false' /></Patient>";
            var parser = new FhirXmlParser(new ParserSettings()
            {
                PermissiveParsing = false
            });

            try
            {
                parser.Parse <Resource>(xml);
                Assert.Fail("Should have thrown on Patient without namespace");
            }
            catch (FormatException fe)
            {
                Assert.IsTrue(fe.Message.Contains("expected the HL7 FHIR namespace"));
            }

            xml = "<Patient xmlns='http://hl7.org/fhir'><f:active value='false' xmlns:f='http://somehwere.else.nl' /></Patient>";

            try
            {
                parser.Parse <Resource>(xml);
                Assert.Fail("Should have thrown on Patient.active with incorrect namespace");
            }
            catch (FormatException fe)
            {
                Assert.IsTrue(fe.Message.Contains("which is not allowed"));
            }
        }
        public void RequiresHl7Namespace()
        {
            var xml    = "<Patient><active value='false' /></Patient>";
            var parser = new FhirXmlParser();

            try
            {
                parser.Parse <Resource>(xml);
                Assert.Fail("Should have thrown on Patient without namespace");
            }
            catch (FormatException fe)
            {
                Assert.IsTrue(fe.Message.Contains("Cannot derive type"));
            }

            xml = "<Patient xmlns='http://hl7.org/fhir'><f:active value='false' xmlns:f='http://somehwere.else.nl' /></Patient>";

            try
            {
                parser.Parse <Resource>(xml);
                Assert.Fail("Should have thrown on Patient.active with incorrect namespace");
            }
            catch (FormatException fe)
            {
                Assert.IsTrue(fe.Message.Contains("unsupported namespace"));
            }
        }
        private static Resource GetRequest(string identifier, NameValueCollection queryParam)
        {
            if (string.IsNullOrEmpty(identifier))
            {
                return(OperationOutcome.ForMessage("No NamingSystem id or identifer in Request", OperationOutcome.IssueType.BusinessRule, OperationOutcome.IssueSeverity.Error));
            }

            NamingSystem namingSystem     = new NamingSystem();
            string       resourceFilePath = Path.GetDirectoryName(new Uri(Assembly.GetExecutingAssembly().CodeBase).LocalPath) + @"\Test Files\";

            FhirXmlParser fxp = new FhirXmlParser();

            if (identifier.ToUpper() == "NHI" || identifier == DIGITAL_HEALTH_NZ + "/id/nhi" || identifier == "2.16.840.1.113883.2.18.2")
            {
                namingSystem = fxp.Parse <NamingSystem>(File.ReadAllText(resourceFilePath + "NamingSystem_NHI.xml"));
            }
            else if (identifier.ToUpper() == "HPI-CPN" || identifier == DIGITAL_HEALTH_NZ + "/id/hpi-person" || identifier == "2.16.840.1.113883.2.18.3.1")
            {
                namingSystem = fxp.Parse <NamingSystem>(File.ReadAllText(resourceFilePath + "NamingSystem_HPI_CPN.xml"));
            }
            else if (identifier.ToUpper() == "HPI-FAC" || identifier == DIGITAL_HEALTH_NZ + "/id/hpi-facility" || identifier == "2.16.840.1.113883.2.18.3.2")
            {
                namingSystem = fxp.Parse <NamingSystem>(File.ReadAllText(resourceFilePath + "NamingSystem_HPI_FAC.xml"));
            }
            else if (identifier.ToUpper() == "HPI-ORG" || identifier == DIGITAL_HEALTH_NZ + "/id/hpi-organisation" || identifier == "2.16.840.1.113883.2.18.3.3")
            {
                namingSystem = fxp.Parse <NamingSystem>(File.ReadAllText(resourceFilePath + "NamingSystem_HPI_ORG.xml"));
            }
            else if (identifier.ToUpper() == "NZMT" || identifier == NzMt.URI || identifier == "2.16.840.1.113883.2.18.21")
            {
                namingSystem = fxp.Parse <NamingSystem>(File.ReadAllText(resourceFilePath + "NamingSystem_NZMT.xml"));
            }
            else if (identifier.ToUpper() == "NZ_ETHNICITY_LEVEL_1" || identifier == NzEthnicityL1.URI || identifier == "2.16.840.1.113883.2.18.11")
            {
                namingSystem = fxp.Parse <NamingSystem>(File.ReadAllText(resourceFilePath + "NamingSystem_NZ_ETHNICITY_LEVEL_1.xml"));
            }
            else if (identifier.ToUpper() == "NZ_ETHNICITY_LEVEL_2" || identifier == NzEthnicityL2.URI || identifier == "2.16.840.1.113883.2.18.11.1")
            {
                namingSystem = fxp.Parse <NamingSystem>(File.ReadAllText(resourceFilePath + "NamingSystem_NZ_ETHNICITY_LEVEL_2.xml"));
            }
            else if (identifier.ToUpper() == "NZ_ETHNICITY_LEVEL_3" || identifier == NzEthnicityL3.URI || identifier == "2.16.840.1.113883.2.18.11.2")
            {
                namingSystem = fxp.Parse <NamingSystem>(File.ReadAllText(resourceFilePath + "NamingSystem_NZ_ETHNICITY_LEVEL_3.xml"));
            }
            else if (identifier.ToUpper() == "NZ_ETHNICITY_LEVEL_4" || identifier == NzEthnicityL4.URI || identifier == "2.16.840.1.113883.2.18.11.5")
            {
                namingSystem = fxp.Parse <NamingSystem>(File.ReadAllText(resourceFilePath + "NamingSystem_NZ_ETHNICITY_LEVEL_4.xml"));
            }
            else
            {
                return(OperationOutcome.ForMessage("Naming System Not Recognised.", OperationOutcome.IssueType.Unknown, OperationOutcome.IssueSeverity.Error));
            }

            AddNarrative(namingSystem);

            return(namingSystem);
        }
Esempio n. 6
0
        public void BundleLinksUnaltered()
        {
            var b = new Bundle
            {
                NextLink = new Uri("Organization/123456/_history/123456", UriKind.Relative)
            };

            var xml = new FhirXmlSerializer().SerializeToString(b);

            b = FhirXmlParser.Parse <Bundle>(xml);

            Assert.IsTrue(!b.NextLink.ToString().EndsWith("/"));
        }
Esempio n. 7
0
        private static string GetDocumentReferenceFromNrl(object targetPatientNumber)
        {
            try
            {
                var client = new HttpClient();
                client.DefaultRequestHeaders.Add("fromASID", NrlsFromAsid);
                client.DefaultRequestHeaders.Add("toASID", NrlsToAsid);
                client.DefaultRequestHeaders.Add("Authorization", NrlsAuthorization);

                var nrlsUrl        = string.Format(NrlsLookupUrlTemplate, targetPatientNumber);
                var responseString = client.GetStringAsync(nrlsUrl).Result;

                FhirXmlParser parser = new FhirXmlParser();
                var           bundle = parser.Parse <Bundle>(responseString);

                var documentReference = bundle.Entry[0].Resource as DocumentReference;
                var documentUrl       = documentReference.Content[0].Attachment.Url;
                Console.WriteLine("The following document reference was found on NRL: {0}", documentUrl);
                Console.WriteLine("Please press any key to continue...");
                Console.ReadKey();
                return(documentUrl);
            }
            catch (Exception exc)
            {
                HandleException(exc, "An error occured whilst getting the document reference from NRL");
            }

            return(null);
        }
Esempio n. 8
0
        private static Bundle ParseXML(string content, bool permissive)
        {
            Bundle bundle = null;

            // Grab all errors found by visiting all nodes and report if not permissive
            if (!permissive)
            {
                List <string> entries = new List <string>();
                ISourceNode   node    = FhirXmlNode.Parse(content, new FhirXmlParsingSettings {
                    PermissiveParsing = permissive
                });
                foreach (Hl7.Fhir.Utility.ExceptionNotification problem in node.VisitAndCatch())
                {
                    entries.Add(problem.Message);
                }
                if (entries.Count > 0)
                {
                    throw new System.ArgumentException(String.Join("; ", entries).TrimEnd());
                }
            }
            // Try Parse
            try
            {
                FhirXmlParser parser = new FhirXmlParser(GetParserSettings(permissive));
                bundle = parser.Parse <Bundle>(content);
            }
            catch (Exception e)
            {
                throw new System.ArgumentException(e.Message);
            }

            return(bundle);
        }
Esempio n. 9
0
        /// <summary>
        /// save patient demography to file/Azure Storage
        /// </summary>
        /// <param name="savePath"></param>
        /// <param name="id"></param>
        /// <returns></returns>
        public PatientViewModel GetPatient(string savePath, string id, bool saveToFile = true)
        {
            string getPatientUrl = AppSettings.FhirAPIBaseUrl + string.Format("Patient/{0}", id);

            //call API to get patient list
            string response = APIHelper.CallFhirApi(BearerToken, getPatientUrl);

            string fhirXml = RemoveAllEmptyNode(response);

            if (saveToFile)
            {
                if (AppSettings.StoredPatientInAzure)
                {
                    //stored the patient information into azure storage to demo
                    MemoryStream stream = new MemoryStream();
                    StreamWriter writer = new StreamWriter(stream);
                    writer.Write(fhirXml);
                    writer.Flush();
                    stream.Position = 0;

                    AzureStorageHelper.UploadBlobToAzure("", string.Format("{0}.xml", id), stream);
                }
                else
                {
                    //stored the patient information into local folder to demo
                    string saveFilePath = Path.Combine(savePath, string.Format("{0}.xml", id));
                    File.WriteAllText(saveFilePath, fhirXml);
                }
            }

            FhirXmlParser fxp     = new FhirXmlParser();
            var           patient = fxp.Parse <Hl7.Fhir.Model.Patient>(fhirXml);

            return(ConvertFhirToViewModel(patient));
        }
        //HttpActionExecutedContext
        public override void OnException(ExceptionContext context)
        {
            var exceptionType    = context.Exception.GetType();
            var expectedType     = GetExceptionType();
            var exceptionMessage = context.Exception.Message;

            if (exceptionType != expectedType && !(expectedType == typeof(Exception)))
            {
                return;
            }

            Resource operationOutcome = null;

            if (exceptionMessage.Contains("<" + nameof(OperationOutcome)))
            {
                var serializer = new FhirXmlParser();
                operationOutcome = serializer.Parse <OperationOutcome>(exceptionMessage);
            }
            var outCome         = operationOutcome ?? GetOperationOutCome(context.Exception);
            var xmlSerializer   = new FhirXmlSerializer();
            var xml             = xmlSerializer.SerializeToString(outCome);
            var internalOutCome = new FhirXmlParser().Parse <OperationOutcome>(xml);

            internalOutCome.Issue[0].Diagnostics = context.Exception.StackTrace;
            xml = xmlSerializer.SerializeToString(internalOutCome);
            var xmlDoc     = XDocument.Parse(xml);
            var error      = xmlDoc.ToString();
            var htmlDecode = WebUtility.HtmlDecode(error);

            Log.Error(htmlDecode);
            SetResponseForClient(context, outCome);
        }
        public override async Task <InputFormatterResult> ReadRequestBodyAsync(InputFormatterContext context, Encoding encoding)
        {
            if (context == null)
            {
                throw new ArgumentNullException(nameof(context));
            }
            if (encoding == null)
            {
                throw new ArgumentNullException(nameof(encoding));
            }

            if (encoding != Encoding.UTF8)
            {
                // throw Error.BadRequest("FHIR supports UTF-8 encoding exclusively, not " + encoding.WebName);
                // throw new ArgumentNullException(nameof(encoding));
                throw new InterneuronBusinessException((short)HttpStatusCode.BadRequest, $"FHIR supports UTF-8 encoding exclusively, not ${encoding.WebName}");
            }

            try
            {
                using (TextReader reader = context.ReaderFactory(context.HttpContext.Request.Body, encoding))
                {
                    FhirXmlParser parser = context.HttpContext.RequestServices.GetRequiredService <FhirXmlParser>();
                    return(await InputFormatterResult.SuccessAsync(parser.Parse(await reader.ReadToEndAsync())));
                }
            }
            catch (FormatException exception)
            {
                //throw Error.BadRequest($"Body parsing failed: {exception.Message}");
                throw new InterneuronBusinessException(exception, (short)HttpStatusCode.BadRequest, $"Body parsing failed: {exception.Message}");
            }
        }
Esempio n. 12
0
        public override async Task <InputFormatterResult> ReadRequestBodyAsync(InputFormatterContext context, Encoding encoding)
        {
            if (context == null)
            {
                throw new ArgumentNullException(nameof(context));
            }
            if (encoding == null)
            {
                throw new ArgumentNullException(nameof(encoding));
            }
            if (encoding != Encoding.UTF8)
            {
                throw Error.BadRequest("FHIR supports UTF-8 encoding exclusively, not " + encoding.WebName);
            }

            try
            {
                using var reader = new StreamReader(context.HttpContext.Request.Body, Encoding.UTF8);
                var body = await reader.ReadToEndAsync().ConfigureAwait(false);

                var resource = _parser.Parse <Resource>(body);
                context.HttpContext.AddResourceType(resource.GetType());

                return(await InputFormatterResult.SuccessAsync(resource).ConfigureAwait(false));
            }
            catch (FormatException exception)
            {
                throw Error.BadRequest($"Body parsing failed: {exception.Message}");
            }
        }
Esempio n. 13
0
        public override Task <object> ReadFromStreamAsync(Type type, Stream readStream, HttpContent content, IFormatterLogger formatterLogger)
        {
            try
            {
                var body = base.ReadBodyFromStream(readStream, content);

                if (type == typeof(Bundle))
                {
                    if (XmlSignatureHelper.IsSigned(body))
                    {
                        if (!XmlSignatureHelper.VerifySignature(body))
                        {
                            throw Error.BadRequest("Digital signature in body failed verification");
                        }
                    }
                }

                if (typeof(Resource).IsAssignableFrom(type))
                {
                    Resource resource = _parser.Parse <Resource>(body);
                    return(Task.FromResult <object>(resource));
                }
                else
                {
                    throw Error.Internal("The type {0} expected by the controller can not be deserialized", type.Name);
                }
            }
            catch (FormatException exc)
            {
                throw Error.BadRequest("Body parsing failed: " + exc.Message);
            }
        }
Esempio n. 14
0
        DomainResource Load(String path)
        {
            const String fcn = "Load";

            try
            {
                switch (Path.GetExtension(path).ToUpper())
                {
                case ".XML":
                {
                    FhirXmlParser parser = new FhirXmlParser();
                    return(parser.Parse <DomainResource>(File.ReadAllText(path)));
                }

                case ".JSON":
                {
                    FhirJsonParser parser = new FhirJsonParser();
                    return(parser.Parse <DomainResource>(File.ReadAllText(path)));
                }

                default:
                {
                    this.ConversionError(this.GetType().Name, fcn, $"Unknown extension for serialized fhir resource '{path}'");
                    return(null);
                }
                }
            }
            catch (Exception err)
            {
                this.ConversionError(this.GetType().Name, fcn, $"Error loading '{path}'. {err.Message}");
                return(null);
            }
        }
Esempio n. 15
0
        public Stream TerminzPost(string resource, string id, string operation)
        {
            // get Parameters from the Request Stream

            string       reqBody   = string.Empty;
            UTF8Encoding enc       = new UTF8Encoding();
            Stream       reqStream = OperationContext.Current.RequestContext.RequestMessage.GetBody <Stream>();

            using (StreamReader reader = new StreamReader(reqStream, enc))
            {
                reqBody = reader.ReadToEnd();
            }

            string reqType = WebOperationContext.Current.IncomingRequest.ContentType.ToLower();

            Parameters fParam = new Parameters();

            if (reqType.Contains("json"))
            {
                FhirJsonParser fjp = new FhirJsonParser();
                fParam = fjp.Parse <Parameters>(reqBody);
            }
            else
            {
                FhirXmlParser fxp = new FhirXmlParser();
                fParam = fxp.Parse <Parameters>(reqBody);
            }

            SetQueryParameters(fParam);

            return(TerminzGet(resource, id, operation));
        }
Esempio n. 16
0
        public void ParseEmptyContained()
        {
            var xml    = "<Patient xmlns='http://hl7.org/fhir'><contained></contained></Patient>";
            var parser = new FhirXmlParser();

            Assert.ThrowsException <FormatException>(() => parser.Parse <Patient>(xml));
        }
Esempio n. 17
0
        public void AcceptNsReassignments()
        {
            var xml = "<ns4:ValueSet xmlns:ns4=\"http://hl7.org/fhir\"><f:identifier xmlns:f=\"http://hl7.org/fhir\"><f:value value=\"....\"/></f:identifier></ns4:ValueSet>";

            FhirXmlParser.Parse <Resource>(xml);
            Assert.IsNotNull(FhirXmlParser.Parse <Resource>(xml));
        }
        /// <inheritdoc />
        /// <remarks>
        /// Reference implementation: https://github.com/aspnet/Mvc/blob/dev/src/Microsoft.AspNetCore.Mvc.Formatters.Xml/XmlDataContractSerializerInputFormatter.cs
        /// </remarks>
        public override async Task <InputFormatterResult> ReadRequestBodyAsync(InputFormatterContext context, Encoding encoding)
        {
            EnsureArg.IsNotNull(context, nameof(context));
            EnsureArg.IsNotNull(encoding, nameof(encoding));

            context.HttpContext.AllowSynchronousIO();

            HttpRequest request = context.HttpContext.Request;

            if (!request.Body.CanSeek)
            {
                request.EnableBuffering();
                await request.Body.DrainAsync(context.HttpContext.RequestAborted);

                request.Body.Seek(0L, SeekOrigin.Begin);
            }

            try
            {
                using (var textReader = XmlDictionaryReader.CreateTextReader(request.Body, encoding, XmlDictionaryReaderQuotas.Max, onClose: null))
                {
                    var model = _parser.Parse <Resource>(textReader);
                    return(InputFormatterResult.Success(model));
                }
            }
            catch (Exception ex)
            {
                var errorMessage = string.IsNullOrEmpty(ex.Message) ? Api.Resources.ParsingError : ex.Message;

                context.ModelState.TryAddModelError(string.Empty, errorMessage);
            }

            return(InputFormatterResult.Failure());
        }
        private Dictionary <string, Base> LoadProfiles(string rootPath, string searchFilter, SearchOption searchOption)
        {
            _logger.Log("Searching " + Path.GetFullPath(rootPath));
            _logger.Log("");

            Dictionary <string, Base> result = new Dictionary <string, Base>();

            IEnumerable <string> files = Directory.GetFiles(rootPath, searchFilter, searchOption);

            foreach (string file in files)
            {
                _logger.Log("Loading " + file);
                string fileContents = FileHelper.ReadInputFile(file);

                string rootNodeName = XmlHelper.GetRootNodeName(fileContents);

                Type type = getTypeFromRootNode(rootNodeName);

                FhirXmlParser parser = new FhirXmlParser();

                result.Add(file, parser.Parse(fileContents, type));
            }

            _logger.Log("");

            return(result);
        }
        public void SearchExtractionAllExamples()
        {
            string examplesZip = @"TestData\examples.zip";

            FhirXmlParser            parser               = new FhirXmlParser();
            int                      errorCount           = 0;
            int                      testFileCount        = 0;
            Dictionary <String, int> exampleSearchValues  = new Dictionary <string, int>();
            Dictionary <string, int> failedInvariantCodes = new Dictionary <string, int>();
            var                      zip = ZipFile.OpenRead(examplesZip);

            using (zip)
            {
                foreach (var entry in zip.Entries)
                {
                    Stream file = entry.Open();
                    using (file)
                    {
                        // Verified examples that fail validations

                        //// vsd-3, vsd-8
                        //if (file.EndsWith("valueset-ucum-common(ucum-common).xml"))
                        //    continue;

                        testFileCount++;
                        // Debug.WriteLine(String.Format("Validating {0}", file));
                        var reader   = SerializationUtil.WrapXmlReader(XmlReader.Create(file));
                        var resource = parser.Parse <Resource>(reader);

                        ExtractValuesForSearchParameterFromFile(exampleSearchValues, resource);

                        if (resource is Bundle)
                        {
                            foreach (var item in (resource as Bundle).Entry)
                            {
                                if (item.Resource != null)
                                {
                                    ExtractValuesForSearchParameterFromFile(exampleSearchValues, item.Resource);
                                }
                            }
                        }
                    }
                }
            }

            var missingSearchValues = exampleSearchValues.Where(i => i.Value == 0);

            if (missingSearchValues.Count() > 0)
            {
                Debug.WriteLine(String.Format("\r\n------------------\r\nValidation failed, missing data in {0} of {1} search parameters", missingSearchValues.Count(), exampleSearchValues.Count));
                foreach (var item in missingSearchValues)
                {
                    Trace.WriteLine("\t" + item.Key);
                }
                // Trace.WriteLine(outcome.ToString());
                errorCount++;
            }

            Assert.IsTrue(140 >= errorCount, String.Format("Failed search parameter data extraction, missing data in {0} of {1} search parameters", missingSearchValues.Count(), exampleSearchValues.Count));
        }
Esempio n. 21
0
        private void SearchExtractionAllExamplesInternal()
        {
            FhirXmlParser parser = new FhirXmlParser(new ParserSettings {
                PermissiveParsing = true
            });
            int errorCount          = 0;
            int testFileCount       = 0;
            var exampleSearchValues = new Dictionary <ModelInfo.SearchParamDefinition, Holder>();
            var zip = TestDataHelper.ReadTestZip("examples.zip");

            using (zip)
            {
                foreach (var entry in zip.Entries)
                {
                    Stream file = entry.Open();
                    using (file)
                    {
                        // Verified examples that fail validations

                        //// vsd-3, vsd-8
                        //if (file.EndsWith("valueset-ucum-common(ucum-common).xml"))
                        //    continue;

                        testFileCount++;
                        // Debug.WriteLine(String.Format("Validating {0}", file));
                        var reader   = SerializationUtil.WrapXmlReader(XmlReader.Create(file));
                        var resource = parser.Parse <Resource>(reader);

                        ExtractValuesForSearchParameterFromFile(exampleSearchValues, resource);

                        if (resource is Bundle)
                        {
                            foreach (var item in (resource as Bundle).Entry)
                            {
                                if (item.Resource != null)
                                {
                                    ExtractValuesForSearchParameterFromFile(exampleSearchValues, item.Resource);
                                }
                            }
                        }
                    }
                }
            }

            var missingSearchValues = exampleSearchValues.Where(i => i.Value.count == 0);

            if (missingSearchValues.Count() > 0)
            {
                Debug.WriteLine(String.Format("\r\n------------------\r\nValidation failed, missing data in {0} of {1} search parameters", missingSearchValues.Count(), exampleSearchValues.Count));
                foreach (var item in missingSearchValues)
                {
                    Trace.WriteLine("\t" + item.Key.Resource.ToString() + "_" + item.Key.Name);
                }
                // Trace.WriteLine(outcome.ToString());
                errorCount++;
            }

            Assert.IsTrue(140 >= errorCount, String.Format("Failed search parameter data extraction, missing data in {0} of {1} search parameters", missingSearchValues.Count(), exampleSearchValues.Count));
        }
Esempio n. 22
0
        /// <summary>
        /// Adds individual FHIR Resource Instance files attached to the implementation guide being exported
        /// to the ZIP package
        /// </summary>
        /// <remarks>Uses the mime-type of the file to determine if the attached file is xml or json.</remarks>
        private void AddResourceInstances()
        {
            var parserSettings = new fhir_latest.Hl7.Fhir.Serialization.ParserSettings();

            parserSettings.AcceptUnknownMembers        = true;
            parserSettings.AllowUnrecognizedEnums      = true;
            parserSettings.DisallowXsiAttributesOnRoot = false;
            var fhirXmlParser  = new FhirXmlParser(parserSettings);
            var fhirJsonParser = new FhirJsonParser(parserSettings);

            // Check that each FHIR resource instance is valid and has the required fields
            foreach (var file in ig.Files)
            {
                var fileData = file.GetLatestData();
                fhir_latest.Hl7.Fhir.Model.Resource resource = null;
                string resourceContent;
                string fileExtension = "";

                try
                {
                    string fileContent = System.Text.Encoding.UTF8.GetString(fileData.Data);

                    if (file.MimeType == "application/xml" || file.MimeType == "text/xml")
                    {
                        resource      = fhirXmlParser.Parse <fhir_latest.Hl7.Fhir.Model.Resource>(fileContent);
                        fileExtension = "xml";
                    }
                    else if (file.MimeType == "application/json" || file.MimeType == "binary/octet-stream")
                    {
                        resource      = fhirJsonParser.Parse <fhir_latest.Hl7.Fhir.Model.Resource>(fileContent);
                        fileExtension = "json";
                    }
                }
                catch
                {
                }

                if (resource == null || string.IsNullOrEmpty(resource.Id))
                {
                    continue;
                }

                try
                {
                    // Convert the resource to the desired format for output
                    resourceContent = this.Serialize(resource);
                    fileExtension   = this.JsonFormat ? "json" : "xml";
                    string fileName = string.Format("resources/{0}/{1}.{2}", resource.ResourceType.ToString().ToLower(), resource.Id, fileExtension);

                    // Add the resource to the zip file
                    this.zip.AddEntry(fileName, resourceContent);
                }
                catch
                {
                    string fileName = string.Format("resources/{0}/{1}.{2}", resource.ResourceType.ToString().ToLower(), resource.Id, fileExtension);
                    this.zip.AddEntry(fileName, fileData.Data);
                }
            }
        }
Esempio n. 23
0
        public void ProcessExpression()
        {
            //string Expression = $"(AuditEvent.entity.what.value as Reference).Url";
            string Expression = $"AuditEvent.entity.what.where(resolve() is Patient)";

            //string Expression = $"AuditEvent.entity.what.reference.startsWith('Patient')";
            //string Expression = $"AuditEvent.entity.what.where(reference.startsWith('Patient/') or reference.contains('/Patient/')) | AuditEvent.agent.who.where(reference.startsWith('Patient/') or reference.contains('/Patient/'))";
            //string Expression = $"AuditEvent.entity.what.where(reference.startsWith('Patient'))";
            Console.Write($"FHIR Path Expression: {Expression}");
            FhirXmlParser FhirXmlParser = new FhirXmlParser();
            Resource      Resource      = FhirXmlParser.Parse <Resource>(ResourceStore.FhirResource1);
            //Hl7.Fhir.ElementModel.PocoNavigator Navigator = new Hl7.Fhir.ElementModel.PocoNavigator(Resource);
            var TypedElement = Resource.ToTypedElement();

            try
            {
                FHIRTools.R4.Common.FhirPathTools.FhirPathProcessor FhirPathProcessor = new Common.FhirPathTools.FhirPathProcessor();
                var CompileEx = FhirPathProcessor.ParseExpression(Expression);


                Hl7.FhirPath.FhirPathCompiler.DefaultSymbolTable.AddFhirExtensions();

                var oFhirEvaluationContext = new Hl7.Fhir.FhirPath.FhirEvaluationContext(TypedElement);


                //The resolve() function then also needs to be provided an external resolver delegate that performs the resolve
                //that delegate can be set as below. Here I am providing my own implementation 'IPyroFhirPathResolve.Resolver'
                oFhirEvaluationContext.ElementResolver = FHIRTools.R4.Common.FhirPathTools.CustomFhirPathResolver.Resolver;
                IEnumerable <ITypedElement> ResultList = TypedElement.Select(Expression, oFhirEvaluationContext);
                //IEnumerable<IElementNavigator> ResultList = Navigator.Select(Expression, oFhirEvaluationContext);



                foreach (ITypedElement oElement in ResultList)
                {
                    if (oElement is IFhirValueProvider FhirValueProvider)
                    {
                        if (FhirValueProvider.FhirValue is ResourceReference Ref)
                        {
                            Console.WriteLine($"Found: {Ref.Url.ToString()}");
                        }
                        else
                        {
                            Console.WriteLine($"TYpe was: {FhirValueProvider.FhirValue.GetType().ToString()}");
                        }
                    }
                    else
                    {
                        Console.WriteLine();
                        Console.WriteLine("No Value Found!");
                    }
                }
            }
            catch (Exception Exec)
            {
                Console.WriteLine();
                Console.WriteLine($"Error Message: {Exec.Message}");
            }
        }
Esempio n. 24
0
        public void HandleCommentsXml()
        {
            string xml = TestDataHelper.ReadTestData("TestPatient.xml");

            var pat = FhirXmlParser.Parse <Patient>(xml);

            Assert.AreEqual(1, pat.Name[0].FhirCommentsElement.Count);
            Assert.AreEqual("See if this is roundtripped", pat.Name[0].FhirComments.First());

            pat.Name[0].FhirCommentsElement.Add(new FhirString("A second line"));

            xml = FhirXmlSerializer.SerializeToString(pat);

            Assert.AreEqual(2, pat.Name[0].FhirCommentsElement.Count);
            Assert.AreEqual("See if this is roundtripped", pat.Name[0].FhirComments.First());
            Assert.AreEqual("A second line", pat.Name[0].FhirComments.Skip(1).First());
        }
Esempio n. 25
0
        public void ConfigureFailOnUnknownMember()
        {
            var xml    = "<Patient xmlns='http://hl7.org/fhir'><daytona></daytona></Patient>";
            var parser = new FhirXmlParser();

            try
            {
                parser.Parse <Resource>(xml);
                Assert.Fail("Should have failed on unknown member");
            }
            catch (FormatException)
            {
            }

            parser.Settings.AcceptUnknownMembers = true;
            parser.Parse <Resource>(xml);
        }
Esempio n. 26
0
        public void ParsePerfXml()
        {
            string xml  = TestDataHelper.ReadTestData("TestPatient.xml");
            var    pser = new FhirXmlParser();

            // Assume that we can happily read the patient gender when enums are enforced
            var p = pser.Parse <Patient>(xml);

            var sw = new Stopwatch();

            sw.Start();
            for (var i = 0; i < 500; i++)
            {
                p = pser.Parse <Patient>(xml);
            }
            sw.Stop();
            Debug.WriteLine($"Parsing took {sw.ElapsedMilliseconds / 500.0 * 1000} micros");
        }
Esempio n. 27
0
        private static T DeserializeXmlResource <T>(string data)
            where T : Base
        {
            FhirXmlParser parser = new FhirXmlParser(new ParserSettings {
                PermissiveParsing = false
            });

            return(parser.Parse <T>(data));
        }
Esempio n. 28
0
        public void AddFragment(String filePath)
        {
            const String fcn = "AddFragment";

            DomainResource domainResource;

            switch (Path.GetExtension(filePath).ToUpper(CultureInfo.InvariantCulture))
            {
            case ".XML":
            {
                FhirXmlParser parser = new FhirXmlParser();
                domainResource = parser.Parse <DomainResource>(File.ReadAllText(filePath));
                break;
            }

            case ".JSON":
            {
                FhirJsonParser parser = new FhirJsonParser();
                domainResource = parser.Parse <DomainResource>(File.ReadAllText(filePath));
                break;
            }

            default:
                throw new Exception($"Unknown extension for serialized fhir resource '{filePath}'");
            }

            switch (domainResource)
            {
            case CodeSystem cs:
            {
                CSInfo ci = new CSInfo(cs);
                this.CodeSystems.Add(cs.Url, ci);
            }
            break;

            case ValueSet vs:
            {
                VSInfo vi = new VSInfo(vs);
                this.ValueSets.Add(vs.Url, vi);
            }
            break;

            case StructureDefinition sd:
            {
                SDInfo fi = new SDInfo(this, sd);
                this.SDFragments.Add(sd.Url.Trim(), fi);
            }
            break;

            default:
                this.ConversionError(this.GetType().Name,
                                     fcn,
                                     $"Unimplemented fragment resource type {domainResource.GetType().Name} file {filePath}");
                return;
            }
        }
        public void ThenTheResponseBodyShouldBeFHIRXML()
        {
            _httpContext.HttpResponse.ContentType.ShouldStartWith(ContentType.Application.FhirXml);
            Log.WriteLine("Response ContentType={0}", _httpContext.HttpResponse.ContentType);
            // TODO Move XML Parsing Out Of Here
            _httpContext.HttpResponse.ResponseXML = XDocument.Parse(_httpContext.HttpResponse.Body);
            FhirXmlParser fhirXmlParser = new FhirXmlParser();

            _httpContext.FhirResponse.Resource = fhirXmlParser.Parse <Resource>(_httpContext.HttpResponse.Body);
        }
        public void AcceptUnknownEnums()
        {
            string xml  = TestDataHelper.ReadTestData("TestPatient.xml");
            var    pser = new FhirXmlParser();

            // Assume that we can happily read the patient gender when enums are enforced
            var p = pser.Parse <Patient>(xml);

            Assert.IsNotNull(p.Gender);
            Assert.AreEqual("male", p.GenderElement.ObjectValue);
            Assert.AreEqual(AdministrativeGender.Male, p.Gender.Value);

            // Verify that if we relax the restriction that everything still works
            pser.Settings.AllowUnrecognizedEnums = true;
            p = pser.Parse <Patient>(xml);

            Assert.IsNotNull(p.Gender);
            Assert.AreEqual("male", p.GenderElement.ObjectValue);
            Assert.AreEqual(AdministrativeGender.Male, p.Gender.Value);


            // Now, pollute the data with an incorrect administrative gender
            // and verify that the system throws the format exception
            var xml2 = xml.Replace("\"male\"", "\"superman\"");

            try
            {
                pser.Settings.AllowUnrecognizedEnums = false;
                p = pser.Parse <Patient>(xml2);
                Assert.Fail();
            }
            catch (FormatException)
            {
                // By default, should *not* accept unknown enums
            }

            // Now, allow unknown enums and check support
            pser.Settings.AllowUnrecognizedEnums = true;
            p = pser.Parse <Patient>(xml2);
            Assert.IsNull(p.Gender);
            Assert.AreEqual("superman", p.GenderElement.ObjectValue);
        }