Beispiel #1
0
        public void AcceptUnknownEnums()
        {
            string xml  = File.ReadAllText(@"TestData\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);
        }
Beispiel #2
0
        private void roundTripOneExample(string filename)
        {
            string testFileName = filename;
            var    original     = TestDataHelper.ReadTestData(testFileName);

            var t = new FhirXmlParser().Parse <Resource>(original);

            var outputXml = new FhirXmlSerializer().SerializeToString(t);

            XmlAssert.AreSame(testFileName, original, outputXml);

            var outputJson = new FhirJsonSerializer().SerializeToString(t);
            var t2         = new FhirJsonParser().Parse <Resource>(outputJson);

            Assert.IsTrue(t.IsExactly(t2));

            var outputXml2 = new FhirXmlSerializer().SerializeToString(t2);

            XmlAssert.AreSame(testFileName, original, outputXml2);
        }
Beispiel #3
0
        private void convertFeed(string inputFile, string outputFile)
        {
            //TODO: call validation after reading

            if (inputFile.EndsWith(".xml"))
            {
                var xml      = File.ReadAllText(inputFile);
                var resource = new FhirXmlParser().Parse <Resource>(xml);

                var json = new FhirJsonSerializer().SerializeToString(resource);
                File.WriteAllText(outputFile, json);
            }
            else
            {
                var json     = File.ReadAllText(inputFile);
                var resource = new FhirJsonParser().Parse <Resource>(json);
                var xml      = new FhirXmlSerializer().SerializeToString(resource);
                File.WriteAllText(outputFile, xml);
            }
        }
        private void forDoc()
        {
            FhirXmlParser parser = new FhirXmlParser(new ParserSettings {
                AcceptUnknownMembers = true
            });
            IFhirReader xmlWithPatientData = null;
            var         patient            = parser.Parse <Patient>(xmlWithPatientData);

            // -----

            ArtifactResolver source = ArtifactResolver.CreateCachedDefault();
            var settings            = new SnapshotGeneratorSettings {
                IgnoreMissingTypeProfiles = true
            };
            StructureDefinition profile = null;

            var generator = new SnapshotGenerator(source, _settings);

            generator.Generate(profile);
        }
Beispiel #5
0
        /// <summary>
        /// Read profile from disk
        /// </summary>
        /// <returns></returns>
        StructureDefinition ReadProfile(String profilePath)
        {
            const String fcn = "ReadProfile";

            if (File.Exists(profilePath) == false)
            {
                throw new NotImplementedException($"Profile file {profilePath} not found");
            }

            String fhirText = File.ReadAllText(profilePath);
            String ext      = Path.GetExtension(profilePath).ToLower();
            Base   resource;

            switch (ext)
            {
            case ".xml":
            {
                FhirXmlParser parser = new FhirXmlParser();
                resource = parser.Parse <Base>(fhirText);
            }
            break;

            case ".json":
            {
                FhirJsonParser parser = new FhirJsonParser();
                resource = parser.Parse(fhirText, typeof(Resource));
            }
            break;

            default:
                throw new NotImplementedException($"Can not handle files of type ");
            }

            if (resource.TypeName != "StructureDefinition")
            {
                this.ConversionError(this.GetType().Name, fcn, $"File {profilePath} is {resource.TypeName}, not StructuredDefinition");
                return(null);
            }

            return((StructureDefinition)resource);
        }
Beispiel #6
0
        public void AddResource(String path,
                                VerifyDel verifyDel)
        {
            DomainResource domainResource;

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

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

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

            if (verifyDel != null)
            {
                if (verifyDel(domainResource) == false)
                {
                    return;
                }
            }

            ResourceMap.Node node = this.CreateMapNode(domainResource);
            if (node == null)
            {
                return;
            }
            this.nodes.Add(node.ResourceUrl, node);
            this.resources.Add(domainResource.GetUrl(), domainResource);
        }
        private static Resource parseResource(string bodyText, string contentType, ParserSettings settings, bool throwOnFormatException)
        {
            Resource result = null;

            var fhirType = ContentType.GetResourceFormatFromContentType(contentType);

            if (fhirType == ResourceFormat.Unknown)
            {
                throw new UnsupportedBodyTypeException(
                          "Endpoint returned a body with contentType '{0}', while a valid FHIR xml/json body type was expected. Is this a FHIR endpoint?"
                          .FormatWith(contentType), contentType, bodyText);
            }

            if (!SerializationUtil.ProbeIsJson(bodyText) && !SerializationUtil.ProbeIsXml(bodyText))
            {
                throw new UnsupportedBodyTypeException(
                          "Endpoint said it returned '{0}', but the body is not recognized as either xml or json.".FormatWith(contentType), contentType, bodyText);
            }

            try
            {
                if (fhirType == ResourceFormat.Json)
                {
                    result = new FhirJsonParser(settings).Parse <Resource>(bodyText);
                }
                else
                {
                    result = new FhirXmlParser(settings).Parse <Resource>(bodyText);
                }
            }
            catch (FormatException fe)
            {
                if (throwOnFormatException)
                {
                    throw fe;
                }
                return(null);
            }

            return(result);
        }
        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);
            }

            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 (XmlDictionaryReader reader = XmlDictionaryReader.CreateTextReader(request.Body, encoding, XmlDictionaryReaderQuotas.Max, onClose: null))
                {
                    FhirXmlParser parser   = context.HttpContext.RequestServices.GetRequiredService <FhirXmlParser>();
                    var           resource = parser.Parse(reader);
                    return(InputFormatterResult.Success(resource));
                }
            }
            catch (FormatException exception)
            {
                throw Error.BadRequest($"Body parsing failed: {exception.Message}");
            }
        }
Beispiel #9
0
        public FhirClient(HttpClient httpClient, ResourceFormat format)
        {
            HttpClient = httpClient;
            _format    = format;

            if (format == ResourceFormat.Json)
            {
                var jsonSerializer = new FhirJsonSerializer();

                _serializer = jsonSerializer;
                _serialize  = (resource, summary) => jsonSerializer.SerializeToString(resource, summary);

                var jsonParser = new FhirJsonParser();

                _parser      = jsonParser;
                _deserialize = jsonParser.Parse <Resource>;

                _contentType = ContentType.JSON_CONTENT_HEADER;
            }
            else if (format == ResourceFormat.Xml)
            {
                var xmlSerializer = new FhirXmlSerializer();

                _serializer = xmlSerializer;
                _serialize  = (resource, summary) => xmlSerializer.SerializeToString(resource, summary);

                var xmlParser = new FhirXmlParser();

                _parser      = xmlParser;
                _deserialize = xmlParser.Parse <Resource>;

                _contentType = ContentType.XML_CONTENT_HEADER;
            }
            else
            {
                throw new InvalidOperationException("Unsupported format.");
            }

            _mediaType = MediaTypeWithQualityHeaderValue.Parse(_contentType);
            SetupAuthenticationAsync(TestApplications.ServiceClient).GetAwaiter().GetResult();
        }
        public static IEnumerable <StructureDefinition> GetStructureDefinitions()
        {
            var xmlParser = new FhirXmlParser();
            var structureDefinitionsPath = GetStructureDefinitionsPath();

            if (!Directory.Exists(structureDefinitionsPath))
            {
                yield break;
            }
            var files = Directory.GetFiles(GetStructureDefinitionsPath());

            foreach (var file in files)
            {
                using (var stream = new FileStream(file, FileMode.Open))
                {
                    var xDocument           = XDocument.Load(stream);
                    var structureDefinition = xmlParser.Parse <StructureDefinition>(xDocument.ToString());
                    yield return(structureDefinition);
                }
            }
        }
        public void UseFileArtifactSource()
        {
            var fa = new DirectorySource(_testPath);

            fa.Mask = "*.xml|*.xsd";
            var names = fa.ListArtifactNames();

            Assert.AreEqual(5, names.Count());
            Assert.IsTrue(names.Contains("extension-definitions.xml"));
            Assert.IsTrue(names.Contains("flag.xsd"));
            Assert.IsFalse(names.Contains("patient.sch"));
            Assert.IsTrue(names.Contains("TestPatient.xml"));
            Assert.IsTrue(names.Contains("nonfhir.xml"));
            Assert.IsTrue(names.Contains("invalid.xml"));

            using (var stream = fa.LoadArtifactByName("TestPatient.xml"))
            {
                var pat = new FhirXmlParser().Parse <Resource>(SerializationUtil.XmlReaderFromStream(stream));
                Assert.IsNotNull(pat);
            }
        }
Beispiel #12
0
        public PatientFixture()
        {
            var parser = new FhirXmlParser();
            var tpXml  = TestData.ReadTextFile("fp-test-patient.xml");

            var patient = parser.Parse <Patient>(tpXml);

            TestInput = patient.ToTypedElement();

            tpXml = TestData.ReadTextFile("questionnaire-example.xml");
            var quest = parser.Parse <Questionnaire>(tpXml);

            Questionnaire = quest.ToTypedElement();

            tpXml = TestData.ReadTextFile("uuid.profile.xml");
            var uuid = parser.Parse <StructureDefinition>(tpXml);

            UuidProfile = uuid.ToTypedElement();

            Xdoc = new XDocument(new XElement("group", new XAttribute("name", "CSharpTests")));
        }
Beispiel #13
0
 private static Resource ParseResource(string data)
 {
     if (SerializationUtil.ProbeIsJson(data))
     {
         FhirJsonParser parser = new FhirJsonParser(new ParserSettings {
             PermissiveParsing = Settings.PermissiveParsing
         });
         return(parser.Parse <Resource>(data));
     }
     else if (SerializationUtil.ProbeIsXml(data))
     {
         FhirXmlParser parser = new FhirXmlParser(new ParserSettings {
             PermissiveParsing = Settings.PermissiveParsing
         });
         return(parser.Parse <Resource>(data));
     }
     else
     {
         throw new FormatException("Data is neither Json nor Xml");
     }
 }
Beispiel #14
0
        private static Bundle GetDocument(string documentReferenceUrl)
        {
            try
            {
                var client = new HttpClient();
                client.DefaultRequestHeaders.Accept.Add(new System.Net.Http.Headers.MediaTypeWithQualityHeaderValue("application/fhir+xml"));
                var           responseString = client.GetStringAsync(documentReferenceUrl).Result;
                FhirXmlParser parser         = new FhirXmlParser();
                var           bundle         = parser.Parse <Bundle>(responseString);
                Console.WriteLine("The following bundle was found {0}", bundle.ToString());
                Console.WriteLine("Please press any key to continue...");
                Console.ReadKey();
                return(bundle);
            }
            catch (Exception exc)
            {
                HandleException(exc, "An error occured whilst getting the document from the API.");
            }

            return(null);
        }
        public void AcceptXsiStuffOnRoot()
        {
            var xml = "<Patient xmlns='http://hl7.org/fhir' xmlns:xsi='http://www.w3.org/2001/XMLSchema-instance' " +
                      "xsi:schemaLocation='http://hl7.org/fhir ../../schema/fhir-all.xsd'></Patient>";
            var parser = new FhirXmlParser();

            // By default, parser will accept xsi: elements
            parser.Parse <Resource>(xml);

            // Now, enforce xsi: attributes are no longer accepted
            parser.Settings.DisallowXsiAttributesOnRoot = true;

            try
            {
                parser.Parse <Resource>(xml);
                Assert.Fail("Should have failed on xsi: elements in root");
            }
            catch (FormatException)
            {
            }
        }
Beispiel #16
0
        public FhirResponse ParseFhirResource()
        {
            var fhirResponse = new FhirResponse();

            switch (ContentType)
            {
            case Constants.ContentType.Application.FhirJson:
                ResponseJSON = JObject.Parse(Body);
                var jsonParser = new FhirJsonParser();
                fhirResponse.Resource = jsonParser.Parse <Resource>(Body);
                break;

            case Constants.ContentType.Application.FhirXml:
                ResponseXML = XDocument.Parse(Body);
                var xmlParser = new FhirXmlParser();
                fhirResponse.Resource = xmlParser.Parse <Resource>(Body);
                break;
            }

            return(fhirResponse);
        }
Beispiel #17
0
        public static Bundle LoadProfileBundle()
        {
            string resourceLocation = "Trifolia.Shared.FHIR.Profiles.Latest.profiles-resources.xml";
            var    resourceStream   = System.Reflection.Assembly.GetExecutingAssembly().GetManifestResourceStream(resourceLocation);

            using (StreamReader profileReader = new StreamReader(resourceStream))
            {
                var parserSettings = new ParserSettings();
                parserSettings.AcceptUnknownMembers        = true;
                parserSettings.AllowUnrecognizedEnums      = true;
                parserSettings.DisallowXsiAttributesOnRoot = false;

                var    parser        = new FhirXmlParser(parserSettings);
                Bundle profileBundle = parser.Parse <Bundle>(profileReader.ReadToEnd());

                AppDomain.CurrentDomain.SetData(appDomainProfileBundleKey, profileBundle);

                GC.Collect();

                return(profileBundle);
            }
        }
Beispiel #18
0
        static void Main(string[] args)
        {
            var parser      = new FhirXmlParser();
            var ProfileList = new List <ProfileInfo>();

            for (int i = 1; i <= 24; i++)
            {
                var name     = "Profile_";
                var profile  = name + i.ToString();
                var p        = Resources.ResourceManager.GetObject(profile).ToString();
                var profile1 = parser.Parse <StructureDefinition>(Resources.ComparisonProfile);
                var profile2 = parser.Parse <StructureDefinition>(p);
                // compute distance between profiles
                var EditDist    = DistanceTrees(profile1, profile2);
                var profileInfo = new ProfileInfo();

                profileInfo.Profiel = profile;
                profileInfo.ED      = EditDist;
                ProfileList.Add(profileInfo);
            }
            List <ProfileInfo> SortedProfileList = ProfileList.OrderBy(t => t.ED).ThenBy(t => t.Profiel).ToList();

            foreach (ProfileInfo p in SortedProfileList)
            {
                var profiel = p.Profiel + ";" + p.ED.ToString();
                lines4.Add(profiel);
            }
            string path4 = "C:/Users/TessaA/Documents/profilecomparison/ranking.csv";

            // file with a ranking of the profile set
            File.WriteAllLines(path4, lines4);
            string path2 = "C:/Users/TessaA/Documents/profilecomparison/test2.txt";
            string path3 = "C:/Users/TessaA/Documents/profilecomparison/test3.csv";

            // file with log of all differences between profiles
            File.WriteAllLines(path2, lines2);
            // file with edit distance matrix between two profiles
            File.WriteAllLines(path3, lines3);
        }
        private async SystemTasks.Task <FhirResponse> ParseResource(HttpContent content, CommandRequest request, FhirResponse fhirResponse)
        {
            var data = await content.ReadAsStreamAsync();

            if (data == null)
            {
                throw new HttpRequestException($"Request resulted in nothing for: {request.FullUrl}.");
            }

            using (var reader = new StreamReader(data, Encoding.UTF8))
            {
                try
                {
                    var mediaType = content.Headers.ContentType.MediaType.ToLowerInvariant();

                    var body = reader.ReadToEnd();

                    if (!string.IsNullOrEmpty(body))
                    {
                        if (mediaType.Contains("xml"))
                        {
                            var xmlParser = new FhirXmlParser();
                            fhirResponse.Resource = xmlParser.Parse <Resource>(body);
                        }
                        else
                        {
                            var jsonParser = new FhirJsonParser();
                            fhirResponse.Resource = jsonParser.Parse <Resource>(body);
                        }
                    }
                }
                catch (Exception ex)
                {
                    throw new HttpRequestException(ex.Message, ex.InnerException);
                }
            }

            return(fhirResponse);
        }
        public void RunPerfTest()
        {
            string xml  = File.ReadAllText(@"TestData\TestPatient.xml");
            string json = File.ReadAllText(@"TestData\TestPatient.json");

            //string xml = Hl7.Fhir.Core.Tests.Properties.TestResources.TestPatientXml;
            //string json = Hl7.Fhir.Core.Tests.Properties.TestResources.TestPatientJson;

            var once = new FhirXmlParser().Parse <Resource>(xml);

            Stopwatch x = new Stopwatch();

            x.Start();

            for (int i = 0; i < 1000; i++)
            {
                var result = new FhirXmlParser().Parse <Resource>(xml);
            }
            x.Stop();

            Debug.WriteLine(x.ElapsedMilliseconds);
        }
Beispiel #21
0
        private static Resource ParseResource(string data)
        {
            if (SerializationUtil.ProbeIsJson(data))
            {
                // TODO read config to determine if PermissiveParsing should be on
                var parser = new FhirJsonParser(new ParserSettings {
                    PermissiveParsing = true
                });
                return(parser.Parse <Resource>(data));
            }

            if (SerializationUtil.ProbeIsXml(data))
            {
                // TODO read config to determine if PermissiveParsing should be on
                var parser = new FhirXmlParser(new ParserSettings {
                    PermissiveParsing = true
                });
                return(parser.Parse <Resource>(data));
            }

            throw new FormatException("Data is neither Json nor Xml");
        }
Beispiel #22
0
        public void CheckComparePrimitiveChanged()
        {
            string xml = File.ReadAllText(@"TestData\TestPatient.xml");

            var p  = new FhirXmlParser().Parse <Patient>(xml);
            var p2 = (Patient)p.DeepCopy();

            // If you set an element to null in the pattern, it need not be set in the source
            p2.Gender = null;
            Assert.IsFalse(p2.Matches(p));
            Assert.IsTrue(p.Matches(p2));

            // If both are null, we're fine
            p.Gender = null;
            Assert.IsTrue(p2.Matches(p));
            Assert.IsTrue(p.Matches(p2));

            p2.Contact[0].Relationship[0].Coding[0].System = "http://nu.nl/different";

            Assert.IsFalse(p2.Matches(p));
            Assert.IsFalse(p.Matches(p2));
        }
Beispiel #23
0
        public void DiscoverExtensions()
        {
            // Do ndjson too!
            string exampleResourcesPath = @"C:\git\MySL.FhirIG\examples";

            foreach (string file in Directory.EnumerateFiles(exampleResourcesPath, "*.xml", SearchOption.AllDirectories))
            {
                try
                {
                    var resource = new FhirXmlParser().Parse <Resource>(File.ReadAllText(file));
                    System.Diagnostics.Trace.WriteLine($"{file} {resource.TypeName}/{resource.Id}");
                    if (resource is Bundle bundle)
                    {
                        foreach (var entry in bundle.Entry.Select(e => e.Resource))
                        {
                            if (entry != null)
                            {
                                System.Diagnostics.Trace.WriteLine($"  -->{entry.TypeName}/{entry.Id}");
                                ScanForExtensions(null, entry.ToTypedElement(), null);
                            }
                        }
                    }
                    else
                    {
                        ScanForExtensions(null, resource.ToTypedElement(), null);
                    }
                }
                catch (Exception ex)
                {
                    System.Diagnostics.Trace.WriteLine($"{file}");
                    System.Diagnostics.Trace.WriteLine($"  ==> Exception {ex.Message}");
                }
            }

            // Next pass was to update the type profile - including the generated extensions.
            // - while merging the profile
            // -- if it is sliced, but not slice for the value, suggest a new one?
            // -- with observations - based on a common profile, then train it on a folder to learn what they should look like
        }
Beispiel #24
0
        public CapabilityStatement.RestComponent GetRestDefinition()
        {
            var assembly = Assembly.GetExecutingAssembly();
            var names    = assembly.GetManifestResourceNames();

            foreach (var name in names)
            {
                if (!name.EndsWith("ExampleServiceRest.xml"))
                {
                    continue;
                }
                using (var stream = assembly.GetManifestResourceStream(name))
                {
                    var xDocument = XDocument.Load(stream);
                    var parser    = new FhirXmlParser();
                    var item      =
                        parser.Parse <CapabilityStatement>(xDocument.ToString());
                    return(item.Rest[0]);
                }
            }
            throw new InvalidDataException();
        }
Beispiel #25
0
        /// <summary>
        /// Gets the specified resource type's profile
        /// </summary>
        /// <remarks>All profiles are stored in resources embedded within the Trifolia.Shared assembly. This method parses the
        /// profile embedded in the assembly and returns the resulting StructureDefinition.</remarks>
        /// <param name="resourceType">The resource type whose profile is to be retrieved</param>
        public static StructureDefinition GetProfile(string resourceType)
        {
            string resourceLocation = string.Format(resourceLocationFormat, resourceType);
            var    resourceStream   = System.Reflection.Assembly.GetExecutingAssembly().GetManifestResourceStream(resourceLocation);

            if (resourceStream == null)
            {
                return(null);
            }

            using (StreamReader profileReader = new StreamReader(resourceStream))
            {
                var parserSettings = new ParserSettings();
                parserSettings.AcceptUnknownMembers        = true;
                parserSettings.AllowUnrecognizedEnums      = true;
                parserSettings.DisallowXsiAttributesOnRoot = false;

                var parser = new FhirXmlParser(parserSettings);
                StructureDefinition profile = parser.Parse <StructureDefinition>(profileReader.ReadToEnd());

                return(profile);
            }
        }
Beispiel #26
0
        public void AnnotationDeserializer()
        {
            var pat = createData();

            pat.AddAnnotation(new YadaYadaAnnotation {
                Num = 4
            });
            var xmlSerializer = new FhirXmlSerializer(new ParserSettings()
            {
                CustomSerializer = new DumpAnnotationCustomSerializer()
            });
            var patXml = xmlSerializer.SerializeToString(pat);

            var xmlDeserializer = new FhirXmlParser(new ParserSettings()
            {
                CustomDeserializer = new RetrieveAnnotationCustomDeserializer()
            });
            var yadaPat = xmlDeserializer.Parse <Patient>(patXml);

            var yada = yadaPat.Annotation <YadaYadaAnnotation>();

            Assert.AreEqual(4, yada?.Num);
        }
Beispiel #27
0
        public void TestValidateDiagnosticReport(string xmlResource)
        {
            var assembly = Assembly.GetExecutingAssembly();
            var names    = assembly.GetManifestResourceNames();
            DiagnosticReport diagnosticReport = null;
            var       item      = names.FirstOrDefault(t => t.EndsWith(xmlResource));
            XDocument xDocument = null;

            if (item != null)
            {
                using (var stream = assembly.GetManifestResourceStream(item))
                {
                    xDocument = XDocument.Load(stream);
                }
                diagnosticReport = new FhirXmlParser().Parse <DiagnosticReport>(xDocument.ToString());
            }
            Assert.IsNotNull(diagnosticReport);

            var validResource = _profileValidator.Validate(diagnosticReport, true, true);
            var xmlSerializer = new FhirXmlSerializer();

            Console.WriteLine(xmlSerializer.SerializeToString(validResource));
        }
Beispiel #28
0
        /// <summary>
        /// Get patient list
        /// </summary>
        /// <param name="filePath"></param>
        /// <returns></returns>
        public List <PatientViewModel> GetPatientList(string filePath)
        {
            List <PatientViewModel> patientList = new List <PatientViewModel>();
            FhirXmlParser           fjp         = new FhirXmlParser();

            if (AppSettings.StoredPatientInAzure)
            {
                //get the patient information from Azure Storage
                List <KeyValuePair <string, string> > azurePatientList = AzureStorageHelper.ListAllBlobFromAzure("", ".xml");
                foreach (KeyValuePair <string, string> item in azurePatientList)
                {
                    var fhirPatient = fjp.Parse <Hl7.Fhir.Model.Patient>(item.Value);
                    if (fhirPatient != null)
                    {
                        patientList.Add(ConvertFhirToViewModel(fhirPatient));
                    }
                }
            }
            else
            {
                //get the patient information from local folder
                string[] jsonFiles = Directory.GetFiles(filePath, "*.xml");
                if (jsonFiles != null && jsonFiles.Length > 0)
                {
                    foreach (string fileName in jsonFiles)
                    {
                        var fhirPatient = fjp.Parse <Hl7.Fhir.Model.Patient>(File.ReadAllText(fileName));
                        if (fhirPatient != null)
                        {
                            patientList.Add(ConvertFhirToViewModel(fhirPatient));
                        }
                    }
                }
            }

            return(patientList.OrderBy(p => p.FullName).ToList());
        }
        public override Task <object> ReadFromStreamAsync(Type type, Stream readStream, HttpContent content, IFormatterLogger formatterLogger)
        {
            return(System.Threading.Tasks.Task.Factory.StartNew <object>(() =>
            {
                try
                {
                    var body = 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))
                    {
                        throw Error.Internal("The type {0} expected by the controller can not be deserialized",
                                             type.Name);
                    }

                    //var fhirparser = new FhirJsonParser();
                    //var resource = fhirparser.Parse(body, type);
                    var fhirXmlParser = new FhirXmlParser();
                    var resource = fhirXmlParser.Parse(body, type);
                    return resource;
                }
                catch (FormatException exc)
                {
                    throw Error.BadRequest("Body parsing failed: " + exc.Message);
                }
            }));
        }
Beispiel #30
0
        public void ValidateDemoPatient()
        {
            var s = new StringReader(TestDataHelper.ReadTestData(@"TestPatient.xml"));

            var patient = new FhirXmlParser().Parse <Patient>(XmlReader.Create(s));

            ICollection <ValidationResult> results = new List <ValidationResult>();

            foreach (var contained in patient.Contained)
            {
                ((DomainResource)contained).Text = new Narrative()
                {
                    Div = "<wrong />"
                }
            }
            ;

            Assert.IsFalse(DotNetAttributeValidation.TryValidate(patient, results, true));
            Assert.IsTrue(results.Count > 0);

            results.Clear();
            foreach (DomainResource contained in patient.Contained)
            {
                contained.Text = null;
            }

            // Try again
            Assert.IsTrue(DotNetAttributeValidation.TryValidate(patient, results, true));

            patient.Identifier[0].System = "urn:oid:crap really not valid";

            results = new List <ValidationResult>();

            Assert.IsFalse(DotNetAttributeValidation.TryValidate(patient, results, true));
            Assert.IsTrue(results.Count > 0);
        }
    }