Exemplo n.º 1
0
        public void Paging()
        {
            FhirClient client = new FhirClient(testEndpoint);

            var result = client.Search <DiagnosticReport>(count: 10);

            Assert.IsNotNull(result);
            Assert.IsTrue(result.Entries.Count <= 10);

            var firstId = result.Entries.First().Id;

            // Browse forward
            result = client.Continue(result);
            Assert.IsNotNull(result);
            var nextId = result.Entries.First().Id;

            Assert.AreNotEqual(firstId, nextId);

            // Browse to first
            result = client.Continue(result, PageDirection.First);
            Assert.IsNotNull(result);
            var prevId = result.Entries.First().Id;

            Assert.AreEqual(firstId, prevId);

            // Forward, then backwards
            // Does not work on Grahame's server yet
            //Assert.IsNotNull(client.Continue(result,PageDirection.Next));
            //result = client.Continue(result, PageDirection.Previous);
            //Assert.IsNotNull(result);
            //prevId = result.Entries.First().Id;
            //Assert.AreEqual(firstId, prevId);
        }
Exemplo n.º 2
0
        public void PagingInJson()
        {
            FhirClient client = new FhirClient(testEndpoint);

            client.PreferredFormat = ResourceFormat.Json;

            var result = client.Search <DiagnosticReport>(pageSize: 10);

            Assert.IsNotNull(result);
            Assert.IsTrue(result.Entry.Count <= 10);

            var firstId = result.Entry.First().Resource.Id;

            // Browse forward
            result = client.Continue(result);
            Assert.IsNotNull(result);
            var nextId = result.Entry.First().Resource.Id;

            Assert.AreNotEqual(firstId, nextId);

            // Browse to first
            result = client.Continue(result, PageDirection.First);
            Assert.IsNotNull(result);
            var prevId = result.Entry.First().Resource.Id;

            Assert.AreEqual(firstId, prevId);

            // Forward, then backwards
            result = client.Continue(result, PageDirection.Next);
            Assert.IsNotNull(result);
            result = client.Continue(result, PageDirection.Previous);
            Assert.IsNotNull(result);
            prevId = result.Entry.First().Resource.Id;
            Assert.AreEqual(firstId, prevId);
        }
Exemplo n.º 3
0
        public void Paging()
        {
            FhirClient client = new FhirClient(testEndpoint);

            var result = client.Search(ResourceType.DiagnosticReport, count: 10);

            Assert.IsNotNull(result);
            Assert.IsTrue(result.Entries.Count <= 10);

            var firstId = result.Entries.First().Id;

            // Browse forward
            result = client.Continue(result);
            Assert.IsNotNull(result);
            var nextId = result.Entries.First().Id;

            Assert.AreNotEqual(firstId, nextId);

            // Browse backward
            //result = client.Continue(result, PageDirection.Previous);
            result = client.Continue(result, PageDirection.First);
            Assert.IsNotNull(result);
            var prevId = result.Entries.First().Id;

            Assert.AreEqual(firstId, prevId);
        }
Exemplo n.º 4
0
        /// <summary>
        /// Get all patients of a given Practitioner
        /// </summary>
        /// <param name="practitionerId"></param>
        /// <returns> a list of Patients </returns>
        public static async Task <List <Models.Patient> > GetPatientsOfPractitioner(string practitionerId)
        {
            List <Models.Patient> patientList = new List <Models.Patient>();

            SortedSet <string> patientIdList = new SortedSet <string>();

            try
            {
                var encounterQuery = new SearchParams()
                                     .Where("participant.identifier=http://hl7.org/fhir/sid/us-npi|" + practitionerId)
                                     .Include("Encounter.participant.individual")
                                     .Include("Encounter.patient")
                                     .LimitTo(LIMIT_ENTRY);
                Bundle Result = await Client.SearchAsync <Encounter>(encounterQuery);

                // implement paging for HAPI FHIR API Bundle
                while (Result != null)
                {
                    foreach (var Entry in Result.Entry)
                    {
                        // Get patient id and add to a list
                        Encounter encounter  = (Encounter)Entry.Resource;
                        string    patientRef = encounter.Subject.Reference;
                        string    patientId  = patientRef.Split('/')[1];
                        patientIdList.Add(patientId);
                    }

                    Result = Client.Continue(Result, PageDirection.Next);
                }

                // fetch patient data from the list of patient ids
                foreach (var patientId in patientIdList)
                {
                    Bundle PatientResult = await Client.SearchByIdAsync <Hl7.Fhir.Model.Patient>(patientId);

                    if (PatientResult.Entry.Count > 0)
                    {
                        // Map the FHIR Patient object to App's Patient object
                        Hl7.Fhir.Model.Patient fhirPatient = (Hl7.Fhir.Model.Patient)PatientResult.Entry[0].Resource;
                        PatientMapper          mapper      = new PatientMapper();
                        Models.Patient         patient     = mapper.Map(fhirPatient);
                        patientList.Add(patient);
                    }
                }
            }
            catch (FhirOperationException FhirException)
            {
                System.Diagnostics.Debug.WriteLine("Fhir error message: " + FhirException.Message);
            }
            catch (Exception GeneralException)
            {
                System.Diagnostics.Debug.WriteLine("General error message: " + GeneralException.Message);
            }

            return(patientList);
        }
Exemplo n.º 5
0
        public List <QuestionnaireResponse> getQRByPatientId(long id)
        {
            Stopwatch stopwatch = new Stopwatch();

            stopwatch.Start();


            List <QuestionnaireResponse> QRs = new List <QuestionnaireResponse>();

            Bundle results = client.Search <QuestionnaireResponse>(new string[] { "subject=Patient/" + id });

            while (results != null)
            {
                foreach (var entry in results.Entry)
                {
                    QuestionnaireResponse QR = (QuestionnaireResponse)entry.Resource;
                    QRs.Add(QR);
                }

                results = client.Continue(results);
            }
            stopwatch.Stop();
            var ts = stopwatch.Elapsed;

            log.logTimeSpan("getQRByPatientId(" + id.ToString() + ")_from_server", ts, QRs.Count);

            return(QRs);
        }
        public void SearchSync_UsingSearchParams_SearchReturned()
        {
            var client = new FhirClient(_endpoint)
            {
                PreferredFormat    = ResourceFormat.Json,
                ReturnFullResource = true
            };

            var srch = new SearchParams()
                       .Where("name=Daniel")
                       .LimitTo(10)
                       .SummaryOnly()
                       .OrderBy("birthdate",
                                SortOrder.Descending);

            var result1 = client.Search <Patient>(srch);

            Assert.IsTrue(result1.Entry.Count >= 1);

            while (result1 != null)
            {
                foreach (var e in result1.Entry)
                {
                    Patient p = (Patient)e.Resource;
                    Console.WriteLine(
                        $"NAME: {p.Name[0].Given.FirstOrDefault()} {p.Name[0].Family.FirstOrDefault()}");
                }
                result1 = client.Continue(result1, PageDirection.Next);
            }

            Console.WriteLine("Test Completed");
        }
        public async Task SearchUsingPostWithCriteria_SyncContinue_SearchReturned()
        {
            var client = new FhirClient(_endpointSupportingSearchUsingPost)
            {
                PreferredFormat    = ResourceFormat.Json,
                ReturnFullResource = true
            };

            var result1 = await client.SearchUsingPostAsync <Patient>(new[] { "family=Chalmers" }, pageSize : 5);

            Assert.IsTrue(result1.Entry.Count >= 1);

            while (result1 != null)
            {
                foreach (var e in result1.Entry)
                {
                    Patient p = (Patient)e.Resource;
                    if (p.Name.Any())
                    {
                        Console.WriteLine(
                            $"NAME: {p.Name[0].Given.FirstOrDefault()} {p.Name[0].Family.FirstOrDefault()}");
                    }
                }
                result1 = client.Continue(result1, PageDirection.Next);
            }

            Console.WriteLine("Test Completed");
        }
        public async Task <NavigateBundle.Model> Handle(NavigateBundle.Query request, CancellationToken cancellationToken)
        {
            //var prayer = client.Operation(new Uri(request.Bundle), "continue");
            var bundle   = client.Continue(request.Bundle, request.Nav);
            var patients = new PatientListModel(
                new List <PatientModel>(),
                bundle.FirstLink?.ToString() != null ? bundle.FirstLink.ToString() : "",
                bundle.LastLink?.ToString() != null ? bundle.LastLink.ToString() : "",
                bundle.NextLink?.ToString() != null ? bundle.NextLink.ToString() : "",
                bundle.PreviousLink?.ToString() != null ? bundle.PreviousLink.ToString() : "",
                bundle.Total ?? 0);

            foreach (var e in bundle.Entry)
            {
                Hl7.Fhir.Model.Patient p = (Hl7.Fhir.Model.Patient)e.Resource;
                patients.Patients.Add(
                    new PatientModel(
                        p.Id, string.Join(" ", p.Name.FirstOrDefault()
                                          .Given), string.Join(" ", p.Name.FirstOrDefault().Family)));
            }


            return(new NavigateBundle.Model()
            {
                Bundle = bundle, Payload = patients
            });
        }
Exemplo n.º 9
0
        public async Task <ActionResult <IEnumerable <CustomPatient> > > GetPatientsAsync()
        {
            List <CustomPatient> patientList = new List <CustomPatient>();
            var filterParams = new SearchParams()
                               .Where("identifier=UPTValue");

            Bundle result = await _client.SearchAsync <Patient>(filterParams);

            while (result != null)
            {
                foreach (var item in result.Entry)
                {
                    var patientRetrieved = (Patient)item.Resource;
                    var customPatient    = new CustomPatient()
                    {
                        Name       = patientRetrieved.Name.FirstOrDefault().Family,
                        FirstNames = patientRetrieved.Name.FirstOrDefault().Given.ToList(),
                        Id         = patientRetrieved.Id
                    };
                    patientList.Add(customPatient);
                }
                result = _client.Continue(result, PageDirection.Next);
            }

            return(Ok(patientList));
        }
Exemplo n.º 10
0
        public List <Patient> getAllPatients()
        {
            Stopwatch stopwatch = new Stopwatch();

            stopwatch.Start();

            List <Patient> patients = new List <Patient>();

            Bundle results = client.Search <Patient>(); //todo error handling

            while (results != null)
            {
                foreach (var entry in results.Entry)
                {
                    Patient pat = (Patient)entry.Resource;
                    patients.Add(pat);
                }
                results = client.Continue(results);
            }

            stopwatch.Stop();
            var ts = stopwatch.Elapsed;

            log.logTimeSpan("getAllPatients()_from_server", ts, patients.Count);

            return(patients);
        }
Exemplo n.º 11
0
        public async Task <ActionResult <IEnumerable <CustomDiagnostic> > > GetDiagnosticsAsync()
        {
            List <CustomDiagnostic> diagnostics = new List <CustomDiagnostic>();
            var filterParams = new SearchParams()
                               .Where("identifier=UPTValue");

            Bundle result = await _client.SearchAsync <DiagnosticReport>(filterParams);

            while (result != null)
            {
                foreach (var item in result.Entry)
                {
                    var diagnosticReceived = (DiagnosticReport)item.Resource;
                    var customDiagnostic   = new CustomDiagnostic
                    {
                        Id              = diagnosticReceived.Id,
                        PatientRef      = diagnosticReceived.Performer.FirstOrDefault().ToString(),
                        PractitionerRef = diagnosticReceived.Subject.ToString(),
                        IssueDate       = diagnosticReceived.Issued.Value
                    };
                    diagnostics.Add(customDiagnostic);
                }
                result = _client.Continue(result, PageDirection.Next);
            }

            return(Ok(diagnostics));
        }
Exemplo n.º 12
0
        public ActionResult HistoryObservation(string id, string type, string patientID)
        {
            bool   status  = false;
            string Message = "";
            List <HistoryObservation> fullVersion = new List <HistoryObservation>();

            //SPRAWDZENIE MODELU
            if (ModelState.IsValid)
            {
                //PODŁĄCZENIE KLIENTA
                var client = new FhirClient("http://localhost:8080/baseR4");
                client.PreferredFormat = ResourceFormat.Json;
                //WYSZUKANIE HISTORII
                Bundle history = client.History("Observation/" + id);

                while (history != null)
                {
                    foreach (var e in history.Entry)
                    {
                        if (e.Resource.TypeName == "Observation")
                        {
                            //POBRANIE POTRZBNYCH DANYCH
                            HistoryObservation observation = new Models.HistoryObservation();
                            observation.LastUpdate = e.Resource.Meta.LastUpdated;
                            observation.VersionId  = int.Parse(e.Resource.VersionId);

                            Observation obs = (Observation)e.Resource;
                            observation.Reason = obs.Code.Text;
                            observation.Status = obs.Status;

                            fullVersion.Add(observation);
                        }
                    }
                    history = client.Continue(history, PageDirection.Next);
                }
                status = true;
            }
            else
            {
                Message = "You haven't got right model";
            }

            for (int i = 0; i < fullVersion.Count - 1; i++)
            {
                if (fullVersion[i].Reason != fullVersion[i + 1].Reason)
                {
                    fullVersion[i].color[0] = "green";
                }
                if (fullVersion[i].Status != fullVersion[i + 1].Status)
                {
                    fullVersion[i].color[1] = "green";
                }
            }

            ViewBag.ID      = patientID;
            ViewBag.Status  = status;
            ViewBag.Message = Message;
            return(View(fullVersion));
        }
        public List <Observation> getAllObservationsByPatId(long id)
        {
            List <Observation> newObservations = new List <Observation>();
            Bundle             results         = client.Search <Observation>(new string[] { "subject=Patient/" + id });

            while (results != null)
            {
                foreach (var entry in results.Entry)
                {
                    Observation obs = (Observation)entry.Resource;
                    newObservations.Add(obs);
                }

                results = client.Continue(results);
            }
            return(newObservations);
        }
Exemplo n.º 14
0
        /// <summary>
        /// To get patient Allergies with the help of global Patient object
        /// </summary>
        public void getPatientAllergies()
        {
            try
            {
                SearchParams searchParams = new SearchParams();

                searchParams.Add("patient", Generalinformation.Id);

                searchParams.Add("_count", "20");

                Bundle bd = _fc.Search <AllergyIntolerance>(searchParams);

                bool isCountOver = false;

                while (!isCountOver)
                {
                    if (bd.NextLink == null)
                    {
                        isCountOver = true;
                    }

                    foreach (Bundle.EntryComponent et in bd.Entry)
                    {
                        if (et.Resource.ResourceType == ResourceType.AllergyIntolerance)
                        {
                            Allergies.Add((AllergyIntolerance)et.Resource);
                        }
                    }

                    bd = _fc.Continue(bd);
                }
            }
            catch (FhirOperationException foe)
            {
                isExceptionEncountered = true;
                ExceptionIssues        = foe.Outcome.Issue;
            }
            catch (Exception ex)
            {
                isExceptionEncountered = true;
                OperationOutcome.IssueComponent ic = new OperationOutcome.IssueComponent();
                ic.Diagnostics = ex.Message;
                ExceptionIssues.Add(ic);
            }
        }
        public async Task <NavigateBundle.Model> Handle(NavigateBundle.Query request, CancellationToken cancellationToken)
        {
            var bundle = client.Continue(request.Bundle, request.Nav);

            return(new NavigateBundle.Model()
            {
                Bundle = bundle
            });
        }
        public ActionResult ShowResourceVersion(string rId, string id)
        {
            var conn = new FhirClient("http://localhost:8080/baseR4");

            conn.PreferredFormat = ResourceFormat.Json;

            Patient patient = conn.Read <Patient>("Patient/" + id);

            UriBuilder uriBuilder = new UriBuilder("http://localhost:8080/baseR4");

            uriBuilder.Path = "Patient/" + patient.Id;
            Resource resultResource = conn.InstanceOperation(uriBuilder.Uri, "everything");
            var      resourceList   = new List <Details>();

            if (resultResource is Bundle)
            {
                Bundle resultBundle = resultResource as Bundle;
                while (resultBundle != null)
                {
                    foreach (var i in resultBundle.Entry)
                    {
                        Details element = new Details();
                        switch (i.Resource.TypeName)
                        {
                        case "Observation":
                            Observation observation = (Observation)i.Resource;
                            if (observation.Id == rId)
                            {
                                element.id           = observation.Id;
                                element.resourceName = "Observation";
                                element.reason       = observation.Code.Text;
                                element.version      = observation.Meta.VersionId;
                                int versions = int.Parse(element.version);
                                for (int j = 1; j <= versions; j++)
                                {
                                    Details    vPatient    = new Details();
                                    UriBuilder uriBuilder1 = new UriBuilder("http://localhost:8080/baseR4");
                                    uriBuilder1.Path = "Observation/" + element.id + "/_history/" + j;
                                    Observation resultResource1 = conn.Read <Observation>(uriBuilder1.Uri);
                                    vPatient.id      = resultResource1.Id;
                                    vPatient.reason  = resultResource1.Code.Text;
                                    vPatient.date    = Convert.ToDateTime(resultResource1.Effective.ToString());
                                    vPatient.version = resultResource1.Meta.VersionId;
                                    vPatient.modDate = Convert.ToDateTime(resultResource1.Meta.LastUpdated.ToString());
                                    resourceList.Add(vPatient);
                                }
                            }
                            break;
                        }
                    }
                    resultBundle = conn.Continue(resultBundle, PageDirection.Next);
                }
            }


            return(View(resourceList));
        }
        /**
         * Index Finished.
         */
        public ViewResult Index(string sortOrder, string searchString)
        {
            var patientList = new List <Patient>();

            var conn = new FhirClient("http://localhost:8080/baseR4");

            conn.PreferredFormat = ResourceFormat.Json;

            Bundle result = conn.Search <Patient>();

            while (result != null)
            {
                foreach (var i in result.Entry)
                {
                    if (i.Resource.TypeName == "Patient")
                    {
                        Patient patient = (Patient)i.Resource;
                        patientList.Add(patient);
                    }
                }
                result = conn.Continue(result, PageDirection.Next);
            }

            // Search case
            if (!String.IsNullOrEmpty(searchString))
            {
                patientList = patientList.Where(s => s.Name[0].Family.ToLower().Contains(searchString.ToLower()))
                              .ToList();
            }

            // Sort case
            ViewBag.SurnameSortParam   = String.IsNullOrEmpty(sortOrder) ? "surname_desc" : "";
            ViewBag.FirstNameSortParam = sortOrder == "firstname" ? "firstname_desc" : "firstname";

            switch (sortOrder)
            {
            case "surname_desc":
                patientList = patientList.OrderByDescending(s => s.Name[0].Family).ToList();
                break;

            case "firstname":
                patientList = patientList.OrderBy(s => s.Name[0].Given.ToList().ToString()).ToList();
                break;

            case "firstname_desc":
                patientList = patientList.OrderByDescending(s => s.Name[0].Given.ToList().ToString()).ToList();
                break;

            default:
                patientList = patientList.OrderBy(s => s.Name[0].Family).ToList();
                break;
            }

            return(View(patientList.ToList()));
        }
Exemplo n.º 18
0
        /// <summary>
        ///  Search for Resources of a certain type that match the given criteria
        /// </summary>
        /// <param name="type">The type of resource to search for</param>
        /// <param name="q">Optional. The search parameters to filter the resources on. Each
        /// given string is a combined key/value pair (separated by '=')</param>
        /// <param name="includes">Optional. A list of include paths</param>
        /// <param name="pageSize">Optional. Asks server to limit the number of entries per page returned</param>
        /// <param name="summary">>Optional. Whether to include only return a summary of the resources in the Bundle</param>
        /// <returns>A List with all resource Ids found by the search, or an empty List if none were found.</returns>
        public List <String> FilteredGetIds(string type, int page = 1, string[] q = null, string[] includes = null, int?pageSize = null, SummaryType?summary = null)
        {
            List <String> result = new List <String>();

            if (string.IsNullOrWhiteSpace(type))
            {
                return(result);
            }
            var bundle = _client.Search(type);

            while (bundle != null)
            {
                foreach (var entry in bundle.Entry)
                {
                    result.Add(entry.Resource.Id);
                }
                bundle = _client.Continue(bundle);
            }
            return(result);
        }
 public async Task <Bundle> PatientsAsync(Action <Exception> errorAction, Bundle existingBundle = null)
 {
     return(await Task.Run(() =>
     {
         try
         {
             if (existingBundle != null)
             {
                 return client.Continue(existingBundle);
             }
             else
             {
                 return client.Search <Patient>();
             }
         } catch (Exception e)
         {
             DispatcherHelper.CheckBeginInvokeOnUI(() => errorAction(e));
             return null;
         }
     }));
 }
Exemplo n.º 20
0
        public ViewResult Index(string sortOrder, string currentFilter, string searchString, int?page)
        {
            var myPatients = new List <Patient>();

            //ŁĄCZENIE Z SERWEREM
            var client = new FhirClient("http://localhost:8080/baseR4");        //second parameter - check standard version

            client.PreferredFormat = ResourceFormat.Json;

            //POBIERANIE PACJENTÓW
            Bundle result = client.Search <Patient>();

            while (result != null)
            {
                foreach (var e in result.Entry)
                {
                    if (e.Resource.TypeName == "Patient")
                    {
                        Patient p = (Patient)e.Resource;
                        myPatients.Add(p);
                    }
                }
                result = client.Continue(result, PageDirection.Next);
            }

            //WYSZUKIWANIE PO NAZWISKU
            ViewBag.CurrentSort = sortOrder;
            if (searchString != null)
            {
                page = 1;
            }
            else
            {
                searchString = currentFilter;
            }
            ViewBag.CurrentFilter = searchString;
            if (!String.IsNullOrEmpty(searchString))
            {
                myPatients = myPatients.FindAll(s => s.Name[0].Family.ToLower().Contains(searchString.ToLower()));
            }

            //STRONICOWANIE
            int pageSize   = 10;
            int pageNumber = (page ?? 1);

            return(View(myPatients.ToPagedList(pageNumber, pageSize)));
        }
        private void ProcessDiagnosticReports(AgsContext context)
        {
            var client  = new FhirClient(this.FhirBaseUrl);
            var reports = (Bundle)client.Get("DiagnosticReport");

            int reportCounter = 0;

            while (reports != null)
            {
                if (reports.Entry == null || reports.Entry.Count == 0)
                {
                    Console.WriteLine("Null or empty list of DiagnosticReport resources returned by FHIR server");
                    return;
                }

                Console.WriteLine("Processing bundle of {0} reports", reports.Entry.Count);

                foreach (var entry in reports.Entry)
                {
                    var resource       = entry.Resource;
                    var reportResource = resource as DiagnosticReport;
                    if (resource.ResourceType != ResourceType.DiagnosticReport)
                    {
                        throw new FHIRGenomicsException(string.Format("We received a {0} resource where we expected a DiagnosticReport", resource.ResourceType));
                    }
                    else if (reportResource == null)
                    {
                        throw new FHIRGenomicsException(string.Format("Unable to cast resource ID {0} as a DiagnosticReport", resource.Id));
                    }

                    if (!ResourceHasProfile(reportResource, Constants.GenomicsProfile.DiagnosticReport))
                    {
                        throw new FHIRGenomicsException("The expected FHIR profile was not specified for the DiagnosticReport");
                    }
                    ProcessDiagnosticReport(reportResource, context);
                    reportCounter++;
                }

                reports = (Bundle)client.Continue(reports);
            }

            context.SaveChanges();
            Console.WriteLine("Processed {0} reports", reportCounter);
        }
Exemplo n.º 22
0
        public void DiscoverExtensionsOnFhirServer()
        {
            string        sourcePath    = Configuration.GetValue <string>("sourcePath");
            string        outputPath    = Configuration.GetValue <string>("outputPath");
            string        canonicalBase = Configuration.GetValue <string>("defaults:baseurl");
            string        publisher     = Configuration.GetValue <string>("defaults:publisher");
            ScanResources processor     = new ScanResources(sourcePath, outputPath,
                                                            canonicalBase, publisher);

            var settings = Configuration.GetSection("scanserver").Get <ScanServerSettings>();
            var server   = new FhirClient(settings.baseurl, new FhirClientSettings()
            {
                VerifyFhirVersion = false
            });

            int createdResources = 0;

            foreach (var query in settings.queries)
            {
                try
                {
                    Bundle batch = server.Get(server.Endpoint + query) as Bundle;
                    do
                    {
                        foreach (var entry in batch.Entry.Select(e => e.Resource))
                        {
                            if (entry != null)
                            {
                                System.Diagnostics.Trace.WriteLine($"  -->{entry.TypeName}/{entry.Id}");
                                processor.ScanForExtensions(null, entry.ToTypedElement(), null);
                                createdResources++;
                            }
                        }
                        // if (batch.NextLink == null)
                        break;
                        batch = server.Continue(batch);
                    }while (true);
                }
                catch (FhirOperationException ex)
                {
                    DebugDumpOutputXml(ex.Outcome);
                }
            }
        }
Exemplo n.º 23
0
        public static void SearchThenAssertResult(FhirClient client, DomainResource resource, SearchParams searchParams)
        {
            Bundle.EntryComponent entry = null;

            // Retry because depending on how the server is implemented, there could be a slight lag between when an object is created and when it's indexed and available for search.
            int retryCount = 0;

            while (retryCount < 5)
            {
                var bundle = client.Search(searchParams, resource.GetType().Name);

                Assert.NotNull(bundle);

                while (bundle.NextLink != null)
                {
                    // Find the resource from the bundle
                    entry = bundle.FindEntry($"{client.Endpoint}{resource.GetType().Name}/{resource.Id}").FirstOrDefault();

                    if (entry != null)
                    {
                        break;
                    }

                    bundle = client.Continue(bundle);
                }

                if (entry == null)
                {
                    // Find the resource from the bundle
                    entry = bundle.FindEntry($"{client.Endpoint}{resource.GetType().Name}/{resource.Id}").FirstOrDefault();
                }

                if (entry != null)
                {
                    break;
                }

                Thread.Sleep(2000);
                retryCount++;
            }

            Assert.NotNull(entry);
            AssertHelper.CheckStatusCode(HttpStatusCode.OK, client.LastResult.Status);
        }
Exemplo n.º 24
0
        private async Task <List <Organization> > GetOrganizationsFromFHIRAsync()
        {
            List <Organization> organizations = new List <Organization>();
            var result = await _client.SearchAsync <Organization>().ConfigureAwait(false);

            while (result != null)
            {
                if (result.Entry != null)
                {
                    foreach (var e in result.Entry)
                    {
                        organizations.Add((Organization)e.Resource);
                    }
                }
                // get the next page of results
                result = _client.Continue(result);
            }
            return(organizations);
        }
Exemplo n.º 25
0
        public static async Task <IActionResult> Run([HttpTrigger(AuthorizationLevel.Function, "get", "post", Route = null)] HttpRequest req)
        {
            var authority     = Environment.GetEnvironmentVariable("FHIR_Authority", EnvironmentVariableTarget.Process);
            var audience      = Environment.GetEnvironmentVariable("FHIR_Audience", EnvironmentVariableTarget.Process);
            var clientId      = Environment.GetEnvironmentVariable("FHIR_ClientId");
            var clientSecret  = Environment.GetEnvironmentVariable("FHIR_ClientSecret");
            var fhirServerUrl = new Uri(Environment.GetEnvironmentVariable("FHIR_URL"));

            var authContext      = new AuthenticationContext(authority);
            var clientCredential = new ClientCredential(clientId, clientSecret);
            var authResult       = authContext.AcquireTokenAsync(audience, clientCredential).Result;
            var client           = new FhirClient(fhirServerUrl)
            {
                PreferredFormat = ResourceFormat.Json, UseFormatParam = true,
            };

            client.OnBeforeRequest += (object sender, BeforeRequestEventArgs e) =>
            {
                e.RawRequest.Headers["Authorization"] = $"Bearer {authResult.AccessToken}";
            };
            var patients = client.Search <Patient>();

            var patientList = new List <Patient>();

            while (patients != null)
            {
                foreach (var e in patients.Entry)
                {
                    patientList.Add((Patient)e.Resource);
                }
                patients = client.Continue(patients, PageDirection.Next);
            }

            foreach (var patient in patientList)
            {
                var rawAddress = patient.Extension.FirstOrDefault(p => p.Url == "address");
                if (rawAddress != null)
                {
                    PostScreenTrigger(rawAddress.Value.ToString());
                }
            }
            return(new OkResult());
        }
Exemplo n.º 26
0
        public async virtual Task <List <Patient> > Search(string term = null)
        {
            if (!string.IsNullOrEmpty(term))
            {
                term = term.ToLower();
                term = term.Trim();

                // var trans = new TransactionBuilder(client.Endpoint);
                // trans = trans.Search(q, "MedicationRequest").Search(t, "MedicationStatement");
                // //var result = await _client.SearchAsync<MedicationRequest>(q);
                // var tResult = _client.TransactionAsync(trans.ToBundle());

                // var result =
                //     PatientList
                //     .Where(x =>
                //         x.GivenNames.Select(n=> n.ToLower()).Contains(term) ||
                //         x.LastName.ToLower().Contains(term)
                //     )
                //     .ToList();

                var queryNames = new SearchParams()
                                 .Where($"given={term}")
                                 .Where($"last={term}")
                                 .LimitTo(50);
                var searchCall = await client.SearchAsync <Patient>(queryNames);


                List <Patient> patients = new List <Patient>();
                while (searchCall != null)
                {
                    foreach (var e in searchCall.Entry)
                    {
                        Patient p = (Patient)e.Resource;
                        patients.Add(p);
                    }
                    searchCall = client.Continue(searchCall, PageDirection.Next);
                }
                return(patients);
            }

            return(PatientList);
        }
Exemplo n.º 27
0
        private System.Collections.Generic.List <Observation> GetPatientObservations(Patient p)
        {
            System.Collections.Generic.List <Observation> result = new System.Collections.Generic.List <Observation>();
            var q = new Query()
                    .For("Patient")
                    .Where($"subject:exact={p.ResourceIdentity}")
                    .SummaryOnly().Include("Patient.managingOrganization")
                    .LimitTo(20);
            var s = client.Search(q);

            while (s != null)
            {
                foreach (var r in s.GetResources())
                {
                    result.Add((Observation)r);
                }
                s = client.Continue(s);
            }
            return(result);
        }
Exemplo n.º 28
0
        private void btnStart_Click(object sender, EventArgs e)
        {
            // Choose your preferred FHIR server or add your own
            // More at http://wiki.hl7.org/index.php?title=Publicly_Available_FHIR_Servers_for_testing

            //var client = new FhirClient("http://fhir2.healthintersections.com.au/open");
            var client = new FhirClient("http://spark.furore.com/fhir");

            //var client = new FhirClient("http://fhirtest.uhn.ca/baseDstu2");
            //var client = new FhirClient("https://fhir-open-api-dstu2.smarthealthit.org/");

            try
            {
                var q = new SearchParams().Where("name=pete");
                //var q = new SearchParams().Where("name=pete").Where("birthdate=1974-12-25");

                var results = client.Search <Patient>(q);

                txtDisplay.Text = "";

                while (results != null)
                {
                    if (results.Total == 0)
                    {
                        txtDisplay.Text = "No results found";
                    }

                    foreach (var entry in results.Entry)
                    {
                        txtDisplay.Text += "Found patient with id " + entry.Resource.Id + Environment.NewLine;
                    }

                    // get the next page of results
                    results = client.Continue(results);
                }
            }
            catch (Exception err)
            {
                txtError.Lines = new string[] { "An error has occurred:", err.Message };
            }
        }
Exemplo n.º 29
0
        public async Task SearchUsingPostMultiple_UsingSearchParams_SearchReturned()
        {
            var client = new FhirClient(_endpointSupportingSearchUsingPost)
            {
                PreferredFormat    = ResourceFormat.Json,
                ReturnFullResource = true
            };

            var srchParams = new SearchParams()
                             .Where("name=Peter")
                             .LimitTo(10)
                             .SummaryOnly()
                             .OrderBy("birthdate",
                                      SortOrder.Descending);

            var task1 = client.SearchUsingPostAsync <Patient>(srchParams);
            var task2 = client.SearchUsingPostAsync <Patient>(srchParams);
            var task3 = client.SearchUsingPostAsync <Patient>(srchParams);

            await Task.WhenAll(task1, task2, task3);

            var result1 = task1.Result;

            Assert.IsTrue(result1.Entry.Count >= 1);

            while (result1 != null)
            {
                foreach (var e in result1.Entry)
                {
                    Patient p = (Patient)e.Resource;
                    if (p.Name.Any())
                    {
                        Console.WriteLine(
                            $"NAME: {p.Name[0].Given.FirstOrDefault()} {p.Name[0].Family.FirstOrDefault()}");
                    }
                }
                result1 = client.Continue(result1, PageDirection.Next);
            }

            Console.WriteLine("Test Completed");
        }
Exemplo n.º 30
0
        private static List <string> GetPatientsID(FhirClient client)
        {
            List <string> patId  = new List <string>();
            var           result = client.Search <Patient>();

            while (result != null)
            {
                if (result.Entry != null)
                {
                    foreach (var pat in result.Entry)
                    {
                        patId.Add(pat.Resource.Id);
                    }
                }

                result = client.Continue(result);
            }


            return(patId);
        }
Exemplo n.º 31
0
        private void btnStart_Click(object sender, EventArgs e)
        {
            // Choose your preferred FHIR server or add your own
            // More at http://wiki.hl7.org/index.php?title=Publicly_Available_FHIR_Servers_for_testing

            //var client = new FhirClient("http://fhir2.healthintersections.com.au/open");
            var client = new FhirClient("http://spark.furore.com/fhir");
            //var client = new FhirClient("http://fhirtest.uhn.ca/baseDstu2");
            //var client = new FhirClient("https://fhir-open-api-dstu2.smarthealthit.org/");

            try
            {
                var q = new SearchParams().Where("name=pete");
                //var q = new SearchParams().Where("name=pete").Where("birthdate=1974-12-25");

                var results = client.Search<Patient>(q);

                txtDisplay.Text = "";

                while (results != null)
                {
                    if (results.Total == 0) txtDisplay.Text = "No results found";

                    foreach (var entry in results.Entry)
                    {
                        txtDisplay.Text += "Found patient with id " + entry.Resource.Id + Environment.NewLine;
                    }

                    // get the next page of results
                    results = client.Continue(results);
                }
            }
            catch (Exception err)
            {
                txtError.Lines = new string[] { "An error has occurred:", err.Message };
            }
        }
Exemplo n.º 32
0
        public void PagingInJson()
        {
            FhirClient client = new FhirClient(testEndpoint);
            client.PreferredFormat = ResourceFormat.Json;

            var result = client.Search<DiagnosticReport>(pageSize: 10);
            Assert.IsNotNull(result);
            Assert.IsTrue(result.Entry.Count <= 10);

            var firstId = result.Entry.First().Resource.Id;

            // Browse forward
            result = client.Continue(result);
            Assert.IsNotNull(result);
            var nextId = result.Entry.First().Resource.Id;
            Assert.AreNotEqual(firstId, nextId);

            // Browse to first
            result = client.Continue(result, PageDirection.First);
            Assert.IsNotNull(result);
            var prevId = result.Entry.First().Resource.Id;
            Assert.AreEqual(firstId, prevId);

            // Forward, then backwards
            result = client.Continue(result, PageDirection.Next);
            Assert.IsNotNull(result);
            result = client.Continue(result, PageDirection.Previous);
            Assert.IsNotNull(result);
            prevId = result.Entry.First().Resource.Id;
            Assert.AreEqual(firstId, prevId);
        }
Exemplo n.º 33
0
        public void Paging()
        {
            FhirClient client = new FhirClient(testEndpoint);

            var result = client.Search(ResourceType.DiagnosticReport, count: 10);
            Assert.IsNotNull(result);
            Assert.IsTrue(result.Entries.Count <= 10);

            var firstId = result.Entries.First().Id;

            // Browse forward
            result = client.Continue(result);
            Assert.IsNotNull(result);
            var nextId = result.Entries.First().Id;
            Assert.AreNotEqual(firstId, nextId);

            // Browse backward
            //result = client.Continue(result, PageDirection.Previous);
            result = client.Continue(result, PageDirection.First);
            Assert.IsNotNull(result);
            var prevId = result.Entries.First().Id;
            Assert.AreEqual(firstId, prevId);
        }