public void ContainedBaseIsNotAddedToId()
        {
            var p = new Patient() { Id = "jaap" };
            var o = new Observation() { Subject = new ResourceReference() { Reference = "#"+p.Id } };
            o.Contained.Add(p);
            o.ResourceBase = new Uri("http://nu.nl/fhir");

            var xml = FhirSerializer.SerializeResourceToXml(o);
            Assert.IsTrue(xml.Contains("value=\"#jaap\""));

            var o2 = FhirParser.ParseFromXml(xml) as Observation;
            o2.ResourceBase = new Uri("http://nu.nl/fhir");
            xml = FhirSerializer.SerializeResourceToXml(o2);
            Assert.IsTrue(xml.Contains("value=\"#jaap\""));
        }
        public void DetermineCollectionName()
        {
            Patient p = new Patient();

            Assert.AreEqual("patient", ResourceLocation.GetCollectionNameForResource(p));
            Assert.AreEqual("patient", ResourceLocation.GetCollectionNameForResource(p.GetType()));
        }
示例#3
0
        /// <summary>
        /// Metoden finder en patient i HL7-Fhir databasen med det givne PCPR og returnere et patient objekt.
        /// </summary>
        /// <param name="CPR"></param>
        /// <returns></returns>
        public CoreEFTest.Models.Patient GetPatient(string CPR)
        {
            CoreEFTest.Models.Patient patient = null;

            var con = new SearchParams();

            con.Add("identifier", CPR);

            Bundle result = client.Search <Hl7.Fhir.Model.Patient>(con);

            foreach (Bundle.EntryComponent component in result.Entry)
            {
                patient = new CoreEFTest.Models.Patient();
                Hl7.Fhir.Model.Patient Hl7patient = (Hl7.Fhir.Model.Patient)component.Resource;

                patient.CPR      = Hl7patient.Identifier[0].Value;
                patient.Name     = Hl7patient.Name[0].Text;
                patient.Lastname = Hl7patient.Name[0].Family;
                //patient.Age = Convert.ToInt32(Hl7patient.BirthDate);
                patient.Adress  = Hl7patient.Address[0].District;
                patient.City    = Hl7patient.Address[0].City;
                patient.zipcode = Convert.ToInt32(Hl7patient.Address[0].PostalCode);
                break;
            }
            return(patient);
        }
        //STUB PATIENTS;
        #region
        public IEnumerable<Patient> GenerateStubExamples()
        {
            //stub1
            var stub1 = new Patient();
            var name1 = new HumanName();
            name1.Family = new List<string> {"Odenkirk"};
            name1.Given = new List<string> { "Bob" };

            stub1.Name = new List<HumanName> { name1 };
            stub1.Id = "b3tter_c@ll_$@ul";
            stub1.Gender = AdministrativeGender.Male;

            //stub2
            var stub2 = new Patient();
            var name2 = new HumanName();
            name2.Family = new List<string> { "Saggot" };
            name2.Given = new List<string> { "Bob" };

            stub2.Name = new List<HumanName> { name2 };
            stub2.Id = "full_house789";
            stub2.Gender = AdministrativeGender.Male;

            //stub3
            var stub3 = new Patient();
            var name3 = new HumanName();
            name3.Family = new List<string> { "Jones" };
            name3.Given = new List<string> { "Jessica" };

            stub3.Name = new List<HumanName> { name3 };
            stub3.Id = "m@r3lou$";
            stub3.Gender = AdministrativeGender.Female;

            return new List<Patient> { stub1, stub2, stub3};
        }
        // Let's request the conformance statement from the SMART on FHIR API server and
        // find out the endpoint URLs for the authorization server



        //public ActionResult FraminghamCalculator(CernerFullConnectionInformationViewModel cfcivm) //Models.ViewModels.Patient viewPatient)
        public FraminghamCalculatorViewModel FraminghamCalculator(CernerFullConnectionInformationViewModel cfcivm) //Models.ViewModels.Patient viewPatient)

        {
            ViewBag.Message = "Framingham Calculator";


            var client = new FhirClient(cfcivm.ServiceUrl)
            {
                PreferredFormat = ResourceFormat.Json
            };;

            client.OnBeforeRequest += (object sender, BeforeRequestEventArgs e) =>
            {
                e.RawRequest.Headers.Add("Authorization", "Bearer " + cfcivm.AccessToken);
            };


            var identity = ResourceIdentity.Build("Patient", cfcivm.PatientId);

            Hl7.Fhir.Model.Patient viewPatient = client.Read <Hl7.Fhir.Model.Patient>(identity);

            //Get those values we don't know how to retrive yet.
            FraminghamCalculatorPatient Fcp = PhillFCM(0);

            Fcp.LastName  = viewPatient.Name[viewPatient.Name.Count - 1].FamilyElement[0].ToString();
            Fcp.FirstName = viewPatient.Name[viewPatient.Name.Count - 1].GivenElement[0].ToString();
            Fcp.Gender    = viewPatient.Gender.ToString();
            Fcp.Age       = Convert.ToDateTime(viewPatient.BirthDate).Age();


            #region Get HDL
            //Now we get some real data like the HDL
            FraminghamCalculator fc = new FraminghamCalculator(Fcp);
            fc.FhirClient = client;

            string loinc_hdl = "2085-9";
            string loinc_ldl = "13457-7";
            string loinc_Cholesterol_Total = "9830-1";
            string loinc_cholesterol       = "2093-3";
            string loinc_Triglycerides     = "2571-8";
            string loinc_SystolicBP        = "8480-6";
            string loinc_DiastolicBP       = "8462-4";

            BloodPressureValue bpv      = fc.GetLatestBloodPressureValue(cfcivm.PatientId, loinc_SystolicBP);
            CholesterolValue   cv_hdl   = fc.GetLatestCholesterolValue(cfcivm.PatientId, loinc_hdl);
            CholesterolValue   cv_total = fc.GetLatestCholesterolValue(cfcivm.PatientId, loinc_cholesterol);

            #endregion Get HDL

            Fcp.SystolicBP       = (int)bpv.Value;
            Fcp.HDL              = (int)cv_hdl.Value;
            Fcp.TotalCholesterol = (int)cv_total.Value;

            FraminghamCalculatorViewModel vm = new FraminghamCalculatorViewModel();

            vm.FraminghamScore = fc.DoCalculation();
            vm.FCM             = Fcp;

            return(vm);
        }
示例#6
0
 private PatientEntity ConvertFHIREntityToLocal(Patient fhirPatient)
 {
     try
     {
         if ((fhirPatient.Name.FirstOrDefault().Given.First() == string.Empty) ||
             (fhirPatient.Name.FirstOrDefault().Family.First() == string.Empty))
         {
             return(null);
         }
         return(new PatientEntity
         {
             Name = fhirPatient.Name.First().Given.First(),
             FamilyName = fhirPatient.Name.First().Family.First(),
             DateOfBirth = DateTime.Parse(fhirPatient.BirthDate),
             Gender = fhirPatient.Gender == AdministrativeGender.Male
                 ? Gender.Male
                 : fhirPatient.Gender == AdministrativeGender.Female
                     ? Gender.Female
                     : Gender.Other,
             Comments = string.Join(Environment.NewLine, fhirPatient.FhirComments)
         });
     }
     catch (Exception ex)
     {
         return(null);
     }
 }
示例#7
0
        public void Test_Init()
        {
            FHIRbase = new FHIRbaseApi();
            CommonPatient = (Patient) FhirParser.ParseFromJson(File.ReadAllText("Examples/common_patient.json"));

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

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

            SearchPatients = new List<Patient>
            {
                (Patient) FHIRbase.Create(SimplePatient),
                (Patient) FHIRbase.Create(SimplePatient),
                (Patient) FHIRbase.Create(SimplePatient),
                (Patient) FHIRbase.Create(CommonPatient),
                (Patient) FHIRbase.Create(CommonPatient),
                (Patient) FHIRbase.Create(CommonPatient),
                (Patient) FHIRbase.Create(CommonPatient)
            };
        }
        public async Task <NavigateBundle.Model> Handle(NavigateBundle.Query request, CancellationToken cancellationToken)
        {
            //var prayer = client.Operation(new Uri(request.Bundle), "continue");
            var bundle   = client.Continue(request.Bundle, request.Nav);
            var patients = new PatientListModel(
                new List <PatientModel>(),
                bundle.FirstLink?.ToString() != null ? bundle.FirstLink.ToString() : "",
                bundle.LastLink?.ToString() != null ? bundle.LastLink.ToString() : "",
                bundle.NextLink?.ToString() != null ? bundle.NextLink.ToString() : "",
                bundle.PreviousLink?.ToString() != null ? bundle.PreviousLink.ToString() : "",
                bundle.Total ?? 0);

            foreach (var e in bundle.Entry)
            {
                Hl7.Fhir.Model.Patient p = (Hl7.Fhir.Model.Patient)e.Resource;
                patients.Patients.Add(
                    new PatientModel(
                        p.Id, string.Join(" ", p.Name.FirstOrDefault()
                                          .Given), string.Join(" ", p.Name.FirstOrDefault().Family)));
            }


            return(new NavigateBundle.Model()
            {
                Bundle = bundle, Payload = patients
            });
        }
示例#9
0
        public void ExtensionManagement()
        {
            Patient p = new Patient();
            Uri u1 = new Uri("http://fhir.org/ext/ext-test");
            Assert.IsNull(p.GetExtension(u1));

            Extension newEx = p.SetExtension(u1, new FhirBoolean(true));
            Assert.AreSame(newEx, p.GetExtension(u1));

            p.AddExtension(new Uri("http://fhir.org/ext/ext-test2"), new FhirString("Ewout"));
            Assert.AreSame(newEx, p.GetExtension(u1));

            p.RemoveExtension(u1);
            Assert.IsNull(p.GetExtension(u1));

            p.SetExtension(new Uri("http://fhir.org/ext/ext-test2"), new FhirString("Ewout Kramer"));
            var ew = p.GetExtensions(new Uri("http://fhir.org/ext/ext-test2"));
            Assert.AreEqual(1, ew.Count());

            p.AddExtension(new Uri("http://fhir.org/ext/ext-test2"), new FhirString("Wouter Kramer"));

            ew = p.GetExtensions(new Uri("http://fhir.org/ext/ext-test2"));
            Assert.AreEqual(2, ew.Count());

        }
示例#10
0
        public string GetEthnicity(Hl7.Fhir.Model.Patient p)
        {
            string ExtList = "";
            //Extension ComplexEx = p.GetExtension("http://hl7.org/fhir/us/core/StructureDefinition/us-core-ethnicity");
            Extension ComplexEx = p.GetExtension("http://hl7.org/fhir/us/core-r4/StructureDefinition/us-core-ethnicity");

            if (ComplexEx != null)
            {
                foreach (Extension SimpleEx in ComplexEx.Extension)
                {
                    string ExtURL  = SimpleEx.Url;
                    string ExtType = "null";
                    string MyValue = "";

                    if (SimpleEx.Value != null)
                    {
                        ExtType = SimpleEx.Value.TypeName;
                        if (ExtType == "Coding")
                        {
                            Coding c         = (Coding)SimpleEx.Value;
                            string MyCode    = c.Code;
                            string MyDisplay = c.Display;
                            MyValue = MyCode + ":" + MyDisplay;
                            ExtList = ExtList + MyDisplay + " - ";
                        }
                    }
                }
            }

            return(ExtList);
        }
示例#11
0
        public HttpResponseMessage Get(string id)
        {
            HttpResponseMessage response = null;
            string token = "";

            //load Patient and generated a new PIN Code valid for 48 hours
            model.Patient pat = (model.Patient)_client.LoadResource("Patient/" + id);
            if (pat != null)
            {
                var fbid = pat.Identifier.FirstOrDefault(ident => ident.System == "http://fhirbot.org");
                if (fbid != null)
                {
                    pat.Identifier.Remove(fbid);
                }
                Random r       = new Random();
                int    randNum = r.Next(1000000);
                token = randNum.ToString("D6");
                model.Identifier newid = new model.Identifier("http://fhirbot.org", token);
                newid.Period = new model.Period(model.FhirDateTime.Now(), new model.FhirDateTime(DateTimeOffset.Now.AddDays(2)));
                pat.Identifier.Add(newid);
                _client.SaveResource(pat);
                string respval = "{\"token\":\"" + token + "\"}";
                response         = this.Request.CreateResponse(HttpStatusCode.OK);
                response.Content = new StringContent(respval, Encoding.UTF8, "application/json");
            }
            else
            {
                response         = this.Request.CreateResponse(HttpStatusCode.NotFound);
                response.Content = new StringContent("Can't find patient with id " + id, Encoding.UTF8, "text/html");
            }


            return(response);
        }
示例#12
0
文件: Test.cs 项目: TonyAbell/spark
 public static Patient Patient()
 {
     Patient patient = new Patient();
     patient.Id = "patient/1";
     HumanName h = new HumanName().WithGiven("Martijn");
     patient.Name = new List<HumanName>();
     patient.Name.Add(h);
     return patient;
 }
示例#13
0
        /// <summary>
        /// Get all patients of a given Practitioner
        /// </summary>
        /// <param name="practitionerId"></param>
        /// <returns> a list of Patients </returns>
        public static async Task <List <Models.Patient> > GetPatientsOfPractitioner(string practitionerId)
        {
            List <Models.Patient> patientList = new List <Models.Patient>();

            SortedSet <string> patientIdList = new SortedSet <string>();

            try
            {
                var encounterQuery = new SearchParams()
                                     .Where("participant.identifier=http://hl7.org/fhir/sid/us-npi|" + practitionerId)
                                     .Include("Encounter.participant.individual")
                                     .Include("Encounter.patient")
                                     .LimitTo(LIMIT_ENTRY);
                Bundle Result = await Client.SearchAsync <Encounter>(encounterQuery);

                // implement paging for HAPI FHIR API Bundle
                while (Result != null)
                {
                    foreach (var Entry in Result.Entry)
                    {
                        // Get patient id and add to a list
                        Encounter encounter  = (Encounter)Entry.Resource;
                        string    patientRef = encounter.Subject.Reference;
                        string    patientId  = patientRef.Split('/')[1];
                        patientIdList.Add(patientId);
                    }

                    Result = Client.Continue(Result, PageDirection.Next);
                }

                // fetch patient data from the list of patient ids
                foreach (var patientId in patientIdList)
                {
                    Bundle PatientResult = await Client.SearchByIdAsync <Hl7.Fhir.Model.Patient>(patientId);

                    if (PatientResult.Entry.Count > 0)
                    {
                        // Map the FHIR Patient object to App's Patient object
                        Hl7.Fhir.Model.Patient fhirPatient = (Hl7.Fhir.Model.Patient)PatientResult.Entry[0].Resource;
                        PatientMapper          mapper      = new PatientMapper();
                        Models.Patient         patient     = mapper.Map(fhirPatient);
                        patientList.Add(patient);
                    }
                }
            }
            catch (FhirOperationException FhirException)
            {
                System.Diagnostics.Debug.WriteLine("Fhir error message: " + FhirException.Message);
            }
            catch (Exception GeneralException)
            {
                System.Diagnostics.Debug.WriteLine("General error message: " + GeneralException.Message);
            }

            return(patientList);
        }
示例#14
0
        public string GetAddress(Hl7.Fhir.Model.Patient p)
        {
            string ad = "";

            foreach (Address a in p.Address)
            {
                ad = ad + a.LineElement[0].ToString() + " " + a.City + " " + a.State + " " + a.Country + "( " + a.PostalCode + ") / ";
            }
            return(ad);
        }
示例#15
0
        public string GetCity(Hl7.Fhir.Model.Patient p)
        {
            string ci = "";

            if (p.Address.Count > 0)
            {
                ci = p.Address[0].City;
            }
            return(ci);
        }
示例#16
0
        public void TestFhirPathTrace()
        {
            var patient = new Hl7.Fhir.Model.Patient()
            {
                Id = "pat45", Active = false
            };

            patient.Meta = new Meta()
            {
                LastUpdated = new DateTimeOffset(2018, 5, 24, 14, 48, 0, TimeSpan.Zero)
            };
            var nav = patient.ToTypedElement();

            EvaluationContext ctx = new FhirEvaluationContext();
            var result            = nav.Select("Resource.meta.trace('log').lastUpdated", ctx);

            Assert.IsNotNull(result.FirstOrDefault());
            Assert.AreEqual(PartialDateTime.Parse("2018-05-24T14:48:00+00:00"), result.First().Value);

            bool traced = false;

            ctx.Tracer = (string name, System.Collections.Generic.IEnumerable <ITypedElement> results) =>
            {
                System.Diagnostics.Trace.WriteLine($"{name}");
                Assert.AreEqual("log", name);
                foreach (ITypedElement item in results)
                {
                    var fhirValue = item.Annotation <IFhirValueProvider>();
                    System.Diagnostics.Trace.WriteLine($"--({fhirValue.FhirValue.GetType().Name}): {item.Value} {fhirValue.FhirValue}");
                    Assert.AreEqual(patient.Meta, fhirValue.FhirValue);
                    traced = true;
                }
            };
            result = nav.Select("Resource.meta.trace('log').lastUpdated", ctx);
            Assert.IsNotNull(result.FirstOrDefault());
            Assert.AreEqual(PartialDateTime.Parse("2018-05-24T14:48:00+00:00"), result.First().Value);
            Assert.IsTrue(traced);

            traced     = false;
            ctx.Tracer = (string name, System.Collections.Generic.IEnumerable <ITypedElement> results) =>
            {
                System.Diagnostics.Trace.WriteLine($"{name}");
                Assert.IsTrue(name == "id" || name == "log");
                foreach (ITypedElement item in results)
                {
                    var fhirValue = item.Annotation <IFhirValueProvider>();
                    System.Diagnostics.Trace.WriteLine($"--({fhirValue.FhirValue.GetType().Name}): {item.Value} {fhirValue.FhirValue}");
                    traced = true;
                }
            };
            result = nav.Select("Resource.trace('id', id).meta.trace('log', lastUpdated).lastUpdated", ctx);
            Assert.IsNotNull(result.FirstOrDefault());
            Assert.AreEqual(PartialDateTime.Parse("2018-05-24T14:48:00+00:00"), result.First().Value);
            Assert.IsTrue(traced);
        }
示例#17
0
        public static List <FHIR_Patient> find_fhir_patients(string _Url, string _Name)
        {
            var endpoint = new Uri(_Url);
            var client   = new FhirClient(endpoint);

            client.UseFormatParam  = true;
            client.PreferredFormat = ResourceFormat.Json;

            var list_fhir = new List <FHIR_Patient>();

            var query = new string[] { "name=" + _Name };

            try
            {
                var        bundle = client.Search("Patient", query);
                UserAction ua     = new UserAction
                {
                    User            = "******",
                    Action_id       = UserActionCode.External_FHIR_Queried.ToString(),
                    Action_desc     = UserActionDesc[UserActionCode.External_FHIR_Queried],
                    External_source = _Url
                };
                Console.WriteLine("Got " + bundle.Entry.Count() + " records!");
                foreach (var pt in bundle.Entry)
                {
                    Hl7.Fhir.Model.Patient p = (Hl7.Fhir.Model.Patient)pt.Resource;
                    var fc = new FHIR_Patient();
                    fc.External_id     = p.Id;
                    fc.External_source = _Url;
                    fc.LastName        = p.Name.First().Family.FirstOrDefault();
                    fc.FirstName       = p.Name.First().Given.FirstOrDefault();
                    fc.Birthdate       = p.BirthDate.ToString();
                    fc.Gender          = p.Gender.ToString();
                    fc.Address         = "";
                    fc.City            = "";
                    fc.State           = "";
                    fc.Zip             = "";
                    if (p.Address.Count > 0)
                    {
                        fc.Address = p.Address.First().Line.FirstOrDefault();
                        fc.City    = p.Address.First().City;
                        fc.State   = p.Address.First().State;
                        fc.Zip     = p.Address.First().PostalCode;
                    }
                    ;
                    list_fhir.Add(fc);
                }
            }
            catch (Exception exp)
            {
                throw exp;
            }

            return(list_fhir);
        }
示例#18
0
        public void TestAllowedChoices()
        {
            Patient p = new Patient();

            p.Deceased = new FhirBoolean(true);
            FhirValidator.Validate(p);

            // Deceased can either be boolean or dateTime, not FhirUri
            p.Deceased = new FhirUri();
            validateErrorOrFail(p);
        }
示例#19
0
        /// <summary>
        /// Generates an observation (BMI, Hemoglobin, Height or Weight)
        /// </summary>
        /// <param name="observationNumber"></param>
        /// <param name="patient"></param>
        /// <param name="encounter"></param>
        /// <returns></returns>
        public HL7.Observation GenerateObservation(int observationNumber, HL7.Patient patient, int encounter)
        {
            HL7.Observation genObs = new HL7.Observation();

            //give an id
            genObs.Id = observationNumber.ToString();

            //status of the observation
            genObs.Status = HL7.Observation.ObservationStatus.Final;

            //add a code
            int obsType = rand.Next(0, 3);

            switch (obsType)
            {
            case 0:
                genObs.Code  = new HL7.CodeableConcept("http://loinc.org", "3141-9", "Body weight Measured");
                genObs.Value = GenerateWeightValues();
                break;

            case 1:
                genObs.Code  = new HL7.CodeableConcept("http://loinc.org", "8302-2", "Body height");
                genObs.Value = GenerateHeightValues();
                break;

            case 2:
                genObs.Code  = new HL7.CodeableConcept("http://loinc.org", "39156-5", "Body mass index (BMI) [Ratio]");
                genObs.Value = GenerateBMIValues();
                break;

            case 3:
                genObs.Code  = new HL7.CodeableConcept("http://loinc.org", "718-7", "Hemoglobin [Mass/volume] in Blood");
                genObs.Value = GenerateHemoValues();
                break;

            default:
                break;
            }

            //add a patient reference
            HL7.ResourceReference patRefence = new HL7.ResourceReference();
            patRefence.ReferenceElement = new HL7.FhirString("Patient/" + Int32.Parse(patient.Id));
            genObs.Subject = patRefence;

            //add an encounter reference
            HL7.ResourceReference encRefence = new HL7.ResourceReference();
            encRefence.ReferenceElement = new HL7.FhirString("Encounter/" + encounter);
            genObs.Encounter            = encRefence;

            //add observation date
            genObs.Effective = new HL7.FhirDateTime(2015, 04, 1);

            return(genObs);
        }
 //[SprinklerTest("TR10", "Failing data")]
 public void FailingData()
 {
     Patient p = new Patient();
     Identifier item = new Identifier();
     item.Label = "hl7v2";
     item.Value = "PID-55101";
     p.Identifier = new List<Identifier>();
     p.Identifier.Add(item);
     p.BirthDate = "1974-02-20";
     ResourceEntry<Patient> r = client.Create<Patient>(p);
 }
示例#21
0
        public static Patient NewPatient(string family, params string[] given)
        {
            Patient p = new Patient();
            HumanName n = new HumanName();
            foreach (string g in given) { n.WithGiven(g); }

            n.AndFamily(family);
            p.Name = new List<HumanName>();
            p.Name.Add(n);
            return p;
        }
示例#22
0
        public void TestVisitOnePathZeroMatch()
        {
            ElementQuery sut = new ElementQuery("Patient.name");

            Patient testPatient = new Patient();
            var result = new List<Object>() ;

            sut.Visit(testPatient, fd => result.Add(fd));

            Assert.AreEqual(testPatient.Name.Count, result.Where(ob => ob != null).Count());
        }
示例#23
0
 /// <summary>
 /// convert Fhir patient response to Patient view model to display
 /// </summary>
 /// <param name="patient"></param>
 /// <returns></returns>
 private PatientViewModel ConvertFhirToViewModel(FhirModel.Patient patient)
 {
     return(new PatientViewModel()
     {
         Id = Int32.Parse(patient.Id),
         LastName = patient.Name[0].Family,
         FirstName = patient.Name[0].Given.ToList()[0],
         DOB = DateTime.Parse(patient.BirthDate),
         Gender = patient.Gender.Value.ToString(),
         MRN = patient.Identifier.Count > 0 ? patient.Identifier.First(i => i.Type.Coding[0].Code == "MR").Value : ""
     });
 }
示例#24
0
        public void ContainedResourcesAreValidatedToo()
        {
            Patient p = new Patient();
            // Deceased can either be boolean or dateTime, not FhirUri
            p.Deceased = new FhirUri();

            var pr = new Patient();
            pr.Contained = new List<Resource> { p };

            validateErrorOrFail(pr,true);
            FhirValidator.Validate(pr);
        }
示例#25
0
        public Hl7.Fhir.Model.Patient FHIR_SearchByIdentifier(ref Patient_FHIR pf)
        {
            string Identifier = pf.Identifier;

            Hl7.Fhir.Model.Patient patient = new  Hl7.Fhir.Model.Patient();
            var client = new Hl7.Fhir.Rest.FhirClient(FHIR_EndPoint_PatientInfo);

            client.PreferredFormat = ResourceFormat.Json;
            Bundle bu = client.Search <Hl7.Fhir.Model.Patient> (new string[]
                                                                { "identifier=" + Identifier,
                                                                  "_revinclude=AllergyIntolerance:patient",
                                                                  "_revinclude=Condition:subject",
                                                                  "_revinclude=MedicationRequest:subject",
                                                                  "_revinclude=Immunization:patient",
                                                                  "_revinclude=CarePlan:subject" });

            foreach (Bundle.EntryComponent entry in bu.Entry)
            {
                string ResourceType = entry.Resource.TypeName;
                if (ResourceType == "Patient")
                {
                    patient = (Patient)entry.Resource;
                }
                else if (ResourceType == "AllergyIntolerance")
                {
                    var allergy = (AllergyIntolerance)entry.Resource;
                    pf.Allergies.Add(allergy);
                }
                else if (ResourceType == "Condition")
                {
                    var condition = (Condition)entry.Resource;
                    pf.Conditions.Add(condition);
                }
                else if (ResourceType == "MedicationRequest")
                {
                    var medication = (MedicationRequest)entry.Resource;
                    pf.Medications.Add(medication);
                }
                else if (ResourceType == "Immunization")
                {
                    var immunization = (Immunization)entry.Resource;
                    pf.Immunizations.Add(immunization);
                }
                else if (ResourceType == "CarePlan")
                {
                    var careplan = (CarePlan)entry.Resource;
                    pf.CarePlans.Add(careplan);
                }
            }
            return(patient);
        }
示例#26
0
 private static void AddTaggedPatient()
 {
     IFhirStore store = Spark.Store.MongoStoreFactory.GetMongoFhirStore();
     var patient = new Patient();
     patient.Id = "Patient/tagged";
     patient.Name = new List<HumanName>();
     patient.Name.Add(new HumanName() {Given = new string[]{"Truus"}, Family = new string[]{"Tagged"}});
     ResourceEntry patientRE = ResourceEntry.Create(patient);
     patientRE.Id = new Uri("Patient/tagged", UriKind.Relative);
     patientRE.SelfLink = new Uri("Patient/tagged", UriKind.Relative);
     patientRE.Tags.Add(new Tag(_otherTag, Tag.FHIRTAGSCHEME_GENERAL, "dummy"));
     var storedPatient = store.AddEntry(patientRE);
     index.Process(storedPatient);
 }
        public void TestSummary()
        {
            var p = new Patient();

            p.BirthDate = "1972-11-30";     // present in both summary and full
            p.Photo = new List<Attachment>() { new Attachment() { ContentType = "text/plain" } };

            var full = FhirSerializer.SerializeResourceToXml(p);
            Assert.IsTrue(full.Contains("<birthDate"));
            Assert.IsTrue(full.Contains("<photo"));

            var summ = FhirSerializer.SerializeResourceToXml(p, summary: true);
            Assert.IsTrue(summ.Contains("<birthDate"));
            Assert.IsFalse(summ.Contains("<photo"));
        }
示例#28
0
        public void TestVisitOnePathOneMatch()
        {
            ElementQuery sut = new ElementQuery("Patient.name");

            Patient testPatient = new Patient();
            var hn = new HumanName().WithGiven("Sjors").AndFamily("Jansen");
            testPatient.Name = new List<HumanName> { hn };

            var result = new List<Object>();

            sut.Visit(testPatient, fd => result.Add(fd));

            Assert.AreEqual(testPatient.Name.Count, result.Where(ob => ob != null).Count());
            Assert.IsTrue(result.Contains(hn));
        }
        public void FindContainedResource()
        {
            var cPat1 = new Patient() { Id = "pat1" };
            var cPat2 = new Patient() { Id = "pat2" };
            var pat = new Patient();

            pat.Contained = new List<Resource> { cPat1, cPat2 };

            var rref = new ResourceReference() { Reference = "#pat2" };

            Assert.IsNotNull(pat.FindContainedResource(rref));
            Assert.IsNotNull(pat.FindContainedResource(rref.Url));

            rref.Reference = "#pat3";
            Assert.IsNull(pat.FindContainedResource(rref));
        }
示例#30
0
        public void TestVisitOnePathTwoMatches()
        {
            ElementQuery sut = new ElementQuery("Patient.name");

            Patient testPatient = new Patient();
            var hn1 = new HumanName().WithGiven("A").AndFamily("B");
            var hn2 = new HumanName().WithGiven("Y").AndFamily("Z");
            testPatient.Name = new List<HumanName> { hn1, hn2 };

            var result = new List<Object>();

            sut.Visit(testPatient, fd => result.Add(fd));

            Assert.AreEqual(testPatient.Name.Count, result.Where(ob => ob != null).Count());
            Assert.IsTrue(result.Contains(hn1));
            Assert.IsTrue(result.Contains(hn2));
        }
示例#31
0
        public void TestFhirPathPolymporphism()
        {
            var patient = new Hl7.Fhir.Model.Patient()
            {
                Active = false
            };

            patient.Meta = new Meta()
            {
                LastUpdated = new DateTimeOffset(2018, 5, 24, 14, 48, 0, TimeSpan.Zero)
            };
            var nav = new PocoNavigator(patient);

            var result = nav.Select("Resource.meta.lastUpdated");

            Assert.IsNotNull(result.FirstOrDefault());
            Assert.AreEqual(PartialDateTime.Parse("2018-05-24T14:48:00+00:00"), result.First().Value);
        }
示例#32
0
        public void TestIndexResourceSimple()
        {
            var patient = new Patient();
            patient.Name.Add(new HumanName().WithGiven("Adriaan").AndFamily("Bestevaer"));

            IKey patientKey = new Key("http://localhost/", "Patient", "001", "v02");

            IndexValue result = sutLimited.IndexResource(patient, patientKey);

            Assert.AreEqual("root", result.Name);
            Assert.AreEqual(5, result.Values.Count, "Expected 1 result for searchparameter 'name' and 4 for meta info");
            Assert.IsInstanceOfType(result.Values[0], typeof(IndexValue));
            var first = (IndexValue)result.Values[0];
            Assert.AreEqual("name", first.Name);
            Assert.AreEqual(2, first.Values.Count);
            Assert.IsInstanceOfType(first.Values[0], typeof(StringValue));
            Assert.IsInstanceOfType(first.Values[1], typeof(StringValue));
        }
示例#33
0
        public void AvoidBOMUse()
        {
            Bundle b = new Bundle();

            var data = FhirSerializer.SerializeResourceToJsonBytes(b);
            Assert.IsFalse(data[0] == Encoding.UTF8.GetPreamble()[0]);

            data = FhirSerializer.SerializeResourceToXmlBytes(b);
            Assert.IsFalse(data[0] == Encoding.UTF8.GetPreamble()[0]);

            Patient p = new Patient();

            data = FhirSerializer.SerializeResourceToJsonBytes(p);
            Assert.IsFalse(data[0] == Encoding.UTF8.GetPreamble()[0]);

            data = FhirSerializer.SerializeResourceToXmlBytes(p);
            Assert.IsFalse(data[0] == Encoding.UTF8.GetPreamble()[0]);
        }
        public async Task <string> AddPatientAsync(PatientCreateRequest patient)
        {
            try
            {
                var newpa = new Hl7.Fhir.Model.Patient()
                {
                    Active    = true,
                    BirthDate = patient.DateOfBirth?.ToString("yyyy-MM-dd", System.Globalization.CultureInfo.InvariantCulture),

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

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

                return(result.Id);
            }
            catch (Exception ex)
            {
                return(null);
            }
        }
        public async void GivenDeviceNotFoundExceptionWithDeviceSystemSet_WhenResolveResourceIdentitiesAsync_ThenDeviceAndPatientCreateInvokedWithDeviceSystemAndIdsReturned_Test()
        {
            var fhirClient      = Substitute.For <IFhirClient>();
            var resourceService = Substitute.For <ResourceManagementService>();

            var device = new Model.Device
            {
                Id      = "1",
                Patient = new Model.ResourceReference("Patient/123"),
            };

            var patient = new Model.Patient
            {
                Id = "123",
            };

            resourceService.EnsureResourceByIdentityAsync <Model.Device>(null, null, null, null).ReturnsForAnyArgs(Task.FromResult(device));
            resourceService.EnsureResourceByIdentityAsync <Model.Patient>(null, null, null, null).ReturnsForAnyArgs(Task.FromResult(patient));

            var mg = Substitute.For <IMeasurementGroup>();

            mg.DeviceId.Returns("deviceId");
            mg.PatientId.Returns("patientId");

            resourceService.GetResourceByIdentityAsync <Model.Device>(Arg.Any <IFhirClient>(), Arg.Any <string>(), Arg.Any <string>())
            .Returns(Task.FromException <Model.Device>(new FhirResourceNotFoundException(ResourceType.Device)));

            using (var idSrv = new R4DeviceAndPatientCreateIdentityService(fhirClient, resourceService))
            {
                idSrv.Initialize(new ResourceIdentityOptions {
                    DefaultDeviceIdentifierSystem = "mySystem"
                });
                var ids = await idSrv.ResolveResourceIdentitiesAsync(mg);

                Assert.Equal("1", ids[ResourceType.Device]);
                Assert.Equal("123", ids[ResourceType.Patient]);
            }

            await resourceService.Received(1).GetResourceByIdentityAsync <Model.Device>(fhirClient, "deviceId", "mySystem");

            await resourceService.Received(1).EnsureResourceByIdentityAsync <Model.Device>(fhirClient, "deviceId", "mySystem", Arg.Any <Action <Model.Device, Model.Identifier> >());

            await resourceService.Received(1).EnsureResourceByIdentityAsync <Model.Patient>(fhirClient, "patientId", null, Arg.Any <Action <Model.Patient, Model.Identifier> >());
        }
        public async void GivenIdNotFoundExceptionWithNoPatientId_WhenResolveResourceIdentitiesAsync_ThenResourceIdentityNotDefinedExceptionThrown_Test(string value)
        {
            var fhirClient      = Substitute.For <IFhirClient>();
            var resourceService = Substitute.For <ResourceManagementService>();

            var device = new Model.Device
            {
                Id      = "1",
                Patient = new Model.ResourceReference("Patient/123"),
            };

            var patient = new Model.Patient
            {
                Id = "123",
            };

            var createService = Substitute.For <ResourceManagementService>();

            resourceService.EnsureResourceByIdentityAsync <Model.Device>(null, null, null, null).ReturnsForAnyArgs(Task.FromResult(device));
            resourceService.EnsureResourceByIdentityAsync <Model.Patient>(null, null, null, null).ReturnsForAnyArgs(Task.FromResult(patient));

            var mg = Substitute.For <IMeasurementGroup>();

            mg.DeviceId.Returns("deviceId");
            mg.PatientId.Returns(value);

            resourceService.GetResourceByIdentityAsync <Model.Device>(Arg.Any <IFhirClient>(), Arg.Any <string>(), Arg.Any <string>())
            .Returns(Task.FromException <Model.Device>(new FhirResourceNotFoundException(ResourceType.Patient)));

            using (var idSrv = new R4DeviceAndPatientCreateIdentityService(fhirClient, resourceService))
            {
                var ex = await Assert.ThrowsAsync <ResourceIdentityNotDefinedException>(() => idSrv.ResolveResourceIdentitiesAsync(mg));

                Assert.Equal(ResourceType.Patient, ex.FhirResourceType);
            }

            await resourceService.Received(1).GetResourceByIdentityAsync <Model.Device>(fhirClient, "deviceId", null);

            await resourceService.DidNotReceiveWithAnyArgs().EnsureResourceByIdentityAsync <Model.Device>(null, null, null, null);

            await resourceService.DidNotReceiveWithAnyArgs().EnsureResourceByIdentityAsync <Model.Patient>(null, null, null, null);
        }
示例#37
0
        /// <summary>
        /// Generates a HL7 Patient class
        /// </summary>
        /// <param name="patientNumber"></param>
        /// <param name="practitioner"></param>
        /// <param name="state"></param>
        /// <param name="district"></param>
        /// <param name="postalCode"></param>
        /// <returns></returns>
        public HL7.Patient GeneratePatient(int patientNumber, int practitioner, string state, string district, string postalCode)
        {
            HL7.Patient genPat = new HL7.Patient();

            //give an id
            genPat.Id = patientNumber.ToString();

            ////give a name
            HL7.HumanName hName = new HL7.HumanName();
            hName.FamilyElement.Add(new HL7.FhirString("TESTLAST"));
            hName.GivenElement.Add(new HL7.FhirString("TESTFIRST"));
            genPat.Name.Add(hName);

            //add a care provider so we can filter for doctor facing app
            HL7.ResourceReference practRef = new HL7.ResourceReference();
            practRef.ReferenceElement = new HL7.FhirString("Practitioner/" + practitioner);
            genPat.CareProvider.Add(practRef);

            //give an address
            HL7.Address address = new HL7.Address();
            address.Use = HL7.Address.AddressUse.Home;
            address.LineElement.Add(new HL7.FhirString("123 Fake Street"));
            address.City       = "FAKETOWN";
            address.District   = district;
            address.State      = state;
            address.PostalCode = postalCode;
            genPat.Address.Add(address);

            //give a gender
            genPat.Gender = (rand.NextDouble() < .5) ? HL7.AdministrativeGender.Female : HL7.AdministrativeGender.Male;

            //give a DOB
            //randomly generate based on age range 0 - 17
            int      years = Convert.ToInt32(Math.Round(16 * rand.NextDouble())) + 1;
            int      days  = Convert.ToInt32(Math.Round(364 * rand.NextDouble()));
            DateTime dob   = new DateTime(2016 - years, 01, 01).AddDays(days);

            HL7.Date hl7DOB = new HL7.Date(dob.ToShortDateString());
            genPat.BirthDateElement = hl7DOB;

            return(genPat);
        }
示例#38
0
        public string GetEmail(Hl7.Fhir.Model.Patient p)
        {
            string te = "";

            foreach (ContactPoint c in p.Telecom)
            {
                if (c.System == ContactPointSystem.Email)
                {
                    if (string.IsNullOrEmpty(te))
                    {
                        te = c.Value + " (" + c.Use + ") ";
                    }
                    else
                    {
                        te = te + ", " + c.Value + " (" + c.Use + ") ";
                    }
                }
            }
            return(te);
        }
        public async void GivenMismatchedDeviceAndPatientIdReference_WhenResolveResourceIdentitiesAsync_ThenPatientDeviceMismatchExceptionThrown_Test()
        {
            var fhirClient      = Substitute.For <IFhirClient>();
            var resourceService = Substitute.For <ResourceManagementService>();

            var device = new Model.Device
            {
                Id      = "1",
                Patient = new Model.ResourceReference("Patient/abc"),
            };

            var patient = new Model.Patient
            {
                Id = "123",
            };

            resourceService.EnsureResourceByIdentityAsync <Model.Device>(null, null, null, null).ReturnsForAnyArgs(Task.FromResult(device));
            resourceService.EnsureResourceByIdentityAsync <Model.Patient>(null, null, null, null).ReturnsForAnyArgs(Task.FromResult(patient));

            var mg = Substitute.For <IMeasurementGroup>();

            mg.DeviceId.Returns("deviceId");
            mg.PatientId.Returns("patientId");

            resourceService.GetResourceByIdentityAsync <Model.Device>(Arg.Any <IFhirClient>(), Arg.Any <string>(), Arg.Any <string>())
            .Returns(Task.FromException <Model.Device>(new FhirResourceNotFoundException(ResourceType.Patient)));

            using (var idSrv = new R4DeviceAndPatientCreateIdentityService(fhirClient, resourceService))
            {
                await Assert.ThrowsAsync <PatientDeviceMismatchException>(() => idSrv.ResolveResourceIdentitiesAsync(mg));
            }

            await resourceService.Received(1).GetResourceByIdentityAsync <Model.Device>(fhirClient, "deviceId", null);

            await resourceService.Received(1).EnsureResourceByIdentityAsync <Model.Device>(fhirClient, "deviceId", null, Arg.Any <Action <Model.Device, Model.Identifier> >());

            await resourceService.Received(1).EnsureResourceByIdentityAsync <Model.Patient>(fhirClient, "patientId", null, Arg.Any <Action <Model.Patient, Model.Identifier> >());
        }
示例#40
0
        /// <summary>
        /// Generates a condition (Hypertension)
        /// </summary>
        /// <param name="conditionNumber"></param>
        /// <param name="patient"></param>
        /// <returns></returns>
        public HL7.Condition GenerateCondition(int conditionNumber, HL7.Patient patient)
        {
            HL7.Condition genCond = new HL7.Condition();

            //give an id
            genCond.Id = conditionNumber.ToString();

            //give a patient association
            HL7.ResourceReference patRefence = new HL7.ResourceReference();
            patRefence.ReferenceElement = new HL7.FhirString("Patient/" + Int32.Parse(patient.Id));
            genCond.Patient             = patRefence;

            //add a code
            genCond.Code = new HL7.CodeableConcept("http://snomed.info/sct", "59621000", "Essential hypertension");

            //add an onset time
            TimeSpan age       = new TimeSpan((long)(DateTime.Now.Subtract(DateTime.Parse(patient.BirthDate)).Ticks *rand.NextDouble()));
            DateTime onsetDate = DateTime.Now.Subtract(age);

            genCond.Onset = new HL7.FhirDateTime(onsetDate.Year, onsetDate.Month, onsetDate.Day);

            return(genCond);
        }
示例#41
0
        public void TestUriReassignments()
        {
            Patient p = new Patient();

            p.Link = new List<ResourceReference>() { new ResourceReference { Type = "patient", Reference = "patient/@10" } };
            p.Provider = new ResourceReference() { Type = "organization", Reference = "http://outside.com/fhir/organization/@100" };
            p.Contact = new List<Patient.ContactComponent>() {
                new Patient.ContactComponent() { 
                    Organization = new ResourceReference() { Type = "organization", Reference = "http://hl7.org/fhir/organization/@200" } } };
            p.Photo = new List<Attachment>() 
                                { new Attachment() { Url = new Uri("media/@300", UriKind.Relative) }, 
                                  new Attachment() { Url = new Uri("#containedPhoto", UriKind.Relative) },
                                  new Attachment() { Url = new Uri("http://www.nu.nl/fotos/1.jpg", UriKind.Absolute) }
                                };

            var pic300 = new Media();
            pic300.Content = new Attachment() { 
                        Url = new Uri("http://hl7.org/fhir/binary/@300") };
           
            var importer = new ResourceImporter(new Uri("http://hl7.org/fhir"));

            importer.QueueNewResourceEntry("patient", "1", p);
            importer.QueueNewResourceEntry("patient", "10", new Patient());
            importer.QueueNewResourceEntry(new Uri("http://outside.com/fhir/organization/@100"), new Organization());
            importer.QueueNewResourceEntry("media", "300", pic300);

            var result = importer.ImportQueued();

            var p1 = (ResourceEntry<Patient>)result.First();
            Assert.AreEqual("patient/@10", p1.Resource.Link[0].Reference);
            Assert.AreEqual("organization/@11", p1.Resource.Provider.Reference);
            Assert.AreEqual("organization/@200", p1.Resource.Contact.First().Organization.Reference);
            Assert.AreEqual("media/@300", p1.Resource.Photo.First().Url.ToString());
            Assert.AreEqual("#containedPhoto", p1.Resource.Photo.Skip(1).First().Url.ToString());
            Assert.AreEqual("http://www.nu.nl/fotos/1.jpg", p1.Resource.Photo.Skip(2).First().Url.ToString());
            Assert.AreEqual("binary/@300", pic300.Content.Url.ToString());
        }
示例#42
0
        private void cmdCreatePatient_Click(object sender, EventArgs e)
        {
            // Code for creating a patient here.
            // Patientidentifier variables
            var MyPatient = new Hl7.Fhir.Model.Patient();

            var PatientName = new Hl7.Fhir.Model.HumanName();

            PatientName.Use = Hl7.Fhir.Model.HumanName.NameUse.Official;

            string patientFirstName = txtFirstName.Text;
            string patientSurname   = txtSurname.Text;
            string patientTitle     = cmbPatientTitle.Text;
            string patientNumber    = txtPatientNum.Text;


            PatientName.Prefix = new string[] { patientTitle };
            PatientName.Given  = new string[] { patientFirstName };
            PatientName.Family = new string[] { patientSurname };

            MyPatient.Name = new List <Hl7.Fhir.Model.HumanName>();
            MyPatient.Name.Add(PatientName);

            // Institution patient identifiers
            var PatientIdentifier = new Hl7.Fhir.Model.Identifier();

            PatientIdentifier.System = "https://medical-test.net";
            PatientIdentifier.Value  = patientNumber;
            MyPatient.Identifier     = new List <Hl7.Fhir.Model.Identifier>();
            MyPatient.Identifier.Add(PatientIdentifier);

            string    xml  = Hl7.Fhir.Serialization.FhirSerializer.SerializeResourceToXml(MyPatient);
            XDocument xDoc = XDocument.Parse(xml);

            txtOutput.Text = xDoc.ToString();
        }
示例#43
0
        public void TestContainedConstraints()
        {
            var pat = new Patient();
            var patn = new Patient();
            pat.Contained = new List<Resource> { patn } ;
            patn.Contained = new List<Resource> { new Patient() };

            // Contained resources should not themselves contain resources
            validateErrorOrFail(pat);

            patn.Contained = null;
            DotNetAttributeValidation.Validate(pat);

            patn.Text = new Narrative();
            patn.Text.Div = "<div>Narrative in contained resource</div>";

            // Contained resources should not contain narrative
            validateErrorOrFail(pat);
        }
示例#44
0
        public void SerializationDoesNotEmitXmlHeader()
        {
            Bundle b = createTestBundle();
            var actual = FhirSerializer.SerializeBundleToXml(b);
            Assert.IsFalse(actual.StartsWith("<?xml"));

            var data = FhirSerializer.SerializeBundleToXmlBytes(b);
            actual = System.Text.Encoding.UTF8.GetString(data);
            Assert.IsFalse(actual.StartsWith("<?xml"));


            Patient p = new Patient();
            actual = FhirSerializer.SerializeResourceToXml(p);
            Assert.IsFalse(actual.StartsWith("<?xml"));

            data = FhirSerializer.SerializeResourceToXmlBytes(p);
            actual = System.Text.Encoding.UTF8.GetString(data);
            Assert.IsFalse(actual.StartsWith("<?xml"));
        }
        public void SerializeSummaryWithQuotes()
        {
            var p = new Patient();
            p.Text = new Narrative() { Div = "<div xmlns=\"http://www.w3.org/1999/xhtml\">Nasty, a text with both \"double\" quotes and 'single' quotes</div>" };

            var xml = FhirSerializer.SerializeResourceToXml(p);
            Assert.IsNotNull(FhirParser.ParseResourceFromXml(xml));
            var json = FhirSerializer.SerializeResourceToJson(p);
            Assert.IsNotNull(FhirParser.ParseResourceFromJson(json));
        }
        public void TestContainedConstraints()
        {
            var pat = new Patient();
            var patn = new Patient();
            pat.Contained = new List<Resource> { patn } ;
            patn.Contained = new List<Resource> { new Patient() };

            validateErrorOrFail(pat);

            patn.Contained = null;
            Validator.ValidateObject(pat, new ValidationContext(pat), true);

            patn.Text = new Narrative();
            patn.Text.Div = "<div />";

            validateErrorOrFail(pat);
        }
示例#47
0
        /// <summary>
        /// Generate data to supplement server data
        /// </summary>
        /// <returns></returns>
        public CreatedDataContainer CreateData()
        {
            //read the state data
            DataTable stateData = ReadStateData();

            DataTable states = stateData.DefaultView.ToTable(true, "State");

            //parameters for the size of the generated data set
            int maxPerState       = 10;
            int minPerState       = 10;
            int maxObsPerPatient  = 5;
            int minObsPerPatien   = 1;
            int maxCondPerPatient = 1;

            double conditionProb = 0.15;


            //set the starting patient number
            int patientNumber     = 100000;
            int observationNumber = 100000;
            int conditionNumber   = 100000;

            //lists to store the generated data
            List <HL7.Patient>     patList  = new List <HL7.Patient>();
            List <HL7.Observation> obsList  = new List <HL7.Observation>();
            List <HL7.Condition>   condList = new List <HL7.Condition>();


            //do patient generation per state
            foreach (DataRow state in states.Rows)
            {
                //get the countys for the given state
                List <DataRow> counties =
                    (from county in stateData.AsEnumerable()
                     where county.Field <string>("State").Equals(state.Field <string>("State"))
                     select county).ToList <DataRow>();

                //randomly determine the number of patients per state
                int patientCount = Convert.ToInt32(Math.Round(rand.NextDouble() * (maxPerState - minPerState))) + minPerState;

                for (int i = 0; i < patientCount; i++)
                {
                    //generate a practitioner id
                    //currently using IDs 1 - 5
                    int practId = rand.Next(1, 5);

                    //select a county
                    DataRow thisCounty = counties[rand.Next(counties.Count())];
                    //generate the new patient
                    HL7.Patient thisPatient = GeneratePatient(patientNumber, practId, thisCounty["State"].ToString(), thisCounty["County"].ToString(), thisCounty["Postal Code"].ToString());
                    //add to the list
                    patList.Add(thisPatient);
                    patientNumber++;
                }
            }

            //generate observations for each patient
            foreach (var patient in patList)
            {
                int obsCount = rand.Next(0, maxObsPerPatient);
                for (int i = 0; i < obsCount; i++)
                {
                    HL7.Observation thisObservation = GenerateObservation(observationNumber, patient, i);
                    obsList.Add(thisObservation);
                    observationNumber++;
                }
            }

            //generate conditions for each patient
            foreach (var patient in patList)
            {
                double condPct = rand.NextDouble();
                if (condPct < conditionProb)
                {
                    HL7.Condition thisCondition = GenerateCondition(conditionNumber, patient);
                    condList.Add(thisCondition);
                    conditionNumber++;
                }
            }

            return(new CreatedDataContainer(patList, condList, obsList));
        }
        public void TestAllowedChoices()
        {
            Patient p = new Patient();

            p.Deceased = new FhirBoolean(true);
            Validator.ValidateObject(p, new ValidationContext(p), true);

            p.Deceased = new FhirUri();
            validateErrorOrFail(p);
        }
        public static AppChallenge.Model.Patient MapToPatient(Hl7.Fhir.Model.Patient patientResource)
        {
            AppChallenge.Model.Patient patientModel = new AppChallenge.Model.Patient();

            patientModel.Id         = Guid.NewGuid();
            patientModel.FamilyName = patientResource.Name[0].Family.FirstOrDefault();
            patientModel.GivenName  = patientResource.Name[0].Given.FirstOrDefault();

            // Default to true if value is null.
            patientModel.IsActive = patientResource.Active.HasValue ? patientResource.Active.Value : true;

            if (patientResource.Telecom.Count != 0)
            {
                var telecom = patientResource.Telecom;

                patientModel.HomePhone = telecom.FirstOrDefault(x => x.Use == ContactPoint.ContactPointUse.Home) != null?
                                         telecom.First(x => x.Use == ContactPoint.ContactPointUse.Home).Value : null;

                patientModel.MobilePhone = telecom.FirstOrDefault(x => x.Use == ContactPoint.ContactPointUse.Mobile) != null?
                                           telecom.First(x => x.Use == ContactPoint.ContactPointUse.Mobile).Value : null;

                patientModel.Email = telecom.FirstOrDefault(x => x.System == ContactPoint.ContactPointSystem.Email) != null?
                                     telecom.First(x => x.System == ContactPoint.ContactPointSystem.Email).Value : null;
            }

            patientModel.PatientGender = patientResource.Gender.HasValue ? patientResource.Gender.Value.ToString() : null;

            if (patientResource.BirthDate != null)
            {
                patientModel.Birthdate = DateTime.Parse(patientResource.BirthDate);
            }

            if (patientResource.Deceased != null)
            {
                var patientResourceDeceasedBoolean = patientResource.Deceased as FhirBoolean;

                if (patientResourceDeceasedBoolean != null)
                {
                    patientModel.IsDeceased = patientResourceDeceasedBoolean.Value != null ?
                                              patientResourceDeceasedBoolean.Value.Value : false;
                }
                else
                {
                    var patientResourceDeceasedDateTime = patientResource.Deceased as FhirDateTime;
                    if (!String.IsNullOrEmpty(patientResourceDeceasedDateTime.Value))
                    {
                        // Set to true if Deceased datetime has a value.
                        patientModel.IsDeceased = true;
                    }
                }
            }
            else
            {
                // Default to false if Deceased property is null.
                patientModel.IsDeceased = false;
            }

            if (patientResource.Address.Count != 0)
            {
                var address = patientResource.Address.First();

                patientModel.StreetAddress = address.Line != null?address.Line.FirstOrDefault() : null;

                patientModel.City       = address.City != null ? address.City : null;
                patientModel.State      = address.State != null ? address.State : null;
                patientModel.PostalCode = address.PostalCode != null ? address.PostalCode : null;
                patientModel.Country    = address.Country != null ? address.Country : null;
            }

            patientModel.PatientMaritalStatus = patientResource.MaritalStatus != null ?
                                                patientResource.MaritalStatus.Text : null;

            if (patientResource.Animal != null)
            {
                patientModel.IsAnimal = true;

                if (patientResource.Animal.Breed != null)
                {
                    var breedCoding = patientResource.Animal.Breed.Coding.FirstOrDefault();
                    patientModel.AnimalBreed = breedCoding != null ? breedCoding.Display : null;
                }

                if (patientResource.Animal.Species != null)
                {
                    var speciesCoding = patientResource.Animal.Species.Coding.FirstOrDefault();
                    patientModel.AnimalSpecies = speciesCoding != null ? speciesCoding.Display : null;
                }

                if (patientResource.Animal.GenderStatus != null)
                {
                    var genderStatusCoding = patientResource.Animal.GenderStatus.Coding.FirstOrDefault();
                    patientModel.AnimalGenderStatus = genderStatusCoding != null ? genderStatusCoding.Code : null;
                }
            }
            else
            {
                patientModel.IsAnimal = false;
            }

            patientModel.PatientContact = new PatientContact(patientModel.Id);

            if (patientResource.Contact.Count != 0)
            {
                var contact = patientResource.Contact.First();

                patientModel.PatientContact.FamilyName = contact.Name.Family.FirstOrDefault();
                patientModel.PatientContact.GivenName  = contact.Name.Given.FirstOrDefault();

                if (contact.Relationship.Count != 0)
                {
                    var relationship = contact.Relationship.FirstOrDefault();
                    patientModel.PatientContact.Relationship = relationship.Coding.Count != 0 ?
                                                               relationship.Coding.FirstOrDefault().Code : null;
                }

                if (contact.Telecom.Count != 0)
                {
                    var telecom = contact.Telecom;

                    patientModel.PatientContact.HomePhone = telecom.FirstOrDefault(x => x.Use == ContactPoint.ContactPointUse.Home) != null?
                                                            telecom.FirstOrDefault(x => x.Use == ContactPoint.ContactPointUse.Home).Value : null;

                    patientModel.PatientContact.MobilePhone = telecom.FirstOrDefault(x => x.Use == ContactPoint.ContactPointUse.Mobile) != null?
                                                              telecom.FirstOrDefault(x => x.Use == ContactPoint.ContactPointUse.Mobile).Value : null;
                }
            }

            patientModel.PatientIdentifier = new PatientIdentifier(patientModel.Id);

            if (patientResource.Identifier.Count != 0)
            {
                var identifier = patientResource.Identifier.FirstOrDefault();

                patientModel.PatientIdentifier.IdentifierUseValue = identifier.Use.HasValue ? identifier.Use.Value.ToString() : null;

                if (identifier.Type != null)
                {
                    patientModel.PatientIdentifier.IdentifierTypeCodeValue = identifier.Type.Coding.Count != 0 ?
                                                                             identifier.Type.Coding.FirstOrDefault().Code
                                                                                : null;
                    patientModel.PatientIdentifier.IdentifierTypeTextValue = identifier.Type.Text;
                }

                patientModel.PatientIdentifier.IdentifierSystemValue = identifier.System;
                patientModel.PatientIdentifier.IdentifierValue       = identifier.Value;
                patientModel.PatientIdentifier.AssignerDisplayValue  = identifier.Assigner != null ?
                                                                       identifier.Assigner.Display : null;
            }

            return(patientModel);
        }
示例#50
0
        public void TestXhtmlValidation()
        {
            var p = new Patient();

            p.Text = new Narrative() { Div = "<div xmlns='http://www.w3.org/1999/xhtml'><p>should be valid</p></div>", Status = Narrative.NarrativeStatus.Generated  };
            DotNetAttributeValidation.Validate(p,true);

            p.Text.Div = "<div xmlns='http://www.w3.org/1999/xhtml'><p>should not be valid<p></div>";
            validateErrorOrFail(p,true);

            p.Text.Div = "<div xmlns='http://www.w3.org/1999/xhtml'><img onmouseover='bigImg(this)' src='smiley.gif' alt='Smiley' /></div>";
            validateErrorOrFail(p,true);
        }
示例#51
0
        /// <summary>
        /// Get Data for ML Task
        /// </summary>
        /// <returns>a list of patients contain observation data for ML task</returns>
        public static async Task <PatientsList> GetData()
        {
            int  count = 0;
            bool stop  = false;

            PatientsList data = new PatientsList();

            try
            {
                var PatientQuery = new SearchParams()
                                   .OrderBy("birthdate")
                                   .LimitTo(LIMIT_ENTRY);

                Bundle PatientResult = await Client.SearchAsync <Hl7.Fhir.Model.Patient>(PatientQuery);

                // paging to search for all patient until reaching NUMBER_OF_DATA_RECORD value
                while (PatientResult != null)
                {
                    if (stop)
                    {
                        break;
                    }

                    foreach (var Entry in PatientResult.Entry)
                    {
                        Hl7.Fhir.Model.Patient fhirPatient = (Hl7.Fhir.Model.Patient)Entry.Resource;
                        PatientMapper          mapper      = new PatientMapper();
                        Models.Patient         patient     = mapper.Map(fhirPatient);

                        if (!AppContext.AnalysisData.Contains(patient) && !data.Contains(patient))
                        {
                            var CholesterolQuery = new SearchParams()
                                                   .Where("patient=" + patient.Id)
                                                   .Where("code=2093-3")
                                                   .OrderBy("-date")
                                                   .LimitTo(1);

                            // Only GetData for patient that has Cholesterol value
                            Bundle CholesterolResult = await Client.SearchAsync <Hl7.Fhir.Model.Observation>(CholesterolQuery);

                            if (CholesterolResult.Entry.Count > 0)
                            {
                                data.AddPatient(await GetDataForAnalysis(patient));
                                count++;
                            }
                        }

                        // Stop if count reachs NUMBER_OF_DATA_RECORD
                        if (count == NUMBER_OF_DATA_RECORD)
                        {
                            stop = true;
                            break;
                        }
                    }

                    PatientResult = Client.Continue(PatientResult, PageDirection.Next);
                }
            }
            catch (FhirOperationException FhirException)
            {
                System.Diagnostics.Debug.WriteLine("Fhir error message: " + FhirException.Message);
            }
            catch (Exception GeneralException)
            {
                System.Diagnostics.Debug.WriteLine("General error message: " + GeneralException.Message);
            }

            return(data);
        }
示例#52
0
        public void ManipulateMeta()
        {
            FhirClient client = new FhirClient(testEndpoint);

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

            //Before we begin, ensure that our new tags are not actually used when doing System Meta()
            var wsm = client.Meta();
            Assert.IsNotNull(wsm);

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

            Assert.IsFalse(wsm.Profile.Contains("http://someserver.org/fhir/StructureDefinition/XYZ2-" + key));
            Assert.IsFalse(wsm.Security.Select(c => c.Code + "@" + c.System).Contains("5678-" + key + "@http://mysystem.com/sec"));
            Assert.IsFalse(wsm.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, false, key);

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

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

            // Now add some additional meta to the patient

            var newMeta = new Meta();
            newMeta.ProfileElement.Add(new FhirUri("http://someserver.org/fhir/StructureDefinition/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, true, key);

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

            // New and old meta should be present when doing system Meta()
            par = client.Meta();
            verifyMeta(par, 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, false, key);

            // Should no longer be present when doing type Meta()
            par = client.Meta(ResourceType.Patient);
            verifyMeta(par, 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, false, key);
        }
        public static void SerializePatient(Hl7.Fhir.Model.Patient value, IFhirWriter writer, bool summary)
        {
            writer.WriteStartRootObject("Patient");
            writer.WriteStartComplexContent();

            // Serialize element _id
            if (value.LocalIdElement != null)
            {
                writer.WritePrimitiveContents("_id", value.LocalIdElement, XmlSerializationHint.Attribute);
            }

            // Serialize element extension
            if (value.Extension != null && !summary && value.Extension.Count > 0)
            {
                writer.WriteStartArrayElement("extension");
                foreach (var item in value.Extension)
                {
                    writer.WriteStartArrayMember("extension");
                    ExtensionSerializer.SerializeExtension(item, writer, summary);
                    writer.WriteEndArrayMember();
                }
                writer.WriteEndArrayElement();
            }

            // Serialize element language
            if (value.LanguageElement != null && !summary)
            {
                writer.WriteStartElement("language");
                CodeSerializer.SerializeCode(value.LanguageElement, writer, summary);
                writer.WriteEndElement();
            }

            // Serialize element text
            if (value.Text != null && !summary)
            {
                writer.WriteStartElement("text");
                NarrativeSerializer.SerializeNarrative(value.Text, writer, summary);
                writer.WriteEndElement();
            }

            // Serialize element contained
            if (value.Contained != null && !summary && value.Contained.Count > 0)
            {
                writer.WriteStartArrayElement("contained");
                foreach (var item in value.Contained)
                {
                    writer.WriteStartArrayMember("contained");
                    FhirSerializer.SerializeResource(item, writer, summary);
                    writer.WriteEndArrayMember();
                }
                writer.WriteEndArrayElement();
            }

            // Serialize element identifier
            if (value.Identifier != null && value.Identifier.Count > 0)
            {
                writer.WriteStartArrayElement("identifier");
                foreach (var item in value.Identifier)
                {
                    writer.WriteStartArrayMember("identifier");
                    IdentifierSerializer.SerializeIdentifier(item, writer, summary);
                    writer.WriteEndArrayMember();
                }
                writer.WriteEndArrayElement();
            }

            // Serialize element name
            if (value.Name != null && value.Name.Count > 0)
            {
                writer.WriteStartArrayElement("name");
                foreach (var item in value.Name)
                {
                    writer.WriteStartArrayMember("name");
                    HumanNameSerializer.SerializeHumanName(item, writer, summary);
                    writer.WriteEndArrayMember();
                }
                writer.WriteEndArrayElement();
            }

            // Serialize element telecom
            if (value.Telecom != null && value.Telecom.Count > 0)
            {
                writer.WriteStartArrayElement("telecom");
                foreach (var item in value.Telecom)
                {
                    writer.WriteStartArrayMember("telecom");
                    ContactSerializer.SerializeContact(item, writer, summary);
                    writer.WriteEndArrayMember();
                }
                writer.WriteEndArrayElement();
            }

            // Serialize element gender
            if (value.Gender != null)
            {
                writer.WriteStartElement("gender");
                CodeableConceptSerializer.SerializeCodeableConcept(value.Gender, writer, summary);
                writer.WriteEndElement();
            }

            // Serialize element birthDate
            if (value.BirthDateElement != null)
            {
                writer.WriteStartElement("birthDate");
                FhirDateTimeSerializer.SerializeFhirDateTime(value.BirthDateElement, writer, summary);
                writer.WriteEndElement();
            }

            // Serialize element deceased
            if (value.Deceased != null)
            {
                writer.WriteStartElement(SerializationUtil.BuildPolymorphicName("deceased", value.Deceased.GetType()));
                FhirSerializer.SerializeElement(value.Deceased, writer, summary);
                writer.WriteEndElement();
            }

            // Serialize element address
            if (value.Address != null && value.Address.Count > 0)
            {
                writer.WriteStartArrayElement("address");
                foreach (var item in value.Address)
                {
                    writer.WriteStartArrayMember("address");
                    AddressSerializer.SerializeAddress(item, writer, summary);
                    writer.WriteEndArrayMember();
                }
                writer.WriteEndArrayElement();
            }

            // Serialize element maritalStatus
            if (value.MaritalStatus != null)
            {
                writer.WriteStartElement("maritalStatus");
                CodeableConceptSerializer.SerializeCodeableConcept(value.MaritalStatus, writer, summary);
                writer.WriteEndElement();
            }

            // Serialize element multipleBirth
            if (value.MultipleBirth != null)
            {
                writer.WriteStartElement(SerializationUtil.BuildPolymorphicName("multipleBirth", value.MultipleBirth.GetType()));
                FhirSerializer.SerializeElement(value.MultipleBirth, writer, summary);
                writer.WriteEndElement();
            }

            // Serialize element photo
            if (value.Photo != null && !summary && value.Photo.Count > 0)
            {
                writer.WriteStartArrayElement("photo");
                foreach (var item in value.Photo)
                {
                    writer.WriteStartArrayMember("photo");
                    AttachmentSerializer.SerializeAttachment(item, writer, summary);
                    writer.WriteEndArrayMember();
                }
                writer.WriteEndArrayElement();
            }

            // Serialize element contact
            if (value.Contact != null && !summary && value.Contact.Count > 0)
            {
                writer.WriteStartArrayElement("contact");
                foreach (var item in value.Contact)
                {
                    writer.WriteStartArrayMember("contact");
                    PatientSerializer.SerializeContactComponent(item, writer, summary);
                    writer.WriteEndArrayMember();
                }
                writer.WriteEndArrayElement();
            }

            // Serialize element animal
            if (value.Animal != null)
            {
                writer.WriteStartElement("animal");
                PatientSerializer.SerializeAnimalComponent(value.Animal, writer, summary);
                writer.WriteEndElement();
            }

            // Serialize element communication
            if (value.Communication != null && !summary && value.Communication.Count > 0)
            {
                writer.WriteStartArrayElement("communication");
                foreach (var item in value.Communication)
                {
                    writer.WriteStartArrayMember("communication");
                    CodeableConceptSerializer.SerializeCodeableConcept(item, writer, summary);
                    writer.WriteEndArrayMember();
                }
                writer.WriteEndArrayElement();
            }

            // Serialize element provider
            if (value.Provider != null)
            {
                writer.WriteStartElement("provider");
                ResourceReferenceSerializer.SerializeResourceReference(value.Provider, writer, summary);
                writer.WriteEndElement();
            }

            // Serialize element link
            if (value.Link != null && value.Link.Count > 0)
            {
                writer.WriteStartArrayElement("link");
                foreach (var item in value.Link)
                {
                    writer.WriteStartArrayMember("link");
                    ResourceReferenceSerializer.SerializeResourceReference(item, writer, summary);
                    writer.WriteEndArrayMember();
                }
                writer.WriteEndArrayElement();
            }

            // Serialize element active
            if (value.ActiveElement != null)
            {
                writer.WriteStartElement("active");
                FhirBooleanSerializer.SerializeFhirBoolean(value.ActiveElement, writer, summary);
                writer.WriteEndElement();
            }


            writer.WriteEndComplexContent();
            writer.WriteEndRootObject();
        }
示例#54
0
        public void TestSummary()
        {
            var p = new Patient();

            p.BirthDate = "1972-11-30";     // present in both summary and full
            p.Photo = new List<Attachment>() { new Attachment() { ContentType = "text/plain" } };

            var full = FhirSerializer.SerializeResourceToXml(p);
            Assert.IsTrue(full.Contains("<birthDate"));
            Assert.IsTrue(full.Contains("<photo"));

            var summ = FhirSerializer.SerializeResourceToXml(p, summary: true);
            Assert.IsTrue(summ.Contains("<birthDate"));
            Assert.IsFalse(summ.Contains("<photo"));

            var q = new Questionnaire();

            q.Status = Questionnaire.QuestionnaireStatus.Published;
            q.Date = "2015-09-27";
            q.Group = new Questionnaire.GroupComponent();
            q.Group.Title = "TITLE";
            q.Group.Text = "TEXT";
            q.Group.LinkId = "linkid";

            var qfull = FhirSerializer.SerializeResourceToXml(q);
            Console.WriteLine(qfull);
            Assert.IsTrue(qfull.Contains("<status value=\"published\""));
            Assert.IsTrue(qfull.Contains("<date value=\"2015-09-27\""));
            Assert.IsTrue(qfull.Contains("<title value=\"TITLE\""));
            Assert.IsTrue(qfull.Contains("<text value=\"TEXT\""));
            Assert.IsTrue(qfull.Contains("<linkId value=\"linkid\""));

            var qSum = FhirSerializer.SerializeResourceToXml(q, summary: true);
            Console.WriteLine(qSum);
            Assert.IsTrue(qSum.Contains("<status value=\"published\""));
            Assert.IsTrue(qSum.Contains("<date value=\"2015-09-27\""));
            Assert.IsTrue(qSum.Contains("<title value=\"TITLE\""));
            Assert.IsFalse(qSum.Contains("<text value=\"TEXT\""));
            Assert.IsFalse(qSum.Contains("<linkId value=\"linkid\""));
        }
示例#55
0
        public void TestEmptyCollectionValidation()
        {
            var p = new Patient();
            p.Identifier = new List<Identifier>();
            p.Identifier.Add(null);

            validateErrorOrFail(p);
        }
        public static Hl7.Fhir.Model.Patient MapModel(iPM_API_Resource.Patient iPMpatient)
        {
            if (iPMpatient == null)
            {
                throw new ArgumentNullException("patient");
            }

            var resource = new Hl7.Fhir.Model.Patient();

            resource.Id = iPMpatient.Pasid;

            resource.Active   = (iPMpatient.ArchvFlag == "Y") ?true : false;
            resource.Deceased = new FhirBoolean((iPMpatient.DecsdFlag == "Y") ? true : false);

            resource.Name = new List <HumanName>();
            var name = new HumanName()
            {
                Family = new[] { iPMpatient.Surname },
                Given  = new[] { iPMpatient.Forename },
                Use    = HumanName.NameUse.Official
            };

            resource.Name.Add(name);

            resource.BirthDate = iPMpatient.DttmOfBirth.ToString();

            //switch (iPMpatient.Gender)
            //{
            //    case GenderCode.Female:
            //        resource.Gender = new CodeableConcept("http://hl7.org/fhir/v3/AdministrativeGender", "F", "Female");
            //        break;

            //    case GenderCode.Male:
            //        resource.Gender = new CodeableConcept("http://hl7.org/fhir/v3/AdministrativeGender", "M", "Male");
            //        break;

            //    case GenderCode.Undetermined:
            //        resource.Gender = new CodeableConcept("http://hl7.org/fhir/v3/AdministrativeGender", "U", "Undetermined");
            //        break;

            //    default:
            //        resource.Gender = new CodeableConcept("http://hl7.org/fhir/v3/NullFlavor", "UNK", "Unknown");
            //        break;
            //}

            //resource.Telecom = new List<ContactPoint>
            //{
            //    new ContactPoint() {
            //        Value = iPMpatient.HomeTelephone.TlandOid.ToString(),
            //        System = ContactPoint.ContactPointSystem.Phone,
            //        Use = ContactPoint.ContactPointUse.Home
            //    },
            //    new ContactPoint() {
            //        Value = "0411445547878",
            //        System =  ContactPoint.ContactPointSystem.Phone,
            //        Use = ContactPoint.ContactPointUse.Mobile
            //    },

            //};

            //resource.Address = new List<Address>
            //{
            //    new Address()
            //    {
            //        Country = iPMpatient.HomeAddress.County,
            //        City = iPMpatient.HomeAddress.Line1,
            //        PostalCode = iPMpatient.HomeAddress.Pcode,
            //        Line = new[]
            //        {
            //            iPMpatient.HomeAddress.Line1,
            //            iPMpatient.HomeAddress.Line2
            //        }
            //    }
            //};

            // Make use of extensions ...
            //
            resource.Extension = new List <Extension>(1);
            //resource.Extension.Add(new Extension(new Uri("http://www.englishclub.com/vocabulary/world-countries-nationality.htm"),
            //                                       new FhirString("Australia")
            //                                     ));

            return(resource);
        }
示例#57
0
        public void TestBundleSummary()
        {
            var p = new Patient();

            p.BirthDate = "1972-11-30";     // present in both summary and full
            p.Photo = new List<Attachment>() { new Attachment() { ContentType = "text/plain" } };

            var b = new Bundle();
            b.AddResourceEntry(p, "http://nu.nl/fhir/Patient/1");

            var full = FhirSerializer.SerializeResourceToXml(b);
            Assert.IsTrue(full.Contains("<entry"));
            Assert.IsTrue(full.Contains("<birthDate"));
            Assert.IsTrue(full.Contains("<photo"));

            var summ = FhirSerializer.SerializeResourceToXml(b, summary: true);
            Assert.IsTrue(summ.Contains("<entry"));
            Assert.IsTrue(summ.Contains("<birthDate"));
            Assert.IsFalse(summ.Contains("<photo"));
        }
示例#58
0
        public static Hl7.Fhir.Model.Patient MapModel(Model.Patient patient)
        {
            if (patient == null)
            {
                throw new ArgumentNullException("patient");
            }

            var resource = new Hl7.Fhir.Model.Patient();

            resource.Id = patient.PatientId.ToString("D");

            resource.Active   = patient.Active;
            resource.Deceased = new FhirBoolean(patient.Deceased);

            resource.Name = new List <HumanName>();
            var name = new HumanName()
            {
                Family = new[] { patient.LastName },
                Given  = new[] { patient.FirstName },
                Use    = HumanName.NameUse.Official
            };

            resource.Name.Add(name);

            resource.BirthDate = patient.Birthday.ToString("s");

            switch (patient.Gender)
            {
            case GenderCode.Female:
                resource.Gender = new CodeableConcept("http://hl7.org/fhir/v3/AdministrativeGender", "F", "Female");
                break;

            case GenderCode.Male:
                resource.Gender = new CodeableConcept("http://hl7.org/fhir/v3/AdministrativeGender", "M", "Male");
                break;

            case GenderCode.Undetermined:
                resource.Gender = new CodeableConcept("http://hl7.org/fhir/v3/AdministrativeGender", "U", "Undetermined");
                break;

            default:
                resource.Gender = new CodeableConcept("http://hl7.org/fhir/v3/NullFlavor", "UNK", "Unknown");
                break;
            }

            resource.Telecom = new List <Contact>
            {
                new Contact()
                {
                    Value  = patient.Phone,
                    System = Contact.ContactSystem.Phone,
                    Use    = Contact.ContactUse.Home
                },
                new Contact()
                {
                    Value  = patient.Mobile,
                    System = Contact.ContactSystem.Phone,
                    Use    = Contact.ContactUse.Mobile
                },
                new Contact()
                {
                    Value  = patient.EMail,
                    System = Contact.ContactSystem.Email,
                    Use    = Contact.ContactUse.Home
                },
            };

            resource.Address = new List <Address>
            {
                new Address()
                {
                    Country = patient.Country,
                    City    = patient.City,
                    Zip     = patient.Zip,
                    Line    = new[]
                    {
                        patient.AddressLine1,
                        patient.AddressLine2
                    }
                }
            };

            // Make use of extensions ...
            //
            resource.Extension = new List <Extension>(1);
            resource.Extension.Add(new Extension(new Uri("http://www.englishclub.com/vocabulary/world-countries-nationality.htm"),
                                                 new FhirString(patient.Nationality)
                                                 ));

            return(resource);
        }
示例#59
0
        public void TestUpdateEncounter()
        {
            var patient = new Patient
            {
                Name = new List <HumanName>
                {
                    new HumanName
                    {
                        Given = new List <string>
                        {
                            "Test",
                            "Update"
                        },
                        Family = "Patient"
                    }
                },
                Active  = true,
                Address = new List <Address>
                {
                    new Address
                    {
                        State   = "Ontario",
                        Country = "Canada",
                        Line    = new List <string>
                        {
                            "123 King Street"
                        },
                        City = "Hamilton"
                    }
                }
            };

            var encounter = new Encounter()
            {
                Class  = new Coding("http://santedb.org/conceptset/v3-ActEncounterCode", "HH"),
                Status = Encounter.EncounterStatus.Finished,
                Period = new Period
                {
                    StartElement = FhirDateTime.Now(),
                    EndElement   = FhirDateTime.Now()
                },
            };

            Resource actualPatient;
            Resource actualEncounter;

            TestUtil.CreateAuthority("TEST", "1.2.3.4", "http://santedb.org/fhir/test", "TEST_HARNESS", AUTH);
            using (TestUtil.AuthenticateFhir("TEST_HARNESS", AUTH))
            {
                var patientResourceHandler   = FhirResourceHandlerUtil.GetResourceHandler(ResourceType.Patient);
                var encounterResourceHandler = FhirResourceHandlerUtil.GetResourceHandler(ResourceType.Encounter);

                actualPatient = patientResourceHandler.Create(patient, TransactionMode.Commit);

                encounter.Subject = new ResourceReference($"urn:uuid:{actualPatient.Id}");

                actualEncounter = encounterResourceHandler.Create(encounter, TransactionMode.Commit);
            }

            Assert.NotNull(actualPatient);
            Assert.NotNull(actualEncounter);

            Assert.IsInstanceOf <Patient>(actualPatient);
            Assert.IsInstanceOf <Encounter>(actualEncounter);

            var createdEncounter = (Encounter)actualEncounter;

            Assert.NotNull(createdEncounter);

            createdEncounter.Status = Encounter.EncounterStatus.Cancelled;
            createdEncounter.Class  = new Coding("http://santedb.org/conceptset/v3-ActEncounterCode", "FLD");

            Resource actual;

            using (TestUtil.AuthenticateFhir("TEST_HARNESS", AUTH))
            {
                var encounterResourceHandler = FhirResourceHandlerUtil.GetResourceHandler(ResourceType.Encounter);

                actual = encounterResourceHandler.Update(createdEncounter.Id, createdEncounter, TransactionMode.Commit);
            }

            Assert.NotNull(actual);
            Assert.IsInstanceOf <Encounter>(actual);

            var updatedEncounter = (Encounter)actual;

            Assert.AreEqual(Encounter.EncounterStatus.Cancelled, updatedEncounter.Status);
            Assert.AreEqual("FLD", updatedEncounter.Class.Code);
        }
        public void TestBuild()
        {
            var p = new Patient();
            var b = new TransactionBuilder("http://myserver.org/fhir")
                        .Create(p)
                        .ResourceHistory("Patient","7")
                        .Delete("Patient","8")
                        .Read("Patient","9", ifNoneMatch: "W/bla")
                        .ToBundle();

            Assert.AreEqual(4, b.Entry.Count);
            
            Assert.AreEqual(Bundle.HTTPVerb.POST, b.Entry[0].Request.Method);
            Assert.AreEqual(p, b.Entry[0].Resource);

            Assert.AreEqual(Bundle.HTTPVerb.GET, b.Entry[1].Request.Method);
            Assert.AreEqual("http://myserver.org/fhir/Patient/7/_history", b.Entry[1].Request.Url);

            Assert.AreEqual(Bundle.HTTPVerb.DELETE, b.Entry[2].Request.Method);
            Assert.AreEqual("http://myserver.org/fhir/Patient/8", b.Entry[2].Request.Url);

            Assert.AreEqual(Bundle.HTTPVerb.GET, b.Entry[3].Request.Method);
            Assert.AreEqual("http://myserver.org/fhir/Patient/9", b.Entry[3].Request.Url);
            Assert.AreEqual("W/bla", b.Entry[3].Request.IfNoneMatch);
        }