/// <summary> /// Deserialize JSON into a FHIR Bundle#Search /// </summary> public static void DeserializeJson(this Bundle.SearchComponent current, ref Utf8JsonReader reader, JsonSerializerOptions options) { string propertyName; while (reader.Read()) { if (reader.TokenType == JsonTokenType.EndObject) { return; } if (reader.TokenType == JsonTokenType.PropertyName) { propertyName = reader.GetString(); if (Hl7.Fhir.Serialization.FhirSerializerOptions.Debug) { Console.WriteLine($"Bundle.SearchComponent >>> Bundle#Search.{propertyName}, depth: {reader.CurrentDepth}, pos: {reader.BytesConsumed}"); } reader.Read(); current.DeserializeJsonProperty(ref reader, options, propertyName); } } throw new JsonException($"Bundle.SearchComponent: invalid state! depth: {reader.CurrentDepth}, pos: {reader.BytesConsumed}"); }
/// <summary> /// Deserialize JSON into a FHIR Bundle#Search /// </summary> public static void DeserializeJsonProperty(this Bundle.SearchComponent current, ref Utf8JsonReader reader, JsonSerializerOptions options, string propertyName) { switch (propertyName) { case "mode": if (reader.TokenType == JsonTokenType.Null) { current.ModeElement = new Code <Hl7.Fhir.Model.Bundle.SearchEntryMode>(); reader.Skip(); } else { current.ModeElement = new Code <Hl7.Fhir.Model.Bundle.SearchEntryMode>(Hl7.Fhir.Utility.EnumUtility.ParseLiteral <Hl7.Fhir.Model.Bundle.SearchEntryMode>(reader.GetString())); } break; case "_mode": if (current.ModeElement == null) { current.ModeElement = new Code <Hl7.Fhir.Model.Bundle.SearchEntryMode>(); } ((Hl7.Fhir.Model.Element)current.ModeElement).DeserializeJson(ref reader, options); break; case "score": if (reader.TokenType == JsonTokenType.Null) { current.ScoreElement = new FhirDecimal(); reader.Skip(); } else { current.ScoreElement = new FhirDecimal(reader.GetDecimal()); } break; case "_score": if (current.ScoreElement == null) { current.ScoreElement = new FhirDecimal(); } ((Hl7.Fhir.Model.Element)current.ScoreElement).DeserializeJson(ref reader, options); break; // Complex: search, Export: SearchComponent, Base: BackboneElement default: ((Hl7.Fhir.Model.BackboneElement)current).DeserializeJsonProperty(ref reader, options, propertyName); break; } }
//TODO: test this public Bundle ToBundle <T>(FhirRequest request, List <T> resources, Guid?bundleId) where T : Resource { var meta = new Meta(); meta.LastUpdated = DateTime.UtcNow; var selfLink = new Bundle.LinkComponent(); selfLink.Relation = "_self"; selfLink.Url = request.RequestUrl.AbsoluteUri; var links = new List <Bundle.LinkComponent>(); links.Add(selfLink); var entryResources = request.IsSummary ? new List <T>() : resources; var entries = new List <Bundle.EntryComponent>(); entryResources.ForEach((r) => { var urlPort = new int[] { 80, 443 }.Contains(request.RequestUrl.Port) ? "" : ":" + request.RequestUrl.Port; var search = new Bundle.SearchComponent(); search.Mode = Bundle.SearchEntryMode.Match; var entry = new Bundle.EntryComponent(); entry.Search = search; entry.FullUrl = $"{request.RequestUrl.Scheme}://{request.RequestUrl.Host}{urlPort}/nrls-ri/{request.ResourceType}/{r.Id}"; entry.Resource = r; entries.Add(entry); }); var bundle = new Bundle(); bundle.Id = $"{(bundleId.HasValue ? bundleId.Value : Guid.NewGuid())}"; bundle.Meta = meta; bundle.Type = Bundle.BundleType.Searchset; bundle.Total = resources.Count; bundle.Link = links; bundle.Entry = entries; return(bundle); }
/// <summary> /// Serialize a FHIR Bundle#Search into JSON /// </summary> public static void SerializeJson(this Bundle.SearchComponent current, Utf8JsonWriter writer, JsonSerializerOptions options, bool includeStartObject = true) { if (includeStartObject) { writer.WriteStartObject(); } // Component: Bundle#Search, Export: SearchComponent, Base: BackboneElement (BackboneElement) ((Hl7.Fhir.Model.BackboneElement)current).SerializeJson(writer, options, false); if (current.ModeElement != null) { if (current.ModeElement.Value != null) { writer.WriteString("mode", Hl7.Fhir.Utility.EnumUtility.GetLiteral(current.ModeElement.Value)); } if (current.ModeElement.HasExtensions() || (!string.IsNullOrEmpty(current.ModeElement.ElementId))) { JsonStreamUtilities.SerializeExtensionList(writer, options, "_mode", false, current.ModeElement.Extension, current.ModeElement.ElementId); } } if (current.ScoreElement != null) { if (current.ScoreElement.Value != null) { writer.WriteNumber("score", (decimal)current.ScoreElement.Value); } if (current.ScoreElement.HasExtensions() || (!string.IsNullOrEmpty(current.ScoreElement.ElementId))) { JsonStreamUtilities.SerializeExtensionList(writer, options, "_score", false, current.ScoreElement.Extension, current.ScoreElement.ElementId); } } if (includeStartObject) { writer.WriteEndObject(); } }
public async Task <HttpResponseMessage> Get(string resource) { string respval; if (Request.RequestUri.AbsolutePath.ToLower().EndsWith("metadata")) { respval = SerializeResponse(FhirHelper.GenerateCapabilityStatement(Request.RequestUri.AbsoluteUri)); } else { var nvc = HttpUtility.ParseQueryString(Request.RequestUri.Query); var id = nvc["_id"]; var nextpage = nvc["_nextpage"]; var count = nvc["_count"] ?? "100"; var querytotal = nvc["_querytotal"] ?? "-1"; IEnumerable <Resource> retVal; ResourceQueryResult searchrslt = null; int iqueryTotal; if (string.IsNullOrEmpty(id)) { var query = FhirParmMapper.Instance.GenerateQuery(storage, resource, nvc); searchrslt = await storage.QueryFhirResourceAsync(query, resource, int.Parse(count), nextpage, long.Parse(querytotal)). ConfigureAwait(false); retVal = searchrslt.Resources; iqueryTotal = (int)searchrslt.Total; } else { retVal = new List <Resource>(); var r = await storage.LoadFhirResourceAsync(id, resource).ConfigureAwait(false); if (r != null) { ((List <Resource>)retVal).Add(r); } iqueryTotal = retVal.Count(); } var baseurl = Request.RequestUri.Scheme + "://" + Request.RequestUri.Authority + "/" + resource; var results = new Bundle { Id = Guid.NewGuid().ToString(), Type = Bundle.BundleType.Searchset, Total = iqueryTotal, Link = new List <Bundle.LinkComponent>() }; var qscoll = Request.RequestUri.ParseQueryString(); qscoll.Remove("_count"); qscoll.Remove("_querytotal"); qscoll.Add("_querytotal", searchrslt.Total.ToString()); qscoll.Add("_count", count); results.Link.Add(new Bundle.LinkComponent { Url = baseurl + "?" + qscoll, Relation = "self" }); if (searchrslt.ContinuationToken != null) { qscoll.Remove("_nextpage"); qscoll.Add("_nextpage", searchrslt.ContinuationToken); results.Link.Add(new Bundle.LinkComponent { Url = baseurl + "?" + qscoll, Relation = "next" }); } results.Entry = new List <Bundle.EntryComponent>(); var match = new Bundle.SearchComponent { Mode = Bundle.SearchEntryMode.Match }; var include = new Bundle.SearchComponent { Mode = Bundle.SearchEntryMode.Include }; foreach (var p in retVal) { results.Entry.Add(new Bundle.EntryComponent { Resource = p, FullUrl = FhirHelper.GetFullUrl(Request, p), Search = match }); var includes = await FhirHelper.ProcessIncludesAsync(p, nvc, storage).ConfigureAwait(false); foreach (var r in includes) { results.Entry.Add(new Bundle.EntryComponent { Resource = r, FullUrl = FhirHelper.GetFullUrl(Request, r), Search = include }); } } respval = SerializeResponse(results); } var response = Request.CreateResponse(HttpStatusCode.OK); response.Headers.TryAddWithoutValidation("Accept", CurrentAcceptType); response.Content = new StringContent(respval, Encoding.UTF8); response.Content.Headers.TryAddWithoutValidation("Content-Type", IsAccceptTypeJson ? Fhircontenttypejson : Fhircontenttypexml); return(response); }
public async Task <HttpResponseMessage> Get(string resource) { try { string respval = null; if (Request.RequestUri.AbsolutePath.ToLower().EndsWith("metadata")) { respval = SerializeResponse(FhirHelper.GenerateCapabilityStatement(Request.RequestUri.AbsoluteUri)); } else { string validResource = FhirHelper.ValidateResourceType(resource); NameValueCollection nvc = HttpUtility.ParseQueryString(Request.RequestUri.Query); string _id = nvc["_id"]; string _nextpage = nvc["_nextpage"]; string _count = nvc["_count"]; if (_count == null) { _count = "100"; } string _querytotal = nvc["_querytotal"]; if (_querytotal == null) { _querytotal = "-1"; } IEnumerable <Resource> retVal = null; ResourceQueryResult searchrslt = null; int iqueryTotal = 0; if (string.IsNullOrEmpty(_id)) { string query = FhirParmMapper.Instance.GenerateQuery(storage, validResource, nvc); searchrslt = await storage.QueryFHIRResource(query, validResource, int.Parse(_count), _nextpage, long.Parse(_querytotal)); retVal = searchrslt.Resources; iqueryTotal = (int)searchrslt.Total; } else { retVal = new List <Resource>(); var r = await storage.LoadFHIRResource(_id, validResource); if (r != null) { ((List <Resource>)retVal).Add(r); } iqueryTotal = retVal.Count(); } var baseurl = Request.RequestUri.Scheme + "://" + Request.RequestUri.Authority + "/" + validResource; Bundle results = new Bundle(); results.Id = Guid.NewGuid().ToString(); results.Type = Bundle.BundleType.Searchset; results.Total = iqueryTotal; results.Link = new System.Collections.Generic.List <Bundle.LinkComponent>(); NameValueCollection qscoll = Request.RequestUri.ParseQueryString(); qscoll.Remove("_count"); qscoll.Remove("_querytotal"); qscoll.Add("_querytotal", searchrslt.Total.ToString()); qscoll.Add("_count", _count); results.Link.Add(new Bundle.LinkComponent() { Url = baseurl + "?" + qscoll.ToString(), Relation = "self" }); if (searchrslt.ContinuationToken != null) { qscoll.Remove("_nextpage"); qscoll.Add("_nextpage", searchrslt.ContinuationToken); results.Link.Add(new Bundle.LinkComponent() { Url = baseurl + "?" + qscoll.ToString(), Relation = "next" }); } results.Entry = new System.Collections.Generic.List <Bundle.EntryComponent>(); Bundle.SearchComponent match = new Bundle.SearchComponent(); match.Mode = Bundle.SearchEntryMode.Match; Bundle.SearchComponent include = new Bundle.SearchComponent(); include.Mode = Bundle.SearchEntryMode.Include; foreach (Resource p in retVal) { results.Entry.Add(new Bundle.EntryComponent() { Resource = p, FullUrl = FhirHelper.GetFullURL(Request, p), Search = match }); var includes = await FhirHelper.ProcessIncludes(p, nvc, storage); foreach (Resource r in includes) { results.Entry.Add(new Bundle.EntryComponent() { Resource = r, FullUrl = FhirHelper.GetFullURL(Request, r), Search = include }); } } if (retVal != null) { respval = SerializeResponse(results); } } var response = this.Request.CreateResponse(HttpStatusCode.OK); response.Headers.TryAddWithoutValidation("Accept", CurrentAcceptType); response.Content = new StringContent(respval, Encoding.UTF8); response.Content.Headers.TryAddWithoutValidation("Content-Type", IsAccceptTypeJSON ? FHIRCONTENTTYPEJSON : FHIRCONTENTTYPEXML); return(response); } catch (Exception e) { OperationOutcome oo = new OperationOutcome(); oo.Issue = new System.Collections.Generic.List <OperationOutcome.IssueComponent>(); OperationOutcome.IssueComponent ic = new OperationOutcome.IssueComponent(); ic.Severity = OperationOutcome.IssueSeverity.Error; ic.Code = OperationOutcome.IssueType.Exception; ic.Diagnostics = e.Message; oo.Issue.Add(ic); var response = this.Request.CreateResponse(HttpStatusCode.BadRequest); response.Headers.TryAddWithoutValidation("Accept", CurrentAcceptType); response.Content = new StringContent(SerializeResponse(oo), Encoding.UTF8); response.Content.Headers.TryAddWithoutValidation("Content-Type", IsAccceptTypeJSON ? FHIRCONTENTTYPEJSON : FHIRCONTENTTYPEXML); response.Content.Headers.LastModified = DateTimeOffset.Now; return(response); } }