private static PersonItem GetProvider(this AllergyIntolerance allergyIntolerance)
        {
            if (allergyIntolerance.Asserter.IsContainedReference)
            {
                var containedReference = allergyIntolerance.Contained.SingleOrDefault(resouce =>
                                                                                      resouce.Id.Equals(allergyIntolerance.Asserter.Reference) && resouce.GetType().Equals(typeof(Practitioner)));

                if (containedReference == null)
                {
                    return(null);
                }

                return((containedReference as Practitioner).ToHealthVault());
            }

            if (string.IsNullOrEmpty(allergyIntolerance.Asserter.Display))
            {
                return(null);
            }

            return(new PersonItem()
            {
                Name = new Name(allergyIntolerance.Asserter.Display)
            });
        }
        /// <summary>
        /// Deserialize JSON into a FHIR AllergyIntolerance
        /// </summary>
        public static void DeserializeJson(this AllergyIntolerance current, ref Utf8JsonReader reader, JsonSerializerOptions options)
        {
            string propertyName;

            while (reader.Read())
            {
                if (reader.TokenType == JsonTokenType.EndObject)
                {
                    return;
                }

                if (reader.TokenType == JsonTokenType.PropertyName)
                {
                    propertyName = reader.GetString();
                    if (Hl7.Fhir.Serialization.FhirSerializerOptions.Debug)
                    {
                        Console.WriteLine($"AllergyIntolerance >>> AllergyIntolerance.{propertyName}, depth: {reader.CurrentDepth}, pos: {reader.BytesConsumed}");
                    }
                    reader.Read();
                    current.DeserializeJsonProperty(ref reader, options, propertyName);
                }
            }

            throw new JsonException($"AllergyIntolerance: invalid state! depth: {reader.CurrentDepth}, pos: {reader.BytesConsumed}");
        }
 public void TestIsAllergicToMedications02()
 {
     var allergyIntolerance = new AllergyIntolerance("http://fhirtest.uhn.ca/baseDstu2/");
     var patientID = 6116;
     var medications = new List<string>() { "NotARealMedicine" };
     var result = allergyIntolerance.IsAllergicToMedications(patientID, medications);
     Assert.False(result);
 }
 public void TestIsAllergicToMedications01()
 {
     var allergyIntolerance = new AllergyIntolerance("http://fhirtest.uhn.ca/baseDstu2/");
     var patientID = 6116;
     var medications = new List<string>() { "hYdRoCoDoNe" };
     var result = allergyIntolerance.IsAllergicToMedications(patientID, medications);
     Assert.True(result);
 }
        public void TheListOfAllergyIntolerancesShouldBeValid()
        {
            Lists.ForEach(list =>
            {
                AccessRecordSteps.BaseListParametersAreValid(list);

                // Added 1.2.1 RMB 1/10/2018
                list.Meta.VersionId.ShouldBeNull("List Meta VersionId should be Null");
                list.Meta.LastUpdated.ShouldBeNull("List Meta LastUpdated should be Null");

                //Alergy specific checks
                CheckForValidMetaDataInResource(list, FhirConst.StructureDefinitionSystems.kList);

                if (list.Title.Equals(FhirConst.ListTitles.kActiveAllergies))
                {
                    list.Code.Coding.First().Code.Equals("886921000000105");
                }
                else if (list.Title.Equals(FhirConst.ListTitles.kResolvedAllergies))
                {
                    // Changed from TBD to 1103671000000101 for 1.2.0 RMB 7/8/2018
                    list.Code.Coding.First().Code.Equals("1103671000000101");
                    // Amended github ref 89
                    // RMB 9/10/2018
                    // git hub ref 174 snomed code display set to Ended allergies
                    // RMB 23/1/19
                    //					list.Code.Coding.First().Display.ShouldBe("Ended allergies (record artifact)");
                    list.Code.Coding.First().Display.ShouldBe("Ended allergies");
                }

                if (list.Entry.Count > 0)
                {
                    list.Entry.ForEach(entry =>
                    {
                        entry.Item.ShouldNotBeNull("The item field must be populated for each list entry.");
                        entry.Item.Reference.ShouldMatch("AllergyIntolerance/.+|#.+");
                        if (entry.Item.IsContainedReference)
                        {
                            string id = entry.Item.Reference.Substring(1);
                            List <Resource> contained = list.Contained.Where(allergy => allergy.Id.Equals(id)).ToList();
                            contained.Count.ShouldBe(1);
                            contained.ForEach(allergy =>
                            {
                                AllergyIntolerance allergyIntolerance = (AllergyIntolerance)allergy;
                                allergyIntolerance.ClinicalStatus.Equals(AllergyIntolerance.AllergyIntoleranceClinicalStatus.Resolved);
                            });
                        }
                    });
                }

                if (list.Entry.Count == 0)
                {
                    list.EmptyReason.ShouldNotBeNull("The List's empty reason field must be populated if the list is empty.");
                    list.Note.ShouldNotBeNull("The List's note field must be populated if the list is empty.");
                }
            });
        }
Example #6
0
        public string PerformActionPOST(string allergyIntoleranceCode, string patientID)
        {
            var result = "";

            var allergyIntolerance = new AllergyIntolerance(url.Trim());

            result = allergyIntolerance.CreateAllergyIntolerance(patientID, allergyIntoleranceCode);

            return(result);
        }
        public void TestGetListOfMedicationAllergies02()
        {
            var allergyIntolerance = new AllergyIntolerance("http://fhirtest.uhn.ca/baseDstu2/");
            var patientID = 6116;
            var medications = new List<string>() { "tylenol" };
            var result = allergyIntolerance.GetListOfMedicationAllergies(patientID, medications).ToList();

            //The patient is not allergic to tylenol and we will be given an empty list.

            Assert.Equal(0,result.Count);
        }
        public void TestGetListOfMedicationAllergies01()
        {
            var allergyIntolerance = new AllergyIntolerance("http://fhirtest.uhn.ca/baseDstu2/");
            var patientID = 6116; //Patient ID for FHIR Server
            var medications = new List<string>() { "hydrocodone", "aspirin" }; //medications the patient is taking
            var result = allergyIntolerance.GetListOfMedicationAllergies(patientID, medications).ToList();
            
            //We know the medication we expect to see in this list should be hydrocodone
            //because patient is alergic

            Assert.Equal("hydrocodone", result[0]);
        }
Example #9
0
 private static void AddAsserter(this AllergyIntolerance allergyIntolerance, Practitioner practitioner)
 {
     if (practitioner != null)
     {
         practitioner.Id = $"#practitioner-{Guid.NewGuid()}";
         allergyIntolerance.Contained.Add(practitioner);
         allergyIntolerance.Asserter = new ResourceReference
         {
             Reference = practitioner.Id
         };
     }
 }
Example #10
0
        public DomainResource GetAllergyWithCategory(FhirClient fhirClient)
        {
            AllergyIntolerance allergyIntolerance = new AllergyIntolerance
            {
                ClinicalStatus     = AllergyIntolerance.AllergyIntoleranceClinicalStatus.Active,
                VerificationStatus = AllergyIntolerance.AllergyIntoleranceVerificationStatus.Confirmed,
                Patient            = new ResourceReference("Patient/example"),
                Category           = new List <AllergyIntolerance.AllergyIntoleranceCategory?>
                {
                    AllergyIntolerance.AllergyIntoleranceCategory.Food
                }
            };

            return(fhirClient.Create(allergyIntolerance));
        }
Example #11
0
        public System.Collections.Generic.List <Hl7.Fhir.Model.AllergyIntolerance> FHIR_SearchAllergies(string PatientId)
        {
            System.Collections.Generic.List <Hl7.Fhir.Model.AllergyIntolerance> As = new System.Collections.Generic.List <Hl7.Fhir.Model.AllergyIntolerance>();
            var client = new Hl7.Fhir.Rest.FhirClient(FHIR_EndPoint_PatientInfo);

            client.PreferredFormat = ResourceFormat.Json;
            Bundle bu = client.Search <Hl7.Fhir.Model.AllergyIntolerance> (new string[]
                                                                           { "patient=" + PatientId });

            foreach (Bundle.EntryComponent ent in bu.Entry)
            {
                AllergyIntolerance a = (AllergyIntolerance)ent.Resource;
                As.Add(a);
            }
            return(As);
        }
        // Added test for 'No information available' 1.2.0 RMB 7/8/2018
        private void checktheListsarevalidforapatientwithlegacyendReason()
        {
            List <List> resolved = Lists.Where(list => list.Title.Equals(FhirConst.ListTitles.kResolvedAllergies)).ToList();

            if (resolved.Count > 0)
            {
                List <Resource> resolvedAllergies = resolved.First().Contained.Where(resource => resource.ResourceType.Equals(ResourceType.AllergyIntolerance)).ToList();
                resolvedAllergies.ForEach(resource =>
                {
                    AllergyIntolerance endedAllergy = (AllergyIntolerance)resource;
                    Extension endAllergy            = endedAllergy.GetExtension(FhirConst.StructureDefinitionSystems.kAllergyEndExt);
                    endAllergy.ShouldNotBeNull();
                    Extension endReason = endAllergy.GetExtension("reasonEnded");
                    endReason.Value.ShouldNotBeNull();
                    endReason.Value.ToString().ShouldBe("No information available");
                });
            }
        }
Example #13
0
        public string PerformActionSEARCH(string patientID)
        {
            var result             = "";
            var allergyIntolerance = new AllergyIntolerance(url.Trim());
            // var allergyIntolerance = new AllergyIntolerance("http://fhirtest.uhn.ca/baseDstu2/");
            //var patientID = 6140; //Patient ID for FHIR Server

            // var medications = new List<string>() { "hydrocodone", "aspirin" }; //medications the patient is taking
            //var response = allergyIntolerance.GetListOfMedicationAllergies(patientID, medications).ToList();
            var response = allergyIntolerance.SearchKnownAllergiesOnPatientID(patientID);

            //var medicationCodes = response.Keys;
            //foreach (string m in medicationCodes)
            //{
            //    result += m;
            //}
            result = response;
            return(result);
        }
Example #14
0
        public async Task<ActionResult> CheckVerification(Models.Medicine med)
        {
            using(var dbcontext = new ApplicationDbContext())
            {
                var allergyIntolerance = new AllergyIntolerance(Constants.HapiFhirServerBase, userManager, authManager);

                var user = dbcontext.Users.FirstOrDefault(a => a.FhirPatientId == med.UserFhirID);
                int patientID;
                if(user == null || !int.TryParse(user.FhirPatientId, out patientID))
                {
                    return new HttpStatusCodeResult(404, "Patient not found");
                }
                if(string.IsNullOrWhiteSpace(user.FhirPatientId))
                {
                    //todo: figure out what to show if the patient has no fhir data setup
                    return new HttpStatusCodeResult(404, "Patient does not have FHIR data");
                }
                var medications = new List<string>() { med.Name };
                med.Found = await allergyIntolerance.IsAllergicToMedications(patientID, medications);
            }
            return View(med);
        }
        public void TheAllergyIntoleranceShouldBeValid()
        {
            AllAllergyIntolerances.AddRange(ActiveAllergyIntolerances);

            //Get the 'contained' resolved allergies from the resolved list
            List <List> resolved = Lists.Where(list => list.Title.Equals(FhirConst.ListTitles.kResolvedAllergies)).ToList();

            if (resolved.Count > 0)
            {
                List <Resource> resolvedAllergies = resolved.First().Contained.Where(resource => resource.ResourceType.Equals(ResourceType.AllergyIntolerance)).ToList();
                resolvedAllergies.ForEach(resource =>
                {
                    AllergyIntolerance allergy = (AllergyIntolerance)resource;
                    AllAllergyIntolerances.Add(allergy);
                });
            }

            TheAllergyIntoleranceRecorderShouldbeValid();
            TheAllergyIntoleranceClinicalStatusShouldbeValid();
            TheAllergyIntoleranceAssertedDateShouldBeValid();
            TheAllergyIntoleranceIdShouldBeValid();

            // Added check for Allergy Identifier should be set and be a GUID RMB 07-08-2016
            // SJD relaxed as no longer constrained to GUID
            TheAllergyIntoleranceIdentifierShouldBeValid();

            TheAllergyIntoleranceMetadataShouldBeValid();
            TheAllergyIntolerancePatientShouldBeValidAndResolvable();
            TheAllergyIntoleranceVerificationStatusShouldbeValid();
            TheAllergyIntoleranceReactionShouldBeValid();
            TheAllergyIntoleranceEndDateShouldBeValid();
            TheAllergyIntoleranceCodeShouldbeValid();
            TheListOfAllergyIntolerancesShouldBeValid();
            TheAllergyIntoleranceCategoryShouldbeValid();
            TheAllergyIntoleranceEncounterShouldBeValid();
            // Added 1.2.1 RMB 1/10/2018
            TheAllergyIntoleranceNotInUseShouldBeValid();
        }
Example #16
0
        private static void SetAllergyIntoleranceCategory(this AllergyIntolerance allergyIntolerance, CodableValue allergenType, Extension allergyExtension)
        {
            List <AllergyIntoleranceCategory?> lstAllergyIntoleranceCategory = new List <AllergyIntoleranceCategory?>();
            string aValue = allergenType.FirstOrDefault().Value;
            AllergyIntoleranceCategory allergyIntoleranceCategory;

            if (aValue != null)
            {
                if (Enum.TryParse(aValue, true, out allergyIntoleranceCategory))
                {
                    lstAllergyIntoleranceCategory.Add(allergyIntoleranceCategory);
                }
                else
                {
                    allergyExtension.AddExtension(HealthVaultExtensions.AllergenType, new FhirString(aValue));
                }
            }

            if (lstAllergyIntoleranceCategory.Count > 0)
            {
                allergyIntolerance.Category = lstAllergyIntoleranceCategory;
            }
        }
Example #17
0
        public static Bundle MapFromCDRToFHirModelBundle(XmlDocument xml, string uri)
        {
            Bundle bundle = new Bundle();

            var resourcesAl1 = xml.SelectNodes("//AL1_PatientAllergyInformation");

            foreach (XmlNode item in resourcesAl1)
            {
                AllergyIntolerance allergy = MapFromCDRToFHirModel(item);
                //bundle.AddResourceEntry(allergy, $"{uri}/{allergy.Id}");
                bundle.AddResourceEntry(allergy, string.Format("{0}/{1}", uri, allergy.Id));
            }

            var resourcesIAM = xml.SelectNodes("//IAM_PatientAdverseReactionInformation");

            foreach (XmlNode item in resourcesIAM)
            {
                AllergyIntolerance allergy = MapFromCDRToFHirModel(item);
                //bundle.AddResourceEntry(allergy, $"{uri}/{allergy.Id}");
                bundle.AddResourceEntry(allergy, string.Format("{0}/{1}", uri, allergy.Id));
            }

            return(bundle);
        }
        public static Allergy ToHealthVault(this AllergyIntolerance allergyIntolerance)
        {
            if (allergyIntolerance.Code.IsNullOrEmpty())
            {
                throw new System.ArgumentException($"Can not transform a {typeof(AllergyIntolerance)} with no code into {typeof(Allergy)}");
            }

            var allergy = allergyIntolerance.ToThingBase <Allergy>();

            string allergenType     = string.Empty;
            var    allergyExtension = allergyIntolerance.GetExtension(HealthVaultExtensions.Allergy);

            if (allergyExtension != null)
            {
                allergenType         = allergyExtension.GetStringExtension(HealthVaultExtensions.AllergenType);
                allergy.AllergenCode = allergyExtension.GetExtensionValue <CodeableConcept>(HealthVaultExtensions.AllergenCode)?.ToCodableValue();
                allergy.Treatment    = allergyExtension.GetExtensionValue <CodeableConcept>(HealthVaultExtensions.AllergyTreatement)?.ToCodableValue();
            }

            var coding = allergyIntolerance.Code.Coding.FirstOrDefault();

            if (coding != null)
            {
                if (HealthVaultVocabularies.SystemContainsHealthVaultUrl(coding.System))
                {
                    allergy.Name = allergyIntolerance.Code.ToCodableValue();
                }
                else
                {
                    allergy.SetAllergyName(
                        coding.Display,
                        coding.Code,
                        HealthVaultVocabularies.Fhir,
                        coding.System,
                        coding.Version);
                }
            }

            if (allergyIntolerance.Reaction != null && allergyIntolerance.Reaction.Count > 0)
            {
                var code = allergyIntolerance.Reaction.First().Manifestation.First().Coding.FirstOrDefault();
                if (code != null)
                {
                    if (HealthVaultVocabularies.SystemContainsHealthVaultUrl(code.System))
                    {
                        allergy.Reaction = allergyIntolerance.Reaction.First().Manifestation.First().ToCodableValue();
                    }
                    else
                    {
                        allergy.SetAllergyReaction(
                            code.Display,
                            code.Code,
                            HealthVaultVocabularies.Fhir,
                            code.System,
                            code.Version);
                    }
                }
            }

            if (allergyIntolerance.Onset != null)
            {
                allergy.FirstObserved = allergyIntolerance.Onset.ToAproximateDateTime();
            }

            if (!string.IsNullOrWhiteSpace(allergenType))
            {
                allergy.AllergenType = new CodableValue(allergenType)
                {
                    new CodedValue(allergenType, HealthVaultVocabularies.AllergenType, HealthVaultVocabularies.Wc, "1")
                };
            }
            else if (allergyIntolerance.Category != null && allergyIntolerance.Category.Count() > 0)
            {
                allergy.AllergenType = new CodableValue(allergyIntolerance.Category.First().Value.ToString())
                {
                    new CodedValue(allergyIntolerance.Category.First().Value.ToString(), FhirCategories.HL7Allergy, HealthVaultVocabularies.Fhir, "")
                };
            }

            if (allergyIntolerance.ClinicalStatus.HasValue)
            {
                if ((allergyIntolerance.ClinicalStatus.Value == (AllergyIntoleranceClinicalStatus.Resolved)) || (allergyIntolerance.ClinicalStatus.Value == (AllergyIntoleranceClinicalStatus.Inactive)))
                {
                    allergy.IsNegated = true;
                }
                else
                {
                    allergy.IsNegated = false;
                }
            }

            if (allergyIntolerance.Asserter != null)
            {
                allergy.TreatmentProvider = GetProvider(allergyIntolerance);
            }

            return(allergy);
        }
        /// <summary>
        /// Serialize a FHIR AllergyIntolerance into JSON
        /// </summary>
        public static void SerializeJson(this AllergyIntolerance current, Utf8JsonWriter writer, JsonSerializerOptions options, bool includeStartObject = true)
        {
            if (includeStartObject)
            {
                writer.WriteStartObject();
            }
            writer.WriteString("resourceType", "AllergyIntolerance");
            // Complex: AllergyIntolerance, Export: AllergyIntolerance, Base: DomainResource (DomainResource)
            ((Hl7.Fhir.Model.DomainResource)current).SerializeJson(writer, options, false);

            if ((current.Identifier != null) && (current.Identifier.Count != 0))
            {
                writer.WritePropertyName("identifier");
                writer.WriteStartArray();
                foreach (Identifier val in current.Identifier)
                {
                    val.SerializeJson(writer, options, true);
                }
                writer.WriteEndArray();
            }

            if (current.ClinicalStatus != null)
            {
                writer.WritePropertyName("clinicalStatus");
                current.ClinicalStatus.SerializeJson(writer, options);
            }

            if (current.VerificationStatus != null)
            {
                writer.WritePropertyName("verificationStatus");
                current.VerificationStatus.SerializeJson(writer, options);
            }

            if (current.TypeElement != null)
            {
                if (current.TypeElement.Value != null)
                {
                    writer.WriteString("type", Hl7.Fhir.Utility.EnumUtility.GetLiteral(current.TypeElement.Value));
                }
                if (current.TypeElement.HasExtensions() || (!string.IsNullOrEmpty(current.TypeElement.ElementId)))
                {
                    JsonStreamUtilities.SerializeExtensionList(writer, options, "_type", false, current.TypeElement.Extension, current.TypeElement.ElementId);
                }
            }

            if ((current.CategoryElement != null) && (current.CategoryElement.Count != 0))
            {
                int valueCount     = 0;
                int extensionCount = 0;
                foreach (Code <Hl7.Fhir.Model.AllergyIntolerance.AllergyIntoleranceCategory> val in current.CategoryElement)
                {
                    if (val.Value != null)
                    {
                        valueCount++;
                    }
                    if (val.HasExtensions())
                    {
                        extensionCount++;
                    }
                }

                if (valueCount > 0)
                {
                    writer.WritePropertyName("category");
                    writer.WriteStartArray();
                    foreach (Code <Hl7.Fhir.Model.AllergyIntolerance.AllergyIntoleranceCategory> val in current.CategoryElement)
                    {
                        if (val.Value == null)
                        {
                            writer.WriteNullValue();
                        }
                        else
                        {
                            writer.WriteStringValue(Hl7.Fhir.Utility.EnumUtility.GetLiteral(val.Value));
                        }
                    }

                    writer.WriteEndArray();
                }

                if (extensionCount > 0)
                {
                    writer.WritePropertyName("_category");
                    writer.WriteStartArray();
                    foreach (Code <Hl7.Fhir.Model.AllergyIntolerance.AllergyIntoleranceCategory> val in current.CategoryElement)
                    {
                        if (val.HasExtensions() || (!string.IsNullOrEmpty(val.ElementId)))
                        {
                            JsonStreamUtilities.SerializeExtensionList(writer, options, string.Empty, true, val.Extension, val.ElementId);
                        }
                        else
                        {
                            writer.WriteNullValue();
                        }
                    }

                    writer.WriteEndArray();
                }
            }

            if (current.CriticalityElement != null)
            {
                if (current.CriticalityElement.Value != null)
                {
                    writer.WriteString("criticality", Hl7.Fhir.Utility.EnumUtility.GetLiteral(current.CriticalityElement.Value));
                }
                if (current.CriticalityElement.HasExtensions() || (!string.IsNullOrEmpty(current.CriticalityElement.ElementId)))
                {
                    JsonStreamUtilities.SerializeExtensionList(writer, options, "_criticality", false, current.CriticalityElement.Extension, current.CriticalityElement.ElementId);
                }
            }

            if (current.Code != null)
            {
                writer.WritePropertyName("code");
                current.Code.SerializeJson(writer, options);
            }

            writer.WritePropertyName("patient");
            current.Patient.SerializeJson(writer, options);

            if (current.Encounter != null)
            {
                writer.WritePropertyName("encounter");
                current.Encounter.SerializeJson(writer, options);
            }

            if (current.Onset != null)
            {
                switch (current.Onset)
                {
                case FhirDateTime v_FhirDateTime:
                    if (v_FhirDateTime != null)
                    {
                        if (!string.IsNullOrEmpty(v_FhirDateTime.Value))
                        {
                            writer.WriteString("onsetDateTime", v_FhirDateTime.Value);
                        }
                        if (v_FhirDateTime.HasExtensions() || (!string.IsNullOrEmpty(v_FhirDateTime.ElementId)))
                        {
                            JsonStreamUtilities.SerializeExtensionList(writer, options, "_onsetDateTime", false, v_FhirDateTime.Extension, v_FhirDateTime.ElementId);
                        }
                    }
                    break;

                case Age v_Age:
                    writer.WritePropertyName("onsetAge");
                    v_Age.SerializeJson(writer, options);
                    break;

                case Period v_Period:
                    writer.WritePropertyName("onsetPeriod");
                    v_Period.SerializeJson(writer, options);
                    break;

                case Range v_Range:
                    writer.WritePropertyName("onsetRange");
                    v_Range.SerializeJson(writer, options);
                    break;

                case FhirString v_FhirString:
                    if (v_FhirString != null)
                    {
                        if (!string.IsNullOrEmpty(v_FhirString.Value))
                        {
                            writer.WriteString("onsetString", v_FhirString.Value);
                        }
                        if (v_FhirString.HasExtensions() || (!string.IsNullOrEmpty(v_FhirString.ElementId)))
                        {
                            JsonStreamUtilities.SerializeExtensionList(writer, options, "_onsetString", false, v_FhirString.Extension, v_FhirString.ElementId);
                        }
                    }
                    break;
                }
            }
            if (current.RecordedDateElement != null)
            {
                if (!string.IsNullOrEmpty(current.RecordedDateElement.Value))
                {
                    writer.WriteString("recordedDate", current.RecordedDateElement.Value);
                }
                if (current.RecordedDateElement.HasExtensions() || (!string.IsNullOrEmpty(current.RecordedDateElement.ElementId)))
                {
                    JsonStreamUtilities.SerializeExtensionList(writer, options, "_recordedDate", false, current.RecordedDateElement.Extension, current.RecordedDateElement.ElementId);
                }
            }

            if (current.Recorder != null)
            {
                writer.WritePropertyName("recorder");
                current.Recorder.SerializeJson(writer, options);
            }

            if (current.Asserter != null)
            {
                writer.WritePropertyName("asserter");
                current.Asserter.SerializeJson(writer, options);
            }

            if (current.LastOccurrenceElement != null)
            {
                if (!string.IsNullOrEmpty(current.LastOccurrenceElement.Value))
                {
                    writer.WriteString("lastOccurrence", current.LastOccurrenceElement.Value);
                }
                if (current.LastOccurrenceElement.HasExtensions() || (!string.IsNullOrEmpty(current.LastOccurrenceElement.ElementId)))
                {
                    JsonStreamUtilities.SerializeExtensionList(writer, options, "_lastOccurrence", false, current.LastOccurrenceElement.Extension, current.LastOccurrenceElement.ElementId);
                }
            }

            if ((current.Note != null) && (current.Note.Count != 0))
            {
                writer.WritePropertyName("note");
                writer.WriteStartArray();
                foreach (Annotation val in current.Note)
                {
                    val.SerializeJson(writer, options, true);
                }
                writer.WriteEndArray();
            }

            if ((current.Reaction != null) && (current.Reaction.Count != 0))
            {
                writer.WritePropertyName("reaction");
                writer.WriteStartArray();
                foreach (AllergyIntolerance.ReactionComponent val in current.Reaction)
                {
                    val.SerializeJson(writer, options, true);
                }
                writer.WriteEndArray();
            }

            if (includeStartObject)
            {
                writer.WriteEndObject();
            }
        }
        /// <summary>
        /// Deserialize JSON into a FHIR AllergyIntolerance
        /// </summary>
        public static void DeserializeJsonProperty(this AllergyIntolerance current, ref Utf8JsonReader reader, JsonSerializerOptions options, string propertyName)
        {
            switch (propertyName)
            {
            case "identifier":
                if ((reader.TokenType != JsonTokenType.StartArray) || (!reader.Read()))
                {
                    throw new JsonException($"AllergyIntolerance error reading 'identifier' expected StartArray, found {reader.TokenType}! depth: {reader.CurrentDepth}, pos: {reader.BytesConsumed}");
                }

                current.Identifier = new List <Identifier>();

                while (reader.TokenType != JsonTokenType.EndArray)
                {
                    Hl7.Fhir.Model.Identifier v_Identifier = new Hl7.Fhir.Model.Identifier();
                    v_Identifier.DeserializeJson(ref reader, options);
                    current.Identifier.Add(v_Identifier);

                    if (!reader.Read())
                    {
                        throw new JsonException($"AllergyIntolerance error reading 'identifier' array, read failed! depth: {reader.CurrentDepth}, pos: {reader.BytesConsumed}");
                    }
                    if (reader.TokenType == JsonTokenType.EndObject)
                    {
                        reader.Read();
                    }
                }

                if (current.Identifier.Count == 0)
                {
                    current.Identifier = null;
                }
                break;

            case "clinicalStatus":
                current.ClinicalStatus = new Hl7.Fhir.Model.CodeableConcept();
                ((Hl7.Fhir.Model.CodeableConcept)current.ClinicalStatus).DeserializeJson(ref reader, options);
                break;

            case "verificationStatus":
                current.VerificationStatus = new Hl7.Fhir.Model.CodeableConcept();
                ((Hl7.Fhir.Model.CodeableConcept)current.VerificationStatus).DeserializeJson(ref reader, options);
                break;

            case "type":
                if (reader.TokenType == JsonTokenType.Null)
                {
                    current.TypeElement = new Code <Hl7.Fhir.Model.AllergyIntolerance.AllergyIntoleranceType>();
                    reader.Skip();
                }
                else
                {
                    current.TypeElement = new Code <Hl7.Fhir.Model.AllergyIntolerance.AllergyIntoleranceType>(Hl7.Fhir.Utility.EnumUtility.ParseLiteral <Hl7.Fhir.Model.AllergyIntolerance.AllergyIntoleranceType>(reader.GetString()));
                }
                break;

            case "_type":
                if (current.TypeElement == null)
                {
                    current.TypeElement = new Code <Hl7.Fhir.Model.AllergyIntolerance.AllergyIntoleranceType>();
                }
                ((Hl7.Fhir.Model.Element)current.TypeElement).DeserializeJson(ref reader, options);
                break;

            case "category":
                if ((reader.TokenType != JsonTokenType.StartArray) || (!reader.Read()))
                {
                    throw new JsonException($"AllergyIntolerance error reading 'category' expected StartArray, found {reader.TokenType}! depth: {reader.CurrentDepth}, pos: {reader.BytesConsumed}");
                }

                current.CategoryElement = new List <Code <Hl7.Fhir.Model.AllergyIntolerance.AllergyIntoleranceCategory> >();

                while (reader.TokenType != JsonTokenType.EndArray)
                {
                    if (reader.TokenType == JsonTokenType.Null)
                    {
                        current.CategoryElement.Add(new Code <Hl7.Fhir.Model.AllergyIntolerance.AllergyIntoleranceCategory>());
                        reader.Skip();
                    }
                    else
                    {
                        current.CategoryElement.Add(new Code <Hl7.Fhir.Model.AllergyIntolerance.AllergyIntoleranceCategory>(Hl7.Fhir.Utility.EnumUtility.ParseLiteral <Hl7.Fhir.Model.AllergyIntolerance.AllergyIntoleranceCategory>(reader.GetString())));
                    }

                    if (!reader.Read())
                    {
                        throw new JsonException($"AllergyIntolerance error reading 'category' array, read failed! depth: {reader.CurrentDepth}, pos: {reader.BytesConsumed}");
                    }
                    if (reader.TokenType == JsonTokenType.EndObject)
                    {
                        reader.Read();
                    }
                }

                if (current.CategoryElement.Count == 0)
                {
                    current.CategoryElement = null;
                }
                break;

            case "_category":
                if ((reader.TokenType != JsonTokenType.StartArray) || (!reader.Read()))
                {
                    throw new JsonException($"AllergyIntolerance error reading 'category' expected StartArray, found {reader.TokenType}! depth: {reader.CurrentDepth}, pos: {reader.BytesConsumed}");
                }

                int i_category = 0;

                while (reader.TokenType != JsonTokenType.EndArray)
                {
                    if (i_category >= current.CategoryElement.Count)
                    {
                        current.CategoryElement.Add(new Code <Hl7.Fhir.Model.AllergyIntolerance.AllergyIntoleranceCategory>());
                    }
                    if (reader.TokenType == JsonTokenType.Null)
                    {
                        reader.Skip();
                    }
                    else
                    {
                        ((Hl7.Fhir.Model.Element)current.CategoryElement[i_category++]).DeserializeJson(ref reader, options);
                    }

                    if (!reader.Read())
                    {
                        throw new JsonException($"AllergyIntolerance error reading 'category' array, read failed! depth: {reader.CurrentDepth}, pos: {reader.BytesConsumed}");
                    }
                    if (reader.TokenType == JsonTokenType.EndObject)
                    {
                        reader.Read();
                    }
                }
                break;

            case "criticality":
                if (reader.TokenType == JsonTokenType.Null)
                {
                    current.CriticalityElement = new Code <Hl7.Fhir.Model.AllergyIntolerance.AllergyIntoleranceCriticality>();
                    reader.Skip();
                }
                else
                {
                    current.CriticalityElement = new Code <Hl7.Fhir.Model.AllergyIntolerance.AllergyIntoleranceCriticality>(Hl7.Fhir.Utility.EnumUtility.ParseLiteral <Hl7.Fhir.Model.AllergyIntolerance.AllergyIntoleranceCriticality>(reader.GetString()));
                }
                break;

            case "_criticality":
                if (current.CriticalityElement == null)
                {
                    current.CriticalityElement = new Code <Hl7.Fhir.Model.AllergyIntolerance.AllergyIntoleranceCriticality>();
                }
                ((Hl7.Fhir.Model.Element)current.CriticalityElement).DeserializeJson(ref reader, options);
                break;

            case "code":
                current.Code = new Hl7.Fhir.Model.CodeableConcept();
                ((Hl7.Fhir.Model.CodeableConcept)current.Code).DeserializeJson(ref reader, options);
                break;

            case "patient":
                current.Patient = new Hl7.Fhir.Model.ResourceReference();
                ((Hl7.Fhir.Model.ResourceReference)current.Patient).DeserializeJson(ref reader, options);
                break;

            case "encounter":
                current.Encounter = new Hl7.Fhir.Model.ResourceReference();
                ((Hl7.Fhir.Model.ResourceReference)current.Encounter).DeserializeJson(ref reader, options);
                break;

            case "onsetDateTime":
                if (reader.TokenType == JsonTokenType.Null)
                {
                    current.Onset = new FhirDateTime();
                    reader.Skip();
                }
                else
                {
                    current.Onset = new FhirDateTime(reader.GetString());
                }
                break;

            case "_onsetDateTime":
                if (current.Onset == null)
                {
                    current.Onset = new FhirDateTime();
                }
                ((Hl7.Fhir.Model.Element)current.Onset).DeserializeJson(ref reader, options);
                break;

            case "onsetAge":
                current.Onset = new Hl7.Fhir.Model.Age();
                ((Hl7.Fhir.Model.Age)current.Onset).DeserializeJson(ref reader, options);
                break;

            case "onsetPeriod":
                current.Onset = new Hl7.Fhir.Model.Period();
                ((Hl7.Fhir.Model.Period)current.Onset).DeserializeJson(ref reader, options);
                break;

            case "onsetRange":
                current.Onset = new Hl7.Fhir.Model.Range();
                ((Hl7.Fhir.Model.Range)current.Onset).DeserializeJson(ref reader, options);
                break;

            case "onsetString":
                if (reader.TokenType == JsonTokenType.Null)
                {
                    current.Onset = new FhirString();
                    reader.Skip();
                }
                else
                {
                    current.Onset = new FhirString(reader.GetString());
                }
                break;

            case "_onsetString":
                if (current.Onset == null)
                {
                    current.Onset = new FhirString();
                }
                ((Hl7.Fhir.Model.Element)current.Onset).DeserializeJson(ref reader, options);
                break;

            case "recordedDate":
                if (reader.TokenType == JsonTokenType.Null)
                {
                    current.RecordedDateElement = new FhirDateTime();
                    reader.Skip();
                }
                else
                {
                    current.RecordedDateElement = new FhirDateTime(reader.GetString());
                }
                break;

            case "_recordedDate":
                if (current.RecordedDateElement == null)
                {
                    current.RecordedDateElement = new FhirDateTime();
                }
                ((Hl7.Fhir.Model.Element)current.RecordedDateElement).DeserializeJson(ref reader, options);
                break;

            case "recorder":
                current.Recorder = new Hl7.Fhir.Model.ResourceReference();
                ((Hl7.Fhir.Model.ResourceReference)current.Recorder).DeserializeJson(ref reader, options);
                break;

            case "asserter":
                current.Asserter = new Hl7.Fhir.Model.ResourceReference();
                ((Hl7.Fhir.Model.ResourceReference)current.Asserter).DeserializeJson(ref reader, options);
                break;

            case "lastOccurrence":
                if (reader.TokenType == JsonTokenType.Null)
                {
                    current.LastOccurrenceElement = new FhirDateTime();
                    reader.Skip();
                }
                else
                {
                    current.LastOccurrenceElement = new FhirDateTime(reader.GetString());
                }
                break;

            case "_lastOccurrence":
                if (current.LastOccurrenceElement == null)
                {
                    current.LastOccurrenceElement = new FhirDateTime();
                }
                ((Hl7.Fhir.Model.Element)current.LastOccurrenceElement).DeserializeJson(ref reader, options);
                break;

            case "note":
                if ((reader.TokenType != JsonTokenType.StartArray) || (!reader.Read()))
                {
                    throw new JsonException($"AllergyIntolerance error reading 'note' expected StartArray, found {reader.TokenType}! depth: {reader.CurrentDepth}, pos: {reader.BytesConsumed}");
                }

                current.Note = new List <Annotation>();

                while (reader.TokenType != JsonTokenType.EndArray)
                {
                    Hl7.Fhir.Model.Annotation v_Note = new Hl7.Fhir.Model.Annotation();
                    v_Note.DeserializeJson(ref reader, options);
                    current.Note.Add(v_Note);

                    if (!reader.Read())
                    {
                        throw new JsonException($"AllergyIntolerance error reading 'note' array, read failed! depth: {reader.CurrentDepth}, pos: {reader.BytesConsumed}");
                    }
                    if (reader.TokenType == JsonTokenType.EndObject)
                    {
                        reader.Read();
                    }
                }

                if (current.Note.Count == 0)
                {
                    current.Note = null;
                }
                break;

            case "reaction":
                if ((reader.TokenType != JsonTokenType.StartArray) || (!reader.Read()))
                {
                    throw new JsonException($"AllergyIntolerance error reading 'reaction' expected StartArray, found {reader.TokenType}! depth: {reader.CurrentDepth}, pos: {reader.BytesConsumed}");
                }

                current.Reaction = new List <AllergyIntolerance.ReactionComponent>();

                while (reader.TokenType != JsonTokenType.EndArray)
                {
                    Hl7.Fhir.Model.AllergyIntolerance.ReactionComponent v_Reaction = new Hl7.Fhir.Model.AllergyIntolerance.ReactionComponent();
                    v_Reaction.DeserializeJson(ref reader, options);
                    current.Reaction.Add(v_Reaction);

                    if (!reader.Read())
                    {
                        throw new JsonException($"AllergyIntolerance error reading 'reaction' array, read failed! depth: {reader.CurrentDepth}, pos: {reader.BytesConsumed}");
                    }
                    if (reader.TokenType == JsonTokenType.EndObject)
                    {
                        reader.Read();
                    }
                }

                if (current.Reaction.Count == 0)
                {
                    current.Reaction = null;
                }
                break;

            // Complex: AllergyIntolerance, Export: AllergyIntolerance, Base: DomainResource
            default:
                ((Hl7.Fhir.Model.DomainResource)current).DeserializeJsonProperty(ref reader, options, propertyName);
                break;
            }
        }
Example #21
0
        internal static AllergyIntolerance ToFhirInternal(Allergy allergy, AllergyIntolerance allergyIntolerance)
        {
            var allergyExtension = new Extension
            {
                Url = HealthVaultExtensions.Allergy
            };

            allergyIntolerance.Code = allergy.Name.ToFhir();

            if (allergy.FirstObserved != null)
            {
                allergyIntolerance.Onset = allergy.FirstObserved.ToFhir();
            }

            if (allergy.AllergenType != null)
            {
                allergyIntolerance.SetAllergyIntoleranceCategory(allergy.AllergenType, allergyExtension);
            }

            if (allergy.Reaction != null)
            {
                allergyIntolerance.Reaction = new List <AllergyIntolerance.ReactionComponent>
                {
                    new AllergyIntolerance.ReactionComponent {
                        Manifestation = new List <CodeableConcept> {
                            allergy.Reaction.ToFhir()
                        },
                        Description = allergy.Reaction.Text
                    }
                };
            }

            if (allergy.TreatmentProvider != null)
            {
                allergyIntolerance.AddAsserter(allergy.TreatmentProvider.ToFhir());
            }

            if (allergy.Treatment != null)
            {
                allergyExtension.AddExtension(HealthVaultExtensions.AllergyTreatement, allergy.Treatment.ToFhir());
            }

            if (allergy.AllergenCode != null)
            {
                allergyExtension.AddExtension(HealthVaultExtensions.AllergenCode, allergy.AllergenCode.ToFhir());
            }

            if (allergy.IsNegated != null)
            {
                if (allergy.IsNegated.Value)
                {
                    allergyIntolerance.ClinicalStatus = AllergyIntoleranceClinicalStatus.Resolved;
                }
                else
                {
                    allergyIntolerance.ClinicalStatus = AllergyIntoleranceClinicalStatus.Active;
                }
            }

            if (allergy.CommonData != null && allergy.CommonData.Note != null)
            {
                var note = new Hl7.Fhir.Model.Annotation();
                note.Text = allergy.CommonData.Note;
                allergyIntolerance.Note = new List <Hl7.Fhir.Model.Annotation> {
                    note
                };
            }

            allergyIntolerance.Type = AllergyIntoleranceType.Allergy;
            allergyIntolerance.Extension.Add(allergyExtension);
            return(allergyIntolerance);
        }
Example #22
0
        public static AllergyIntolerance MapFromCDRToFHirModel(XmlNode xml)
        {
            // TODO : map this resource

            List <Annotation> annotationList = new List <Annotation>
            {
                new Annotation
                {
                    Text = GetElementToString(xml, "AllergyReactionCode") // TODO : what's the mapping ?????
                }
            };

            List <CodeableConcept> manifestationList = new List <CodeableConcept>
            {
                new CodeableConcept
                {
                    Text = GetElementToString(xml, "AllergyReactionCode"),
                }
            };

            List <AllergyIntolerance.ReactionComponent> reactionList = new List <AllergyIntolerance.ReactionComponent>
            {
                new AllergyIntolerance.ReactionComponent
                {
                    Severity      = GetSeverityFromHl7(GetElementToString(xml, "AllergySeverityCodeIdentifierId")), //Modified, add suffix Id
                    Manifestation = manifestationList,

                    Substance = new CodeableConcept
                    {
                        Coding = new List <Coding>
                        {
                            new Coding
                            {
                                Code    = GetElementToString(xml, "AllergenCodeMnemonicDescriptionIdentifierId"), //Modified, add suffix Id
                                Display = GetElementToString(xml, "AllergenCodeMnemonicDescriptionText"),
                                System  = GetElementToString(xml, "AllergenCodeMnemonicDescriptionNameOfCodingSystem")
                            }
                        },
                        Text = GetElementToString(xml, "AllergenCodeMnemonicDescriptionText")
                    }
                }
            };


            var assertedDate = GetElementToString(xml, "StatusedAtDateTimeTime"); // IAM

            if (string.IsNullOrEmpty(assertedDate))
            {
                assertedDate = GetElementToString(xml, "IdentificationDate");                                    // AL1
            }
            AllergyIntolerance allergy = new AllergyIntolerance
            {
                AssertedDate = assertedDate, // IAM-20
                Note         = annotationList,
                Reaction     = reactionList,
                //Code = new CodeableConcept
                //{
                //    Text = GetElementToString(xml, "AllergenCodeMnemonicDescriptionText"),
                //    Coding = new List<Coding>
                //    {
                //        new Coding
                //        {
                //            Display = GetElementToString(xml, "AllergenCodeMnemonicDescriptionText")
                //        }
                //    }
                //}
            };

            return(allergy);
        }