Esempio n. 1
0
    private static void PutPatient()
    {
      Hl7.Fhir.Rest.FhirClient clientFhir = new Hl7.Fhir.Rest.FhirClient(StaticTestData.FhirEndpoint(), false);
      //Hl7.Fhir.Rest.FhirClient clientFhir = new Hl7.Fhir.Rest.FhirClient("https://stu3.test.pyrohealth.net/fhir", false);
      clientFhir.Timeout = 1000 * 720; // give the call a while to execute (particularly while debugging).
      //clientFhir.Timeout = 30000; // give the call a while to execute (particularly while debugging).
      Hl7.Fhir.Model.Patient Pat = new Hl7.Fhir.Model.Patient();
      //Pat.Id = Guid.NewGuid().ToString();
      Pat.Name = new List<Hl7.Fhir.Model.HumanName>()
      {
       new Hl7.Fhir.Model.HumanName()
       {
         Family = "millar104"
       }
      };
      var response = clientFhir.Create<Hl7.Fhir.Model.Patient>(Pat);
      string PatientResourceId = response.Id;
      Assert.AreEqual("1", response.VersionId);

      Pat.Id = PatientResourceId;
      Pat.Name[0].Family = "millar105";

      response = clientFhir.Update<Hl7.Fhir.Model.Patient>(Pat);
      Assert.AreEqual("2", response.VersionId);

      var PatientResult = (Hl7.Fhir.Model.Patient)clientFhir.Get($"{StaticTestData.FhirEndpoint()}/{PatientResourceId}");

      Assert.AreEqual(Hl7.Fhir.Model.ResourceType.Patient, PatientResult.ResourceType);
      
    }
Esempio n. 2
0
        public void CreatePatient()
        {
            Patient p = new Patient();

            p.Name = new System.Collections.Generic.List <HumanName>();
            p.Name.Add(new HumanName().WithGiven("Grahame").AndFamily("Grieve"));
            p.BirthDate            = new DateTime(1970, 3, 1).ToFhirDate(); // yes there are extensions to convert to FHIR format
            p.Active               = true;
            p.ManagingOrganization = new ResourceReference("Organization/1", "Demo Org");

            Hl7.Fhir.Rest.FhirClient clientFhir = new Hl7.Fhir.Rest.FhirClient(_baseAddress, false);
            var result = clientFhir.Create <Patient>(p);

            Assert.IsNotNull(result.Id, "Newly created patient should have an ID");
            Assert.IsNotNull(result.Meta, "Newly created patient should have an Meta created");
            Assert.IsNotNull(result.Meta.LastUpdated, "Newly created patient should have the creation date populated");
            Assert.IsTrue(result.Active.Value, "The patient was created as an active patient");
        }
Esempio n. 3
0
        public void Test_TransBundleIfNoneExsists()
        {
            CleanUpByIdentifier(ResourceType.Patient);
            CleanUpByIdentifier(ResourceType.Observation);

            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).

            //Test If-None-Exsists within a bundle transaction where their is a link from
            //one resource Observation to a Patient resource that by an identifier Reference.
            //So the idea is that the Observation resource identifier Reference is updated
            //with the servers true Id for the Patient resource which already exsists in the server.
            //The Patient resource in the bundle is not actualy commited as it already exsist.
            //So the test is as follows:
            //1. Add as a POST (Create) patient one as setup so it is in the server
            //2. POST a transaction bundle which has the same Pateint one resource marked as 'IfNoneExsists'
            //   and an Observation resource with a identifier Reference to Patient one. I will also add
            //   another Patient Two and Observation two resource that also have a identifier Reference link between
            //   them selves and IfNoneExists for the Patient two, yet in this case the Patient resource
            //   will not exists, so will be commited.
            //3. The outcome should be:
            //   - Patient One - OK (indicating it is already in the server, and has the same Fhir id as the step 1 PUT)
            //   - ObservationOne - Created (referance updated Patient One Fhir Id)
            //   - Patient Two - Created (Assigned a new Fhir ID)
            //   - Observation Two - Created (referance updated Patient One Fhir Id)


            //Arrange ------------------------------------------------------------

            //Patient One Setup
            string  PatientOneMRNIdentifer = Guid.NewGuid().ToString();
            Patient PatientOne             = StaticTestData.CreateTestPatient(PatientOneMRNIdentifer);

            Patient PatientCreateResult = null;

            try
            {
                //POST Patent One as Setup
                PatientCreateResult = clientFhir.Create(PatientOne);
            }
            catch (Exception Exec)
            {
                Assert.True(false, "Exception thrown on PUT Patient One setup: " + Exec.Message);
            }
            //Get the Fhir Id Assiged to patient One to assert later
            string PatientOneFhirId = PatientCreateResult.Id;

            Observation ObservationOne = new Observation();

            ObservationOne.Subject    = new ResourceReference($"{ResourceType.Patient.GetLiteral()}?identifier={PatientOneMRNIdentifer}");
            ObservationOne.Identifier = new List <Identifier>()
            {
                new Identifier()
                {
                    System = StaticTestData.TestIdentiferSystem,
                    Value  = Common.Tools.FhirGuid.FhirGuid.NewFhirGuid()
                }
            };
            ObservationOne.Code        = new CodeableConcept();
            ObservationOne.Code.Coding = new List <Coding>();
            ObservationOne.Code.Coding.Add(new Coding()
            {
                System = "http:/mytestcodesystem.com/system",
                Code   = "ObsOne"
            });

            //Patient Two Setup
            string  PatientTwoMRNIdentifer = Guid.NewGuid().ToString();
            Patient PatientTwo             = StaticTestData.CreateTestPatient(PatientTwoMRNIdentifer);

            Observation ObservationTwo = new Observation();

            ObservationTwo.Subject    = new ResourceReference($"{ResourceType.Patient.GetLiteral()}?identifier={PatientTwoMRNIdentifer}");
            ObservationTwo.Identifier = new List <Identifier>()
            {
                new Identifier()
                {
                    System = StaticTestData.TestIdentiferSystem,
                    Value  = Common.Tools.FhirGuid.FhirGuid.NewFhirGuid()
                }
            };
            ObservationTwo.Code        = new CodeableConcept();
            ObservationTwo.Code.Coding = new List <Coding>();
            ObservationTwo.Code.Coding.Add(new Coding()
            {
                System = "http:/mytestcodesystem.com/system",
                Code   = "ObsTwo"
            });

            //Now setup Transaction bundle
            Bundle TransBundleIfNoneExsists = new Bundle();

            TransBundleIfNoneExsists.Id    = Guid.NewGuid().ToString();
            TransBundleIfNoneExsists.Type  = Bundle.BundleType.Transaction;
            TransBundleIfNoneExsists.Entry = new List <Bundle.EntryComponent>();

            //Patient One Entry
            var PatientOneEntry = new Bundle.EntryComponent();

            TransBundleIfNoneExsists.Entry.Add(PatientOneEntry);
            PatientOneEntry.FullUrl             = CreateFullUrlUUID(Guid.NewGuid().ToString());
            PatientOneEntry.Resource            = PatientOne;
            PatientOneEntry.Request             = new Bundle.RequestComponent();
            PatientOneEntry.Request.Method      = Bundle.HTTPVerb.POST;
            PatientOneEntry.Request.Url         = ResourceType.Patient.GetLiteral();
            PatientOneEntry.Request.IfNoneExist = $"identifier={PatientOneMRNIdentifer}";

            //Observation One Entry
            //Patient One Entry
            var ObservationOneEntry = new Bundle.EntryComponent();

            TransBundleIfNoneExsists.Entry.Add(ObservationOneEntry);
            ObservationOneEntry.FullUrl        = CreateFullUrlUUID(Guid.NewGuid().ToString());
            ObservationOneEntry.Resource       = ObservationOne;
            ObservationOneEntry.Request        = new Bundle.RequestComponent();
            ObservationOneEntry.Request.Method = Bundle.HTTPVerb.POST;
            ObservationOneEntry.Request.Url    = ResourceType.Observation.GetLiteral();

            //Patient Two Entry
            var PatientTwoEntry = new Bundle.EntryComponent();

            TransBundleIfNoneExsists.Entry.Add(PatientTwoEntry);
            PatientTwoEntry.FullUrl             = CreateFullUrlUUID(Guid.NewGuid().ToString());
            PatientTwoEntry.Resource            = PatientTwo;
            PatientTwoEntry.Request             = new Bundle.RequestComponent();
            PatientTwoEntry.Request.Method      = Bundle.HTTPVerb.POST;
            PatientTwoEntry.Request.Url         = ResourceType.Patient.GetLiteral();
            PatientTwoEntry.Request.IfNoneExist = $"identifier={PatientTwoMRNIdentifer}";

            //Observation One Entry
            //Patient One Entry
            var ObservationTwoEntry = new Bundle.EntryComponent();

            TransBundleIfNoneExsists.Entry.Add(ObservationTwoEntry);
            ObservationTwoEntry.FullUrl        = CreateFullUrlUUID(Guid.NewGuid().ToString());
            ObservationTwoEntry.Resource       = ObservationTwo;
            ObservationTwoEntry.Request        = new Bundle.RequestComponent();
            ObservationTwoEntry.Request.Method = Bundle.HTTPVerb.POST;
            ObservationTwoEntry.Request.Url    = ResourceType.Observation.GetLiteral();

            //Act -------------------------------------------------------------------
            Bundle TransactionResult = null;

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

            //Assert ---------------------------------------------------------------
            Assert.True(TransactionResult.Type == Bundle.BundleType.TransactionResponse);
            Assert.AreEqual(TransactionResult.Entry.Count, 4);

            //Patient One
            Assert.AreEqual(TransactionResult.Entry[0].Resource.ResourceType, ResourceType.Patient);
            //Assert.AreSame(TransactionResult.Entry[0].Resource.Id, PatientOneFhirId);
            Assert.AreEqual(TransactionResult.Entry[0].Response.Status, "200 OK");
            Assert.AreEqual(TransactionResult.Entry[0].Response.Etag, "W/\"1\"");

            //Observation One
            Assert.AreEqual(TransactionResult.Entry[1].Resource.ResourceType, ResourceType.Observation);
            Assert.AreEqual(TransactionResult.Entry[1].Response.Status, "201 Created");
            Assert.AreEqual(TransactionResult.Entry[1].Response.Etag, "W/\"1\"");
            if (TransactionResult.Entry[1].Resource is Observation ObsOneResult)
            {
                Assert.AreEqual(ObsOneResult.Code.Coding[0].Code, "ObsOne");
                Assert.AreEqual(ObsOneResult.Subject.Reference, $"{ResourceType.Patient.GetLiteral()}/{PatientOneFhirId}");
            }
            else
            {
                Assert.True(false, "Entry[1] shoudl have been a Observation resource");
            }

            //Patient Two
            Assert.AreEqual(TransactionResult.Entry[2].Resource.ResourceType, ResourceType.Patient);
            Assert.AreEqual(TransactionResult.Entry[2].Response.Status, "201 Created");
            Assert.AreEqual(TransactionResult.Entry[2].Response.Etag, "W/\"1\"");
            string PatientTwoFhirId = string.Empty;

            if (TransactionResult.Entry[2].Resource is Patient PatTwoResult)
            {
                Assert.AreEqual(PatTwoResult.Identifier[0].Value, PatientTwoMRNIdentifer);
                PatientTwoFhirId = PatTwoResult.Id;
            }
            else
            {
                Assert.True(false, "Entry[2] should have been a Patient resource");
            }

            //Observation Two
            Assert.AreEqual(TransactionResult.Entry[3].Resource.ResourceType, ResourceType.Observation);
            Assert.AreEqual(TransactionResult.Entry[3].Response.Status, "201 Created");
            Assert.AreEqual(TransactionResult.Entry[3].Response.Etag, "W/\"1\"");
            if (TransactionResult.Entry[3].Resource is Observation ObsTwoResult)
            {
                Assert.AreEqual(ObsTwoResult.Code.Coding[0].Code, "ObsTwo");
                Assert.AreEqual(ObsTwoResult.Subject.Reference, $"{ResourceType.Patient.GetLiteral()}/{PatientTwoFhirId}");
            }
            else
            {
                Assert.True(false, "Entry[3] should have been a Observation resource");
            }

            CleanUpByIdentifier(ResourceType.Patient);
            CleanUpByIdentifier(ResourceType.Observation);
        }
Esempio n. 4
0
        public ActionResult GenerateResource(Models.CreateResourceViewModel model)
        {
            var prefix     = model.patientPrefix;
            var firstName  = model.patientFirstname;
            var familyName = model.patientFamilyName;
            var gender     = model.patientGender;
            var dob        = model.patientDateOfBirth;

            model.myPatient = new Patient();

            //Patient's Name
            model.patientName         = new HumanName();
            model.patientName.Use     = HumanName.NameUse.Official;
            model.patientName.Prefix  = new string[] { prefix };
            model.patientName.Given   = new string[] { firstName };
            model.patientName.Family  = familyName;
            model.myPatient.Gender    = gender == "Male" ? AdministrativeGender.Male : AdministrativeGender.Female;
            model.myPatient.BirthDate = dob;
            model.myPatient.Name      = new List <HumanName>();
            model.myPatient.Name.Add(model.patientName);

            //Patient Identifier
            model.patientIdentifier        = new Identifier();
            model.patientIdentifier.System = "http://ns.electronichealth.net.au/id/hi/ihi/1.0";
            model.patientIdentifier.Value  = "8003608166690503";
            model.myPatient.Identifier     = new List <Hl7.Fhir.Model.Identifier>();
            model.myPatient.Identifier.Add(model.patientIdentifier);

            //Extensions
            var raceExtension = new Extension();

            raceExtension.Url   = "http://hl7api.sourceforge.net/hapi-fhir/res/raceExt.html";
            raceExtension.Value = new Code {
                Value = "WHITE"
            };

            //raceExtension.AddExtension("http://hl7api.sourceforge.net/hapi-fhir/res/raceExt.html", new FhirDecimal { Value = 1.2M }, true);

            model.myPatient.Extension.Add(raceExtension);

            //Create a client to send to the server at a given endpoint.
            var FhirClient = new Hl7.Fhir.Rest.FhirClient(OpenFHIRUrl);

            try
            {
                //Validating the Patient Resource Model we created against the structure definition on the server
                model.validatePatientResource = FhirClient.ValidateCreate(model.myPatient);

                model.ReturnedPatient = FhirClient.Create <Patient>(model.myPatient);

                FhirJsonSerializer fhirJsonSerializer = new FhirJsonSerializer();

                //Data that we are sending to the server
                string jsonData = fhirJsonSerializer.SerializeToString(model.myPatient);
                model.PatientJsonDataSent = JValue.Parse(jsonData).ToString();

                //Data that we getting from the server
                jsonData = fhirJsonSerializer.SerializeToString(model.ReturnedPatient);
                model.PatientJsonDataRecieved = JValue.Parse(jsonData).ToString();
            }

            catch (FhirOperationException FhirOpExec)
            {
                var response     = FhirOpExec.Outcome;
                var errorDetails = fhirJsonSerializer.SerializeToString(response);
                model.ResourceRawJsonData = JValue.Parse(errorDetails).ToString();
            }
            catch (WebException ex)
            {
                var response = new StreamReader(ex.Response.GetResponseStream()).ReadToEnd();
                var error    = JsonConvert.DeserializeObject(response);
                model.ResourceRawJsonData = error.ToString();
            }

            return(View(model));
        }
Esempio n. 5
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;
        }
Esempio n. 6
0
        public static bool SaveLabObservation(LabObserveration labObs)
        {
            Observation obs = new Observation();

            var patIdentifier = labObs.FHIR_Identifier;

            Hl7.Fhir.Model.Patient patient = new  Hl7.Fhir.Model.Patient();
            var    client = new Hl7.Fhir.Rest.FhirClient(FHIR_EndPoint);
            Bundle bu     = client.Search <Hl7.Fhir.Model.Patient> (new string[]
                                                                    { "identifier=" + patIdentifier });

            foreach (Bundle.EntryComponent entry in bu.Entry)
            {
                string ResourceType = entry.Resource.TypeName;
                if (ResourceType == "Patient")
                {
                    patient = (Patient)entry.Resource;
                    break;
                }
            }

            obs.Subject = new ResourceReference()
            {
                Display   = patient.Name[0].ToString(),
                Reference = "Patient/" + patient.Id
            };

            obs.Effective = new FhirDateTime(DateTimeOffset.Parse(labObs.EffectiveDate.ToString()));

            Quantity quantity = new Quantity()
            {
                Value  = Convert.ToDecimal(labObs.ValueQuantity),
                Code   = labObs.ValueUnit,
                System = "http://unitsofmeasure.org",
                Unit   = labObs.ValueUnit
            };

            obs.Value = quantity;

            //Observation Code
            CodeableConcept ccu = new CodeableConcept();
            Coding          cu  = new Coding("http://loinc.org", labObs.Code);

            ccu.Coding = new List <Coding> {
                cu
            };
            obs.Code = ccu;

            obs.Status = (ObservationStatus)Enum.Parse(typeof(ObservationStatus), labObs.Status);

            Meta md = new Meta();

            md.Profile = new string[] { "urn:" + "http://myorganization.org/StructureDefinition/us-core-patient" };
            obs.Meta   = md;

            String DivNarrative =
                "<div xmlns='http://www.w3.org/1999/xhtml'>" +
                "Code:" + obs.Code.Coding.FirstOrDefault().Code + "<br/>" +
                "Status:" + obs.Status + "<br/>" +
                "</div>";

            obs.Text = new Narrative()
            {
                Status = Narrative.NarrativeStatus.Generated,
                Div    = DivNarrative
            };
            try
            {
                Parameters inParams = new Parameters();
                inParams.Add("resource", obs);

                //Validate the resource

                OperationOutcome val = client.ValidateResource(obs);
                if (val.Errors != 0)
                {
                    return(false);
                }

                //Success : Now save the observation
                Observation ObservationCreated = client.Create <Observation>(obs);
            }
            catch (FhirOperationException)
            {
                return(false);
            }


            return(true);
        }
    public void Test_TokenCaseInCorrect()
    {
      CleanUpByIdentifier(ResourceType.Observation);

      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 an Observation one with an Effective Period 10:00 AM to 11:00 AM 
      FhirDateTime ObsOneEffectiveStart = new FhirDateTime(new DateTimeOffset(2018, 08, 5, 10, 00, 00, new TimeSpan(8, 0, 0)));
      FhirDateTime ObsOneEffectiveEnd = new FhirDateTime(new DateTimeOffset(2018, 08, 5, 11, 00, 00, new TimeSpan(8, 0, 0)));
      string ObsOneResourceId = string.Empty;
      Observation ObsOne = new Observation();
      ObsOne.Identifier = new List<Identifier>(){
         new Identifier()
         {
            System = StaticTestData.TestIdentiferSystem,
            Value = Common.Tools.FhirGuid.FhirGuid.NewFhirGuid()
         }
      };
      ObsOne.Code = new CodeableConcept();
      ObsOne.Code.Coding = new List<Coding>();
      ObsOne.Code.Coding.Add(new Coding()
      {
        System = "http:/mytestcodesystem.com/system",
        Code = "ObsOne"
      });
      var EffectiveObsOnePeriod = new Period();
      EffectiveObsOnePeriod.StartElement = ObsOneEffectiveStart;
      EffectiveObsOnePeriod.EndElement = ObsOneEffectiveEnd;
      ObsOne.Effective = EffectiveObsOnePeriod;

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

      //Add an Observation one with an Effective Period 10:30 AM to 11:30 AM 
      FhirDateTime ObsTwoEffectiveStart = new FhirDateTime(new DateTimeOffset(2018, 08, 5, 10, 30, 00, new TimeSpan(8, 0, 0)));
      FhirDateTime ObsTwoEffectiveEnd = new FhirDateTime(new DateTimeOffset(2018, 08, 5, 11, 30, 00, new TimeSpan(8, 0, 0)));
      string ObsTwoResourceId = string.Empty;
      Observation ObsTwo = new Observation();
      ObsTwo.Identifier = new List<Identifier>(){
         new Identifier()
         {
            System = StaticTestData.TestIdentiferSystem,
            Value = Common.Tools.FhirGuid.FhirGuid.NewFhirGuid()
         }
      };
      ObsTwo.Code = new CodeableConcept();
      ObsTwo.Code.Coding = new List<Coding>();
      ObsTwo.Code.Coding.Add(new Coding()
      {
        System = "http:/mytestcodesystem.com/system",
        Code = "ObsTwo"
      });
      var EffectiveObsTwoPeriod = new Period();
      EffectiveObsTwoPeriod.StartElement = ObsTwoEffectiveStart;
      EffectiveObsTwoPeriod.EndElement = ObsTwoEffectiveEnd;
      ObsTwo.Effective = EffectiveObsTwoPeriod;

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

      //Assert
      var SearchParam = new SearchParams();
      try
      {
        //ObsOne = 10:00 to 11:00
        //ObsTwo = 10:30 to 11:30
        SearchParam.Add("identifier", $"{StaticTestData.TestIdentiferSystem}|");
        SearchParam.Add("code", "http:/mytestcodesystem.com/system|obsone");
        clientFhir.PreferredParameterHandling = SearchParameterHandling.Strict;
        Bundle BundleResult = clientFhir.Search<Observation>(SearchParam);

        //From thr R4 FHIR Spec
        //Note: There are many challenging issues around case senstivity and token searches. 
        //Some code systems are case sensitive(e.g.UCUM) while others are known not to be.For many 
        //code systems, it's ambiguous. Other kinds of values are also ambiguous. When in doubt, servers
        //SHOULD treat tokens in a case-insensitive manner, on the grounds that including undesired data 
        //has less safety implications than excluding desired behavior. Clients SHOULD always use the 
        //correct case when possible, and allow for the server to perform case-insensitive matching.

        //STU3 was a little vage on this point. Trying to conclude case sesativity based on CodeSystem is 
        //a more difficult goal and would slow down searches, do not plan on doing that any time soon.
        Assert.IsNotNull(BundleResult);
        Assert.IsNotNull(BundleResult.Entry);
        Assert.AreEqual(1, BundleResult.Entry.Count);
        Assert.AreEqual(ObsOneResourceId, BundleResult.Entry[0].Resource.Id);
      }
      catch (Exception Exec)
      {
        Assert.True(false, "Exception thrown on resource Search: " + Exec.Message);
      }

      CleanUpByIdentifier(ResourceType.Observation);
    }
    public void Test_TokenCaseCorrect()
    {
      CleanUpByIdentifier(ResourceType.Observation);

      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 an Observation one with an Effective Period 10:00 AM to 11:00 AM 
      FhirDateTime ObsOneEffectiveStart = new FhirDateTime(new DateTimeOffset(2018, 08, 5, 10, 00, 00, new TimeSpan(8, 0, 0)));
      FhirDateTime ObsOneEffectiveEnd = new FhirDateTime(new DateTimeOffset(2018, 08, 5, 11, 00, 00, new TimeSpan(8, 0, 0)));
      string ObsOneResourceId = string.Empty;
      Observation ObsOne = new Observation();
      ObsOne.Identifier = new List<Identifier>(){
         new Identifier()
         {
            System = StaticTestData.TestIdentiferSystem,
            Value = Common.Tools.FhirGuid.FhirGuid.NewFhirGuid()
         }
      };
      ObsOne.Code = new CodeableConcept();
      ObsOne.Code.Coding = new List<Coding>();
      ObsOne.Code.Coding.Add(new Coding()
      {
        System = "http:/mytestcodesystem.com/system",
        Code = "ObsOne"
      });
      var EffectiveObsOnePeriod = new Period();
      EffectiveObsOnePeriod.StartElement = ObsOneEffectiveStart;
      EffectiveObsOnePeriod.EndElement = ObsOneEffectiveEnd;
      ObsOne.Effective = EffectiveObsOnePeriod;

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

      //Add an Observation one with an Effective Period 10:30 AM to 11:30 AM 
      FhirDateTime ObsTwoEffectiveStart = new FhirDateTime(new DateTimeOffset(2018, 08, 5, 10, 30, 00, new TimeSpan(8, 0, 0)));
      FhirDateTime ObsTwoEffectiveEnd = new FhirDateTime(new DateTimeOffset(2018, 08, 5, 11, 30, 00, new TimeSpan(8, 0, 0)));
      string ObsTwoResourceId = string.Empty;
      Observation ObsTwo = new Observation();
      ObsTwo.Identifier = new List<Identifier>(){
         new Identifier()
         {
            System = StaticTestData.TestIdentiferSystem,
            Value = Common.Tools.FhirGuid.FhirGuid.NewFhirGuid()
         }
      };
      ObsTwo.Code = new CodeableConcept();
      ObsTwo.Code.Coding = new List<Coding>();
      ObsTwo.Code.Coding.Add(new Coding()
      {
        System = "http:/mytestcodesystem.com/system",
        Code = "ObsTwo"
      });
      var EffectiveObsTwoPeriod = new Period();
      EffectiveObsTwoPeriod.StartElement = ObsTwoEffectiveStart;
      EffectiveObsTwoPeriod.EndElement = ObsTwoEffectiveEnd;
      ObsTwo.Effective = EffectiveObsTwoPeriod;

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

      //Assert
      var SearchParam = new SearchParams();
      try
      {
        //ObsOne = 10:00 to 11:00
        //ObsTwo = 10:30 to 11:30
        SearchParam.Add("identifier", $"{StaticTestData.TestIdentiferSystem}|");
        SearchParam.Add("code", "http:/mytestcodesystem.com/system|ObsOne");
        clientFhir.PreferredParameterHandling = SearchParameterHandling.Strict;
        Bundle BundleResult = clientFhir.Search<Observation>(SearchParam);

        Assert.IsNotNull(BundleResult);
        Assert.IsNotNull(BundleResult.Entry);
        Assert.AreEqual(1, BundleResult.Entry.Count);
        Assert.AreEqual(ObsOneResourceId, BundleResult.Entry[0].Resource.Id);        
      }
      catch (Exception Exec)
      {
        Assert.True(false, "Exception thrown on resource Search: " + Exec.Message);
      }

      CleanUpByIdentifier(ResourceType.Observation);
    }
    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.");
      }

    }
Esempio n. 10
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);
            }
        }