public void WhenBasicTransactionSubmitted_AllActionsExecuted()
        {
            // Create observation so that we can do the update and create in a transaction
            var updateResource = _fhirClient.Create(_resource);

            updateResource.Comment = "This is an updated resource";

            var transaction = new TransactionBuilder(_fhirClient.Endpoint)
                              .Create(_resource)
                              .Update(updateResource.Id, updateResource);

            var bundle = transaction.ToBundle();

            bundle.Type = Bundle.BundleType.Transaction;

            BundleHelper.CleanEntryRequestUrls(bundle, _fhirClient.Endpoint);

            var transactionResult = _fhirClient.Transaction(bundle);

            Assert.NotNull(transactionResult);
            Assert.Equal(2, transactionResult.Entry.Count);

            var createResult = transactionResult.Entry[0];

            AssertHelper.CheckStatusCode(HttpStatusCode.Created, createResult.Response.Status);

            var updateResult = transactionResult.Entry[1];

            AssertHelper.CheckStatusCode(HttpStatusCode.OK, updateResult.Response.Status);

            AssertHelper.CheckStatusCode(HttpStatusCode.OK, _fhirClient.LastResult.Status);
        }
Exemplo n.º 2
0
        public void CreateAndFullRepresentation()
        {
            FhirClient client = new FhirClient(testEndpoint);

            client.ReturnFullResource = true;       // which is also the default

            var pat = client.Read <Patient>("Patient/example");

            pat.Id = null;
            pat.Identifier.Clear();
            var patC = client.Create <Patient>(pat);

            Assert.IsNotNull(patC);

            client.ReturnFullResource = false;
            patC = client.Create <Patient>(pat);

            Assert.IsNull(patC);

            if (client.LastBody != null)
            {
                var returned = client.LastBodyAsResource;
                Assert.IsTrue(returned is OperationOutcome);
            }
        }
Exemplo n.º 3
0
        public void RequestFullResource()
        {
            var client  = new FhirClient(testEndpoint);
            var minimal = false;

            client.OnBeforeRequest += (object s, BeforeRequestEventArgs e) => e.RawRequest.Headers["Prefer"] = minimal ? "return=minimal" : "return=representation";

            var result = client.Read <Patient>("Patient/example");

            Assert.IsNotNull(result);
            result.Id   = null;
            result.Meta = null;

            client.ReturnFullResource = true;
            minimal = false;
            var posted = client.Create(result);

            Assert.IsNotNull(posted, "Patient example not found");

            minimal = true;     // simulate a server that does not return a body, even if ReturnFullResource = true
            posted  = client.Create(result);
            Assert.IsNotNull(posted, "Did not return a resource, even when ReturnFullResource=true");

            client.ReturnFullResource = false;
            minimal = true;
            posted  = client.Create(result);
            Assert.IsNull(posted);
        }
Exemplo n.º 4
0
        public DomainResource GetObservationForPatient(FhirClient fhirClient)
        {
            Patient patient = new Patient
            {
                Gender = AdministrativeGender.Male,
                Name   = new List <HumanName>
                {
                    new HumanName
                    {
                        Text = "xyz"
                    }
                }
            };

            Patient uploadedPatient = fhirClient.Create(patient);

            var observation = new Observation
            {
                Status  = ObservationStatus.Final,
                Code    = new CodeableConcept("http://loinc.org", "29463-7", "Body weight"),
                Value   = new Quantity(120.00M, "kg"),
                Subject = new ResourceReference($"Patient/{uploadedPatient.Id}")
            };

            return(fhirClient.Create(observation));
        }
Exemplo n.º 5
0
        public void TestFhirCreate()
        {
            Observation observation1 = MockedResources.Observation1;
            Observation observation2 = MockedResources.Observation2;

            var observation1Entry = fhirClient.Create(observation1);
            var observation2Entry = fhirClient.Create(observation2);

            Assert.AreEqual("4", observation1Entry.Id);
            Assert.AreEqual("5", observation2Entry.Id);
            Assert.AreEqual(MockedResources.Observation1.Device.Reference, observation1Entry.Device.Reference);
            Assert.AreEqual(MockedResources.Observation2.Device.Reference, observation2Entry.Device.Reference);
            Assert.AreEqual(MockedResources.Observation1.Code.Coding[0].System, observation1Entry.Code.Coding[0].System);
            Assert.AreEqual(MockedResources.Observation2.Code.Coding[0].System, observation2Entry.Code.Coding[0].System);
        }
        public void TestFhirCreate()
        {
            Device device1 = MockedResources.Device1;
            Device device2 = MockedResources.Device2;

            var device1Entry = fhirClient.Create(device1);
            var device2Entry = fhirClient.Create(device2);

            Assert.AreEqual("4", device1Entry.Id);
            Assert.AreEqual("5", device2Entry.Id);
            Assert.AreEqual(MockedResources.Device1.Model, device1Entry.Model);
            Assert.AreEqual(MockedResources.Device2.Model, device2Entry.Model);
            Assert.AreEqual(MockedResources.Device1.Type.Text, device1Entry.Type.Text);
            Assert.AreEqual(MockedResources.Device2.Type.Text, device2Entry.Type.Text);
        }
        public void TestFhirCreate()
        {
            Patient patient1 = MockedResources.Patient1;
            Patient patient2 = MockedResources.Patient2;

            var patient1Entry = fhirClient.Create(patient1);
            var patient2Entry = fhirClient.Create(patient2);

            Assert.AreEqual("4", patient1Entry.Id);
            Assert.AreEqual("5", patient2Entry.Id);
            Assert.AreEqual(MockedResources.Patient1.BirthDate, patient1Entry.BirthDate);
            Assert.AreEqual(MockedResources.Patient2.BirthDate, patient2Entry.BirthDate);
            Assert.AreEqual(MockedResources.Patient1.Address[0].City, patient1Entry.Address[0].City);
            Assert.AreEqual(MockedResources.Patient2.Address[0].City, patient2Entry.Address[0].City);
        }
        public void Boundary_HL7FHIR_REST()
        {
            var client = new FhirClient("https://aseecest3fhirservice.azurewebsites.net/");

            //var k = new Fhir
            //client.PreferredFormat = ResourceFormat.Unknown;
            // client.UseFormatParam = true; //depends on the sever  format in url or in header (default)
            // client.ReturnFullResource = false; //Give minimal response
            client.Timeout = 120000; // The timeout is set in milliseconds, with a default of 100000

            //var location_A = new Uri("https://vonk.fire.ly/Patient/58689c4c-daf4-450b-a1ca-7c1846bb65b5");
            //var pat_A = client.Read<Patient>(location_A);
            // or
            //var pat_A = client.Read<Patient>("Patient/58689c4c-daf4-450b-a1ca-7c1846bb65b5");
            var pat_A = client.Read <Patient>("Patient/5425b28a-7d57-4edb-9700-58bbecc52fc1");

            //b46b6f29-fb93-4929-a760-ee722cb37f94

            // Read a specific version of a Patient resource with technical id '32' and version id '4'
            //var location_B = new Uri("http://vonk.fire.ly/Patient/32/_history/4");
            //var pat_B = client.Read<Patient>(location_B);
            // or
            //var pat_B = client.Read<Patient>("Patient/32/_history/4");

            var pat_C = makeAPatient();//Go to makeAPAtient at study the code setting up at HL7 FHIR Patient!
            //pat_C.Telecom = pat_A.Telecom;

            //The client.Create call below will throw an exception Hint se error.txt file
            // Your error correcting code
            // goes here !! Requires some knowlegde about Patient class!
            var created_pat = client.Create(pat_C);

            //After succesfully Create, retrive the patient ID from created_pat, and use the ID to retrieve the patient in Postman/AdvancedRESTClient
            //  client.Delete(created_pat);//Clean up the test. Check result in Postman/AdvancedRESTClient
        }
Exemplo n.º 9
0
        public string CreateHl7FHIRBMPObservation(BPMCompleteSequence seqtocreate) //Signature may be changed
        {
            var saveobs = makeABPMObservation(seqtocreate);

            saveobs = client.Create(saveobs);
            return(saveobs.Id);
        }
Exemplo n.º 10
0
        /// <summary>
        /// Create a patient with the specified name
        /// </summary>
        /// <param name="fhirClient"></param>
        /// <param name="familyName"></param>
        /// <param name="givenName"></param>
        static void CreatePatient(
            FhirClient fhirClient,
            string familyName,
            string givenName)
        {
            Patient toCreate = new Patient()
            {
                Name = new List <HumanName>()
                {
                    new HumanName()
                    {
                        Family = familyName,
                        Given  = new List <string>()
                        {
                            givenName,
                        },
                    }
                },
                BirthDateElement = new Date(1970, 01, 01),
            };

            Patient created = fhirClient.Create <Patient>(toCreate);

            System.Console.WriteLine($"Created Patient/{created.Id}");
        }
Exemplo n.º 11
0
 public IActionResult Create(JsonTextModel json = null)
 {
     if (json.JsonText_ != null)
     {
         var parser = new FhirJsonParser();
         try
         {
             var        res      = parser.Parse <Resource>(json.JsonText_);
             FhirClient client   = new FhirClient(url);
             var        resEntry = client.Create(res);
             json.Status_ = JsonTextModel.CREATED;
         }
         catch (Exception e)
         {
             json.Status_ = JsonTextModel.FAILED;
             return(View(json));
         }
     }
     else
     {
         json         = new JsonTextModel();
         json.Status_ = JsonTextModel.CREATING;
     }
     return(View(json));
 }
Exemplo n.º 12
0
        public static Patient CreatePatient(string given, string family, DateTime birthDate)
        {
            Patient patient         = new Patient();
            Patient responsePatient = new Patient();

            //Set patient name
            patient.Name = new List <HumanName>();

            HumanName patientName = new HumanName();

            patientName.Use    = HumanName.NameUse.Official;
            patientName.Prefix = new string[] { "Mr" };

            //Default way using properties to set Given and Family name
            //patientName.Given = new string[] { given };
            //patientName.Family = family;

            //Using methods to sets the Given and Family name
            patientName.WithGiven(given).AndFamily(family);

            patient.Name.Add(patientName);

            //Set patient Identifier
            patient.Identifier = new List <Identifier>();

            Identifier patientIdentifier = new Identifier();

            patientIdentifier.System = "http://someurl.net/not-sure-about-the-value/1.0";
            patientIdentifier.Value  = Guid.NewGuid().ToString();

            patient.Identifier.Add(patientIdentifier);

            //Set patient birth date
            patient.BirthDate = birthDate.ToFhirDate();

            //Set Active Flag
            patient.Active = true;

            try
            {
                LogToFile("Creating Patient");

                LogToFile("Request: ");
                var patientXml = FhirSerializer.SerializeResourceToXml(patient);
                LogToFile(XDocument.Parse(patientXml).ToString());

                FhirClient fhirClient = new FhirClient(FhirClientEndPoint);
                responsePatient = fhirClient.Create(patient);

                LogToFile("Response: ");
                var responsePatientXml = FhirSerializer.SerializeResourceToXml(responsePatient);
                LogToFile(XDocument.Parse(responsePatientXml).ToString());
            }
            catch (Exception ex)
            {
                LogToFile(ex.ToString());
            }

            return(responsePatient);
        }
        //private static string GetData(string url)
        //{
        //    var httpWebRequest = (HttpWebRequest)WebRequest.Create(url);
        //    httpWebRequest.ContentType = "application/json";
        //    httpWebRequest.Accept = "application/json";
        //    httpWebRequest.Method = "GET";

        //    string response;

        //    try
        //    {
        //        HttpWebResponse httpResponse = (HttpWebResponse)httpWebRequest.GetResponse();
        //        using (var streamReader = new StreamReader(httpResponse.GetResponseStream()))
        //        {
        //            response = streamReader.ReadToEnd();
        //            return response;
        //        }
        //    }
        //    catch (FhirOperationException FhirOpExec)
        //    {
        //        throw FhirOpExec;
        //    }
        //    catch (WebException ex)
        //    {
        //        var res = new StreamReader(ex.Response.GetResponseStream()).ReadToEnd();
        //        var json = JsonConvert.DeserializeObject(res);
        //        return json.ToString();
        //    }
        //    catch (Exception GeneralException)
        //    {
        //        throw GeneralException;
        //    }
        //}

        /// <summary>
        /// Converts XML file to FHIR json format and posts to FHIR server
        /// </summary>
        /// <param name="bundle"></param>
        /// <returns></returns>
        public string Post(Bundle bundle)
        {
            string jsonResponse;

            try
            {
                var token = RequestAccessToken();
                fhirClient.PreferredFormat  = ResourceFormat.Json;
                fhirClient.OnBeforeRequest += (object sender, BeforeRequestEventArgs e) =>
                {
                    // Replace with a valid bearer token for this server
                    e.RawRequest.Headers.Add("Authorization", "Bearer " + token.Result.AccessToken);
                };
                var response = fhirClient.Create(bundle);
                jsonResponse = fhirJsonSerializer.SerializeToString(response);
                return(jsonResponse);
            }
            catch (FhirOperationException FhirOpExec)
            {
                var response     = FhirOpExec.Outcome;
                var errorDetails = fhirJsonSerializer.SerializeToString(response);
                jsonResponse = JValue.Parse(errorDetails).ToString();
            }
            catch (WebException ex)
            {
                var response = new StreamReader(ex.Response.GetResponseStream()).ReadToEnd();
                var error    = JsonConvert.DeserializeObject(response);
                jsonResponse = error.ToString();
            }
            return(jsonResponse);
        }
Exemplo n.º 14
0
        public async Task<ActionResult> Register(RegisterViewModel model)
        {
            if(ModelState.IsValid)
            {
                var client = new FhirClient(Constants.HapiFhirServerBase);
                var fhirResult = client.Create(new Hl7.Fhir.Model.Patient() { });
                var user = new ApplicationUser { UserName = model.Email, Email = model.Email, FhirPatientId = fhirResult.Id };
                var result = await UserManager.CreateAsync(user, model.Password);
                if(result.Succeeded)
                {
                    await UserManager.AddToRolesAsync(user.Id, Enum.GetName(typeof(AccountLevel), model.Account_Level));
                    await SignInManager.SignInAsync(user, isPersistent: false, rememberBrowser: false);

                    // For more information on how to enable account confirmation and password reset please visit http://go.microsoft.com/fwlink/?LinkID=320771
                    // Send an email with this link
                    // string code = await UserManager.GenerateEmailConfirmationTokenAsync(user.Id);
                    // var callbackUrl = Url.Action("ConfirmEmail", "Account", new { userId = user.Id, code = code }, protocol: Request.Url.Scheme);
                    // await UserManager.SendEmailAsync(user.Id, "Confirm your account", "Please confirm your account by clicking <a href=\"" + callbackUrl + "\">here</a>");

                    return RedirectToAction("Index", "Home");
                }
                AddErrors(result);
            }
            // If we got this far, something failed, redisplay form
            return View(viewName: "Register");
        }
Exemplo n.º 15
0
        public static Patient CreatePatient()
        {
            var patient = new Patient
            {
                Identifier = new List <Identifier> {
                    new Identifier(Systems.PATIENT_PASSPORT, GetCodeBySystem(Systems.PATIENT_PASSPORT))
                    {
                        Assigner = new ResourceReference
                        {
                            Reference = "Организация 123"
                        }
                    }
                },
                Gender    = AdministrativeGender.Male,
                BirthDate = DateTime.Today.AddYears(-54).ToString(CultureInfo.CurrentCulture),
                Name      = new List <HumanName>
                {
                    new HumanName
                    {
                        Family = new List <string> {
                            "Петров"
                        },
                        Given = new List <string> {
                            "Петр", "Петрович"
                        }
                    }
                }
            };

            return(FhirClient.Create(patient));
        }
Exemplo n.º 16
0
        public async static Task<Tuple<List<Medication>, Hl7.Fhir.Model.Patient>> GetMedicationDetails(string id, ApplicationUserManager userManager)
        {
            Tuple<List<Medication>, Hl7.Fhir.Model.Patient> tup;
            using (var dbcontext = new ApplicationDbContext())
            {
                // Should be FhirID
                var user = await userManager.FindByIdAsync(id);
                if (user == null)
                {
                    return null;
                }

                var client = new FhirClient(Constants.HapiFhirServerBase);
                if (string.IsNullOrWhiteSpace(user.FhirPatientId))
                {
                    var result = client.Create(new Hl7.Fhir.Model.Patient() { });
                    user.FhirPatientId = result.Id;
                    await userManager.UpdateAsync(user);
                }
                var patient = client.Read<Hl7.Fhir.Model.Patient>(Constants.PatientBaseUrl + user.FhirPatientId);
                tup= new Tuple<List<Medication>, Patient>(await EhrBase.GetMedicationDataForPatientAsync(user.FhirPatientId, client), patient);
                return tup;
            }

        }
Exemplo n.º 17
0
        public static Encounter CreateEncounter(Patient patient, Condition condition, Organization orderOrganization)
        {
            var encounter = new Encounter
            {
                Identifier = new List <Identifier>
                {
                    new Identifier(Systems.ORGANIZATIONS, GetCodeBySystem(Systems.ORGANIZATIONS))
                    {
                        Assigner = FhirHelper.CreateReference(orderOrganization)
                    }
                },
                Type = new List <CodeableConcept>
                {
                    new CodeableConcept(Systems.ENCOUNTER_TYPE, GetCodeBySystem(Systems.ENCOUNTER_TYPE))
                },
                Class      = Encounter.EncounterClass.Outpatient,
                Status     = Encounter.EncounterState.Arrived,
                Patient    = FhirHelper.CreateReference(patient),
                Indication = new List <ResourceReference> {
                    new ResourceReference {
                        Reference = condition.Id
                    }
                },
                Reason = new List <CodeableConcept>
                {
                    new CodeableConcept(Systems.REASON_CODE, GetCodeBySystem(Systems.REASON_CODE))
                },
                ServiceProvider = FhirHelper.CreateReference(orderOrganization),
            };

            return(FhirClient.Create(encounter));
        }
Exemplo n.º 18
0
        public void WhenBatchSubmitted_AllActionsExecuted()
        {
            // Create observations so that we can do the update, read, and delete in the batch
            var updateResource = _fhirClient.Create(_resource);
            var readResource   = _fhirClient.Create(_resource);
            var deleteResource = _fhirClient.Create(_resource);

            updateResource.Comment = "This is an updated resource";

            var transaction = new TransactionBuilder(_fhirClient.Endpoint)
                              .Create(_resource)
                              .Read("Observation", readResource.Id)
                              .Delete("Observation", deleteResource.Id)
                              .Update(updateResource.Id, updateResource);

            var bundle = transaction.ToBundle();

            bundle.Type = Bundle.BundleType.Batch;

            BundleHelper.CleanEntryRequestUrls(bundle, _fhirClient.Endpoint);

            var batchResult = _fhirClient.Transaction(bundle);

            Assert.NotNull(batchResult);

            Assert.NotNull(batchResult.Entry);
            Assert.Equal(4, batchResult.Entry.Count);

            var createResult = batchResult.Entry[0];

            AssertHelper.CheckStatusCode(HttpStatusCode.Created, createResult.Response.Status);

            var readResult = batchResult.Entry[1];

            AssertHelper.CheckStatusCode(HttpStatusCode.OK, readResult.Response.Status);

            var deleteResult = batchResult.Entry[2];

            AssertHelper.CheckDeleteStatusCode(deleteResult.Response.Status);

            var updateResult = batchResult.Entry[3];

            AssertHelper.CheckStatusCode(HttpStatusCode.OK, updateResult.Response.Status);

            AssertHelper.CheckStatusCode(HttpStatusCode.OK, _fhirClient.LastResult.Status);
        }
Exemplo n.º 19
0
        public void CreateEditDelete()
        {
            var furore = new Organization
            {
                Name       = "Furore",
                Identifier = new List <Identifier> {
                    new Identifier("http://hl7.org/test/1", "3141")
                },
                Telecom = new List <Contact> {
                    new Contact {
                        System = Contact.ContactSystem.Phone, Value = "+31-20-3467171"
                    }
                }
            };

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

            var fe = client.Create(furore, tags);

            Assert.IsNotNull(furore);
            Assert.IsNotNull(fe);
            Assert.IsNotNull(fe.Id);
            Assert.IsNotNull(fe.SelfLink);
            Assert.AreNotEqual(fe.Id, fe.SelfLink);
            Assert.IsNotNull(fe.Tags);
            Assert.AreEqual(1, fe.Tags.Count());
            Assert.AreEqual(fe.Tags.First(), tags[0]);
            createdTestOrganization = fe.Id;

            fe.Resource.Identifier.Add(new Identifier("http://hl7.org/test/2", "3141592"));

            var fe2 = client.Update(fe);

            Assert.IsNotNull(fe2);
            Assert.AreEqual(fe.Id, fe2.Id);
            Assert.AreNotEqual(fe.SelfLink, fe2.SelfLink);
            Assert.IsNotNull(fe2.Tags);
            Assert.AreEqual(1, fe2.Tags.Count());
            Assert.AreEqual(fe2.Tags.First(), tags[0]);

            client.Delete(fe2.Id);

            try
            {
                fe = client.Read <Organization>(ResourceLocation.GetIdFromResourceId(fe.Id));
                Assert.Fail();
            }
            catch
            {
                Assert.IsTrue(client.LastResponseDetails.Result == HttpStatusCode.Gone);
            }

            Assert.IsNull(fe);
        }
Exemplo n.º 20
0
        public DomainResource GetDataWithConditionCode(FhirClient fhirClient)
        {
            var condition = new Observation
            {
                Status = ObservationStatus.Final,
                Code   = new CodeableConcept("http://snomed.info/sct", "39065001", "Normal metabolizer")
            };

            return(fhirClient.Create(condition));
        }
Exemplo n.º 21
0
        public DomainResource GetDataWithResourceCodableConcept(FhirClient fhirClient)
        {
            Observation observation = new Observation
            {
                Status = ObservationStatus.Final,
                Code   = new CodeableConcept("http://loinc.org", "LA25391-6", "Normal metabolizer"),
                Value  = new CodeableConcept("http://loinc.org", "LA25391-6", "Normal metabolizer")
            };

            return(fhirClient.Create(observation));
        }
Exemplo n.º 22
0
        public static Organization CreateOrganization()
        {
            var organization = new Organization
            {
                Identifier = new List <Identifier>
                {
                    new Identifier(Systems.ORGANIZATIONS, GetCodeBySystem(Systems.ORGANIZATIONS)),
                }
            };

            return(FhirClient.Create(organization));
        }
Exemplo n.º 23
0
            /// <summary>
            /// Notify that an object was created
            /// </summary>
            public void NotifyCreated <TModel>(TModel data) where TModel : IdentifiedData
            {
                try
                {
                    var msgBundle = this.CreateMessageBundle(out Bundle focusBundle);
                    // Convert the data element over
                    (data as IdentifiedData).AddAnnotation(focusBundle);
                    var focalResource = this.ConvertToResource(data);
                    focusBundle.Entry.Add(new Bundle.EntryComponent()
                    {
                        FullUrl  = $"urn:uuid:{data.Key}",
                        Resource = focalResource
                    });

                    // Iterate over the bundle and set the HTTP request option
                    foreach (var entry in focusBundle.Entry)
                    {
                        if (entry.Request == null)
                        {
                            entry.Request = new Bundle.RequestComponent()
                            {
                                Url    = $"{entry.Resource.TypeName}/{entry.Resource.Id}",
                                Method = Bundle.HTTPVerb.POST
                            };
                            entry.Response = new Bundle.ResponseComponent()
                            {
                                Status = "200"
                            };
                        }
                    }

                    m_client.Create(msgBundle);
                }
                catch (Exception e)
                {
                    this.m_tracer.TraceError("Could not send create to {0} for {1} - {2}", this.Endpoint, data, e);
                    throw new DataDispatchException($"Error sending create notification to {this.Endpoint}", e);
                }
            }
Exemplo n.º 24
0
        public string PostMedicationOrder(string patientID, string medicationName)
        {
            //Potential Parameters to pass in:
            //patientID, medicationName, system, and display

            //First we need to create our medication
            Medication medication = new Medication();

            medication.Code = new CodeableConcept("ICD-10", medicationName);

            //Now we need to push this to the server and grab the ID
            var    medicationResource   = fhirClient.Create <Hl7.Fhir.Model.Medication>(medication);
            string medicationResourceID = medicationResource.Id;

            //Create an empty medication order resource and then assign attributes
            Hl7.Fhir.Model.MedicationOrder fhirMedicationOrder = new Hl7.Fhir.Model.MedicationOrder();

            //There is no API for "Reference" in MedicationOrder model, unlike Patient model.
            //You must initialize ResourceReference inline.
            fhirMedicationOrder.Medication = new ResourceReference()
            {
                Reference = fhirClient.Endpoint.OriginalString + "Medication/" + medicationResourceID,
                Display   = "EhrgoHealth"
            };

            //Now associate Medication Order to a Patient
            fhirMedicationOrder.Patient           = new ResourceReference();
            fhirMedicationOrder.Patient.Reference = "Patient/" + patientID;

            //Push the local patient resource to the FHIR Server and expect a newly assigned ID
            var medicationOrderResource = fhirClient.Create <Hl7.Fhir.Model.MedicationOrder>(fhirMedicationOrder);

            //   medicationOrderResource.Medication
            String returnID = "The newly created Medication ID is: ";

            returnID += medicationOrderResource.Id;
            return(returnID);
        }
Exemplo n.º 25
0
        static void Main(string[] args)
        {
            try
            {
                // Create fhir client https://<your box name>.aidbox.app
                var client = new FhirClient("https://tutorial.aidbox.app");

                // Currently Aidbox doesn't support XML format
                // We need explicitly set it to JSON
                client.PreferredFormat = ResourceFormat.Json;

                // Subscribe OnBeforeRequest in order to set authorization header
                client.OnBeforeRequest += Client_OnBeforeRequest;

                // Create sample resource
                var patient = new Patient
                {
                    Name = new List <HumanName>
                    {
                        new HumanName
                        {
                            Given = new List <string> {
                                "John"
                            },
                            Family = "Doe"
                        }
                    }
                };

                // Create sample resource in box
                var newPatient = client.Create(patient);

                // Show identifier of newly created patient
                Console.WriteLine("New patient: {0}", newPatient.Id);

                // Read newly created patient from server
                var readPatient = client.Read <Patient>("Patient/" + newPatient.Id);

                // Show it id, given name and family
                Console.WriteLine("Read patient: {0} {1} {2}", readPatient.Id, readPatient.Name[0].Given.First(), readPatient.Name[0].Family);
            }
            catch (Exception e)
            {
                // Show error is something go wrong
                Console.WriteLine("Something go wrong: {0}", e);
            }

            Console.WriteLine("Press any key to exit");
            Console.ReadKey();
        }
Exemplo n.º 26
0
        public string PostPatient(string name)
        {
            //Create an empty patient resource and then assign attributes
            Hl7.Fhir.Model.Patient fhirPatient = new Hl7.Fhir.Model.Patient();
            fhirPatient.Name.Add(new Hl7.Fhir.Model.HumanName().AndFamily(name));

            //Push the local patient resource to the FHIR Server and expect a newly assigned ID
            var patientResource = fhirClient.Create <Hl7.Fhir.Model.Patient>(fhirPatient);

            String returnID = "The newly created Patient ID is: ";

            returnID += patientResource.Id;
            return(returnID);
        }
Exemplo n.º 27
0
        public Procedure GetProcedureWithBodySite(FhirClient fhirClient)
        {
            Procedure procedure = new Procedure
            {
                Status   = EventStatus.Completed,
                Subject  = new ResourceReference("Patient/example"),
                BodySite = new List <CodeableConcept>
                {
                    new CodeableConcept("http://snomed.info/sct", "272676008", "sample")
                }
            };

            return(fhirClient.Create(procedure));
        }
Exemplo n.º 28
0
        private Uri tryCreatePatient(FhirClient client, ResourceFormat formatIn, string id = null)
        {
            client.PreferredFormat = formatIn;
            ResourceEntry <Patient> created = null;

            Patient demopat = DemoData.GetDemoPatient();

            if (id == null)
            {
                HttpTests.AssertSuccess(client, () => created = client.Create <Patient>(demopat));
            }
            else
            {
                HttpTests.AssertSuccess(client, () => created = client.Create <Patient>(demopat, id));

                var ep = new RestUrl(client.Endpoint);
                if (!ep.IsEndpointFor(created.Id))
                {
                    TestResult.Fail("Location of created resource is not located within server endpoint");
                }

                var rl = new ResourceIdentity(created.Id);
                if (rl.Id != id)
                {
                    TestResult.Fail("Server refused to honor client-assigned id");
                }
            }

            HttpTests.AssertLocationPresentAndValid(client);

            // Create bevat geen response content meer. Terecht verwijderd?:
            // EK: Niet helemaal, er is weliswaar geen data meer gereturned, maar de headers (id, versie, modified) worden
            // nog wel geupdate
            HttpTests.AssertContentLocationValidIfPresent(client);

            return(created.SelfLink);
        }
Exemplo n.º 29
0
        public void CreateEditDelete()
        {
            var furore = new Organization
            {
                Name = "Furore",
                Identifier = new List<Identifier> { new Identifier("http://hl7.org/test/1", "3141") },
                Telecom = new List<Contact> { new Contact { System = Contact.ContactSystem.Phone, Value = "+31-20-3467171" } }
            };

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

            var fe = client.Create(furore,tags);

            Assert.IsNotNull(furore);
            Assert.IsNotNull(fe);
            Assert.IsNotNull(fe.Id);
            Assert.IsNotNull(fe.SelfLink);
            Assert.AreNotEqual(fe.Id,fe.SelfLink);
            Assert.IsNotNull(fe.Tags);
            Assert.AreEqual(1, fe.Tags.Count());
            Assert.AreEqual(fe.Tags.First(), tags[0]);
            createdTestOrganization = fe.Id;

            fe.Resource.Identifier.Add(new Identifier("http://hl7.org/test/2", "3141592"));

            var fe2 = client.Update(fe);

            Assert.IsNotNull(fe2);
            Assert.AreEqual(fe.Id, fe2.Id);
            Assert.AreNotEqual(fe.SelfLink, fe2.SelfLink);
            Assert.IsNotNull(fe2.Tags);
            Assert.AreEqual(1, fe2.Tags.Count());
            Assert.AreEqual(fe2.Tags.First(), tags[0]);

            client.Delete(fe2.Id);

            try
            {
                fe = client.Read<Organization>(ResourceLocation.GetIdFromResourceId(fe.Id));
                Assert.Fail();
            }
            catch
            {
                Assert.IsTrue(client.LastResponseDetails.Result == HttpStatusCode.Gone);
            }

            Assert.IsNull(fe);
        }
Exemplo n.º 30
0
        public DomainResource GetConditionToSearchViaContent(FhirClient fhirClient)
        {
            var condition = new Condition
            {
                Text = new Narrative
                {
                    Status = Narrative.NarrativeStatus.Generated,
                    Div    = "<div xmlns=\"http://www.w3.org/1999/xhtml\">bone</div>"
                },
                ClinicalStatus = Condition.ConditionClinicalStatusCodes.Active,
                Subject        = new ResourceReference("Patient/example")
            };

            return(fhirClient.Create(condition));
        }
Exemplo n.º 31
0
        public void AddPatient(string firstName, string lastName, bool isMale = true, string birthDate = "01-01-1990", string idVal = "000-00-0000")
        {
            var pat = new Patient();

            var id = new Identifier();

            id.System = "http://hl7.org/fhir/sid/us-ssn";
            id.Value  = idVal;
            pat.Identifier.Add(id);

            var name = new HumanName().WithGiven(firstName).AndFamily(lastName);

            name.Prefix = new string[] { isMale ? "Mr." : "Mrs." };
            name.Use    = HumanName.NameUse.Official;

            pat.Name.Add(name);

            pat.Gender = isMale ? AdministrativeGender.Male : AdministrativeGender.Female;

            pat.BirthDate = birthDate;

            pat.Deceased = new FhirBoolean(false);
            client.Create(pat);
        }
Exemplo n.º 32
0
        public void CreateAndFullRepresentation()
        {
            FhirClient client = new FhirClient(testEndpoint);

            client.ReturnFullResource = true;       // which is also the default

            var pat             = client.Read <Patient>("Patient/example");
            ResourceIdentity ri = pat.ResourceIdentity().WithBase(client.Endpoint);

            pat.Id = null;
            pat.Identifier.Clear();
            var patC = client.Create <Patient>(pat);

            Assert.IsNotNull(patC);

            client.ReturnFullResource = false;
            patC = client.Create <Patient>(pat);

            Assert.IsNull(patC);

            if (client.LastBody != null)
            {
                var returned = client.LastBodyAsResource;
                Assert.IsTrue(returned is OperationOutcome);
            }

            // Now validate this resource
            client.ReturnFullResource = true;       // which is also the default
            Parameters p = new Parameters();

            //  p.Add("mode", new FhirString("create"));
            p.Add("resource", pat);
            OperationOutcome ooI = (OperationOutcome)client.InstanceOperation(ri.WithoutVersion(), "validate", p);

            Assert.IsNotNull(ooI);
        }
Exemplo n.º 33
0
        public DomainResource GetAllergyWithCategory(FhirClient fhirClient)
        {
            AllergyIntolerance allergyIntolerance = new AllergyIntolerance
            {
                ClinicalStatus     = AllergyIntolerance.AllergyIntoleranceClinicalStatus.Active,
                VerificationStatus = AllergyIntolerance.AllergyIntoleranceVerificationStatus.Confirmed,
                Patient            = new ResourceReference("Patient/example"),
                Category           = new List <AllergyIntolerance.AllergyIntoleranceCategory?>
                {
                    AllergyIntolerance.AllergyIntoleranceCategory.Food
                }
            };

            return(fhirClient.Create(allergyIntolerance));
        }
Exemplo n.º 34
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!";
        }
Exemplo n.º 35
0
        public void CreateDynamic()
        {
            Resource furore = new Organization
            {
                Name = "Furore",
                Identifier = new List<Identifier> { new Identifier("http://hl7.org/test/1", "3141") },
                Telecom = new List<ContactPoint> { 
                    new ContactPoint { System = ContactPoint.ContactPointSystem.Phone, Value = "+31-20-3467171", Use = ContactPoint.ContactPointUse.Work },
                    new ContactPoint { System = ContactPoint.ContactPointSystem.Fax, Value = "+31-20-3467172" } 
                }
            };

            FhirClient client = new FhirClient(testEndpoint);

            var fe = client.Create(furore);
            Assert.IsNotNull(fe);
        }
Exemplo n.º 36
0
        public void ManipulateMeta()
        {
           FhirClient client = new FhirClient(testEndpoint);
           var pat = FhirParser.ParseResourceFromXml(File.ReadAllText(@"TestData\TestPatient.xml"));
           var key = new Random().Next();
           pat.Id = "NetApiMetaTestPatient" + key;

           var meta = new Meta();
           meta.ProfileElement.Add(new FhirUri("http://someserver.org/fhir/Profile/XYZ1-" + key));
           meta.Security.Add(new Coding("http://mysystem.com/sec", "1234-" + key));
           meta.Tag.Add(new Coding("http://mysystem.com/tag", "sometag1-" + key));
           pat.Meta = meta;

          //Before we begin, ensure that our new tags are not actually used when doing System Meta()
          var wsm = client.Meta();
          Assert.IsFalse(wsm.Meta.Profile.Contains("http://someserver.org/fhir/Profile/XYZ1-" + key));
          Assert.IsFalse(wsm.Meta.Security.Select(c => c.Code + "@" + c.System).Contains("1234-" + key + "@http://mysystem.com/sec"));
          Assert.IsFalse(wsm.Meta.Tag.Select(c => c.Code + "@" + c.System).Contains("sometag1-" + key + "@http://mysystem.com/tag"));

          Assert.IsFalse(wsm.Meta.Profile.Contains("http://someserver.org/fhir/Profile/XYZ2-" + key));
          Assert.IsFalse(wsm.Meta.Security.Select(c => c.Code + "@" + c.System).Contains("5678-" + key + "@http://mysystem.com/sec"));
          Assert.IsFalse(wsm.Meta.Tag.Select(c => c.Code + "@" + c.System).Contains("sometag2-" + key + "@http://mysystem.com/tag"));


          // First, create a patient with the first set of meta
          var pat2 = client.Create(pat);
          var loc = pat2.ResourceIdentity(testEndpoint);          

          // Meta should be present on created patient
          verifyMeta(pat2.Meta, false,key);

          // Should be present when doing instance Meta()
          var par = client.Meta(loc);
          verifyMeta(par.Meta, false,key);

          // Should be present when doing type Meta()
          par = client.Meta(ResourceType.Patient);
          verifyMeta(par.Meta, false,key);

          // Should be present when doing System Meta()
          par = client.Meta();
          verifyMeta(par.Meta, false,key);

          // Now add some additional meta to the patient

          var newMeta = new Meta();
          newMeta.ProfileElement.Add(new FhirUri("http://someserver.org/fhir/Profile/XYZ2-" + key));
          newMeta.Security.Add(new Coding("http://mysystem.com/sec", "5678-" + key));
          newMeta.Tag.Add(new Coding("http://mysystem.com/tag", "sometag2-" + key));       

          
          client.AddMeta(loc, newMeta);
          var pat3 = client.Read<Patient>(loc);

          // New and old meta should be present on instance
          verifyMeta(pat3.Meta, true, key);

          // New and old meta should be present on Meta()
          par = client.Meta(loc);
          verifyMeta(par.Meta, true, key);

          // New and old meta should be present when doing type Meta()
          par = client.Meta(ResourceType.Patient);
          verifyMeta(par.Meta, true, key);

          // New and old meta should be present when doing system Meta()
          par = client.Meta();
          verifyMeta(par.Meta, true, key);

          // Now, remove those new meta tags
          client.DeleteMeta(loc, newMeta);

          // Should no longer be present on instance
          var pat4 = client.Read<Patient>(loc);
          verifyMeta(pat4.Meta, false, key);

          // Should no longer be present when doing instance Meta()
          par = client.Meta(loc);
          verifyMeta(par.Meta, false, key);

          // Should no longer be present when doing type Meta()
          par = client.Meta(ResourceType.Patient);
          verifyMeta(par.Meta, false, key);

          // clear out the client that we created, no point keeping it around
          client.Delete(pat4);

          // Should no longer be present when doing System Meta()
          par = client.Meta();
          verifyMeta(par.Meta, false, key);
        }
Exemplo n.º 37
0
        public void CreateEditDelete()
        {
            var pat = (Patient)FhirParser.ParseResourceFromXml(File.ReadAllText(@"TestData\TestPatient.xml"));
            var key = new Random().Next();
            pat.Id = "NetApiCRUDTestPatient" + key;

            FhirClient client = new FhirClient(testEndpoint);

            var fe = client.Create(pat);
            Assert.IsNotNull(fe);
            Assert.IsNotNull(fe.Id);
            Assert.IsNotNull(fe.Meta.VersionId);
            createdTestPatientUrl = fe.ResourceIdentity();

            fe.Identifier.Add(new Identifier("http://hl7.org/test/2", "3141592"));
            var fe2 = client.Update(fe);

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

            fe.Identifier.Add(new Identifier("http://hl7.org/test/3", "3141592"));
            var fe3 = client.Update(fe);
            Assert.IsNotNull(fe3);
            Assert.AreEqual(3, fe3.Identifier.Count);

            client.Delete(fe3);

            try
            {
                // Get most recent version
                fe = client.Read<Patient>(fe.ResourceIdentity().WithoutVersion());
                Assert.Fail();
            }
            catch
            {
                Assert.IsTrue(client.LastResult.Status == HttpStatusCode.Gone.ToString());
            }
        }
Exemplo n.º 38
0
        public void RequestFullResource()
        {
            var client = new FhirClient(testEndpoint);
            var minimal = false;
            client.OnBeforeRequest += (object s, BeforeRequestEventArgs e) => e.RawRequest.Headers["Prefer"] = minimal ? "return=minimal" : "return=representation";

            var result = client.Read<Patient>("Patient/example");
            Assert.IsNotNull(result);
            result.Id = null;
            result.Meta = null;

            client.ReturnFullResource = true;
            minimal = false;
            var posted = client.Create(result);
            Assert.IsNotNull(posted, "Patient example not found");

            minimal = true;     // simulate a server that does not return a body, even if ReturnFullResource = true
            posted = client.Create(result);
            Assert.IsNotNull(posted, "Did not return a resource, even when ReturnFullResource=true");

            client.ReturnFullResource = false;
            minimal = true;
            posted = client.Create(result);
            Assert.IsNull(posted);
        }
Exemplo n.º 39
0
        public void CreateEditDelete()
        {
            FhirClient client = new FhirClient(testEndpoint);
            var pat = client.Read<Patient>("Patient/example");
            pat.Id = null;
            pat.Identifier.Clear();
            pat.Identifier.Add(new Identifier("http://hl7.org/test/2", "99999"));

            var fe = client.Create(pat);
            Assert.IsNotNull(fe);
            Assert.IsNotNull(fe.Id);
            Assert.IsNotNull(fe.Meta.VersionId);
            createdTestPatientUrl = fe.ResourceIdentity();

            fe.Identifier.Add(new Identifier("http://hl7.org/test/2", "3141592"));
            var fe2 = client.Update(fe);

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

            fe.Identifier.Add(new Identifier("http://hl7.org/test/3", "3141592"));
            var fe3 = client.Update(fe);
            Assert.IsNotNull(fe3);
            Assert.AreEqual(3, fe3.Identifier.Count);

            client.Delete(fe3);

            try
            {
                // Get most recent version
                fe = client.Read<Patient>(fe.ResourceIdentity().WithoutVersion());
                Assert.Fail();
            }
            catch
            {
                Assert.IsTrue(client.LastResult.Status == "410");
            }
        }
Exemplo n.º 40
0
        public void CreateAndFullRepresentation()
        {
            FhirClient client = new FhirClient(testEndpoint);
            client.ReturnFullResource = true;       // which is also the default

            var pat = client.Read<Patient>("Patient/example");
            pat.Id = null;
            pat.Identifier.Clear();
            var patC = client.Create<Patient>(pat);
            Assert.IsNotNull(patC);

            client.ReturnFullResource = false;
            patC = client.Create<Patient>(pat);

            Assert.IsNull(patC);

            if (client.LastBody != null)
            {
                var returned = client.LastBodyAsResource;
                Assert.IsTrue(returned is OperationOutcome);
            }
        }
Exemplo n.º 41
0
        public static void AddMedicationOrder(string id, string medicationName)
        {
            using (var dbcontext = new ApplicationDbContext())
            {
                var user = dbcontext.Users.FirstOrDefault(a => a.Id == id);
                //todo: I'm not sure about the web portion with regards with what the view should return, I leave
                //      leave that to you, but I left logic to return the medication order ID if you desire. To
                //      show whether the post was successful

                //todo: I do not know where the medicationName will be pulled from, so change harcoded "medicationName"
                //      to the parameter name you expect to use.

                //Full list of Parameters you may also decide to pass in:
                //patientID (done), medicationName, system, and display

                //First let us create the FHIR client
                var fhirClient = new FhirClient(Constants.HapiFhirServerBase);

                //First we need to create our medication
                var medication = new Medication
                {
                    Code = new CodeableConcept("ICD-10", medicationName)
                };

                //Now we need to push this to the server and grab the ID
                var medicationResource = fhirClient.Create<Hl7.Fhir.Model.Medication>(medication);
                var medicationResourceID = medicationResource.Id;

                //Create an empty medication order resource and then assign attributes
                var fhirMedicationOrder = new Hl7.Fhir.Model.MedicationOrder();

                //There is no API for "Reference" in MedicationOrder model, unlike Patient model.
                //You must initialize ResourceReference inline.
                fhirMedicationOrder.Medication = new ResourceReference()
                {
                    Reference = fhirClient.Endpoint.OriginalString + "Medication/" + medicationResourceID,
                    Display = "EhrgoHealth"
                };

                //Now associate Medication Order to a Patient
                fhirMedicationOrder.Patient = new ResourceReference();
                fhirMedicationOrder.Patient.Reference = "Patient/" + user.FhirPatientId;

                //Push the local patient resource to the FHIR Server and expect a newly assigned ID
                var medicationOrderResource = fhirClient.Create<Hl7.Fhir.Model.MedicationOrder>(fhirMedicationOrder);
            }
        }
Exemplo n.º 42
0
        private void button1_Click_2(object sender, EventArgs e)
        {
            var endpoint = new Uri("http://fhirtest.uhn.ca/baseDstu2");
            var client = new FhirClient(endpoint);

            // Create new value for observation
            SampledData val = new SampledData();
            CodeableConcept concept = new CodeableConcept();
            concept.Coding = new List<Coding>();

            if (conversionList.Text.Equals("age")) 
            {
                val.Data = CurrentMeasurement.age.ToString();
                Coding code = new Coding();
                code.Code = "410668003";
                concept.Coding.Add(code);
            }
            else if (conversionList.Text.Equals("bmr")) 
            {
                val.Data = CurrentMeasurement.bmr.ToString();
                Coding code = new Coding();
                code.Code = "60621009";
                concept.Coding.Add(code);
            }
            else if (conversionList.Text.Equals("height")) 
            {
                val.Data = CurrentMeasurement.height.ToString();
                Coding code = new Coding();
                code.Code = "60621009"; //SNOMED CT code
                concept.Coding.Add(code);
            }
            else if (conversionList.Text.Equals("m_active_time")) val.Data = CurrentMeasurement.m_active_time.ToString();
            else if (conversionList.Text.Equals("m_calories")) val.Data = CurrentMeasurement.m_calories.ToString();
            else if (conversionList.Text.Equals("m_distance")) val.Data = CurrentMeasurement.m_distance.ToString();
            else if (conversionList.Text.Equals("m_inactive_time")) val.Data = CurrentMeasurement.m_inactive_time.ToString();
            else if (conversionList.Text.Equals("m_lcat")) val.Data = CurrentMeasurement.m_lcat.ToString();
            else if (conversionList.Text.Equals("m_lcit")) val.Data = CurrentMeasurement.m_lcit.ToString();
            else if (conversionList.Text.Equals("m_steps")) val.Data = CurrentMeasurement.m_steps.ToString();
            else if (conversionList.Text.Equals("m_total_calories")) val.Data = CurrentMeasurement.m_total_calories.ToString();
            else if (conversionList.Text.Equals("s_asleep_time")) val.Data = CurrentMeasurement.s_asleep_time.ToString();
            else if (conversionList.Text.Equals("s_awake")) val.Data = CurrentMeasurement.s_awake.ToString();
            else if (conversionList.Text.Equals("s_awake_time")) val.Data = CurrentMeasurement.s_awake_time.ToString();
            else if (conversionList.Text.Equals("s_awakenings")) val.Data = CurrentMeasurement.s_awakenings.ToString();
            else if (conversionList.Text.Equals("s_bedtime")) val.Data = CurrentMeasurement.s_bedtime.ToString();
            else if (conversionList.Text.Equals("s_clinical_deep")) val.Data = CurrentMeasurement.s_clinical_deep.ToString();
            else if (conversionList.Text.Equals("s_count")) val.Data = CurrentMeasurement.s_count.ToString();
            else if (conversionList.Text.Equals("s_duration")) val.Data = CurrentMeasurement.s_duration.ToString();
            else if (conversionList.Text.Equals("s_light")) val.Data = CurrentMeasurement.s_light.ToString();
            else if (conversionList.Text.Equals("s_quality")) val.Data = CurrentMeasurement.s_quality.ToString();
            else if (conversionList.Text.Equals("s_rem")) val.Data = CurrentMeasurement.s_rem.ToString();
            else if (conversionList.Text.Equals("weight")) val.Data = CurrentMeasurement.weight.ToString();
            else val.Data = "E"; // Error
            

            Console.WriteLine("Value data: " + val.Data);

            ResourceReference dev = new ResourceReference();
            dev.Reference = "Device/" + CurrentDevice.Id;

            ResourceReference pat = new ResourceReference();
            pat.Reference = "Patient/" + CurrentPatient.Id;

            Console.WriteLine("Patient reference: " + pat.Reference);

            Console.WriteLine("Conversion: " + conversionList.Text);

            CodeableConcept naam = new CodeableConcept();
            naam.Text = conversionList.Text;

            DateTime date = DateTime.ParseExact(CurrentMeasurement.date, "yyyymmdd", null);
            Console.WriteLine("" + date.ToString());
            var obs = new Observation() {Device = dev, Subject = pat, Value = val, Issued = date, Code = naam,  Category = concept, Status = Observation.ObservationStatus.Final};
            client.Create(obs);

            conversionStatus.Text = "Done!";
        }
        private Uri tryCreatePatient(FhirClient client, ResourceFormat formatIn, string id = null)
        {
            client.PreferredFormat = formatIn;
            ResourceEntry<Patient> created = null;

            Patient demopat = DemoData.GetDemoPatient();

            if (id == null)
            {
                HttpTests.AssertSuccess(client, () => created = client.Create<Patient>(demopat));
            }
            else
            {
                HttpTests.AssertSuccess(client, () => created = client.Create<Patient>(demopat, id));

                var ep = new RestUrl(client.Endpoint);
                if (!ep.IsEndpointFor(created.Id))
                    TestResult.Fail("Location of created resource is not located within server endpoint");

                var rl = new ResourceIdentity(created.Id);
                if (rl.Id != id)
                    TestResult.Fail("Server refused to honor client-assigned id");
            }
            
            HttpTests.AssertLocationPresentAndValid(client);
            
            // Create bevat geen response content meer. Terecht verwijderd?:
            // EK: Niet helemaal, er is weliswaar geen data meer gereturned, maar de headers (id, versie, modified) worden
            // nog wel geupdate
            HttpTests.AssertContentLocationValidIfPresent(client);

            return created.SelfLink;
        }      
Exemplo n.º 44
0
 //Test for github issue https://github.com/ewoutkramer/fhir-net-api/issues/145
 public void Create_ObservationWithValueAsSimpleQuantity_ReadReturnsValueAsQuantity()
 {
     FhirClient client = new FhirClient(testEndpoint);
     var observation = new Observation();
     observation.Status = Observation.ObservationStatus.Preliminary;
     observation.Code = new CodeableConcept("http://loinc.org", "2164-2");
     observation.Value = new SimpleQuantity()
     {
         System = "http://unitsofmeasure.org",
         Value = 23,
         Code = "mg",
         Unit = "miligram"
     };
     observation.BodySite = new CodeableConcept("http://snomed.info/sct", "182756003");
     var fe = client.Create(observation);
     fe = client.Read<Observation>(fe.ResourceIdentity().WithoutVersion());
     Assert.IsInstanceOfType(fe.Value, typeof(Quantity));
 }
Exemplo n.º 45
0
        public void CreateAndFullRepresentation()
        {
            FhirClient client = new FhirClient(testEndpoint);
            client.ReturnFullResource = true;       // which is also the default

            var pat = client.Read<Patient>("Patient/example");
            ResourceIdentity ri = pat.ResourceIdentity().WithBase(client.Endpoint);
            pat.Id = null;
            pat.Identifier.Clear();
            var patC = client.Create<Patient>(pat);
            Assert.IsNotNull(patC);

            client.ReturnFullResource = false;
            patC = client.Create<Patient>(pat);

            Assert.IsNull(patC);

            if (client.LastBody != null)
            {
                var returned = client.LastBodyAsResource;
                Assert.IsTrue(returned is OperationOutcome);
            }

            // Now validate this resource
            client.ReturnFullResource = true;       // which is also the default
            Parameters p = new Parameters();
          //  p.Add("mode", new FhirString("create"));
            p.Add("resource", pat);
            OperationOutcome ooI = (OperationOutcome)client.InstanceOperation(ri.WithoutVersion(), "validate", p);
            Assert.IsNotNull(ooI);
        }
Exemplo n.º 46
0
        public void CallsCallbacks()
        {
            FhirClient client = new FhirClient(testEndpoint);

            bool calledBefore=false;
            HttpStatusCode? status=null;
            byte[] body = null;
            byte[] bodyOut = null;

            client.OnBeforeRequest += (sender, e) =>
                {
                    calledBefore = true;
                    bodyOut = e.Body;
                };

            client.OnAfterResponse += (sender, e) =>
                {
                    body = e.Body;
                    status = e.RawResponse.StatusCode;
                };

            var pat = client.Read<Patient>("Patient/1");
            Assert.IsTrue(calledBefore);
            Assert.IsNotNull(status);
            Assert.IsNotNull(body);

            var bodyText = HttpToEntryExtensions.DecodeBody(body, Encoding.UTF8);

            Assert.IsTrue(bodyText.Contains("<Patient"));

            calledBefore = false;
            client.Create(pat);
            Assert.IsTrue(calledBefore);
            Assert.IsNotNull(bodyOut);

            bodyText = HttpToEntryExtensions.DecodeBody(body, Encoding.UTF8);
            Assert.IsTrue(bodyText.Contains("<Patient"));

        }
Exemplo n.º 47
0
        // Create a device
        private void btnDeviceCreate_Click(object sender, EventArgs e)
        {
            createDeviceStatus.Text = "Creating...";

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

            var dev = new Device() { Manufacturer = createDeviceManufacturer.Text, Model =  createDeviceModel.Text};
            client.Create(dev);

            createDeviceStatus.Text = "Done!";
        }
Exemplo n.º 48
0
        public void CreateEditDelete()
        {
            var furore = new Organization
            {
                Name = "Furore",
                Identifier = new List<Identifier> { new Identifier("http://hl7.org/test/1", "3141") },
                Telecom = new List<Contact> { new Contact { System = Contact.ContactSystem.Phone, Value = "+31-20-3467171" } }
            };

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

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

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

            fe.Resource.Identifier.Add(new Identifier("http://hl7.org/test/2", "3141592"));
            var fe2 = client.Update(fe, refresh: true);
            
            Assert.IsNotNull(fe2);
            Assert.AreEqual(fe.Id, fe2.Id);
            Assert.AreNotEqual(fe.SelfLink, fe2.SelfLink);
            Assert.AreEqual(2, fe2.Resource.Identifier.Count);

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

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

            client.Delete(fe3);

            try
            {
                // Get most recent version
                fe = client.Read<Organization>(new ResourceIdentity(fe.Id));
                Assert.Fail();
            }
            catch
            {
                Assert.IsTrue(client.LastResponseDetails.Result == HttpStatusCode.Gone);
            }
        }