/// <summary>
        /// Deserialize JSON into a FHIR MedicationStatement
        /// </summary>
        public static void DeserializeJson(this MedicationStatement 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($"MedicationStatement >>> MedicationStatement.{propertyName}, depth: {reader.CurrentDepth}, pos: {reader.BytesConsumed}");
                    }
                    reader.Read();
                    current.DeserializeJsonProperty(ref reader, options, propertyName);
                }
            }

            throw new JsonException($"MedicationStatement: invalid state! depth: {reader.CurrentDepth}, pos: {reader.BytesConsumed}");
        }
        public void ShouldParseResponseMessage()
        {
            MedicationStatement expectedMedicationStatement = new MedicationStatement()
            {
                BrandName            = null,
                DateEntered          = DateTime.Today,
                DIN                  = "123456",
                Directions           = "DIRECTIONS",
                DispensedDate        = DateTime.Today.AddDays(-1),
                Dosage               = 1.555F,
                DrugDiscontinuedDate = null,
                GenericName          = "GENERICNAME   LABNAME   STRENGHT   TYPE",
                PharmacyId           = "BC123456",
                PractitionerSurname  = "DR.GATEWAY",
                PrescriptionStatus   = 'F',
                Quantity             = 55.5F
            };

            string        dateTime = DateTime.Now.ToString("yyyy/MM/dd HH:mm:ss", this.culture);
            string        date     = DateTime.Now.ToString("yyMMdd", this.culture);
            StringBuilder sb       = new StringBuilder();

            sb.Append($"MSH|^~\\&|{hnClientConfig.SendingApplication}|{hnClientConfig.SendingFacility}|{hnClientConfig.ReceivingApplication}|{hnClientConfig.ReceivingFacility}|{dateTime}|{userId}:{ipAddress}|ZPN|{traceNumber}|{hnClientConfig.ProcessingID}|{hnClientConfig.MessageVersion}\r");
            sb.Append($"ZCB|BCXXZZZYYY|{date}|{traceNumber}\r");
            sb.Append($"ZZZ|TRP|0|{traceNumber}|{hnClientConfig.ZZZ.PractitionerIdRef}|{hnClientConfig.ZZZ.PractitionerId}||0 Operation successful\r");
            sb.Append($"ZCC||||||||||{phn}\r");
            sb.Append("ZPB");

            // ZPB1 medical condition
            sb.Append("|ZPB1^THIS IS A CLINICAL CONDITION*AND IT HAS EXACTLY 56 BYTES^Y^DP^20170330^^^");

            // ZPB2 reactions
            sb.Append("|ZPB2^294322^ALLOPURINOL                   APOTEX INC     300 MG    TABLET^^^AE^20190815^*ADE_0427_Adverse Drug Reaction_Possible_Hospitalization^91^XXANR^20190815");

            // ZPB3 prescriptions
            sb.Append("|ZPB3^");

            sb.Append($"{expectedMedicationStatement.DIN}^");
            sb.Append($"{expectedMedicationStatement.GenericName}^N^");
            sb.Append($"{expectedMedicationStatement.Quantity.ToString("F1").Replace(".", string.Empty)}^");
            sb.Append($"{expectedMedicationStatement.Dosage.ToString("F3").Replace(".", string.Empty)}^^^");
            sb.Append($"{expectedMedicationStatement.PrescriptionStatus}^");
            sb.Append($"{expectedMedicationStatement.DispensedDate.ToString("yyyyMMdd")}^CACI^P1^XXALE^");
            sb.Append($"{expectedMedicationStatement.PractitionerSurname}^");
            sb.Append($"{expectedMedicationStatement.DrugDiscontinuedDate?.ToString("yyyyMMdd")}^^");
            sb.Append($"{expectedMedicationStatement.Directions}^^^^");
            sb.Append($"{expectedMedicationStatement.DateEntered?.ToString("yyyyMMdd")}^");
            sb.Append($"{expectedMedicationStatement.PharmacyId}^Y^5790");

            // Other prescriptions
            sb.Append("~ZPB3^572349^COLCHICINE                    ODAN LABS      0.6 MG    TABLET^N^70^1000^^^D^20190129^NI^P1^XXALE^PHARMACISTWITHLONGCHARACTERNAME#035^20190129^PR^ADAPTED RX AND DISCONTINUED^REASON FOR DISCONTINUATION^P1^XXALE^20190129^QAERXPP^Y^5788^HIGH^CHGD");
            sb.Append("~ZPB3^294322^ALLOPURINOL                   APOTEX INC     300 MG    TABLET^N^1200^4000^^^D^20190116^^91^XXALT^ABLEBODIED^20190116^PH^PRESCRIPTION # 16^REASON FOR DISCONTINUATION^P1^XXAKZ^20190116^BC000000QA^N");

            List <MedicationStatement> medicationStatements = this.parser.ParseResponseMessage(sb.ToString());

            Assert.Equal(3, medicationStatements.Count);
            Assert.True(expectedMedicationStatement.IsDeepEqual(medicationStatements.First()));
        }
        public void WhenMedicationStatementTransformedToHealthVault_MedicationReferenceWillThrowIfNotContained()
        {
            var medicationStatement = new MedicationStatement()
            {
                Medication = new ResourceReference("medication/832475"),
            };

            Assert.ThrowsException <NotImplementedException>(() => medicationStatement.ToHealthVault());
        }
        public void WhenMedicationStatementTransformedToHealthVault_MedicationReferenceReturnsNullIfContainedMedicationIsMissing()
        {
            var medicationStatement = new MedicationStatement()
            {
                Medication = new ResourceReference("#med"),
            };

            Assert.IsNull(medicationStatement.ToHealthVault());
        }
        public void WhenMedicationStatementTransformedToHealthVault_MedicationShouldBeEitherCodeableOrReference()
        {
            var medicationStatement = new MedicationStatement()
            {
                Medication = new Quantity()
                {
                    Value = 10
                }
            };

            Assert.ThrowsException <ArgumentOutOfRangeException>(() => medicationStatement.ToHealthVault());
        }
        public static ThingBase ToHealthVault(this MedicationStatement medicationStatement)
        {
            var fhirMedication = MedicationStatementHelper.ExtractEmbeddedMedication(medicationStatement);

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

            var hvMedication = fhirMedication.ToHealthVault() as HVMedication;

            if (medicationStatement.Dosage.Any())
            {
                var dosage = medicationStatement.Dosage.First();

                switch (dosage.Dose)
                {
                case null:
                    break;

                case SimpleQuantity doseQuantity:
                    var dose = new GeneralMeasurement {
                    };
                    dose.Structured.Add(new StructuredMeasurement
                    {
                        Value = (double)doseQuantity.Value,
                        Units = CodeToHealthVaultHelper.CreateCodableValueFromQuantityValues(doseQuantity.System, doseQuantity.Code, doseQuantity.Unit)
                    });
                    hvMedication.Dose = dose;
                    break;

                case Range doseRange:
                    throw new NotImplementedException();
                }

                Timing.RepeatComponent repeat = dosage.Timing?.Repeat;
                if (repeat?.Period != null && repeat?.PeriodUnit != null)
                {
                    var frequency = new GeneralMeasurement {
                    };
                    frequency.Structured.Add(new StructuredMeasurement
                    {
                        Value = (double)repeat.Period,
                        Units = CodeToHealthVaultHelper.GetRecurrenceIntervalFromPeriodUnit(repeat.PeriodUnit.Value)
                    });
                    hvMedication.Frequency = frequency;
                }

                var route = dosage.Route.ToCodableValue();
                hvMedication.Route = route;
            }
            return(hvMedication);
        }
Esempio n. 7
0
 private MedicationRequest ExtractEmbeddedMedicationRequest(MedicationStatement medicationStatement)
 {
     foreach (var reference in medicationStatement.BasedOn)
     {
         if (reference.IsContainedReference)
         {
             return(medicationStatement.Contained.First(resource
                                                        => reference.Matches(resource.GetContainerReference()) &&
                                                        resource.ResourceType == ResourceType.MedicationRequest) as MedicationRequest);
         }
     }
     throw new AssertInconclusiveException();
 }
        public void WhenMedicationStatementTransformedToHealthVault_MedicationCodeableConceptIsUsed()
        {
            const string medicationName      = "Amoxicillin 250mg/5ml Suspension";
            var          medicationStatement = new MedicationStatement()
            {
                Medication = new CodeableConcept()
                {
                    Text = medicationName
                }
            };

            var hvMedication = medicationStatement.ToHealthVault() as HVMedication;

            Assert.AreEqual(medicationName, hvMedication.Name.Text);
        }
Esempio n. 9
0
        public void TestValidateMedicationStatement(string xmlResource)
        {
            var assembly = Assembly.GetExecutingAssembly();
            var names    = assembly.GetManifestResourceNames();
            MedicationStatement medicationStatement = null;
            var       item      = names.FirstOrDefault(t => t.EndsWith(xmlResource));
            XDocument xDocument = null;

            if (item != null)
            {
                using (var stream = assembly.GetManifestResourceStream(item))
                {
                    xDocument = XDocument.Load(stream);
                }
                medicationStatement = new FhirXmlParser().Parse <MedicationStatement>(xDocument.ToString());
            }
            Assert.IsNotNull(medicationStatement);

            var validResource = _profileValidator.Validate(medicationStatement, true, true);
            var xmlSerializer = new FhirXmlSerializer();

            Console.WriteLine(xmlSerializer.SerializeToString(validResource));
        }
        internal static MedicationStatement ToFhirInternal(HVMedication hvMedication, MedicationStatement medicationStatement)
        {
            var embeddedMedication = new FhirMedication();

            embeddedMedication.Id = "med" + Guid.NewGuid();

            medicationStatement.Contained.Add(ToFhirInternal(hvMedication, embeddedMedication));
            medicationStatement.Medication = embeddedMedication.GetContainerReference();

            medicationStatement.SetStatusAsActive();
            medicationStatement.SetTakenAsNotApplicable();

            medicationStatement.Dosage = AddDosage(hvMedication.Dose, hvMedication.Frequency, hvMedication.Route);

            if (hvMedication.Prescription != null)
            {
                var embeddedMedicationRequest = new MedicationRequest();
                embeddedMedicationRequest.Id = "medReq" + Guid.NewGuid();

                Practitioner prescribedBy = hvMedication.Prescription.PrescribedBy.ToFhir();
                prescribedBy.Id = "prac" + Guid.NewGuid();
                medicationStatement.Contained.Add(prescribedBy);

                MedicationRequest request = ToFhirInternal(hvMedication.Prescription, embeddedMedicationRequest);
                request.Medication = embeddedMedication.GetContainerReference();
                request.Requester  = new MedicationRequest.RequesterComponent
                {
                    Agent = prescribedBy.GetContainerReference()
                };
                medicationStatement.Contained.Add(request);
                medicationStatement.BasedOn.Add(embeddedMedicationRequest.GetContainerReference());
            }

            return(medicationStatement);
        }
        /// <summary>
        /// Serialize a FHIR MedicationStatement into JSON
        /// </summary>
        public static void SerializeJson(this MedicationStatement current, Utf8JsonWriter writer, JsonSerializerOptions options, bool includeStartObject = true)
        {
            if (includeStartObject)
            {
                writer.WriteStartObject();
            }
            writer.WriteString("resourceType", "MedicationStatement");
            // Complex: MedicationStatement, Export: MedicationStatement, 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.BasedOn != null) && (current.BasedOn.Count != 0))
            {
                writer.WritePropertyName("basedOn");
                writer.WriteStartArray();
                foreach (ResourceReference val in current.BasedOn)
                {
                    val.SerializeJson(writer, options, true);
                }
                writer.WriteEndArray();
            }

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

            writer.WriteString("status", Hl7.Fhir.Utility.EnumUtility.GetLiteral(current.StatusElement.Value));

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

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

            if (current.Medication != null)
            {
                switch (current.Medication)
                {
                case CodeableConcept v_CodeableConcept:
                    writer.WritePropertyName("medicationCodeableConcept");
                    v_CodeableConcept.SerializeJson(writer, options);
                    break;

                case ResourceReference v_ResourceReference:
                    writer.WritePropertyName("medicationReference");
                    v_ResourceReference.SerializeJson(writer, options);
                    break;
                }
            }
            writer.WritePropertyName("subject");
            current.Subject.SerializeJson(writer, options);

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

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

                case Period v_Period:
                    writer.WritePropertyName("effectivePeriod");
                    v_Period.SerializeJson(writer, options);
                    break;
                }
            }
            if (current.DateAssertedElement != null)
            {
                if (!string.IsNullOrEmpty(current.DateAssertedElement.Value))
                {
                    writer.WriteString("dateAsserted", current.DateAssertedElement.Value);
                }
                if (current.DateAssertedElement.HasExtensions() || (!string.IsNullOrEmpty(current.DateAssertedElement.ElementId)))
                {
                    JsonStreamUtilities.SerializeExtensionList(writer, options, "_dateAsserted", false, current.DateAssertedElement.Extension, current.DateAssertedElement.ElementId);
                }
            }

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

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

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

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

            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.Dosage != null) && (current.Dosage.Count != 0))
            {
                writer.WritePropertyName("dosage");
                writer.WriteStartArray();
                foreach (Dosage val in current.Dosage)
                {
                    val.SerializeJson(writer, options, true);
                }
                writer.WriteEndArray();
            }

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

                current.BasedOn = new List <ResourceReference>();

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

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

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

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

                current.PartOf = new List <ResourceReference>();

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

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

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

            case "status":
                if (reader.TokenType == JsonTokenType.Null)
                {
                    current.StatusElement = new Code <Hl7.Fhir.Model.MedicationStatement.MedicationStatusCodes>();
                    reader.Skip();
                }
                else
                {
                    current.StatusElement = new Code <Hl7.Fhir.Model.MedicationStatement.MedicationStatusCodes>(Hl7.Fhir.Utility.EnumUtility.ParseLiteral <Hl7.Fhir.Model.MedicationStatement.MedicationStatusCodes>(reader.GetString()));
                }
                break;

            case "_status":
                if (current.StatusElement == null)
                {
                    current.StatusElement = new Code <Hl7.Fhir.Model.MedicationStatement.MedicationStatusCodes>();
                }
                ((Hl7.Fhir.Model.Element)current.StatusElement).DeserializeJson(ref reader, options);
                break;

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

                current.StatusReason = new List <CodeableConcept>();

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

                current.DerivedFrom = new List <ResourceReference>();

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

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

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

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

                current.ReasonCode = new List <CodeableConcept>();

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

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

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

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

                current.ReasonReference = new List <ResourceReference>();

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

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

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

            case "note":
                if ((reader.TokenType != JsonTokenType.StartArray) || (!reader.Read()))
                {
                    throw new JsonException($"MedicationStatement 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($"MedicationStatement 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 "dosage":
                if ((reader.TokenType != JsonTokenType.StartArray) || (!reader.Read()))
                {
                    throw new JsonException($"MedicationStatement error reading 'dosage' expected StartArray, found {reader.TokenType}! depth: {reader.CurrentDepth}, pos: {reader.BytesConsumed}");
                }

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

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

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

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

            // Complex: MedicationStatement, Export: MedicationStatement, Base: DomainResource
            default:
                ((Hl7.Fhir.Model.DomainResource)current).DeserializeJsonProperty(ref reader, options, propertyName);
                break;
            }
        }
        public void WhenMedicationStatementTransformedToHealthVault_MedicationReferenceWillThrowIfNull()
        {
            var medicationStatement = new MedicationStatement();

            Assert.ThrowsException <ArgumentOutOfRangeException>(() => medicationStatement.ToHealthVault());
        }
 internal static Medication ExtractEmbeddedMedication(this MedicationStatement medicationStatement)
 {
     return(MedicationHelper.GetMedication(medicationStatement, medicationStatement.Medication));
 }
 private static void SetTakenAsNotApplicable(this MedicationStatement medicationStatement)
 {
     medicationStatement.Taken = MedicationStatement.MedicationStatementTaken.Na;
 }
 private static void SetStatusAsActive(this MedicationStatement medicationStatement)
 {
     medicationStatement.Status = MedicationStatement.MedicationStatementStatus.Active;
 }
        public void WhenMedicationStatementTransformedToHealthVault_ThenDosageIsCopiedToDoseFrequencyAndRoute()
        {
            var embeddedMedication = new FhirMedication()
            {
                Code = new CodeableConcept()
                {
                    Text = "Amoxicillin 250mg/5ml Suspension"
                }
            };
            string embeddedMedicationId = "med" + Guid.NewGuid();

            embeddedMedication.Id = embeddedMedicationId;

            const int    dosage              = 1;
            const int    period              = 8;
            const string routeCode           = "po";
            var          medicationStatement = new MedicationStatement()
            {
                Medication = new ResourceReference(embeddedMedicationId),
                Dosage     = new System.Collections.Generic.List <Dosage>
                {
                    new Dosage
                    {
                        Dose = new SimpleQuantity()
                        {
                            Value  = dosage,
                            Unit   = "Tablets",
                            System = HealthVaultVocabularies.GenerateSystemUrl
                                         (HealthVaultVocabularies.MedicationDoseUnits,
                                         HealthVaultVocabularies.Wc),
                            Code = "tablet"
                        },
                        Timing = new Timing
                        {
                            Repeat = new Timing.RepeatComponent
                            {
                                Period     = period,
                                PeriodUnit = Timing.UnitsOfTime.H
                            }
                        },
                        Route = new CodeableConcept
                        {
                            Text   = "By mouth",
                            Coding = new System.Collections.Generic.List <Coding>
                            {
                                new Coding
                                {
                                    Code   = routeCode,
                                    System = HealthVaultVocabularies.GenerateSystemUrl
                                                 (HealthVaultVocabularies.MedicationRoutes,
                                                 HealthVaultVocabularies.Wc),
                                    Version = "2"
                                }
                            }
                        }
                    }
                }
            };

            medicationStatement.Contained.Add(embeddedMedication);
            medicationStatement.Medication = embeddedMedication.GetContainerReference();

            var hvMedication = medicationStatement.ToHealthVault() as HVMedication;

            Assert.AreEqual(dosage, hvMedication?.Dose?.Structured?.First()?.Value);
            Assert.AreEqual(period, hvMedication?.Frequency?.Structured?.First()?.Value);
            Assert.AreEqual(routeCode, hvMedication?.Route?.First()?.Value);
        }