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\""));
        }
Exemplo n.º 2
1
        public Bundle SetBundleResult(OrderResponse orderResp, DiagnosticReport diagReport, Observation observ, Practitioner pract)
        {
            Bundle bundle = new Bundle();
            bundle.Meta = new Meta() { Profile = new string[] { MetaBundleResult } };
            bundle.Entry = new List<Bundle.BundleEntryComponent>();
            if (orderResp != null)
            {
                Bundle.BundleEntryComponent component = new Bundle.BundleEntryComponent
                {
                    Resource = orderResp,
                    Transaction = new Bundle.BundleEntryTransactionComponent { Method = Bundle.HTTPVerb.POST, Url = "OrderResponse" }
                };
                bundle.Entry.Add(component);
            }
            if (diagReport != null)
            {
                Bundle.BundleEntryComponent component = new Bundle.BundleEntryComponent
                {
                    Resource = diagReport,
                    Transaction = new Bundle.BundleEntryTransactionComponent() { Method = Bundle.HTTPVerb.POST, Url = "DiagnosticReport" }
                };
                bundle.Entry.Add(component);
            }
            if (observ != null)
            {
                Bundle.BundleEntryComponent component = new Bundle.BundleEntryComponent()
                {
                    Resource = observ,
                    Transaction = new Bundle.BundleEntryTransactionComponent() { Method = Bundle.HTTPVerb.POST, Url = "Observation" }
                };
                bundle.Entry.Add(component);
            }
            //необязательный параметр
            if (pract != null)
            {
                Bundle.BundleEntryComponent component = new Bundle.BundleEntryComponent
                {
                    Resource = pract,
                    Transaction = new Bundle.BundleEntryTransactionComponent { Method = Bundle.HTTPVerb.POST, Url = "Practitioner" }
                };
                bundle.Entry.Add(component);
            }

            return bundle;
        }
Exemplo n.º 3
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);
        }
        public void ValidateResourceWithIncorrectChildElement()
        {
            FhirDateTime dt = new FhirDateTime();
            dt.Value = "Ewout Kramer";

            Observation o = new Observation { Applies = dt };
            DiagnosticReport rep = new DiagnosticReport();
            rep.Contained = new List<Resource> { o };

            validateErrorOrFail(rep);
        }
Exemplo n.º 5
0
 public static string ToValue(this FHIR.Observation observation)
 {
     if (observation.Value != null)
     {
         return(observation.Value.ToValue());
     }
     else if (observation.Component != null && observation.Component.Any())
     {
         return(string.Join(", ", observation.Component.Select(c => c.ToValue())));
     }
     else
     {
         throw new ArgumentException($"Unsupported FHIR observation value type.");
     }
 }
Exemplo n.º 6
0
        private Observation ConvertObservation(FHIR.Observation observation)
        {
            var result = new Observation
            {
                Id   = observation.Id,
                Text = observation.Code.Text
            };

            if (observation.Effective is FHIR.Period periodValue)
            {
                result.DateTime = periodValue.StartElement.ToDateTimeOffset();
            }
            else
            {
                throw new ArgumentException($"Unsupported FHIR date type {observation.Effective.GetType().Name}.");
            }

            result.Value = observation.ToValue();

            return(result);
        }
Exemplo n.º 7
0
        /// <summary>
        /// Get patient data for ML task
        /// </summary>
        /// <param name="patient"> given patient </param>
        /// <returns> a patient contains observation values for ML task </returns>
        public static async Task <Models.Patient> GetDataForAnalysis(Models.Patient patient)
        {
            Models.Patient currentPatient = patient;
            currentPatient.Observations    = new List <Models.Observation>();
            currentPatient.HasObservations = true;
            try
            {
                var ObservationQuery = new SearchParams()
                                       .Where("patient=" + currentPatient.Id)
                                       .OrderBy("-date")
                                       .LimitTo(LIMIT_ENTRY);

                Bundle ObservationResult = await Client.SearchAsync <Hl7.Fhir.Model.Observation>(ObservationQuery);

                foreach (var Entry in ObservationResult.Entry)
                {
                    Hl7.Fhir.Model.Observation fhirObservation = (Hl7.Fhir.Model.Observation)Entry.Resource;
                    if (fhirObservation.Value != null && fhirObservation.Value is Hl7.Fhir.Model.Quantity)
                    {
                        ObservationMapper  mapper      = new ObservationMapper();
                        Models.Observation observation = mapper.Map(fhirObservation);
                        if (!currentPatient.ContainsObservation(observation.CodeText))
                        {
                            currentPatient.Observations.Add(observation);
                        }
                    }
                }
            }
            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(currentPatient);
        }
Exemplo n.º 8
0
        /// <summary>
        /// Get Observation values of a patients list (Total Cholesterol, Blood Pressure)
        /// </summary>
        /// <param name="patients"> given list of patients </param>
        /// <returns> list of patients that contain Cholesterol and Blood Pressure values </returns>
        public static async Task <PatientsList> GetObservationValues(PatientsList patients)
        {
            PatientsList MonitoredPatientList = new PatientsList();

            foreach (Models.Patient MonitoredPatient in patients)
            {
                try
                {
                    Models.Patient patient = MonitoredPatient;
                    patient.Observations    = new List <Models.Observation>();
                    patient.HasObservations = true;

                    // sort by date, limit to 1 so only take the newest Cholesterol observation
                    var ObservationQuery = new SearchParams()
                                           .Where("patient=" + MonitoredPatient.Id)
                                           .Where("code=" + CHOLESTEROL_CODE)
                                           .OrderBy("-date")
                                           .LimitTo(1);

                    Bundle ObservationResult = await Client.SearchAsync <Hl7.Fhir.Model.Observation>(ObservationQuery);

                    if (ObservationResult.Entry.Count > 0)
                    {
                        // Map the FHIR Observation object to App's Observation object
                        Hl7.Fhir.Model.Observation fhirObservation        = (Hl7.Fhir.Model.Observation)ObservationResult.Entry[0].Resource;
                        ObservationMapper          mapper                 = new ObservationMapper();
                        Models.Observation         cholesterolObservation = mapper.Map(fhirObservation);
                        patient.Observations.Add(cholesterolObservation);
                    }

                    // sort by date, limit to 5 so only take the lastest Blood Pressure observation
                    ObservationQuery = new SearchParams()
                                       .Where("patient=" + MonitoredPatient.Id)
                                       .Where("code=" + BLOOD_PRESSURE_CODE)
                                       .OrderBy("-date")
                                       .LimitTo(5);

                    ObservationResult = await Client.SearchAsync <Hl7.Fhir.Model.Observation>(ObservationQuery);

                    for (int i = 0; i < ObservationResult.Entry.Count; i++)
                    {
                        // Map the FHIR Observation object to App's Observation object
                        Hl7.Fhir.Model.Observation fhirObservation = (Hl7.Fhir.Model.Observation)ObservationResult.Entry[i].Resource;
                        ComponentObservationMapper mapper          = new ComponentObservationMapper();

                        Models.Observation diastolicObservation = mapper.Map(fhirObservation.Component[0]);
                        diastolicObservation.Id = fhirObservation.Id;

                        Models.Observation systolicObservation = mapper.Map(fhirObservation.Component[1]);
                        systolicObservation.Id = fhirObservation.Id;

                        if (fhirObservation.Issued != null)
                        {
                            diastolicObservation.Issued = ((DateTimeOffset)fhirObservation.Issued).DateTime;
                            systolicObservation.Issued  = ((DateTimeOffset)fhirObservation.Issued).DateTime;
                        }
                        else
                        {
                            diastolicObservation.Issued = null;
                            systolicObservation.Issued  = null;
                        }

                        patient.Observations.Add(diastolicObservation);
                        patient.Observations.Add(systolicObservation);
                    }

                    MonitoredPatientList.AddPatient(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(MonitoredPatientList);
        }
        public static void SerializeObservation(Hl7.Fhir.Model.Observation value, IFhirWriter writer, bool summary)
        {
            writer.WriteStartRootObject("Observation");
            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 name
            if (value.Name != null && !summary)
            {
                writer.WriteStartElement("name");
                CodeableConceptSerializer.SerializeCodeableConcept(value.Name, writer, summary);
                writer.WriteEndElement();
            }

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

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

            // Serialize element comments
            if (value.CommentsElement != null && !summary)
            {
                writer.WriteStartElement("comments");
                FhirStringSerializer.SerializeFhirString(value.CommentsElement, writer, summary);
                writer.WriteEndElement();
            }

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

            // Serialize element issued
            if (value.IssuedElement != null && !summary)
            {
                writer.WriteStartElement("issued");
                InstantSerializer.SerializeInstant(value.IssuedElement, writer, summary);
                writer.WriteEndElement();
            }

            // Serialize element status
            if (value.StatusElement != null && !summary)
            {
                writer.WriteStartElement("status");
                CodeSerializer.SerializeCode <Hl7.Fhir.Model.ObservationStatus>(value.StatusElement, writer, summary);
                writer.WriteEndElement();
            }

            // Serialize element reliability
            if (value.ReliabilityElement != null && !summary)
            {
                writer.WriteStartElement("reliability");
                CodeSerializer.SerializeCode <Hl7.Fhir.Model.Observation.ObservationReliability>(value.ReliabilityElement, writer, summary);
                writer.WriteEndElement();
            }

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

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

            // Serialize element identifier
            if (value.Identifier != null && !summary)
            {
                writer.WriteStartElement("identifier");
                IdentifierSerializer.SerializeIdentifier(value.Identifier, writer, summary);
                writer.WriteEndElement();
            }

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

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

            // Serialize element referenceRange
            if (value.ReferenceRange != null && !summary && value.ReferenceRange.Count > 0)
            {
                writer.WriteStartArrayElement("referenceRange");
                foreach (var item in value.ReferenceRange)
                {
                    writer.WriteStartArrayMember("referenceRange");
                    ObservationSerializer.SerializeObservationReferenceRangeComponent(item, writer, summary);
                    writer.WriteEndArrayMember();
                }
                writer.WriteEndArrayElement();
            }

            // Serialize element component
            if (value.Component != null && !summary && value.Component.Count > 0)
            {
                writer.WriteStartArrayElement("component");
                foreach (var item in value.Component)
                {
                    writer.WriteStartArrayMember("component");
                    ObservationSerializer.SerializeObservationComponentComponent(item, writer, summary);
                    writer.WriteEndArrayMember();
                }
                writer.WriteEndArrayElement();
            }


            writer.WriteEndComplexContent();
            writer.WriteEndRootObject();
        }
Exemplo n.º 10
0
 public virtual Model.Observation MergeObservation(ILookupTemplate <IFhirTemplate> config, Model.Observation observation, IObservationGroup grp)
 {
     return(_fhirTemplateProcessor.MergeObservation(config, grp, observation));
 }
Exemplo n.º 11
0
        private string createObservation(decimal value)
        {
            Observation observation = new Observation();
            observation.Status = Observation.ObservationStatus.Preliminary;
            observation.Reliability = Observation.ObservationReliability.Questionable;
            observation.Name = new CodeableConcept("http://loinc.org", "2164-2");
            observation.Value = new Quantity() { System = new Uri("http://unitofmeasure.org"), Value = value, Units = "mmol" };
            observation.BodySite = new CodeableConcept("http://snomed.info/sct", "182756003");

            ResourceEntry<Observation> entry = client.Create<Observation>(observation, null, true);
            return entry.GetBasicId();
        }
Exemplo n.º 12
0
        public Bundle SetBundleOrder(Order order, DiagnosticOrder diagnosticOrder,
                                     Specimen specimen, Encounter encounter, Condition condition,
                                     Observation observation, Practitioner practitioner, Coverage coverage, Patient patient)
        {
            Bundle bundle = new Bundle();
            bundle.Meta = new Meta() { Profile = new string[] { MetaBundleOrder } };
            bundle.Entry = new List<Bundle.BundleEntryComponent>();

            if (order != null)
            {
                Bundle.BundleEntryComponent component = new Bundle.BundleEntryComponent
                {
                    Resource = order,
                    Transaction = new Bundle.BundleEntryTransactionComponent { Method = Bundle.HTTPVerb.POST, Url = "Order" }
                };
                bundle.Entry.Add(component);
            }

            if (diagnosticOrder != null)
            {
                Bundle.BundleEntryComponent component = new Bundle.BundleEntryComponent
                {
                    Resource = diagnosticOrder,
                    Transaction = new Bundle.BundleEntryTransactionComponent() { Method = Bundle.HTTPVerb.POST, Url = "DiagnosticOrder" }
                };
                bundle.Entry.Add(component);
            }

            if (specimen != null)
            {
                Bundle.BundleEntryComponent component = new Bundle.BundleEntryComponent
                {
                    Resource = specimen,
                    Transaction = new Bundle.BundleEntryTransactionComponent() { Method = Bundle.HTTPVerb.POST, Url = "Specimen" }
                };
                bundle.Entry.Add(component);
            }

            if (encounter != null)
            {
                Bundle.BundleEntryComponent component = new Bundle.BundleEntryComponent
                {
                    Resource = encounter,
                    Transaction = new Bundle.BundleEntryTransactionComponent() { Method = Bundle.HTTPVerb.POST, Url = "Encounter" }
                };
                bundle.Entry.Add(component);
            }

            if (condition != null)
            {
                Bundle.BundleEntryComponent component = new Bundle.BundleEntryComponent
                {
                    Resource = condition,
                    Transaction = new Bundle.BundleEntryTransactionComponent() { Method = Bundle.HTTPVerb.POST, Url = "Condition" }
                };
                bundle.Entry.Add(component);
            }

            if (observation != null)
            {
                Bundle.BundleEntryComponent component = new Bundle.BundleEntryComponent
                {
                    Resource = observation,
                    Transaction = new Bundle.BundleEntryTransactionComponent() { Method = Bundle.HTTPVerb.POST, Url = "Observation" }
                };
                bundle.Entry.Add(component);
            }

            if (practitioner != null)
            {
                Bundle.BundleEntryComponent component = new Bundle.BundleEntryComponent
                {
                    Resource = practitioner,
                    Transaction = new Bundle.BundleEntryTransactionComponent() { Method = Bundle.HTTPVerb.POST, Url = "Practitioner" }
                };
                bundle.Entry.Add(component);
            }
            if (coverage != null)
            {
                Bundle.BundleEntryComponent component = new Bundle.BundleEntryComponent
                {
                    Resource = coverage,
                    Transaction = new Bundle.BundleEntryTransactionComponent() { Method = Bundle.HTTPVerb.POST, Url = "Coverage" }
                };
                bundle.Entry.Add(component);
            }
            if (patient != null)
            {
                Bundle.BundleEntryComponent component = new Bundle.BundleEntryComponent
                {
                    Resource = patient,
                    Transaction = new Bundle.BundleEntryTransactionComponent() { Method = Bundle.HTTPVerb.POST, Url = "Patient" }
                };
                bundle.Entry.Add(component);
            }
            return bundle;
        }
Exemplo n.º 13
0
        public void TestDecimalPrecisionSerializationInJson()
        {
            var dec6 = 6m;
            var dec60 = 6.0m;

            var obs = new Observation { Value = new FhirDecimal(dec6) };
            var json = FhirSerializer.SerializeResourceToJson(obs);
            var obs2 = (Observation)FhirParser.ParseFromJson(json);
            Assert.AreEqual("6", ((FhirDecimal)obs2.Value).Value.Value.ToString(CultureInfo.InvariantCulture));

            obs = new Observation { Value = new FhirDecimal(dec60) };
            json = FhirSerializer.SerializeResourceToJson(obs);
            obs2 = (Observation)FhirParser.ParseFromJson(json);
            Assert.AreEqual("6.0", ((FhirDecimal)obs2.Value).Value.Value.ToString(CultureInfo.InvariantCulture));
        }
Exemplo n.º 14
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));
        }
Exemplo n.º 15
0
 //Test for github issue https://github.com/ewoutkramer/fhir-net-api/issues/145
 public void Create_ObservationWithValueAsSimpleQuantity_ReadReturnsValueAsQuantity()
 {
     FhirClient client = new FhirClient(testEndpoint);
     var observation = new Observation();
     observation.Status = Observation.ObservationStatus.Preliminary;
     observation.Code = new CodeableConcept("http://loinc.org", "2164-2");
     observation.Value = new SimpleQuantity()
     {
         System = "http://unitsofmeasure.org",
         Value = 23,
         Code = "mg",
         Unit = "miligram"
     };
     observation.BodySite = new CodeableConcept("http://snomed.info/sct", "182756003");
     var fe = client.Create(observation);
     fe = client.Read<Observation>(fe.ResourceIdentity().WithoutVersion());
     Assert.IsInstanceOfType(fe.Value, typeof(Quantity));
 }
Exemplo n.º 16
0
        public void ValidateResourceWithIncorrectElement()
        {
            FhirDateTime dt = new FhirDateTime();

            dt.Value = "Ewout Kramer";

            Observation o = new Observation { Applies = dt };
            DiagnosticReport rep = new DiagnosticReport();
            rep.Contained = new List<Resource> { o };

            var errors = dt.Validate();

            Assert.IsTrue(errors.Count == 1);
        }
Exemplo n.º 17
0
        private void button1_Click_2(object sender, EventArgs e)
        {
            var endpoint = new Uri("http://fhirtest.uhn.ca/baseDstu2");
            var client = new FhirClient(endpoint);

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

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

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

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

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

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

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

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

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

            conversionStatus.Text = "Done!";
        }
Exemplo n.º 18
0
 public void TestLongDecimalSerialization()
 {
     var dec = 3.1415926535897932384626433833m;
     var obs = new Observation { Value = new FhirDecimal(dec) };
     var json = FhirSerializer.SerializeResourceToJson(obs);
     var obs2 = (Observation)FhirParser.ParseFromJson(json);
     Assert.AreEqual(dec.ToString(CultureInfo.InvariantCulture), ((FhirDecimal)obs2.Value).Value.Value.ToString(CultureInfo.InvariantCulture));
 }
Exemplo n.º 19
0
        /// <summary>
        /// Parse Observation
        /// </summary>
        public static Hl7.Fhir.Model.Observation ParseObservation(IFhirReader reader, ErrorList errors, Hl7.Fhir.Model.Observation existingInstance = null)
        {
            Hl7.Fhir.Model.Observation result = existingInstance != null ? existingInstance : new Hl7.Fhir.Model.Observation();
            string currentElementName         = reader.CurrentElementName;

            reader.EnterElement();

            while (reader.HasMoreElements())
            {
                var atName = reader.CurrentElementName;
                // Parse element extension
                if (atName == "extension")
                {
                    result.Extension = new List <Hl7.Fhir.Model.Extension>();
                    reader.EnterArray();

                    while (ParserUtils.IsAtArrayElement(reader, "extension"))
                    {
                        result.Extension.Add(ExtensionParser.ParseExtension(reader, errors));
                    }

                    reader.LeaveArray();
                }

                // Parse element language
                else if (atName == "language")
                {
                    result.LanguageElement = CodeParser.ParseCode(reader, errors);
                }

                // Parse element text
                else if (atName == "text")
                {
                    result.Text = NarrativeParser.ParseNarrative(reader, errors);
                }

                // Parse element contained
                else if (atName == "contained")
                {
                    result.Contained = new List <Hl7.Fhir.Model.Resource>();
                    reader.EnterArray();

                    while (ParserUtils.IsAtArrayElement(reader, "contained"))
                    {
                        result.Contained.Add(ParserUtils.ParseContainedResource(reader, errors));
                    }

                    reader.LeaveArray();
                }

                // Parse element _id
                else if (atName == "_id")
                {
                    result.LocalIdElement = Id.Parse(reader.ReadPrimitiveContents(typeof(Id)));
                }

                // Parse element name
                else if (atName == "name")
                {
                    result.Name = CodeableConceptParser.ParseCodeableConcept(reader, errors);
                }

                // Parse element value
                else if (atName.StartsWith("value"))
                {
                    result.Value = FhirParser.ParseElement(reader, errors);
                }

                // Parse element interpretation
                else if (atName == "interpretation")
                {
                    result.Interpretation = CodeableConceptParser.ParseCodeableConcept(reader, errors);
                }

                // Parse element comments
                else if (atName == "comments")
                {
                    result.CommentsElement = FhirStringParser.ParseFhirString(reader, errors);
                }

                // Parse element applies
                else if (atName.StartsWith("applies"))
                {
                    result.Applies = FhirParser.ParseElement(reader, errors);
                }

                // Parse element issued
                else if (atName == "issued")
                {
                    result.IssuedElement = InstantParser.ParseInstant(reader, errors);
                }

                // Parse element status
                else if (atName == "status")
                {
                    result.StatusElement = CodeParser.ParseCode <Hl7.Fhir.Model.ObservationStatus>(reader, errors);
                }

                // Parse element reliability
                else if (atName == "reliability")
                {
                    result.ReliabilityElement = CodeParser.ParseCode <Hl7.Fhir.Model.Observation.ObservationReliability>(reader, errors);
                }

                // Parse element bodySite
                else if (atName == "bodySite")
                {
                    result.BodySite = CodeableConceptParser.ParseCodeableConcept(reader, errors);
                }

                // Parse element method
                else if (atName == "method")
                {
                    result.Method = CodeableConceptParser.ParseCodeableConcept(reader, errors);
                }

                // Parse element identifier
                else if (atName == "identifier")
                {
                    result.Identifier = IdentifierParser.ParseIdentifier(reader, errors);
                }

                // Parse element subject
                else if (atName == "subject")
                {
                    result.Subject = ResourceReferenceParser.ParseResourceReference(reader, errors);
                }

                // Parse element performer
                else if (atName == "performer")
                {
                    result.Performer = ResourceReferenceParser.ParseResourceReference(reader, errors);
                }

                // Parse element referenceRange
                else if (atName == "referenceRange")
                {
                    result.ReferenceRange = new List <Hl7.Fhir.Model.Observation.ObservationReferenceRangeComponent>();
                    reader.EnterArray();

                    while (ParserUtils.IsAtArrayElement(reader, "referenceRange"))
                    {
                        result.ReferenceRange.Add(ObservationParser.ParseObservationReferenceRangeComponent(reader, errors));
                    }

                    reader.LeaveArray();
                }

                // Parse element component
                else if (atName == "component")
                {
                    result.Component = new List <Hl7.Fhir.Model.Observation.ObservationComponentComponent>();
                    reader.EnterArray();

                    while (ParserUtils.IsAtArrayElement(reader, "component"))
                    {
                        result.Component.Add(ObservationParser.ParseObservationComponentComponent(reader, errors));
                    }

                    reader.LeaveArray();
                }

                else
                {
                    errors.Add(String.Format("Encountered unknown element {0} while parsing {1}", reader.CurrentElementName, currentElementName), reader);
                    reader.SkipSubElementsFor(currentElementName);
                    result = null;
                }
            }

            reader.LeaveElement();
            return(result);
        }