Example #1
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 #2
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);
        }
Example #3
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())
                });
            }
        }
Example #4
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 #5
0
        public static Patient ReadPatient(string patientId)
        {
            Patient responsePatient = new Patient();

            try
            {
                LogToFile("Read Patient");

                string location = $"Patient/{patientId}";
                LogToFile("Request: \n\n" + location);

                FhirClient fhirClient = new FhirClient(FhirClientEndPoint);
                responsePatient = fhirClient.Read <Patient>(location);

                LogToFile("Response: ");
                var responsePatientXml = FhirSerializer.SerializeResourceToXml(responsePatient);
                LogToFile(XDocument.Parse(responsePatientXml).ToString());
            }
            catch (Exception ex)
            {
                LogToFile(ex.ToString());
            }

            return(responsePatient);
        }
        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 #7
0
        public static Patient CreatePatient(string given, string family, DateTime birthDate)
        {
            Patient patient         = new Patient();
            Patient responsePatient = new Patient();

            //Set patient name
            patient.Name = new List <HumanName>();

            HumanName patientName = new HumanName();

            patientName.Use    = HumanName.NameUse.Official;
            patientName.Prefix = new string[] { "Mr" };

            //Default way using properties to set Given and Family name
            //patientName.Given = new string[] { given };
            //patientName.Family = family;

            //Using methods to sets the Given and Family name
            patientName.WithGiven(given).AndFamily(family);

            patient.Name.Add(patientName);

            //Set patient Identifier
            patient.Identifier = new List <Identifier>();

            Identifier patientIdentifier = new Identifier();

            patientIdentifier.System = "http://someurl.net/not-sure-about-the-value/1.0";
            patientIdentifier.Value  = Guid.NewGuid().ToString();

            patient.Identifier.Add(patientIdentifier);

            //Set patient birth date
            patient.BirthDate = birthDate.ToFhirDate();

            //Set Active Flag
            patient.Active = true;

            try
            {
                LogToFile("Creating Patient");

                LogToFile("Request: ");
                var patientXml = FhirSerializer.SerializeResourceToXml(patient);
                LogToFile(XDocument.Parse(patientXml).ToString());

                FhirClient fhirClient = new FhirClient(FhirClientEndPoint);
                responsePatient = fhirClient.Create(patient);

                LogToFile("Response: ");
                var responsePatientXml = FhirSerializer.SerializeResourceToXml(responsePatient);
                LogToFile(XDocument.Parse(responsePatientXml).ToString());
            }
            catch (Exception ex)
            {
                LogToFile(ex.ToString());
            }

            return(responsePatient);
        }
Example #8
0
        public static Patient UpdatePatientBirthDate(Patient patient, DateTime birthDate)
        {
            Patient responsePatient = new Patient();

            patient.BirthDate = birthDate.ToFhirDate();

            try
            {
                LogToFile("Update Patient");

                LogToFile("Request: ");
                var patientXml = FhirSerializer.SerializeResourceToXml(patient);
                LogToFile(XDocument.Parse(patientXml).ToString());

                FhirClient fhirClient = new FhirClient(FhirClientEndPoint);
                responsePatient = fhirClient.Update(patient);

                LogToFile("Response: ");
                var responsePatientXml = FhirSerializer.SerializeResourceToXml(responsePatient);
                LogToFile(XDocument.Parse(responsePatientXml).ToString());
            }
            catch (Exception ex)
            {
                LogToFile(ex.ToString());
            }

            return(responsePatient);
        }
        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 #10
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);
        }
Example #11
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 #12
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 #13
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");
        }
Example #14
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 #15
0
        private double valueFromObservation(Observation o)
        {
            var    a = FhirSerializer.SerializeResourceToXml(o);
            string b = XDocument.Parse(a).ToString();

            Console.WriteLine(b);
            Console.WriteLine("--------------------------------------------");
            try
            {
                b = b.Substring(b.IndexOf("<value value=") + 14, 20);
                Console.WriteLine(b);
                b = b.Substring(0, b.IndexOf('"'));
                Console.WriteLine(b);
                b = b.Replace(".", ",");
                Console.WriteLine(b);
                if (b.IndexOf(",") < 0)
                {
                    b = b + ",0";
                }
            }
            catch (Exception) { }

            double value;

            if (double.TryParse(b, out value))
            {
                return(value);
            }
            else
            {
                return(-1.0);
            }
        }
Example #16
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"));
        }
Example #17
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 #18
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));
        }
Example #19
0
        public void SerializeEmptyParams()
        {
            var par = new Parameters();
            var xml = FhirSerializer.SerializeResourceToXml(par);

            var par2 = (new FhirXmlParser()).Parse <Parameters>(xml);

            Assert.AreEqual(0, par2.Parameter.Count);
        }
Example #20
0
        public void TryScriptInject()
        {
            var x = new Patient();

            x.Name.Add(HumanName.ForFamily("<script language='javascript'></script>"));

            var xml = FhirSerializer.SerializeResourceToXml(x);

            Assert.IsFalse(xml.Contains("<script"));
        }
        public void CheckCopyCarePlan()
        {
            string xml = File.ReadAllText(@"TestData\careplan-example-f201-renal.xml");

            var p    = new FhirXmlParser().Parse <CarePlan>(xml);
            var p2   = (CarePlan)p.DeepCopy();
            var xml2 = FhirSerializer.SerializeResourceToXml(p2);

            XmlAssert.AreSame(xml, xml2);
        }
        public void CheckCopyAllFields()
        {
            string xml = File.ReadAllText(@"TestData\TestPatient.xml");

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

            XmlAssert.AreSame(xml, xml2);
        }
Example #23
0
        public void CheckCopyAllFields()
        {
            Stream xmlExample = System.Reflection.Assembly.GetExecutingAssembly().GetManifestResourceStream("Hl7.Fhir.Test.TestPatient.xml");
            string xml        = new StreamReader(xmlExample).ReadToEnd();

            var p    = (Patient)FhirParser.ParseResourceFromXml(xml);
            var p2   = (Patient)p.DeepCopy();
            var xml2 = FhirSerializer.SerializeResourceToXml(p2);

            XmlAssert.AreSame(xml, xml2);
        }
Example #24
0
 private string Serialize(Resource resource)
 {
     if (this.JsonFormat)
     {
         return(FhirSerializer.SerializeResourceToJson(resource));
     }
     else
     {
         string xml = FhirSerializer.SerializeResourceToXml(resource);
         return(PrettyXml(xml));
     }
 }
        public void RetainSpacesInAttribute()
        {
            var xml = "<Basic xmlns='http://hl7.org/fhir'><extension url='http://blabla.nl'><valueString value='Daar gaat ie dan" + "&#xA;" + "verdwijnt dit?' /></extension></Basic>";

            var basic = FhirXmlParser.Parse <DomainResource>(xml);

            Assert.IsTrue(basic.GetStringExtension("http://blabla.nl").Contains("\n"));

            var outp = FhirSerializer.SerializeResourceToXml(basic);

            Assert.IsTrue(outp.Contains("&#xA;"));
        }
Example #26
0
        public static void ExpandProfileFile(string inputfile, string outputfile)
        {
            var source   = new CachedArtifactSource(ArtifactResolver.CreateOffline());
            var expander = new ProfileExpander(source);

            string xml  = File.ReadAllText(inputfile);
            var    diff = (Profile)FhirParser.ParseResourceFromXml(xml);

            expander.Expand(diff);
            xml = FhirSerializer.SerializeResourceToXml(diff);
            File.WriteAllText(outputfile, xml);
        }
Example #27
0
        private void AddImplementationGuide(bool includeVocabulary)
        {
            ImplementationGuideExporter igExporter = new ImplementationGuideExporter(this.tdb, this.schema, "http", "test.com");
            var fhirIg = igExporter.Convert(this.ig, includeVocabulary: includeVocabulary);

            var    fhirIgContent  = FhirSerializer.SerializeResourceToXml(fhirIg);
            string fhirIgFileName = string.Format("resources/implementationguide/ImplementationGuide_{0}.xml", ig.Id);

            this.control.source = "implementationguide/ImplementationGuide_" + ig.Id.ToString() + ".xml";

            this.zip.AddEntry(fhirIgFileName, fhirIgContent);
        }
        public static Bundle RefreshBundle(this FhirClient client, Bundle bundle)
        {
            if (bundle == null)
            {
                throw Error.ArgumentNull("bundle");
            }

            // Clone old bundle, without the entries (so, just the header)
            var    oldEntries = bundle.Entry;
            Bundle result;

            try
            {
                bundle.Entry = new List <Bundle.BundleEntryComponent>();
                var xml = FhirSerializer.SerializeResourceToXml(bundle, summary: false);
                result = (Bundle)FhirParser.ParseResourceFromXml(xml);
            }
            catch
            {
                throw;
            }
            finally
            {
                bundle.Entry = oldEntries;
            }

            result.Id               = "urn:uuid:" + Guid.NewGuid().ToString("n");
            result.Meta             = new Meta();
            result.Meta.LastUpdated = DateTimeOffset.Now;
            result.Entry            = new List <Bundle.BundleEntryComponent>();

            foreach (var entry in bundle.Entry)
            {
                if (entry.Resource != null)
                {
                    if (!entry.IsDeleted())
                    {
                        Resource newEntry = client.Read <Resource>(entry.GetResourceLocation());
                        result.Entry.Add(new Bundle.BundleEntryComponent()
                        {
                            Resource = newEntry, Base = bundle.Base, ElementId = entry.ElementId
                        });
                    }
                }
                else
                {
                    throw Error.NotSupported("Cannot refresh an entry of type {0}", messageArgs: entry.GetType().Name);
                }
            }

            return(result);
        }
Example #29
0
        public static void ExpandProfileFile(string inputfile, string outputfile)
        {
            var source = ArtifactResolver.CreateOffline();
            //var source = new CachedArtifactSource(ArtifactResolver.CreateOffline());
            var expander = new SnapshotGenerator(source);

            string xml  = File.ReadAllText(inputfile);
            var    diff = (new FhirXmlParser()).Parse <StructureDefinition>(xml);

            expander.Generate(diff);
            xml = FhirSerializer.SerializeResourceToXml(diff);
            File.WriteAllText(outputfile, xml);
        }
Example #30
0
        public void TestSummary()
        {
            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 full = FhirSerializer.SerializeResourceToXml(p);

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

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

            Assert.IsTrue(summ.Contains("<birthDate"));
            Assert.IsFalse(summ.Contains("<photo"));

            var q = new Questionnaire();

            q.Status       = Questionnaire.QuestionnaireStatus.Published;
            q.Date         = "2015-09-27";
            q.Group        = new Questionnaire.GroupComponent();
            q.Group.Title  = "TITLE";
            q.Group.Text   = "TEXT";
            q.Group.LinkId = "linkid";

            var qfull = FhirSerializer.SerializeResourceToXml(q);

            Console.WriteLine(qfull);
            Assert.IsTrue(qfull.Contains("<status value=\"published\""));
            Assert.IsTrue(qfull.Contains("<date value=\"2015-09-27\""));
            Assert.IsTrue(qfull.Contains("<title value=\"TITLE\""));
            Assert.IsTrue(qfull.Contains("<text value=\"TEXT\""));
            Assert.IsTrue(qfull.Contains("<linkId value=\"linkid\""));

            var qSum = FhirSerializer.SerializeResourceToXml(q, summary: true);

            Console.WriteLine(qSum);
            Assert.IsTrue(qSum.Contains("<status value=\"published\""));
            Assert.IsTrue(qSum.Contains("<date value=\"2015-09-27\""));
            Assert.IsTrue(qSum.Contains("<title value=\"TITLE\""));
            Assert.IsFalse(qSum.Contains("<text value=\"TEXT\""));
            Assert.IsFalse(qSum.Contains("<linkId value=\"linkid\""));
        }