public async Task <List <CholesterolRecord> > FetchCholesterol(string id) { //Create search parameters var q = new SearchParams().Where("patient=" + id).Where("code=2093-3").OrderBy("-date"); //Set number of results per page to 1 q.Count = 1; //Search result using parameters above Bundle result = await _client.SearchAsync <Observation>(q); var cholesterolRecords = new List <CholesterolRecord>(); if (result.Total > 0) { Bundle.EntryComponent e = (Bundle.EntryComponent)result.Entry[0]; Observation o = (Observation)e.Resource; var record = new CholesterolRecord() { CholesterolValue = ((Quantity)o.Value).Value.ToString(), Date = DateTime.Parse(o.Issued.ToFhirDateTime()).ToString("dd/MM/yyyy HH:mm") }; cholesterolRecords.Add(record); } else { cholesterolRecords.Add(new CholesterolRecord() { CholesterolValue = "0", Date = "" }); } return(cholesterolRecords); }
public RecordModel GetCholesterolRecordById(string id) { InitializeClient(); var q = new SearchParams().Where("patient=" + id).Where("code=2093-3").OrderBy("-date"); Bundle result = _client.Search <Observation>(q); if (result.Total > 0) { Bundle.EntryComponent e = (Bundle.EntryComponent)result.Entry[0]; Observation o = (Observation)e.Resource; var date = o.Issued.ToFhirDateTime(); Quantity quantity = (Quantity)o.Value; var weight = quantity.Value.ToString(); return(new RecordModel() { Name = RecordType.Cholesterol, Value = weight, Date = date }); } return(new RecordModel() { Name = RecordType.Cholesterol, Value = 0.ToString() }); }
public override Composite Convert(Bundle.EntryComponent entry, int resourceIndex) { // create the resource root using the type of the resource and iteration of the resource var resourceRoot = new Composite(MappedTermsDictionary[entry.Resource.TypeName] + $":{resourceIndex}"); resourceRoot = Helpers.ReflectionHelper.GetObjectComposite(entry.Resource, resourceRoot, MappedTermsDictionary, SkipNodeNames); // prune nodes var matchingNodes = resourceRoot.All(new List <Component>()).Where(x => x.GetType() == typeof(Leaf) && NodePruneList.Any(t => x.PathToRoot.Contains(t))).ToList(); foreach (var node in matchingNodes) { // get the parent node of the node at the start of the path var currentNode = node.Parent; // calculate how many nodes we need to traverse backwards var iterationCount = NodePruneList.OrderByDescending(x => x.Length) .First(t => node.PathToRoot.Contains(t))?.Split('/').Length; // traverse nodes to get to the sub root, removing the old ones as we go for (var i = 0; i < iterationCount; i++) { var oldNode = currentNode; currentNode = currentNode.Parent; currentNode.Remove(oldNode); } // add the leaf from the end of the path to the start of the path resourceRoot.FindById(currentNode.Id).Add(new Leaf(node.Name)); } // done, return resource root return(resourceRoot); }
public async void GivenTwoEntriesAndNoContinuationToken_ReadOneFromBundleWithContinuationAsync_ThenThrows_Test() { var bundle = new Bundle(); bundle.Entry = new List <Bundle.EntryComponent>(); bundle.Link = new List <Bundle.LinkComponent>(); var observation1 = new Observation(); var entry1 = new Bundle.EntryComponent(); entry1.Resource = observation1; bundle.Entry.Add(entry1); var observation2 = new Observation(); var entry2 = new Bundle.EntryComponent(); entry2.Resource = observation2; bundle.Entry.Add(entry2); var client = Substitute.For <IFhirClient>(); client.ContinueAsync(Arg.Any <Bundle>()).Returns(System.Threading.Tasks.Task.FromResult <Bundle>(null)); await Assert.ThrowsAsync <MultipleResourceFoundException <Observation> >(() => bundle.ReadOneFromBundleWithContinuationAsync <Observation>(client)); }
public async void GivenTwoEntriesAndNoContinuationToken_ReadOneFromBundleWithContinuationAsync_ThenThrows_Test() { var bundle = new Bundle { Entry = new List <Bundle.EntryComponent>(), Link = new List <Bundle.LinkComponent>(), }; var observation1 = new Observation(); var entry1 = new Bundle.EntryComponent { Resource = observation1, }; bundle.Entry.Add(entry1); var observation2 = new Observation(); var entry2 = new Bundle.EntryComponent { Resource = observation2, }; bundle.Entry.Add(entry2); var client = Utilities.CreateMockFhirService(); await Assert.ThrowsAsync <MultipleResourceFoundException <Observation> >(() => bundle.ReadOneFromBundleWithContinuationAsync <Observation>(client)); }
public async void GivenOneEntryAndNoContinuationToken_ReadOneFromBundleWithContinuationAsync_ThenResourceIsReturned_Test() { var bundle = new Bundle { Entry = new List <Bundle.EntryComponent>(), Link = new List <Bundle.LinkComponent>(), }; var observation = new Observation { Id = Guid.NewGuid().ToString(), }; var entry = new Bundle.EntryComponent { Resource = observation, }; bundle.Entry.Add(entry); var client = Utilities.CreateMockFhirService(); var result = await bundle.ReadOneFromBundleWithContinuationAsync <Observation>(client); Assert.NotNull(result); Assert.Equal(observation.ToJson(), result.ToJson()); }
public static Bundle Append(this Bundle bundle, IEnumerable<ResourceData> resourcesData) { if (!resourcesData.IsCollectionValid() && Bundle.BundleType.Searchset == bundle.Type) { Bundle.EntryComponent bundleEntry = new Bundle.EntryComponent(); OperationOutcome outcome = new OperationOutcome(); CodeableConcept codeableConcept = new CodeableConcept(); codeableConcept.Text = "There is no matching record found for the given criteria"; outcome.AddWarning(string.Format("Not Found"), OperationOutcome.IssueType.NotFound, codeableConcept); bundleEntry.Resource = outcome; bundleEntry.Resource.Id = "warning"; bundleEntry.Search = new Bundle.SearchComponent() { Mode = Bundle.SearchEntryMode.Outcome }; bundle.Entry.Add(bundleEntry); return bundle; } foreach (ResourceData resourceData in resourcesData) { bundle.Append(resourceData); } return bundle; }
public static Bundle.EntryComponent TranslateToSparseEntry(this ResourceData resourceData, FhirResponse response = null) { var bundleEntry = new Bundle.EntryComponent(); if (response != null) { bundleEntry.Response = new Bundle.ResponseComponent() { Status = string.Format("{0} {1}", (int)response.StatusCode, response.StatusCode), Location = response.Key != null ? response.Key.ToString() : null, Etag = response.Key != null ? ETagExtension.Create(response.Key.VersionId).ToString() : null, LastModified = (resourceData != null && resourceData.Resource != null && resourceData.Resource.Meta != null) ? resourceData.Resource.Meta.LastUpdated : null }; } SetBundleEntryResource(resourceData, bundleEntry); return bundleEntry; }
/// <summary> /// Deserialize JSON into a FHIR Bundle#Entry /// </summary> public static void DeserializeJson(this Bundle.EntryComponent 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.EntryComponent >>> Bundle#Entry.{propertyName}, depth: {reader.CurrentDepth}, pos: {reader.BytesConsumed}"); } reader.Read(); current.DeserializeJsonProperty(ref reader, options, propertyName); } } throw new JsonException($"Bundle.EntryComponent: invalid state! depth: {reader.CurrentDepth}, pos: {reader.BytesConsumed}"); }
public PatientModel GetPatientDetails(PatientModel patient) { var patientId = patient.Id; var q = new SearchParams().Where("_id=" + patientId); Bundle result = _client.Search <Patient>(q); if (result.Total > 0) { Bundle.EntryComponent e = (Bundle.EntryComponent)result.Entry[0]; Patient p = (Patient)e.Resource; var birthdate = p.BirthDate; var gender = p.Gender; var listAdr = p.Address; var adr = listAdr[0]; var address = ((adr.Line).ToList())[0]; var city = adr.City; var state = adr.State; var country = adr.Country; patient.Birthdate = birthdate; patient.Gender = gender; patient.Address = address; patient.City = city; patient.State = state; patient.Country = country; return(patient); } return(patient); }
public static Bundle.EntryComponent TranslateToSparseEntry(this Entry entry) { var bundleEntry = new Bundle.EntryComponent(); SetBundleEntryResource(entry, bundleEntry); return(bundleEntry); }
public static Bundle.EntryComponent TranslateToSparseEntry(this Interaction interaction) { var entry = new Bundle.EntryComponent(); ConnectResource(interaction, entry); return(entry); }
public static Key ExtractKey(this Localhost localhost, Bundle.EntryComponent entry) { Uri uri = new Uri(entry.Request.Url, UriKind.RelativeOrAbsolute); Key compare = ExtractKey(uri); // This fails!! ResourceIdentity does not work in this case. return(localhost.LocalUriToKey(uri)); }
public static Uri ReadSearchUri(Bundle.EntryComponent entry) { if (string.IsNullOrEmpty(entry.Request.IfNoneExist) == false) { return(new Uri(string.Format("{0}?{1}", entry.TypeName, entry.Request.IfNoneExist), UriKind.Relative)); } return(null); }
private static void ConnectResource(Interaction interaction, Bundle.EntryComponent entry) { if (interaction.HasResource()) { entry.Resource = interaction.Resource; interaction.Key.ApplyTo(entry.Resource); entry.FullUrl = interaction.Key.ToUriString(); } }
public static ResourceManipulationOperation GetManipulationOperation(Bundle.EntryComponent entryComponent, ILocalhost localhost, ISearchService service = null) { searchService = service; Bundle.HTTPVerb method = localhost.ExtrapolateMethod(entryComponent, null); //CCR: is key needed? Isn't method required? Key key = localhost.ExtractKey(entryComponent); var searchUri = GetSearchUri(entryComponent, method); return(builders[method](entryComponent.Resource, key, service, searchUri != null? ParseQueryString(localhost, searchUri): null)); }
private static void SetBundleEntryResource(Entry entry, Bundle.EntryComponent bundleEntry) { if (entry.HasResource()) { bundleEntry.Resource = entry.Resource; entry.Key.ApplyTo(bundleEntry.Resource); bundleEntry.FullUrl = entry.Key.ToUriString(); } }
private static Bundle.EntryComponent CreateEntryForResource(Resource resource) { var entry = new Bundle.EntryComponent(); entry.Resource = resource; // entry.FullUrl = resource.ResourceIdentity().ToString(); entry.FullUrl = resource.ExtractKey().ToUriString(); return(entry); }
private static void SetBundleEntryResource(this ResourceData resourceData, Bundle.EntryComponent bundleEntry) { if (resourceData.Resource.IsNotNull()) { bundleEntry.Resource = resourceData.Resource; //resourceData.Key.ApplyTo(bundleEntry.Resource); //bundleEntry.FullUrl = resourceData.fHIRParam.ToUriString(); } }
private Bundle.EntryComponent newEntry(Bundle.HTTPVerb method) { var newEntry = new Bundle.EntryComponent(); newEntry.Request = new Bundle.RequestComponent(); newEntry.Request.Method = method; return(newEntry); }
private bool GetProcessing(Bundle.EntryComponent GetEntry, int GetEntryIndex) { IRequestMeta RequestMeta = IRequestMetaFactory.CreateRequestMeta(); RequestMeta.Set(GetEntry.Request); RequestMeta.RequestHeader.Prefer = _RequestHeader.Prefer; IResourceServiceOutcome ResourceServiceOutcome = null; if (RequestMeta.SearchParameterGeneric.ParameterList.Count > 0) { ResourceServiceOutcome = IResourceServices.GetSearch(RequestMeta); } else { ResourceServiceOutcome = IResourceServices.GetRead(RequestMeta.PyroRequestUri.FhirRequestUri.ResourceId, RequestMeta); } if (ResourceServiceOutcome.SuccessfulTransaction) { GetEntry.FullUrl = CreateFullUrl(ResourceServiceOutcome); GetEntry.Response = new Bundle.ResponseComponent(); GetEntry.Response.Status = FormatHTTPStatusCodeAsString(ResourceServiceOutcome.HttpStatusCode); if (ResourceServiceOutcome.ResourceResult != null) { if (ResourceServiceOutcome.ResourceResult.ResourceType == ResourceType.OperationOutcome) { GetEntry.Response.Outcome = ResourceServiceOutcome.ResourceResult; } else { GetEntry.Resource = ResourceServiceOutcome.ResourceResult; } } if (ResourceServiceOutcome.LastModified.HasValue) { GetEntry.Response.Etag = HttpHeaderSupport.GetEntityTagHeaderValueFromVersion(ResourceServiceOutcome.ResourceVersionNumber).ToString(); if (ResourceServiceOutcome.IsDeleted.HasValue && !ResourceServiceOutcome.IsDeleted.Value) { GetEntry.Response.LastModified = ResourceServiceOutcome.LastModified; } GetEntry.Response.Location = FormatResponseLocation(RequestMeta.PyroRequestUri.FhirRequestUri.OriginalString, ResourceServiceOutcome.FhirResourceId, ResourceServiceOutcome.ResourceVersionNumber); } return(true); } else { if (ResourceServiceOutcome.ResourceResult != null && ResourceServiceOutcome.ResourceResult is OperationOutcome Op) { IdentifieBatchEntityToClient(Op, GetEntry.FullUrl, "GET", GetEntryIndex); } _ServiceOperationOutcome = ResourceServiceOutcome; return(false); } }
private Bundle.EntryComponent newEntry(Bundle.HTTPVerb method, InteractionType interactionType) { var newEntry = new Bundle.EntryComponent(); newEntry.Request = new Bundle.RequestComponent(); newEntry.Request.Method = method; newEntry.AddAnnotation(interactionType); return(newEntry); }
public static void Append(this Bundle bundle, Bundle.HTTPVerb method, Resource resource) { Bundle.EntryComponent entry = CreateEntryForResource(resource); if (entry.Request == null) { entry.Request = new Bundle.RequestComponent(); } entry.Request.Method = method; bundle.Entry.Add(entry); }
internal static Bundle.EntryComponent ToBundleEntry(this HttpWebResponse response, byte[] body, ParserSettings parserSettings, bool throwOnFormatException) { var result = new Bundle.EntryComponent(); result.Response = new Bundle.ResponseComponent(); result.Response.Status = ((int)response.StatusCode).ToString(); result.Response.SetHeaders(response.Headers); var contentType = getContentType(response); var charEncoding = getCharacterEncoding(response); result.Response.Location = response.Headers[HttpUtil.LOCATION] ?? response.Headers[HttpUtil.CONTENTLOCATION]; #if !DOTNETFW if (!String.IsNullOrEmpty(response.Headers[HttpUtil.LASTMODIFIED])) { result.Response.LastModified = DateTimeOffset.Parse(response.Headers[HttpUtil.LASTMODIFIED]); } #else result.Response.LastModified = response.LastModified; #endif result.Response.Etag = getETag(response); if (body != null) { result.Response.SetBody(body); if (IsBinaryResponse(response.ResponseUri.OriginalString, contentType)) { result.Resource = makeBinaryResource(body, contentType); if (result.Response.Location != null) { var ri = new ResourceIdentity(result.Response.Location); result.Resource.Id = ri.Id; result.Resource.Meta = new Meta(); result.Resource.Meta.VersionId = ri.VersionId; result.Resource.ResourceBase = ri.BaseUri; } } else { var bodyText = DecodeBody(body, charEncoding); var resource = parseResource(bodyText, contentType, parserSettings, throwOnFormatException); result.Resource = resource; if (result.Response.Location != null) { result.Resource.ResourceBase = new ResourceIdentity(result.Response.Location).BaseUri; } } } return(result); }
public void Create(Resource r) { var newEntry = new Bundle.EntryComponent(); newEntry.Request = new Bundle.RequestComponent(); newEntry.Request.Method = Bundle.HTTPVerb.POST; newEntry.Resource = r; newEntry.Request.Url = new RestUrl(BaseUrl).AddPath(r.TypeName).ToString(); newEntry.FullUrl = r.Id.ToString(); _bundle.Entry.Add(newEntry); }
private static Uri GetSearchUri(Bundle.EntryComponent entryComponent, Bundle.HTTPVerb method) { var searchUri = method switch { Bundle.HTTPVerb.POST => PostManipulationOperation.ReadSearchUri(entryComponent), Bundle.HTTPVerb.PUT => PutManipulationOperation.ReadSearchUri(entryComponent), Bundle.HTTPVerb.DELETE => DeleteManipulationOperation.ReadSearchUri(entryComponent), _ => null }; return(searchUri); }
private static Bundle.EntryComponent CreateEntryForResource(Resource resource) { var entry = new Bundle.EntryComponent { Resource = resource, FullUrl = resource.ResourceBase == null ? $"urn:uuid:{Guid.NewGuid().ToString("D")}" : resource.ExtractKey().ToUriString() }; return(entry); }
/// <summary> /// Add resource to the bundle and to the resource dictionary. /// </summary> /// <param name="fullUrl"></param> /// <param name="resource"></param> public void AddResource(DomainResource resource) { if (String.IsNullOrEmpty(resource.Id) == true) { resource.Id = $"{Guid.NewGuid().ToString()}"; } if (this.resources.ContainsKey(resource.Id) == false) { Bundle.EntryComponent entry = this.Bundle.AddResourceEntry(resource, resource.Id); this.resources.Add(resource.Id, entry); } }
public void LoadEntry(Bundle.EntryComponent Entry) { this.FullUrl = Entry.FullUrl; this.FullUrlUUID = GetUUIDfromFullURL(Entry.FullUrl); this.FhirId = Tools.FhirGuid.FhirGuid.NewFhirGuid(); this.ResourceName = Entry.Resource.ResourceType.GetLiteral(); this.ResourceReference = $"{this.ResourceName}/{this.FhirId}"; this.Entry = Entry; if (Entry.Request != null && !string.IsNullOrWhiteSpace(Entry.Request.IfNoneExist)) { this.IfNoneExistEntryRequestProperty = Entry.Request.IfNoneExist; } }
private async Task <Bundle.EntryComponent> ProcessEntity(Bundle.EntryComponent entry) { // ReSharper disable once SwitchStatementMissingSomeCases switch (entry.Request.Method) { case Bundle.HTTPVerb.GET: return(new Bundle.EntryComponent { // TODO: Check if this works on API level Resource = await this.Repository.ReadResourceAsync(entry.Request.ElementId), Response = new Bundle.ResponseComponent { Status = HttpStatusCode.OK.ToString() } }); case Bundle.HTTPVerb.POST: return(new Bundle.EntryComponent { Resource = await this.Repository.CreateResourceAsync(entry.Resource), Response = new Bundle.ResponseComponent { Status = HttpStatusCode.Created.ToString() } }); case Bundle.HTTPVerb.PUT: return(new Bundle.EntryComponent { Resource = await this.Repository.UpdateResourceAsync(entry.Resource), Response = new Bundle.ResponseComponent { Status = HttpStatusCode.OK.ToString() } }); case Bundle.HTTPVerb.DELETE: await this.Repository.DeleteResourceAsync(entry.Request.ElementId); return(new Bundle.EntryComponent { Resource = entry.Resource, Response = new Bundle.ResponseComponent { Status = HttpStatusCode.OK.ToString() } }); default: throw new UnsupportedOperationException(entry.Request.Method.ToString()); } }