コード例 #1
0
ファイル: ModelTests.cs プロジェクト: szs0321/fhir-ru
        public void TestDeepCopy()
        {
            var p = new Patient();

            p.Name = new List <HumanName>();
            p.Name.Add(HumanName.ForFamily("Kramer").WithGiven("Ewout"));
            p.Name.Add(HumanName.ForFamily("Kramer").WithGiven("Wouter"));
            p.SetExtension("http://test.nl/test", new FhirString("Hello, world"));

            var p2 = (Patient)p.DeepCopy();

            Assert.IsTrue(p2 is Patient);
            Assert.AreNotEqual(p, p2);
            Assert.IsNotNull(p2.Name);
            Assert.AreNotEqual(p.Name, p2.Name);
            Assert.AreEqual(p.Name[0].Family.First(), p2.Name[0].Family.First());
            Assert.AreEqual(p.Name[0].Given.First(), p2.Name[0].Given.First());
            Assert.AreEqual(p.Name[1].Family.First(), p2.Name[1].Family.First());
            Assert.AreEqual(p.Name[1].Given.First(), p2.Name[1].Given.First());

            var ext  = p.GetExtension("http://test.nl/test");
            var ext2 = p2.GetExtension("http://test.nl/test");

            Assert.AreNotEqual(ext, ext2);
            Assert.AreNotEqual(ext.Value, ext2.Value);
            Assert.AreEqual(((FhirString)ext.Value).Value, ((FhirString)ext2.Value).Value);
        }
コード例 #2
0
ファイル: ApiTest.cs プロジェクト: tamizhvendan/fhirbase-net
        public void Test_Init()
        {
            FHIRbase      = new FHIRbaseApi();
            CommonPatient = (Patient)FhirParser.ParseFromJson(File.ReadAllText("Examples/common_patient.json"));

            SimplePatient = new Patient();
            SimplePatient.Name.Add(HumanName.ForFamily("Hello").WithGiven("World"));
            SimplePatient.Telecom.Add(new ContactPoint
            {
                System = ContactPoint.ContactPointSystem.Phone,
                Use    = ContactPoint.ContactPointUse.Mobile,
                Value  = "123456789"
            });

            RemovedPatient = FHIRbase.Search("Patient");
            foreach (var entryComponent in RemovedPatient.Entry)
            {
                FHIRbase.Delete(entryComponent.Resource);
            }

            SearchPatients = new List <Patient>
            {
                (Patient)FHIRbase.Create(SimplePatient),
                (Patient)FHIRbase.Create(SimplePatient),
                (Patient)FHIRbase.Create(SimplePatient),
                (Patient)FHIRbase.Create(CommonPatient),
                (Patient)FHIRbase.Create(CommonPatient),
                (Patient)FHIRbase.Create(CommonPatient),
                (Patient)FHIRbase.Create(CommonPatient)
            };
        }
コード例 #3
0
        public void TestNullExtensionRemoval()
        {
            var p = new Patient
            {
                Extension = new List <Extension>
                {
                    new Extension("http://hl7.org/fhir/Profile/iso-21090#qualifier", new Code("VV")),
                    null
                },

                Contact = new List <Patient.ContactComponent>
                {
                    null,
                    new Patient.ContactComponent {
                        Name = HumanName.ForFamily("Kramer")
                    },
                }
            };

            var xml = FhirXmlSerializer.SerializeToString(p);

            var p2 = (new FhirXmlParser()).Parse <Patient>(xml);

            Assert.AreEqual(1, p2.Extension.Count);
            Assert.AreEqual(1, p2.Contact.Count);
        }
コード例 #4
0
        public void TestSigning()
        {
            Bundle b = new Bundle();

            b.Title       = "Updates to resource 233";
            b.Id          = new Uri("urn:uuid:0d0dcca9-23b9-4149-8619-65002224c3");
            b.LastUpdated = new DateTimeOffset(2012, 11, 2, 14, 17, 21, TimeSpan.Zero);
            b.AuthorName  = "Ewout Kramer";

            ResourceEntry <Patient> p = new ResourceEntry <Patient>();

            p.Id            = new ResourceIdentity("http://test.com/fhir/Patient/233");
            p.Resource      = new Patient();
            p.Resource.Name = new List <HumanName> {
                HumanName.ForFamily("Kramer").WithGiven("Ewout")
            };
            b.Entries.Add(p);

            var certificate = getCertificate();

            var bundleData   = FhirSerializer.SerializeBundleToXmlBytes(b);
            var bundleXml    = Encoding.UTF8.GetString(bundleData);
            var bundleSigned = XmlSignatureHelper.Sign(bundleXml, certificate);

            _signedXml = bundleSigned;

            using (var response = postBundle(bundleSigned))
            {
                if (response.StatusCode != HttpStatusCode.OK)
                {
                    TestResult.Fail("Server refused POSTing signed document at /");
                }
            }
        }
コード例 #5
0
        private Patient createData()
        {
            var result = new Patient()
            {
                Active = true, Gender = AdministrativeGender.Male
            };

            result.Name.Add(HumanName.ForFamily("Kramer").WithGiven("Ewout"));
            return(result);
        }
コード例 #6
0
        public void TryScriptInject()
        {
            var x = new Patient();

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

            var xml = FhirXmlSerializer.SerializeToString(x);

            Assert.IsFalse(xml.Contains("<script"));
        }
コード例 #7
0
        public void ClientForPPT()
        {
            var client = new FhirClient(new Uri("http://hl7connect.healthintersections.com.au/svc/fhir/patient/"));

            // Note patient is a ResourceEntry<Patient>, not a Patient
            var patEntry = client.Read <Patient>("1");
            var pat      = patEntry.Resource;

            pat.Name.Add(HumanName.ForFamily("Kramer").WithGiven("Ewout"));

            client.Update <Patient>(patEntry);
        }
コード例 #8
0
        public void Shold_ReadPatients_When_KeyIsValid()
        {
            // Setup mock fhir client and patient response
            Mock <IFhirClient> mockClient = new Mock <IFhirClient>();
            Patient            res        = new Patient();

            res.Name.Add(HumanName.ForFamily("Doe").WithGiven("John"));
            mockClient.Setup(x => x.Read <DomainResource>(It.IsAny <string>(), It.IsAny <string>(), null)).Returns(res);

            // Create service to tests
            IFhirService service = new TestService(mockClient.Object);

            // Execute the request to read patient's data
            Key key = Key.Create("Patient");
            ServerFhirResponse response = service.Read(key);

            // Verify the response
            Assert.Equal(res.Name[0].Family, ((Patient)response.Resource).Name[0].Family);
        }
コード例 #9
0
        public void Test_Patient_CRUD()
        {
            var createdPatient = FhirResourceHelper.CreatePatient();

            Assert.That(createdPatient, Is.Not.Null);
            Assert.That(createdPatient.VersionId, Is.Not.Empty);

            var patient = Client.Read <Patient>(string.Format("Patient/{0}", createdPatient.Id));

            Assert.That(patient, Is.Not.Null);
            Assert.That(patient.VersionId, Is.Not.Empty);

            createdPatient.Name.Add(HumanName.ForFamily("Kramer").WithGiven("Hello"));
            var updatedPatient = Client.Update(createdPatient);

            Assert.That(createdPatient.VersionId, Is.Not.EqualTo(updatedPatient.VersionId));
            Assert.That(updatedPatient.Name.Exists(x => x.Given.Any(y => y == "Hello")), Is.True);

            Client.Delete(updatedPatient);
        }
コード例 #10
0
ファイル: TestXmlSignature.cs プロジェクト: schellack/spark
        public void TestSigning()
        {
            Bundle b = new Bundle();

            b.Title       = "Updates to resource 233";
            b.Id          = new Uri("urn:uuid:0d0dcca9-23b9-4149-8619-65002224c3");
            b.LastUpdated = new DateTimeOffset(2012, 11, 2, 14, 17, 21, TimeSpan.Zero);
            b.AuthorName  = "Ewout Kramer";

            ResourceEntry <Patient> p = new ResourceEntry <Patient>();

            p.Id            = new ResourceIdentity("http://test.com/fhir/Patient/233");
            p.Resource      = new Patient();
            p.Resource.Name = new List <HumanName> {
                HumanName.ForFamily("Kramer").WithGiven("Ewout")
            };
            b.Entries.Add(p);

            var myAssembly = typeof(TestXmlSignature).Assembly;
            var stream     = myAssembly.GetManifestResourceStream("Spark.Tests.spark.pfx");

            var data = new byte[stream.Length];

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

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

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

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

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

            Assert.AreEqual(bundleSigned.Length, changedBundle.Length);

            Assert.IsFalse(XmlSignatureHelper.VerifySignature(changedBundle));
        }
コード例 #11
0
        // When button 2 is clikced, create patient
        private void button2_Click(object sender, EventArgs e)
        {
            // Edit status text
            createPatientStatus.Text = "Creating...";

            // Set FHIR endpoint and create client
            var endpoint = new Uri("http://fhirtest.uhn.ca/baseDstu2");
            var client   = new FhirClient(endpoint);

            // Create new patient birthdate and name
            var pat = new Patient()
            {
                BirthDate = birthDate.Text, Name = new List <HumanName>()
            };

            pat.Name.Add(HumanName.ForFamily(lastName.Text).WithGiven(givenName.Text));

            // Upload to server
            //client.ReturnFullResource = true;
            client.Create(pat);
            createPatientStatus.Text = "Created!";
        }
コード例 #12
0
        public static Patient CreateTestPatient(string Mrn = "", string FhirId = "")
        {
            string PatientMRNIdentifer = Mrn;

            if (string.IsNullOrWhiteSpace(PatientMRNIdentifer))
            {
                PatientMRNIdentifer = Guid.NewGuid().ToString();
            }

            //Add a Patient resource by Create
            Patient Pat = new Patient();

            if (!string.IsNullOrWhiteSpace(FhirId))
            {
                Pat.Id = FhirId;
            }
            Pat.Name.Add(HumanName.ForFamily("TestPatient").WithGiven("Test"));
            Pat.BirthDateElement = new Date("1979-09-30");
            Pat.Identifier.Add(new Identifier(StaticTestData.TestIdentiferSystem, PatientMRNIdentifer));
            Pat.Gender = AdministrativeGender.Unknown;
            return(Pat);
        }
コード例 #13
0
        public async Task GivenRedactAnonymizationConfig_WhenAnonymizeResource_ThenPropertiesShouldBeRedacted()
        {
            string configurationContent =
                @"
            {
	            ""fhirPathRules"": [
		            {
			            ""path"": ""Patient.name"",
			            ""method"": ""redact""
		            }
	            ]
            }";

            Patient patient = new Patient();

            patient.Name.Add(HumanName.ForFamily("Test"));
            IAnonymizer anonymizer = await CreateAnonymizerFromConfigContent(configurationContent);

            ResourceElement resourceElement    = anonymizer.Anonymize(new ResourceElement(patient.ToTypedElement()));
            Patient         anonymizedResource = resourceElement.Instance.ToPoco <Patient>();

            Assert.Empty(anonymizedResource.Name);
        }
コード例 #14
0
        public async Task GivenSubstituteAnonymizationConfig_WhenAnonymizeResource_ThenSubstitutedNodeShouldBeReturned()
        {
            string configurationContent =
                @"
            {
              ""fhirPathRules"": [
                {
                  ""path"": ""Patient.name.family"",
                  ""method"": ""substitute"",
                  ""replaceWith"": ""test""
                }
              ]
            }";

            Patient patient = new Patient();

            patient.Name.Add(HumanName.ForFamily("input"));
            IAnonymizer anonymizer = await CreateAnonymizerFromConfigContent(configurationContent);

            ResourceElement resourceElement    = anonymizer.Anonymize(new ResourceElement(patient.ToTypedElement()));
            Patient         anonymizedResource = resourceElement.Instance.ToPoco <Patient>();

            Assert.Equal("test", anonymizedResource.Name.First().Family);
        }
コード例 #15
0
        public void Test_DeleteHistoryIndexes()
        {
            FhirClient clientFhir = new FhirClient(StaticTestData.FhirEndpoint(), false);

            clientFhir.Timeout = 1000 * 720; // give the call a while to execute (particularly while debugging).

            string PatientOneResourceId   = Guid.NewGuid().ToString();
            string PatientOneMRNIdentifer = Guid.NewGuid().ToString();

            //Add a Patient resource by Create
            Patient PatientOne = new Patient();

            PatientOne.Id = PatientOneResourceId;
            PatientOne.Name.Add(HumanName.ForFamily("TestPatient").WithGiven("Test"));
            PatientOne.BirthDateElement = new Date("1979-09-30");
            PatientOne.Identifier.Add(new Identifier(StaticTestData.TestIdentiferSystem, PatientOneMRNIdentifer));
            PatientOne.Gender = AdministrativeGender.Unknown;

            Patient PatientResult = null;

            try
            {
                PatientResult = clientFhir.Update <Patient>(PatientOne);
            }
            catch (Exception Exec)
            {
                Assert.True(false, "Exception thrown on Patient resource Update: " + Exec.Message);
            }
            Assert.NotNull(PatientResult, "Resource create by Updated returned resource of null");

            PatientResult = null;

            //Update the patient again to ensure there are History indexes to delete
            try
            {
                PatientResult = clientFhir.Update <Patient>(PatientOne);
            }
            catch (Exception Exec)
            {
                Assert.True(false, "Exception thrown on Patient resource Update: " + Exec.Message);
            }
            Assert.NotNull(PatientResult, "Resource create by Updated returned resource of null");

            //------------------------------------------------------------------------------------
            // ------------ Base Operation, limited types by parameters --------------------------
            //------------------------------------------------------------------------------------

            //Now setup to use the base operation $delete-history-indexes
            //Parameter Resource
            Parameters ParametersIn = new Parameters();

            //ParametersIn.Id = Guid.NewGuid().ToString();
            ParametersIn.Parameter = new List <Parameters.ParameterComponent>();
            var ParamOne = new Parameters.ParameterComponent();

            ParametersIn.Parameter.Add(ParamOne);
            ParamOne.Name  = "ResourceType";
            ParamOne.Value = new FhirString(FHIRAllTypes.Patient.GetLiteral());

            Parameters ParametersResult = null;

            try
            {
                var ResourceResult = clientFhir.WholeSystemOperation(OperationName, ParametersIn);
                ParametersResult = ResourceResult as Parameters;
            }
            catch (Exception Exec)
            {
                Assert.True(false, $"Exception thrown on Operation call to ${OperationName}: " + Exec.Message);
            }
            Assert.NotNull(ParametersResult, "Resource create by Updated returned resource of null");
            Assert.NotNull(ParametersResult.Parameter, "ParametersResult.Parameter is null");
            Assert.AreEqual(ParametersResult.Parameter.Count(), 1, "ParametersResult.Parameter contains more than one parameter.");
            Assert.AreEqual(ParametersResult.Parameter[0].Name, $"{FHIRAllTypes.Patient.GetLiteral()}_TotalIndexesDeletedCount", "ParametersResult.Parameter.Name not as expected.");
            Assert.IsInstanceOf <FhirDecimal>(ParametersResult.Parameter[0].Value, "ParametersResult.Parameter.Value expected FhirDecimal.");
            Assert.Greater((ParametersResult.Parameter[0].Value as FhirDecimal).Value, 0, "ParametersResult.Parameter.Value expected to be greater than 0.");
            ParametersResult = null;


            //------------------------------------------------------------------------------------
            // ------------ Resource Base Operation ALL resource ResourceType = *----------------------------------------------
            //------------------------------------------------------------------------------------

            //Now setup to use the base operation $delete-history-indexes
            //Parameter Resource
            ParametersIn           = new Parameters();
            ParametersIn.Id        = Guid.NewGuid().ToString();
            ParametersIn.Parameter = new List <Parameters.ParameterComponent>();
            ParamOne = new Parameters.ParameterComponent();
            ParametersIn.Parameter.Add(ParamOne);
            ParamOne.Name  = "ResourceType";
            ParamOne.Value = new FhirString("*");

            ParametersResult = null;
            try
            {
                var ResourceResult = clientFhir.WholeSystemOperation(OperationName, ParametersIn);
                ParametersResult = ResourceResult as Parameters;
            }
            catch (Exception Exec)
            {
                Assert.True(false, $"Exception thrown on Operation call to ${OperationName}: " + Exec.Message);
            }
            Assert.NotNull(ParametersResult, "Resource create by Updated returned resource of null");
            Assert.NotNull(ParametersResult.Parameter, "ParametersResult.Parameter is null");
            Assert.AreEqual(ParametersResult.Parameter.Count(), ModelInfo.SupportedResources.Count, "ParametersResult.Parameter.Count Not equal to Supported resource total.");
            ParametersResult = null;

            //------------------------------------------------------------------------------------
            // ------------ Resource Type Operation ----------------------------------------------
            //------------------------------------------------------------------------------------

            //Update the patient again to ensure there are History indexes to delete
            PatientResult = null;
            try
            {
                PatientResult = clientFhir.Update <Patient>(PatientOne);
            }
            catch (Exception Exec)
            {
                Assert.True(false, "Exception thrown on Patient resource Update: " + Exec.Message);
            }
            Assert.NotNull(PatientResult, "Resource create by Updated returned resource of null");

            ParametersIn    = new Parameters();
            ParametersIn.Id = Guid.NewGuid().ToString();

            ParametersResult = null;
            try
            {
                var ResourceResult = clientFhir.TypeOperation <Patient>(OperationName, ParametersIn);
                ParametersResult = ResourceResult as Parameters;
            }
            catch (Exception Exec)
            {
                Assert.True(false, $"Exception thrown on Operation call to ${OperationName}: " + Exec.Message);
            }
            Assert.NotNull(ParametersResult, "Resource create by Updated returned resource of null");
            Assert.NotNull(ParametersResult.Parameter, "ParametersResult.Parameter is null");
            Assert.AreEqual(ParametersResult.Parameter.Count(), 1, "ParametersResult.Parameter contains more than one parameter.");
            Assert.AreEqual(ParametersResult.Parameter[0].Name, $"{FHIRAllTypes.Patient.GetLiteral()}_TotalIndexesDeletedCount", "ParametersResult.Parameter.Name not as expected.");
            Assert.IsInstanceOf <FhirDecimal>(ParametersResult.Parameter[0].Value, "ParametersResult.Parameter.Value expected FhirDecimal.");
            Assert.Greater((ParametersResult.Parameter[0].Value as FhirDecimal).Value, 0, "ParametersResult.Parameter.Value expected to be greater than 0.");

            //--- Clean Up ---------------------------------------------------------
            //Clean up by deleting all Test Patients
            SearchParams sp = new SearchParams().Where($"identifier={StaticTestData.TestIdentiferSystem}|");

            try
            {
                clientFhir.Delete("Patient", sp);
            }
            catch (Exception Exec)
            {
                Assert.True(false, "Exception thrown on conditional delete of resource Patient: " + Exec.Message);
            }
        }
コード例 #16
0
        public void Test_ConditionalCreate()
        {
            Hl7.Fhir.Rest.FhirClient clientFhir = new Hl7.Fhir.Rest.FhirClient(StaticTestData.FhirEndpoint(), false);
            clientFhir.Timeout = 1000 * 600; // give the call a while to execute (particularly while debugging).
            string TempResourceVersion = string.Empty;
            string TempResourceId      = string.Empty;

            //Best to have this clean up here as things can get out of
            //synch with the database when debugging.
            //We always need a clean db to start run.
            var sp = new SearchParams().Where("identifier=http://TestingSystem.org/id|");

            try
            {
                clientFhir.Delete("Patient", sp);
            }
            catch (Exception Exec)
            {
                Assert.True(false, "Exception thrown on conditional delete of resource G: " + Exec.Message);
            }


            // Prepare test patient
            Patient PatientOne = new Patient();

            PatientOne.Name.Add(HumanName.ForFamily("FhirMan").WithGiven("Sam"));
            PatientOne.BirthDateElement = new Date("1970-01");
            PatientOne.Identifier.Add(new Identifier(StaticTestData.TestIdentiferSystem, "5"));

            SearchParams SearchParams = new SearchParams().Where("identifier=5");

            try
            {
                var ResultOne = clientFhir.Create(PatientOne, SearchParams);
                TempResourceId      = ResultOne.Id;
                TempResourceVersion = ResultOne.VersionId;
            }
            catch (FhirOperationException execOper)
            {
                Assert.Fail("Exception was thrown on Condition Create, message was: " + execOper.Message);
            }

            try
            {
                //This will return status OK but does not commit the resource and therefore
                //does not increment the resource version number
                clientFhir.Create(PatientOne, SearchParams);
            }
            catch (FhirOperationException execOper)
            {
                Assert.Fail("Exception was thrown on Condition Create, message was: " + execOper.Message);
            }

            try
            {
                //This will return status OK but does not commit the resource and therefore
                //does not increment the resource version number
                var PatientResult = (Patient)clientFhir.Get($"{StaticTestData.FhirEndpoint()}/Patient/{TempResourceId}");
                Assert.AreEqual(TempResourceVersion, PatientResult.VersionId, "The Version Id was not correct post Conditional Create when Resource was found.");
            }
            catch (FhirOperationException execOper)
            {
                Assert.Fail("Exception was thrown on Condition Create get operation, message was: " + execOper.Message);
            }


            // Create another Patient with the same name
            Patient PatientTwo = new Patient();

            PatientTwo.Name.Add(HumanName.ForFamily("FhirMan").WithGiven("Sam"));
            PatientTwo.BirthDateElement = new Date("1970-01");
            PatientTwo.Identifier.Add(new Identifier(StaticTestData.TestIdentiferSystem, "6"));
            try
            {
                var ResultTwo = clientFhir.Create(PatientTwo);
            }
            catch (FhirOperationException execOper)
            {
                Assert.Fail("Exception was thrown on Condition Create, message was: " + execOper.Message);
            }

            //Now try an Create another again with a search on the Name
            //This should fail as it will resolve to many resource
            Patient PatientThree = new Patient();

            PatientThree.Name.Add(HumanName.ForFamily("FhirMan").WithGiven("Sam"));
            PatientThree.BirthDateElement = new Date("1970-01");
            PatientThree.Identifier.Add(new Identifier(StaticTestData.TestIdentiferSystem, "7"));
            SearchParams = new SearchParams().Where("family=FhirMan").Where("given=Sam");
            try
            {
                var ResultThree = clientFhir.Create(PatientTwo, SearchParams);
                Assert.IsNull(ResultThree, "ResultThree should be null as the ConditionaCreate search parameters should find many resource");
            }
            catch (FhirOperationException execOper)
            {
                Assert.AreEqual(System.Net.HttpStatusCode.PreconditionFailed, execOper.Status, "Did not get Http status 412 when resolving against many resources on ConditionalCreate");
            }



            //Clean up by deleting all resources created while also testing Conditional Delete many
            sp = new SearchParams().Where("identifier=http://TestingSystem.org/id|");
            try
            {
                clientFhir.Delete("Patient", sp);
            }
            catch (Exception Exec)
            {
                Assert.True(false, "Exception thrown on conditional delete of resource G: " + Exec.Message);
            }
        }
コード例 #17
0
        /// <summary>
        /// Executes the specified arguments.
        /// </summary>
        /// <param name="arguments">The arguments.</param>
        /// <returns>System.Int32.</returns>
        /// <remarks>N/A</remarks>
        public override int Execute(Arguments arguments)
        {
            // Get us the needed parameters first
            //
            var url = arguments["url"];
            var id  = arguments["id"];

            var name      = arguments["name"];
            var firstname = arguments["firstname"];
            var gender    = arguments["gender"];
            var dob       = arguments["dob"];
            var phone     = arguments["phone"];
            var email     = arguments["email"];


            // Try to retrieve patient from server and update it
            try
            {
                // Get patient representation from server
                //
                #region retrieve patient
                var client   = new FhirClient(url);
                var identity = ResourceIdentity.Build("Patient", id);
                var entry    = client.Read(identity) as ResourceEntry <Patient>;

                var patient = entry.Resource as Patient;
                if (patient == null)
                {
                    Console.WriteLine("Could not retrieve patient {0} from server {1}", id, url);
                    return(1);
                }
                #endregion

                // We have the patient now modify local representation
                //
                #region prepare patient update
                if (!(String.IsNullOrEmpty(name) && !String.IsNullOrEmpty(firstname)))
                {
                    patient.Name = new List <HumanName>();
                    patient.Name.Add(HumanName.ForFamily(name).WithGiven(firstname));
                }

                if (!String.IsNullOrEmpty(gender))
                {
                    patient.Gender = new CodeableConcept("http://dummy.org/gender", gender, gender);
                }

                if (!String.IsNullOrEmpty(dob))
                {
                    var birthdate = DateTime.ParseExact(dob, "dd/MM/yyyy", new CultureInfo("en-US"));
                    patient.BirthDate = birthdate.ToString("s");
                }

                patient.Telecom = new List <Contact>();
                if (!String.IsNullOrEmpty(phone))
                {
                    patient.Telecom.Add(new Contact()
                    {
                        Value  = phone,
                        System = Contact.ContactSystem.Phone,
                        Use    = Contact.ContactUse.Home
                    });
                }

                if (!String.IsNullOrEmpty(email))
                {
                    patient.Telecom.Add(new Contact()
                    {
                        Value  = email,
                        System = Contact.ContactSystem.Email,
                        Use    = Contact.ContactUse.Home
                    });
                }
                #endregion

                // Finally send the update to the server
                //
                #region do patient update
                entry.Resource = patient;
                client.Update(entry, false);
                Console.WriteLine("Patient {0} updated on server {1}", id, url);
                return(0);

                #endregion
            }
            catch (Exception e)
            {
                Console.WriteLine(e.Message);
                return(1);
            }
        }
コード例 #18
0
        public void Test_ConditionalRead()
        {
            Hl7.Fhir.Rest.FhirClient clientFhir = new Hl7.Fhir.Rest.FhirClient(StaticTestData.FhirEndpoint(), false);
            clientFhir.Timeout = 1000 * 720; // give the call a while to execute (particularly while debugging).

            string         PatientOneId       = string.Empty;
            string         PatientOneVersion  = string.Empty;
            DateTimeOffset?PatientOneModified = null;

            // Prepare 3 test patients
            Patient PatientOne = new Patient();

            string TestPat1 = Guid.NewGuid().ToString();

            PatientOne.Id = TestPat1;
            PatientOne.Name.Add(HumanName.ForFamily("FhirMan").WithGiven("Sam"));
            PatientOne.BirthDateElement = new Date("1970-01");
            PatientOne.Identifier.Add(new Identifier(StaticTestData.TestIdentiferSystem, "6"));

            Patient ResultOne = null;

            try
            {
                ResultOne          = clientFhir.Update(PatientOne);
                PatientOneId       = ResultOne.Id;
                PatientOneVersion  = ResultOne.VersionId;
                PatientOneModified = ResultOne.Meta.LastUpdated;
            }
            catch (Exception Exec)
            {
                Assert.True(false, "Exception thrown on resource Get: " + Exec.Message);
            }


            Patient PatientTwo = null;

            try
            {
                //Resource has not changed so should return a 304 Not Modified
                PatientTwo = clientFhir.Read <Patient>($"{StaticTestData.FhirEndpoint()}/Patient/{PatientOneId}", PatientOneVersion, PatientOneModified);
                Assert.Fail("Conditional Read is expected to throw an exception due to bug in FHIR .NET API");
            }
            catch (FhirOperationException ExecOp)
            {
                //Catch the error and check it is a 304 http status.
                Assert.True(true, "FhirOperationException should be thrown on resource Read: " + ExecOp.Message);
                Assert.IsTrue(ExecOp.Status.IsRedirection());
            }

            PatientTwo         = null;
            PatientOneModified = PatientOneModified.Value.AddMinutes(-1);
            try
            {
                //If-Modified-Since has been pushed back 1 min so we should get a resource back this time
                PatientTwo = clientFhir.Read <Patient>($"{StaticTestData.FhirEndpoint()}/Patient/{PatientOneId}", PatientOneVersion, PatientOneModified);
                Assert.NotNull(PatientTwo, "Not Resource returned when 1 min subtracted from last-modified on Conditional Read.");
                //reset the PatientOneModified
                PatientOneModified = PatientTwo.Meta.LastUpdated;
            }
            catch (FhirOperationException ExecOp)
            {
                Assert.True(false, "FhirOperationException thrown on resource Read: " + ExecOp.Message);
                Assert.IsTrue(ExecOp.Status.IsRedirection());
            }

            PatientTwo        = null;
            PatientOneVersion = "xxxxx";
            try
            {
                //If-None-Match version has been set to not match so we should get a resource back this time
                PatientTwo = clientFhir.Read <Patient>($"{StaticTestData.FhirEndpoint()}/Patient/{PatientOneId}", PatientOneVersion, PatientOneModified);
                Assert.NotNull(PatientTwo, "Not Resource returned when Resource Version did not match active resource Version on Conditional Read.");
            }
            catch (FhirOperationException ExecOp)
            {
                Assert.True(false, "FhirOperationException thrown on resource Read: " + ExecOp.Message);
            }

            //Clean up by deleting all Test Patients
            var sp = new SearchParams().Where("identifier=" + StaticTestData.TestIdentiferSystem + "|");

            try
            {
                clientFhir.Delete("Patient", sp);
            }
            catch (Exception Exec)
            {
                Assert.True(false, "Exception thrown on conditional delete of resource G: " + Exec.Message);
            }
        }
コード例 #19
0
        public void Setup()
        {
            Server = StaticTestData.StartupServer();

            clientFhir         = new Hl7.Fhir.Rest.FhirClient(StaticTestData.FhirEndpoint(), false);
            clientFhir.Timeout = 1000 * 720; // give the call a while to execute (particularly while debugging).

            //This Set up creates an Observation linked to a Patient as the 'subject' and an Organization as the 'performer'
            // Observation1
            //           --> Patient
            //           --> Organization - > Endpoint
            //           --> Observation2
            //                           ----> Observation3

            //Add a Endpoint resource
            //Loop only here for load testing
            for (int i = 0; i < 1; i++)
            {
                Endpoint EndpointOnex = new Endpoint();
                EndpointOnex.Name    = EndpointOneName;
                EndpointOneIdentifer = Guid.NewGuid().ToString();
                EndpointOnex.Identifier.Add(new Identifier(StaticTestData.TestIdentiferSystem, EndpointOneIdentifer));
                Endpoint EndPointOneResult = null;
                try
                {
                    EndPointOneResult = clientFhir.Create(EndpointOnex);
                }
                catch (Exception Exec)
                {
                    Assert.True(false, "Exception thrown on resource Create: " + Exec.Message);
                }
                Assert.NotNull(EndPointOneResult, "Resource created but returned resource is null");
                EndpointOneResourceId = EndPointOneResult.Id;
            }

            //Add a Endpoint resource
            Endpoint EndpointTwo = new Endpoint();

            EndpointTwo.Name = EndpointOneName;
            string EndpointTwoIdentifer = Guid.NewGuid().ToString();

            EndpointTwo.Identifier.Add(new Identifier(StaticTestData.TestIdentiferSystem, EndpointTwoIdentifer));
            Endpoint EndPointTwoResult = null;

            try
            {
                EndPointTwoResult = clientFhir.Create(EndpointTwo);
            }
            catch (Exception Exec)
            {
                Assert.True(false, "Exception thrown on resource Create: " + Exec.Message);
            }
            Assert.NotNull(EndPointTwoResult, "Resource created but returned resource is null");
            string EndpointTwoResourceId = EndPointTwoResult.Id;



            //Add a Organization resource by Update
            Organization OrganizationOne = new Organization();

            OrganizationOne.Name     = OrganizationOneName;
            OrganizationOneIdentifer = Guid.NewGuid().ToString();
            OrganizationOne.Identifier.Add(new Identifier(StaticTestData.TestIdentiferSystem, OrganizationOneIdentifer));
            OrganizationOne.Endpoint = new List <ResourceReference>()
            {
                new ResourceReference($"{ResourceType.Endpoint.GetLiteral()}/{EndpointOneResourceId}")
            };
            Organization OrganizationOneResult = null;

            try
            {
                OrganizationOneResult = clientFhir.Create(OrganizationOne);
            }
            catch (Exception Exec)
            {
                Assert.True(false, "Exception thrown on resource Create: " + Exec.Message);
            }
            Assert.NotNull(OrganizationOneResult, "Resource created but returned resource is null");
            OrganizationOneResourceId = OrganizationOneResult.Id;

            //Patient where Obs.performer -> Org.name
            // Add a Patient to Link to a Observation below  ================================
            //Loop only here for load testing debugging
            for (int i = 0; i < 10; i++)
            {
                Patient PatientOne = new Patient();
                PatientOne.Name.Add(HumanName.ForFamily(PatientOneFamily).WithGiven("Test"));
                PatientOne.BirthDateElement = new Date("1979-09-30");
                PatientOneMRNIdentifer      = Guid.NewGuid().ToString();
                PatientOne.Identifier.Add(new Identifier(StaticTestData.TestIdentiferSystem, PatientOneMRNIdentifer));
                PatientOne.Gender = AdministrativeGender.Unknown;
                PatientOne.ManagingOrganization = new ResourceReference($"{ResourceType.Organization.GetLiteral()}/{OrganizationOneResourceId}");
                Patient PatientResult = null;
                try
                {
                    PatientResult = clientFhir.Create(PatientOne);
                }
                catch (Exception Exec)
                {
                    Assert.True(false, "Exception thrown on resource Create: " + Exec.Message);
                }
                Assert.NotNull(PatientResult, "Resource created but returned resource is null");
                PatientResourceId = PatientResult.Id;
            }

            //Here we set up 3 observations linked in a chain Obs1 -> Obs2 - > Obs3 to test recursive includes

            // Add Observation 3 Linked to no other observation
            // This is to test recursive includes
            Observation ObsResourceThree = new Observation();

            ObsResourceThree.Status   = ObservationStatus.Final;
            ObsResourceThree.Code     = new CodeableConcept("http://somesystem.net/ObSystem", "WCC");
            ObservationThreeIdentifer = Guid.NewGuid().ToString();
            ObsResourceThree.Identifier.Add(new Identifier(StaticTestData.TestIdentiferSystem, ObservationTwoIdentifer));
            ObsResourceThree.Subject   = new ResourceReference($"{ResourceType.Patient.GetLiteral()}/{PatientResourceId}");
            ObsResourceThree.Performer = new List <ResourceReference>()
            {
                new ResourceReference($"{ResourceType.Organization.GetLiteral()}/{OrganizationOneResourceId}")
            };
            Observation ObservationThreeResult = null;

            try
            {
                ObservationThreeResult = clientFhir.Create(ObsResourceThree);
            }
            catch (Exception Exec)
            {
                Assert.True(false, "Exception thrown on Observation resource two create: " + Exec.Message);
            }
            Assert.NotNull(ObservationThreeResult, "Resource created but returned resource is null");
            ObservationThreeResourceId = ObservationThreeResult.Id;
            ObservationThreeResult     = null;


            // Add Observation 2 Linked to the Observation3 above and Patient above
            // This is to test recursive includes
            Observation ObsResourceTwo = new Observation();

            ObsResourceTwo.Status   = ObservationStatus.Final;
            ObsResourceTwo.Code     = new CodeableConcept("http://somesystem.net/ObSystem", "WCC");
            ObservationTwoIdentifer = Guid.NewGuid().ToString();
            ObsResourceTwo.Identifier.Add(new Identifier(StaticTestData.TestIdentiferSystem, ObservationTwoIdentifer));
            ObsResourceTwo.Subject   = new ResourceReference($"{ResourceType.Patient.GetLiteral()}/{PatientResourceId}");
            ObsResourceTwo.Performer = new List <ResourceReference>()
            {
                new ResourceReference($"{ResourceType.Organization.GetLiteral()}/{OrganizationOneResourceId}")
            };
            ObsResourceTwo.Related = new List <Observation.RelatedComponent>();
            var RelatedArtifact2 = new Observation.RelatedComponent();

            RelatedArtifact2.Target = new ResourceReference($"{ResourceType.Observation.GetLiteral()}/{ObservationThreeResourceId}");
            ObsResourceTwo.Related.Add(RelatedArtifact2);
            Observation ObservationTwoResult = null;

            try
            {
                ObservationTwoResult = clientFhir.Create(ObsResourceTwo);
            }
            catch (Exception Exec)
            {
                Assert.True(false, "Exception thrown on Observation resource two create: " + Exec.Message);
            }
            Assert.NotNull(ObservationTwoResult, "Resource created but returned resource is null");
            ObservationTwoResourceId = ObservationTwoResult.Id;
            ObservationTwoResult     = null;

            // Add Observation1 linked to Observation 2 above and the Patient above ================================
            Observation ObsResourceOne = new Observation();

            ObsResourceOne.Status   = ObservationStatus.Final;
            ObsResourceOne.Code     = new CodeableConcept("http://somesystem.net/ObSystem", "HB");
            ObservationOneIdentifer = Guid.NewGuid().ToString();
            ObsResourceOne.Identifier.Add(new Identifier(StaticTestData.TestIdentiferSystem, ObservationOneIdentifer));
            ObsResourceOne.Subject   = new ResourceReference($"{ResourceType.Patient.GetLiteral()}/{PatientResourceId}");
            ObsResourceOne.Performer = new List <ResourceReference>()
            {
                new ResourceReference($"{ResourceType.Organization.GetLiteral()}/{OrganizationOneResourceId}")
            };
            ObsResourceOne.Related = new List <Observation.RelatedComponent>();
            var RelatedArtifact1 = new Observation.RelatedComponent();

            RelatedArtifact1.Target = new ResourceReference($"{ResourceType.Observation.GetLiteral()}/{ObservationTwoResourceId}");
            ObsResourceOne.Related.Add(RelatedArtifact1);
            Observation ObservationOneResult = null;

            try
            {
                ObservationOneResult = clientFhir.Create(ObsResourceOne);
            }
            catch (Exception Exec)
            {
                Assert.True(false, "Exception thrown on resource Create: " + Exec.Message);
            }
            Assert.NotNull(ObservationOneResult, "Resource created but returned resource is null");
            ObservationOneResourceId = ObservationOneResult.Id;
            ObservationOneResult     = null;
        }
コード例 #20
0
        public void Test_PUT_IfMatch()
        {
            Hl7.Fhir.Rest.FhirClient clientFhir = new Hl7.Fhir.Rest.FhirClient(StaticTestData.FhirEndpoint(), false);
            clientFhir.Timeout = 1000 * 720; // give the call a while to execute (particularly while debugging).

            //Best to have this clean up here as things can get out of
            //synch with the database when debugging.
            //We always need a clean db to start run.
            var sp = new SearchParams().Where("identifier=http://TestingSystem.org/id|");

            try
            {
                clientFhir.Delete("Patient", sp);
            }
            catch (Exception Exec)
            {
                Assert.True(false, "Exception thrown on conditional delete of resource G: " + Exec.Message);
            }

            string         PatientOneId       = string.Empty;
            string         PatientOneVersion  = string.Empty;
            DateTimeOffset?PatientOneModified = null;

            // Prepare Patient
            Patient PatientOne     = new Patient();
            string  TestPatIfMatch = Guid.NewGuid().ToString();

            PatientOne.Id = TestPatIfMatch;
            PatientOne.Name.Add(HumanName.ForFamily("IfMatch0").WithGiven("Test0"));
            PatientOne.BirthDateElement = new Date("1970-01");
            PatientOne.Identifier.Add(new Identifier(StaticTestData.TestIdentiferSystem, "AF28B8ED-B81A-41D4-96DE-9012ED1868BD"));

            Patient ResultOne = null;

            try
            {
                ResultOne          = clientFhir.Update(PatientOne);
                PatientOneId       = ResultOne.Id;
                PatientOneVersion  = ResultOne.VersionId;
                PatientOneModified = ResultOne.Meta.LastUpdated;
            }
            catch (Exception Exec)
            {
                Assert.True(false, "Exception thrown on resource Get: " + Exec.Message);
            }

            ResultOne.Name.Clear();
            ResultOne.Name.Add(HumanName.ForFamily("IfMatch1").WithGiven("Test1"));

            Patient ResultTwo = null;

            try
            {
                //Perform a Version aware update that should be successfully. This uses "if-match" HTTP Header.
                ResultTwo = clientFhir.Update(ResultOne, true);
            }
            catch (Exception Exec)
            {
                Assert.True(false, "Exception thrown on resource Get: " + Exec.Message);
            }

            //Increment the last returned resource's version by one and then attempt a version aware update.
            //This should fail with a HTTP Error '409 Conflict'
            ResultTwo.VersionId = (Convert.ToInt32(ResultTwo.VersionId) + 1).ToString();
            Patient ResultThree = null;

            try
            {
                ResultThree = clientFhir.Update(ResultTwo, true);
            }
            catch (FhirOperationException execOper)
            {
                Assert.AreEqual(System.Net.HttpStatusCode.Conflict, execOper.Status, "Did not get Http status 409 Conflict on incorrect Version aware update.");
            }
            catch (Exception Exec)
            {
                Assert.True(false, "Exception thrown on Version aware update: " + Exec.Message);
            }

            //Clean up by deleting all Test Patients
            sp = new SearchParams().Where("identifier=http://TestingSystem.org/id|");
            try
            {
                clientFhir.Delete("Patient", sp);
            }
            catch (Exception Exec)
            {
                Assert.True(false, "Exception thrown on conditional delete of resource G: " + Exec.Message);
            }
        }
コード例 #21
0
        public void Test_ConditionalUpdate()
        {
            Hl7.Fhir.Rest.FhirClient clientFhir = new Hl7.Fhir.Rest.FhirClient(StaticTestData.FhirEndpoint(), false);
            clientFhir.Timeout = 1000 * 720; // give the call a while to execute (particularly while debugging).

            // Prepare 3 test patients
            Patient p1       = new Patient();
            string  TestPat1 = Guid.NewGuid().ToString();

            p1.Id = TestPat1;
            p1.Name.Add(HumanName.ForFamily("Postlethwaite").WithGiven("Brian"));
            p1.BirthDateElement = new Date("1970-01");
            p1.Identifier.Add(new Identifier(StaticTestData.TestIdentiferSystem, "1"));
            var r1 = clientFhir.Update(p1);

            Patient p2       = new Patient();
            string  TestPat2 = Guid.NewGuid().ToString();

            p2.Id = TestPat2;
            p2.Name.Add(HumanName.ForFamily("Portlethwhite").WithGiven("Brian"));
            p2.BirthDateElement = new Date("1970-01");
            p2.Identifier.Add(new Identifier(StaticTestData.TestIdentiferSystem, "1"));
            var r2 = clientFhir.Update(p2);

            Patient p3       = new Patient();
            string  TestPat3 = Guid.NewGuid().ToString();

            p3.Id = TestPat3;
            p3.Name.Add(HumanName.ForFamily("Dole").WithGiven("Bob"));
            p3.BirthDateElement = new Date("1957-01");
            p3.Identifier.Add(new Identifier(StaticTestData.TestIdentiferSystem, "1"));
            var r3 = clientFhir.Update(p3);


            // Test the conditional update now
            // Try to update Bob Doles data
            Patient p3a = new Patient();

            p3a.Name.Add(HumanName.ForFamily("Dole").WithGiven("Bob"));
            p3a.BirthDateElement = new Date("1957-01-12");
            p3a.Identifier.Add(new Identifier(StaticTestData.TestIdentiferSystem, "1"));
            SearchParams sp  = new SearchParams().Where("name=Dole").Where("birthdate=1957-01");
            var          r3a = clientFhir.Update(p3a, sp);

            Assert.AreEqual(TestPat3, r3a.Id, "pat3 should have been updated (not a new one created)");
            Assert.AreEqual("1957-01-12", r3a.BirthDate, "Birth date should have been updated");

            // Try to update Brian's data (which has multuple rows!)
            Patient p1a = new Patient();

            p1a.Name.Add(HumanName.ForFamily("Postlethwaite").WithGiven("Brian"));
            p1a.BirthDateElement = new Date("1970-02");
            p1a.Identifier.Add(new Identifier(StaticTestData.TestIdentiferSystem, "1"));
            sp = new SearchParams().Where("identifier=1");
            try
            {
                var r1a = clientFhir.Update(p1a, sp);
                Assert.Fail("This identifier is used multiple times, the conditional update should have failed");
            }
            catch (FhirOperationException ex)
            {
                Assert.AreEqual(System.Net.HttpStatusCode.PreconditionFailed, ex.Status, "Expected failure of the update due to a pre-condition check");
            }

            // Try to update Bob Doles data with incorrect id
            Patient p3b = new Patient();

            p3b.Id = "NotTheCorrectId";
            p3b.Name.Add(HumanName.ForFamily("Dole").WithGiven("Bob"));
            p3b.BirthDateElement = new Date("1957-01-01");
            p3b.Identifier.Add(new Identifier(StaticTestData.TestIdentiferSystem, "1"));
            try
            {
                var r3b = clientFhir.Update(p3b, sp);
                Assert.Fail("This identifier given in the resource Update does not match the Id in the resource located by search.");
            }
            catch (FhirOperationException ex)
            {
                Assert.AreEqual(System.Net.HttpStatusCode.PreconditionFailed, ex.Status, "Expected failure of the update due to a pre-condition check");
            }

            // Try to update New Patient resource where search returns zero hits and Resource is created occurs
            Patient p4 = new Patient();

            p4.Name.Add(HumanName.ForFamily("Dole4").WithGiven("John"));
            p4.BirthDateElement = new Date("1957-01-01");
            p4.Identifier.Add(new Identifier(StaticTestData.TestIdentiferSystem, "2"));
            sp = new SearchParams().Where("identifier=http://TestingSystem.org/id|2");
            Patient r4 = null;

            try
            {
                r4 = clientFhir.Update(p4, sp);
            }
            catch (FhirOperationException ex)
            {
                Assert.True(false, "Update p4 failed" + ex.Message);
            }


            //Clean up by deleting all resources created while also testing Conditional Delete many
            sp = new SearchParams().Where("identifier=http://TestingSystem.org/id|");
            try
            {
                clientFhir.Delete("Patient", sp);
            }
            catch (Exception Exec)
            {
                Assert.True(false, "Exception thrown on conditional delete of resource G: " + Exec.Message);
            }
        }
コード例 #22
0
        private static Resource MediMobiExample()
        {
            var patient = new Patient
            {
                Id         = "patient",
                Identifier = new List <Identifier>
                {
                    new Identifier("https://www.ehealth.fgov.be/standards/fhir/NamingSystem/ssin", "00.01.01-003.03")
                },
                Name = new List <HumanName> {
                    HumanName.ForFamily("Doe").WithGiven("Jane")
                },
                Gender   = AdministrativeGender.Female,
                Language = "nl-be",
                Address  = new List <Address>
                {
                    new Address()
                    {
                        Line       = new [] { "Astridstraat 192" },
                        City       = "Zottegem",
                        PostalCode = "9620",
                        Use        = Address.AddressUse.Home
                    }
                },
                Telecom = new List <ContactPoint>
                {
                    new ContactPoint(ContactPoint.ContactPointSystem.Phone, ContactPoint.ContactPointUse.Mobile,
                                     "+32478123456"),
                    new ContactPoint(ContactPoint.ContactPointSystem.Email, ContactPoint.ContactPointUse.Home,
                                     "*****@*****.**")
                }
            };

            var campus = new Location()
            {
                Id      = "campus",
                Name    = "Hospital X - campus Ghent",
                Address = new Address
                {
                    Line = new List <string>()
                    {
                        "Steenweg 37"
                    },
                    PostalCode = "9000",
                    City       = "Ghent"
                }
            };

            var location = new Location
            {
                Id        = "location",
                Name      = "Wachtzaal Orthopedie",
                Alias     = new [] { "Route 37" },
                PartOf    = new ResourceReference("#campus"),
                Contained = new List <Resource> {
                    campus
                }
            };

            var healthcareService = new HealthcareService()
            {
                Id         = "healthcareService",
                Identifier =
                    new List <Identifier> {
                    new Identifier("http://demohospital.mediligo.com/service", "orthopedics")
                },
                Specialty = new List <CodeableConcept> {
                    new CodeableConcept("http://snomed.info/sct", "394801008")
                },
                Name = "Orthopedie"
            };

            var x = new Appointment
            {
                Id        = "example",
                Contained = new List <Resource>
                {
                    patient, location, healthcareService
                },
                Identifier =
                    new List <Identifier> {
                    new Identifier("http://demohospital.mediligo.com/appointement", "1234")
                },
                Status          = Appointment.AppointmentStatus.Booked,
                ServiceCategory = new List <CodeableConcept>
                {
                    new CodeableConcept("https://demohospital.mediligo.com/serviceType", "shoulder-first-consult"),
                    new CodeableConcept("http://mediligo.com/fhir/MediMobi/CodeSystem/medimobi-appointment-class",
                                        "consultation-mobile")
                },
                Start       = new DateTimeOffset(2020, 10, 24, 10, 0, 0, TimeSpan.FromHours(1)),
                End         = new DateTimeOffset(2020, 10, 24, 11, 0, 0, TimeSpan.FromHours(1)),
                Participant = new List <Appointment.ParticipantComponent>
                {
                    new Appointment.ParticipantComponent {
                        Actor = new ResourceReference("#patient")
                    },
                    new Appointment.ParticipantComponent {
                        Actor = new ResourceReference("#location")
                    },
                    new Appointment.ParticipantComponent {
                        Actor = new ResourceReference("#healthcareService")
                    }
                }
            };

            return(x);
        }
コード例 #23
0
ファイル: Program.cs プロジェクト: jmpcm/opcfhir
        static void Main(string[] args)
        {
            const string kDeviceId       = "device-0001";
            const string kObservationId  = "bp-0001";
            const string kPatientId      = "patient-0001";
            const string kPractitionerId = "practitioner-0001";

            Patient patient = new Patient()
            {
                Id = kPatientId
            };

            patient.Name.Add(HumanName.ForFamily("Miranda").WithGiven("Jorge"));

            Practitioner practitioner = new Practitioner()
            {
                Id = kPractitionerId
            };

            practitioner.Name.Add(HumanName.ForFamily("Banerjee").WithGiven("Suprateek"));

            Device device = new Device()
            {
                Id           = kDeviceId,
                Manufacturer = "A&D",
                Model        = "UA-651BLE"
            };

            Observation observation = new Observation()
            {
                Id      = kObservationId,
                Device  = new ResourceReference("Device/" + kDeviceId),
                Subject = new ResourceReference("Patient" + kPatientId)
            };

            observation.Performer.Add(new ResourceReference("Practitioner" + kPractitionerId));

            /* Systolic component */
            Observation.ComponentComponent systolic = new Observation.ComponentComponent();
            systolic.Code = new CodeableConcept();
            systolic.Code.Coding.Add(new Coding("http://loinc.org", "8480 - 6"));
            systolic.Code.Coding.Add(new Coding("http://snomed.info/sct", "271649006"));
            systolic.Value = new Quantity()
            {
                Value = 107,
                Unit  = "mmHg",
                Code  = "mm[Hg]"
            };
            systolic.Interpretation = new CodeableConcept("http://hl7.org/fhir/v2/0078", "N", "normal");

            /* Diastolic component */
            Observation.ComponentComponent diastolic = new Observation.ComponentComponent();
            diastolic.Code  = new CodeableConcept("http://loinc.org", "8462-4");
            diastolic.Code  = new CodeableConcept("http://snomed.info/sct", "271650006");
            diastolic.Value = new Quantity()
            {
                Value = 60,
                Unit  = "mmHg",
                Code  = "mm[Hg]"
            };
            diastolic.Interpretation = new CodeableConcept("http://hl7.org/fhir/v2/0078", "L", "low");

            observation.Component.Add(systolic);
            observation.Component.Add(diastolic);

            string json = FhirSerializer.SerializeToJson(observation);
        }
コード例 #24
0
    public void Test_CaseSensitive_FHIR_Id()
    {
      CleanUpByIdentifier(ResourceType.Patient);

      Hl7.Fhir.Rest.FhirClient clientFhir = new Hl7.Fhir.Rest.FhirClient(StaticTestData.FhirEndpoint(), false);
      clientFhir.Timeout = 1000 * 720; // give the call a while to execute (particularly while debugging).
      
      //Add a Patient resource by Update
      Patient PatientOne = new Patient();
      string PatientOneResourceId = Guid.NewGuid().ToString().ToLower();
      PatientOne.Id = PatientOneResourceId;
      string PatientOneFamilyName = "TestPatientOne";
      PatientOne.Name.Add(HumanName.ForFamily(PatientOneFamilyName).WithGiven("Test"));
      PatientOne.BirthDateElement = new Date("1979-09-30");
      string PatientOneMRNIdentifer = Guid.NewGuid().ToString();
      PatientOne.Identifier.Add(new Identifier(StaticTestData.TestIdentiferSystem, PatientOneMRNIdentifer));
      PatientOne.Gender = AdministrativeGender.Unknown;

      Patient PatientResult = null;
      try
      {
        PatientResult = clientFhir.Update(PatientOne);
      }
      catch (Exception Exec)
      {
        Assert.True(false, "Exception thrown on resource Create: " + Exec.Message);
      }
      Assert.NotNull(PatientResult, "Resource create by Updated returned resource of null");      
      PatientResult = null;


      //Add a Patient resource by Update
      Patient PatientTwo = new Patient();
      string PatientTwoResourceId = PatientOneResourceId.ToUpper();
      PatientTwo.Id = PatientTwoResourceId;
      string PatientTwoFamilyName = "TestPatientTwo";
      PatientTwo.Name.Add(HumanName.ForFamily(PatientTwoFamilyName).WithGiven("Test"));
      PatientTwo.BirthDateElement = new Date("1979-09-30");
      string PatientTwoMRNIdentifer = Guid.NewGuid().ToString();
      PatientTwo.Identifier.Add(new Identifier(StaticTestData.TestIdentiferSystem, PatientOneMRNIdentifer));
      PatientTwo.Gender = AdministrativeGender.Unknown;

      PatientResult = null;
      try
      {
        PatientResult = clientFhir.Update(PatientTwo);
      }
      catch (Exception Exec)
      {
        Assert.True(false, "Exception thrown on resource Create: " + Exec.Message);
      }
      Assert.NotNull(PatientResult, "Resource create by Updated returned resource of null");      
      PatientResult = null;

      Bundle SearchResult = null;
      try
      {
        SearchResult = clientFhir.SearchById<Patient>(PatientOneResourceId);
      }
      catch (Exception Exec)
      {
        Assert.True(false, "Exception thrown on resource Create: " + Exec.Message);
      }
      Assert.AreEqual(1, SearchResult.Entry.Count);
      Assert.AreEqual(PatientOneFamilyName, (SearchResult.Entry[0].Resource as Patient).Name[0].Family);

      SearchResult = null;
      try
      {
        SearchResult = clientFhir.SearchById<Patient>(PatientTwoResourceId);
      }
      catch (Exception Exec)
      {
        Assert.True(false, "Exception thrown on resource Create: " + Exec.Message);
      }
      Assert.AreEqual(1, SearchResult.Entry.Count);
      Assert.AreEqual(PatientTwoFamilyName, (SearchResult.Entry[0].Resource as Patient).Name[0].Family);

      //--- Clean Up ---------------------------------------------------------
      //Clean up by deleting all Test Patients
      SearchParams sp = new SearchParams().Where($"identifier={StaticTestData.TestIdentiferSystem}|");
      try
      {
        clientFhir.Delete("Patient", sp);
      }
      catch (Exception Exec)
      {
        Assert.True(false, "Exception thrown on conditional delete of resource Patient: " + Exec.Message);
      }

    }
コード例 #25
0
        /// <summary>
        /// Executes the specified arguments.
        /// </summary>
        /// <param name="arguments">The arguments.</param>
        /// <returns>System.Int32.</returns>
        public override int Execute(Arguments arguments)
        {
            // Get us the needed parameters first
            //
            var url = arguments["url"];

            var name      = arguments["name"];
            var firstname = arguments["firstname"];
            var gender    = arguments["gender"];
            var dob       = arguments["dob"];
            var phone     = arguments["phone"];
            var email     = arguments["email"];

            // Create an in-memory representation of a Patient resource

            var patient = new Patient();

            if (!(String.IsNullOrEmpty(name) && !String.IsNullOrEmpty(firstname)))
            {
                patient.Name = new List <HumanName>();
                patient.Name.Add(HumanName.ForFamily(name).WithGiven(firstname));
            }

            if (!String.IsNullOrEmpty(gender))
            {
                patient.Gender = new CodeableConcept("http://dummy.org/gender", gender, gender);
            }

            if (!String.IsNullOrEmpty(dob))
            {
                var birthdate = DateTime.ParseExact(dob, "dd/MM/yyyy", new CultureInfo("en-US"));
                patient.BirthDate = birthdate.ToString("s");
            }

            patient.Telecom = new List <Contact>();
            if (!String.IsNullOrEmpty(phone))
            {
                patient.Telecom.Add(new Contact()
                {
                    Value  = phone,
                    System = Contact.ContactSystem.Phone,
                    Use    = Contact.ContactUse.Home
                });
            }

            if (!String.IsNullOrEmpty(email))
            {
                patient.Telecom.Add(new Contact()
                {
                    Value  = email,
                    System = Contact.ContactSystem.Email,
                    Use    = Contact.ContactUse.Home
                });
            }


            try
            {
                var client = new FhirClient(url);
                var entry  = client.Create(patient);

                if (entry == null)
                {
                    Console.WriteLine("Couldn not register patient on server {0}", url);
                    return(1);
                }

                var identity = new ResourceIdentity(entry.Id);
                ID = identity.Id;

                Console.WriteLine("Registered patient {0} on server {1}", ID, url);
                return(0);
            }
            catch (Exception e)
            {
                Console.WriteLine(e.Message);
                return(1);
            }
        }
コード例 #26
0
        public void Test_BundleTransaction()
        {
            Hl7.Fhir.Rest.FhirClient clientFhir = new Hl7.Fhir.Rest.FhirClient(StaticTestData.FhirEndpoint(), false);
            clientFhir.Timeout = 1000 * 1000; // give the call a while to execute (particularly while debugging).

            //------------------------------------------------------------------------------------------------------
            //Transaction Bundle 1 (Create) ---------------------------------------------------------------------------------
            //------------------------------------------------------------------------------------------------------

            Bundle TransBundle = new Bundle();

            TransBundle.Id    = Guid.NewGuid().ToString();
            TransBundle.Type  = Bundle.BundleType.Transaction;
            TransBundle.Entry = new List <Bundle.EntryComponent>();
            string PatientOneMRNIdentifer      = Guid.NewGuid().ToString();
            string OrganizationOneMRNIdentifer = Guid.NewGuid().ToString();

            //Add a Patient resource by Create
            Patient PatientOne             = StaticTestData.CreateTestPatient(PatientOneMRNIdentifer);
            string  OrgOneResourceIdFulUrl = CreateFullUrlUUID(Guid.NewGuid().ToString());

            PatientOne.ManagingOrganization = new ResourceReference()
            {
                Reference = OrgOneResourceIdFulUrl
            };

            var PatientEntry = new Bundle.EntryComponent();

            TransBundle.Entry.Add(PatientEntry);
            PatientEntry.Resource       = PatientOne;
            PatientEntry.Request        = new Bundle.RequestComponent();
            PatientEntry.Request.Method = Bundle.HTTPVerb.POST;
            string PatientResourceIdFulUrl = CreateFullUrlUUID(Guid.NewGuid().ToString());

            PatientEntry.FullUrl        = PatientResourceIdFulUrl;
            PatientEntry.Resource       = PatientOne;
            PatientEntry.Request        = new Bundle.RequestComponent();
            PatientEntry.Request.Method = Bundle.HTTPVerb.POST;
            PatientEntry.Request.Url    = "Patient";

            //Add a Organization resource by Create
            Organization OrganizationOne = new Organization();

            OrganizationOne.Name = "Test OrganizationOne";
            OrganizationOne.Identifier.Add(new Identifier(StaticTestData.TestIdentiferSystem, OrganizationOneMRNIdentifer));

            var OrganizationOneEntry = new Bundle.EntryComponent();

            TransBundle.Entry.Add(OrganizationOneEntry);
            OrganizationOneEntry.Resource       = OrganizationOne;
            OrganizationOneEntry.Request        = new Bundle.RequestComponent();
            OrganizationOneEntry.Request.Method = Bundle.HTTPVerb.POST;
            OrganizationOneEntry.FullUrl        = OrgOneResourceIdFulUrl;

            OrganizationOneEntry.Resource       = OrganizationOne;
            OrganizationOneEntry.Request        = new Bundle.RequestComponent();
            OrganizationOneEntry.Request.Method = Bundle.HTTPVerb.POST;
            OrganizationOneEntry.Request.Url    = "Organization";


            Bundle TransactionResult = null;

            try
            {
                TransactionResult = clientFhir.Transaction(TransBundle);
            }
            catch (Exception Exec)
            {
                Assert.True(false, "Exception thrown on POST Transaction bundle: " + Exec.Message);
            }

            Assert.True(TransactionResult.Type == Bundle.BundleType.TransactionResponse);
            Assert.IsTrue(TransactionResult.Entry[0].Response.Status.Contains(System.Net.HttpStatusCode.Created.ToString()));
            Assert.IsTrue(TransactionResult.Entry[1].Response.Status.Contains(System.Net.HttpStatusCode.Created.ToString()));
            Patient      TransactionResultPatient      = TransactionResult.Entry[0].Resource as Patient;
            Organization TransactionResultOrganization = TransactionResult.Entry[1].Resource as Organization;
            string       PatientOneResourceId          = TransactionResult.Entry[0].Resource.Id;
            string       OrgOneResourceId = TransactionResult.Entry[1].Resource.Id;


            //Check that the referance in the Patient to the Organization has been updated.
            Assert.AreEqual(TransactionResultPatient.ManagingOrganization.Reference, $"Organization/{TransactionResultOrganization.Id}");

            //Check the Response Etag matches the resource Version number
            string PatientResourceVersionNumber = TransactionResultPatient.VersionId;

            Assert.AreEqual(Common.Tools.HttpHeaderSupport.GetEntityTagHeaderValueFromVersion(PatientResourceVersionNumber).Tag, Common.Tools.HttpHeaderSupport.GetETagEntityTagHeaderValueFromETagString(TransactionResult.Entry[0].Response.Etag).Tag);

            //Check that the FullURL of the entry is correct aginst the returned Resource
            string PatientFullUrlExpected = $"{StaticTestData.FhirEndpoint()}/Patient/{PatientOneResourceId}";

            Assert.AreEqual(PatientFullUrlExpected, TransactionResult.Entry[0].FullUrl);

            //------------------------------------------------------------------------------------------------------
            //Transaction Bundle 2 (Update) ------------------------------------------------------------------------
            //------------------------------------------------------------------------------------------------------

            TransBundle.Id = Guid.NewGuid().ToString();
            TransBundle.Entry.Clear();
            //Patient
            PatientOne.Id = PatientOneResourceId;
            PatientOne.Name.Clear();
            string PatientFamilyName = "TestPatientUpdate";

            PatientOne.Name.Add(HumanName.ForFamily(PatientFamilyName).WithGiven("TestUpdate"));
            //PatientOne.BirthDateElement = new Date("1979-09-30");
            //PatientOne.Identifier.Add(new Identifier(StaticTestData.TestIdentiferSystem, PatientOneMRNIdentifer));
            //PatientOne.Gender = AdministrativeGender.Unknown;

            PatientEntry = new Bundle.EntryComponent();
            TransBundle.Entry.Add(PatientEntry);
            PatientResourceIdFulUrl     = $"{StaticTestData.FhirEndpoint()}/Patient/{PatientOneResourceId}";
            PatientEntry.FullUrl        = PatientResourceIdFulUrl;
            PatientEntry.Resource       = PatientOne;
            PatientEntry.Request        = new Bundle.RequestComponent();
            PatientEntry.Request.Method = Bundle.HTTPVerb.PUT;
            PatientEntry.Request.Url    = $"Patient/{PatientOneResourceId}";

            //Organization
            OrganizationOne.Id   = OrgOneResourceId;
            OrganizationOne.Name = "Test OrganizationOne Updated";
            //OrganizationOne.Identifier.Add(new Identifier(StaticTestData.TestIdentiferSystem, OrganizationOneMRNIdentifer));

            OrganizationOneEntry = new Bundle.EntryComponent();
            TransBundle.Entry.Add(OrganizationOneEntry);
            OrgOneResourceIdFulUrl              = $"{StaticTestData.FhirEndpoint()}/Organization/{OrgOneResourceId}";
            OrganizationOneEntry.FullUrl        = OrgOneResourceIdFulUrl;
            OrganizationOneEntry.Resource       = OrganizationOne;
            OrganizationOneEntry.Request        = new Bundle.RequestComponent();
            OrganizationOneEntry.Request.Method = Bundle.HTTPVerb.PUT;
            OrganizationOneEntry.Request.Url    = $"Organization/{OrgOneResourceId}";

            TransactionResult = null;
            try
            {
                TransactionResult = clientFhir.Transaction(TransBundle);
            }
            catch (Exception Exec)
            {
                Assert.True(false, "Exception thrown on PUT Transaction bundle: " + Exec.Message);
            }
            Assert.IsTrue(TransactionResult.Entry[0].Response.Status.Contains(System.Net.HttpStatusCode.OK.ToString()));
            Assert.IsTrue(TransactionResult.Entry[1].Response.Status.Contains(System.Net.HttpStatusCode.OK.ToString()));

            TransactionResultPatient      = TransactionResult.Entry[0].Resource as Patient;
            TransactionResultOrganization = TransactionResult.Entry[1].Resource as Organization;

            //Check the family name was updated in the returned resource
            Assert.AreEqual(PatientFamilyName, TransactionResultPatient.Name[0].Family);

            //------------------------------------------------------------------------------------------------------
            //Transaction Bundle 3 (GET) ------------------------------------------------------------------------
            //------------------------------------------------------------------------------------------------------
            TransBundle.Id = Guid.NewGuid().ToString();
            TransBundle.Entry.Clear();

            PatientEntry = new Bundle.EntryComponent();
            TransBundle.Entry.Add(PatientEntry);
            PatientEntry.Request        = new Bundle.RequestComponent();
            PatientEntry.Request.Method = Bundle.HTTPVerb.GET;
            PatientEntry.Request.Url    = $"Patient/{TransactionResultPatient.Id}";

            OrganizationOneEntry = new Bundle.EntryComponent();
            TransBundle.Entry.Add(OrganizationOneEntry);
            OrganizationOneEntry.Request        = new Bundle.RequestComponent();
            OrganizationOneEntry.Request.Method = Bundle.HTTPVerb.GET;
            OrganizationOneEntry.Request.Url    = $"Organization/{TransactionResultOrganization.Id}";

            TransactionResult = null;
            try
            {
                TransactionResult = clientFhir.Transaction(TransBundle);
            }
            catch (Exception Exec)
            {
                Assert.True(false, "Exception thrown on GET Transaction bundle" + Exec.Message);
            }
            Assert.IsTrue(TransactionResult.Entry[0].Response.Status.Contains(System.Net.HttpStatusCode.OK.ToString()));
            Assert.IsTrue(TransactionResult.Entry[1].Response.Status.Contains(System.Net.HttpStatusCode.OK.ToString()));

            TransactionResultPatient      = TransactionResult.Entry[0].Resource as Patient;
            TransactionResultOrganization = TransactionResult.Entry[1].Resource as Organization;

            //------------------------------------------------------------------------------------------------------
            //Transaction Bundle 4 Search (GET) ------------------------------------------------------------------------
            //------------------------------------------------------------------------------------------------------
            TransBundle.Id = Guid.NewGuid().ToString();
            TransBundle.Entry.Clear();

            PatientEntry = new Bundle.EntryComponent();
            TransBundle.Entry.Add(PatientEntry);
            PatientEntry.Request        = new Bundle.RequestComponent();
            PatientEntry.Request.Method = Bundle.HTTPVerb.GET;
            PatientEntry.Request.Url    = $"Patient?identifier={StaticTestData.TestIdentiferSystem}|{PatientOneMRNIdentifer}";

            OrganizationOneEntry = new Bundle.EntryComponent();
            TransBundle.Entry.Add(OrganizationOneEntry);
            OrganizationOneEntry.Request        = new Bundle.RequestComponent();
            OrganizationOneEntry.Request.Method = Bundle.HTTPVerb.GET;
            OrganizationOneEntry.Request.Url    = $"Organization?identifier={StaticTestData.TestIdentiferSystem}|{OrganizationOneMRNIdentifer}";

            TransactionResult = null;
            try
            {
                TransactionResult = clientFhir.Transaction(TransBundle);
            }
            catch (Exception Exec)
            {
                Assert.True(false, "Exception thrown on GET Transaction bundle" + Exec.Message);
            }
            Assert.IsTrue(TransactionResult.Entry[0].Response.Status.Contains(System.Net.HttpStatusCode.OK.ToString()));
            Assert.IsTrue(TransactionResult.Entry[1].Response.Status.Contains(System.Net.HttpStatusCode.OK.ToString()));

            Bundle TransactionResultSearchPatientOneBundle   = TransactionResult.Entry[0].Resource as Bundle;
            Bundle TransactionResultOrganizationSearchBundle = TransactionResult.Entry[1].Resource as Bundle;

            //Check we only got one back in the search bundle
            Assert.AreEqual(TransactionResultSearchPatientOneBundle.Entry.Count, 1);
            Assert.AreEqual(TransactionResultOrganizationSearchBundle.Entry.Count, 1);

            //Check that each we got back were the two we added.
            Assert.AreEqual(TransactionResultSearchPatientOneBundle.Entry[0].Resource.Id, PatientOneResourceId);
            Assert.AreEqual(TransactionResultOrganizationSearchBundle.Entry[0].Resource.Id, OrgOneResourceId);

            //------------------------------------------------------------------------------------------------------
            //Transaction Bundle 5 If-Match (GET) --------------------------------------------------------------------
            //------------------------------------------------------------------------------------------------------
            TransBundle.Id = Guid.NewGuid().ToString();
            TransBundle.Entry.Clear();

            PatientEntry = new Bundle.EntryComponent();
            TransBundle.Entry.Add(PatientEntry);
            PatientEntry.Request         = new Bundle.RequestComponent();
            PatientEntry.Request.Method  = Bundle.HTTPVerb.GET;
            PatientEntry.Request.Url     = $"Patient?identifier={StaticTestData.TestIdentiferSystem}|{PatientOneMRNIdentifer}";
            PatientEntry.Request.IfMatch = Common.Tools.HttpHeaderSupport.GetETagString(TransactionResultSearchPatientOneBundle.Entry[0].Resource.VersionId);

            OrganizationOneEntry = new Bundle.EntryComponent();
            TransBundle.Entry.Add(OrganizationOneEntry);
            OrganizationOneEntry.Request         = new Bundle.RequestComponent();
            OrganizationOneEntry.Request.Method  = Bundle.HTTPVerb.GET;
            OrganizationOneEntry.Request.Url     = $"Organization?identifier={StaticTestData.TestIdentiferSystem}|{OrganizationOneMRNIdentifer}";
            OrganizationOneEntry.Request.IfMatch = Common.Tools.HttpHeaderSupport.GetETagString(TransactionResultOrganizationSearchBundle.Entry[0].Resource.VersionId);

            TransactionResult = null;
            try
            {
                TransactionResult = clientFhir.Transaction(TransBundle);
            }
            catch (Exception Exec)
            {
                Assert.True(false, "Exception thrown on GET Transaction bundle" + Exec.Message);
            }
            Assert.IsTrue(TransactionResult.Entry[0].Response.Status.Contains(System.Net.HttpStatusCode.OK.ToString()));
            Assert.IsTrue(TransactionResult.Entry[1].Response.Status.Contains(System.Net.HttpStatusCode.OK.ToString()));

            TransactionResultSearchPatientOneBundle   = TransactionResult.Entry[0].Resource as Bundle;
            TransactionResultOrganizationSearchBundle = TransactionResult.Entry[1].Resource as Bundle;

            //Check we only got one back in the search bundle
            Assert.AreEqual(TransactionResultSearchPatientOneBundle.Entry.Count, 1);
            Assert.AreEqual(TransactionResultOrganizationSearchBundle.Entry.Count, 1);


            //------------------------------------------------------------------------------------------------------
            //Transaction Bundle 6 If-Match (DELETE) --------------------------------------------------------------------
            //------------------------------------------------------------------------------------------------------
            TransBundle.Id = Guid.NewGuid().ToString();
            TransBundle.Entry.Clear();

            PatientEntry = new Bundle.EntryComponent();
            TransBundle.Entry.Add(PatientEntry);
            PatientEntry.Request         = new Bundle.RequestComponent();
            PatientEntry.Request.Method  = Bundle.HTTPVerb.DELETE;
            PatientEntry.Request.Url     = $"Patient?identifier={StaticTestData.TestIdentiferSystem}|{PatientOneMRNIdentifer}";
            PatientEntry.Request.IfMatch = Common.Tools.HttpHeaderSupport.GetETagString(TransactionResultSearchPatientOneBundle.Entry[0].Resource.VersionId);

            OrganizationOneEntry = new Bundle.EntryComponent();
            TransBundle.Entry.Add(OrganizationOneEntry);
            OrganizationOneEntry.Request         = new Bundle.RequestComponent();
            OrganizationOneEntry.Request.Method  = Bundle.HTTPVerb.DELETE;
            OrganizationOneEntry.Request.Url     = $"Organization?identifier={StaticTestData.TestIdentiferSystem}|{OrganizationOneMRNIdentifer}";
            OrganizationOneEntry.Request.IfMatch = Common.Tools.HttpHeaderSupport.GetETagString(TransactionResultOrganizationSearchBundle.Entry[0].Resource.VersionId);

            TransactionResult = null;
            try
            {
                TransactionResult = clientFhir.Transaction(TransBundle);
            }
            catch (Exception Exec)
            {
                Assert.True(false, "Exception thrown on GET Transaction bundle" + Exec.Message);
            }
            Assert.IsTrue(TransactionResult.Entry[0].Response.Status.Contains(System.Net.HttpStatusCode.NoContent.ToString()));
            Assert.IsTrue(TransactionResult.Entry[1].Response.Status.Contains(System.Net.HttpStatusCode.NoContent.ToString()));

            CleanUpByIdentifier(ResourceType.Patient);
            CleanUpByIdentifier(ResourceType.Organization);
        }
コード例 #27
0
    public void Test_CRUD()
    {

      Hl7.Fhir.Rest.FhirClient clientFhir = new Hl7.Fhir.Rest.FhirClient(StaticTestData.FhirEndpoint(), false);
      clientFhir.Timeout = 1000 * 720; // give the call a while to execute (particularly while debugging).

      string PatientResourceId = string.Empty;

      //Add a Patient resource by Update
      Patient PatientOne = new Patient();
      PatientOne.Name.Add(HumanName.ForFamily("TestPatient").WithGiven("Test"));
      PatientOne.BirthDateElement = new Date("1979-09-30");
      string PatientOneMRNIdentifer = Guid.NewGuid().ToString();
      PatientOne.Identifier.Add(new Identifier(StaticTestData.TestIdentiferSystem, PatientOneMRNIdentifer));
      PatientOne.Gender = AdministrativeGender.Unknown;

      Patient PatientResult = null;
      try
      {
        PatientResult = clientFhir.Create(PatientOne);
      }
      catch (Exception Exec)
      {
        Assert.True(false, "Exception thrown on resource Create: " + Exec.Message);
      }
      Assert.NotNull(PatientResult, "Resource create by Updated returned resource of null");
      PatientResourceId = PatientResult.Id;
      PatientResult = null;

      //Get the Added resource by Id
      try
      {
        //PatientOneResourceId
        PatientResult = (Patient)clientFhir.Get($"{StaticTestData.FhirEndpoint()}/Patient/{PatientResourceId}");
      }
      catch (Exception Exec)
      {
        Assert.True(false, "Exception thrown on resource Get: " + Exec.Message);
      }
      Assert.NotNull(PatientResult, "Resource Get returned resource of null");
      Assert.AreEqual(PatientResourceId, PatientResult.Id, "Resource created by Updated has incorrect Resource Id");
      Assert.AreEqual(AdministrativeGender.Unknown, PatientResult.Gender, "Patient gender does not match.");

      //Update
      PatientResult.Gender = AdministrativeGender.Male;
      try
      {
        clientFhir.Update(PatientResult);
      }
      catch (Exception Exec)
      {
        Assert.True(false, "Exception thrown on resource Get: " + Exec.Message);
      }
      PatientResult = null;

      //Get the Added resource by Id
      try
      {
        PatientResult = (Patient)clientFhir.Get($"{StaticTestData.FhirEndpoint()}/Patient/{PatientResourceId}");
      }
      catch (Exception Exec)
      {
        Assert.True(false, "Exception thrown on resource Get: " + Exec.Message);
      }
      Assert.NotNull(PatientResult, "Resource Get returned resource of null");
      Assert.AreEqual(AdministrativeGender.Male, PatientResult.Gender, "Patient gender does not match.");

      //Delete Resource
      try
      {
        clientFhir.Delete($"Patient/{PatientResourceId}");
      }
      catch (Exception Exec)
      {
        Assert.True(false, "Exception thrown on resource Get: " + Exec.Message);
      }

      //Get the Added resource by Id
      try
      {
        var Result = clientFhir.Get($"{StaticTestData.FhirEndpoint()}/Patient/{PatientResourceId}");
      }
      catch (Hl7.Fhir.Rest.FhirOperationException OpExec)
      {
        Assert.AreEqual(OpExec.Status, System.Net.HttpStatusCode.Gone, "Final Get did not return Http Status of Gone.");
      }

    }