Example #1
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);
        }
Example #2
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 #3
0
        public void ParseJsonNativeValues()
        {
            Patient p = new Patient();

            p.SetExtension(new Uri("http://blabla.nl/number"), new FhirDecimal(new Decimal(3.14)));
            p.SetExtension(new Uri("http://blabla.nl/int"), new Integer(150));
            p.SetExtension(new Uri("http://blabla.nl/bool"), new FhirBoolean(true));

            var json = FhirSerializer.SerializeResourceToJson(p);

            Assert.IsTrue(json.Contains("\"value\":3.14"));
            Assert.IsTrue(json.Contains("\"value\":150"));
            Assert.IsTrue(json.Contains("\"value\":true"));

            var err = new ErrorList();

            p = (Patient)FhirParser.ParseResourceFromJson(json, err);
            Assert.IsTrue(err.Count == 0);

            var ex = p.GetExtension(new Uri("http://blabla.nl/number"));

            Assert.AreEqual(new Decimal(3.14), ((FhirDecimal)ex.Value).Value.Value);
            ex = p.GetExtension(new Uri("http://blabla.nl/int"));
            Assert.AreEqual(150, ((Integer)ex.Value).Value.Value);
            ex = p.GetExtension(new Uri("http://blabla.nl/bool"));
            Assert.AreEqual(true, ((FhirBoolean)ex.Value).Value.Value);
        }
        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 #5
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 #6
0
        public void UpdateAndCheckHistory()
        {
            _store.EraseData();

            var importer = new ResourceImporter(new Uri("http://localhost"));

            importer.QueueNewEntry(_stockPatient);
            importer.QueueNewEntry(_stockOrg);

            var dd = (ResourceEntry)clone(_stockPatient);

            ((Patient)dd.Resource).Name[0].Text = "Donald Duck";
            dd.Links.SelfLink = null;
            importer.QueueNewEntry(dd);

            importer.QueueNewDeletedEntry(_stockPatient.Id);
            importer.QueueNewDeletedEntry(_stockOrg.Id);

            var imported = importer.ImportQueued();
            var origId   = imported.First().Id;

            _store.AddEntries(imported);

            var history = _store.ListVersionsById(origId)
                          .OrderBy(be => new ResourceLocation(be.Links.SelfLink).VersionId);

            Assert.IsNotNull(history);
            Assert.AreEqual(3, history.Count());

            Assert.IsTrue(history.All(be => be.Id == origId));

            Assert.IsTrue(history.Last() is DeletedEntry);

            var ver1 = new ResourceLocation(history.First().Links.SelfLink).VersionId;
            var ver2 = new ResourceLocation(history.ElementAt(1).Links.SelfLink).VersionId;
            var ver3 = new ResourceLocation(history.ElementAt(2).Links.SelfLink).VersionId;

            Assert.AreNotEqual(Int32.Parse(ver1), Int32.Parse(ver2));
            Assert.AreNotEqual(Int32.Parse(ver2), Int32.Parse(ver3));
            Assert.AreNotEqual(Int32.Parse(ver1), Int32.Parse(ver3));

            var firstVersionAsEntry = _store.FindVersionByVersionId(history.First().Links.SelfLink);

            //TODO: There's a bug here...the cr+lf in the _stockPatient gets translated to \r\n in the 'firstVersion'.
            //Cannot see this in the stored version though.
            Assert.AreEqual(FhirSerializer.SerializeResourceToJson(_stockPatient.Resource),
                            FhirSerializer.SerializeResourceToJson(((ResourceEntry)firstVersionAsEntry).Resource));

            var secondVersionAsEntry = _store.FindVersionByVersionId(history.ElementAt(1).Links.SelfLink);

            Assert.AreEqual("Donald Duck", ((Patient)((ResourceEntry)secondVersionAsEntry).Resource).Name[0].Text);

            var allHistory = _store.ListVersions();

            Assert.AreEqual(5, allHistory.Count());
            Assert.AreEqual(3, allHistory.Count(be => be.Id.ToString().Contains("patient")));
            Assert.AreEqual(2, allHistory.Count(be => be.Id.ToString().Contains("organization")));
            Assert.AreEqual(2, allHistory.Count(be => be is DeletedEntry));
        }
Example #7
0
        public static string GetDemoPatientJson()
        {
            var pat = GetDemoPatient();

            var json = FhirSerializer.SerializeResourceToJson(pat);

            return(json);
        }
        public void SaveJSONResponseToDisk(string filename)
        {
            var JSONResponse = JToken.Parse(FhirSerializer.SerializeResourceToJson(FhirResponse.Resource));

            string jsonPrettyPrinted = JsonConvert.SerializeObject(JSONResponse, Formatting.Indented);

            File.WriteAllText(@filename, jsonPrettyPrinted);
        }
 public Resource Update(Resource resource)
 {
     return(ExecuteFunction("fhir.update", new NpgsqlParameter
     {
         NpgsqlDbType = NpgsqlDbType.Jsonb,
         Value = FhirSerializer.SerializeResourceToJson(resource)
     }));
 }
Example #10
0
        public void ResourceWithExtensionAndNarrative()
        {
            HumanName name = new HumanName().WithGiven("Wouter").WithGiven("Gert")
                             .AndFamily("van der").AndFamily("Vlies");

            name.FamilyElement[0].AddExtension(new Uri("http://hl7.org/fhir/profile/@iso-21090#name-qualifier"),
                                               new Code("VV"));

            Patient p = new Patient()
            {
                Id         = "Ab4",
                Identifier = new List <Identifier> {
                    new Identifier {
                        Value = "3141"
                    }
                },
                BirthDateElement = new FhirDateTime(1972, 11, 30),
                Name             = new List <HumanName> {
                    name
                },
                Text = new Narrative()
                {
                    Status = Narrative.NarrativeStatus.Generated,
                    Div    = "<div xmlns='http://www.w3.org/1999/xhtml'>Patient 3141 - Wouter Gert, nov. 30th, 1972</div>"
                },

                Contained = new List <Resource>()
                {
                    new List()
                    {
                        Mode = List.ListMode.Snapshot
                    }
                }
            };


            Assert.AreEqual(@"<?xml version=""1.0"" encoding=""utf-16""?>" +
                            @"<Patient id=""Ab4"" xmlns=""http://hl7.org/fhir"">" +
                            @"<text><status value=""generated"" /><div xmlns='http://www.w3.org/1999/xhtml'>Patient 3141 - Wouter Gert, nov. 30th, 1972</div></text>" +
                            @"<contained><List><mode value=""snapshot"" /></List></contained>" +
                            @"<identifier><value value=""3141"" /></identifier>" +
                            @"<name>" +
                            @"<family value=""van der"">" +
                            @"<extension><url value=""http://hl7.org/fhir/profile/@iso-21090#name-qualifier"" /><valueCode value=""VV"" /></extension>" +
                            @"</family><family value=""Vlies"" /><given value=""Wouter"" /><given value=""Gert"" /></name>" +
                            @"<birthDate value=""1972-11-30"" />" +
                            @"</Patient>", FhirSerializer.SerializeResourceToXml(p));

            Assert.AreEqual(@"{""Patient"":{""_id"":""Ab4""," +
                            @"""text"":{""status"":{""value"":""generated""},""div"":""<div xmlns='http://www.w3.org/1999/xhtml'>" +
                            @"Patient 3141 - Wouter Gert, nov. 30th, 1972</div>""}," +
                            @"""contained"":[{""List"":{""mode"":{""value"":""snapshot""}}}]," +
                            @"""identifier"":[{""value"":{""value"":""3141""}}]," +
                            @"""name"":[{""family"":[{""value"":""van der""," +
                            @"""extension"":[{""url"":{""value"":""http://hl7.org/fhir/profile/@iso-21090#name-qualifier""},""valueCode"":{""value"":""VV""}}]}," +
                            @"{""value"":""Vlies""}],""given"":[{""value"":""Wouter""},{""value"":""Gert""}]}],""birthDate"":{""value"":""1972-11-30""}" +
                            @"}}", FhirSerializer.SerializeResourceToJson(p));
        }
        public IActionResult Read(string type, string id, string version = null)
        {
            FhirClient    client = new FhirClient(url);
            String        text   = FhirSerializer.SerializeResourceToJson(client.Get(ResourceIdentity.Build(type, id, version)));
            JsonTextModel m      = new JsonTextModel(type, id, version, text);

            m.Status_ = JsonTextModel.READING;
            return(View(m));
        }
Example #12
0
        public void TestLongDecimalSerialization()
        {
            var dec = 3.1415926535897932384626433833m;
            var obs = new Observation {
                Value = new FhirDecimal(dec)
            };
            var json = FhirSerializer.SerializeResourceToJson(obs);
            var obs2 = (Observation)FhirParser.ParseFromJson(json);

            Assert.AreEqual(dec.ToString(CultureInfo.InvariantCulture), ((FhirDecimal)obs2.Value).Value.Value.ToString(CultureInfo.InvariantCulture));
        }
Example #13
0
 private string Serialize(Resource resource)
 {
     if (this.JsonFormat)
     {
         return(FhirSerializer.SerializeResourceToJson(resource));
     }
     else
     {
         string xml = FhirSerializer.SerializeResourceToXml(resource);
         return(PrettyXml(xml));
     }
 }
 public static BsonDocument CreateDocument(Resource resource)
 {
     if (resource != null)
     {
         string json = FhirSerializer.SerializeResourceToJson(resource);
         return(BsonDocument.Parse(json));
     }
     else
     {
         return(new BsonDocument());
     }
 }
        private static string CreateJsonDict(string[] names, string[] values)
        {
            var dict = names.Zip(values, (s, s1) => new Tuple <string, string>(s, s1))
                       .ToDictionary(k => k.Item1, v => v.Item2);
            var result = new Parameters();

            foreach (var item in dict)
            {
                result.Add(item.Key, new FhirString(item.Value));
            }

            return(FhirSerializer.SerializeResourceToJson(result));
        }
Example #16
0
        public void SaveToFhirContextToDisk(string filename)
        {
            var doc = new XDocument(
                new XElement("fhirContext",
                             new XElement("request",
                                          new XElement("fhirRequestParameters", FhirSerializer.SerializeResourceToJson(HttpRequestConfiguration.BodyParameters))
                                          ),
                             new XElement("response",
                                          new XElement("fhirResponseResource", FhirSerializer.SerializeResourceToJson(FhirResponse.Resource))
                                          )
                             )
                );

            doc.Save(filename);
        }
Example #17
0
        public static string Serialize(Hl7.Fhir.Model.Resource fhirResource, string mimeFormat, bool summary)
        {
            string payload = string.Empty;

            if (mimeFormat.IndexOf("JSON", StringComparison.InvariantCultureIgnoreCase) >= 0)
            {
                payload = FhirSerializer.SerializeResourceToJson(fhirResource, summary);
            }
            else
            {
                payload = FhirSerializer.SerializeResourceToXml(fhirResource, summary);
            }

            return(payload);
        }
        public void SerializeNarrativeWithQuotes()
        {
            var p = new Patient();

            p.Text = new Narrative()
            {
                Div = "<div xmlns=\"http://www.w3.org/1999/xhtml\">Nasty, a text with both \"double\" quotes and 'single' quotes</div>"
            };

            var xml = FhirSerializer.SerializeResourceToXml(p);

            Assert.IsNotNull(FhirXmlParser.Parse <Resource>(xml));
            var json = FhirSerializer.SerializeResourceToJson(p);

            Assert.IsNotNull(FhirJsonParser.Parse <Resource>(json));
        }
        public void TestCreate()
        {
            string patient1Json     = FhirSerializer.SerializeResourceToJson(MockedResources.Patient1);
            string patient1Xml      = FhirSerializer.SerializeResourceToXml(MockedResources.Patient1);
            string device1Json      = FhirSerializer.SerializeResourceToJson(MockedResources.Device1);
            string device1Xml       = FhirSerializer.SerializeResourceToXml(MockedResources.Device1);
            string observation1Json = FhirSerializer.SerializeResourceToJson(MockedResources.Observation1);
            string observation1Xml  = FhirSerializer.SerializeResourceToXml(MockedResources.Observation1);

            HttpRequestMessage request1 = new HttpRequestMessage(HttpMethod.Post, baseUrl + "/Patient")
            {
                Content = new StringContent(patient1Json, Encoding.UTF8, "application/json+fhir")
            };
            var response1 = httpClient.SendAsync(request1).Result;
            HttpRequestMessage request2 = new HttpRequestMessage(HttpMethod.Post, baseUrl + "/Device")
            {
                Content = new StringContent(device1Json, Encoding.UTF8, "application/json+fhir")
            };
            var response2 = httpClient.SendAsync(request2).Result;
            HttpRequestMessage request3 = new HttpRequestMessage(HttpMethod.Post, baseUrl + "/Observation")
            {
                Content = new StringContent(observation1Json, Encoding.UTF8, "application/json+fhir")
            };
            var response3 = httpClient.SendAsync(request3).Result;
            HttpRequestMessage request4 = new HttpRequestMessage(HttpMethod.Post, baseUrl + "/Patient")
            {
                Content = new StringContent(patient1Xml, Encoding.UTF8, "application/xml+fhir")
            };
            var response4 = httpClient.SendAsync(request4).Result;
            HttpRequestMessage request5 = new HttpRequestMessage(HttpMethod.Post, baseUrl + "/Device")
            {
                Content = new StringContent(device1Xml, Encoding.UTF8, "application/xml+fhir")
            };
            var response5 = httpClient.SendAsync(request5).Result;
            HttpRequestMessage request6 = new HttpRequestMessage(HttpMethod.Post, baseUrl + "/Observation")
            {
                Content = new StringContent(observation1Xml, Encoding.UTF8, "application/xml+fhir")
            };
            var response6 = httpClient.SendAsync(request6).Result;

            Assert.AreEqual(HttpStatusCode.Forbidden, response1.StatusCode);
            Assert.AreEqual(HttpStatusCode.Forbidden, response2.StatusCode);
            Assert.AreEqual(HttpStatusCode.Forbidden, response3.StatusCode);
            Assert.AreEqual(HttpStatusCode.Forbidden, response4.StatusCode);
            Assert.AreEqual(HttpStatusCode.Forbidden, response5.StatusCode);
            Assert.AreEqual(HttpStatusCode.Forbidden, response6.StatusCode);
        }
Example #20
0
        public void SimpleStoreAndRetrieve()
        {
            _store.EraseData();

            _store.AddEntry(_stockPatient);

            ResourceEntry readBack = (ResourceEntry)_store.FindEntryById(_stockPatient.Id);

            Assert.IsNotNull(readBack);
            Assert.IsNotNull(readBack.Id);
            Assert.AreEqual(_stockPatient.Id, readBack.Id);
            Assert.IsNotNull(readBack.Links.SelfLink);
            Assert.IsNotNull(readBack.LastUpdated);

            Assert.AreEqual(FhirSerializer.SerializeResourceToJson(_stockPatient.Resource),
                            FhirSerializer.SerializeResourceToJson(readBack.Resource));
        }
Example #21
0
        public void RoundTripOneExample()
        {
            string exampleXml = @"TestData\testscript-example(example).xml";
            var    original   = File.ReadAllText(exampleXml);

            var t         = new FhirXmlParser().Parse <TestScript>(original);
            var outputXml = FhirSerializer.SerializeResourceToXml(t);

            XmlAssert.AreSame(original, outputXml);

            var outputJson = FhirSerializer.SerializeResourceToJson(t);
            var t2         = new FhirJsonParser().Parse <TestScript>(outputJson);
//            Assert.IsTrue(t.IsExactly(t2));

            var outputXml2 = FhirSerializer.SerializeResourceToXml(t2);

            XmlAssert.AreSame(original, outputXml2);
        }
Example #22
0
        public void HandleCommentsJson()
        {
            string json = File.ReadAllText(@"TestData\TestPatient.json");

            var pat = FhirParser.ParseFromJson(json) as Patient;

            Assert.AreEqual(1, pat.Telecom[0].FhirCommentsElement.Count);
            Assert.AreEqual("   home communication details aren't known   ", pat.Telecom[0].FhirComments.First());

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

            json = FhirSerializer.SerializeResourceToJson(pat);
            pat  = FhirParser.ParseFromJson(json) as Patient;

            Assert.AreEqual(2, pat.Telecom[0].FhirCommentsElement.Count);
            Assert.AreEqual("   home communication details aren't known   ", pat.Telecom[0].FhirComments.First());
            Assert.AreEqual("A second line", pat.Telecom[0].FhirComments.Skip(1).First());
        }
Example #23
0
        /// <summary>
        /// Executes the specified arguments.
        /// </summary>
        /// <param name="arguments">The arguments.</param>
        /// <returns>System.Int32.</returns>
        /// <remarks> </remarks>
        public override int Execute(Arguments arguments)
        {
            // Get us the needed parameters first
            //
            var url     = arguments["url"];
            var id      = arguments["id"];
            var version = arguments["version"];
            var format  = arguments["format"];

            // Call the FHIR server
            //
            try
            {
                var client   = new FhirClient(url);
                var identity = ResourceIdentity.Build("Patient", id, version);
                var patient  = client.Read(identity);

                String text;

                if (format == "json")
                {
                    text = FhirSerializer.SerializeResourceToJson(patient.Resource);
                }
                else
                {
                    text = FhirSerializer.SerializeResourceToXml(patient.Resource);
                }

                if (!String.IsNullOrEmpty(arguments["file"]))
                {
                    File.WriteAllText(arguments["file"], text);
                }
                else
                {
                    Console.WriteLine(text);
                }
                return(0);
            }
            catch (Exception e)
            {
                Console.WriteLine(e.Message);
                return(1);
            }
        }
        public void TestExample()
        {
            var tmp  = Path.GetTempFileName();
            var tmpx = tmp + ".xml";
            var tmpj = tmp + ".json";

            (var _, var __, Patient p) = makeTestData();
            var rXml  = FhirSerializer.SerializeResourceToXml(p);
            var rJson = FhirSerializer.SerializeResourceToJson(p);

            File.WriteAllText(tmpx, rXml);
            File.WriteAllText(tmpj, rJson);

            var x = new XmlFileConformanceScanner(tmpx);
            var j = new JsonFileConformanceScanner(tmpj);

            assertExample(x, tmpx);
            assertExample(j, tmpj);
        }
Example #25
0
        public bool SaveResource(Resource r)
        {
            string rt      = Enum.GetName(typeof(Hl7.Fhir.Model.ResourceType), r.ResourceType);
            var    request = new RestRequest(rt, Method.POST);

            request.AddHeader("accept", "application/json");
            request.AddHeader("content-type", "application/json");
            if (BearerToken != null)
            {
                request.AddHeader("Authorization", "Bearer " + BearerToken);
            }
            string srv = FhirSerializer.SerializeResourceToJson(r);

            request.AddParameter("application/json; charset=utf-8", srv, ParameterType.RequestBody);
            request.RequestFormat = DataFormat.Json;
            IRestResponse response2 = _client.Execute(request);

            return(response2.ResponseStatus == ResponseStatus.Completed);
        }
Example #26
0
        public void RoundTripOneExample()
        {
            string testFileName = "testscript-example(example).xml";
            var    original     = TestDataHelper.ReadTestData(testFileName);

            var t         = new FhirXmlParser().Parse <TestScript>(original);
            var outputXml = FhirSerializer.SerializeResourceToXml(t);

            XmlAssert.AreSame(testFileName, original, outputXml);

            var outputJson = FhirSerializer.SerializeResourceToJson(t);
            var t2         = new FhirJsonParser().Parse <TestScript>(outputJson);

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

            var outputXml2 = FhirSerializer.SerializeResourceToXml(t2);

            XmlAssert.AreSame(testFileName, original, outputXml2);
        }
Example #27
0
        public void TestExample()
        {
            var tmp  = Path.GetTempFileName();
            var tmpx = tmp + ".xml";
            var tmpj = tmp + ".json";

            (var _, var __, Patient p) = makeTestData();
            var rXml  = FhirSerializer.SerializeResourceToXml(p);
            var rJson = FhirSerializer.SerializeResourceToJson(p);

            File.WriteAllText(tmpx, rXml);
            File.WriteAllText(tmpj, rJson);

            var x = new XmlArtifactScanner(tmpx, DefaultArtifactSummaryHarvester.Harvest);
            var j = new JsonArtifactScanner(tmpj, DefaultArtifactSummaryHarvester.Harvest);

            assertExample(x, tmpx);
            assertExample(j, tmpj);
        }
Example #28
0
        public string Read(string patid)
        {
            String payload = String.Empty;

            //  iPM_API_Resource.Patient iPmPatient;
            try
            {
                int id = Int32.Parse(patid);

                // Call the iPM pat Service to get the patient
                iPM_API_Resource.PatientService ps  = new iPM_API_Resource.PatientService();
                iPM_API_Resource.Patient        pat = ps.GetByPatientIdentifier(patid, iPM_API_Resource.PatientLoadDepth.PatientOnly);

                if (pat != null)
                {
                    var resource = FHIRDataMapper.PatientMapper.MapModel(pat);

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

                        response.LastModified = DateTime.Now;
                        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);
                }
                return(payload);
            }
            catch (Exception exp)
            {
                throw exp;
            }
        }
Example #29
0
        private void convertResource(string inputFile, string outputFile)
        {
            //TODO: call validation after reading

            if (inputFile.EndsWith(".xml"))
            {
                var xml      = File.ReadAllText(inputFile);
                var resource = FhirParser.ParseResourceFromXml(xml);

                var json = FhirSerializer.SerializeResourceToJson(resource);
                File.WriteAllText(outputFile, json);
            }
            else
            {
                var json     = File.ReadAllText(inputFile);
                var resource = FhirParser.ParseResourceFromJson(json);
                var xml      = FhirSerializer.SerializeResourceToXml(resource);
                File.WriteAllText(outputFile, xml);
            }
        }
Example #30
0
        public void TestDecimalPrecisionSerializationInJson()
        {
            var dec6  = 6m;
            var dec60 = 6.0m;

            var obs = new Observation {
                Value = new FhirDecimal(dec6)
            };
            var json = FhirSerializer.SerializeResourceToJson(obs);
            var obs2 = (Observation)FhirParser.ParseFromJson(json);

            Assert.AreEqual("6", ((FhirDecimal)obs2.Value).Value.Value.ToString(CultureInfo.InvariantCulture));

            obs = new Observation {
                Value = new FhirDecimal(dec60)
            };
            json = FhirSerializer.SerializeResourceToJson(obs);
            obs2 = (Observation)FhirParser.ParseFromJson(json);
            Assert.AreEqual("6.0", ((FhirDecimal)obs2.Value).Value.Value.ToString(CultureInfo.InvariantCulture));
        }