public async Task InitializeAsync()
        {
            // Create various resources.
            Device = await FhirClient.CreateAsync(Samples.GetJsonSample <Device>("Device-d1"));

            Patient = await FhirClient.CreateAsync(Samples.GetJsonSample <Patient>("Patient-f001"));

            string patientReference = $"Patient/{Patient.Id}";

            Observation observationToCreate = Samples.GetJsonSample <Observation>("Observation-For-Patient-f001");

            observationToCreate.Subject.Reference = patientReference;

            observationToCreate.Device = new ResourceReference($"Device/{Device.Id}");

            Observation = await FhirClient.CreateAsync(observationToCreate);

            Encounter encounterToCreate = Samples.GetJsonSample <Encounter>("Encounter-For-Patient-f001");

            encounterToCreate.Subject.Reference = patientReference;

            Encounter = await FhirClient.CreateAsync(encounterToCreate);

            Condition conditionToCreate = Samples.GetJsonSample <Condition>("Condition-For-Patient-f001");

            conditionToCreate.Subject.Reference = patientReference;

            Condition = await FhirClient.CreateAsync(conditionToCreate);
        }
예제 #2
0
            public ClassFixture(DataStore dataStore, Format format)
                : base(dataStore, format)
            {
                Tag = Guid.NewGuid().ToString();

                // Construct an observation pointing to a patient and a diagnostic report pointing to the observation and the patient

                Patient smithPatient = FhirClient.CreateAsync(new Patient {
                    Name = new List <HumanName> {
                        new HumanName {
                            Family = "Smith"
                        }
                    }
                }).Result.Resource;
                Patient trumanPatient = FhirClient.CreateAsync(new Patient {
                    Name = new List <HumanName> {
                        new HumanName {
                            Family = "Truman"
                        }
                    }
                }).Result.Resource;

                var smithObservation  = CreateObservation(smithPatient);
                var trumanObservation = CreateObservation(trumanPatient);

                SmithDiagnosticReport = CreateDiagnosticReport(smithPatient, smithObservation);

                TrumanDiagnosticReport = CreateDiagnosticReport(trumanPatient, trumanObservation);

                DiagnosticReport CreateDiagnosticReport(Patient patient, Observation observation)
                {
                    return(FhirClient.CreateAsync(
                               new DiagnosticReport
                    {
                        Meta = new Meta {
                            Tag = new List <Coding> {
                                new Coding("testTag", Tag)
                            }
                        },
                        Status = DiagnosticReport.DiagnosticReportStatus.Final,
                        Code = new CodeableConcept("http://snomed.info/sct", "429858000"),
                        Subject = new ResourceReference($"Patient/{patient.Id}"),
                        Result = new List <ResourceReference> {
                            new ResourceReference($"Observation/{observation.Id}")
                        },
                    }).Result.Resource);
                }

                Observation CreateObservation(Patient patient)
                {
                    return(FhirClient.CreateAsync(
                               new Observation()
                    {
                        Status = ObservationStatus.Final,
                        Code = new CodeableConcept("http://snomed.info/sct", "429858000"),
                        Subject = new ResourceReference($"Patient/{patient.Id}"),
                    }).Result.Resource);
                }
            }
예제 #3
0
        public async Task GivenAResource_WhenCreated_ThenCorrectNumberOfMetricNotificationsShouldBeEmitted()
        {
            _metricHandler?.ResetCount();

            await ExecuteAndValidate(
                () => _client.CreateAsync(Samples.GetDefaultObservation().ToPoco()),
                (type : typeof(ApiResponseNotification), count : 1),
                (type : typeof(CosmosStorageRequestMetricsNotification), count : 1));
        }
        protected static async Task <TResource> CreateResourceByIdentityAsync <TResource>(FhirClient client, Model.Identifier identifier, Action <TResource, Model.Identifier> propertySetter)
            where TResource : Model.Resource, new()
        {
            EnsureArg.IsNotNull(client, nameof(client));
            EnsureArg.IsNotNull(identifier, nameof(identifier));
            var resource = new TResource();

            propertySetter?.Invoke(resource, identifier);

            return(await client.CreateAsync <TResource>(resource).ConfigureAwait(false));
        }
        /// <summary>
        /// Create a new Patint
        /// </summary>
        /// <param name="patient"></param>
        /// <returns>New Patient</returns>
        public async Task <Patient> CreatePatientAsync(PatientDto patient)
        {
            Patient result     = null;
            var     newPatient = _patientDtoToPatientConverter.Convert(patient);
            // Before adding the patient to the server, let's validate it first
            bool success = ValidatePatient(newPatient);

            if (success)
            {
                result = await _fhirClient.CreateAsync(newPatient).ConfigureAwait(false);
            }
            return(result);
        }
예제 #6
0
        public virtual async Task <string> SaveObservationAsync(ILookupTemplate <IFhirTemplate> config, IObservationGroup observationGroup, IDictionary <ResourceType, string> ids)
        {
            var identifier = GenerateObservationIdentifier(observationGroup, ids);
            var cacheKey   = $"{identifier.System}|{identifier.Value}";

            if (!_observationCache.TryGetValue(cacheKey, out Model.Observation existingObservation))
            {
                existingObservation = await GetObservationFromServerAsync(identifier).ConfigureAwait(false);
            }

            Model.Observation result;
            if (existingObservation == null)
            {
                var newObservation = GenerateObservation(config, observationGroup, identifier, ids);
                result = await _client.CreateAsync(newObservation).ConfigureAwait(false);

                _logger.LogMetric(IomtMetrics.FhirResourceSaved(ResourceType.Observation, ResourceOperation.Created), 1);
            }
            else
            {
                var policyResult = await Policy <Model.Observation>
                                   .Handle <FhirOperationException>(ex => ex.Status == System.Net.HttpStatusCode.Conflict || ex.Status == System.Net.HttpStatusCode.PreconditionFailed)
                                   .RetryAsync(2, async(polyRes, attempt) =>
                {
                    existingObservation = await GetObservationFromServerAsync(identifier).ConfigureAwait(false);
                })
                                   .ExecuteAndCaptureAsync(async() =>
                {
                    var mergedObservation = MergeObservation(config, existingObservation, observationGroup);
                    return(await _client.UpdateAsync(mergedObservation, versionAware: true).ConfigureAwait(false));
                }).ConfigureAwait(false);

                var exception = policyResult.FinalException;

                if (exception != null)
                {
                    throw exception;
                }

                result = policyResult.Result;
                _logger.LogMetric(IomtMetrics.FhirResourceSaved(ResourceType.Observation, ResourceOperation.Updated), 1);
            }

            _observationCache.CreateEntry(cacheKey)
            .SetAbsoluteExpiration(DateTimeOffset.UtcNow.AddHours(1))
            .SetSize(1)
            .SetValue(result)
            .Dispose();

            return(result.Id);
        }
예제 #7
0
        public void PatientCreationUpdateDeletion()
        {
            Patient patient = null !;

            "When creating a patient resource".x(
                async() => patient = await _client.CreateAsync(
                    new Patient
            {
                Active = true,
                Name   =
                {
                    new HumanName
                    {
                        Family = "Tester", Given = new[]{ "Anne"                                      }, Use = HumanName.NameUse.Usual
                    }
                }
            }).ConfigureAwait(false));

            "Then patient has id".x(() => Assert.NotNull(patient.Id));

            "And patient can be updated".x(
                async() =>
            {
                patient.BirthDateElement = new Date(1970, 1, 1);
                patient = await _client.UpdateAsync(patient).ConfigureAwait(false);

                Assert.NotNull(patient.BirthDate);
            });

            "and can be found when searched".x(
                async() =>
            {
                var p = await _client.SearchByIdAsync <Patient>(patient.Id).ConfigureAwait(false);
                Assert.NotEmpty(p.GetResources());
            });

            "When patient can be deleted".x(
                async() =>
            {
                await _client.DeleteAsync(patient).ConfigureAwait(false);
            });

            "Then cannot be found".x(
                async() =>
            {
                var p = await _client.SearchByIdAsync <Patient>(patient.Id).ConfigureAwait(false);
                Assert.Empty(p.GetResources());
            });
        }
        public async Task <string> AddPatientAsync(PatientCreateRequest patient)
        {
            try
            {
                var newpa = new Hl7.Fhir.Model.Patient()
                {
                    Active    = true,
                    BirthDate = patient.DateOfBirth?.ToString("yyyy-MM-dd", System.Globalization.CultureInfo.InvariantCulture),

                    Gender = patient.Gender.ToLower() == "female" ? AdministrativeGender.Female : AdministrativeGender.Male,
                    Name   = new List <HumanName>()
                    {
                        new HumanName()
                        {
                            Use    = HumanName.NameUse.Usual,
                            Text   = patient.Firstname + patient.Lastname,
                            Family = patient.Lastname,
                            Given  = new List <string>()
                            {
                                patient.Firstname
                            }
                        }
                    },
                    Telecom = new List <ContactPoint>()
                    {
                        new ContactPoint()
                        {
                            Use   = ContactPoint.ContactPointUse.Mobile,
                            Rank  = 1,
                            Value = patient.PhoneNumber
                        }
                    }
                };

                var fhirClient = new FhirClient("http://hapi.fhir.org/baseDstu3");
                var result     = await fhirClient.CreateAsync <Hl7.Fhir.Model.Patient>(newpa);

                return(result.Id);
            }
            catch (Exception ex)
            {
                return(null);
            }
        }
예제 #9
0
        public async Task <string> AddMedicinesToPatientAsync(string emrPatientId, List <MedicationEntity> medicineList)
        {
            //   emrPatientId = "1795445";

            if (medicineList == null)
            {
                return(null);
            }

            if (string.IsNullOrEmpty(emrPatientId))
            {
                throw new Exception("EMR Patient Id is invalid or not found.");
            }

            try
            {
                var patientMedicine = new MedicationRequest
                {
                    Status  = MedicationRequestStatus.Active,
                    Intent  = MedicationRequestIntent.Order,
                    Subject = new ResourceReference
                    {
                        Reference = $"Patient/{emrPatientId}",
                    },
                    Category = new CodeableConcept
                    {
                        Coding = GetMedicineNames(medicineList)
                    },
                    DosageInstruction = GetDosageInstructions(medicineList)
                };


                var fhirClient = new FhirClient("http://hapi.fhir.org/baseDstu3");
                var result     = await fhirClient.CreateAsync <MedicationRequest>(patientMedicine);


                return(result.Id);
            }
            catch (System.Exception ex)
            {
                throw;
            }
        }
예제 #10
0
        public async Task <OrganizationCreationResponse> CreateAsync(OrganizationForCreation org)
        {
            var Result = new OrganizationCreationResponse {
                Data = new NewOrganization()
            };
            Organization organization = new Organization
            {
                Name    = org.name,
                Address = GetFHIROrgAddresses(org),
                Telecom = GetFHIROrgTelecoms(org),
                Type    = GetFHIROrgType(org)
            };

            Organization FHIROrganization = await _client.CreateAsync(organization).ConfigureAwait(false);

            Result.Data.OrganizationId = FHIROrganization.Id;//1ce02b5e-a9ae-4f4a-a2b9-cc0a8d4c987b

            return(Result);
        }
예제 #11
0
        public async Task <IActionResult> CreatePractitionerAsync(CustomPractitioner customPractitioner)
        {
            Practitioner practitioner = new Practitioner();

            practitioner.Identifier.Add(new Identifier("UptSystem", "UPTValue"));
            practitioner.Name.Add(new HumanName()
            {
                Given  = customPractitioner.FirstNames,
                Family = customPractitioner.Name
            });

            var response = await _client.CreateAsync(practitioner);

            if (response == null)
            {
                return(BadRequest("Object sent was not correct!"));
            }
            return(Created($"{BASEURL}/Practitioner/{response.Id}", "Created with succes!"));
        }
        public async Task <string> AddPatientConditions(string emrPatientId, MedicalConditionRequest MedicalRequestModel
                                                        )
        {
            //List<MedicalConditionEntity> medicalConditionList, List<AnatomyEntity> anatomyList
            if (string.IsNullOrEmpty(emrPatientId))
            {
                throw new Exception("EMR Patient Id is invalid or not found.");
            }

            try
            {
                var request = new Condition
                {
                    ClinicalStatus     = Condition.ConditionClinicalStatusCodes.Active,
                    VerificationStatus = Condition.ConditionVerificationStatus.Confirmed,
                    Subject            = new ResourceReference
                    {
                        Reference = $"Patient/{emrPatientId}",
                    },
                };

                List <MedicalConditionEntity> medicalConditionList = MedicalRequestModel.MedicalConditions;
                List <AnatomyEntity>          anatomyList          = MedicalRequestModel.Anatomies;


                request.Category = GetCategories(medicalConditionList);
                request.Severity = GetSeverityList(medicalConditionList);
                request.Code     = GetProblems(medicalConditionList);
                request.BodySite = GetBodySites(anatomyList);


                var fhirClient = new FhirClient("http://hapi.fhir.org/baseDstu3");
                var result     = await fhirClient.CreateAsync <Condition>(request);

                return(result.Id);
            }
            catch (Exception)
            {
                throw;
            }
        }
예제 #13
0
		public void CreateEditDeleteAsync()
		{
			var furore = new Organization
			{
				Name = "Furore",
				Identifier = new List<Identifier> { new Identifier("http://hl7.org/test/1", "3141") },
				Telecom = new List<Contact> { new Contact { System = Contact.ContactSystem.Phone, Value = "+31-20-3467171" } }
			};

			FhirClient client = new FhirClient(testEndpoint);
			var tags = new List<Tag> { new Tag("http://nu.nl/testname", Tag.FHIRTAGSCHEME_GENERAL, "TestCreateEditDelete") };

			var fe = client.CreateAsync<Organization>(furore, tags: tags, refresh: true).Result;

			Assert.IsNotNull(furore);
			Assert.IsNotNull(fe);
			Assert.IsNotNull(fe.Id);
			Assert.IsNotNull(fe.SelfLink);
			Assert.AreNotEqual(fe.Id, fe.SelfLink);
			Assert.IsNotNull(fe.Tags);
			Assert.AreEqual(1, fe.Tags.Count(), "Tag count on new organization record don't match");
			Assert.AreEqual(fe.Tags.First(), tags[0]);
			createdTestOrganizationUrl = fe.Id;

			fe.Resource.Identifier.Add(new Identifier("http://hl7.org/test/2", "3141592"));
			var fe2 = client.UpdateAsync(fe, refresh: true).Result;

			Assert.IsNotNull(fe2);
			Assert.AreEqual(fe.Id, fe2.Id);
			Assert.AreNotEqual(fe.SelfLink, fe2.SelfLink);
			Assert.AreEqual(2, fe2.Resource.Identifier.Count);

			Assert.IsNotNull(fe2.Tags);
			Assert.AreEqual(1, fe2.Tags.Count(), "Tag count on updated organization record don't match");
			Assert.AreEqual(fe2.Tags.First(), tags[0]);

			fe.Resource.Identifier.Add(new Identifier("http://hl7.org/test/3", "3141592"));
			var fe3 = client.UpdateAsync(fe2.Id, fe.Resource, refresh: true).Result;
			Assert.IsNotNull(fe3);
			Assert.AreEqual(3, fe3.Resource.Identifier.Count);

			client.DeleteAsync(fe3).Wait();

			try
			{
				// Get most recent version
				fe = client.ReadAsync<Organization>(new ResourceIdentity(fe.Id)).Result;
				Assert.Fail();
			}
			catch
			{
				Assert.IsTrue(client.LastResponseDetails.Result == HttpStatusCode.Gone);
			}
		}
예제 #14
0
        public void CreateEditDeleteAsync()
        {
            var furore = new Organization
            {
                Name       = "Furore",
                Identifier = new List <Identifier> {
                    new Identifier("http://hl7.org/test/1", "3141")
                },
                Telecom = new List <Contact> {
                    new Contact {
                        System = Contact.ContactSystem.Phone, Value = "+31-20-3467171"
                    }
                }
            };

            FhirClient client = new FhirClient(testEndpoint);
            var        tags   = new List <Tag> {
                new Tag("http://nu.nl/testname", Tag.FHIRTAGSCHEME_GENERAL, "TestCreateEditDelete")
            };

            var fe = client.CreateAsync <Organization>(furore, tags: tags, refresh: true).Result;

            Assert.IsNotNull(furore);
            Assert.IsNotNull(fe);
            Assert.IsNotNull(fe.Id);
            Assert.IsNotNull(fe.SelfLink);
            Assert.AreNotEqual(fe.Id, fe.SelfLink);
            Assert.IsNotNull(fe.Tags);
            Assert.AreEqual(1, fe.Tags.Count(), "Tag count on new organization record don't match");
            Assert.AreEqual(fe.Tags.First(), tags[0]);
            createdTestOrganizationUrl = fe.Id;

            fe.Resource.Identifier.Add(new Identifier("http://hl7.org/test/2", "3141592"));
            var fe2 = client.UpdateAsync(fe, refresh: true).Result;

            Assert.IsNotNull(fe2);
            Assert.AreEqual(fe.Id, fe2.Id);
            Assert.AreNotEqual(fe.SelfLink, fe2.SelfLink);
            Assert.AreEqual(2, fe2.Resource.Identifier.Count);

            Assert.IsNotNull(fe2.Tags);
            Assert.AreEqual(1, fe2.Tags.Count(), "Tag count on updated organization record don't match");
            Assert.AreEqual(fe2.Tags.First(), tags[0]);

            fe.Resource.Identifier.Add(new Identifier("http://hl7.org/test/3", "3141592"));
            var fe3 = client.UpdateAsync(fe2.Id, fe.Resource, refresh: true).Result;

            Assert.IsNotNull(fe3);
            Assert.AreEqual(3, fe3.Resource.Identifier.Count);

            client.DeleteAsync(fe3).Wait();

            try
            {
                // Get most recent version
                fe = client.ReadAsync <Organization>(new ResourceIdentity(fe.Id)).Result;
                Assert.Fail();
            }
            catch
            {
                Assert.IsTrue(client.LastResponseDetails.Result == HttpStatusCode.Gone);
            }
        }
예제 #15
0
            public ClassFixture(DataStore dataStore, Format format)
                : base(dataStore, format)
            {
                Tag = Guid.NewGuid().ToString();

                // Construct an observation pointing to a patient and a diagnostic report pointing to the observation and the patient along with some not matching entries
                var snomedCode = new CodeableConcept("http://snomed.info/sct", "429858000");
                var loincCode  = new CodeableConcept("http://loinc.org", "4548-4");

                var meta = new Meta
                {
                    Tag = new List <Coding>
                    {
                        new Coding("testTag", Tag),
                    },
                };

                var organization = FhirClient.CreateAsync(new Organization {
                    Meta = meta, Address = new List <Address> {
                        new Address {
                            City = "Seattle"
                        }
                    }
                }).Result.Resource;

                AdamsPatient = FhirClient.CreateAsync(new Patient {
                    Meta = meta, Name = new List <HumanName> {
                        new HumanName {
                            Family = "Adams"
                        }
                    }
                }).Result.Resource;
                SmithPatient = FhirClient.CreateAsync(new Patient {
                    Meta = meta, Name = new List <HumanName> {
                        new HumanName {
                            Family = "Smith"
                        }
                    }, ManagingOrganization = new ResourceReference($"Organization/{organization.Id}")
                }).Result.Resource;
                TrumanPatient = FhirClient.CreateAsync(new Patient {
                    Meta = meta, Name = new List <HumanName> {
                        new HumanName {
                            Family = "Truman"
                        }
                    }
                }).Result.Resource;

                var adamsLoincObservation   = CreateObservation(AdamsPatient, loincCode);
                var smithLoincObservation   = CreateObservation(SmithPatient, loincCode);
                var smithSnomedObservation  = CreateObservation(SmithPatient, snomedCode);
                var trumanLoincObservation  = CreateObservation(TrumanPatient, loincCode);
                var trumanSnomedObservation = CreateObservation(TrumanPatient, snomedCode);

                SmithSnomedDiagnosticReport  = CreateDiagnosticReport(SmithPatient, smithSnomedObservation, snomedCode);
                TrumanSnomedDiagnosticReport = CreateDiagnosticReport(TrumanPatient, trumanSnomedObservation, snomedCode);
                SmithLoincDiagnosticReport   = CreateDiagnosticReport(SmithPatient, smithLoincObservation, loincCode);
                TrumanLoincDiagnosticReport  = CreateDiagnosticReport(TrumanPatient, trumanLoincObservation, loincCode);

                var group = new Group
                {
                    Meta = new Meta {
                        Tag = new List <Coding> {
                            new Coding("testTag", Tag)
                        }
                    },
                    Type   = Group.GroupType.Person, Actual = true,
                    Member = new List <Group.MemberComponent>
                    {
                        new Group.MemberComponent {
                            Entity = new ResourceReference($"Patient/{AdamsPatient.Id}")
                        },
                        new Group.MemberComponent {
                            Entity = new ResourceReference($"Patient/{SmithPatient.Id}")
                        },
                        new Group.MemberComponent {
                            Entity = new ResourceReference($"Patient/{TrumanPatient.Id}")
                        },
                    },
                };

                PatientGroup = FhirClient.CreateAsync(group).Result.Resource;

                DiagnosticReport CreateDiagnosticReport(Patient patient, Observation observation, CodeableConcept code)
                {
                    return(FhirClient.CreateAsync(
                               new DiagnosticReport
                    {
                        Meta = meta,
                        Status = DiagnosticReport.DiagnosticReportStatus.Final,
                        Code = code,
                        Subject = new ResourceReference($"Patient/{patient.Id}"),
                        Result = new List <ResourceReference> {
                            new ResourceReference($"Observation/{observation.Id}")
                        },
                    }).Result.Resource);
                }

                Observation CreateObservation(Patient patient, CodeableConcept code)
                {
                    return(FhirClient.CreateAsync(
                               new Observation()
                    {
                        Status = ObservationStatus.Final,
                        Code = code,
                        Subject = new ResourceReference($"Patient/{patient.Id}"),
                    }).Result.Resource);
                }
            }
예제 #16
0
        public async Task <string> AddMedicinesToPatientAsyncTest()
        {
            try
            {
                var patientMedicine = new MedicationRequest
                {
                    Status   = MedicationRequestStatus.Active,
                    Intent   = MedicationRequestIntent.Order,
                    Category = new CodeableConcept
                    {
                        Coding = new List <Coding>
                        {
                            new Coding
                            {
                                Code    = "386864001",
                                Display = "amlodipine 5 mg oral tablet"
                            }
                        }
                    },
                    Subject = new ResourceReference
                    {
                        Reference = "Patient/1795445",
                    },
                    DosageInstruction = new List <Dosage>
                    {
                        new Dosage
                        {
                            Text   = "50 mg = 2 tab(s), PO, qDay, # 10 tab(s), 2 Refill(s)",
                            Timing = new Timing
                            {
                                Repeat = new Timing.RepeatComponent
                                {
                                    Frequency  = 1,
                                    Period     = 1,
                                    PeriodUnit = Timing.UnitsOfTime.D
                                }
                            },
                            Route = new CodeableConcept
                            {
                                Coding = new List <Coding>
                                {
                                    new Coding
                                    {
                                        Display = "Oral"
                                    }
                                }
                            },
                            MaxDosePerLifetime = new Quantity
                            {
                                Value  = 5,
                                Unit   = "mg",
                                System = "http://unitsofmeasure.org"
                            }
                        },
                    }
                };

                var fhirClient = new FhirClient("http://hapi.fhir.org/baseDstu3");
                var result     = await fhirClient.CreateAsync <MedicationRequest>(patientMedicine);

                return(result.Id);
            }
            catch (System.Exception ex)
            {
                throw;
            }
        }