예제 #1
0
        private static OperationOutcome AddIssue(this OperationOutcome outcome, OperationOutcome.IssueSeverity severity, string message, OperationOutcome.IssueType issueType = OperationOutcome.IssueType.Unknown, CodeableConcept codeableConcept = null)
        {
            if (outcome.Issue == null)
            {
                outcome.Init();
            }

            var item = new OperationOutcome.IssueComponent();

            item.Severity    = severity;
            item.Diagnostics = message;
            item.Code        = issueType;
            item.Details     = codeableConcept;
            outcome.Issue.Add(item);
            return(outcome);
        }
        public static OperationOutcome CreateError(string diagnostics, CodeableConcept details, OperationOutcome.IssueType?issueType = null, bool spineError = false)
        {
            var issueTypeVal = issueType.HasValue ? issueType.Value : OperationOutcome.IssueType.Invalid;

            return(Create(OperationOutcome.IssueSeverity.Error, issueTypeVal, diagnostics, details, spineError));
        }
예제 #3
0
        private OperationOutcome processResult(string code, string system, string display, Coding coding, CodeableConcept codeableConcept, ValidateCodeResult result)
        {
            if (result?.Result?.Value == null)
            {
                throw Error.InvalidOperation($"Terminology service at {Endpoint.Endpoint.ToString()} did not return a result.");
            }

            var outcome = new OperationOutcome();

            if (result?.Result?.Value == false)
            {
                string message = result?.Message?.Value;

                if (message != null)
                {
                    outcome.AddIssue(message, Issue.TERMINOLOGY_CODE_NOT_IN_VALUESET);
                }
                else
                {
                    if (code != null && coding == null)
                    {
                        coding = new Coding(system, code, display);
                    }

                    // Serialize the code or coding to json for display purposes in the issue
                    var jsonSer     = new FhirJsonSerializer();
                    var codeDisplay = codeableConcept != null?jsonSer.SerializeToString(codeableConcept)
                                          : jsonSer.SerializeToString(coding);

                    outcome.AddIssue($"Validation of '{codeDisplay}' failed, but" +
                                     $"the terminology service at {Endpoint.Endpoint.ToString()} did not provide further details.",
                                     Issue.TERMINOLOGY_CODE_NOT_IN_VALUESET);
                }
            }

            return(outcome);
        }
        public Extension Convert(TemplateExtension extension)
        {
            var fhirExtension = new Extension()
            {
                Url = extension.Identifier
            };

            switch (extension.Type)
            {
            case "String":
                fhirExtension.Value = new FhirString(extension.Value);
                break;

            case "Integer":
                try
                {
                    fhirExtension.Value = new Integer(Int32.Parse(extension.Value));
                }
                catch { }
                break;

            case "Boolean":
                try
                {
                    fhirExtension.Value = new FhirBoolean(Boolean.Parse(extension.Value));
                }
                catch { }
                break;

            case "Date":
                fhirExtension.Value = new Date(extension.Value);
                break;

            case "DateTime":
                fhirExtension.Value = new FhirDateTime(extension.Value);
                break;

            case "Code":
                fhirExtension.Value = new Code(extension.Value);
                break;

            case "Coding":
            case "CodeableConcept":
                string[] valueSplit = extension.Value.Split('|');

                if (valueSplit.Length == 3)
                {
                    var coding = new Coding();
                    coding.Code    = valueSplit[0];
                    coding.Display = valueSplit[1];
                    coding.System  = valueSplit[2];

                    if (extension.Type == "Coding")
                    {
                        fhirExtension.Value = coding;
                    }
                    else
                    {
                        var codeableConcept = new CodeableConcept();
                        codeableConcept.Coding.Add(coding);
                        fhirExtension.Value = codeableConcept;
                    }
                }
                break;
            }

            if (fhirExtension.Value != null)
            {
                return(fhirExtension);
            }

            return(null);
        }
            }                                                                                                                                      // BuildMemberBase.cs:117

            // BuildMemberBase.cs:119
            // BuildMemberBase.cs:120
            /// <summary>
            /// Read item.
            /// </summary>
            public void ReadItem(BreastRadiologyDocument doc, Observation.ComponentComponent item)                                                 // BuildMemberBase.cs:123
            {                                                                                                                                      // BuildMemberBase.cs:124
                this.Value = (CodeableConcept)item.Value;                                                                                          // BuildMemberComponents.cs:53
            }                                                                                                                                      // BuildMemberBase.cs:127
예제 #6
0
        private static Parameters createTranslateConceptParams(Code code, FhirUri system, FhirString version, FhirUri valueSet, Coding coding, CodeableConcept codeableConcept, FhirUri target, IEnumerable <TranslateConceptDependency> dependencies)
        {
            if (target == null)
            {
                throw new ArgumentNullException("target");
            }

            var par = new Parameters().Add("target", target);

            if (code != null)
            {
                par.Add("code", code);
            }
            if (system != null)
            {
                par.Add("system", system);
            }
            if (version != null)
            {
                par.Add("version", version);
            }
            if (valueSet != null)
            {
                par.Add("valueSet", valueSet);
            }
            if (coding != null)
            {
                par.Add("coding", coding);
            }
            if (codeableConcept != null)
            {
                par.Add("codeableConcept", codeableConcept);
            }

            if (dependencies != null && dependencies.Any())
            {
                foreach (var dependency in dependencies)
                {
                    var dependencyPar = new List <Tuple <string, Base> >();

                    if (dependency.Element != null)
                    {
                        dependencyPar.Add(Tuple.Create("element", (Base)dependency.Element));
                    }
                    if (dependency.Concept != null)
                    {
                        dependencyPar.Add(Tuple.Create("concept", (Base)dependency.Concept));
                    }

                    par.Add("dependency", dependencyPar);
                }
            }

            return(par);
        }
예제 #7
0
 public static void SetType(this DocumentReference documentReference, CodeableConcept codeableConcept = null)
 {
     // Setting a generic Code to every DocumentReference for now
     documentReference.Type = codeableConcept ?? new CodeableConcept(VocabularyUris.Loinc, "51899-3", "Details Document", "Details Document");
 }
예제 #8
0
        /// <summary>
        /// Constructs the object which will be placed at the target FHIR location according the mapping rules and openEHR message values.
        /// </summary>
        /// <param name="adapter">The current adapter being processed.</param>
        /// <param name="node">The current node being processed.</param>
        /// <returns>Returns the constructed value to be placed at the target FHIR location.</returns>
        public object ConstructNewTargetValue(OpenEhrToFhirAdapterBase adapter, Component node, BaseMapping mapping, object oldValue = null)
        {
            object newTargetValue = null;

            // fhir resource destination
            var destination = node.NetPath(adapter.Mappings);

            // list + CodeableConcept combined logic i.e. substance:0|code or substance|code
            if (Regex.Match(node.Name, ":\\d+\\|+").Success ||
                Regex.Match(node.Name, $"{mapping.OpenEhrFieldPath}\\|+").Success ||
                Regex.Match(node.Name, $"{mapping.OpenEhrFieldPath}:\\d+").Success)
            {
                // Get all components of this codeable concept
                var siblingNodes = ((Composite)node.Parent).FindMany(mapping, new List <Component>()).Where(x => x.NetPath(adapter.Mappings) == destination).ToList();

                var system = ((Composite)siblingNodes.FirstOrDefault(x => x.Name.Contains("terminology")))?.Children[0].Name;
                var code   = ((Composite)siblingNodes.FirstOrDefault(x => x.Name.Contains("code")))?.Children[0].Name;
                var text   = ((Composite)siblingNodes.FirstOrDefault(x => x.Name.Contains("value")))?.Children[0].Name;

                if (system == null && code == null && text == null)
                {
                    newTargetValue = StringHelper.ParseOpenEhrCcString(((Composite)node).Children.First().Name);
                }
                else
                {
                    newTargetValue = new CodeableConcept(system, code, text);
                }

                if (GetType() == typeof(ConditionalMapping))
                {
                    // the type of codeable concept type to search for i.e. Terminology/Code/Value
                    var conditionalSearchType = ((ConditionalMapping)mapping).Conditions.First().Item1;

                    // the actual value to search for in order to match the conditional mapping
                    var conditionalSearchValue = string.Empty;

                    switch (conditionalSearchType)
                    {
                    case "code":
                    {
                        conditionalSearchValue = code;
                        break;
                    }

                    case "terminology":
                    {
                        conditionalSearchValue = system;
                        break;
                    }

                    case "value":
                    {
                        conditionalSearchValue = text;
                        break;
                    }
                    }

                    var metConditions = ((ConditionalMapping)mapping).Conditions.Where(x =>
                                                                                       string.Equals(x.Item2, conditionalSearchValue, StringComparison.InvariantCultureIgnoreCase))
                                        .ToList();

                    var destinationIsCollection = oldValue is IEnumerable;
                    if (destinationIsCollection)
                    {
                        if (((IList)oldValue).Count == 0)
                        {
                            var listGenericType = oldValue.GetType().GenericTypeArguments[0];
                            var codeGenericType = metConditions[0].Item3.GetType();
                            var list            = (IList)Activator.CreateInstance(typeof(List <>).MakeGenericType(listGenericType), null);
                            foreach (var metCondition in metConditions)
                            {
                                var obj = Activator.CreateInstance(typeof(Code <>).MakeGenericType(codeGenericType), metCondition.Item3);
                                list.Add(obj);
                            }

                            newTargetValue = list;
                        }
                    }
                    else
                    {
                        newTargetValue = metConditions[0].Item3;
                    }
                }
                else if (GetType() == typeof(ExtensionMapping))
                {
                    if (oldValue != null)
                    {
                        ((List <Extension>)oldValue).Add(new Extension(
                                                             ((ExtensionMapping)mapping).ExtensionFhirStructureDefinitionUrl,
                                                             new CodeableConcept(system, code, text)));
                        newTargetValue = oldValue;
                    }
                }

                // mark these nodes as processed so skip duplicate processing
                adapter.ProcessedNodes.AddRange(siblingNodes);
            }
            else
            {
                var siblingNodes = ((Composite)node.Parent).FindMany(mapping, new List <Component>()).Where(x => x.NetPath(adapter.Mappings) == destination).ToList();

                if (GetType() == typeof(ExtensionMapping))
                {
                    var childLeafValue = ((Composite)node).Children[0] as Composite;
                    ((List <Extension>)oldValue).Add(new Extension(((ExtensionMapping)mapping).ExtensionFhirStructureDefinitionUrl, new FhirString(childLeafValue?.Children[0].Name)));
                    newTargetValue = oldValue;
                }
                else
                {
                    if (siblingNodes.Count == 1)
                    {
                        newTargetValue = StringHelper.ParseOpenEhrCcString(((Composite)siblingNodes[0]).Children[0].Name);
                    }
                    else
                    {
                        var index  = node.ParentResourceIndex(adapter.Mappings);
                        var t_node = (Composite)siblingNodes.Where(x => x.NetPath(adapter.Mappings) == destination).ToList()[index];
                        newTargetValue = StringHelper.ParseOpenEhrCcString(t_node.Children[0].Name);
                    }
                }

                adapter.ProcessedNodes.AddRange(siblingNodes);
            }

            return(newTargetValue);
        }
예제 #9
0
        private DEMOGRAPHICS buildDemographic(Patient iPatient)
        {
            DEMOGRAPHICS result = new DEMOGRAPHICS();

            if (iPatient.Identifier.Count > 0)
            {
                // PERSON_ID
                result.PERSON_ID = iPatient.Id;

                // MRN
                foreach (Identifier i in iPatient.Identifier)
                {
                    if (i.Type != null)
                    {
                        foreach (var code in i.Type.Coding)
                        {
                            if (code.Code == "MR")
                            {
                                result.MRN = iPatient.Identifier.FirstOrDefault().Value;
                            }
                        }
                    }
                }

                // BIRTH_DATE
                if (iPatient.BirthDate != null)
                {
                    result.BIRTH_DATE = DateTime.ParseExact(iPatient.BirthDate, "yyyy-MM-dd", System.Globalization.CultureInfo.InvariantCulture);

                    // GENDER
                    if (iPatient.Gender != null)
                    {
                        if (iPatient.Gender == AdministrativeGender.Female)
                        {
                            result.GENDER = "F";
                        }
                        else if (iPatient.Gender == AdministrativeGender.Male)
                        {
                            result.GENDER = "M";
                        }
                        else if (iPatient.Gender == AdministrativeGender.Other)
                        {
                            result.GENDER = "O";
                        }
                        else if (iPatient.Gender == AdministrativeGender.Unknown)
                        {
                            result.GENDER = "U";
                        }
                        else
                        {
                            result.GENDER = "U";
                        }

                        // PRIMARY_LANGUAGE and NEEDS_INTERPRETER
                        if (iPatient.Communication.Count > 0)
                        {
                            string lang = iPatient.Communication.FirstOrDefault().Language.Coding.FirstOrDefault().Code;
                            int    end  = lang.IndexOf('-');
                            if (end < 0)
                            {
                                end = lang.Length < 4 ? lang.Length : 3;
                            }

                            result.PRIMARY_LANGUAGE = lang.Substring(0, end);

                            if (iPatient.Communication.FirstOrDefault().Preferred != null)
                            {
                                result.NEEDS_INTERPRETER = "S";
                            }
                            else
                            {
                                result.NEEDS_INTERPRETER = "";
                            }
                        }
                        else
                        {
                            result.PRIMARY_LANGUAGE  = "";
                            result.NEEDS_INTERPRETER = "";
                        }

                        // race
                        result.RACE1              = "UN";
                        result.RACE2              = "UN";
                        result.RACE3              = "UN";
                        result.RACE4              = "UN";
                        result.RACE5              = "UN";
                        result.HISPANIC           = "U";
                        result.SEXUAL_ORIENTATION = null;
                        result.GENDER_IDENTITY    = null;

                        if (iPatient.Extension.Count() > 0)
                        {
                            int race_count = 0;
                            foreach (Extension e in iPatient.Extension)
                            {
                                if (e.TypeName == "CodeableConcept")
                                {
                                    CodeableConcept c = (CodeableConcept)e.Value;

                                    if (c.Text == "race")
                                    {
                                        if (race_count == 0)
                                        {
                                            result.RACE1 = RaceAbbreviationGivenConceptCode(c.Coding.FirstOrDefault().Code);
                                            race_count++;
                                        }
                                        else if (race_count == 1)
                                        {
                                            result.RACE2 = RaceAbbreviationGivenConceptCode(c.Coding.FirstOrDefault().Code);
                                            race_count++;
                                        }
                                        else if (race_count == 2)
                                        {
                                            result.RACE3 = RaceAbbreviationGivenConceptCode(c.Coding.FirstOrDefault().Code);
                                            race_count++;
                                        }
                                        else if (race_count == 3)
                                        {
                                            result.RACE4 = RaceAbbreviationGivenConceptCode(c.Coding.FirstOrDefault().Code);
                                            race_count++;
                                        }
                                        else if (race_count == 4)
                                        {
                                            result.RACE5 = RaceAbbreviationGivenConceptCode(c.Coding.FirstOrDefault().Code);
                                            race_count++;
                                        }
                                    }

                                    if (c.Text == "ethnicity")
                                    {
                                        result.HISPANIC = EthnicityAbbreviationGivenConceptCode(c.Coding.FirstOrDefault().Code);
                                    }
                                }
                            }

                            // SEXUAL_ORIENTATION
                            result.SEXUAL_ORIENTATION = null;

                            // GENDER_IDENTITY
                            result.GENDER_IDENTITY = null;
                        }
                    }
                    else
                    {
                        // missing gender
                        log.Info("Error: Missing gender for " + iPatient.Id);
                        result = null;
                    }
                }
                else
                {
                    // Invalid Birth Date
                    log.Info("Error: Missing Birthdate for " + iPatient.Id);
                    result = null;
                }
            }

            return(result);
        }
예제 #10
0
        private Questionnaire.ItemComponent CreateItemComponentV2(QuestionnaireItem2 item)
        {
            Questionnaire.QuestionnaireItemType?itemType = EnumUtility.ParseLiteral <Questionnaire.QuestionnaireItemType>(item.Type);
            if (!itemType.HasValue)
            {
                throw new Exception($"QuestionnaireItemType at question with linkId: {item.LinkId} is not conforming to any valid literals. QuestionnaireItemType: {item.Type}");
            }

            Questionnaire.ItemComponent itemComponent = new Questionnaire.ItemComponent
            {
                Type = itemType,
            };

            itemComponent.LinkId = string.IsNullOrWhiteSpace(item.LinkId) ? null : item.LinkId;
            itemComponent.Prefix = string.IsNullOrWhiteSpace(item.Prefix) ? null : item.Prefix;
            itemComponent.Text   = string.IsNullOrWhiteSpace(item.Text) ? null : item.Text;
            if (!string.IsNullOrWhiteSpace(item.EnableWhen))
            {
                itemComponent.EnableWhen = ParseEnableWhen(item.EnableWhen).ToList();
                // TODO: Defaults to 'any' in the first iteration of "migrate to R4".
                itemComponent.EnableBehavior = Questionnaire.EnableWhenBehavior.Any;
            }
            if (itemType != Questionnaire.QuestionnaireItemType.Group && itemType != Questionnaire.QuestionnaireItemType.Display)
            {
                itemComponent.Required = item.Required.HasValue ? item.Required : null;
                itemComponent.ReadOnly = item.ReadOnly;
                itemComponent.Initial  = string.IsNullOrEmpty(item.Initial)
                    ? null
                    : new List <Questionnaire.InitialComponent> {
                    new Questionnaire.InitialComponent {
                        Value = GetElement(itemType.Value, item.Initial)
                    }
                };
                itemComponent.MaxLength = item.MaxLength.HasValue ? item.MaxLength : null;
            }

            if (itemType != Questionnaire.QuestionnaireItemType.Display)
            {
                itemComponent.Repeats = item.Repeats;
            }

            if (!string.IsNullOrWhiteSpace(item.ValidationText))
            {
                itemComponent.SetStringExtension(Constants.ValidationTextUri, item.ValidationText);
            }

            if (!string.IsNullOrWhiteSpace(item.Options) && item.Options.IndexOf('#') == 0)
            {
                itemComponent.AnswerValueSetElement = new Canonical($"#{item.Options.Substring(1)}");
            }
            else if (!string.IsNullOrWhiteSpace(item.Options) &&
                     (item.Options.IndexOf("http://") == 0 || item.Options.IndexOf("https://") == 0))
            {
                itemComponent.AnswerValueSetElement = new Canonical(item.Options);
            }

            if (!string.IsNullOrWhiteSpace(item.EntryFormat))
            {
                itemComponent.SetStringExtension(Constants.EntryFormatUri, item.EntryFormat);
            }

            if (item.MaxValueInteger.HasValue)
            {
                itemComponent.SetIntegerExtension(Constants.MaxValueUri, item.MaxValueInteger.Value);
            }
            if (item.MinValueInteger.HasValue)
            {
                itemComponent.SetIntegerExtension(Constants.MinValueUri, item.MinValueInteger.Value);
            }

            if (item.MaxValueDate.HasValue)
            {
                itemComponent.SetExtension(Constants.MaxValueUri, new FhirDateTime(new DateTimeOffset(item.MaxValueDate.Value.ToUniversalTime())));
            }
            if (item.MinValueDate.HasValue)
            {
                itemComponent.SetExtension(Constants.MinValueUri, new FhirDateTime(new DateTimeOffset(item.MinValueDate.Value.ToUniversalTime())));
            }

            if (item.MinLength.HasValue)
            {
                itemComponent.SetIntegerExtension(Constants.MinLenghtUri, item.MinLength.Value);
            }

            if (item.MaxDecimalPlaces.HasValue)
            {
                itemComponent.SetIntegerExtension(Constants.MaxDecimalPlacesUri, item.MaxDecimalPlaces.Value);
            }

            if (!string.IsNullOrWhiteSpace(item.RepeatsText))
            {
                itemComponent.SetStringExtension(Constants.RepeatsTextUri, item.RepeatsText);
            }

            if (!string.IsNullOrWhiteSpace(item.ItemControl))
            {
                CodeableConcept codeableConcept = new CodeableConcept
                {
                    Coding = new List <Coding> {
                        new Coding
                        {
                            System = Constants.ItemControlSystem,
                            Code   = item.ItemControl
                        }
                    }
                };

                itemComponent.SetExtension(Constants.ItemControlUri, codeableConcept);
            }

            if (item.MaxOccurs.HasValue)
            {
                itemComponent.SetIntegerExtension(Constants.MaxOccursUri, item.MaxOccurs.Value);
            }
            if (item.MinOccurs.HasValue)
            {
                itemComponent.SetIntegerExtension(Constants.MinOccursUri, item.MinOccurs.Value);
            }

            if (!string.IsNullOrWhiteSpace(item.Regex))
            {
                itemComponent.SetStringExtension(Constants.RegexUri, item.Regex);
            }

            if (!string.IsNullOrWhiteSpace(item.Markdown))
            {
                if (itemComponent.Text == null)
                {
                    throw new MissingRequirementException($"Question with linkId: {item.LinkId}. The 'Text' attribute is required when setting the 'Markdown' extension so that form fillers which do not support the 'Markdown' extension still can display informative text to the user.");
                }
                itemComponent.TextElement.SetExtension(Constants.RenderingMarkdownUri, new Markdown(item.Markdown));
            }
            if (!string.IsNullOrWhiteSpace(item.Unit))
            {
                Coding unitCoding = ParseCoding(item.Unit);
                itemComponent.SetExtension(Constants.QuestionnaireUnitUri, unitCoding);
            }

            if (!string.IsNullOrWhiteSpace(item.Code))
            {
                itemComponent.Code = ParseArrayOfCoding(item.Code);
            }

            if (!string.IsNullOrWhiteSpace(item.Option))
            {
                List <Element> options = ParseArrayOfElement(item.Option);
                foreach (DataType element in options)
                {
                    if (element is ResourceReference)
                    {
                        itemComponent.AddExtension(Constants.OptionReferenceUri, element);
                    }
                    else
                    {
                        itemComponent.AnswerOption.Add(new Questionnaire.AnswerOptionComponent {
                            Value = element
                        });
                    }
                }
            }

            if (!string.IsNullOrWhiteSpace(item.FhirPathExpression))
            {
                itemComponent.SetStringExtension(Constants.FhirPathUri, item.FhirPathExpression);
            }

            if (item.Hidden)
            {
                itemComponent.SetBoolExtension(Constants.QuestionnaireItemHidden, item.Hidden);
            }

            if (item.AttachmentMaxSize.HasValue && itemComponent.Type == Questionnaire.QuestionnaireItemType.Attachment)
            {
                itemComponent.SetExtension(Constants.QuestionnaireAttachmentMaxSize, new FhirDecimal(item.AttachmentMaxSize));
            }

            if (!string.IsNullOrWhiteSpace(item.CalculatedExpression))
            {
                itemComponent.SetStringExtension(Constants.CalculatedExpressionUri, item.CalculatedExpression);
            }

            if (!string.IsNullOrWhiteSpace(item.GuidanceAction))
            {
                itemComponent.SetStringExtension(Constants.GuidanceActionUri, item.GuidanceAction.Trim());
            }

            if (!string.IsNullOrWhiteSpace(item.GuidanceParameter))
            {
                itemComponent.SetStringExtension(Constants.GuidanceParameterUri, $"hn_frontend_{item.GuidanceParameter.Trim()}");
            }

            if (!string.IsNullOrWhiteSpace(item.FhirPathValidation))
            {
                itemComponent.SetStringExtension(Constants.FhirPathValidationUri, item.FhirPathValidation);
            }

            if (!string.IsNullOrWhiteSpace(item.FhirPathMaxValue))
            {
                itemComponent.SetStringExtension(Constants.SdfMaxValueUri, item.FhirPathMaxValue);
            }

            if (!string.IsNullOrWhiteSpace(item.FhirPathMinValue))
            {
                itemComponent.SetStringExtension(Constants.SdfMinValueUri, item.FhirPathMinValue);
            }

            if (!string.IsNullOrWhiteSpace(item.EnableBehavior))
            {
                itemComponent.EnableBehavior = EnumUtility.ParseLiteral <Questionnaire.EnableWhenBehavior>(item.EnableBehavior.ToLowerInvariant());
            }

            return(itemComponent);
        }
예제 #11
0
        public static bool SaveLabObservation(LabObserveration labObs)
        {
            Observation obs = new Observation();

            var patIdentifier = labObs.FHIR_Identifier;

            Hl7.Fhir.Model.Patient patient = new  Hl7.Fhir.Model.Patient();
            var    client = new Hl7.Fhir.Rest.FhirClient(FHIR_EndPoint);
            Bundle bu     = client.Search <Hl7.Fhir.Model.Patient> (new string[]
                                                                    { "identifier=" + patIdentifier });

            foreach (Bundle.EntryComponent entry in bu.Entry)
            {
                string ResourceType = entry.Resource.TypeName;
                if (ResourceType == "Patient")
                {
                    patient = (Patient)entry.Resource;
                    break;
                }
            }

            obs.Subject = new ResourceReference()
            {
                Display   = patient.Name[0].ToString(),
                Reference = "Patient/" + patient.Id
            };

            obs.Effective = new FhirDateTime(DateTimeOffset.Parse(labObs.EffectiveDate.ToString()));

            Quantity quantity = new Quantity()
            {
                Value  = Convert.ToDecimal(labObs.ValueQuantity),
                Code   = labObs.ValueUnit,
                System = "http://unitsofmeasure.org",
                Unit   = labObs.ValueUnit
            };

            obs.Value = quantity;

            //Observation Code
            CodeableConcept ccu = new CodeableConcept();
            Coding          cu  = new Coding("http://loinc.org", labObs.Code);

            ccu.Coding = new List <Coding> {
                cu
            };
            obs.Code = ccu;

            obs.Status = (ObservationStatus)Enum.Parse(typeof(ObservationStatus), labObs.Status);

            Meta md = new Meta();

            md.Profile = new string[] { "urn:" + "http://myorganization.org/StructureDefinition/us-core-patient" };
            obs.Meta   = md;

            String DivNarrative =
                "<div xmlns='http://www.w3.org/1999/xhtml'>" +
                "Code:" + obs.Code.Coding.FirstOrDefault().Code + "<br/>" +
                "Status:" + obs.Status + "<br/>" +
                "</div>";

            obs.Text = new Narrative()
            {
                Status = Narrative.NarrativeStatus.Generated,
                Div    = DivNarrative
            };
            try
            {
                Parameters inParams = new Parameters();
                inParams.Add("resource", obs);

                //Validate the resource

                OperationOutcome val = client.ValidateResource(obs);
                if (val.Errors != 0)
                {
                    return(false);
                }

                //Success : Now save the observation
                Observation ObservationCreated = client.Create <Observation>(obs);
            }
            catch (FhirOperationException)
            {
                return(false);
            }


            return(true);
        }
        public static CodeableConcept ToCodeableConcept(this Coding coding)
        {
            CodeableConcept retVal = new CodeableConcept(coding.System, coding.Code, coding.Display, coding.Display);

            return(retVal);
        }
        public override void Build()
        {
            if (this.memberNode.Slices.Count <= 1)
            {
                return;
            }

            // Block is marked with !, so the top level lines are not merged, so we
            // dont have duplicate Read/Write Components methods.
            // component block may have been defined in a class merged into this one,
            // so check to see if it exists.
            String          readBlockName      = $"ReadComponents";
            String          writeBlockName     = $"WriteComponents";
            String          componentBlockName = $"!Components";
            CodeBlockNested componentBlock     = this.codeBlocks.ClassMethods?.Find(componentBlockName, false);

            if (componentBlock == null)
            {
                this.codeBlocks.ClassMethods
                .BlankLine()
                .StartBlock(componentBlockName)

                .BlankLine()
                .SummaryOpen()
                .Summary($"Read all component values from resource into this instance")
                .SummaryClose()
                .AppendCode($"private void ReadComponents(BreastRadiologyDocument doc)")
                .OpenBrace()
                .AppendCode($"List<{this.FhirClassName}> items = this.Resource.GetValue<{this.FhirClassName}>(\"{this.fhirName}\").ToList();")
                .DefineBlock(out this.readBlock, readBlockName)
                .CloseBrace()

                .BlankLine()
                .SummaryOpen()
                .Summary($"Write all values from this instance into resource")
                .SummaryClose()
                .AppendCode($"private void WriteComponents(BreastRadiologyDocument doc)")
                .OpenBrace()
                .AppendCode($"List<{this.FhirClassName}> items = new List<{this.FhirClassName}>();")
                .DefineBlock(out this.writeBlock, writeBlockName)
                .AppendCode($"this.Resource.SetValue(\"{this.fhirName}\", items);")
                .CloseBrace()
                .EndBlock()
                ;
            }
            else
            {
                this.readBlock  = componentBlock.Find(readBlockName);
                this.writeBlock = componentBlock.Find(writeBlockName);
            }

            if (this.codeBlocks.ClassWriteCode.Find("!WriteComponents") == null)
            {
                this.codeBlocks.ClassWriteCode
                .StartBlock("!WriteComponents")
                .AppendCode($"this.WriteComponents(this.Doc);")
                .EndBlock()
                ;
            }

            if (this.codeBlocks.ClassReadCode.Find("!ReadComponents") == null)
            {
                this.codeBlocks.ClassReadCode
                .StartBlock("!ReadComponents")
                .AppendCode($"this.ReadComponents(this.Doc);")
                .EndBlock()
                ;
            }

            foreach (ElementTreeSlice memberSlice in this.memberNode.Slices.Skip(1))
            {
                this.sliceName = memberSlice.ElementDefinition.SliceName;

                ElementTreeNode valueNode = memberSlice.Nodes.GetItem("value[x]");
                ElementTreeNode codeNode  = memberSlice.Nodes.GetItem("code");

                this.componentCode = (CodeableConcept)codeNode.ElementDefinition.Fixed;
                if (this.componentCode == null)
                {
                    this.componentCode = (CodeableConcept)codeNode.ElementDefinition.Pattern;
                }
                if (this.componentCode == null)
                {
                    throw new Exception("Missing {this.fhirName}.code fixed value");
                }

                ElementDefinition sliceDef = memberSlice.ElementDefinition;
                Int32             max      = CSMisc.ToMax(sliceDef.Max);
                Int32             min      = sliceDef.Min.Value;
                this.sliceName = this.sliceName.ToMachineName();

                this.itemElementSetName.Clear();
                foreach (var type in valueNode.ElementDefinition.Type)
                {
                    this.itemElementSetName.Add(type.Code);
                }

                this.containerClassName = $"M{this.sliceName.ToMachineName()}";
                this.itemElementGetName = (this.itemElementSetName.Count == 1) ? valueNode.ElementDefinition.Type[0].Code : "Element";
                base.BuildOne(memberSlice.ElementDefinition.ElementId, min, max);
            }
        }
        public void CodeableConceptMapTest()
        {
            var input = new CodeableConcept();

            input.Text   = "bla text";
            input.Coding = new List <Coding>();

            var coding1 = new Coding();

            coding1.CodeElement    = new Code("bla");
            coding1.SystemElement  = new FhirUri("http://bla.com");
            coding1.DisplayElement = new FhirString("bla display");

            var coding2 = new Coding();

            coding2.CodeElement    = new Code("flit");
            coding2.SystemElement  = new FhirUri("http://flit.com");
            coding2.DisplayElement = new FhirString("flit display");

            input.Coding.Add(coding1);
            input.Coding.Add(coding2);

            var result = sut.Map(input);

            Assert.AreEqual(2, result.Count()); //1 with text and 1 with the codings below it

            //Check wether CodeableConcept.Text is in the result.
            var textIVs = result.Where(c => c.GetType() == typeof(IndexValue) && (c as IndexValue).Name == "text").ToList();

            Assert.AreEqual(1, textIVs.Count());
            var textIV = (IndexValue)textIVs.FirstOrDefault();

            Assert.IsNotNull(textIV);
            Assert.AreEqual(1, textIV.Values.Count());
            Assert.IsInstanceOfType(textIV.Values[0], typeof(StringValue));
            Assert.AreEqual("bla text", (textIV.Values[0] as StringValue).Value);

            //Check wether both codings are in the result.
            var codingIVs = result.Where(c => c.GetType() == typeof(IndexValue) && (c as IndexValue).Name == "coding").ToList();

            Assert.AreEqual(1, codingIVs.Count());
            var codingIV = (IndexValue)codingIVs.First();

            var codeIVs = codingIV.Values.Where(c => c.GetType() == typeof(CompositeValue)).ToList();

            Assert.AreEqual(2, codeIVs.Count());

            var codeIV1 = (CompositeValue)codeIVs[0];
            var codeIV2 = (CompositeValue)codeIVs[1];

            if (((codeIV1.Components[0] as IndexValue).Values[0] as StringValue).Value == "bla")
            {
                CheckCoding(codeIV1, "bla", "http://bla.com", "bla display");
                CheckCoding(codeIV2, "flit", "http://flit.com", "flit display");
            }
            else //apparently the codings are in different order in the result.
            {
                CheckCoding(codeIV2, "bla", "http://bla.com", "bla display");
                CheckCoding(codeIV1, "flit", "http://flit.com", "flit display");
            }
        }
예제 #15
0
        public Appointment BuildAppointment(Boolean addOrgType, Boolean addDeliveryChannel, Boolean addPracRole)
        {
            var storedPatient = _fhirResourceRepository.Patient;
            var storedBundle  = _fhirResourceRepository.Bundle;

            var firstSlot = storedBundle.Entry
                            .Where(entry => entry.Resource.ResourceType.Equals(ResourceType.Slot))
                            .Select(entry => (Slot)entry.Resource)
                            .First();

            var schedule = storedBundle.Entry
                           .Where(entry =>
                                  entry.Resource.ResourceType.Equals(ResourceType.Schedule) &&
                                  ComposeReferenceFromEntry(entry) == firstSlot.Schedule.Reference)
                           .Select(entry => (Schedule)entry.Resource)
                           .First();



            //Patient
            var patient = GetPatient(storedPatient);

            //Practitioners
            var practitionerReferences = schedule.Extension.Where(extension => extension is ResourceReference).Select(extension => ((ResourceReference)extension.Value).Reference);
            var practitioners          = GetPractitioners(practitionerReferences);

            //Location
            var locationReference = schedule.Actor.First(actor => actor.Reference.Contains("Location")).Reference;
            var location          = GetLocation(locationReference);

            //Participants
            var participants = new List <ParticipantComponent>
            {
                patient
            };

            participants.AddRange(practitioners);
            participants.Add(location);

            //Slots
            var slot = GetSlot(firstSlot);

            var slots = new List <ResourceReference>
            {
                slot
            };

            //Extensions
            var bookingOrganizationExtension = GetBookingOrganizationExtension();

            //Contained Resources
            var bookingOrganization = GetBookingOrganization(addOrgType);

            //Initialize Appointment
            var appointment = new Appointment
            {
                Status         = AppointmentStatus.Booked,
                Start          = firstSlot.Start,
                End            = firstSlot.End,
                Participant    = participants,
                Slot           = slots,
                Description    = "Default Description",
                CreatedElement = new FhirDateTime(DateTime.UtcNow)
            };

            //Add Extensions & Contained Resources
            appointment.Extension.Add(bookingOrganizationExtension);
            appointment.Contained.Add(bookingOrganization);


            //Practitioner Role
            if (addPracRole)
            {
                CodeableConcept roleCode = new CodeableConcept("https://fhir.nhs.uk/STU3/CodeSystem/CareConnect-SDSJobRoleName-1", "R0260", "General Medical Practitioner");
                Extension       pracRole = new Extension("https://fhir.nhs.uk/STU3/StructureDefinition/Extension-GPConnect-PractitionerRole-1", roleCode);
                appointment.Extension.Add(pracRole);
            }

            //Deliver Channel
            if (addDeliveryChannel)
            {
                Code      channelCode = new Code("In-person");
                Extension delChannel  = new Extension("https://fhir.nhs.uk/STU3/StructureDefinition/Extension-GPConnect-DeliveryChannel-2", channelCode);
                appointment.Extension.Add(delChannel);
            }

            CodeableConcept type = new CodeableConcept("http://hl7.org/fhir/ValueSet/c80-practice-codes", "394802001", "General medicine", null);

            appointment.AppointmentType = type;

            return(appointment);
        }
예제 #16
0
        protected override async Task OnInitializedAsync()
        {
            Tag = Guid.NewGuid().ToString();

            // Construct an observation pointing to a patient and a diagnostic report pointing to the observation and the patient along with some not matching entries
            var snomedCode = new CodeableConcept("http://snomed.info/sct", "429858000");
            var loincCode  = new CodeableConcept("http://loinc.org", "4548-4");

            var meta = new Meta
            {
                Tag = new List <Coding>
                {
                    new Coding("testTag", Tag),
                },
            };

            PercocetMedication = (await TestFhirClient.CreateAsync(new Medication {
                Meta = meta, Code = new CodeableConcept("http://snomed.info/sct", "16590-619-30", "Percocet tablet")
            })).Resource;
            TramadolMedication = (await TestFhirClient.CreateAsync(new Medication {
                Meta = meta, Code = new CodeableConcept("http://snomed.info/sct", "108505002", "Tramadol hydrochloride (substance)")
            })).Resource;
            Organization       = (await TestFhirClient.CreateAsync(new Organization {
                Meta = meta, Address = new List <Address> {
                    new Address {
                        City = "Seattle"
                    }
                }
            })).Resource;

            DeletedOrganization = (await TestFhirClient.CreateAsync(new Organization {
                Meta = meta, Address = new List <Address> {
                    new Address {
                        City = "SeattleForgotten"
                    }
                }
            })).Resource;

            Organization.Name = "Updated";

            Organization = (await TestFhirClient.UpdateAsync(Organization)).Resource;

            Practitioner = (await TestFhirClient.CreateAsync(new Practitioner {
                Meta = meta
            })).Resource;
            PatiPatient  = await CreatePatient("Pati", Practitioner, Organization, "1990-01-01");

            PatientWithDeletedOrganization = await CreatePatient("NonExisting", Practitioner, DeletedOrganization, "1990-01-01");

            DeletedDevice = (await TestFhirClient.CreateAsync(new Device
            {
                Meta = meta,
                Patient = new ResourceReference($"Patient/{PatientWithDeletedOrganization.Id}"),
            })).Resource;

            await TestFhirClient.DeleteAsync(DeletedOrganization);

            await TestFhirClient.DeleteAsync(DeletedDevice);

            // Organization Hierarchy
            LabFOrganization = TestFhirClient.CreateAsync(new Organization {
                Meta = meta
            }).Result.Resource;
            LabEOrganization = (await TestFhirClient.CreateAsync(new Organization {
                Meta = meta, PartOf = new ResourceReference($"Organization/{LabFOrganization.Id}")
            })).Resource;
            LabDOrganization = (await TestFhirClient.CreateAsync(new Organization {
                Meta = meta, PartOf = new ResourceReference($"Organization/{LabEOrganization.Id}")
            })).Resource;
            LabCOrganization = (await TestFhirClient.CreateAsync(new Organization {
                Meta = meta, PartOf = new ResourceReference($"Organization/{LabDOrganization.Id}")
            })).Resource;
            LabBOrganization = (await TestFhirClient.CreateAsync(new Organization {
                Meta = meta, PartOf = new ResourceReference($"Organization/{LabCOrganization.Id}")
            })).Resource;
            LabAOrganization = (await TestFhirClient.CreateAsync(new Organization {
                Meta = meta, PartOf = new ResourceReference($"Organization/{LabBOrganization.Id}")
            })).Resource;

            AndersonPractitioner = (await TestFhirClient.CreateAsync(new Practitioner {
                Meta = meta, Name = new List <HumanName> {
                    new HumanName {
                        Family = "Anderson"
                    }
                }
            })).Resource;
            SanchezPractitioner  = (await TestFhirClient.CreateAsync(new Practitioner {
                Meta = meta, Name = new List <HumanName> {
                    new HumanName {
                        Family = "Sanchez"
                    }
                }
            })).Resource;
            TaylorPractitioner   = (await TestFhirClient.CreateAsync(new Practitioner {
                Meta = meta, Name = new List <HumanName> {
                    new HumanName {
                        Family = "Taylor"
                    }
                }
            })).Resource;

            AdamsPatient = await CreatePatient("Adams", AndersonPractitioner, Organization, "1974-12-25");

            SmithPatient = await CreatePatient("Smith", SanchezPractitioner, Organization, "1981-07-02");

            TrumanPatient = await CreatePatient("Truman", TaylorPractitioner, Organization, "1941-01-15");

            AdamsLoincObservation = await CreateObservation(AdamsPatient, Practitioner, Organization, loincCode, "1990-06-12");

            SmithLoincObservation = await CreateObservation(SmithPatient, Practitioner, Organization, loincCode, "2008-04-10");

            SmithSnomedObservation = await CreateObservation(SmithPatient, Practitioner, Organization, snomedCode, "1977-09-01");

            TrumanLoincObservation = await CreateObservation(TrumanPatient, Practitioner, Organization, loincCode, "2018-11-09");

            TrumanSnomedObservation = await CreateObservation(TrumanPatient, Practitioner, Organization, snomedCode, "1980-03-17");

            ObservationWithUntypedReferences = await CreateObservation(AdamsPatient, Practitioner, Organization, loincCode, "1990-06-12", untypedReferences : true);

            SmithSnomedDiagnosticReport = await CreateDiagnosticReport(SmithPatient, SmithSnomedObservation, snomedCode);

            TrumanSnomedDiagnosticReport = await CreateDiagnosticReport(TrumanPatient, TrumanSnomedObservation, snomedCode);

            SmithLoincDiagnosticReport = await CreateDiagnosticReport(SmithPatient, SmithLoincObservation, loincCode);

            TrumanLoincDiagnosticReport = await CreateDiagnosticReport(TrumanPatient, TrumanLoincObservation, loincCode);

            AdamsMedicationRequest = await CreateMedicationRequest(AdamsPatient, AndersonPractitioner, PercocetMedication);

            SmithMedicationRequest = await CreateMedicationRequest(SmithPatient, SanchezPractitioner, PercocetMedication);

            AdamsMedicationDispense = await CreateMedicationDispense(AdamsMedicationRequest, AdamsPatient, TramadolMedication);

            SmithMedicationDispense = await CreateMedicationDispense(SmithMedicationRequest, SmithPatient, TramadolMedication);

            TrumanMedicationDispenseWithoutRequest = await CreateMedicationDispense(null, TrumanPatient, TramadolMedication);

            CareTeam = await CreateCareTeam();

            Location = (await TestFhirClient.CreateAsync(new Location
            {
                ManagingOrganization = new ResourceReference($"Organization/{Organization.Id}"),
                Meta = meta,
            })).Resource;

            LocationPartOfSelf = (await TestFhirClient.CreateAsync(new Location())).Resource;

            LocationPartOfSelf.PartOf = new ResourceReference($"{LocationPartOfSelf.TypeName}/{LocationPartOfSelf.Id}");
            LocationPartOfSelf        = (await TestFhirClient.UpdateAsync(LocationPartOfSelf)).Resource;

            var group = new Group
            {
                Meta   = meta,
                Type   = Group.GroupType.Person, Actual = true,
                Member = new List <Group.MemberComponent>
                {
                    new Group.MemberComponent {
                        Entity = new ResourceReference($"Patient/{AdamsPatient.Id}")
                    },
                    new Group.MemberComponent {
                        Entity = new ResourceReference($"Patient/{SmithPatient.Id}")
                    },
                    new Group.MemberComponent {
                        Entity = new ResourceReference($"Patient/{TrumanPatient.Id}")
                    },
                },
            };

            PatientGroup = (await TestFhirClient.CreateAsync(@group)).Resource;

            async Task <DiagnosticReport> CreateDiagnosticReport(Patient patient, Observation observation, CodeableConcept code)
            {
                return((await TestFhirClient.CreateAsync(
                            new DiagnosticReport
                {
                    Meta = meta,
                    Status = DiagnosticReport.DiagnosticReportStatus.Final,
                    Code = code,
                    Subject = new ResourceReference($"Patient/{patient.Id}"),
                    Result = new List <ResourceReference> {
                        new ResourceReference($"Observation/{observation.Id}")
                    },
                })).Resource);
            }

            async Task <Observation> CreateObservation(Patient patient, Practitioner practitioner, Organization organization, CodeableConcept code, string effectiveDate, bool untypedReferences = false)
            {
                return((await TestFhirClient.CreateAsync(
                            new Observation()
                {
                    Meta = meta,
                    Status = ObservationStatus.Final,
                    Code = code,
                    Subject = new ResourceReference(untypedReferences ? patient.Id : $"Patient/{patient.Id}"),
                    Performer = new List <ResourceReference>()
                    {
                        new ResourceReference(untypedReferences ? organization.Id : $"Organization/{organization.Id}"),
                        new ResourceReference(untypedReferences ? practitioner.Id : $"Practitioner/{practitioner.Id}"),
                    },
                    Effective = new FhirDateTime(effectiveDate),
                })).Resource);
            }

            async Task <Patient> CreatePatient(string familyName, Practitioner practitioner, Organization organization, string birthDate)
            {
                return((await TestFhirClient.CreateAsync(
                            new Patient
                {
                    Meta = meta,
                    BirthDate = birthDate,
                    Name = new List <HumanName> {
                        new HumanName {
                            Family = familyName
                        }
                    },
                    GeneralPractitioner = new List <ResourceReference>()
                    {
                        new ResourceReference($"Practitioner/{practitioner.Id}"),
                    },
                    ManagingOrganization = new ResourceReference($"Organization/{organization.Id}"),
                })).Resource);
            }

            async Task <MedicationDispense> CreateMedicationDispense(MedicationRequest medicationRequest, Patient patient, Medication medication)
            {
                return((await TestFhirClient.CreateAsync(
                            new MedicationDispense
                {
                    Meta = meta,
                    AuthorizingPrescription = medicationRequest == null
                            ? null
                            : new List <ResourceReference>
                    {
                        new ResourceReference($"MedicationRequest/{medicationRequest.Id}"),
                    },
                    Subject = new ResourceReference($"Patient/{patient.Id}"),
                    Performer = new List <MedicationDispense.PerformerComponent>()
                    {
                        new MedicationDispense.PerformerComponent()
                        {
                            Actor = new ResourceReference($"Practitioner/{Practitioner.Id}"),
                        },
                    },
#if R5
                    Medication = new CodeableReference
                    {
                        Concept = medication.Code,
                        Reference = new ResourceReference($"Medication/{medication.Id}"),
                    },
#else
                    Medication = medication.Code,
#endif
#if Stu3
                    Status = MedicationDispense.MedicationDispenseStatus.InProgress,
#else
                    Status = MedicationDispense.MedicationDispenseStatusCodes.InProgress,
#endif
                })).Resource);
            }

            async Task <MedicationRequest> CreateMedicationRequest(Patient patient, Practitioner practitioner, Medication medication)
            {
                return((await TestFhirClient.CreateAsync(
                            new MedicationRequest
                {
                    Meta = meta,
                    Subject = new ResourceReference($"Patient/{patient.Id}"),
#if Stu3
                    Intent = MedicationRequest.MedicationRequestIntent.Order,
                    Status = MedicationRequest.MedicationRequestStatus.Completed,
                    Requester = new MedicationRequest.RequesterComponent
                    {
                        Agent = new ResourceReference($"Practitioner/{practitioner.Id}"),
                    },
#else
                    IntentElement = new Code <MedicationRequest.medicationRequestIntent> {
                        Value = MedicationRequest.medicationRequestIntent.Order
                    },
                    StatusElement = new Code <MedicationRequest.medicationrequestStatus> {
                        Value = MedicationRequest.medicationrequestStatus.Completed
                    },
                    Requester = new ResourceReference($"Practitioner/{practitioner.Id}"),
#endif
#if R5
                    Medication = new CodeableReference
                    {
                        Concept = medication.Code,
                        Reference = new ResourceReference($"Medication/{medication.Id}"),
                    },
#else
                    Medication = medication.Code,
#endif
                })).Resource);
            }

            async Task <CareTeam> CreateCareTeam()
            {
                return((await TestFhirClient.CreateAsync(
                            new CareTeam
                {
                    Meta = meta,
                    Participant = new List <CareTeam.ParticipantComponent>()
                    {
                        new CareTeam.ParticipantComponent {
                            Member = new ResourceReference($"Patient/{AdamsPatient.Id}")
                        },
                        new CareTeam.ParticipantComponent {
                            Member = new ResourceReference($"Patient/{SmithPatient.Id}")
                        },
                        new CareTeam.ParticipantComponent {
                            Member = new ResourceReference($"Patient/{TrumanPatient.Id}")
                        },
                        new CareTeam.ParticipantComponent {
                            Member = new ResourceReference($"Organization/{Organization.Id}")
                        },
                        new CareTeam.ParticipantComponent {
                            Member = new ResourceReference($"Practitioner/{Practitioner.Id}")
                        },
                    },
                })).Resource);
            }
        }
예제 #17
0
        public static Parameters ValidateCode(this FhirClient client, String valueSetId, CodeableConcept codeableConcept)
        {
            if (codeableConcept == null)
            {
                throw new ArgumentNullException("codeableConcept");
            }

            var par = new Parameters().Add("codeableConcept", codeableConcept);

            return(validateCodeForValueSetId(client, valueSetId, par));
        }
 public static List <Bundle.EntryComponent> GetEntryListFromFhirDiagnosticReportForSubject(ResourceReference subject, CodeableConcept procedureCode) =>
 GetBundleDiagnosticReportForOptionalCriteria(new string[] { $"subject={subject.Reference}", $"code={procedureCode.Text}" }).Entry;
예제 #19
0
        protected override async Task OnInitializedAsync()
        {
            Tag = Guid.NewGuid().ToString();

            await TestFhirClient.CreateResourcesAsync <Patient>(p =>
            {
                p.Meta = new Meta
                {
                    Tag = new List <Coding>
                    {
                        new Coding("testTag", Tag),
                    },
                };
            });

            Observations = await TestFhirClient.CreateResourcesAsync <Observation>(
                o => SetObservation(o, cc => cc.Coding.Add(new Coding("system1", "code1"))),
                o => SetObservation(o, cc => cc.Coding.Add(new Coding("system2", "code2"))),
                o => SetObservation(o, cc => cc.Text = "text"),
                o => SetObservation(o, cc => cc.Coding.Add(new Coding("system1", "code2", "text2"))),
                o => SetObservation(o, cc => cc.Coding.Add(new Coding("system3", "code3", "text"))),
                o => SetObservation(o, cc =>
            {
                cc.Text = "text";
                cc.Coding.Add(new Coding("system1", "code1"));
                cc.Coding.Add(new Coding("system3", "code2"));
            }),
                o => SetObservation(o, cc =>
            {
                cc.Coding.Add(new Coding("system2", "code1"));
                cc.Coding.Add(new Coding("system3", "code3", "text2"));
            }),
                o => SetObservation(o, cc => cc.Coding.Add(new Coding(null, "code3"))),
                o =>
            {
                SetObservation(o, cc => { });
                o.Category = new List <CodeableConcept>
                {
                    new CodeableConcept("system", "test"),
                };
            });

            void SetObservation(Observation observation, Action <CodeableConcept> codeableConceptCustomizer)
            {
                observation.Meta = new Meta
                {
                    Tag = new List <Coding>
                    {
                        new Coding("testTag", Tag),
                    },
                };
                observation.Code   = new CodeableConcept("system", "code");
                observation.Status = ObservationStatus.Registered;

                var codeableConcept = new CodeableConcept();

                codeableConceptCustomizer(codeableConcept);

                observation.Value = codeableConcept;
            }
        }
예제 #20
0
            }                                                                                                                                      // BuildMemberBase.cs:117

            // BuildMemberBase.cs:119
            // BuildMemberBase.cs:120
            /// <summary>
            /// Read item.
            /// </summary>
            public void ReadItem(BreastRadiologyDocument doc, CodeableConcept item)                                                                // BuildMemberBase.cs:123
            {                                                                                                                                      // BuildMemberBase.cs:124
                this.Value = item;                                                                                                                 // BuildMemberElement.cs:40
                List <Extension> extensionList = item.Extension;                                                                                   // BuildMemberElement.cs:41
            }                                                                                                                                      // BuildMemberBase.cs:127
        public void CreateElementDefinition(
            StructureDefinition strucDef,
            TemplateConstraint constraint,
            SimpleSchema.SchemaObject schemaObject,
            string sliceName = null)
        {
            if (constraint.IsPrimitive)     // Skip primitives (for now, at least)
            {
                return;
            }

            string newSliceName = null;

            if (constraint.IsBranch)
            {
                newSliceName = string.Format("{0}_slice_pos{1}", constraint.Context, constraint.Order);
            }

            var igSettings          = GetIGSettings(constraint);
            var constraintFormatter = FormattedConstraintFactory.NewFormattedConstraint(this.tdb, igSettings, this.igTypePlugin, constraint);

            ElementDefinition newElementDef = new ElementDefinition()
            {
                Short      = !string.IsNullOrEmpty(constraint.Label) ? constraint.Label : constraint.Context,
                Label      = !string.IsNullOrEmpty(constraint.Label) ? constraint.Label : null,
                Comments   = !string.IsNullOrEmpty(constraint.Notes) ? constraint.Notes : null,
                Path       = constraint.GetElementPath(strucDef.ConstrainedType),
                Name       = constraint.IsBranch ? newSliceName : sliceName,
                Definition = constraintFormatter.GetPlainText(false, false, false)
            };

            // Cardinality
            if (!string.IsNullOrEmpty(constraint.Cardinality))
            {
                newElementDef.Min = constraint.CardinalityType.Left;
                newElementDef.Max = constraint.CardinalityType.Right == Cardinality.MANY ? "*" : constraint.CardinalityType.Right.ToString();
            }

            // Binding
            string valueConformance = string.IsNullOrEmpty(constraint.ValueConformance) ? constraint.Conformance : constraint.ValueConformance;
            bool   hasBinding       = constraint.References.Any(y => y.ReferenceType == ConstraintReferenceTypes.Template);

            if (constraint.ValueSet != null && valueConformance.IndexOf("NOT") < 0)
            {
                hasBinding            = true;
                newElementDef.Binding = new ElementDefinition.ElementDefinitionBindingComponent()
                {
                    ValueSet = new ResourceReference()
                    {
                        Reference = string.Format("ValueSet/{0}", constraint.ValueSet.Id),
                        Display   = constraint.ValueSet.Name
                    }
                };

                if (valueConformance == "SHALL")
                {
                    newElementDef.Binding.Strength = BindingStrength.Required;
                }
                else if (valueConformance == "SHOULD")
                {
                    newElementDef.Binding.Strength = BindingStrength.Preferred;
                }
                else if (valueConformance == "MAY")
                {
                    newElementDef.Binding.Strength = BindingStrength.Example;
                }
            }

            // Single-Value Binding
            if (schemaObject != null && (!string.IsNullOrEmpty(constraint.Value) || !string.IsNullOrEmpty(constraint.DisplayName)))
            {
                hasBinding = true;
                switch (schemaObject.DataType)
                {
                case "CodeableConcept":
                    var fixedCodeableConcept = new CodeableConcept();
                    var coding = new Coding();
                    fixedCodeableConcept.Coding.Add(coding);

                    if (!string.IsNullOrEmpty(constraint.Value))
                    {
                        coding.Code = constraint.Value;
                    }

                    if (constraint.CodeSystem != null)
                    {
                        coding.System = constraint.CodeSystem.Oid;
                    }

                    if (!string.IsNullOrEmpty(constraint.DisplayName))
                    {
                        coding.Display = constraint.DisplayName;
                    }

                    newElementDef.Fixed = fixedCodeableConcept;
                    break;

                case "Coding":
                    var fixedCoding = new Coding();

                    if (!string.IsNullOrEmpty(constraint.Value))
                    {
                        fixedCoding.Code = constraint.Value;
                    }

                    if (constraint.CodeSystem != null)
                    {
                        fixedCoding.System = constraint.CodeSystem.Oid;
                    }

                    if (!string.IsNullOrEmpty(constraint.DisplayName))
                    {
                        fixedCoding.Display = constraint.DisplayName;
                    }

                    newElementDef.Fixed = fixedCoding;
                    break;

                case "code":
                    var fixedCode = new Code();
                    fixedCode.Value     = !string.IsNullOrEmpty(constraint.Value) ? constraint.Value : constraint.DisplayName;
                    newElementDef.Fixed = fixedCode;
                    break;

                default:
                    var fixedString = new FhirString();
                    fixedString.Value   = !string.IsNullOrEmpty(constraint.Value) ? constraint.Value : constraint.DisplayName;
                    newElementDef.Fixed = fixedString;
                    break;
                }
            }

            // Add the type of the element when bound to a value set
            if (hasBinding && schemaObject != null && !string.IsNullOrEmpty(schemaObject.DataType))
            {
                StructureDefinition profile = GetBaseProfile(constraint.Template);
                newElementDef.Type = GetProfileDataTypes(profile, constraint);

                var containedTemplates = (from tcr in constraint.References
                                          join t in this.tdb.Templates on tcr.ReferenceIdentifier equals t.Oid
                                          where tcr.ReferenceType == ConstraintReferenceTypes.Template
                                          select new { Identifier = t.Oid, t.PrimaryContextType });

                // If there is a contained template/profile, make sure it supports a "Reference" type, and then output the profile identifier in the type
                if (containedTemplates.Count() > 0 && newElementDef.Type.Exists(y => y.Code == "Reference" || y.Code == "Extension"))
                {
                    var containedTypes = new List <ElementDefinition.TypeRefComponent>();
                    foreach (var containedTemplate in containedTemplates)
                    {
                        bool isExtension = containedTemplate.PrimaryContextType == "Extension" && newElementDef.Type.Exists(y => y.Code == "Extension");

                        containedTypes.Add(new ElementDefinition.TypeRefComponent()
                        {
                            Code    = isExtension ? "Extension" : "Reference",
                            Profile = new List <string>(new string[] { containedTemplate.Identifier })
                        });
                    }

                    newElementDef.Type = containedTypes;
                }
            }

            // Add the element to the list
            strucDef.Differential.Element.Add(newElementDef);

            // Children
            foreach (var childConstraint in constraint.ChildConstraints.OrderBy(y => y.Order))
            {
                var childSchemaObject = schemaObject != null?schemaObject.Children.SingleOrDefault(y => y.Name == childConstraint.Context) : null;

                CreateElementDefinition(strucDef, childConstraint, childSchemaObject, newSliceName);
            }
        }
예제 #22
0
 /// <summary>
 /// Get primary code
 /// </summary>
 public static Coding GetCoding(this CodeableConcept me) => me.Coding.FirstOrDefault();
예제 #23
0
        public static Resource GetStatement(bool inBundle)
        {
            TerminologyCapabilities tsCapabilityStatement = new TerminologyCapabilities
            {
                Url          = ServerCapability.TERMINZ_CANONICAL + "/TerminologyCapabilities/Terminz-Example",
                Id           = "Terminz-Example",
                Description  = new Markdown("HL7© FHIR© terminology services for use in New Zealand."),
                Name         = "Patients First Terminology Server (Terminz)",
                Purpose      = new Markdown("Exemplar of terminology services approach for New Zealand."),
                Publisher    = "Patients First Ltd",
                Version      = "4.0.0",
                Status       = PublicationStatus.Draft,
                Date         = "2019-05-08",
                Experimental = true,
                Copyright    = new Markdown("© 2019+ Patients First Ltd"),
                LockedDate   = false
            };

            ContactDetail cd = new ContactDetail {
                Name = "Peter Jordan"
            };
            ContactPoint cp = new ContactPoint {
                System = ContactPoint.ContactPointSystem.Email, Value = "*****@*****.**"
            };

            cd.Telecom.Add(cp);
            tsCapabilityStatement.Contact.Add(cd);

            CodeableConcept cc = new CodeableConcept("http://hl7.org/fhir/ValueSet/jurisdiction", "NZL", "New Zealand", "New Zealand");

            tsCapabilityStatement.Jurisdiction.Add(cc);

            tsCapabilityStatement.CodeSystem.Add(FhirSnomed.GetCapabilities());
            tsCapabilityStatement.CodeSystem.Add(FhirLoinc.GetCapabilities());
            tsCapabilityStatement.CodeSystem.Add(NzMt.GetCapabilities());
            tsCapabilityStatement.CodeSystem.Add(FhirRxNorm.GetCapabilities());

            tsCapabilityStatement.Expansion = new TerminologyCapabilities.ExpansionComponent
            {
                Hierarchical = false,
                Paging       = true,
                Incomplete   = false,
                TextFilter   = new Markdown("Results include synonyms, not just preferred terms.")
            };

            tsCapabilityStatement.CodeSearch = TerminologyCapabilities.CodeSearchSupport.All;

            tsCapabilityStatement.ValidateCode = new TerminologyCapabilities.ValidateCodeComponent()
            {
                Translations = false
            };

            tsCapabilityStatement.Translation = new TerminologyCapabilities.TranslationComponent()
            {
                NeedsMap = true
            };

            tsCapabilityStatement.Closure = new TerminologyCapabilities.ClosureComponent()
            {
                Translation = false
            };

            // text element

            XNamespace ns = "http://www.w3.org/1999/xhtml";

            var summary = new XElement(ns + "div",
                                       new XElement(ns + "h2", tsCapabilityStatement.Name),
                                       new XElement(ns + "p", tsCapabilityStatement.Description),
                                       new XElement(ns + "table",
                                                    new XElement(ns + "tr",
                                                                 new XElement(ns + "td", "Purpose"),
                                                                 new XElement(ns + "td", tsCapabilityStatement.Purpose.ToString())
                                                                 ),
                                                    new XElement(ns + "tr",
                                                                 new XElement(ns + "td", "Publisher"),
                                                                 new XElement(ns + "td", tsCapabilityStatement.Publisher)
                                                                 ),
                                                    new XElement(ns + "tr",
                                                                 new XElement(ns + "td", "Version"),
                                                                 new XElement(ns + "td", tsCapabilityStatement.Version)
                                                                 ),
                                                    new XElement(ns + "tr",
                                                                 new XElement(ns + "td", "Date"),
                                                                 new XElement(ns + "td", tsCapabilityStatement.Date)
                                                                 )
                                                    ),
                                       new XElement(ns + "table",
                                                    new XElement(ns + "tr",
                                                                 new XElement(ns + "th", "Code System"),
                                                                 new XElement(ns + "th", "Description"),
                                                                 new XElement(ns + "th", "URI"),
                                                                 new XElement(ns + "th", "Version")
                                                                 ),
                                                    new XElement(ns + "tr",
                                                                 new XElement(ns + "td", FhirSnomed.TITLE),
                                                                 new XElement(ns + "td", FhirSnomed.DESCRIPTION),
                                                                 new XElement(ns + "td", FhirSnomed.URI),
                                                                 new XElement(ns + "td", FhirSnomed.CURRENT_VERSION)
                                                                 ),
                                                    new XElement(ns + "tr",
                                                                 new XElement(ns + "td", FhirLoinc.TITLE),
                                                                 new XElement(ns + "td", FhirLoinc.DESCRIPTION),
                                                                 new XElement(ns + "td", FhirLoinc.URI),
                                                                 new XElement(ns + "td", FhirLoinc.CURRENT_VERSION)
                                                                 ),
                                                    new XElement(ns + "tr",
                                                                 new XElement(ns + "td", NzMt.TITLE),
                                                                 new XElement(ns + "td", NzMt.DESCRIPTION),
                                                                 new XElement(ns + "td", NzMt.URI),
                                                                 new XElement(ns + "td", NzMt.CURRENT_VERSION)
                                                                 ),
                                                    new XElement(ns + "tr",
                                                                 new XElement(ns + "td", FhirRxNorm.TITLE),
                                                                 new XElement(ns + "td", FhirRxNorm.DESCRIPTION),
                                                                 new XElement(ns + "td", FhirRxNorm.URI),
                                                                 new XElement(ns + "td", FhirRxNorm.CURRENT_VERSION)
                                                                 )
                                                    )
                                       );

            tsCapabilityStatement.Text = new Narrative
            {
                Status = Narrative.NarrativeStatus.Generated,
                Div    = summary.ToString()
            };

            // place in a bundle

            if (inBundle)
            {
                Bundle tcsBundle = new Bundle
                {
                    Id   = Guid.NewGuid().ToString(),
                    Type = Bundle.BundleType.Searchset
                };

                tcsBundle.Link.Add(new Bundle.LinkComponent {
                    Url = ServerCapability.TERMINZ_CANONICAL + "/TerminologyCapabilities", Relation = "self"
                });
                tcsBundle.AddResourceEntry(tsCapabilityStatement, tsCapabilityStatement.Url);
                tcsBundle.Total = tcsBundle.Entry.Count;

                return(tcsBundle);
            }

            return(tsCapabilityStatement);
        }
        public static async Task <ValidateCodeResult> ValidateCodeAsync(this IFhirClient client, String valueSetId,
                                                                        FhirUri identifier    = null, FhirUri context                 = null, ValueSet valueSet  = null, Code code = null,
                                                                        FhirUri system        = null, FhirString version              = null, FhirString display = null,
                                                                        Coding coding         = null, CodeableConcept codeableConcept = null, FhirDateTime date  = null,
                                                                        FhirBoolean @abstract = null)
        {
            if (valueSetId == null)
            {
                throw new ArgumentNullException(nameof(valueSetId));
            }

            var par = new Parameters()
                      .Add(nameof(identifier), identifier)
                      .Add(nameof(context), context)
                      .Add(nameof(valueSet), valueSet)
                      .Add(nameof(code), code)
                      .Add(nameof(system), system)
                      .Add(nameof(version), version)
                      .Add(nameof(display), display)
                      .Add(nameof(coding), coding)
                      .Add(nameof(codeableConcept), codeableConcept)
                      .Add(nameof(date), date)
                      .Add(nameof(@abstract), @abstract);

            ResourceIdentity location = new ResourceIdentity("ValueSet/" + valueSetId);
            var result = await client.InstanceOperationAsync(location.WithoutVersion().MakeRelative(), RestOperation.VALIDATE_CODE, par).ConfigureAwait(false);

            if (result != null)
            {
                return(ValidateCodeResult.FromParameters(result.OperationResult <Parameters>()));
            }
            else
            {
                return(null);
            }
        }
예제 #25
0
            public ClassFixture(DataStore dataStore, Format format, TestFhirServerFactory testFhirServerFactory)
                : base(dataStore, format, testFhirServerFactory)
            {
                Tag = Guid.NewGuid().ToString();

                // Construct an observation pointing to a patient and a diagnostic report pointing to the observation and the patient along with some not matching entries
                var snomedCode = new CodeableConcept("http://snomed.info/sct", "429858000");
                var loincCode  = new CodeableConcept("http://loinc.org", "4548-4");

                var meta = new Meta
                {
                    Tag = new List <Coding>
                    {
                        new Coding("testTag", Tag),
                    },
                };

                var organization = TestFhirClient.CreateAsync(new Organization {
                    Meta = meta, Address = new List <Address> {
                        new Address {
                            City = "Seattle"
                        }
                    }
                }).Result.Resource;

                AdamsPatient = TestFhirClient.CreateAsync(new Patient {
                    Meta = meta, Name = new List <HumanName> {
                        new HumanName {
                            Family = "Adams"
                        }
                    }
                }).Result.Resource;
                SmithPatient = TestFhirClient.CreateAsync(new Patient {
                    Meta = meta, Name = new List <HumanName> {
                        new HumanName {
                            Family = "Smith"
                        }
                    }, ManagingOrganization = new ResourceReference($"Organization/{organization.Id}")
                }).Result.Resource;
                TrumanPatient = TestFhirClient.CreateAsync(new Patient {
                    Meta = meta, Name = new List <HumanName> {
                        new HumanName {
                            Family = "Truman"
                        }
                    }
                }).Result.Resource;

                var adamsLoincObservation   = CreateObservation(AdamsPatient, loincCode);
                var smithLoincObservation   = CreateObservation(SmithPatient, loincCode);
                var smithSnomedObservation  = CreateObservation(SmithPatient, snomedCode);
                var trumanLoincObservation  = CreateObservation(TrumanPatient, loincCode);
                var trumanSnomedObservation = CreateObservation(TrumanPatient, snomedCode);

                SmithSnomedDiagnosticReport  = CreateDiagnosticReport(SmithPatient, smithSnomedObservation, snomedCode);
                TrumanSnomedDiagnosticReport = CreateDiagnosticReport(TrumanPatient, trumanSnomedObservation, snomedCode);
                SmithLoincDiagnosticReport   = CreateDiagnosticReport(SmithPatient, smithLoincObservation, loincCode);
                TrumanLoincDiagnosticReport  = CreateDiagnosticReport(TrumanPatient, trumanLoincObservation, loincCode);

                var group = new Group
                {
                    Meta = new Meta {
                        Tag = new List <Coding> {
                            new Coding("testTag", Tag)
                        }
                    },
                    Type   = Group.GroupType.Person,
                    Actual = true,
                    Member = new List <Group.MemberComponent>
                    {
                        new Group.MemberComponent {
                            Entity = new ResourceReference($"Patient/{AdamsPatient.Id}")
                        },
                        new Group.MemberComponent {
                            Entity = new ResourceReference($"Patient/{SmithPatient.Id}")
                        },
                        new Group.MemberComponent {
                            Entity = new ResourceReference($"Patient/{TrumanPatient.Id}")
                        },
                    },
                };

                PatientGroup = TestFhirClient.CreateAsync(group).Result.Resource;

                DiagnosticReport CreateDiagnosticReport(Patient patient, Observation observation, CodeableConcept code)
                {
                    return(TestFhirClient.CreateAsync(
                               new DiagnosticReport
                    {
                        Meta = meta,
                        Status = DiagnosticReport.DiagnosticReportStatus.Final,
                        Code = code,
                        Subject = new ResourceReference($"Patient/{patient.Id}"),
                        Result = new List <ResourceReference> {
                            new ResourceReference($"Observation/{observation.Id}")
                        },
                    }).Result.Resource);
                }

                Observation CreateObservation(Patient patient, CodeableConcept code)
                {
                    return(TestFhirClient.CreateAsync(
                               new Observation()
                    {
                        Meta = meta,
                        Status = ObservationStatus.Final,
                        Code = code,
                        Subject = new ResourceReference($"Patient/{patient.Id}"),
                    }).Result.Resource);
                }
            }
        public async static Task <ValidateCodeResult> ValidateCodeAsync(this IFhirClient client,
                                                                        FhirUri identifier    = null, FhirUri context                 = null, ValueSet valueSet  = null, Code code = null,
                                                                        FhirUri system        = null, FhirString version              = null, FhirString display = null,
                                                                        Coding coding         = null, CodeableConcept codeableConcept = null, FhirDateTime date  = null,
                                                                        FhirBoolean @abstract = null)
        {
            var par = new Parameters()
                      .Add(nameof(identifier), identifier)
                      .Add(nameof(context), context)
                      .Add(nameof(valueSet), valueSet)
                      .Add(nameof(code), code)
                      .Add(nameof(system), system)
                      .Add(nameof(version), version)
                      .Add(nameof(display), display)
                      .Add(nameof(coding), coding)
                      .Add(nameof(codeableConcept), codeableConcept)
                      .Add(nameof(date), date)
                      .Add(nameof(@abstract), @abstract);

            var result = await client.TypeOperationAsync <ValueSet>(RestOperation.VALIDATE_CODE, par).ConfigureAwait(false);

            if (result != null)
            {
                return(ValidateCodeResult.FromParameters(result.OperationResult <Parameters>()));
            }
            else
            {
                return(null);
            }
        }
        public static OperationOutcome Create(OperationOutcome.IssueSeverity issueSeverity, OperationOutcome.IssueType issueType, string diagnostics, CodeableConcept details, bool spineError)
        {
            var outcome = Base(spineError);

            outcome.Issue = new List <OperationOutcome.IssueComponent>
            {
                new OperationOutcome.IssueComponent
                {
                    Severity    = issueSeverity,
                    Code        = issueType,
                    Diagnostics = diagnostics,
                    Details     = details
                }
            };

            return(outcome);
        }
예제 #28
0
        /// <summary>
        /// Given a observation POCO, maps the data to an Observation Resource.
        /// </summary>
        /// <param name="observation"></param>
        /// <returns></returns>
        public static Observation MapModel(POCO.Observation observation)
        {
            if (observation == null)
            {
                throw new ArgumentNullException("observation");
            }

            var resource = new Observation();

            resource.Id = observation.ObservationId.ToString("D");

            // Observation Status
            switch (observation.Status)
            {
            case ObsStatus.amended:
                resource.Status = ObservationStatus.Amended;
                break;

            case ObsStatus.cancelled:
                resource.Status = ObservationStatus.Cancelled;
                break;

            case ObsStatus.entered_in_error:
                resource.Status = ObservationStatus.EnteredInError;
                break;

            case ObsStatus.final:
                resource.Status = ObservationStatus.Final;
                break;

            case ObsStatus.preliminary:
                resource.Status = ObservationStatus.Preliminary;
                break;

            case ObsStatus.registered:
                resource.Status = ObservationStatus.Registered;
                break;

            case ObsStatus.unknown:
                resource.Status = ObservationStatus.Unknown;
                break;

            default:
                resource.Status = ObservationStatus.EnteredInError;
                break;
            }

            // Observation Category
            if (observation.CategoryCode[0] != string.Empty || observation.CategoryDisplay[0] != string.Empty || observation.CategorySystem[0] != string.Empty || observation.CategoryText != null)
            {
                CodeableConcept observationCategory = new CodeableConcept();
                List <Coding>   observationCodings  = new List <Coding>();

                if (observation.CategoryCode[0] != string.Empty || observation.CategoryDisplay[0] != string.Empty || observation.CategorySystem[0] != string.Empty)
                {
                    for (int i = 0; i < observation.CategoryCode.Count; i++)
                    {
                        Coding observationCoding = new Coding()
                        {
                            System  = observation.CategorySystem[i],
                            Display = observation.CategoryDisplay[i],
                            Code    = observation.CategoryCode[i]
                        };
                        observationCodings.Add(observationCoding);
                    }
                    observationCategory.Coding = observationCodings;
                }
                observationCategory.Text = observation.CategoryText;

                resource.Category = observationCategory;
            }

            // Observation Code
            if (observation.CodeCode[0] != string.Empty || observation.CodeDisplay[0] != string.Empty || observation.CodeSystem[0] != string.Empty || observation.CodeText != null)
            {
                CodeableConcept observationCode    = new CodeableConcept();
                List <Coding>   observationCodings = new List <Coding>();

                if (observation.CodeCode[0] != string.Empty || observation.CodeDisplay[0] != string.Empty || observation.CodeSystem[0] != string.Empty)
                {
                    for (int i = 0; i < observation.CodeCode.Count; i++)
                    {
                        Coding observationCoding = new Coding()
                        {
                            System  = observation.CodeSystem[i],
                            Display = observation.CodeDisplay[i],
                            Code    = observation.CodeCode[i]
                        };
                        observationCodings.Add(observationCoding);
                    }
                    observationCode.Coding = observationCodings;
                }
                observationCode.Text = observation.CategoryText;

                resource.Code = observationCode;
            }

            // Observation references to other resources
            if (observation.PatientReference != null)
            {
                resource.Subject           = new ResourceReference();
                resource.Subject.Reference = observation.PatientReference;
            }
            if (observation.DeviceReference != null)
            {
                resource.Device           = new ResourceReference();
                resource.Device.Reference = observation.DeviceReference;
            }

            if (observation.PerformerReferences[0] != string.Empty)
            {
                foreach (var reference in observation.PerformerReferences)
                {
                    ResourceReference performerReference = new ResourceReference();
                    performerReference.Reference = reference;
                    resource.Performer.Add(performerReference);
                }
            }

            // Observation Effective times
            // The choice of Type is DateTime.
            if (observation.EffectiveDateTime != null)
            {
                FhirDateTime dateTime = new FhirDateTime(observation.EffectiveDateTime);
                resource.Effective = dateTime;
            }
            // The choice of Type is Period.
            else
            {
                Period period = new Period
                {
                    Start = observation.EffectivePeriodStart.ToString(),
                    End   = observation.EffectivePeriodEnd.ToString()
                };
                resource.Effective = period;
            }

            resource.Issued = observation.Issued;

            // Observation Comments
            resource.Comments = observation.Comments;

            // Site of Body where Observation was made
            if (observation.BodySiteCode != null || observation.BodySiteDisplay != null || observation.BodySiteSystem != null || observation.BodySiteText != null)
            {
                CodeableConcept observationBodySite = new CodeableConcept();
                List <Coding>   observationCodings  = new List <Coding>();

                if (observation.BodySiteCode != null || observation.BodySiteDisplay != null || observation.BodySiteSystem != null)
                {
                    Coding observationCoding = new Coding()
                    {
                        System  = observation.BodySiteSystem,
                        Display = observation.BodySiteDisplay,
                        Code    = observation.BodySiteCode
                    };
                    observationCodings.Add(observationCoding);
                    observationBodySite.Coding = observationCodings;
                }
                observationBodySite.Text = observation.BodySiteText;

                resource.BodySite = observationBodySite;
            }

            // Observation Interpretation
            if (observation.InterpretationCode != null || observation.InterpretationDisplay != null || observation.InterpretationSystem != null || observation.InterpretationText != null)
            {
                CodeableConcept observationInterpretation = new CodeableConcept();
                List <Coding>   observationCodings        = new List <Coding>();

                if (observation.InterpretationCode != null || observation.InterpretationDisplay != null || observation.InterpretationSystem != null)
                {
                    Coding observationCoding = new Coding()
                    {
                        System  = observation.InterpretationSystem,
                        Display = observation.InterpretationDisplay,
                        Code    = observation.InterpretationCode
                    };
                    observationCodings.Add(observationCoding);
                    observationInterpretation.Coding = observationCodings;
                }
                observationInterpretation.Text = observation.InterpretationText;

                resource.Interpretation = observationInterpretation;
            }

            // Observation Values
            // Values are componentised
            if (observation.ComponentCodeCode[0] != string.Empty || observation.ComponentCodeText != null)
            {
                for (int i = 0; i < observation.ComponentCodeCode.Count; i++)
                {
                    ComponentComponent component = new ComponentComponent();
                    CodeableConcept    concept   = new CodeableConcept();
                    Coding             coding    = new Coding();
                    coding.Code    = observation.ComponentCodeCode[i];
                    coding.Display = observation.ComponentCodeDisplay[i];
                    coding.System  = observation.ComponentCodeSystem[i];
                    concept.Coding.Add(coding);
                    concept.Text   = observation.ComponentCodeText;
                    component.Code = concept;

                    resource.Component.Add(component);

                    // value is of Type Quantity
                    if (observation.ValueQuantityValue != null)
                    {
                        Quantity quantity = new Quantity();
                        quantity.Code   = observation.ValueQuantityCode[i];
                        quantity.System = observation.ValueQuantitySystem[i];
                        quantity.Unit   = observation.ValueQuantityUnit[i];
                        quantity.Value  = observation.ValueQuantityValue[i];

                        resource.Component[i].Value = quantity;
                    }
                    // value is of Type CodeableConcept
                    else if (observation.ValueCode[0] != string.Empty)
                    {
                        concept        = new CodeableConcept();
                        coding         = new Coding();
                        coding.Code    = observation.ValueCode[i];
                        coding.Display = observation.ValueDisplay[i];
                        coding.System  = observation.ValueSystem[i];

                        concept.Coding.Add(coding);
                        concept.Text = observation.ValueText[i];
                        resource.Component[i].Value = concept;
                    }
                    // value is of Type String
                    else if (observation.ValueString[0] != string.Empty)
                    {
                        FhirString fhirString = new FhirString();
                        fhirString.Value = observation.ValueString[i];

                        resource.Component[i].Value = fhirString;
                    }
                    // value is of Type SampledData
                    else if (observation.ValueSampledDataOriginValue != null)
                    {
                        SampledData    sampleData = new SampledData();
                        SimpleQuantity quantity   = new SimpleQuantity();
                        quantity.Code   = observation.ValueSampledDataOriginCode[i];
                        quantity.System = observation.ValueSampledDataOriginSystem[i];
                        quantity.Unit   = observation.ValueSampledDataOriginUnit[i];
                        quantity.Value  = observation.ValueSampledDataOriginValue[i];

                        sampleData.Origin     = quantity;
                        sampleData.Data       = observation.ValueSampledDataData[i];
                        sampleData.Dimensions = observation.ValueSampledDataDimensions[i];
                        sampleData.Period     = observation.ValueSampledDataPeriod[i];

                        resource.Component[i].Value = sampleData;
                    }
                    // value is of Type Period
                    else if (observation.ValuePeriodStart != null)
                    {
                        Period period = new Period();
                        period.Start = observation.ValuePeriodStart[i].ToString();
                        period.End   = observation.ValuePeriodEnd[i].ToString();

                        resource.Component[i].Value = period;
                    }
                    // No value provided
                    else
                    {
                        resource.Component[i].Value = null;
                    }
                }
            }
            //There is only one "set" of values
            else
            {
                // value is of Type Quantity
                if (observation.ValueQuantityValue != null)
                {
                    Quantity quantity = new Quantity();
                    quantity.Code   = observation.ValueQuantityCode[0];
                    quantity.System = observation.ValueQuantitySystem[0];
                    quantity.Unit   = observation.ValueQuantityUnit[0];
                    quantity.Value  = observation.ValueQuantityValue[0];

                    resource.Value = quantity;
                }
                // value is of Type CodeableConcept
                else if (observation.ValueCode[0] != string.Empty)
                {
                    CodeableConcept concept = new CodeableConcept();
                    Coding          coding  = new Coding();
                    coding.Code    = observation.ValueCode[0];
                    coding.Display = observation.ValueDisplay[0];
                    coding.System  = observation.ValueSystem[0];

                    concept.Coding.Add(coding);
                    concept.Text   = observation.ValueText[0];
                    resource.Value = concept;
                }
                // value is of Type String
                else if (observation.ValueString[0] != string.Empty)
                {
                    FhirString fhirString = new FhirString();
                    fhirString.Value = observation.ValueString[0];

                    resource.Value = fhirString;
                }
                // value is of Type SampledData
                else if (observation.ValueSampledDataOriginValue != null)
                {
                    SampledData    sampleData = new SampledData();
                    SimpleQuantity quantity   = new SimpleQuantity();
                    quantity.Code   = observation.ValueSampledDataOriginCode[0];
                    quantity.System = observation.ValueSampledDataOriginSystem[0];
                    quantity.Unit   = observation.ValueSampledDataOriginUnit[0];
                    quantity.Value  = observation.ValueSampledDataOriginValue[0];

                    sampleData.Origin     = quantity;
                    sampleData.Data       = observation.ValueSampledDataData[0];
                    sampleData.Dimensions = observation.ValueSampledDataDimensions[0];
                    sampleData.Period     = observation.ValueSampledDataPeriod[0];

                    resource.Value = sampleData;
                }
                // value is of Type Period
                else if (observation.ValuePeriodStart != null)
                {
                    Period period = new Period();
                    period.Start = observation.ValuePeriodStart[0].ToString();
                    period.End   = observation.ValuePeriodEnd[0].ToString();

                    resource.Value = period;
                }
                // No value provided.
                else
                {
                    resource.Value = null;
                }
            }

            return(resource);
        }
        public static async Task <Parameters> TranslateConceptAsync(this FhirClient client, Code code, FhirUri system, FhirString version,
                                                                    FhirUri valueSet, Coding coding, CodeableConcept codeableConcept, FhirUri target, IEnumerable <TranslateConceptDependency> dependencies)
        {
            Parameters par = createTranslateConceptParams(code, system, version, valueSet, coding, codeableConcept, target, dependencies);

            return(OperationResult <Parameters>(await client.TypeOperationAsync <ConceptMap>(RestOperation.TRANSLATE, par).ConfigureAwait(false)));
        }
예제 #30
0
 public static OperationOutcome AddWarning(this OperationOutcome outcome, string message, OperationOutcome.IssueType issueType = OperationOutcome.IssueType.NotFound, CodeableConcept codeableConcept = null)
 {
     return(outcome.AddIssue(OperationOutcome.IssueSeverity.Warning, message, issueType, codeableConcept));
 }