Ejemplo n.º 1
0
        // static IElementNavigator ToNamedNode(ElementDefinition elementDef) => new ElementDefinitionNamedNode(elementDef);

        void clearIssues()
        {
            _outcome = null;
        }
Ejemplo n.º 2
0
        private void WriteHTMLOutput(Type type, object value, Stream writeStream)
        {
            StreamWriter writer = new StreamWriter(writeStream, Encoding.UTF8);

            writer.WriteLine("<html>");
            writer.WriteLine("<head>");
            writer.WriteLine("  <link rel=\"icon\" href=\"/Content/Fire.png\"></link>");
            writer.WriteLine("</head>");
            writer.WriteLine("<body>");
            if (type == typeof(OperationOutcome))
            {
                OperationOutcome oo = (OperationOutcome)value;

                if (oo.Text != null)
                {
                    writer.Write(oo.Text.Div);
                }
            }
            else if (type == typeof(Resource))
            {
                if (value is Bundle)
                {
                    Bundle resource = (Bundle)value;

                    if (resource.SelfLink != null)
                    {
                        writer.WriteLine(String.Format("Searching: {0}<br/>", resource.SelfLink.OriginalString));

                        // Hl7.Fhir.Model.Parameters query = FhirParser.ParseQueryFromUriParameters(collection, parameters);

                        NameValueCollection ps = resource.SelfLink.ParseQueryString();
                        if (ps.AllKeys.Contains(FhirParameter.SORT))
                        {
                            writer.WriteLine(String.Format("    Sort by: {0}<br/>", ps[FhirParameter.SORT]));
                        }
                        if (ps.AllKeys.Contains(FhirParameter.SUMMARY))
                        {
                            writer.WriteLine("    Summary only<br/>");
                        }
                        if (ps.AllKeys.Contains(FhirParameter.COUNT))
                        {
                            writer.WriteLine(String.Format("    Count: {0}<br/>", ps[FhirParameter.COUNT]));
                        }
                        if (ps.AllKeys.Contains(FhirParameter.SNAPSHOT_INDEX))
                        {
                            writer.WriteLine(String.Format("    From RowNum: {0}<br/>", ps[FhirParameter.SNAPSHOT_INDEX]));
                        }
                        if (ps.AllKeys.Contains(FhirParameter.SINCE))
                        {
                            writer.WriteLine(String.Format("    Since: {0}<br/>", ps[FhirParameter.SINCE]));
                        }


                        foreach (var item in ps.AllKeys.Where(k => !k.StartsWith("_")))
                        {
                            if (ModelInfo.SearchParameters.Exists(s => s.Name == item))
                            {
                                writer.WriteLine(String.Format("    {0}: {1}<br/>", item, ps[item]));
                                //var parameters = transportContext..Request.TupledParameters();
                                //int pagesize = Request.GetIntParameter(FhirParameter.COUNT) ?? Const.DEFAULT_PAGE_SIZE;
                                //bool summary = Request.GetBooleanParameter(FhirParameter.SUMMARY) ?? false;
                                //string sortby = Request.GetParameter(FhirParameter.SORT);
                            }
                            else
                            {
                                writer.WriteLine(String.Format("    <i>{0}: {1} (excluded)</i><br/>", item, ps[item]));
                            }
                        }
                    }

                    if (resource.FirstLink != null)
                    {
                        writer.WriteLine(String.Format("First Link: {0}<br/>", resource.FirstLink.OriginalString));
                    }
                    if (resource.PreviousLink != null)
                    {
                        writer.WriteLine(String.Format("Previous Link: {0}<br/>", resource.PreviousLink.OriginalString));
                    }
                    if (resource.NextLink != null)
                    {
                        writer.WriteLine(String.Format("Next Link: {0}<br/>", resource.NextLink.OriginalString));
                    }
                    if (resource.LastLink != null)
                    {
                        writer.WriteLine(String.Format("Last Link: {0}<br/>", resource.LastLink.OriginalString));
                    }

                    // Write the other Bundle Header data
                    writer.WriteLine(String.Format("<span style=\"word-wrap: break-word; display:block;\">Type: {0}, {1} of {2}</span>", resource.Type.ToString(), resource.Entry.Count, resource.Total));

                    foreach (var item in resource.Entry)
                    {
                        //IKey key = item.ExtractKey();

                        writer.WriteLine("<div class=\"item-tile\">");
                        if (item.IsDeleted())
                        {
                            if (item.Request != null)
                            {
                                string id = item.Request.Url;
                                writer.WriteLine(String.Format("<span style=\"word-wrap: break-word; display:block;\">{0}</span>", id));
                            }

                            //if (item.Deleted.Instant.HasValue)
                            //    writer.WriteLine(String.Format("<i>Deleted: {0}</i><br/>", item.Deleted.Instant.Value.ToString()));

                            writer.WriteLine("<hr/>");
                            writer.WriteLine("<b>DELETED</b><br/>");
                        }
                        else if (item.Resource != null)
                        {
                            Key    key       = item.Resource.ExtractKey();
                            string visualurl = key.WithoutBase().ToUriString();
                            string realurl   = key.ToUriString() + "?_format=html";

                            writer.WriteLine(String.Format("<a style=\"word-wrap: break-word; display:block;\" href=\"{0}\">{1}</a>", realurl, visualurl));
                            if (item.Resource.Meta != null && item.Resource.Meta.LastUpdated.HasValue)
                            {
                                writer.WriteLine(String.Format("<i>Modified: {0}</i><br/>", item.Resource.Meta.LastUpdated.Value.ToString()));
                            }
                            writer.WriteLine("<hr/>");

                            if (item.Resource is DomainResource)
                            {
                                if ((item.Resource as DomainResource).Text != null && !string.IsNullOrEmpty((item.Resource as DomainResource).Text.Div))
                                {
                                    writer.Write((item.Resource as DomainResource).Text.Div);
                                }
                                else
                                {
                                    writer.WriteLine(String.Format("Blank Text: {0}<br/>", item.Resource.ExtractKey().ToUriString()));
                                }
                            }
                            else
                            {
                                writer.WriteLine("This is not a domain resource");
                            }
                        }
                        writer.WriteLine("</div>");
                    }
                }
                else
                {
                    DomainResource resource = (DomainResource)value;
                    string         org      = resource.ResourceBase + "/" + resource.ResourceType.ToString() + "/" + resource.Id;
                    // TODO: This is probably a bug in the service (Id is null can throw ResourceIdentity == null
                    // reference ResourceIdentity : org = resource.ResourceIdentity().OriginalString;
                    writer.WriteLine(String.Format("Retrieved: {0}<hr/>", org));

                    string text = (resource.Text != null) ? resource.Text.Div : null;
                    writer.Write(text);
                    writer.WriteLine("<hr/>");

                    SummaryType summary = requestMessage.RequestSummary();

                    string xml = _serializer.SerializeToString(resource, summary);
                    System.Xml.XPath.XPathDocument xmlDoc = new System.Xml.XPath.XPathDocument(new StringReader(xml));

                    // And we also need an output writer
                    System.IO.TextWriter output = new System.IO.StringWriter(new System.Text.StringBuilder());

                    // Now for a little magic
                    // Create XML Reader with style-sheet
                    System.Xml.XmlReader stylesheetReader = System.Xml.XmlReader.Create(new StringReader(Resources.RenderXMLasHTML));

                    System.Xml.Xsl.XslCompiledTransform xslTransform = new System.Xml.Xsl.XslCompiledTransform();
                    xslTransform.Load(stylesheetReader);
                    xslTransform.Transform(xmlDoc, null, output);

                    writer.WriteLine(output.ToString());
                }
            }

            writer.WriteLine("</body>");
            writer.WriteLine("</html>");
            writer.Flush();
        }
Ejemplo n.º 3
0
 internal OperationOutcome.IssueComponent Trace(OperationOutcome outcome, string message, Issue issue, ITypedElement location)
 {
     return(Settings.Trace || issue.Severity != OperationOutcome.IssueSeverity.Information
         ? Trace(outcome, message, issue, location.Location)
         : null);
 }
Ejemplo n.º 4
0
 public static OperationOutcome AddIssue(this OperationOutcome outcome, string message, Issue infoIssue, string location = null)
 {
     outcome.AddIssue(infoIssue.ToIssueComponent(message, location));
     return(outcome);
 }
Ejemplo n.º 5
0
        public async Task <HttpResponseMessage> Save(Class value)
        {
            OperationOutcome outcome = await ecommerceReader.Save(value);

            return(Request.CreateResponse(HttpStatusCode.OK, outcome));
        }
Ejemplo n.º 6
0
        //   private OperationOutcome validateElement(ElementDefinitionNavigator definition, IElementNavigator instance)

        private OperationOutcome validateElement(ElementDefinitionNavigator definition, ScopedNode instance)
        {
            var outcome = new OperationOutcome();

            Trace(outcome, $"Start validation of ElementDefinition at path '{definition.QualifiedDefinitionPath()}'", Issue.PROCESSING_PROGRESS, instance);

            // If navigator cannot be moved to content, there's really nothing to validate against.
            if (definition.AtRoot && !definition.MoveToFirstChild())
            {
                outcome.AddIssue($"Snapshot component of profile '{definition.StructureDefinition?.Url}' has no content.", Issue.PROFILE_ELEMENTDEF_IS_EMPTY, instance);
                return(outcome);
            }

            // This does not work, since the children might still be empty, we need something better
            //// Any node must either have a value, or children, or both (e.g. extensions on primitives)
            if (instance.Value == null && !instance.Children().Any())
            {
                outcome.AddIssue("Element must not be empty", Issue.CONTENT_ELEMENT_MUST_HAVE_VALUE_OR_CHILDREN, instance);
                return(outcome);
            }

            var elementConstraints = definition.Current;

            if (elementConstraints.IsPrimitiveValueConstraint())
            {
                // The "value" property of a FHIR Primitive is the bottom of our recursion chain, it does not have a nameReference
                // nor a <type>, the only thing left to do to validate the content is to validate the string representation of the
                // primitive against the regex given in the core definition
                outcome.Add(VerifyPrimitiveContents(elementConstraints, instance));
            }
            else
            {
                bool isInlineChildren = !definition.Current.IsRootElement();

                // Now, validate the children
                if (definition.HasChildren)
                {
                    // If we are at the root of an abstract type (e.g. is this instance a Resource)?
                    // or we are at a nested resource, we may expect more children in the instance than
                    // we know about
                    bool allowAdditionalChildren = (isInlineChildren && elementConstraints.IsResourcePlaceholder()) ||
                                                   (!isInlineChildren && definition.StructureDefinition.Abstract == true);

                    // Handle in-lined constraints on children. In a snapshot, these children should be exhaustive,
                    // so there's no point in also validating the <type> or <nameReference>
                    // TODO: Check whether this is even true when the <type> has a profile?
                    // Note: the snapshot is *not* exhaustive if the declared type is a base FHIR type (like Resource),
                    // in which case there may be additional children (verified in the next step)
                    outcome.Add(this.ValidateChildConstraints(definition, instance, allowAdditionalChildren: allowAdditionalChildren));

                    // Special case: if we are located at a nested resource (i.e. contained or Bundle.entry.resource),
                    // we need to validate based on the actual type of the instance
                    if (isInlineChildren && elementConstraints.IsResourcePlaceholder())
                    {
                        outcome.Add(this.ValidateType(elementConstraints, instance));
                    }
                }

                if (!definition.HasChildren)
                {
                    // No inline-children, so validation depends on the presence of a <type> or <nameReference>
                    if (elementConstraints.Type != null || elementConstraints.NameReference != null)
                    {
                        outcome.Add(this.ValidateType(elementConstraints, instance));
                        outcome.Add(ValidateNameReference(elementConstraints, definition, instance));
                    }
                    else
                    {
                        Trace(outcome, "ElementDefinition has no child, nor does it specify a type or nameReference to validate the instance data against", Issue.PROFILE_ELEMENTDEF_CONTAINS_NO_TYPE_OR_NAMEREF, instance);
                    }
                }
            }

            outcome.Add(this.ValidateFixed(elementConstraints, instance));
            outcome.Add(this.ValidatePattern(elementConstraints, instance));
            outcome.Add(this.ValidateMinMaxValue(elementConstraints, instance));
            outcome.Add(ValidateMaxLength(elementConstraints, instance));
            outcome.Add(this.ValidateFp(elementConstraints, instance));
            outcome.Add(this.ValidateBinding(elementConstraints, instance));
            outcome.Add(this.ValidateExtension(elementConstraints, instance, "http://hl7.org/fhir/StructureDefinition/regex"));

            // If the report only has partial information, no use to show the hierarchy, so flatten it.
            if (Settings.Trace == false)
            {
                outcome.Flatten();
            }

            return(outcome);
        }
Ejemplo n.º 7
0
 public static void Clear(this OperationOutcome outcome)
 {
     outcome.Issue.Clear();
 }
        public void ValidateInvariantAllExamples()
        {
            FhirXmlParser            parser               = new FhirXmlParser();
            int                      errorCount           = 0;
            int                      testFileCount        = 0;
            Dictionary <string, int> failedInvariantCodes = new Dictionary <string, int>();

            var zip = TestDataHelper.ReadTestZip("examples.zip");

            using (zip)
            {
                foreach (var entry in zip.Entries)
                {
                    Stream file = entry.Open();
                    using (file)
                    {
                        // Verified examples that fail validations
                        // dom-3
                        if (entry.Name.EndsWith("list-example-familyhistory-genetics-profile-annie(prognosis).xml"))
                        {
                            continue;
                        }
                        if (entry.Name.EndsWith("questionnaire-sdc-profile-example-loinc(questionnaire-sdc-profile-example-loinc).xml"))
                        {
                            continue;
                        }
                        if (entry.Name.EndsWith("questionnaireresponse-example(3141).xml"))
                        {
                            continue;
                        }

                        // vsd-3, vsd-8
                        //if (file.EndsWith("valueset-ucum-common(ucum-common).xml"))
                        //    continue;

                        // vsd-9
                        if (entry.Name.EndsWith("valueset-example-expansion(example-expansion).xml"))
                        {
                            continue;
                        }


                        var reader   = SerializationUtil.WrapXmlReader(XmlReader.Create(file));
                        var resource = parser.Parse <Resource>(reader);

                        testFileCount++;
                        // Debug.WriteLine(String.Format("Validating {0}", entry.Name));
                        resource.InvariantConstraints = new List <ElementDefinition.ConstraintComponent>();
                        resource.AddDefaultConstraints();
                        var outcome = new OperationOutcome();
                        resource.ValidateInvariants(outcome);
                        if (outcome.Issue.Count > 0)
                        {
                            Debug.WriteLine(String.Format("Validating {0} failed:", entry.Name));
                            foreach (var item in outcome.Issue)
                            {
                                if (!failedInvariantCodes.ContainsKey(item.Details.Coding[0].Code))
                                {
                                    failedInvariantCodes.Add(item.Details.Coding[0].Code, 1);
                                }
                                else
                                {
                                    failedInvariantCodes[item.Details.Coding[0].Code]++;
                                }

                                Trace.WriteLine("\t" + item.Details.Coding[0].Code + ": " + item.Details.Text);
                            }

                            Trace.WriteLine("-------------------------");
                            Trace.WriteLine(new FhirXmlSerializer().SerializeToString(resource));
                            Trace.WriteLine("-------------------------");
                        }
                        if (outcome.Issue.Count != 0)
                        {
                            errorCount++;
                        }
                    }
                }
            }

            Debug.WriteLine(String.Format("\r\n------------------\r\nValidation failed in {0} of {1} examples", errorCount, testFileCount));
            if (failedInvariantCodes.Count > 0)
            {
                Debug.Write("Issues with Invariant: ");
                bool b = false;
                foreach (var item in failedInvariantCodes)
                {
                    if (b)
                    {
                        Debug.Write(", ");
                    }
                    Debug.Write(String.Format("{0} ({1})", item.Key, item.Value));
                    b = true;
                }
            }
            Assert.AreEqual(0, errorCount, String.Format("Failed Validating {0} of {1} examples", errorCount, testFileCount));
        }
Ejemplo n.º 9
0
 public static void AddIssue(this OperationOutcome outcome, params OperationOutcome.IssueComponent[] issue)
 {
     outcome.AddIssue((IEnumerable<OperationOutcome.IssueComponent>)issue);
 }
Ejemplo n.º 10
0
 public static void AddIssue(this OperationOutcome outcome, IEnumerable<OperationOutcome.IssueComponent> issues)
 {
     outcome.Issue.AddRange(issues);
 }
Ejemplo n.º 11
0
 public static OperationOutcome.IssueComponent AddIssue(this OperationOutcome outcome, OperationOutcome.IssueComponent issue)
 {
     outcome.Issue.Add(issue);
     return issue;
 }
        /// <summary>
        /// Invoke the operation
        /// </summary>
        public Resource Invoke(Parameters parameters)
        {
            var resource = parameters.Parameter.FirstOrDefault(o => o.Name == "resource");
            var profile  = parameters.Parameter.FirstOrDefault(o => o.Name == "profile");
            var mode     = parameters.Parameter.FirstOrDefault(o => o.Name == "mode");

            var retVal = new OperationOutcome();

            // Get the profile handler for the specified profile, if no profile then just perform a profile mode
            if (!resource.Resource.TryDeriveResourceType(out ResourceType rt))
            {
                retVal.Issue.Add(new OperationOutcome.IssueComponent()
                {
                    Code        = OperationOutcome.IssueType.NotSupported,
                    Severity    = OperationOutcome.IssueSeverity.Fatal,
                    Diagnostics = $"Resource {resource.Resource.TypeName} not supported"
                });
            }
            else
            {
                var hdlr = FhirResourceHandlerUtil.GetResourceHandler(rt);
                if (hdlr == null)
                {
                    retVal.Issue.Add(new OperationOutcome.IssueComponent()
                    {
                        Code        = OperationOutcome.IssueType.NotSupported,
                        Severity    = OperationOutcome.IssueSeverity.Fatal,
                        Diagnostics = $"Resource {resource.Resource.TypeName} not supported"
                    });
                }
                else
                {
                    // Find all profiles and validate
                    if (profile?.Value != null)
                    {
                        retVal.Issue = ExtensionUtil.ProfileHandlers.Where(o => (profile.Value as FhirUri).Value == o.ProfileUri.ToString()).Select(o => o.Validate(resource.Resource))
                                       .SelectMany(i => i.Select(o => DataTypeConverter.ToIssue(o))).ToList();
                    }

                    try
                    {
                        // Instruct the handler to perform an update with
                        hdlr.Update(resource.Resource.Id, resource.Resource, Core.Services.TransactionMode.Rollback);
                        retVal.Issue.Add(new OperationOutcome.IssueComponent()
                        {
                            Diagnostics = "Resource Valid",
                            Severity    = OperationOutcome.IssueSeverity.Information,
                            Code        = OperationOutcome.IssueType.Unknown
                        });
                    }
                    catch (DetectedIssueException e)
                    {
                        retVal.Issue.AddRange(e.Issues.Select(o => DataTypeConverter.ToIssue(o)));
                    }
                    catch (Exception e)
                    {
                        retVal.Issue.Add(new OperationOutcome.IssueComponent()
                        {
                            Severity    = OperationOutcome.IssueSeverity.Error,
                            Code        = OperationOutcome.IssueType.NoStore,
                            Diagnostics = e.Message
                        });
                    }
                }
            }
            return(retVal);
        }
Ejemplo n.º 13
0
 /// <summary>
 /// Mark the operation as having succeeded.
 /// </summary>
 public void Success()
 {
     _outcome = OperationOutcome.Success;
 }
Ejemplo n.º 14
0
 public FhirOperationException(string message, OperationOutcome outcome)
     : base(message)
 {
     Outcome = outcome;
 }
Ejemplo n.º 15
0
 public static IEnumerable<OperationOutcome.IssueComponent> ListErrors(this OperationOutcome outcome)
 {
     return outcome.Issue.Where(issue => !issue.Success);
 }
Ejemplo n.º 16
0
 /// <summary>
 /// Mark the operation as having failed.
 /// </summary>
 public void Fail()
 {
     _outcome = OperationOutcome.Fail;
 }
Ejemplo n.º 17
0
 public static IEnumerable<OperationOutcome.IssueComponent> ErrorsAt(this OperationOutcome outcome, string path)
 {
     return outcome.ListErrors().Where(issue => issue.IsAt(path));
 }
Ejemplo n.º 18
0
 public SparkException(HttpStatusCode statuscode, OperationOutcome outcome, string message = null)
     : this(statuscode, message)
 {
     Outcome = outcome;
 }
Ejemplo n.º 19
0
 public static IEnumerable<OperationOutcome.IssueComponent> AtLevel(this OperationOutcome outcome, int level)
 {
     return outcome.Issue.Where(i => i.GetHierarchyLevel() == level);
 }
Ejemplo n.º 20
0
        public static OperationOutcome ValidateEntry(ResourceEntry entry)
        {
            OperationOutcome result = new OperationOutcome();

            result.Issue = new List <OperationOutcome.OperationOutcomeIssueComponent>();

            ICollection <ValidationResult> vresults = new List <ValidationResult>();


            // Phase 1, validate against low-level rules built into the FHIR datatypes

            // todo: The API no longer seems to have the FhirValidator class.

            /*
             * (!FhirValidator.TryValidate(entry.Resource, vresults, recurse: true))
             * {
             *  foreach (var vresult in vresults)
             *      result.Issue.Add(createValidationResult("[.NET validation] " + vresult.ErrorMessage, vresult.MemberNames));
             * }
             */

            // Phase 2, validate against the XML schema
            var xml = FhirSerializer.SerializeResourceToXml(entry.Resource);
            var doc = XDocument.Parse(xml);

            doc.Validate(SchemaCollection.ValidationSchemaSet, (source, args) => result.Issue.Add(createValidationResult("[XSD validation] " + args.Message, null)));


            // Phase 3, validate against a profile, if present
            var profileTags = entry.GetAssertedProfiles();

            if (profileTags.Count() == 0)
            {
                // If there's no profile specified, at least compare it to the "base" profile
                string baseProfile = CoreZipArtifactSource.CORE_SPEC_PROFILE_URI_PREFIX + entry.Resource.GetCollectionName();
                profileTags = new Uri[] { new Uri(baseProfile, UriKind.Absolute) };
            }

            var artifactSource = ArtifactResolver.CreateOffline();
            var specProvider   = new SpecificationProvider(artifactSource);

            foreach (var profileTag in profileTags)
            {
                var specBuilder = new SpecificationBuilder(specProvider);
                specBuilder.Add(StructureFactory.PrimitiveTypes());
                specBuilder.Add(StructureFactory.MetaTypes());
                specBuilder.Add(StructureFactory.NonFhirNamespaces());
                specBuilder.Add(profileTag.ToString());
                specBuilder.Expand();

                string path = Directory.GetCurrentDirectory();

                var spec = specBuilder.ToSpecification();
                var nav  = doc.CreateNavigator();
                nav.MoveToFirstChild();

                Report report = spec.Validate(nav);
                var    errors = report.Errors;
                foreach (var error in errors)
                {
                    result.Issue.Add(createValidationResult("[Profile validator] " + error.Message, null));
                }
            }

            if (result.Issue.Count == 0)
            {
                return(null);
            }
            else
            {
                return(result);
            }
        }
Ejemplo n.º 21
0
        internal static OperationOutcome ValidateResourceReference(this Validator validator, ScopedNavigator instance, ElementDefinition.TypeRefComponent typeRef)
        {
            var outcome = new OperationOutcome();

            var reference = instance.ParseResourceReference()?.Reference;

            if (reference == null)       // No reference found -> this is always valid
            {
                return(outcome);
            }

            // Try to resolve the reference *within* the current instance (Bundle, resource with contained resources) first
            var referencedResource = validator.resolveReference(instance, reference,
                                                                out ElementDefinition.AggregationMode? encounteredKind, outcome);

            // Validate the kind of aggregation.
            // If no aggregation is given, all kinds of aggregation are allowed, otherwise only allow
            // those aggregation types that are given in the Aggregation element
            bool hasAggregation = typeRef.Aggregation != null && typeRef.Aggregation.Count() != 0;

            if (hasAggregation && !typeRef.Aggregation.Any(a => a == encounteredKind))
            {
                validator.Trace(outcome, $"Encountered a reference ({reference}) of kind '{encounteredKind}' which is not allowed", Issue.CONTENT_REFERENCE_OF_INVALID_KIND, instance);
            }

            // Bail out if we are asked to follow an *external reference* when this is disabled in the settings
            if (validator.Settings.ResolveExteralReferences == false && encounteredKind == ElementDefinition.AggregationMode.Referenced)
            {
                return(outcome);
            }

            // If we failed to find a referenced resource within the current instance, try to resolve it using an external method
            if (referencedResource == null && encounteredKind == ElementDefinition.AggregationMode.Referenced)
            {
                try
                {
                    referencedResource = validator.ExternalReferenceResolutionNeeded(reference, outcome, instance.Location);
                }
                catch (Exception e)
                {
                    validator.Trace(outcome, $"Resolution of external reference {reference} failed. Message: {e.Message}",
                                    Issue.UNAVAILABLE_REFERENCED_RESOURCE, instance);
                }
            }

            // If the reference was resolved (either internally or externally, validate it
            if (referencedResource != null)
            {
                validator.Trace(outcome, $"Starting validation of referenced resource {reference} ({encounteredKind})", Issue.PROCESSING_START_NESTED_VALIDATION, instance);

                // References within the instance are dealt with within the same validator,
                // references to external entities will operate within a new instance of a validator (and hence a new tracking context).
                // In both cases, the outcome is included in the result.
                OperationOutcome childResult;

                if (encounteredKind != ElementDefinition.AggregationMode.Referenced)
                {
                    childResult = validator.Validate(referencedResource, typeRef.GetDeclaredProfiles(), statedProfiles: null, statedCanonicals: null);
                }
                else
                {
                    var newValidator = validator.NewInstance();
                    childResult = newValidator.Validate(referencedResource, typeRef.GetDeclaredProfiles(), statedProfiles: null, statedCanonicals: null);
                }

                // Prefix each path with the referring resource's path to keep the locations
                // interpretable
                foreach (var issue in childResult.Issue)
                {
                    issue.Location = issue.Location.Concat(new string[] { instance.Location });
                }

                outcome.Include(childResult);
            }
            else
            {
                validator.Trace(outcome, $"Cannot resolve reference {reference}", Issue.UNAVAILABLE_REFERENCED_RESOURCE, instance);
            }

            return(outcome);
        }
Ejemplo n.º 22
0
 internal OperationOutcome.IssueComponent Trace(OperationOutcome outcome, string message, Issue issue, string location)
 {
     return(Settings.Trace || issue.Severity != OperationOutcome.IssueSeverity.Information
         ? outcome.AddIssue(message, issue, location)
         : null);
 }
Ejemplo n.º 23
0
        private static IElementNavigator resolveReference(this Validator validator, ScopedNavigator instance, string reference, out ElementDefinition.AggregationMode?referenceKind, OperationOutcome outcome)
        {
            var identity = new ResourceIdentity(reference);

            if (identity.Form == ResourceIdentityForm.Undetermined)
            {
                if (!Uri.IsWellFormedUriString(reference, UriKind.RelativeOrAbsolute))
                {
                    validator.Trace(outcome, $"Encountered an unparseable reference ({reference})", Issue.CONTENT_UNPARSEABLE_REFERENCE, instance);
                    referenceKind = null;
                    return(null);
                }
            }

            var result = instance.Resolve(reference);

            if (identity.Form == ResourceIdentityForm.Local)
            {
                referenceKind = ElementDefinition.AggregationMode.Contained;
                if (result == null)
                {
                    validator.Trace(outcome, $"Contained reference ({reference}) is not resolvable", Issue.CONTENT_CONTAINED_REFERENCE_NOT_RESOLVABLE, instance);
                }
            }
            else
            {
                if (result != null)
                {
                    referenceKind = ElementDefinition.AggregationMode.Bundled;
                }
                else
                {
                    referenceKind = ElementDefinition.AggregationMode.Referenced;
                }
            }

            return(result);
        }
Ejemplo n.º 24
0
 public FhirServerException(HttpStatusCode statuscode, OperationOutcome outcome, string message = null)
     : this(statuscode, message)
 {
     this.Outcome = outcome;
 }
Ejemplo n.º 25
0
        internal static OperationOutcome ValidateType(this Validator validator, ElementDefinition definition, ScopedNavigator instance)
        {
            var outcome = new OperationOutcome();

            validator.Trace(outcome, "Validating against constraints specified by the element's defined type", Issue.PROCESSING_PROGRESS, instance);

            if (definition.Type.Any(tr => tr.Code == null))
            {
                validator.Trace(outcome, "ElementDefinition contains a type with an empty type code", Issue.PROFILE_ELEMENTDEF_CONTAINS_NULL_TYPE, instance);
            }

            // Check if this is a choice: there are multiple distinct Codes to choose from
            var typeRefs = definition.Type.Where(tr => tr.Code != null);
            var choices  = typeRefs.Select(tr => tr.Code.Value).Distinct();

            if (choices.Count() > 1)
            {
                if (instance.Type != null)
                {
                    // This is a choice type, find out what type is present in the instance data
                    // (e.g. deceased[Boolean], or _resourceType in json). This is exposed by IElementNavigator.TypeName.
                    var instanceType = ModelInfo.FhirTypeNameToFhirType(instance.Type);
                    if (instanceType != null)
                    {
                        // In fact, the next statements are just an optimalization, without them, we would do an ANY validation
                        // against *all* choices, what we do here is pre-filtering for sensible choices, and report if there isn't
                        // any.
                        var applicableChoices = typeRefs.Where(tr => ModelInfo.IsInstanceTypeFor(tr.Code.Value, instanceType.Value));

                        // Instance typename must be one of the applicable types in the choice
                        if (applicableChoices.Any())
                        {
                            outcome.Include(validator.ValidateTypeReferences(applicableChoices, instance));
                        }
                        else
                        {
                            var choiceList = String.Join(",", choices.Select(t => "'" + t.GetLiteral() + "'"));
                            validator.Trace(outcome, $"Type specified in the instance ('{instance.Type}') is not one of the allowed choices ({choiceList})",
                                            Issue.CONTENT_ELEMENT_HAS_INCORRECT_TYPE, instance);
                        }
                    }
                    else
                    {
                        validator.Trace(outcome, $"Instance indicates the element is of type '{instance.Type}', which is not a known FHIR core type.",
                                        Issue.CONTENT_ELEMENT_CHOICE_INVALID_INSTANCE_TYPE, instance);
                    }
                }
                else
                {
                    validator.Trace(outcome, "ElementDefinition is a choice or contains a polymorphic type constraint, but the instance does not indicate its actual type",
                                    Issue.CONTENT_ELEMENT_CANNOT_DETERMINE_TYPE, instance);
                }
            }
            else if (choices.Count() == 1)
            {
                // Only one type present in list of typerefs, all of the typerefs are candidates
                outcome.Include(validator.ValidateTypeReferences(typeRefs, instance));
            }

            return(outcome);
        }
Ejemplo n.º 26
0
 public PyroException(HttpStatusCode statuscode, OperationOutcome OperationOutcome, string message, Exception inner)
     : base(message, inner)
 {
     this.HttpStatusCode   = statuscode;
     this.OperationOutcome = OperationOutcome;
 }
Ejemplo n.º 27
0
 public static OperationOutcome AddError(this OperationOutcome outcome, string message)
 {
     return(outcome.AddIssue(OperationOutcome.IssueSeverity.Error, message));
 }
Ejemplo n.º 28
0
        protected void ValidateOperationOutcome(string[] expectedDiagnostics, IssueSeverity[] expectedIsseSeverity, IssueType[] expectedCodeTypes, OperationOutcome operationOutcome)
        {
            Assert.NotNull(operationOutcome?.Id);
            Assert.NotEmpty(operationOutcome?.Issue);

            Assert.Equal(expectedCodeTypes.Length, operationOutcome.Issue.Count);
            Assert.Equal(expectedDiagnostics.Length, operationOutcome.Issue.Count);

            for (int iter = 0; iter < operationOutcome.Issue.Count; iter++)
            {
                Assert.Equal(expectedCodeTypes[iter], operationOutcome.Issue[iter].Code);
                Assert.Equal(expectedIsseSeverity[iter], operationOutcome.Issue[iter].Severity);
                Assert.Equal(expectedDiagnostics[iter], operationOutcome.Issue[iter].Diagnostics);
            }
        }
        /// <summary>
        /// Search for Documents or Get one by _id
        /// </summary>
        /// <remarks>
        /// As the NRLS is implemented with just a search and not read, to read a document the _id parameter is supplied
        /// </remarks>
        public async Task <Bundle> Find(FhirRequest request)
        {
            ValidateResource(request.StrResourceType);

            request.ProfileUri = _resourceProfile;

            var id = request.IdParameter;

            //We are going to be strict hear for search and only proceed if we have valid parameters
            if (request.InvalidParameters.Count() > 0)
            {
                throw new HttpFhirException("Invalid parameters", OperationOutcomeFactory.CreateInvalidParameter($"Invalid parameter: {string.Join(", ", request.InvalidParameters)}"), HttpStatusCode.BadRequest);
            }

            //If we have an _id param it should be the only param so check for that here.
            if (request.HasIdParameter)
            {
                ObjectId mongoId;
                if (!ObjectId.TryParse(id, out mongoId))
                {
                    throw new HttpFhirException("Invalid _id parameter", OperationOutcomeFactory.CreateNotFound(id), HttpStatusCode.NotFound);
                }

                if (request.QueryParameters.Count() > 1)
                {
                    throw new HttpFhirException("Invalid _id parameter combination", OperationOutcomeFactory.CreateInvalidParameter("Invalid parameter: _id"), HttpStatusCode.BadRequest);
                }

                request.Id        = id;
                request.IsIdQuery = true;

                var results = await _fhirSearch.GetAsBundle <DocumentReference>(request);

                var response = ParseRead(results, id) as Bundle;

                return(response);
            }

            //If we are here then it is a standard search query
            var patient = request.QueryParameters.FirstOrDefault(x => x.Item1 == "subject");

            if (patient != null)
            {
                var invalidPatient = _fhirValidation.ValidatePatientParameter(patient.Item2);

                if (invalidPatient != null)
                {
                    throw new HttpFhirException("Missing or Invalid patient parameter", invalidPatient, HttpStatusCode.BadRequest);
                }

                var nhsNumber = _fhirValidation.GetSubjectReferenceParameterId(patient.Item2);

                var patientRequest = NrlsPointerHelper.CreatePatientSearch(request, nhsNumber);
                var patients       = await _fhirSearch.Find <Patient>(patientRequest);

                if (patients.Entry.Count == 0)
                {
                    throw new HttpFhirException("Unknown patient", OperationOutcomeFactory.CreatePatientNotFound(nhsNumber), HttpStatusCode.NotFound);
                }
            }
            else
            {
                throw new HttpFhirException("Missing or Invalid patient parameter", OperationOutcomeFactory.CreateInvalidParameter("Missing parameter: subject"), HttpStatusCode.BadRequest);
            }

            var custodian = request.QueryParameters.FirstOrDefault(x => x.Item1 == "custodian");
            var useCustodianIdentifierValidation = false;

            if (custodian == null)
            {
                //temporarily also support the incorrectly spec'd custodian.identifier parameter
                //custodian is a reference type and should not be used in this way
                custodian = request.QueryParameters.FirstOrDefault(x => x.Item1 == "custodian.identifier");

                useCustodianIdentifierValidation = custodian != null;
            }

            if (custodian != null)
            {
                //temporarily also support the incorrectly spec'd custodian.identifier parameter
                var invalidCustodian = useCustodianIdentifierValidation ? _fhirValidation.ValidateCustodianIdentifierParameter(custodian.Item2) :
                                       _fhirValidation.ValidateCustodianParameter(custodian.Item2);

                if (invalidCustodian != null)
                {
                    throw new HttpFhirException("Missing or Invalid custodian parameter", invalidCustodian, HttpStatusCode.BadRequest);
                }

                var custodianOrgCode = useCustodianIdentifierValidation? _fhirValidation.GetOrganizationParameterIdentifierId(custodian.Item2) :
                                       _fhirValidation.GetOrganizationParameterId(custodian.Item2);

                var custodianRequest = NrlsPointerHelper.CreateOrgSearch(request, custodianOrgCode);
                var custodians       = await _fhirSearch.Find <Organization>(custodianRequest);

                if (custodians.Entry.Count == 0)
                {
                    var invalidOrg = OperationOutcomeFactory.CreateOrganizationNotFound(custodianOrgCode);

                    throw new HttpFhirException("Missing or Invalid custodian parameter", invalidOrg, HttpStatusCode.NotFound);
                }

                //This is now out of scope
                //var invalidOrgInteraction = ValidateOrganisationInteraction(request.RequestingAsid, custodianOrgCode, true);

                //if (invalidOrgInteraction != null)
                //{
                //    throw new HttpFhirException("Invalid Provider Request Exception", invalidOrgInteraction, HttpStatusCode.Unauthorized);
                //}
            }

            var type = request.QueryParameters.FirstOrDefault(x => x.Item1 == "type.coding");

            if (type != null)
            {
                var invalidType = _fhirValidation.ValidTypeParameter(type.Item2);

                if (invalidType != null)
                {
                    throw new HttpFhirException("Missing or Invalid type parameter", invalidType, HttpStatusCode.BadRequest);
                }
            }

            var summary = request.QueryParameters.FirstOrDefault(x => x.Item1 == "_summary");

            if (summary != null)
            {
                var validSummaryParams          = new string[] { "subject", "_format", "_summary" };
                var invalidSummaryParams        = request.QueryParameters.Where(x => !validSummaryParams.Contains(x.Item1));
                OperationOutcome invalidSummary = null;

                if (invalidSummaryParams.Any())
                {
                    var invalidSummaryParamsList = string.Join(", ", invalidSummaryParams.Select(x => $"{x.Item1}={x.Item2}"));

                    invalidSummary = OperationOutcomeFactory.CreateInvalidParameter("Invalid parameter", $"Unsupported search parameter - {invalidSummaryParamsList}");

                    throw new HttpFhirException("Missing or Invalid type parameter", invalidSummary, HttpStatusCode.BadRequest);
                }

                invalidSummary = _fhirValidation.ValidSummaryParameter(summary.Item2);

                if (invalidSummary != null)
                {
                    throw new HttpFhirException("Missing or Invalid type parameter", invalidSummary, HttpStatusCode.BadRequest);
                }

                request.IsSummary = true;
            }

            //Only allow current pointers
            var queryParameters = request.QueryParameters.ToList();

            queryParameters.Add(new Tuple <string, string>("status", "current"));
            request.QueryParameters   = queryParameters;
            request.AllowedParameters = request.AllowedParameters.Concat(new string[] { "status" }).ToArray();

            return(await _fhirSearch.Find <DocumentReference>(request));
        }
Ejemplo n.º 30
0
 public FhirOperationException(string message, OperationOutcome outcome, Exception inner)
     : base(message, inner)
 {
     Outcome = outcome;
 }
        public void ValidateInvariantAllExamplesWithOtherConstraints()
        {
            string profiles = TestDataHelper.GetFullPathForExample("profiles-others.xml");

            FhirXmlParser            parser               = new FhirXmlParser();
            int                      errorCount           = 0;
            int                      testFileCount        = 0;
            Dictionary <string, int> failedInvariantCodes = new Dictionary <string, int>();
            List <String>            checkedCode          = new List <string>();


            Bundle otherSDs;
            Dictionary <string, List <ElementDefinition.ConstraintComponent> > invariantCache = new Dictionary <string, List <ElementDefinition.ConstraintComponent> >();

            using (Stream streamOther = File.OpenRead(profiles))
            {
                otherSDs = new Fhir.Serialization.FhirXmlParser().Parse <Bundle>(SerializationUtil.XmlReaderFromStream(streamOther));
                foreach (StructureDefinition resource in otherSDs.Entry.Select(e => e.Resource).Where(r => r != null && r is StructureDefinition))
                {
                    List <ElementDefinition.ConstraintComponent> cacheForResource;
                    if (invariantCache.ContainsKey(resource.ConstrainedType.ToString()))
                    {
                        cacheForResource = invariantCache[resource.ConstrainedType.ToString()];
                    }
                    else
                    {
                        cacheForResource = new List <ElementDefinition.ConstraintComponent>();
                        invariantCache.Add(resource.ConstrainedType.ToString(), cacheForResource);
                    }

                    // read the invariants for elements in the differential
                    foreach (var ed in resource.Differential.Element)
                    {
                        foreach (var constraint in ed.Constraint)
                        {
                            var ext = constraint.GetExtensionValue <FhirString>("http://hl7.org/fhir/StructureDefinition/structuredefinition-expression");
                            if (ext == null)
                            {
                                continue;
                            }
                            string expression = ext.Value;
                            string parentPath = ed.Path;
                            if (parentPath.Contains("."))
                            {
                                // This expression applied to a backbone element, so need to give it scope
                                expression = parentPath.Replace(resource.ConstrainedType.ToString() + ".", "") + ".all(" + expression + ")";
                                ext.Value  = expression;
                            }
                            string key = constraint.Key;
                            if (!string.IsNullOrEmpty(expression))
                            {
                                cacheForResource.Add(constraint);
                            }
                        }
                    }
                }
            }

            var zip = TestDataHelper.ReadTestZip("examples.zip");

            using (zip)
            {
                foreach (var entry in zip.Entries)
                {
                    Stream file = entry.Open();
                    using (file)
                    {
                        // Verified examples that fail validations
                        // dom-3
                        if (entry.Name.EndsWith("list-example-familyhistory-genetics-profile-annie(prognosis).xml"))
                        {
                            continue;
                        }
                        if (entry.Name.EndsWith("questionnaire-sdc-profile-example-loinc(questionnaire-sdc-profile-example-loinc).xml"))
                        {
                            continue;
                        }
                        if (entry.Name.EndsWith("questionnaireresponse-example(3141).xml"))
                        {
                            continue;
                        }
                        if (entry.Name.EndsWith("dataelement-example(gender).xml"))
                        {
                            continue;
                        }


                        // vsd-3, vsd-8
                        //if (file.EndsWith("valueset-ucum-common(ucum-common).xml"))
                        //    continue;

                        var reader   = SerializationUtil.WrapXmlReader(XmlReader.Create(file));
                        var resource = parser.Parse <Resource>(reader);

                        testFileCount++;
                        // Debug.WriteLine(String.Format("Validating {0}", entry.Name));
                        resource.AddDefaultConstraints();
                        if (invariantCache.ContainsKey(resource.ResourceType.ToString()))
                        {
                            resource.InvariantConstraints.AddRange(invariantCache[resource.ResourceType.ToString()]);
                        }
                        var outcome = new OperationOutcome();
                        resource.ValidateInvariants(outcome);
                        // Debug.WriteLine("Key: " + String.Join(", ", resource.InvariantConstraints.Select(s => s.Key)));
                        foreach (var item in resource.InvariantConstraints)
                        {
                            if (checkedCode.Contains(item.Key))
                            {
                                continue;
                            }
                            checkedCode.Add(item.Key);
                            string expression = item.GetExtensionValue <FhirString>("http://hl7.org/fhir/StructureDefinition/structuredefinition-expression").Value;
                            if (expression.Contains("[x]"))
                            {
                                Debug.WriteLine(String.Format("Expression {0} had an [x] in it '{1}'", item.Key, expression));
                            }
                            if (expression.Contains("\"%\""))
                            {
                                Debug.WriteLine(String.Format("Expression {0} had an \"%\" in it '{1}'", item.Key, expression));
                            }
                            if (expression.Contains("$parent"))
                            {
                                Debug.WriteLine(String.Format("Expression {0} had a '$parent' in it '{1}'", item.Key, expression));
                            }
                            if (expression.Contains("descendents"))
                            {
                                Debug.WriteLine(String.Format("Expression {0} had an 'descendents' in it '{1}'", item.Key, expression));
                            }
                            if (expression.Contains("Decimal"))
                            {
                                Debug.WriteLine(String.Format("Expression {0} had an 'Decimal' in it '{1}'", item.Key, expression));
                            }
                            if (expression.Contains("String"))
                            {
                                Debug.WriteLine(String.Format("Expression {0} had an 'String' in it '{1}'", item.Key, expression));
                            }
                            if (expression.Contains("Integer"))
                            {
                                Debug.WriteLine(String.Format("Expression {0} had an 'Integer' in it '{1}'", item.Key, expression));
                            }
                        }
                        // we can skip the US zipcode validations
                        if (outcome.Issue.Where(i => (i.Diagnostics != "address.postalCode.all(matches('[0-9]{5}(-[0-9]{4}){0,1}'))")).Count() > 0)
                        {
                            Debug.WriteLine(String.Format("Validating {0} failed:", entry.Name));
                            foreach (var item in outcome.Issue)
                            {
                                if (!failedInvariantCodes.ContainsKey(item.Details.Coding[0].Code))
                                {
                                    failedInvariantCodes.Add(item.Details.Coding[0].Code, 1);
                                }
                                else
                                {
                                    failedInvariantCodes[item.Details.Coding[0].Code]++;
                                }

                                Trace.WriteLine("\t" + item.Details.Coding[0].Code + ": " + item.Details.Text);
                                Trace.WriteLine("\t" + item.Diagnostics);
                            }
                            //  Trace.WriteLine("-------------------------");
                            //  Trace.WriteLine(FhirSerializer.SerializeResourceToXml(resource));
                            //  Trace.WriteLine("-------------------------");
                            // count the issue
                            errorCount++;
                        }
                    }
                }
            }

            Debug.WriteLine(String.Format("\r\n------------------\r\nValidation failed in {0} of {1} examples", errorCount, testFileCount));
            if (failedInvariantCodes.Count > 0)
            {
                Debug.Write("Issues with Invariant: ");
                bool b = false;
                foreach (var item in failedInvariantCodes)
                {
                    if (b)
                    {
                        Debug.Write(", ");
                    }
                    Debug.Write(String.Format("{0} ({1})", item.Key, item.Value));
                    b = true;
                }
            }
            Assert.AreEqual(22, errorCount, String.Format("Failed Validating {0} of {1} examples", errorCount, testFileCount));

            /*
             * Validating dataelement-labtestmaster-example(prothrombin).xml failed:
             *  inv-2: One and only one DataElement.code must have is-data-element-concept set to "true"
             *  code.extension(%"ext-11179-de-is-data-element-concept").count() = 1
             * Validating dataelement-sdc-profile-example(dataelement-sdc-profile-example).xml failed:
             *  inv-2: One and only one DataElement.code must have is-data-element-concept set to "true"
             *  code.extension(%"ext-11179-de-is-data-element-concept").count() = 1
             * Validating dataelement-sdc-profile-example-de(dataelement-sdc-profile-example-de).xml failed:
             *  inv-2: One and only one DataElement.code must have is-data-element-concept set to "true"
             *  code.extension(%"ext-11179-de-is-data-element-concept").count() = 1
             * Validating organization-example-f001-burgers(f001).xml failed:
             *  inv-2: (Zip or Postal Code) SHALL be formatted as 99999[-9999] for US Zip or ZIP +4 codes or as A9A9A9 for Canadian postal codes.
             *  address.postalCode.all($this.matches('[0-9]{5}(-[0-9]{4}){0,1}'))
             *  inv-2: (Zip or Postal Code) SHALL be formatted as 99999[-9999] for US Zip or ZIP +4 codes or as A9A9A9 for Canadian postal codes.
             *  address.postalCode.all($this.matches('[0-9]{5}(-[0-9]{4}){0,1}'))
             *  inv-2: (Zip or Postal Code) SHALL be formatted as 99999[-9999] for US Zip or ZIP +4 codes or as A9A9A9 for Canadian postal codes.
             *  address.postalCode.all($this.matches('[0-9]{5}(-[0-9]{4}){0,1}'))
             * Validating organization-example-f201-aumc(f201).xml failed:
             *  inv-2: (Zip or Postal Code) SHALL be formatted as 99999[-9999] for US Zip or ZIP +4 codes or as A9A9A9 for Canadian postal codes.
             *  address.postalCode.all($this.matches('[0-9]{5}(-[0-9]{4}){0,1}'))
             *  inv-2: (Zip or Postal Code) SHALL be formatted as 99999[-9999] for US Zip or ZIP +4 codes or as A9A9A9 for Canadian postal codes.
             *  address.postalCode.all($this.matches('[0-9]{5}(-[0-9]{4}){0,1}'))
             *  inv-2: (Zip or Postal Code) SHALL be formatted as 99999[-9999] for US Zip or ZIP +4 codes or as A9A9A9 for Canadian postal codes.
             *  address.postalCode.all($this.matches('[0-9]{5}(-[0-9]{4}){0,1}'))
             * Validating organization-example-f203-bumc(f203).xml failed:
             *  inv-2: (Zip or Postal Code) SHALL be formatted as 99999[-9999] for US Zip or ZIP +4 codes or as A9A9A9 for Canadian postal codes.
             *  address.postalCode.all($this.matches('[0-9]{5}(-[0-9]{4}){0,1}'))
             *  inv-2: (Zip or Postal Code) SHALL be formatted as 99999[-9999] for US Zip or ZIP +4 codes or as A9A9A9 for Canadian postal codes.
             *  address.postalCode.all($this.matches('[0-9]{5}(-[0-9]{4}){0,1}'))
             *  inv-2: (Zip or Postal Code) SHALL be formatted as 99999[-9999] for US Zip or ZIP +4 codes or as A9A9A9 for Canadian postal codes.
             *  address.postalCode.all($this.matches('[0-9]{5}(-[0-9]{4}){0,1}'))
             * Validating patient-example(example).xml failed:
             *  inv-1: (Zip or Postal Code) SHALL be formatted as 99999[-9999] for US Zip or ZIP +4 codes or as A9A9A9 for Canadian postal codes.
             *  address.postalCode.all($this.matches('[0-9]{5}(-[0-9]{4}){0,1}'))
             *  inv-1: (Zip or Postal Code) SHALL be formatted as 99999[-9999] for US Zip or ZIP +4 codes or as A9A9A9 for Canadian postal codes.
             *  address.postalCode.all($this.matches('[0-9]{5}(-[0-9]{4}){0,1}'))
             *  inv-1: (Zip or Postal Code) SHALL be formatted as 99999[-9999] for US Zip or ZIP +4 codes or as A9A9A9 for Canadian postal codes.
             *  address.postalCode.all(matches('[0-9]{5}(-[0-9]{4}){0,1}'))
             * Validating patient-example-f001-pieter(f001).xml failed:
             *  inv-1: (Zip or Postal Code) SHALL be formatted as 99999[-9999] for US Zip or ZIP +4 codes or as A9A9A9 for Canadian postal codes.
             *  address.postalCode.all($this.matches('[0-9]{5}(-[0-9]{4}){0,1}'))
             *  inv-1: (Zip or Postal Code) SHALL be formatted as 99999[-9999] for US Zip or ZIP +4 codes or as A9A9A9 for Canadian postal codes.
             *  address.postalCode.all($this.matches('[0-9]{5}(-[0-9]{4}){0,1}'))
             *  inv-1: (Zip or Postal Code) SHALL be formatted as 99999[-9999] for US Zip or ZIP +4 codes or as A9A9A9 for Canadian postal codes.
             *  address.postalCode.all(matches('[0-9]{5}(-[0-9]{4}){0,1}'))
             * Validating patient-example-f201-roel(f201).xml failed:
             *  inv-1: (Zip or Postal Code) SHALL be formatted as 99999[-9999] for US Zip or ZIP +4 codes or as A9A9A9 for Canadian postal codes.
             *  address.postalCode.all($this.matches('[0-9]{5}(-[0-9]{4}){0,1}'))
             *  inv-1: (Zip or Postal Code) SHALL be formatted as 99999[-9999] for US Zip or ZIP +4 codes or as A9A9A9 for Canadian postal codes.
             *  address.postalCode.all($this.matches('[0-9]{5}(-[0-9]{4}){0,1}'))
             *  inv-1: (Zip or Postal Code) SHALL be formatted as 99999[-9999] for US Zip or ZIP +4 codes or as A9A9A9 for Canadian postal codes.
             *  address.postalCode.all(matches('[0-9]{5}(-[0-9]{4}){0,1}'))
             * Validating patient-example-us-extensions(us01).xml failed:
             *  inv-1: (Zip or Postal Code) SHALL be formatted as 99999[-9999] for US Zip or ZIP +4 codes or as A9A9A9 for Canadian postal codes.
             *  address.postalCode.all($this.matches('[0-9]{5}(-[0-9]{4}){0,1}'))
             *  inv-1: (Zip or Postal Code) SHALL be formatted as 99999[-9999] for US Zip or ZIP +4 codes or as A9A9A9 for Canadian postal codes.
             *  address.postalCode.all($this.matches('[0-9]{5}(-[0-9]{4}){0,1}'))
             *  inv-1: (Zip or Postal Code) SHALL be formatted as 99999[-9999] for US Zip or ZIP +4 codes or as A9A9A9 for Canadian postal codes.
             *  address.postalCode.all(matches('[0-9]{5}(-[0-9]{4}){0,1}'))
             * Validating practitioner-example-f001-evdb(f001).xml failed:
             *  inv-2: (Zip or Postal Code) SHALL be formatted as 99999[-9999] for US Zip or ZIP +4 codes or as A9A9A9 for Canadian postal codes.
             *  address.postalCode.all($this.matches('[0-9]{5}(-[0-9]{4}){0,1}'))
             * Validating practitioner-example-f002-pv(f002).xml failed:
             *  inv-2: (Zip or Postal Code) SHALL be formatted as 99999[-9999] for US Zip or ZIP +4 codes or as A9A9A9 for Canadian postal codes.
             *  address.postalCode.all($this.matches('[0-9]{5}(-[0-9]{4}){0,1}'))
             * Validating practitioner-example-f003-mv(f003).xml failed:
             *  inv-2: (Zip or Postal Code) SHALL be formatted as 99999[-9999] for US Zip or ZIP +4 codes or as A9A9A9 for Canadian postal codes.
             *  address.postalCode.all($this.matches('[0-9]{5}(-[0-9]{4}){0,1}'))
             * Validating practitioner-example-f004-rb(f004).xml failed:
             *  inv-2: (Zip or Postal Code) SHALL be formatted as 99999[-9999] for US Zip or ZIP +4 codes or as A9A9A9 for Canadian postal codes.
             *  address.postalCode.all($this.matches('[0-9]{5}(-[0-9]{4}){0,1}'))
             * Validating practitioner-example-f005-al(f005).xml failed:
             *  inv-2: (Zip or Postal Code) SHALL be formatted as 99999[-9999] for US Zip or ZIP +4 codes or as A9A9A9 for Canadian postal codes.
             *  address.postalCode.all($this.matches('[0-9]{5}(-[0-9]{4}){0,1}'))
             * Validating practitioner-example-f006-rvdb(f006).xml failed:
             *  inv-2: (Zip or Postal Code) SHALL be formatted as 99999[-9999] for US Zip or ZIP +4 codes or as A9A9A9 for Canadian postal codes.
             *  address.postalCode.all($this.matches('[0-9]{5}(-[0-9]{4}){0,1}'))
             * Validating practitioner-example-f007-sh(f007).xml failed:
             *  inv-2: (Zip or Postal Code) SHALL be formatted as 99999[-9999] for US Zip or ZIP +4 codes or as A9A9A9 for Canadian postal codes.
             *  address.postalCode.all($this.matches('[0-9]{5}(-[0-9]{4}){0,1}'))
             * Validating practitioner-example-f201-ab(f201).xml failed:
             *  inv-2: (Zip or Postal Code) SHALL be formatted as 99999[-9999] for US Zip or ZIP +4 codes or as A9A9A9 for Canadian postal codes.
             *  address.postalCode.all($this.matches('[0-9]{5}(-[0-9]{4}){0,1}'))
             * Validating practitioner-example-f202-lm(f202).xml failed:
             *  inv-2: (Zip or Postal Code) SHALL be formatted as 99999[-9999] for US Zip or ZIP +4 codes or as A9A9A9 for Canadian postal codes.
             *  address.postalCode.all($this.matches('[0-9]{5}(-[0-9]{4}){0,1}'))
             * Validating practitioner-example-f203-jvg(f203).xml failed:
             *  inv-2: (Zip or Postal Code) SHALL be formatted as 99999[-9999] for US Zip or ZIP +4 codes or as A9A9A9 for Canadian postal codes.
             *  address.postalCode.all($this.matches('[0-9]{5}(-[0-9]{4}){0,1}'))
             * Validating practitioner-example-f204-ce(f204).xml failed:
             *  inv-2: (Zip or Postal Code) SHALL be formatted as 99999[-9999] for US Zip or ZIP +4 codes or as A9A9A9 for Canadian postal codes.
             *  address.postalCode.all($this.matches('[0-9]{5}(-[0-9]{4}){0,1}'))
             * Validating valueset-example-expansion(example-expansion).xml failed:
             *      vsd-9: Must have a code if not abstract
             *      expansion.contains.all(code.exists() or (abstract = 'true'))
             *
             * ------------------
             * Validation failed in 22 of 725 examples
             * Issues with Invariant: inv-2 (23), inv-1 (12), vsd-9 (1)
             *
             */
        }
Ejemplo n.º 32
0
        public async Task <Bundle.EntryComponent> ExecuteAsync(Bundle.EntryComponent interaction)
        {
            if (interaction == null)
            {
                throw Error.ArgumentNull(nameof(interaction));
            }
            bool compressRequestBody = false;

            compressRequestBody = CompressRequestBody; // PCL doesn't support compression at the moment

            byte[] outBody;
            var    request = interaction.ToHttpRequest(BaseUrl, Prefer, PreferredFormat, UseFormatParameter, compressRequestBody, out outBody);

#if !NETSTANDARD1_1
            request.Timeout = Timeout;
#endif

            if (PreferCompressedResponses)
            {
                request.Headers["Accept-Encoding"] = "gzip, deflate";
            }

            LastRequest = request;
            if (BeforeRequest != null)
            {
                BeforeRequest(request, outBody);
            }

            // Write the body to the output
            if (outBody != null)
            {
                request.WriteBody(compressRequestBody, outBody);
            }

            // Make sure the HttpResponse gets disposed!
            using (HttpWebResponse webResponse = (HttpWebResponse)await request.GetResponseAsync(new TimeSpan(0, 0, 0, 0, Timeout)).ConfigureAwait(false))
            //using (HttpWebResponse webResponse = (HttpWebResponse)request.GetResponseNoEx())
            {
                try
                {
                    //Read body before we call the hook, so the hook cannot read the body before we do
                    var inBody = readBody(webResponse);

                    LastResponse = webResponse;
                    if (AfterResponse != null)
                    {
                        AfterResponse(webResponse, inBody);
                    }

                    // Do this call after AfterResponse, so AfterResponse will be called, even if exceptions are thrown by ToBundleEntry()
                    try
                    {
                        LastResult = null;

                        if (webResponse.StatusCode.IsSuccessful())
                        {
                            LastResult = webResponse.ToBundleEntry(inBody, ParserSettings, throwOnFormatException: true);
                            return(LastResult);
                        }
                        else
                        {
                            LastResult = webResponse.ToBundleEntry(inBody, ParserSettings, throwOnFormatException: false);
                            throw buildFhirOperationException(webResponse.StatusCode, LastResult.Resource);
                        }
                    }
                    catch (UnsupportedBodyTypeException bte)
                    {
                        // The server responded with HTML code. Still build a FhirOperationException and set a LastResult.
                        // Build a very minimal LastResult
                        var errorResult = new Bundle.EntryComponent();
                        errorResult.Response        = new Bundle.ResponseComponent();
                        errorResult.Response.Status = ((int)webResponse.StatusCode).ToString();

                        OperationOutcome operationOutcome = OperationOutcome.ForException(bte, OperationOutcome.IssueType.Invalid);

                        errorResult.Resource = operationOutcome;
                        LastResult           = errorResult;

                        throw buildFhirOperationException(webResponse.StatusCode, operationOutcome);
                    }
                }
                catch (AggregateException ae)
                {
                    //EK: This code looks weird. Is this correct?
                    if (ae.GetBaseException() is WebException)
                    {
                    }
                    throw ae.GetBaseException();
                }
            }
        }
Ejemplo n.º 33
0
        /// <summary>
        /// Performs application-defined tasks associated with freeing, releasing, or resetting unmanaged resources.
        /// </summary>
        public void Dispose()
        {
            try
            {
                _sw.Stop();

                var exceptionThrown = HasExceptionBeenThrown();
                if (exceptionThrown && _autoFailOnException)
                    _outcome = OperationOutcome.Fail;
                else if (!exceptionThrown && _autoSucceedOnExit)
                    _outcome = OperationOutcome.Success;

                if (_warnIfExceeds.HasValue && _sw.Elapsed > _warnIfExceeds.Value)
                    _logger.Write(LogEventLevel.Warning, OperationExccededTimeMessage, _identifier, _description, _warnIfExceeds.Value, _outcome, _sw.Elapsed, _sw.ElapsedMilliseconds);
                else if (_outcome == OperationOutcome.Fail)
                    _logger.Write(LogEventLevel.Warning, OperationCompletedMessage, _identifier, _description, _outcome, _sw.Elapsed, _sw.ElapsedMilliseconds);
                else
                    _logger.Write(_level, OperationCompletedMessage, _identifier, _description, _outcome, _sw.Elapsed, _sw.ElapsedMilliseconds);
            }
            finally
            {
                if(_contextualPropertiesBookmark != null)
                    _contextualPropertiesBookmark.Dispose();

                if(_operationContextBookmark != null)
                    _operationContextBookmark.Dispose();
            }
        }