Example #1
0
        public void TestSigning()
        {
            Bundle b = new Bundle();

            b.Title       = "Updates to resource 233";
            b.Id          = new Uri("urn:uuid:0d0dcca9-23b9-4149-8619-65002224c3");
            b.LastUpdated = new DateTimeOffset(2012, 11, 2, 14, 17, 21, TimeSpan.Zero);
            b.AuthorName  = "Ewout Kramer";

            ResourceEntry <Patient> p = new ResourceEntry <Patient>();

            p.Id            = new ResourceIdentity("http://test.com/fhir/Patient/233");
            p.Resource      = new Patient();
            p.Resource.Name = new List <HumanName> {
                HumanName.ForFamily("Kramer").WithGiven("Ewout")
            };
            b.Entries.Add(p);

            var certificate = getCertificate();

            var bundleData   = FhirSerializer.SerializeBundleToXmlBytes(b);
            var bundleXml    = Encoding.UTF8.GetString(bundleData);
            var bundleSigned = XmlSignatureHelper.Sign(bundleXml, certificate);

            _signedXml = bundleSigned;

            using (var response = postBundle(bundleSigned))
            {
                if (response.StatusCode != HttpStatusCode.OK)
                {
                    TestResult.Fail("Server refused POSTing signed document at /");
                }
            }
        }
        private void testJsonFeed(string jsonFile)
        {
            Bundle    bundleResult;
            ErrorList errors = new Support.ErrorList();

            using (JsonReader jr = new JsonTextReader(new StreamReader(jsonFile)))
            {
                Debug.WriteLine("  Reading Json feed...");
                bundleResult = FhirParser.ParseBundle(jr, errors);

                jr.Close();
            }

            if (errors.Count > 0)
            {
                Debug.WriteLine("=== Json Feed Parse errors ===" + Environment.NewLine + errors.ToString());
                _roundTripFailed = true;
            }
            else
            {
                string xmlFile = Path.ChangeExtension(jsonFile, ".xml");

                using (XmlWriter xw = new XmlTextWriter(new System.IO.StreamWriter(xmlFile)))
                {
                    Debug.WriteLine("  Writing Xml feed...");
                    FhirSerializer.SerializeBundle(bundleResult, xw);
                    xw.Flush();
                    xw.Close();
                }
            }
        }
        private void testSingleJsonResource(string jsonFile)
        {
            Support.ErrorList errors = new Support.ErrorList();
            Model.Resource    singleResult;

            using (JsonTextReader jr = new JsonTextReader(new System.IO.StreamReader(jsonFile)))
            {
                Debug.WriteLine("  Reading from json...");
                singleResult = FhirParser.ParseResource(jr, errors);
                jr.Close();
            }

            if (errors.Count > 0)
            {
                Debug.WriteLine("=== Json Parse errors ===" + Environment.NewLine + errors.ToString());
                _roundTripFailed = true;
            }
            else
            {
                string xmlFile = Path.ChangeExtension(jsonFile, ".xml");

                using (XmlWriter xw = new XmlTextWriter(new System.IO.StreamWriter(xmlFile)))
                {
                    Debug.WriteLine("  Writing xml...");
                    FhirSerializer.SerializeResource(singleResult, xw);
                }
            }
        }
        public void ContainedBaseIsNotAddedToId()
        {
            var p = new Patient()
            {
                Id = "jaap"
            };
            var o = new Observation()
            {
                Subject = new ResourceReference()
                {
                    Reference = "#" + p.Id
                }
            };

            o.Contained.Add(p);
            o.ResourceBase = new Uri("http://nu.nl/fhir");

            var xml = FhirSerializer.SerializeResourceToXml(o);

            Assert.IsTrue(xml.Contains("value=\"#jaap\""));

            var o2 = FhirXmlParser.Parse <Observation>(xml);

            o2.ResourceBase = new Uri("http://nu.nl/fhir");
            xml             = FhirSerializer.SerializeResourceToXml(o2);
            Assert.IsTrue(xml.Contains("value=\"#jaap\""));
        }
Example #5
0
        public Base Read(SearchParams searchParams)
        {
            var parameters = searchParams.Parameters;

            foreach (var parameter in parameters)
            {
                if (parameter.Item1.ToLower().Contains("log") && parameter.Item2.ToLower().Contains("normal"))
                {
                    throw new ArgumentException("Using " + nameof(SearchParams) +
                                                " in Read(SearchParams searchParams) should throw an exception which is put into an OperationOutcomes issues");
                }
                if (parameter.Item1.Contains("log") && parameter.Item2.Contains("operationoutcome"))
                {
                    var operationOutcome = new OperationOutcome {
                        Issue = new List <OperationOutcome.IssueComponent>()
                    };
                    var issue = new OperationOutcome.IssueComponent
                    {
                        Severity = OperationOutcome.IssueSeverity.Information,
                        Code     = OperationOutcome.IssueType.Incomplete,
                        Details  = new CodeableConcept("SomeExampleException", typeof(FhirOperationException).ToString(),
                                                       "Something expected happened and needs to be handled with more detail.")
                    };
                    operationOutcome.Issue.Add(issue);
                    //var errorMessage = fh
                    var serialized = FhirSerializer.SerializeResourceToXml(operationOutcome);
                    throw new ArgumentException(serialized);
                }
            }
            throw new ArgumentException("Generic error");
        }
        private static void setBodyAndContentType(HttpWebRequest request, Resource data, ResourceFormat format, bool CompressRequestBody, out byte[] body)
        {
            if (data == null)
            {
                throw Error.ArgumentNull(nameof(data));
            }

            if (data is Binary)
            {
                var bin = (Binary)data;
                body = bin.Content;
                // This is done by the caller after the OnBeforeRequest is called so that other properties
                // can be set before the content is committed
                // request.WriteBody(CompressRequestBody, bin.Content);
                request.ContentType = bin.ContentType;
            }
            else
            {
                body = format == ResourceFormat.Xml ?
                       FhirSerializer.SerializeToXmlBytes(data, summary: Fhir.Rest.SummaryType.False) :
                       FhirSerializer.SerializeToJsonBytes(data, summary: Fhir.Rest.SummaryType.False);

                // This is done by the caller after the OnBeforeRequest is called so that other properties
                // can be set before the content is committed
                // request.WriteBody(CompressRequestBody, body);
                request.ContentType = Hl7.Fhir.Rest.ContentType.BuildContentType(format, forBundle: false);
            }
        }
Example #7
0
        public void ManageSearchResult()
        {
            var q = new Query()
                    .For("Patient").Where("name:exact=ewout").OrderBy("birthDate", SortOrder.Descending)
                    .SummaryOnly().Include("Patient.managingOrganization")
                    .LimitTo(20);

            var x = FhirSerializer.SerializeResourceToXml(q);

            Console.WriteLine(x);

            Assert.AreEqual("Patient", q.ResourceType);

            var p = q.Parameter.SingleWithName("name");

            Assert.AreEqual("name:exact", Query.ExtractParamKey(p));
            Assert.AreEqual("ewout", Query.ExtractParamValue(p));

            var o = q.Sort;

            Assert.AreEqual("birthDate", o.Item1);
            Assert.AreEqual(SortOrder.Descending, o.Item2);

            Assert.IsTrue(q.Summary);
            Assert.IsTrue(q.Includes.Contains("Patient.managingOrganization"));
            Assert.AreEqual(20, q.Count);
        }
        public override Task WriteToStreamAsync(Type type, object value, Stream writeStream, HttpContent content, TransportContext transportContext)
        {
            return(Task.Factory.StartNew(() =>
            {
                XmlWriter writer = new XmlTextWriter(writeStream, Encoding.UTF8);
                // todo: klopt het dat Bundle wel en <?xml ...> header heeft een Resource niet?
                // follow up: is now ticket in FhirApi. Check later.

                if (type == typeof(Profile))
                {
                    Profile resource = (Profile)value;
                    FhirSerializer.SerializeResource(resource, writer);
                }
                else if (type == typeof(ResourceEntry))
                {
                    ResourceEntry entry = (ResourceEntry)value;
                    FhirSerializer.SerializeResource(entry.Resource, writer);
                }
                else if (type == typeof(Bundle))
                {
                    FhirSerializer.SerializeBundle((Bundle)value, writer);
                }

                writer.Flush();
            }));
        }
Example #9
0
        private static void generateSnapshotAndCompare(StructureDefinition original, ArtifactResolver source)
        {
            var generator = new SnapshotGenerator(source, markChanges: false);

            var expanded = (StructureDefinition)original.DeepCopy();

            Assert.IsTrue(original.IsExactly(expanded));

            generator.Generate(expanded);

            // Simulate bug in Grahame's expander
            if (original.Snapshot.Element.Count == expanded.Snapshot.Element.Count)
            {
                for (var ix = 0; ix < expanded.Snapshot.Element.Count; ix++)
                {
                    if (original.Snapshot.Element[ix].Path == expanded.Snapshot.Element[ix].Path)
                    {
                        expanded.Snapshot.Element[ix].Min         = original.Snapshot.Element[ix].Min;
                        expanded.Snapshot.Element[ix].MustSupport = original.Snapshot.Element[ix].MustSupport;
                    }
                }
            }

            var areEqual = original.IsExactly(expanded);

            if (!areEqual)
            {
                File.WriteAllText("c:\\temp\\snapshotgen-source.xml", FhirSerializer.SerializeResourceToXml(original));
                File.WriteAllText("c:\\temp\\snapshotgen-dest.xml", FhirSerializer.SerializeResourceToXml(expanded));
            }

            Assert.IsTrue(areEqual);
        }
Example #10
0
        public void SerializeAndDeserializeTagList()
        {
            IList <Tag> tl = new List <Tag>();

            tl.Add(new Tag {
                Label = "No!", Uri = new Uri("http://www.nu.nl/tags")
            });
            tl.Add(new Tag {
                Label = "Maybe", Uri = new Uri("http://www.furore.com/tags")
            });

            string json = FhirSerializer.SerializeTagListToJson(tl);

            Assert.AreEqual(jsonTagList, json);

            string xml = FhirSerializer.SerializeTagListToXml(tl);

            Assert.AreEqual(xmlTagList, xml);

            ErrorList errors = new ErrorList();

            tl = FhirParser.ParseTagListFromXml(xml, errors);
            Assert.IsTrue(errors.Count == 0, errors.ToString());
            verifyTagList(tl);

            tl = FhirParser.ParseTagListFromJson(json, errors);
            Assert.IsTrue(errors.Count == 0, errors.ToString());
            verifyTagList(tl);
        }
Example #11
0
        private void convertResource(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 r2 = resource.DeepCopy();
                Assert.IsTrue(resource.Matches(r2 as Resource), "Serialization of " + inputFile + " did not match output - Matches test");
                Assert.IsTrue(resource.IsExactly(r2 as Resource), "Serialization of " + inputFile + " did not match output - IsExactly test");
                Assert.IsFalse(resource.Matches(null), "Serialization of " + inputFile + " matched null - Matches test");
                Assert.IsFalse(resource.IsExactly(null), "Serialization of " + inputFile + " matched null - IsExactly test");

                var json = FhirSerializer.SerializeResourceToJson(resource);
                File.WriteAllText(outputFile, json);
            }
            else
            {
                var json     = File.ReadAllText(inputFile);
                var resource = new FhirJsonParser().Parse <Resource>(json);
                var xml      = FhirSerializer.SerializeResourceToXml(resource);
                File.WriteAllText(outputFile, xml);
            }
        }
Example #12
0
        public void LetsDoJson()
        {
            string xmlString =
                @"<Patient xmlns='http://hl7.org/fhir'>
                    <name>
                        <use value='official' />  
                        <given value='Regina' />
                        <prefix value='Dr.'>
                        <extension>
                            <url value='http://hl7.org/fhir/profile/@iso-20190' />
                            <valueCoding>
                                <system value='urn:oid:2.16.840.1.113883.5.1122' />       
                                <code value='AC' />
                            </valueCoding>
                        </extension>
                        </prefix>
                    </name>
                    <text>
                        <status value='generated' />
                        <div xmlns='http://www.w3.org/1999/xhtml'>Whatever</div>
                    </text>
                </Patient>";

            ErrorList list = new ErrorList();
            Patient   p    = (Patient)FhirParser.ParseResourceFromXml(xmlString, list);

            p.Name[0].GivenElement[0].Value = "Rex";
            string json = FhirSerializer.SerializeResourceToJson(p);

            Debug.WriteLine(json);
        }
Example #13
0
        public void Test()
        {
            var parameters = new Parameters();

            "source-code".Do(x => parameters.Parameter.Add(new Parameters.ParametersParameterComponent
            {
                Name  = "SourceCode",
                Value = new FhirString(x)
            }));

            "target-code".Do(x => parameters.Parameter.Add(new Parameters.ParametersParameterComponent
            {
                Name  = "TargetCode",
                Value = new FhirString(x)
            }));

            "barcode".Do(x => parameters.Parameter.Add(new Parameters.ParametersParameterComponent
            {
                Name  = "Barcode",
                Value = new FhirString(x)
            }));

            var jsonToSend = FhirSerializer.SerializeToJson(parameters);

            File.WriteAllText("out.json", jsonToSend);
        }
Example #14
0
        /// <summary>
        /// Send a Bundle to a path on the server
        /// </summary>
        /// <param name="bundle">The contents of the Bundle to be sent</param>
        /// <param name="path">A path on the server to send the Bundle to</param>
        /// <returns>True if the bundle was successfully delivered, false otherwise</returns>
        /// <remarks>This method differs from Batch, in that it can be used to deliver a Bundle
        /// at the endpoint for messages, documents or binaries, instead of the batched update
        /// REST endpoint.</remarks>
        public bool DeliverBundle(Bundle bundle, string path)
        {
            if (Endpoint == null)
            {
                throw new InvalidOperationException("Endpoint must be provided using either the Endpoint property or the FhirClient constructor");
            }

            byte[] data;
            string contentType = ContentType.BuildContentType(PreferredFormat, false);

            if (PreferredFormat == ContentType.ResourceFormat.Json)
            {
                data = FhirSerializer.SerializeBundleToJsonBytes(bundle);
            }
            else if (PreferredFormat == ContentType.ResourceFormat.Xml)
            {
                data = FhirSerializer.SerializeBundleToXmlBytes(bundle);
            }
            else
            {
                throw new ArgumentException("Cannot encode a batch into format " + PreferredFormat.ToString());
            }

            var req = createRequest(Endpoint, true);

            req.Method      = "POST";
            req.ContentType = contentType;
            prepareRequest(req, data);

            return(doRequest(req, HttpStatusCode.OK, () => true));
        }
Example #15
0
        public override Task WriteToStreamAsync(Type type, object value, Stream writeStream, HttpContent content, TransportContext transportContext)
        {
            return(Task.Factory.StartNew(() =>
            {
                XmlWriter writer = new XmlTextWriter(writeStream, new UTF8Encoding(false));
                SummaryType summary = requestMessage.RequestSummary();

                if (type == typeof(OperationOutcome))
                {
                    Resource resource = (Resource)value;
                    FhirSerializer.SerializeResource(resource, writer, summary);
                }
                else if (typeof(Resource).IsAssignableFrom(type))
                {
                    Resource resource = (Resource)value;
                    FhirSerializer.SerializeResource(resource, writer, summary);
                }
                else if (type == typeof(FhirResponse))
                {
                    FhirResponse response = (value as FhirResponse);
                    if (response.HasBody)
                    {
                        FhirSerializer.SerializeResource(response.Resource, writer, summary);
                    }
                }

                writer.Flush();
            }));
        }
Example #16
0
        public override System.Threading.Tasks.Task WriteToStreamAsync(Type type, object value, Stream writeStream, HttpContent content, TransportContext transportContext)
        {
            StreamWriter writer     = new StreamWriter(writeStream);
            JsonWriter   jsonwriter = SerializationUtil.CreateJsonTextWriter(writer); // This will use the BetterJsonWriter which handles precision correctly

            if (type == typeof(OperationOutcome))
            {
                Resource resource = (Resource)value;
                FhirSerializer.SerializeResource(resource, jsonwriter);
            }
            else if (typeof(Resource).IsAssignableFrom(type))
            {
                if (value != null)
                {
                    Resource    r  = value as Resource;
                    SummaryType st = SummaryType.False;
                    if (r.HasAnnotation <SummaryType>())
                    {
                        st = r.Annotation <SummaryType>();
                    }
                    FhirSerializer.SerializeResource(r, jsonwriter, st);
                }
            }
            writer.Flush();
            return(System.Threading.Tasks.Task.FromResult(false));
            // return System.Threading.Tasks.Task.CompletedTask;
        }
Example #17
0
        public void PolymorphAndArraySerialization()
        {
            Extension ext = new Extension()
            {
                Url       = new Uri("http://hl7.org/fhir/profiles/@3141#test"),
                Value     = new FhirBoolean(true),
                Extension = new List <Extension>()
                {
                    new Extension()
                    {
                        Value = new Coding()
                        {
                            Code = "R51", System = new Uri("http://hl7.org/fhir/sid/icd-10")
                        }
                    }
                }
            };

            Assert.AreEqual(@"<?xml version=""1.0"" encoding=""utf-16""?>" +
                            @"<element xmlns=""http://hl7.org/fhir"">" +
                            @"<extension><valueCoding><system value=""http://hl7.org/fhir/sid/icd-10"" /><code value=""R51"" /></valueCoding></extension>" +
                            @"<url value=""http://hl7.org/fhir/profiles/@3141#test"" />" +
                            @"<valueBoolean value=""true"" />" +
                            @"</element>", FhirSerializer.SerializeElementAsXml(ext));
            Assert.AreEqual(
                @"{" +
                @"""extension"":[{""valueCoding"":{""system"":{""value"":""http://hl7.org/fhir/sid/icd-10""},""code"":{""value"":""R51""}}}]," +
                @"""url"":{""value"":""http://hl7.org/fhir/profiles/@3141#test""}," +
                @"""valueBoolean"":{""value"":true}" +
                @"}", FhirSerializer.SerializeElementAsJson(ext));
        }
Example #18
0
        public override Task WriteToStreamAsync(Type type, object value, Stream writeStream, HttpContent content, TransportContext transportContext)
        {
            return(Task.Factory.StartNew(() =>
            {
                StreamWriter writer = new StreamWriter(writeStream);
                JsonWriter jsonwriter = new JsonTextWriter(writer);
                if (type == typeof(OperationOutcome))
                {
                    Resource resource = (Resource)value;
                    FhirSerializer.SerializeResource(resource, jsonwriter);
                }
                else if (type == typeof(ResourceEntry))
                {
                    ResourceEntry entry = (ResourceEntry)value;
                    FhirSerializer.SerializeResource(entry.Resource, jsonwriter);
                    content.Headers.SetFhirTags(entry.Tags);
                }
                else if (type == typeof(Bundle))
                {
                    FhirSerializer.SerializeBundle((Bundle)value, jsonwriter);
                }
                else if (type == typeof(TagList))
                {
                    FhirSerializer.SerializeTagList((TagList)value, jsonwriter);
                }

                writer.Flush();
            }));
        }
Example #19
0
        public static void Setup(TestContext context)
        {
            ExportTests.tdb = new MockObjectRepository();
            TrifoliaImporter importer = new TrifoliaImporter(ExportTests.tdb);

            ExportTests.tdb.InitializeFHIR3Repository();
            ExportTests.tdb.InitializeLCGAndLogin();

            string importContent = Helper.GetSampleContents(IMPORT_XML);
            var    importModel   = ImportModel.Deserialize(importContent);

            var importStatus = importer.Import(importModel);

            Assert.IsTrue(importStatus.Success, "Expected import to succeed");
            Assert.AreNotEqual(importStatus.ImplementationGuides.Count, 0, "Expected import to include implementation guides");

            ImplementationGuide ig = ExportTests.tdb.ImplementationGuides.SingleOrDefault(y => y.Id == importStatus.ImplementationGuides.First().InternalId);
            var schema             = ig.ImplementationGuideType.GetSimpleSchema();
            ImplementationGuideExporter exporter = new ImplementationGuideExporter(ExportTests.tdb, schema, "localhost", "http");

            ExportTests.exportedBundle = exporter.GetImplementationGuides(implementationGuideId: ig.Id, include: "ImplementationGuide:resource");

            ExportTests.exportedXml = FhirSerializer.SerializeResourceToXml(ExportTests.exportedBundle);

            Assert.IsNotNull(ExportTests.exportedXml);
        }
Example #20
0
        public void TestNullExtensionRemoval()
        {
            var p = new Patient
            {
                Extension = new List <Extension>
                {
                    new Extension("http://hl7.org/fhir/Profile/iso-21090#qualifier", new Code("VV")),
                    null
                },

                Contact = new List <Patient.ContactComponent>
                {
                    null,
                    new Patient.ContactComponent {
                        Name = HumanName.ForFamily("Kramer")
                    },
                }
            };

            var xml = FhirSerializer.SerializeResourceToXml(p);

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

            Assert.AreEqual(1, p2.Extension.Count);
            Assert.AreEqual(1, p2.Contact.Count);
        }
        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 = FhirSerializer.SerializeResourceToXml(poco);

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

            poco = FhirXmlParser.Parse <Resource>(xml);
            Assert.IsNotNull(poco);
            var json2 = FhirSerializer.SerializeResourceToJson(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);
            Assert.AreEqual(0, errors.Count, "Errors were encountered comparing converted content\r\n" + String.Join("\r\n", errors));
        }
Example #22
0
        public void TestBundleSummary()
        {
            var p = new Patient();

            p.BirthDate = "1972-11-30";     // present in both summary and full
            p.Photo     = new List <Attachment>()
            {
                new Attachment()
                {
                    ContentType = "text/plain"
                }
            };

            var b = new Bundle();

            b.AddResourceEntry(p, "http://nu.nl/fhir/Patient/1");

            var full = FhirSerializer.SerializeResourceToXml(b);

            Assert.IsTrue(full.Contains("<entry"));
            Assert.IsTrue(full.Contains("<birthDate"));
            Assert.IsTrue(full.Contains("<photo"));

            var summ = FhirSerializer.SerializeResourceToXml(b, summary: true);

            Assert.IsTrue(summ.Contains("<entry"));
            Assert.IsTrue(summ.Contains("<birthDate"));
            Assert.IsFalse(summ.Contains("<photo"));
        }
Example #23
0
        /// <summary>
        /// Sends the FHIR messages.
        /// </summary>
        /// <param name="patient">The patient.</param>
        /// <returns>List&lt;System.Boolean&gt;.</returns>
        public static List <bool> SendFhirMessages(Patient patient)
        {
            var results = new List <bool>();

            foreach (var endpoint in configuration.Endpoints)
            {
                using (var client = new HttpClient())
                {
                    if (endpoint.RequiresAuthorization)
                    {
                        client.DefaultRequestHeaders.Add("Authorization", new[] { $"Bearer {GetAuthorizationToken(endpoint)}" });
                    }

                    traceSource.TraceEvent(TraceEventType.Verbose, 0, "Sending FHIR message to endpoint " + endpoint);

                    var content = new StringContent(FhirSerializer.SerializeResourceToXml(patient));
                    content.Headers.Remove("Content-Type");
                    content.Headers.Add("Content-Type", "application/xml+fhir");

                    var response = client.PostAsync($"{endpoint.Address}/Patient", content).Result;

                    if (response.IsSuccessStatusCode)
                    {
                        traceSource.TraceEvent(TraceEventType.Verbose, 0, $"Message sent successfully, response: {response.Content.ReadAsStringAsync().Result}");
                    }
                    else
                    {
                        traceSource.TraceEvent(TraceEventType.Error, 0, $"Unable to send message, response: {response.Content.ReadAsStringAsync().Result}");
                    }
                }
            }

            return(results);
        }
Example #24
0
        public void TestIdInSummary()
        {
            var p = new Patient();

            p.Id        = "test-id-1";
            p.BirthDate = "1972-11-30";     // present in both summary and full
            p.Photo     = new List <Attachment>()
            {
                new Attachment()
                {
                    ContentType = "text/plain"
                }
            };

            var full = FhirSerializer.SerializeResourceToXml(p);

            Assert.IsTrue(full.Contains("<id value="));
            Assert.IsTrue(full.Contains("<birthDate"));
            Assert.IsTrue(full.Contains("<photo"));

            var summ = FhirSerializer.SerializeResourceToXml(p, summary: true);

            Assert.IsTrue(summ.Contains("<id value="));
            Assert.IsTrue(summ.Contains("<birthDate"));
            Assert.IsFalse(summ.Contains("<photo"));
        }
        private void testFeed(string file, string baseFilename)
        {
            Bundle    bundleResult;
            ErrorList errors = new Support.ErrorList();

            using (XmlReader xr = createReader(file))
            {
                Debug.WriteLine("  Reading Xml feed...");
                bundleResult = FhirParser.ParseBundle(xr, errors);

                xr.Close();
            }

            if (errors.Count > 0)
            {
                Debug.WriteLine("=== Xml Feed Parse errors ===" + Environment.NewLine + errors.ToString());
                _roundTripFailed = true;
            }
            else
            {
                string jsonFile = baseFilename + "-roundtrip.json";
                //string xmlFile = Path.ChangeExtension(jsonFile, ".xml");

                using (JsonTextWriter jw = new JsonTextWriter(new StreamWriter(jsonFile)))
                {
                    Debug.WriteLine("  Writing Xml feed...");
                    FhirSerializer.SerializeBundle(bundleResult, jw);
                    jw.Flush();
                    jw.Close();
                }

                testJsonFeed(jsonFile);
            }
        }
Example #26
0
        private String Serialize(iSOFT.ANZ.PatientManagerServiceLibrary.Patient iPMpatient)
        {
            var resource = PatientMapper.MapModel(iPMpatient);

            String payload = String.Empty;

            if (WebOperationContext.Current != null)
            {
                var response = WebOperationContext.Current.OutgoingResponse;

                response.LastModified = iPMpatient.ModifDttm;
                string accept = WebOperationContext.Current.IncomingRequest.Accept;
                if (!String.IsNullOrEmpty(accept) && accept == "application/json")
                {
                    payload = FhirSerializer.SerializeResourceToJson(resource);
                    response.ContentType = "application/json+fhir";
                }
                else
                {
                    payload = FhirSerializer.SerializeResourceToXml(resource);
                    response.ContentType = "application/xml+fhir";
                }
            }
            return(payload);
        }
        private void testSingleResource(string file, string baseFilename)
        {
            Model.Resource    singleResult;
            Support.ErrorList errors = new Support.ErrorList();

            using (XmlReader xr = createReader(file))
            {
                Debug.WriteLine("  Reading Xml...");
                singleResult = FhirParser.ParseResource(xr, errors);
                xr.Close();
            }

            if (errors.Count > 0)
            {
                Debug.WriteLine("=== Xml Parse errors ===" + Environment.NewLine + errors.ToString());
                _roundTripFailed = true;
            }
            else
            {
                string jsonFile = baseFilename + "-roundtrip.json";

                using (JsonTextWriter w = new JsonTextWriter(new System.IO.StreamWriter(jsonFile)))
                {
                    Debug.WriteLine("  Writing json...");
                    FhirSerializer.SerializeResource(singleResult, w);
                }

                testSingleJsonResource(jsonFile);
            }
        }
        public void WhenHealthVaultBloodGlucoseTransformedToFhir_ThenCodeAndValuesEqual()
        {
            var when         = new HealthServiceDateTime();
            var bloodGlucose = new BloodGlucose
            {
                When  = when,
                Value = new BloodGlucoseMeasurement(101),
                GlucoseMeasurementType      = new CodableValue("Whole blood", "wb", "glucose-meaurement-type", "wc", "1"),
                OutsideOperatingTemperature = true,
                IsControlTest      = false,
                ReadingNormalcy    = Normalcy.Normal,
                MeasurementContext = new CodableValue("Before meal", "BeforeMeal", "glucose-measurement-context", "wc", "1"),
            };

            var observation = bloodGlucose.ToFhir();

            var json = FhirSerializer.SerializeToJson(observation);

            Assert.IsNotNull(observation);
            Assert.AreEqual(101, ((Quantity)observation.Value).Value);
            Assert.AreEqual("Whole blood", observation.Method.Text);

            var bloodGlucoseExtension = observation.GetExtension(HealthVaultExtensions.BloodGlucose);

            Assert.AreEqual("Before meal", bloodGlucoseExtension.GetExtensionValue <CodeableConcept>(HealthVaultExtensions.BloodGlucoseMeasurementContext).Text);
            Assert.AreEqual(true, bloodGlucoseExtension.GetBoolExtension(HealthVaultExtensions.OutsideOperatingTemperatureExtensionName));
            Assert.AreEqual(false, bloodGlucoseExtension.GetBoolExtension(HealthVaultExtensions.IsControlTestExtensionName));
            Assert.AreEqual("Normal", bloodGlucoseExtension.GetStringExtension(HealthVaultExtensions.ReadingNormalcyExtensionName));
        }
Example #29
0
        private void AddValueSets()
        {
            var valueSets = (from t in templates
                             join tc in this.tdb.TemplateConstraints on t.Id equals tc.TemplateId
                             where tc.ValueSet != null
                             select tc.ValueSet).Distinct();
            ValueSetExporter exporter = new ValueSetExporter(this.tdb);

            foreach (var valueSet in valueSets)
            {
                var fhirValueSet         = exporter.Convert(valueSet);
                var fhirValueSetContent  = FhirSerializer.SerializeResourceToXml(fhirValueSet);
                var fhirValueSetFileName = string.Format("resources/valueset/{0}.xml", valueSet.Id);

                // Add the value set file to the package
                this.zip.AddEntry(fhirValueSetFileName, fhirValueSetContent);

                // Add the value set to the control file so it knows what to do with it
                string resourceKey = "ValueSet/" + valueSet.GetFhirId();

                this.control.resources.Add(resourceKey, new Models.Control.ResourceReference()
                {
                    template_base  = "instance-template-format.html",
                    reference_base = string.Format("ValueSet-{0}.html", valueSet.GetFhirId())
                });
            }
        }
        public override Task WriteToStreamAsync(Type type, object value, Stream writeStream, HttpContent content, TransportContext transportContext)
        {
            return(Task.Factory.StartNew(() =>
            {
                StreamWriter writer = new StreamWriter(writeStream);
                JsonWriter jsonwriter = new JsonTextWriter(writer);

                if (type == typeof(Profile))
                {
                    Profile entry = (Profile)value;
                    FhirSerializer.SerializeResource(entry, jsonwriter);
                }
                else if (type == typeof(ResourceEntry))
                {
                    ResourceEntry entry = (ResourceEntry)value;
                    FhirSerializer.SerializeResource(entry.Resource, jsonwriter);
                }
                else if (type == typeof(Bundle))
                {
                    FhirSerializer.SerializeBundle((Bundle)value, jsonwriter);
                }

                writer.Flush();
            }));
        }