public ActionResult <string> GetPatient()
        {
            FhirClient fhirClient      = _client.ConfigureBasicClient("http://fhir.hl7fundamentals.org/r4/");
            Resource   patientResource = fhirClient.Get("Patient/50672");

            return(Ok(patientResource.ToJson()));
        }
        public void TestWithParam()
        {
            var client = new FhirClient(testEndpoint);
            var res    = client.Get("ValueSet/patient-contact-relationship/$validate-code?system=http://hl7.org/fhir/patient-contact-relationship&code=emergency");

            Assert.IsNotNull(res);
        }
        public IActionResult Read(string type, string id, string version = null)
        {
            FhirClient    client = new FhirClient(url);
            String        text   = FhirSerializer.SerializeResourceToJson(client.Get(ResourceIdentity.Build(type, id, version)));
            JsonTextModel m      = new JsonTextModel(type, id, version, text);

            m.Status_ = JsonTextModel.READING;
            return(View(m));
        }
        public static bool TryGetSmartUrls(
            FhirClient fhirClient,
            out string authorizeUrl,
            out string tokenUrl
            )
        {
            authorizeUrl = string.Empty;
            tokenUrl     = string.Empty;

            CapabilityStatement capabilities = (CapabilityStatement)fhirClient.Get("metadata");

            foreach (CapabilityStatement.RestComponent restComponent in capabilities.Rest)
            {
                if (restComponent.Security == null)
                {
                    continue;
                }

                foreach (Extension securityExt in restComponent.Security.Extension)
                {
                    if (securityExt.Url != "http://fhir-registry.smarthealthit.org/StructureDefinition/oauth-uris")
                    {
                        continue;
                    }

                    if ((securityExt.Extension == null) || (securityExt.Extension.Count == 0))
                    {
                        continue;
                    }

                    foreach (Extension smartExt in securityExt.Extension)
                    {
                        switch (smartExt.Url)
                        {
                        case "authorize":
                            authorizeUrl = ((FhirUri)smartExt.Value).Value.ToString();
                            break;

                        case "token":
                            tokenUrl = ((FhirUri)smartExt.Value).Value.ToString();
                            break;
                        }
                    }
                }
            }

            if (string.IsNullOrEmpty(authorizeUrl) || string.IsNullOrEmpty(tokenUrl))
            {
                return(false);
            }

            return(true);
        }
Exemple #5
0
        private IList <PatientProfile> GetPendingPatients()
        {
            List <PatientProfile> listPending = new List <PatientProfile>();

            try
            {
                MongoDBWrapper      dbwrapper          = new MongoDBWrapper(NoIDMongoDBAddress, SparkMongoDBAddress);
                List <SessionQueue> pendingSessionList = dbwrapper.GetPendingPatients();
                FhirClient          client             = new FhirClient(sparkEndpointAddress);

                foreach (var pending in pendingSessionList)
                {
                    string         sparkAddress   = sparkEndpointAddress.ToString() + "/Patient/" + pending.SparkReference;
                    Patient        pendingPatient = (Patient)client.Get(sparkAddress);
                    PatientProfile patientProfile = new PatientProfile(pendingPatient, true);
                    patientProfile.SessionID       = pending._id;
                    patientProfile.LocalNoID       = pending.LocalReference;
                    patientProfile.NoIDStatus      = pending.ApprovalStatus;
                    patientProfile.NoIDType        = pending.PatientStatus;
                    patientProfile.CheckinDateTime = FHIRUtilities.DateTimeToFHIRString(pending.SubmitDate);

                    listPending.Add(patientProfile);
                }

                /*
                 * string gtDateFormat = "gt" + FHIRUtilities.DateToFHIRString(DateTime.UtcNow.AddDays(-2));
                 * client.PreferredFormat = ResourceFormat.Json;
                 * Uri uriTwoDays = new Uri(sparkEndpointAddress.ToString() + "/Patient?_lastUpdated=" + gtDateFormat);
                 * Bundle patientBundle = (Bundle)client.Get(uriTwoDays);
                 * foreach (Bundle.EntryComponent entry in patientBundle.Entry)
                 * {
                 *  string ptURL = entry.FullUrl.ToString().Replace("http://localhost:49911/fhir", sparkEndpointAddress.ToString());
                 *  Patient pt = (Patient)client.Get(ptURL);
                 *  if (pt.Meta.Extension.Count > 0)
                 *  {
                 *      Extension ext = pt.Meta.Extension[0];
                 *      if (ext.Value.ToString().ToLower().Contains("pending") == true)
                 *      {
                 *          PatientProfile patientProfile = new PatientProfile(pt, false);
                 *          listPending.Add(patientProfile);
                 *      }
                 *  }
                 * }
                 */
            }
            catch (Exception ex)
            {
                throw ex;
            }
            return(listPending);
        }
        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);
        }
        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);
                }
            }
        }
Exemple #8
0
        static void Main(string[] args)
        {
            //One of the test endpoints
            string adhaPDEndpoint = "https://sandbox.digitalhealth.gov.au/FhirServerSTU3-PDA/fhir";

            //New up a FHIR client to make the request
            FhirClient client = new FhirClient(adhaPDEndpoint);

            // Load certificate used to sign the client request
            X509Certificate2 signingCert = GetCertificate(
                "06fba6",
                X509FindType.FindBySerialNumber,
                StoreName.My,
                StoreLocation.CurrentUser,
                true);

            //Add the certificate to the FHIR client request
            client.OnBeforeRequest += (object sender, BeforeRequestEventArgs e) =>
            {
                e.RawRequest.ClientCertificates.Add(signingCert);
            };

            //Make the request to GET all PractitionerRole resources
            Resource responseResource = client.Get("/PractitionerRole");

            if (responseResource is Bundle bundle)
            {
                Console.WriteLine($"Recived a {bundle.TypeName} resource containing a collection of resources as follows:");
                int counter = 1;
                foreach (var entry in bundle.Entry)
                {
                    Console.WriteLine($"Resource {counter.ToString()} is a {entry.Resource.TypeName} resource.");
                    counter++;
                }
            }
            else
            {
                Console.WriteLine($"Not the response we were expecting!");
            }
            Console.ReadKey();
        }
Exemple #9
0
        public static string GetIndividualResourceFromBundle(Bundle bundle)
        {
            LogToFile("Get Individual Resource From Bundle:");

            string patientId = string.Empty;

            foreach (var entryItem in bundle.Entry)
            {
                Uri uri = new Uri(FhirClientEndPoint + entryItem.Response.Location);

                FhirClient fhirClient = new FhirClient(FhirClientEndPoint);
                var        resource   = fhirClient.Get(uri);

                var resourceXml = FhirSerializer.SerializeResourceToXml(resource);
                LogToFile(XDocument.Parse(resourceXml).ToString());

                if (resource.ResourceType == ResourceType.Patient)
                {
                    patientId = resource.Id;
                }
            }

            return(patientId);
        }
 public void TestWithParam()
 {
     var client = new FhirClient(testEndpoint);
     var res = client.Get("ValueSet/101/$validate?system=http://hl7.org/fhir/patient-contact-relationship&code=emergency");
     Assert.IsNotNull(res);
 }
        private void ProcessDiagnosticReport(DiagnosticReport report, AgsContext context)
        {
            var client = new FhirClient(this.FhirBaseUrl);

            // The result collection contains observations, including a Grouper type observation that will hold PGx results.
            // There can be >1 Grouper, so we need to do a little more investigation (peeking at the first observation type)
            // to see if it's really the one we want.
            var pgxObservations = new List <Observation>();

            foreach (var result in report.Result)
            {
                var observation = client.Read <Observation>(result.Url);
                if (!ResourceHasProfile(observation, Constants.GenomicsProfile.Grouper))
                {
                    continue;
                }

                foreach (var member in observation.HasMember)
                {
                    var memberResource = client.Read <Observation>(member.Url);
                    if (memberResource == null ||
                        !ResourceHasProfile(memberResource, PgxObservationProfiles))
                    {
                        pgxObservations.Clear();
                        break;
                    }
                    pgxObservations.Add(memberResource);
                }

                // If we have any PGx observations at this point, we must have found the right grouper.  We can stop
                // processing since we have found what we're looking for.
                if (pgxObservations.Count > 0)
                {
                    break;
                }
            }

            // Now that we're out of the loop, confirm or refute the assumption that all of our results should have
            // a PGx grouper that contains PGx results.  If we didn't find one, halt the program.
            if (pgxObservations.Count == 0)
            {
                throw new FHIRGenomicsException("No grouper containing PGx-related Observation resources was found");
            }

            // Get the patient
            Patient patient = client.Read <Patient>(report.Subject.Url);

            if (patient == null)
            {
                throw new FHIRGenomicsException("Unable to find the patient associated with this DiagnosticReport");
            }
            ProcessPatient(patient, context);

            AgsresultMessages message = new AgsresultMessages {
                Sender      = "HGSC",
                Format      = "FHIR",
                ReceivedOn  = DateTime.Now,
                ProcessedOn = DateTime.Now,
                Status      = "Processed"
            };

            context.AgsresultMessages.Add(message);

            AgsresultAttributes sample = NewResultAttribute(Constants.Attribute.Sample);

            sample.Value = string.Empty;
            message.AgsresultAttributes.Add(sample);
            context.SaveChanges();

            if (report.Status.HasValue)
            {
                AgsresultAttributes status = NewResultAttribute(Constants.Attribute.Status, sample.ResultAttributeId);
                status.Value = report.Status.Value.ToString();
                message.AgsresultAttributes.Add(status);
            }

            AgsresultAttributes createdOn = NewResultAttribute(Constants.Attribute.CreatedOn, sample.ResultAttributeId);

            createdOn.Value = DateTime.Now.ToShortDateString();
            message.AgsresultAttributes.Add(createdOn);

            var specimens = report.Specimen;

            if (specimens == null || specimens.Count == 0)
            {
                throw new FHIRGenomicsException("No specimen was found for this DiagnosticReport");
            }
            else if (specimens.Count != 1)
            {
                throw new FHIRGenomicsException(string.Format("We are expecting exactly 1 specimen for this DiagnosticReport, but found {0}", specimens.Count));
            }
            var specimen = (Specimen)client.Get(specimens[0].Url);

            AgsresultAttributes sampleType = NewResultAttribute(Constants.Attribute.SampleType, sample.ResultAttributeId);

            sampleType.Value = specimen.Type.Coding[0].Display;
            message.AgsresultAttributes.Add(sampleType);

            AgsresultAttributes accession = NewResultAttribute(Constants.Attribute.LabAccession, sample.ResultAttributeId);

            accession.Value = report.Identifier.Find(x => x.System.Equals(Constants.CodeSystem.HGSC)).Value;
            message.AgsresultAttributes.Add(accession);

            var interpreters = report.ResultsInterpreter;

            if (interpreters == null || interpreters.Count == 0)
            {
                throw new FHIRGenomicsException("We expected at least one signer (ResultsInterpreter) for this DiagnosticReport, but found 0");
            }

            foreach (var interpreter in interpreters)
            {
                AgsresultAttributes interpreterAttr = NewResultAttribute(Constants.Attribute.SignedBy, sample.ResultAttributeId);
                var role         = (PractitionerRole)client.Get(interpreter.Url);
                var practitioner = (Practitioner)client.Get(role.Practitioner.Url);
                interpreterAttr.Value = FormatName(practitioner.Name);
                message.AgsresultAttributes.Add(interpreterAttr);
            }

            var serviceRequest = (ServiceRequest)client.Get(report.BasedOn[0].Url);

            if (!ResourceHasProfile(serviceRequest, Constants.GenomicsProfile.ServiceRequest))
            {
                throw new FHIRGenomicsException("The ServiceRequest profile did not match the Genomics IG profile");
            }
            Coding indicationCoding = null;

            foreach (var reasonCode in serviceRequest.ReasonCode)
            {
                indicationCoding = reasonCode.Coding.Find(x => x.System.Equals(Constants.CodeSystem.GeneInsight));
                if (indicationCoding != null)
                {
                    break;
                }
            }
            if (indicationCoding == null)
            {
                throw new FHIRGenomicsException("Unable to find a valid reason for testing within the ServiceRequest");
            }
            AgsresultAttributes testIndication = NewResultAttribute(Constants.Attribute.TestIndication, sample.ResultAttributeId);

            testIndication.Value = indicationCoding.Display;
            message.AgsresultAttributes.Add(testIndication);

            Coding requestCoding = serviceRequest.Code.Coding.Find(x => x.System.Equals(Constants.CodeSystem.BaylorLabTestCodes));

            if (requestCoding == null)
            {
                throw new FHIRGenomicsException("Unable to find a valid code for the ServiceRequest");
            }
            AgsresultAttributes assayTest = NewResultAttribute(Constants.Attribute.AssayTestCode, sample.ResultAttributeId);

            assayTest.Value = requestCoding.Display;
            message.AgsresultAttributes.Add(assayTest);

            AgsresultAttributes observedOn = NewResultAttribute(Constants.Attribute.ObservedOn, sample.ResultAttributeId);

            observedOn.Value = serviceRequest.AuthoredOn;
            message.AgsresultAttributes.Add(observedOn);

            AgsresultAttributes receivedOn = NewResultAttribute(Constants.Attribute.ReceivedOn, sample.ResultAttributeId);

            receivedOn.Value = specimen.ReceivedTime;
            message.AgsresultAttributes.Add(receivedOn);

            AgsresultAttributes collectedOn = NewResultAttribute(Constants.Attribute.CollectionDate, sample.ResultAttributeId);

            collectedOn.Value = ((FhirDateTime)specimen.Collection.Collected).ToString();
            message.AgsresultAttributes.Add(collectedOn);

            //var tmp = client.SearchById("PlanDefinition", serviceRequest.InstantiatesCanonical.First());
            //var tmp2 = client.SearchById("PlanDefinition", serviceRequest.InstantiatesCanonical.First().Replace("urn:uuid:", ""));
            //var planDefinition = (PlanDefinition)client.Get(serviceRequest.InstantiatesCanonical.First());
            //if (planDefinition == null) {
            //	throw new FHIRGenomicsException("Failed to retrieve a PlanDefinition resource from the ServiceRequest");
            //}

            //var methodBuilder = new StringBuilder();
            //foreach (var action in planDefinition.Action) {
            //	methodBuilder.AppendLine(action.Description);
            //}

            //AgsresultAttributes method = NewResultAttribute(Constants.Attribute.MethodDescription, sample.ResultAttributeId);
            //method.Value = methodBuilder.ToString();
            //message.AgsresultAttributes.Add(method);

            context.SaveChanges();

            foreach (var pgxObservation in pgxObservations)
            {
                AgsresultAttributes pgxResult = NewResultAttribute(Constants.Attribute.PGxResult, sample.ResultAttributeId);
                pgxResult.Value = string.Empty;
                message.AgsresultAttributes.Add(pgxResult);
                context.SaveChanges();

                if (pgxObservation.DerivedFrom == null)
                {
                    throw new FHIRGenomicsException("Expected exactly one DerivedFrom entry, but none were found");
                }

                foreach (var geneDerivation in pgxObservation.DerivedFrom)
                {
                    var geneObservation = (Observation)client.Get(geneDerivation.Url);

                    AgsresultAttributes gene = NewResultAttribute(Constants.Attribute.GeneSymbol, pgxResult.ResultAttributeId);
                    gene.Value = ((CodeableConcept)geneObservation.Component[0].Value).Coding[0].Display;
                    message.AgsresultAttributes.Add(gene);

                    AgsresultAttributes diplotype = NewResultAttribute(Constants.Attribute.PGxDiplotype, pgxResult.ResultAttributeId);
                    diplotype.Value = ((CodeableConcept)geneObservation.Value).Text;
                    message.AgsresultAttributes.Add(diplotype);
                }

                AgsresultAttributes phenotype = NewResultAttribute(Constants.Attribute.PGxPhenotype, pgxResult.ResultAttributeId);
                var pgxPhenotypeConcept       = ((CodeableConcept)pgxObservation.Value);
                if (((CodeableConcept)pgxObservation.Value).Coding.Count == 0)
                {
                    phenotype.Value = pgxPhenotypeConcept.Text;
                }
                else
                {
                    phenotype.Value = pgxPhenotypeConcept.Coding[0].Display;
                }
                message.AgsresultAttributes.Add(phenotype);

                AgsresultAttributes variantInterpretation = NewResultAttribute(Constants.Attribute.VariantInterpretation, pgxResult.ResultAttributeId);
                variantInterpretation.Value = pgxObservation.GetExtensionValue <Element>(Constants.HGSCExtension.InterpretationSummaryText).ToString();
                message.AgsresultAttributes.Add(variantInterpretation);

                foreach (var pgxMed in pgxObservation.Component)
                {
                    AgsresultAttributes pgxMedication = NewResultAttribute(Constants.Attribute.PGxAssociatedMedication, pgxResult.ResultAttributeId);
                    pgxMedication.Value = ((CodeableConcept)pgxMed.Value).Coding[0].Display;
                    message.AgsresultAttributes.Add(pgxMedication);
                    context.SaveChanges();

                    AgsresultAttributes pgxRecommendation = NewResultAttribute(Constants.Attribute.PGxAssociatedRecommendation, pgxMedication.ResultAttributeId);
                    pgxRecommendation.Value = pgxMed.GetExtensionValue <RelatedArtifact>(Constants.HGSCExtension.RelatedArtifact).Url;
                    message.AgsresultAttributes.Add(pgxRecommendation);
                }
                context.SaveChanges();
            }
        }
        public void ProcessRequest(HttpContext context)
        {
            context.Response.ContentType = "text/plain";
            try
            {
                foreach (String key in context.Request.QueryString.AllKeys)
                {
                    switch (key.ToLower())
                    {
                    case "localnoid":
                        _localNoID = context.Request.QueryString[key];
                        break;

                    case "fieldname":
                        _confirmFieldName = context.Request.QueryString[key];
                        break;

                    case "confirmreponse":
                        _confirmReponse = context.Request.QueryString[key];
                        break;

                    case "computername":
                        _computerName = context.Request.QueryString[key];
                        break;

                    case "clinicarea":
                        _clinicArea = context.Request.QueryString[key];
                        break;
                    }
                }
                MongoDBWrapper dbwrapper      = new MongoDBWrapper(NoIDMongoDBAddress, SparkMongoDBAddress);
                FhirClient     client         = new FhirClient(sparkEndpointAddress);
                string         sparkReference = dbwrapper.GetSparkID(_localNoID);
                string         sparkAddress   = sparkEndpointAddress.ToString() + "/Patient/" + sparkReference;
                Patient        pendingPatient = (Patient)client.Get(sparkAddress);
                if (pendingPatient != null)
                {
                    if (_confirmFieldName == "birthdate")
                    {
                        if (pendingPatient.BirthDate != null && _confirmReponse == pendingPatient.BirthDate)
                        {
                            SessionQueue seq = Utilities.PatientToSessionQueue(pendingPatient, sparkReference, _localNoID, "return", "pending");
                            seq.SubmitDate          = DateTime.UtcNow;
                            seq._id                 = StringUtilities.SHA256(DomainName + Guid.NewGuid().ToString() + NodeSalt);
                            seq.SessionComputerName = _computerName;
                            seq.ClinicArea          = _clinicArea;
                            dbwrapper.AddPendingPatient(seq);
                            context.Response.Write("yes");
                        }
                        else
                        {
                            context.Response.Write("no");
                        }
                    }
                    else if (_confirmFieldName == "lastname")
                    {
                        //TODO: implement lastname, use metaphone or just accept exact matches?
                        context.Response.Write("Error occurred.  " + _confirmFieldName + " is not implemented yet!");
                    }
                    else if (_confirmFieldName == "firstname")
                    {
                        //TODO: implement firstname, use root or just accept exact matches?
                        context.Response.Write("Error occurred.  " + _confirmFieldName + " is not implemented yet!");
                    }
                    else if (_confirmFieldName == "failedchallenge")
                    {
                        SessionQueue seq = Utilities.PatientToSessionQueue(pendingPatient, sparkReference, _localNoID, "return**", "pending");
                        seq.SubmitDate          = DateTime.UtcNow;
                        seq._id                 = StringUtilities.SHA256(DomainName + Guid.NewGuid().ToString() + NodeSalt);
                        seq.SessionComputerName = _computerName;
                        seq.ClinicArea          = _clinicArea;
                        dbwrapper.AddPendingPatient(seq);
                        context.Response.Write("yes");
                    }
                }
            }
            catch (Exception ex)
            {
                context.Response.Write("no. Error occured for LocalNoID = " + _localNoID + ".  UpdatePendingStatus::ProcessRequest: " + ex.Message);
            }
            context.Response.End();
        }