public static OperationOutcome ValidateResource(this FhirClient client, DomainResource resource, string id = null, FhirUri profile = null)
        {
            if (resource == null)
            {
                throw Error.ArgumentNull(nameof(resource));
            }

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

            if (profile != null)
            {
                par.Add("profile", profile);
            }

            if (id == null)
            {
                return(expect <OperationOutcome>(client.TypeOperation(Operation.VALIDATE_RESOURCE, resource.TypeName, par)));
            }
            else
            {
                var loc = ResourceIdentity.Build(resource.TypeName, id);
                return(expect <OperationOutcome>(client.InstanceOperation(loc, Operation.VALIDATE_RESOURCE, par)));
            }
        }
Пример #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 href=\"/Content/fhir-html.css\" rel=\"stylesheet\"></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     = FhirSerializer.SerializeResourceToXml(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();
        }
Пример #3
0
 /// <summary>
 /// see http://hl7.org/fhir/http.html#create
 /// implementations MUST set LogicalId, VersionId and LastUpdated
 /// see https://www.hl7.org/fhir/datatypes.html#id
 /// Id format: [A-Za-z0-9\-\.]{1,64} (see Id.PATTERN)
 /// </summary>
 /// <param name="resource">
 /// The resource to create
 /// </param>
 /// <returns>
 /// Resource with adjusted values (LogicalId, VersionId, LastUpdated)
 /// </returns>
 public abstract Task <DomainResource> CreateResourceAsync(DomainResource resource);
        public static async Task <OperationOutcome> ValidateUpdateAsync(this FhirClient client, DomainResource resource, string id, FhirUri profile = null)
        {
            if (id == null)
            {
                throw Error.ArgumentNull(nameof(id));
            }
            if (resource == null)
            {
                throw Error.ArgumentNull(nameof(resource));
            }

            var par = new Parameters().Add("resource", resource).Add("mode", new Code("update"));

            if (profile != null)
            {
                par.Add("profile", profile);
            }

            var loc = ResourceIdentity.Build(resource.TypeName, id);

            return(OperationResult <OperationOutcome>(await client.InstanceOperationAsync(loc, RestOperation.VALIDATE_RESOURCE, par).ConfigureAwait(false)));
        }
 public static OperationOutcome ValidateCreate(this FhirClient client, DomainResource resource,
                                               FhirUri profile = null)
 {
     return(ValidateCreateAsync(client, resource, profile).WaitResult());
 }
        public static async Task <OperationOutcome> ValidateCreateAsync(this FhirClient client, DomainResource resource, FhirUri profile = null)
        {
            if (resource == null)
            {
                throw Error.ArgumentNull(nameof(resource));
            }

            var par = new Parameters().Add("resource", resource).Add("mode", new Code("create"));

            if (profile != null)
            {
                par.Add("profile", profile);
            }

            return(OperationResult <OperationOutcome>(await client.TypeOperationAsync(RestOperation.VALIDATE_RESOURCE, resource.TypeName, par).ConfigureAwait(false)));
        }
Пример #7
0
        /// <summary>
        /// Deserialize JSON into a FHIR DomainResource
        /// </summary>
        public static void DeserializeJsonProperty(this DomainResource current, ref Utf8JsonReader reader, JsonSerializerOptions options, string propertyName)
        {
            switch (propertyName)
            {
            case "text":
                current.Text = new Hl7.Fhir.Model.Narrative();
                ((Hl7.Fhir.Model.Narrative)current.Text).DeserializeJson(ref reader, options);
                break;

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

                current.Contained = new List <Resource>();

                while (reader.TokenType != JsonTokenType.EndArray)
                {
                    current.Contained.Add(JsonStreamResourceConverter.PolymorphicRead(ref reader, typeof(Resource), options));

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

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

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

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

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

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

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

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

                current.ModifierExtension = new List <Extension>();

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

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

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

            // Complex: DomainResource, Export: DomainResource, Base: Resource
            default:
                ((Hl7.Fhir.Model.Resource)current).DeserializeJsonProperty(ref reader, options, propertyName);
                break;
            }
        }
Пример #8
0
        public async Task <IActionResult> Get(string ResourceName, string id, string vid)
        {
            var buri = this.CalculateBaseURI("{ResourceName}");

            if (!Id.IsValidValue(id))
            {
                throw new FhirServerException(HttpStatusCode.BadRequest, "ID [" + id + "] is not a valid FHIR Resource ID");
            }

            var Inputs = GetInputs(buri);
            IFhirResourceServiceSTU3 model = GetResourceModel(ResourceName, Inputs);

            Hl7.Fhir.Rest.SummaryType summary = GetSummaryParameter(Request);

            Resource resource = await model.Get(id, vid, summary);

            if (resource != null)
            {
                resource.ResourceBase = new Hl7.Fhir.Rest.ResourceIdentity(Request.RequestUri()).BaseUri;

                if (resource is DomainResource)
                {
                    DomainResource dr = resource as DomainResource;
                    switch (summary)
                    {
                    case Hl7.Fhir.Rest.SummaryType.False:
                        break;

                    case Hl7.Fhir.Rest.SummaryType.True:
                        // summary doesn't have the text in it.
                        dr.Text = null;
                        // there are no contained references in the summary form
                        dr.Contained = null;

                        // Add in the Meta Tag that indicates that this resource is only a partial
                        resource.Meta.Tag = new List <Coding>
                        {
                            new Coding("http://hl7.org/fhir/v3/ObservationValue", "SUBSETTED")
                        };
                        break;

                    case Hl7.Fhir.Rest.SummaryType.Text:
                        // what do we need to filter here
                        break;

                    case Hl7.Fhir.Rest.SummaryType.Data:
                        // summary doesn't have the text in it.
                        dr.Text = null;
                        // Add in the Meta Tag that indicates that this resource is only a partial
                        resource.Meta.Tag = new List <Coding>
                        {
                            new Coding("http://hl7.org/fhir/v3/ObservationValue", "SUBSETTED")
                        };
                        break;
                    }
                }

                if (ResourceName == "Binary")
                {
                    // We need to reset the accepts type so that the correct formatter is used on the way out.
                    string formatParam = this.Request.GetParameter("_format");
                    if (string.IsNullOrEmpty(formatParam))
                    {
                        this.Request.GetTypedHeaders().Accept.Clear();
                        this.Request.GetTypedHeaders().Accept.Add(new MediaTypeHeaderValue((resource as Binary).ContentType));
                    }
                }

                return(new ObjectResult(resource));
            }

            // this request is a "you wanted what?"
            return(new NotFoundResult());
        }
Пример #9
0
 public bool TryGetResource(String url, out DomainResource resource)
 {
     return(this.resources.TryGetValue(url, out resource));
 }
Пример #10
0
        public HttpResponseMessage Get(string ResourceName, string id, string vid)
        {
            try
            {
                var buri = this.CalculateBaseURI("{ResourceName}");

                if (!Id.IsValidValue(id))
                {
                    throw new FhirServerException(HttpStatusCode.BadRequest, "ID [" + id + "] is not a valid FHIR Resource ID");
                }

                var Inputs = GetInputs(buri);
                IFhirResourceServiceSTU3  model   = GetResourceModel(ResourceName, Inputs);
                Hl7.Fhir.Rest.SummaryType summary = GetSummaryParameter(Request);

                Resource resource = model.Get(id, vid, summary);
                if (resource != null)
                {
                    var baseResource = new Hl7.Fhir.Rest.ResourceIdentity(Request.RequestUri);
                    resource.ResourceBase = new Uri(string.Format("http://{0}", baseResource.Authority));

                    if (resource is DomainResource)
                    {
                        DomainResource dr = resource as DomainResource;
                        switch (summary)
                        {
                        case Hl7.Fhir.Rest.SummaryType.False:
                            break;

                        case Hl7.Fhir.Rest.SummaryType.True:
                            // summary doesn't have the text in it.
                            dr.Text = null;
                            // there are no contained references in the summary form
                            dr.Contained = null;

                            // Add in the Meta Tag that indicates that this resource is only a partial
                            resource.Meta.Tag = new List <Coding>
                            {
                                new Coding("http://hl7.org/fhir/v3/ObservationValue", "SUBSETTED")
                            };
                            break;

                        case Hl7.Fhir.Rest.SummaryType.Text:
                            // what do we need to filter here
                            break;

                        case Hl7.Fhir.Rest.SummaryType.Data:
                            // summary doesn't have the text in it.
                            dr.Text = null;
                            // Add in the Meta Tag that indicates that this resource is only a partial
                            resource.Meta.Tag = new List <Coding>
                            {
                                new Coding("http://hl7.org/fhir/v3/ObservationValue", "SUBSETTED")
                            };
                            break;
                        }
                    }

                    if (ResourceName == "Binary")
                    {
                        // We need to reset the accepts type so that the correct formatter is used on the way out.
                        string formatParam = this.ControllerContext.Request.GetParameter("_format");
                        if (string.IsNullOrEmpty(formatParam))
                        {
                            this.ControllerContext.Request.Headers.Accept.Clear();
                            this.ControllerContext.Request.Headers.Accept.Add(new MediaTypeWithQualityHeaderValue((resource as Binary).ContentType));
                        }
                    }

                    var msg = Request.ResourceResponse(resource, HttpStatusCode.OK);
                    msg.Headers.Location = resource.ResourceIdentity().WithBase(resource.ResourceBase);
                    msg.Headers.Add("ETag", String.Format("\"{0}\"", resource.Meta.VersionId));

                    if (ResourceName == "Binary")
                    {
                        // We need to reset the accepts type so that the correct formatter is used on the way out.
                        string formatParam = this.ControllerContext.Request.GetParameter("_format");
                        if (string.IsNullOrEmpty(formatParam))
                        {
                            msg.Content.Headers.ContentDisposition = new ContentDispositionHeaderValue("attachment")
                            {
                                FileName = String.Format("fhir_binary_{0}_{1}.{2}",
                                                         resource.Id,
                                                         resource.Meta != null ? resource.Meta.VersionId : "0",
                                                         GetFileExtensionForMimeType((resource as Binary).ContentType))
                            };
                        }
                    }

                    return(msg);
                }

                // this request is a "you wanted what?"
                return(Request.CreateResponse(HttpStatusCode.NotFound));
            }
            catch (Exception ex)
            {
                System.Diagnostics.Trace.WriteLine(ex.Message);
                return(null);
            }
        }
Пример #11
0
 public async Task <Permission> Find(User user, DomainResource resource)
 => await _dbContext.Permissions
 .SingleOrDefaultAsync(p => p.User == user && p.Resource == resource);
Пример #12
0
        public void AddFragment(String path)
        {
            DomainResource domainResource = this.Load(path);

            AddFragment(domainResource.GetUrl(), domainResource);
        }
Пример #13
0
        /// <summary>
        /// Note: This modifies the resource in b.
        /// </summary>
        void SplitExampleBundle(Bundle b, String prefix)
        {
            Dictionary <String, DomainResource> entryDict = new Dictionary <string, DomainResource>();

            void Write(Bundle.EntryComponent entry)
            {
                DomainResource dr      = (DomainResource)entry.Resource;
                String         profile = dr?.Meta?.Profile?.FirstOrDefault();

                if (profile == null)
                {
                    return;
                }
                if (profile.StartsWith("http://hl7.org/fhir/us/breast-radiology/") == false)
                {
                    return;
                }

                List <String> containNames = new List <string>();

                dr = this.SetReferencesContained(entryDict, containNames, dr);

                // If there are contained resource to add, parse this into a domain resource
                // add the contained resources and write it out again.
                if (containNames.Count > 0)
                {
                    foreach (String containName in containNames)
                    {
                        if (entryDict.TryGetValue(containName,
                                                  out DomainResource containedResource) == false)
                        {
                            throw new Exception($"Can not find bundle entry {containName}");
                        }
                        containedResource = this.SetReferencesContained(entryDict,
                                                                        containNames,
                                                                        containedResource);
                        dr.Contained.Add(containedResource);
                    }
                }

                String json = dr.ToFormatedJson();
                String path = this.ExamplePath(prefix, dr);

                File.WriteAllText(path, json);
            }

            foreach (Bundle.EntryComponent entry in b.Entry)
            {
                DomainResource dr = (DomainResource)entry.Resource;

                // make a copy so we dont change the original id.
                String         json   = dr.ToFormatedJson();
                FhirJsonParser parser = new FhirJsonParser();
                dr = parser.Parse <DomainResource>(json);

                dr.Id = $"{dr.TypeName}.{dr.Id}";
                entryDict.Add(entry.FullUrl, dr);
            }

            foreach (Bundle.EntryComponent entry in b.Entry)
            {
                Write(entry);
            }
        }