private static void ProcessEncounters(List<TimelineEntry> timeline, Bundle matchingEncounters)
        {
            foreach (var encounter in matchingEncounters.Entries.Select(x => (ResourceEntry<Encounter>)x))
            {
                DateTimeOffset? startTime;
                DateTimeOffset? endTime;

                if (encounter.Resource.Hospitalization != null)
                {
                    startTime = DateTimeOffset.Parse(encounter.Resource.Hospitalization.Period.Start);
                    endTime = DateTimeOffset.Parse(encounter.Resource.Hospitalization.Period.End);
                }
                else
                {
                    startTime = encounter.Published;
                    endTime = encounter.Published;
                }

                timeline.Add(new TimelineEntry
                {
                    StartTime = startTime,
                    EndTime = endTime,
                    TypeOfEntry = TimelineEntryType.Encounter,
                    Summary = encounter.Resource.Reason.ToString()
                });
            }
        }
Пример #2
0
        public Hl7.Fhir.Model.Bundle everythingById(string id)
        {
            Hl7.Fhir.Model.Bundle ReturnedBundle = null;

            try
            {
                //Attempt to send the resource to the server endpoint
                UriBuilder UriBuilderx = new UriBuilder(FhirClientEndPoint);
                UriBuilderx.Path = "Patient/" + id;
                Hl7.Fhir.Model.Resource ReturnedResource = _client.InstanceOperation(UriBuilderx.Uri, "everything");

                if (ReturnedResource is Hl7.Fhir.Model.Bundle)
                {
                    ReturnedBundle = ReturnedResource as Hl7.Fhir.Model.Bundle;
                    Console.WriteLine("Received: " + ReturnedBundle.Total + " results. ");
                }
                else
                {
                    throw new Exception("Operation call must return a bundle resource");
                }
                Console.WriteLine();
            }
            catch (Hl7.Fhir.Rest.FhirOperationException FhirOpExec)
            {
                //Process any Fhir Errors returned as OperationOutcome resource
                Console.WriteLine();
                Console.WriteLine("An error message: " + FhirOpExec.Message);
                Console.WriteLine();
                string    xml  = Hl7.Fhir.Serialization.FhirSerializer.SerializeResourceToXml(FhirOpExec.Outcome);
                XDocument xDoc = XDocument.Parse(xml);
                Console.WriteLine(xDoc.ToString());
            }
            return(ReturnedBundle);
        }
Пример #3
0
        /// <summary>
        /// Map the specified <paramref name="modelInstance"/> to a bundle
        /// </summary>
        public Resource MapToFhir(IdentifiedData modelInstance)
        {
            if (!(modelInstance is Core.Model.Collection.Bundle sdbBundle))
            {
                this.m_tracer.TraceError("Instance must be a bundle");
                throw new ArgumentException(nameof(modelInstance), this.m_localizationService.FormatString("error.type.ArgumentException", new
                {
                    param = "bundle"
                }));
            }

            var retVal = new Hl7.Fhir.Model.Bundle()
            {
                Type = Hl7.Fhir.Model.Bundle.BundleType.TransactionResponse,
                Meta = new Meta()
                {
                    LastUpdated = DateTimeOffset.Now
                }
            };

            // Parse return value
            foreach (var entry in sdbBundle.Item)
            {
                var handler = FhirResourceHandlerUtil.GetMapperForInstance(entry);
                if (handler == null)
                {
                    continue;                  // TODO: Warn
                }
                retVal.Entry.Add(new Hl7.Fhir.Model.Bundle.EntryComponent()
                {
                    Resource = handler.MapToFhir(entry)
                });
            }
            return(retVal);
        }
Пример #4
0
        internal static Bundle Load(JsonReader reader)
        {
            JObject feed;

            try
            {
                reader.DateParseHandling = DateParseHandling.None;
                reader.FloatParseHandling = FloatParseHandling.Decimal;
                feed = JObject.Load(reader);

                if( feed.Value<string>(JsonDomFhirReader.RESOURCETYPE_MEMBER_NAME) != "Bundle")
                    throw Error.Format("Input data is not an json FHIR bundle", null);

            }
            catch (Exception exc)
            {
                throw Error.Format("Exception while parsing feed: " + exc.Message, null);
            }

            Bundle result;

            try
            {
                result = new Bundle()
                {
                    Title = feed.Value<string>(BundleXmlParser.XATOM_TITLE),
                    LastUpdated = instantOrNull(feed[BundleXmlParser.XATOM_UPDATED]),
                    Id = SerializationUtil.UriValueOrNull(feed[BundleXmlParser.XATOM_ID]),
                    Links = getLinks(feed[BundleXmlParser.XATOM_LINK]),
                    Tags = TagListParser.ParseTags(feed[BundleXmlParser.XATOM_CATEGORY]),
                    AuthorName = feed[BundleXmlParser.XATOM_AUTHOR] as JArray != null ?
                                feed[BundleXmlParser.XATOM_AUTHOR]
                                    .Select(auth => auth.Value<string>(BundleXmlParser.XATOM_AUTH_NAME))
                                    .FirstOrDefault()
                                : null,
                    AuthorUri = feed[BundleXmlParser.XATOM_AUTHOR] as JArray != null ?
                                feed[BundleXmlParser.XATOM_AUTHOR]
                                    .Select(auth => auth.Value<string>(BundleXmlParser.XATOM_AUTH_URI))
                                    .FirstOrDefault() : null,
                    TotalResults = intValueOrNull(feed[BundleXmlParser.XATOM_TOTALRESULTS])
                };
            }
            catch (Exception exc)
            {
                throw Error.Format("Exception while parsing json feed attributes: " + exc.Message, null);                
            }

            var entries = feed[BundleXmlParser.XATOM_ENTRY];
            if (entries != null)
            {
                if (!(entries is JArray))
                {
                    throw Error.Format("The json feed contains a single entry, instead of an array", null);
                }

                result.Entries = loadEntries((JArray)entries, result);
            }

            return result;
        }
Пример #5
0
        public static void DebugDumpBundle(Hl7.Fhir.Model.Bundle b)
        {
            System.Diagnostics.Trace.WriteLine(String.Format("--------------------------------------------\r\nBundle Type: {0} ({1} total items, {2} included)", b.Type.ToString(), b.Total, (b.Entry != null ? b.Entry.Count.ToString() : "-")));

            if (b.Entry != null)
            {
                foreach (var item in b.Entry)
                {
                    if (item.Request != null)
                    {
                        System.Diagnostics.Trace.WriteLine(String.Format("        {0}: {1}", item.Request.Method.ToString(), item.Request.Url));
                    }
                    if (item.Response != null && item.Response.Status != null)
                    {
                        System.Diagnostics.Trace.WriteLine(String.Format("        {0}", item.Response.Status));
                    }
                    if (item.Resource != null && item.Resource is Hl7.Fhir.Model.DomainResource)
                    {
                        if (item.Resource.Meta != null && item.Resource.Meta.LastUpdated.HasValue)
                        {
                            System.Diagnostics.Trace.WriteLine(String.Format("            Last Updated:{0}, [{1}]", item.Resource.Meta.LastUpdated.Value, item.Resource.Meta.LastUpdated.Value.ToString("HH:mm:ss.FFFF")));
                        }
                        Hl7.Fhir.Rest.ResourceIdentity ri = new Hl7.Fhir.Rest.ResourceIdentity(item.FullUrl);
                        System.Diagnostics.Trace.WriteLine(String.Format("            {0}", (item.Resource as Hl7.Fhir.Model.DomainResource).ResourceIdentity(ri.BaseUri).OriginalString));
                    }
                }
            }
        }
Пример #6
0
        private void getPatientById(string id) //TODO zaimplementować to w HistoryForm
        {
            Patient                    p                    = null;
            List <Observation>         observations         = new List <Observation>();
            List <Medication>          medications          = new List <Medication>();
            List <MedicationStatement> medicationStatements = new List <MedicationStatement>();

            Hl7.Fhir.Model.Bundle ReturnedBundle = db.everythingById(id);
            foreach (var Entry in ReturnedBundle.Entry)
            {
                if (Entry.Resource is Patient)
                {
                    p = (Patient)Entry.Resource;
                }
                if (Entry.Resource is Observation)
                {
                    observations.Add((Observation)Entry.Resource);
                }
                if (Entry.Resource is Medication)
                {
                    medications.Add((Medication)Entry.Resource);
                }
                if (Entry.Resource is MedicationStatement)
                {
                    medicationStatements.Add((MedicationStatement)Entry.Resource);
                }

                Console.WriteLine(string.Format("{0}/{1}", Entry.Resource.TypeName, Entry.Resource.Id));
            }
            Console.WriteLine(string.Format("{0} {1}", p.Name.First().Given.FirstOrDefault(), p.Name.First().Family));
            Period a = medicationStatements[0].Effective as Period;

            Console.WriteLine(string.Format("{0}", a.Start));
        }
Пример #7
0
 public static Bundle CreateBundle(this ILocalhost localhost, Bundle.BundleType type)
 {
     Bundle bundle = new Bundle();
     bundle.Base = localhost.Base.ToString();
     bundle.Type = type;
     return bundle;
 }
        public static void WriteTo(Bundle bundle, JsonWriter writer, bool summary = false)
        {
            if (bundle == null) throw new ArgumentException("Bundle cannot be null");

            JObject result = new JObject();

            result.Add(new JProperty(JsonDomFhirReader.RESOURCETYPE_MEMBER_NAME, "Bundle"));

            if (!String.IsNullOrWhiteSpace(bundle.Title))
                result.Add(new JProperty(BundleXmlParser.XATOM_TITLE, bundle.Title));
            if (SerializationUtil.UriHasValue(bundle.Id)) result.Add(new JProperty(BundleXmlParser.XATOM_ID, bundle.Id));
            if (bundle.LastUpdated != null) 
                result.Add(new JProperty(BundleXmlParser.XATOM_UPDATED, bundle.LastUpdated));

            if (!String.IsNullOrWhiteSpace(bundle.AuthorName))
                result.Add(jsonCreateAuthor(bundle.AuthorName, bundle.AuthorUri));
            if (bundle.TotalResults != null) result.Add(new JProperty(BundleXmlParser.XATOM_TOTALRESULTS, bundle.TotalResults.ToString()));
          
            if (bundle.Links.Count > 0)
                result.Add(new JProperty(BundleXmlParser.XATOM_LINK, jsonCreateLinkArray(bundle.Links)));
            if (bundle.Tags != null && bundle.Tags.Count() > 0)
                result.Add( TagListSerializer.CreateTagCategoryPropertyJson(bundle.Tags));

            var entryArray = new JArray();

            foreach (var entry in bundle.Entries)
                entryArray.Add(createEntry(entry,summary));

            result.Add(new JProperty(BundleXmlParser.XATOM_ENTRY, entryArray));

            result.WriteTo(writer);
        }
Пример #9
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 /");
            }
        }
        public async Task <BundleResponse> Handle(BundleRequest bundleRequest, CancellationToken cancellationToken)
        {
            var bundleResource = bundleRequest.Bundle.ToPoco <Hl7.Fhir.Model.Bundle>();

            await FillRequestLists(bundleResource.Entry);

            if (bundleResource.Type == Hl7.Fhir.Model.Bundle.BundleType.Batch)
            {
                var responseBundle = new Hl7.Fhir.Model.Bundle
                {
                    Type = Hl7.Fhir.Model.Bundle.BundleType.BatchResponse,
                };

                await ExecuteAllRequests(responseBundle);

                return(new BundleResponse(responseBundle.ToResourceElement()));
            }
            else if (bundleResource.Type == Hl7.Fhir.Model.Bundle.BundleType.Transaction)
            {
                var responseBundle = new Hl7.Fhir.Model.Bundle
                {
                    Type = Hl7.Fhir.Model.Bundle.BundleType.TransactionResponse,
                };

                return(await ExecuteTransactionForAllRequests(responseBundle));
            }

            throw new MethodNotAllowedException(string.Format(Api.Resources.InvalidBundleType, bundleResource.Type));
        }
        public static void WriteTo(Bundle bundle, XmlWriter writer, bool summary = false)
        {
            if (bundle == null) throw new ArgumentException("Bundle cannot be null");

            var root = new XElement(BundleXmlParser.XATOMNS + BundleXmlParser.XATOM_FEED);

            if (!String.IsNullOrWhiteSpace(bundle.Title)) root.Add(xmlCreateTitle(bundle.Title));
            if (SerializationUtil.UriHasValue(bundle.Id)) root.Add(xmlCreateId(bundle.Id));
            if (bundle.LastUpdated != null) root.Add(new XElement(BundleXmlParser.XATOMNS + BundleXmlParser.XATOM_UPDATED, bundle.LastUpdated));

            if (!String.IsNullOrWhiteSpace(bundle.AuthorName))
                root.Add(xmlCreateAuthor(bundle.AuthorName, bundle.AuthorUri));
            if (bundle.TotalResults != null) root.Add(new XElement(BundleXmlParser.XOPENSEARCHNS + BundleXmlParser.XATOM_TOTALRESULTS, bundle.TotalResults));

            if (bundle.Links != null)
            {
                foreach (var l in bundle.Links)
                    root.Add(xmlCreateLink(l.Rel, l.Uri));
            }

            if (bundle.Tags != null)
            {
                foreach (var tag in bundle.Tags)
                    root.Add(TagListSerializer.CreateTagCategoryPropertyXml(tag));
            }

            foreach (var entry in bundle.Entries)
                root.Add(createEntry(entry, summary));

            root.WriteTo(writer);
            //var result = new XDocument(root);
            //result.WriteTo(writer);
        }
Пример #12
0
        public List <Hl7.Fhir.Model.Observation> observationsByID(string id)
        {
            List <Hl7.Fhir.Model.Observation> observations = new List <Observation>();

            try
            {
                //Attempt to send the resource to the server endpoint
                UriBuilder UriBuilderx = new UriBuilder(FhirClientEndPoint);
                UriBuilderx.Path = "Patient/" + id;
                Hl7.Fhir.Model.Resource ReturnedResource = _client.InstanceOperation(UriBuilderx.Uri, "everything");

                if (ReturnedResource is Hl7.Fhir.Model.Bundle)
                {
                    Hl7.Fhir.Model.Bundle ReturnedBundle = ReturnedResource as Hl7.Fhir.Model.Bundle;
                    foreach (var Entry in ReturnedBundle.Entry)
                    {
                        if (Entry.Resource is Observation)
                        {
                            observations.Add((Observation)Entry.Resource);
                        }
                    }
                }
                else
                {
                    throw new Exception("Operation call must return a bundle resource");
                }
            }
            catch (Hl7.Fhir.Rest.FhirOperationException FhirOpExec)
            {
                Console.WriteLine("An error message: " + FhirOpExec.Message);
            }
            return(observations);
        }
Пример #13
0
 /// <summary>
 /// Creates a snapshot for search commands
 /// </summary>
 public Snapshot CreateSnapshot(Bundle.BundleType type, Uri link, IEnumerable<string> keys, string sortby = null, int? count = null, IList<string> includes = null)
 {
     
     Snapshot snapshot = Snapshot.Create(type, link, keys, sortby, NormalizeCount(count), includes);
     snapshotstore.AddSnapshot(snapshot);
     return snapshot;
 }
        public static bool TryValidate(Bundle bundle, ICollection<ValidationResult> validationResults = null)
        {
            if (bundle == null) throw new ArgumentNullException("bundle");

            var results = validationResults ?? new List<ValidationResult>();
            return Validator.TryValidateObject(bundle, ValidationContextFactory.Create(bundle, null), results, true);
        }
Пример #15
0
 public static Key ExtractKey(this Localhost localhost, Bundle.BundleEntryComponent entry)
 {
     Uri uri = new Uri(entry.Request.Url, UriKind.RelativeOrAbsolute);
     Key compare = ExtractKey(uri); // This fails!! ResourceIdentity does not work in this case.
     return localhost.LocalUriToKey(uri);   
     
 }
Пример #16
0
        private void getPatientData()
        {
            Patient p = patient;

            observations         = new List <Observation>();
            medications          = new List <Medication>();
            medicationStatements = new List <MedicationStatement>();

            Hl7.Fhir.Model.Bundle ReturnedBundle = data;
            foreach (var Entry in ReturnedBundle.Entry)
            {
                if (Entry.Resource is Patient)
                {
                    p = (Patient)Entry.Resource;
                }
                if (Entry.Resource is Observation)
                {
                    observations.Add((Observation)Entry.Resource);
                }
                if (Entry.Resource is Medication)
                {
                    medications.Add((Medication)Entry.Resource);
                }
                if (Entry.Resource is MedicationStatement)
                {
                    medicationStatements.Add((MedicationStatement)Entry.Resource);
                }

                //Console.WriteLine(string.Format("{0}/{1}", Entry.Resource.TypeName, Entry.Resource.Id));
            }
            //Console.WriteLine(string.Format("{0} {1}", p.Name.First().Given.FirstOrDefault(), p.Name.First().Family));
            //Period a = medicationStatements[0].Effective as Period;
            //Console.WriteLine(string.Format("{0}", a.Start));
        }
Пример #17
0
        public void ResourceListFiltering()
        {
            var testBundle = new Bundle();

            testBundle.AddResourceEntry(new Patient { Id = "1234", Meta = new Meta { VersionId = "v2" } }, "http://nu.nl/fhir/Patient/1234");
            testBundle.AddResourceEntry(new Patient { Id = "1234", Meta = new Meta { VersionId = "v3" } }, "http://nu.nl/fhir/Patient/1234");
            testBundle.AddResourceEntry(new Patient { Id = "1234", Meta = new Meta { VersionId = "v4" } }, "http://nu.nl/fhir/Patient/1234")
                        .Request = new Bundle.BundleEntryRequestComponent { Method = Bundle.HTTPVerb.DELETE } ;

            testBundle.AddResourceEntry(new Patient { Id = "5678" }, "http://server1.com/fhir/Patient/5678");
            testBundle.AddResourceEntry(new Patient { Id = "1.2.3.4.5" }, "urn:oid:1.2.3.4.5");

            var result = testBundle.FindEntry("http://nu.nl/fhir/Patient/1234");
            Assert.AreEqual(2, result.Count());
            result = testBundle.FindEntry("http://nu.nl/fhir/Patient/1234", includeDeleted: true);
            Assert.AreEqual(3, result.Count());
            result = testBundle.FindEntry("http://nu.nl/fhir/Patient/1234/_history/v3", includeDeleted: true);
            Assert.AreEqual(1, result.Count());
            result = testBundle.FindEntry(new Uri("http://server3.org/fhir/Patient/1234"));
            Assert.AreEqual(0, result.Count());

            result = testBundle.FindEntry(new Uri("http://server1.com/fhir/Patient/5678"));
            Assert.AreEqual(1, result.Count());
            result = testBundle.FindEntry(new Uri("http://server2.com/fhir/Patient/5678"));
            Assert.AreEqual(0, result.Count());

            result = testBundle.FindEntry(new Uri("urn:oid:1.2.3.4.5"));
            Assert.AreEqual(1, result.Count());
        }
        public void ResourceListFiltering()
        {
            var testBundle = new Bundle();

            testBundle.Entry.Add(new Bundle.BundleEntryComponent { Resource = new Patient { Id = "1234", Meta = new Meta { VersionId = "v2" } } });
            testBundle.Entry.Add(new Bundle.BundleEntryComponent { Resource = new Patient { Id = "1234", Meta = new Meta { VersionId = "v3" } } });
            testBundle.Entry.Add(new Bundle.BundleEntryComponent { Resource = new Patient { Id = "1234", Meta = new Meta { VersionId = "v4"} }, 
                            Transaction = new Bundle.BundleEntryTransactionComponent {Method = Bundle.HTTPVerb.DELETE}  });

            testBundle.Entry.Add(new Bundle.BundleEntryComponent { Resource = new Patient { Id = "5678" }, Base = "http://server1.com/fhir" });

            testBundle.Entry.Add(new Bundle.BundleEntryComponent { Resource = new Patient { Id = "1.2.3.4.5" }, Base = "urn:oid:" });

            var result = testBundle.FindEntry("Patient", "1234");
            Assert.AreEqual(2, result.Count());
            result = testBundle.FindEntry("Patient", "1234", includeDeleted: true);
            Assert.AreEqual(3, result.Count());
            result = testBundle.FindEntry("Patient", "1234", "v3", includeDeleted: true);
            Assert.AreEqual(1, result.Count());
            result = testBundle.FindEntry(new Uri("http://server3.org/fhir/Patient/1234"));
            Assert.AreEqual(0, result.Count());

            result = testBundle.FindEntry("Patient", "5678");
            Assert.AreEqual(1, result.Count());
            result = testBundle.FindEntry(new Uri("http://server1.com/fhir/Patient/5678"));
            Assert.AreEqual(1, result.Count());
            result = testBundle.FindEntry(new Uri("http://server2.com/fhir/Patient/5678"));
            Assert.AreEqual(0, result.Count());

            result = testBundle.FindEntry(new Uri("urn:oid:1.2.3.4.5"));
            Assert.AreEqual(1, result.Count());
        }
Пример #19
0
 public static void Append(this Bundle bundle, Bundle.HTTPVerb method, IEnumerable<Resource> resources)
 {
     foreach (Resource resource in resources)
     {
         bundle.Append(method, resource);
     }
 }
Пример #20
0
        public async Task GivenATransactionBundleRequestWithNullUrl_WhenProcessing_ReturnsABadRequest()
        {
            var bundle = new Hl7.Fhir.Model.Bundle
            {
                Type  = BundleType.Transaction,
                Entry = new List <EntryComponent>
                {
                    new EntryComponent
                    {
                        Request = new RequestComponent
                        {
                            Method = HTTPVerb.PUT,
                            Url    = null,
                        },
                        Resource = new Basic {
                            Id = "test"
                        },
                    },
                },
            };

            _router.When(r => r.RouteAsync(Arg.Any <RouteContext>()))
            .Do(RouteAsyncFunction);

            var bundleRequest = new BundleRequest(bundle.ToResourceElement());

            await Assert.ThrowsAsync <RequestNotValidException>(async() => await _bundleHandler.Handle(bundleRequest, default));
        }
Пример #21
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 myAssembly = typeof(TestXmlSignature).Assembly;
            var stream = myAssembly.GetManifestResourceStream("Spark.Tests.spark.pfx");

            var data = new byte[stream.Length];
            stream.Read(data,0,(int)stream.Length);
            var certificate = new X509Certificate2(data);

            var bundleData = FhirSerializer.SerializeBundleToXmlBytes(b);
            var bundleXml = Encoding.UTF8.GetString(bundleData);

            var bundleSigned = XmlSignatureHelper.Sign(bundleXml, certificate);

            Assert.IsTrue(XmlSignatureHelper.IsSigned(bundleSigned));
            Assert.IsTrue(XmlSignatureHelper.VerifySignature(bundleSigned));

            var changedBundle = bundleSigned.Replace("<name>Ewout", "<name>Ewald");
            Assert.AreEqual(bundleSigned.Length, changedBundle.Length);

            Assert.IsFalse(XmlSignatureHelper.VerifySignature(changedBundle));
        }
Пример #22
0
        public async Task GivenABundleWithMultipleCalls_WhenProcessed_ThenANotificationWillBeEmitted(BundleType type, HTTPVerb method1, HTTPVerb method2, int code200s, int code404s)
        {
            var bundle = new Hl7.Fhir.Model.Bundle
            {
                Type  = type,
                Entry = new List <EntryComponent>
                {
                    new EntryComponent
                    {
                        Request = new RequestComponent
                        {
                            Method = method1,
                            Url    = "unused1",
                        },
                        Resource = new Patient(),
                    },
                    new EntryComponent
                    {
                        Request = new RequestComponent
                        {
                            Method = method2,
                            Url    = "unused2",
                        },
                        Resource = new Patient(),
                    },
                },
            };

            _router.When(r => r.RouteAsync(Arg.Any <RouteContext>()))
            .Do(RouteAsyncFunction);

            BundleMetricsNotification notification = null;
            await _mediator.Publish(Arg.Do <BundleMetricsNotification>(note => notification = note), Arg.Any <CancellationToken>());

            var            bundleRequest  = new BundleRequest(bundle.ToResourceElement());
            BundleResponse bundleResponse = await _bundleHandler.Handle(bundleRequest, default);

            var bundleResource = bundleResponse.Bundle.ToPoco <Hl7.Fhir.Model.Bundle>();

            Assert.Equal(type == BundleType.Batch ? BundleType.BatchResponse : BundleType.TransactionResponse, bundleResource.Type);
            Assert.Equal(2, bundleResource.Entry.Count);

            await _mediator.Received().Publish(Arg.Any <BundleMetricsNotification>(), Arg.Any <CancellationToken>());

            Assert.Equal(type == BundleType.Batch ? AuditEventSubType.Batch : AuditEventSubType.Transaction, notification.FhirOperation);

            var results = notification.ApiCallResults;

            Assert.Equal(code200s, results["200"]);

            if (code404s > 0)
            {
                Assert.Equal(code404s, results["404"]);
            }
            else
            {
                Assert.Equal(1, results.Keys.Count);
            }
        }
Пример #23
0
        public static void AssertEntryIdsArePresentAndAbsoluteUrls(Bundle b)
        {
            if (b.Entries.Any(e => e.Id == null || e.SelfLink == null))
                TestResult.Fail("Some id/selflinks in the bundle are null");

            if (!b.Entries.All(e => e.Id.IsAbsoluteUri && e.SelfLink.IsAbsoluteUri))
                TestResult.Fail("Some id/selflinks in the bundle are relative");
        }
Пример #24
0
        private Bundle.EntryComponent newEntry(Bundle.HTTPVerb method)
        {
            var newEntry = new Bundle.EntryComponent();
            newEntry.Request = new Bundle.RequestComponent();
            newEntry.Request.Method = method;

            return newEntry;
        }
Пример #25
0
        public static void Append(this Bundle bundle, Bundle.HTTPVerb method, Resource resource)
        {
            Bundle.BundleEntryComponent entry = CreateEntryForResource(resource);

            if (entry.Request == null) entry.Request = new Bundle.BundleEntryRequestComponent();
            entry.Request.Method = method;
            bundle.Entry.Add(entry);
        }
Пример #26
0
 public  static Bundle Bundle()
 {
     Bundle bundle = new Bundle();
     Patient p = Test.Patient();
     BundleEntry entry = ResourceEntry.Create(p);
     bundle.Entries.Add(entry);
     return bundle;
 }
Пример #27
0
 public static ParsedPatient FromBundle(Bundle bundle)
 {
     return(new ParsedPatient {
         Resources = bundle.Entry.Select(e => new ParsedResource {
             Resource = e.Resource
         }).ToList(), Seed = Seed.Random()
     });
 }
        private Bundle.BundleEntryComponent newEntry(Bundle.HTTPVerb method)
        {
            var newEntry = new Bundle.BundleEntryComponent();
            newEntry.Transaction = new Bundle.BundleEntryTransactionComponent();
            newEntry.Transaction.Method = method;

            return newEntry;
        }
        public async Task <IEnumerable <Observation> > GetObservationsAsync(string userId)
        {
            FHIR.Bundle result = await _fhirClient.SearchAsync <FHIR.Observation>(new SearchParams().Add("subject:Patient.identifier", userId));

            return(result.Entry
                   .Select(e => (FHIR.Observation)e.Resource)
                   .Select(ConvertObservation));
        }
Пример #30
0
        public async Task GivenABundle_WhenOneRequestProducesA429_429IsRetriedThenSucceeds()
        {
            var bundle = new Hl7.Fhir.Model.Bundle
            {
                Type  = BundleType.Batch,
                Entry = new List <EntryComponent>
                {
                    new EntryComponent {
                        Request = new RequestComponent {
                            Method = HTTPVerb.GET, Url = "/Patient"
                        }
                    },
                    new EntryComponent {
                        Request = new RequestComponent {
                            Method = HTTPVerb.GET, Url = "/Patient"
                        }
                    },
                    new EntryComponent {
                        Request = new RequestComponent {
                            Method = HTTPVerb.GET, Url = "/Patient"
                        }
                    },
                },
            };

            int callCount = 0;

            _router.When(r => r.RouteAsync(Arg.Any <RouteContext>()))
            .Do(info =>
            {
                info.Arg <RouteContext>().Handler = context =>
                {
                    callCount++;
                    if (callCount == 2)
                    {
                        context.Response.StatusCode = StatusCodes.Status429TooManyRequests;
                    }
                    else
                    {
                        context.Response.StatusCode = StatusCodes.Status200OK;
                    }

                    return(Task.CompletedTask);
                };
            });

            var            bundleRequest  = new BundleRequest(bundle.ToResourceElement());
            BundleResponse bundleResponse = await _bundleHandler.Handle(bundleRequest, default);

            Assert.Equal(4, callCount);
            var bundleResource = bundleResponse.Bundle.ToPoco <Hl7.Fhir.Model.Bundle>();

            Assert.Equal(3, bundleResource.Entry.Count);
            foreach (var entry in bundleResource.Entry)
            {
                Assert.Equal("200", entry.Response.Status);
            }
        }
Пример #31
0
 public static void Append(this Bundle bundle, Bundle.HTTPVerb method, Resource resource)
 {
     var entry = new Bundle.BundleEntryComponent();
     entry.Resource = resource;
     entry.Base = bundle.Base;
     if (entry.Transaction == null) entry.Transaction = new Bundle.BundleEntryTransactionComponent();
     entry.Transaction.Method = method;
     bundle.Entry.Add(entry);
 }
Пример #32
0
        public async Task GivenABundleWithAGet_WhenNotAuthorized_ReturnsABundleResponseWithCorrectEntry()
        {
            var bundle = new Hl7.Fhir.Model.Bundle
            {
                Type  = Hl7.Fhir.Model.Bundle.BundleType.Batch,
                Entry = new List <Hl7.Fhir.Model.Bundle.EntryComponent>
                {
                    new Hl7.Fhir.Model.Bundle.EntryComponent
                    {
                        Request = new Hl7.Fhir.Model.Bundle.RequestComponent
                        {
                            Method = Hl7.Fhir.Model.Bundle.HTTPVerb.GET,
                            Url    = "/Patient",
                        },
                    },
                },
            };

            _router.When(r => r.RouteAsync(Arg.Any <RouteContext>()))
            .Do(RouteAsyncFunction);

            var bundleRequest = new BundleRequest(bundle.ToResourceElement());

            BundleResponse bundleResponse = await _bundleHandler.Handle(bundleRequest, CancellationToken.None);

            var bundleResource = bundleResponse.Bundle.ToPoco <Hl7.Fhir.Model.Bundle>();

            Assert.Equal(Hl7.Fhir.Model.Bundle.BundleType.BatchResponse, bundleResource.Type);
            Assert.Single(bundleResource.Entry);

            Hl7.Fhir.Model.Bundle.EntryComponent entryComponent = bundleResource.Entry.First();
            Assert.Equal("403", entryComponent.Response.Status);

            var operationOutcome = entryComponent.Response.Outcome as OperationOutcome;

            Assert.NotNull(operationOutcome);
            Assert.Single(operationOutcome.Issue);

            var issueComponent = operationOutcome.Issue.First();

            Assert.Equal(OperationOutcome.IssueSeverity.Error, issueComponent.Severity);
            Assert.Equal(OperationOutcome.IssueType.Forbidden, issueComponent.Code);
            Assert.Equal("Authorization failed.", issueComponent.Diagnostics);

            void RouteAsyncFunction(CallInfo callInfo)
            {
                var routeContext = callInfo.Arg <RouteContext>();

                routeContext.Handler = context =>
                {
                    context.Response.StatusCode = 403;

                    return(Task.CompletedTask);
                };
            }
        }
Пример #33
0
        public void SetBody(Bundle bundle, ResourceFormat format)
        {
            if (bundle == null) throw Error.ArgumentNull("bundle");

            _body = format == ResourceFormat.Xml ?
                FhirSerializer.SerializeBundleToXmlBytes(bundle, summary: false) :
                FhirSerializer.SerializeBundleToJsonBytes(bundle, summary: false);

            _contentType = ContentType.BuildContentType(format, forBundle: true);
        }
Пример #34
0
        public async Task GivenABundle_WhenMultipleRequests_ReturnsABundleResponseWithCorrectOrder()
        {
            var bundle = new Hl7.Fhir.Model.Bundle
            {
                Type  = Hl7.Fhir.Model.Bundle.BundleType.Batch,
                Entry = new List <Hl7.Fhir.Model.Bundle.EntryComponent>
                {
                    new Hl7.Fhir.Model.Bundle.EntryComponent
                    {
                        Request = new RequestComponent
                        {
                            Method = HTTPVerb.GET,
                            Url    = "/Patient",
                        },
                    },
                    new Hl7.Fhir.Model.Bundle.EntryComponent
                    {
                        Request = new RequestComponent
                        {
                            Method = HTTPVerb.POST,
                            Url    = "/Patient",
                        },
                        Resource = new Hl7.Fhir.Model.Patient
                        {
                        },
                    },
                    new Hl7.Fhir.Model.Bundle.EntryComponent
                    {
                        Request = new RequestComponent
                        {
                            Method = HTTPVerb.PUT,
                            Url    = "/Patient/789",
                        },
                        Resource = new Hl7.Fhir.Model.Patient
                        {
                        },
                    },
                },
            };

            _router.When(r => r.RouteAsync(Arg.Any <RouteContext>()))
            .Do(RouteAsyncFunction);

            var            bundleRequest  = new BundleRequest(bundle.ToResourceElement());
            BundleResponse bundleResponse = await _bundleHandler.Handle(bundleRequest, default);

            var bundleResource = bundleResponse.Bundle.ToPoco <Hl7.Fhir.Model.Bundle>();

            Assert.Equal(Hl7.Fhir.Model.Bundle.BundleType.BatchResponse, bundleResource.Type);
            Assert.Equal(3, bundleResource.Entry.Count);
            Assert.Equal("403", bundleResource.Entry[0].Response.Status);
            Assert.Equal("404", bundleResource.Entry[1].Response.Status);
            Assert.Equal("200", bundleResource.Entry[2].Response.Status);
        }
Пример #35
0
 public static Snapshot TakeSnapshotFromBundle(Bundle bundle)
 {
     // Is Snapshot not a type of bundle???
     Snapshot snapshot = new Snapshot();
     snapshot.FeedTitle = bundle.Title;
     snapshot.Id = Guid.NewGuid().ToString();
     snapshot.FeedSelfLink = bundle.Links.SelfLink.ToString();
     snapshot.Contents = bundle.SelfLinks();
     snapshot.MatchCount = snapshot.Contents.Count();
     return snapshot;
 }
Пример #36
0
 public static IList<Interaction> GetInteractions(this ILocalhost localhost, Bundle bundle)
 {
     var interactions = new List<Interaction>();
     foreach(var entry in bundle.Entry)
     {
         Interaction interaction = localhost.ToInteraction(entry);
         interaction.SupplementBase(bundle.Base);
         interactions.Add(interaction);
     }
     return interactions;
 }
Пример #37
0
        private void ensureAbsoluteUris(Bundle bundle)
        {
            bundle.Id = makeAbsolute(bundle.Id);

            foreach (var link in bundle.Links)
                link.Uri = makeAbsolute(link.Uri);

            foreach (BundleEntry be in bundle.Entries)
                ensureAbsoluteUris(be);

            bundle.Links.Base = _endpoint;
        }
Пример #38
0
 public Bundle FirstPage(Bundle bundle, int count)
 {
     Snapshot snapshot = Snapshot.TakeSnapshotFromBundle(bundle);
     
     if (bundle.Entries.Count > count)
     {
         _store.StoreSnapshot(snapshot);
     }
     
     // Return the first page
     return GetPage(snapshot, 0, count);
 }
Пример #39
0
        public Bundle.BundleEntryComponent Execute(Bundle.BundleEntryComponent interaction, Type expected)
        {
            if (interaction == null) throw Error.ArgumentNull("interaction");

            LastResult = doRequest(interaction);
            var status = LastResult.Response.Status;
            HttpStatusCode statusCode;
            if (!Enum.TryParse<HttpStatusCode>(status, out statusCode))
            {
                // If the status code is unable to be parsed, then report
                // in internal server error
                statusCode = HttpStatusCode.InternalServerError;
            }

            if (status.StartsWith("2"))      // 2xx codes - success
            {
                // We have a successful call, but the body is not of the type we expect.
                if (LastResult.Resource != null && !LastResult.Resource.GetType().CanBeTreatedAsType(expected))
                {                                     
                    // If this is an operationoutcome, that may still be allright. Keep the OperationOutcome in 
                    // the LastResult, and return null as the result.
                    if (LastResult.Resource is OperationOutcome)
                        return null;
                    
                    var message = String.Format("Operation {0} on {1} expected a body of type {2} but a {3} was returned", LastResult.Request.Method,
                        LastResult.Request.Url, expected.Name, LastResult.Resource.GetType().Name);
                    throw new FhirOperationException(message, statusCode);
                }

                return LastResult;
            }
            else if (status.StartsWith("3") || status.StartsWith("1"))      // 3xx codes - we don't handle them, unless the .NET API did it for us
            {
                throw Error.NotSupported("Server returned a status code '{0}', which is not supported by the FhirClient".FormatWith(status));
            }
            else if (status.StartsWith("4") || status.StartsWith("5"))      // 4xx/5xx codes - client or server error.
            {
                var message = String.Format("Operation was unsuccessful, and returned status {0}.", status);

                var outcome = LastResult.Resource as OperationOutcome;
                if (outcome != null)
                {
                    throw new FhirOperationException(message + " OperationOutcome: " + outcome.ToString(), statusCode, outcome);
                }
                else
                    throw new FhirOperationException(message, statusCode);
            }
            else
            {
                throw Error.NotSupported("Server returned an illegal http status code '{0}', which is not defined by the Http standard".FormatWith(status));
            }
        }
Пример #40
0
        protected async Task <TResource> GetResourceByIdentityAsync <TResource>(Model.Identifier identifier)
            where TResource : Model.Resource, new()
        {
            EnsureArg.IsNotNull(identifier, nameof(identifier));

            string fhirTypeName = ModelInfo.GetFhirTypeNameForType(typeof(TResource));

            _ = Enum.TryParse(fhirTypeName, out ResourceType resourceType);

            Model.Bundle result = await FhirService.SearchForResourceAsync(resourceType, identifier.ToSearchQueryParameter()).ConfigureAwait(false);

            return(await result.ReadOneFromBundleWithContinuationAsync <TResource>(FhirService));
        }
Пример #41
0
        public void testExtensionDefinitions()
        {
            // obsolete:
            // Bundle b = (Bundle)FhirParser.ParseResourceFromXml(File.ReadAllText("TestData\\extension-definitions.xml"));
            var parser = new FhirXmlParser();

            Model.Bundle b = parser.Parse <Model.Bundle>(File.ReadAllText("TestData\\extension-definitions.xml"));

            foreach (Model.Bundle.EntryComponent be in b.Entry)
            {
                testStructureDefinition((Model.StructureDefinition)be.Resource);
            }
        }
        public void BundleEntryByReference()
        {
            Bundle b = new Bundle();

            b.Entries.Add(new ResourceEntry<Patient> { Id = new Uri("http://x.com/Patient/1"), SelfLink = new Uri("http://x.com/Patient/1/_history/1") });
            b.Entries.Add(new ResourceEntry<Patient> { Id = new Uri("http://x.com/Patient/1"), SelfLink = new Uri("http://x.com/Patient/1/_history/2") });
            b.Entries.Add(new ResourceEntry<Patient> { Id = new Uri("http://y.com/Patient/1"), SelfLink = new Uri("http://y.com/Patient/1") });

            b.Links.Base = new Uri("http://x.com");

            Assert.AreEqual(2, b.FindEntryByReference(new Uri("Patient/1", UriKind.Relative)).Count());
            Assert.AreEqual(1, b.FindEntryByReference(new Uri("Patient/1/_history/1", UriKind.Relative)).Count());
            Assert.AreEqual(2, b.FindEntryByReference(new Uri("http://y.com/Patient/1")).Count());
        }
Пример #43
0
        public void TestPostXds()
        {
            Bundle xdsBundle = DemoData.GetDemoConn5ExampleBundle();
            xdsBundle.SetBundleType(BundleType.Document);

            _deliveryResult = client.DeliverToMailbox(xdsBundle);

            if (_deliveryResult.Entries.Count != 12)
                TestResult.Fail("Result bundle should contain exactly two resources");
            if(_deliveryResult.Entries.ByResourceType<DocumentReference>().Count() != 1)
                TestResult.Fail("Result bundle should contain one DocumentReference");
            if (_deliveryResult.Entries.ByResourceType<Binary>().Count() != 1)
                TestResult.Fail("Result bundle should contain one Binary");
        }
Пример #44
0
        public void TestPostXdsWidthCid()
        {
            Bundle xdsBundle = DemoData.GetDemoConn5CidExampleBundle();
            xdsBundle.SetBundleType(BundleType.Document);

            _deliveryResult = client.DeliverToMailbox(xdsBundle);

            if (_deliveryResult.Entries.Count != 7)
                TestResult.Fail("Result bundle should contain exactly 7 resources");
            if (_deliveryResult.Entries.ByResourceType<DocumentReference>().Count() != 1)
                TestResult.Fail("Result bundle should contain one DocumentReference");
            if (_deliveryResult.Entries.ByResourceType<Binary>().Count() != 1)
                TestResult.Fail("Result bundle should contain one Binary");
            HttpTests.AssertEntryIdsArePresentAndAbsoluteUrls(_deliveryResult);
        }
Пример #45
0
 public static Key ExtractKey(this ILocalhost localhost, Bundle.BundleEntryComponent entry)
 {
     if (entry.Transaction != null && entry.Transaction.Url != null)
     {
         return localhost.UriToKey(entry.Transaction.Url);
     }
     else if (entry.Resource != null)
     {
         return entry.Resource.ExtractKey();
     }
     else
     {
         return null;
     }
 }
Пример #46
0
        public async Task <SearchObservationsResponse> GetObservationsAsync()
        {
            string userId = _userContext.UserId;

            FHIR.Bundle result = await _fhirClient.SearchAsync <FHIR.Observation>(new SearchParams().Add("subject:Patient.identifier", userId));

            IEnumerable <Observation> observations = result.Entry
                                                     .Select(e => (FHIR.Observation)e.Resource)
                                                     .Select(ConvertObservation);

            return(new SearchObservationsResponse
            {
                Observations = observations
            });
        }
Пример #47
0
        public static Snapshot Create(Bundle.BundleType type, Uri selflink, IEnumerable<string> keys, string sortby, IEnumerable<string> includes = null)
        {
            Snapshot snapshot = new Snapshot();
            snapshot.Type = type;
            snapshot.Id = CreateKey();
            snapshot.WhenCreated = DateTimeOffset.UtcNow;
            //snapshot.FeedTitle = title;
            snapshot.FeedSelfLink = selflink.ToString();

            snapshot.Includes = (includes != null) ? includes.ToList() : null;
            snapshot.Keys = keys;
            snapshot.Count = keys.Count();
            snapshot.SortBy = sortby;
            return snapshot;
        }
Пример #48
0
        public async Task GivenAnEmptyBatchBundle_WhenProcessed_ReturnsABundleResponseWithNoEntries()
        {
            var bundle = new Hl7.Fhir.Model.Bundle
            {
                Type = BundleType.Batch,
            };

            var bundleRequest = new BundleRequest(bundle.ToResourceElement());

            BundleResponse bundleResponse = await _bundleHandler.Handle(bundleRequest, CancellationToken.None);

            var bundleResource = bundleResponse.Bundle.ToPoco <Hl7.Fhir.Model.Bundle>();

            Assert.Equal(BundleType.BatchResponse, bundleResource.Type);
            Assert.Empty(bundleResource.Entry);
        }
Пример #49
0
        private async Task ExecuteRequests(Hl7.Fhir.Model.Bundle responseBundle, Hl7.Fhir.Model.Bundle.HTTPVerb httpVerb)
        {
            foreach (RouteContext request in _requests[httpVerb])
            {
                var entryComponent = new Hl7.Fhir.Model.Bundle.EntryComponent();

                if (request.Handler != null)
                {
                    HttpContext httpContext = request.HttpContext;
                    await request.Handler.Invoke(httpContext);

                    httpContext.Response.Body.Seek(0, SeekOrigin.Begin);
                    string bodyContent = new StreamReader(httpContext.Response.Body).ReadToEnd();

                    ResponseHeaders responseHeaders = httpContext.Response.GetTypedHeaders();
                    entryComponent.Response = new Hl7.Fhir.Model.Bundle.ResponseComponent
                    {
                        Status       = httpContext.Response.StatusCode.ToString(),
                        Location     = responseHeaders.Location?.OriginalString,
                        Etag         = responseHeaders.ETag?.ToString(),
                        LastModified = responseHeaders.LastModified,
                    };

                    if (!string.IsNullOrWhiteSpace(bodyContent))
                    {
                        var entryComponentResource = _fhirJsonParser.Parse <Resource>(bodyContent);

                        if (entryComponentResource.ResourceType == ResourceType.OperationOutcome)
                        {
                            entryComponent.Response.Outcome = entryComponentResource;
                        }
                        else
                        {
                            entryComponent.Resource = entryComponentResource;
                        }
                    }
                }
                else
                {
                    entryComponent.Response = new Hl7.Fhir.Model.Bundle.ResponseComponent {
                        Status = ((int)HttpStatusCode.NotFound).ToString()
                    };
                }

                responseBundle.Entry.Add(entryComponent);
            }
        }
Пример #50
0
        /// <summary>
        /// Extra Fhir resource list from fhir bundle.entry.
        /// </summary>
        /// <param name="bundle"></param>
        /// <param name="resourceName"></param>
        /// <returns></returns>
        private List <Resource> ExtraFhirResourceFromBundle(FhirModel.Bundle bundle, string resourceName)
        {
            List <Resource> fhirResourceList = new List <Resource>();

            if (bundle.Entry != null && bundle.Entry.Count > 0)
            {
                bundle.Entry.ForEach(e =>
                {
                    if (e.Resource.ResourceType.ToString() == resourceName)
                    {
                        fhirResourceList.Add(e.Resource);
                    }
                });
            }

            return(fhirResourceList);
        }
    public void NextSceneOnClick(string input)
    {
        int Case = GameObject.FindGameObjectWithTag("Manager").GetComponent <Settings>().QuestionType;

        if (Case != 1)
        {
            Debug.Log("Should be trying to load next scene");
            SceneManager.LoadScene(TargetScene);
        }
        else
        {
            string FHIR_Information = input;

            var Fhir_Client = new FhirClient("http://stu3.test.pyrohealth.net/fhir");
            Fhir_Client.Timeout = (60 * 1000);

            Hl7.Fhir.Model.Bundle ReturnedSearchBundle = Fhir_Client.Search <Hl7.Fhir.Model.Observation>(new string[] { "patient=Patient/" + FHIR_Information });

            string id = "";

            foreach (var Entry in ReturnedSearchBundle.Entry)
            {
                id = Entry.Resource.Id;
            }

            var obs = Fhir_Client.Read <Observation>("Observation/" + id);

            if (obs.Code.Coding[0].Code == "23537-4")
            {
                if (obs.Interpretation.Coding[0].Code == "H")
                {
                    SceneManager.LoadScene(13);
                }
                else
                {
                    SceneManager.LoadScene(9);
                }
            }
            else
            {
                SceneManager.LoadScene(1);
            }
        }
    }
        private async Task <BundleResponse> ExecuteTransactionForAllRequests(Hl7.Fhir.Model.Bundle responseBundle)
        {
            try
            {
                using (var transaction = _transactionHandler.BeginTransaction())
                {
                    await ExecuteAllRequests(responseBundle);

                    transaction.Complete();
                }
            }
            catch (TransactionAbortedException)
            {
                _logger.LogError("Failed to commit a transaction. Throwing BadRequest as a default exception.");
                throw new TransactionFailedException(Api.Resources.GeneralTransactionFailedError, HttpStatusCode.BadRequest);
            }

            return(new BundleResponse(responseBundle.ToResourceElement()));
        }
        public async Task GivenABundle_WhenOneRequestProducesA429_SubsequentRequestAreSkipped()
        {
            var bundle = new Hl7.Fhir.Model.Bundle
            {
                Type  = BundleType.Batch,
                Entry = new List <EntryComponent>
                {
                    new EntryComponent {
                        Request = new RequestComponent {
                            Method = HTTPVerb.GET, Url = "/Patient"
                        }
                    },
                    new EntryComponent {
                        Request = new RequestComponent {
                            Method = HTTPVerb.GET, Url = "/Patient"
                        }
                    },
                },
            };

            int callCount = 0;

            _router.When(r => r.RouteAsync(Arg.Any <RouteContext>()))
            .Do(info =>
            {
                info.Arg <RouteContext>().Handler = context =>
                {
                    callCount++;
                    context.Response.StatusCode = StatusCodes.Status429TooManyRequests;
                    return(Task.CompletedTask);
                };
            });

            var            bundleRequest  = new BundleRequest(bundle.ToResourceElement());
            BundleResponse bundleResponse = await _bundleHandler.Handle(bundleRequest, default);

            Assert.Equal(1, callCount);
            var bundleResource = bundleResponse.Bundle.ToPoco <Hl7.Fhir.Model.Bundle>();

            Assert.Equal(2, bundleResource.Entry.Count);
            Assert.All(bundleResource.Entry, e => Assert.Equal("429", e.Response.Status));
        }
Пример #54
0
        public async Task <BundleResponse> Handle(BundleRequest bundleRequest, CancellationToken cancellationToken)
        {
            var bundleResource = bundleRequest.Bundle.ToPoco <Hl7.Fhir.Model.Bundle>();

            if (bundleResource.Type != Hl7.Fhir.Model.Bundle.BundleType.Batch)
            {
                throw new MethodNotAllowedException(Microsoft.Health.Fhir.Api.Resources.OnlyCertainBundleTypesSupported);
            }

            await FillRequestLists(bundleResource.Entry);

            var responseBundle = new Hl7.Fhir.Model.Bundle
            {
                Type = Hl7.Fhir.Model.Bundle.BundleType.BatchResponse,
            };

            await ExecuteAllRequests(responseBundle);

            return(new BundleResponse(responseBundle.ToResourceElement()));
        }
Пример #55
0
        public async Task GivenABundle_WhenProcessed_CertainResponseHeadersArePropagatedToOuterResponse()
        {
            var bundle = new Hl7.Fhir.Model.Bundle
            {
                Type  = BundleType.Batch,
                Entry = new List <EntryComponent>
                {
                    new EntryComponent {
                        Request = new RequestComponent {
                            Method = HTTPVerb.GET, Url = "/Patient"
                        }
                    },
                    new EntryComponent {
                        Request = new RequestComponent {
                            Method = HTTPVerb.GET, Url = "/Patient"
                        }
                    },
                },
            };

            string headerName = "x-ms-request-charge";

            _router.When(r => r.RouteAsync(Arg.Any <RouteContext>()))
            .Do(info =>
            {
                info.Arg <RouteContext>().Handler = context =>
                {
                    IHeaderDictionary headers = context.Response.Headers;
                    headers.TryGetValue(headerName, out StringValues existing);
                    headers[headerName] = (existing == default(StringValues) ? 2.0 : double.Parse(existing.ToString()) + 2.0).ToString(CultureInfo.InvariantCulture);
                    return(Task.CompletedTask);
                };
            });

            var bundleRequest = new BundleRequest(bundle.ToResourceElement());
            await _bundleHandler.Handle(bundleRequest, default);

            Assert.Equal("4", _fhirRequestContext.ResponseHeaders[headerName].ToString());
        }
Пример #56
0
        public List <Diagnosis> FindDiagnosis(string patientId)
        {
            var diagnosticResults = new List <Diagnosis>();


            Hl7.Fhir.Rest.FhirClient fhirClient = FhirClientManager.CreateClientConnection(Configuration);

            fhirClient = FhirClientManager.CreateClientConnection(Configuration);

            Hl7.Fhir.Model.Bundle ReturnedSearchBundle =
                fhirClient.Search <Hl7.Fhir.Model.DiagnosticReport>(new string[] { $"patient={patientId}" });

            foreach (var resource in ReturnedSearchBundle.Entry)
            {
                var diagnosticReport = (DiagnosticReport)resource.Resource;
                foreach (var item in diagnosticReport.Contained)
                {
                    diagnosticResults.Add((Diagnosis)item);
                }
            }

            return(diagnosticResults);
        }
Пример #57
0
        public async Task GivenABundleWithAnExportPost_WhenProcessed_ThenItIsProcessedCorrectly()
        {
            var bundle = new Hl7.Fhir.Model.Bundle
            {
                Type  = BundleType.Batch,
                Entry = new List <EntryComponent>
                {
                    new EntryComponent {
                        Request = new RequestComponent {
                            Method = HTTPVerb.POST, Url = "/$export"
                        }
                    },
                },
            };
            var bundleRequest = new BundleRequest(bundle.ToResourceElement());

            BundleResponse bundleResponse = await _bundleHandler.Handle(bundleRequest, CancellationToken.None);

            var bundleResource = bundleResponse.Bundle.ToPoco <Hl7.Fhir.Model.Bundle>();

            Assert.Equal(BundleType.BatchResponse, bundleResource.Type);
            Assert.Single(bundleResource.Entry);
        }
        public async Task GivenATransactionBundleWithIdentifierReferences_WhenResolved_ThenReferencesValuesAreNotUpdated()
        {
            var observation = new Observation
            {
                Subject = new ResourceReference
                {
                    Identifier = new Identifier("https://example.com", "12345"),
                },
            };

            var bundle = new Hl7.Fhir.Model.Bundle
            {
                Entry = new List <EntryComponent>
                {
                    new EntryComponent
                    {
                        Resource = observation,
                    },
                },
            };

            var referenceIdDictionary = new Dictionary <string, (string resourceId, string resourceType)>();

            foreach (var entry in bundle.Entry)
            {
                var references = entry.Resource.GetAllChildren <ResourceReference>().ToList();

                // Asserting the conditional reference value before resolution
                Assert.Null(references.First().Reference);
                var requestUrl = (entry.Request != null) ? entry.Request.Url : null;
                await _testBaseConditionalHandler.ResolveReferencesAsync(entry.Resource, referenceIdDictionary, requestUrl, CancellationToken.None);

                // Asserting the resolved reference value after resolution
                Assert.Null(references.First().Reference);
            }
        }
Пример #59
0
        public async Task GivenAFailedTransaction_WhenProcessed_ThenNoNotificationWillBeEmitted()
        {
            var bundle = new Hl7.Fhir.Model.Bundle
            {
                Type  = BundleType.Transaction,
                Entry = new List <EntryComponent>
                {
                    new EntryComponent
                    {
                        Request = new RequestComponent
                        {
                            Method = HTTPVerb.PUT,
                            Url    = "unused1",
                        },
                        Resource = new Patient(),
                    },
                    new EntryComponent
                    {
                        Request = new RequestComponent
                        {
                            // This will fail and cause an exception to be thrown
                            Method = HTTPVerb.GET,
                            Url    = "unused2",
                        },
                    },
                },
            };

            _router.When(r => r.RouteAsync(Arg.Any <RouteContext>()))
            .Do(RouteAsyncFunction);

            var bundleRequest = new BundleRequest(bundle.ToResourceElement());
            await Assert.ThrowsAsync <FhirTransactionFailedException>(() => _bundleHandler.Handle(bundleRequest, default));

            await _mediator.DidNotReceive().Publish(Arg.Any <BundleMetricsNotification>(), Arg.Any <CancellationToken>());
        }
        private async Task ExecuteRequests(Hl7.Fhir.Model.Bundle responseBundle, Hl7.Fhir.Model.Bundle.HTTPVerb httpVerb)
        {
            foreach (RouteContext request in _requests[httpVerb])
            {
                var entryComponent = new Hl7.Fhir.Model.Bundle.EntryComponent();

                if (request.Handler != null)
                {
                    HttpContext httpContext = request.HttpContext;

                    IFhirRequestContext originalFhirRequestContext = _fhirRequestContextAccessor.FhirRequestContext;

                    request.RouteData.Values.TryGetValue(KnownActionParameterNames.ResourceType, out object resourceType);
                    var newFhirRequestContext = new FhirRequestContext(
                        httpContext.Request.Method,
                        httpContext.Request.GetDisplayUrl(),
                        originalFhirRequestContext.BaseUri.OriginalString,
                        originalFhirRequestContext.CorrelationId,
                        httpContext.Request.Headers,
                        httpContext.Response.Headers,
                        resourceType?.ToString())
                    {
                        Principal = originalFhirRequestContext.Principal,
                    };
                    _fhirRequestContextAccessor.FhirRequestContext = newFhirRequestContext;

                    _bundleHttpContextAccessor.HttpContext = httpContext;

                    await request.Handler.Invoke(httpContext);

                    httpContext.Response.Body.Seek(0, SeekOrigin.Begin);
                    string bodyContent = new StreamReader(httpContext.Response.Body).ReadToEnd();

                    ResponseHeaders responseHeaders = httpContext.Response.GetTypedHeaders();
                    entryComponent.Response = new Hl7.Fhir.Model.Bundle.ResponseComponent
                    {
                        Status       = httpContext.Response.StatusCode.ToString(),
                        Location     = responseHeaders.Location?.OriginalString,
                        Etag         = responseHeaders.ETag?.ToString(),
                        LastModified = responseHeaders.LastModified,
                    };

                    if (!string.IsNullOrWhiteSpace(bodyContent))
                    {
                        var entryComponentResource = _fhirJsonParser.Parse <Resource>(bodyContent);

                        if (entryComponentResource.ResourceType == ResourceType.OperationOutcome)
                        {
                            entryComponent.Response.Outcome = entryComponentResource;

                            if (responseBundle.Type == Hl7.Fhir.Model.Bundle.BundleType.TransactionResponse)
                            {
                                ThrowTransactionException(httpContext, (OperationOutcome)entryComponentResource);
                            }
                        }
                        else
                        {
                            entryComponent.Resource = entryComponentResource;
                        }
                    }
                    else
                    {
                        if (httpContext.Response.StatusCode == (int)HttpStatusCode.Forbidden)
                        {
                            entryComponent.Response.Outcome = CreateOperationOutcome(
                                OperationOutcome.IssueSeverity.Error,
                                OperationOutcome.IssueType.Forbidden,
                                Api.Resources.Forbidden);
                        }
                    }
                }
                else
                {
                    entryComponent.Response = new Hl7.Fhir.Model.Bundle.ResponseComponent
                    {
                        Status  = ((int)HttpStatusCode.NotFound).ToString(),
                        Outcome = CreateOperationOutcome(
                            OperationOutcome.IssueSeverity.Error,
                            OperationOutcome.IssueType.NotFound,
                            string.Format(Api.Resources.BundleNotFound, $"{request.HttpContext.Request.Path}{request.HttpContext.Request.QueryString}")),
                    };
                }

                responseBundle.Entry.Add(entryComponent);
            }
        }