Example #1
0
        /// <summary>
        /// Gets back a resource from a json sample file.
        /// </summary>
        /// <param name="fileName">The JSON filename, omit the extension</param>
        public static Resource GetJsonSample(string fileName)
        {
            var fhirSource = GetJson(fileName);
            var parser     = new Hl7.Fhir.Serialization.FhirJsonParser();

            return(parser.Parse <Resource>(fhirSource));
        }
        public async Task GivenATransactionBundleReferencesInResourceBody_WhenSuccessfulExecution_ReferencesAreResolvedCorrectlyAsync()
        {
            var id = Guid.NewGuid().ToString();

            // Insert a resource that has a predefined identifier.
            var resource = Samples.GetJsonSample <Patient>("PatientWithMinimalData");

            resource.Identifier[0].Value = id;
            await _client.CreateAsync(resource);

            var bundleAsString = Samples.GetJson("Bundle-TransactionWithReferenceInResourceBody");

            bundleAsString = bundleAsString.Replace("http:/example.org/fhir/ids|234234", $"http:/example.org/fhir/ids|{id}");
            var parser = new Hl7.Fhir.Serialization.FhirJsonParser();
            var bundle = parser.Parse <Bundle>(bundleAsString);

            using FhirResponse <Bundle> fhirResponseForReferenceResolution = await _client.PostBundleAsync(bundle);

            Assert.NotNull(fhirResponseForReferenceResolution);
            Assert.Equal(HttpStatusCode.OK, fhirResponseForReferenceResolution.StatusCode);

            foreach (var entry in fhirResponseForReferenceResolution.Resource.Entry)
            {
                IEnumerable <ResourceReference> references = entry.Resource.GetAllChildren <ResourceReference>();

                foreach (var reference in references)
                {
                    // Asserting the conditional reference value after resolution
                    Assert.True(reference.Reference.Contains("/", StringComparison.Ordinal));

                    // Also asserting that the conditional reference is resolved correctly
                    Assert.False(reference.Reference.Contains("?", StringComparison.Ordinal));
                }
            }
        }
Example #3
0
        /// <summary>
        /// Gets back a resource from a definition file.
        /// </summary>
        /// <typeparam name="T">The resource type.</typeparam>
        /// <param name="fileName">The JSON filename, omit the extension</param>
        public static Bundle GetDefinition(string fileName)
        {
            var json = EmbeddedResourceManager.GetStringContent(EmbeddedResourceSubNamespace, fileName, "json");

            var parser = new Hl7.Fhir.Serialization.FhirJsonParser();

            return((Bundle)parser.Parse(json, typeof(Bundle)));
        }
Example #4
0
        /// <summary>
        /// Gets back a resource from a json sample file.
        /// </summary>
        /// <typeparam name="T">The resource type.</typeparam>
        /// <param name="fileName">The JSON filename, omit the extension</param>
        public static T GetJsonSample <T>(string fileName)
        {
            var json = GetJson(fileName);

            if (typeof(Resource).IsAssignableFrom(typeof(T)))
            {
                var parser = new Hl7.Fhir.Serialization.FhirJsonParser();
                return((T)(object)parser.Parse(json, typeof(T)));
            }

            return(JsonConvert.DeserializeObject <T>(json));
        }
Example #5
0
        public static Results ExpandValueSet(string valueset, string filter)
        {
            Results returnValueSet = new Results();

            switch (valueset)
            {
            case "top-2000-lab-observations-us":
                var client = new Hl7.Fhir.Rest.FhirClient(FHIR_EndPoint_LOINC);

                client.OnBeforeRequest += (object msender, BeforeRequestEventArgs mer) =>
                {
                    mer.RawRequest.Headers.Add("Authorization", "Basic " + "YWJoaWppdGd1bGFiOiFJbmRpYW5hMDAx");
                };

                var response = client.ExpandValueSet(ResourceIdentity.Build("ValueSet", valueset), filter: new FhirString(filter));
                var ValueSet = response.Expansion.Contains.Select(vs => new Result {
                    id = vs.Code, text = vs.Display
                });
                returnValueSet.results = ValueSet;
                break;

            case "ucum":
                var clientRest = new RestClient(FHIR_EndPoint_UCUM);
                var request    = new RestRequest("/ValueSet/ucum/$expand", Method.GET);
                request.AddQueryParameter("filter", filter);
                request.AddQueryParameter("_format", "json");
                var responseJson = clientRest.Execute(request).Content;

                //var result = JsonConvert.DeserializeObject<ValueSet>(responseJson);
                var      parser = new Hl7.Fhir.Serialization.FhirJsonParser();
                ValueSet result = parser.Parse <ValueSet>(responseJson);
                ValueSet = result.Expansion.Contains.Select(vs => new Result {
                    id = vs.Code, text = vs.Display
                });
                returnValueSet.results = ValueSet;
                break;

            default:
                returnValueSet.results = new List <Result>();
                break;
            }

            return(returnValueSet);
        }
        public async Task GivenAValidBundleWithForbiddenUser_WhenSubmittingATransaction_ThenOperationOutcomeWithForbiddenStatusIsReturned()
        {
            TestFhirClient tempClient = _client.CreateClientForUser(TestUsers.ReadOnlyUser, TestApplications.NativeClient);

            var id             = Guid.NewGuid().ToString();
            var bundleAsString = Samples.GetJson("Bundle-TransactionWithValidBundleEntry");

            bundleAsString = bundleAsString.Replace("identifier=234234", $"identifier={id}");
            var parser        = new Hl7.Fhir.Serialization.FhirJsonParser();
            var requestBundle = parser.Parse <Bundle>(bundleAsString);

            using var fhirException = await Assert.ThrowsAsync <FhirException>(async () => await tempClient.PostBundleAsync(requestBundle));

            Assert.Equal(HttpStatusCode.Forbidden, fhirException.StatusCode);

            string[]    expectedDiagnostics = { "Transaction failed on 'POST' for the requested url '/Patient'.", "Authorization failed." };
            IssueType[] expectedCodeType    = { OperationOutcome.IssueType.Processing, OperationOutcome.IssueType.Forbidden };
            ValidateOperationOutcome(expectedDiagnostics, expectedCodeType, fhirException.OperationOutcome);
        }
        public async Task GivenAProperBundle_WhenSubmittingATransaction_ThenSuccessIsReturnedWithExpectedStatusCodesPerRequests()
        {
            var id = Guid.NewGuid().ToString();

            // Insert resources first inorder to test a delete.
            var resource = Samples.GetJsonSample <Patient>("PatientWithMinimalData");

            resource.Identifier[0].Value = id;
            using FhirResponse <Patient> response = await _client.CreateAsync(resource);

            var insertedId     = response.Resource.Id;
            var bundleAsString = Samples.GetJson("Bundle-TransactionWithAllValidRoutes");

            bundleAsString = bundleAsString.Replace("http:/example.org/fhir/ids|234234", $"http:/example.org/fhir/ids|{id}");
            bundleAsString = bundleAsString.Replace("234235", Guid.NewGuid().ToString());
            bundleAsString = bundleAsString.Replace("456456", Guid.NewGuid().ToString());

            var parser        = new Hl7.Fhir.Serialization.FhirJsonParser();
            var requestBundle = parser.Parse <Bundle>(bundleAsString);

            requestBundle.Entry.Add(new EntryComponent
            {
                Request = new RequestComponent
                {
                    Method = HTTPVerb.DELETE,
                    Url    = "Patient/" + insertedId,
                },
            });

            using FhirResponse <Bundle> fhirResponse = await _client.PostBundleAsync(requestBundle);

            Assert.NotNull(fhirResponse);
            Assert.Equal(HttpStatusCode.OK, fhirResponse.StatusCode);

            Assert.True("201".Equals(fhirResponse.Resource.Entry[0].Response.Status), "Create");
            Assert.True("201".Equals(fhirResponse.Resource.Entry[1].Response.Status), "Conditional Create");
            Assert.True("201".Equals(fhirResponse.Resource.Entry[2].Response.Status), "Update");
            Assert.True("201".Equals(fhirResponse.Resource.Entry[3].Response.Status), "Conditional Update");
            Assert.True("200".Equals(fhirResponse.Resource.Entry[4].Response.Status), "Get");
            Assert.True("200".Equals(fhirResponse.Resource.Entry[5].Response.Status), "Get");
            Assert.True("204".Equals(fhirResponse.Resource.Entry[6].Response.Status), "Delete");
        }
        protected void ParseResponseBody()
        {
            var     tpXml   = this.Body;
            Patient Patient = null;

            if (this.Format == FhirApi.FhirFormat.Xml)
            {
                var parser = new Hl7.Fhir.Serialization.FhirXmlParser();
                Patient = parser.Parse <Patient>(tpXml);
            }
            else
            {
                var parser = new Hl7.Fhir.Serialization.FhirJsonParser();
                Patient = parser.Parse <Patient>(tpXml);
            }

            IElementNavigator PocoPatient = new PocoNavigator(Patient);

            this.ApiPatient = new ApiPatient(PocoPatient);
        }
        public async Task GivenABundleWithMutipleEntriesReferringToSameResource_WhenSubmittingATransaction_ThenProperOperationOutComeIsReturned()
        {
            var id = Guid.NewGuid().ToString();

            // Insert resources first inorder to test a delete.
            var resource = Samples.GetJsonSample <Patient>("PatientWithMinimalData");

            resource.Identifier[0].Value = id;
            using FhirResponse <Patient> response = await _client.CreateAsync(resource);

            var bundleAsString = Samples.GetJson("Bundle-TransactionWithConditionalReferenceReferringToSameResource");

            bundleAsString = bundleAsString.Replace("http:/example.org/fhir/ids|234234", $"http:/example.org/fhir/ids|{id}");
            var parser = new Hl7.Fhir.Serialization.FhirJsonParser();
            var bundle = parser.Parse <Bundle>(bundleAsString);

            using var fhirException = await Assert.ThrowsAsync <FhirException>(async () => await _client.PostBundleAsync(bundle));

            Assert.Equal(HttpStatusCode.BadRequest, fhirException.StatusCode);

            string[]    expectedDiagnostics = { $"Bundle contains multiple entries that refers to the same resource 'Patient?identifier=http:/example.org/fhir/ids|{id}'." };
            IssueType[] expectedCodeType    = { OperationOutcome.IssueType.Invalid };
            ValidateOperationOutcome(expectedDiagnostics, expectedCodeType, fhirException.OperationOutcome);
        }
Example #10
0
        protected void ParseResponseBody()
        {
            var    tpXml  = this.Body;
            Bundle Bundle = null;

            if (this.Format == FhirApi.FhirFormat.Xml)
            {
                var parser = new Hl7.Fhir.Serialization.FhirXmlParser();
                Bundle = parser.Parse <Bundle>(tpXml);
            }
            else
            {
                var parser = new Hl7.Fhir.Serialization.FhirJsonParser();
                Bundle = parser.Parse <Bundle>(tpXml);
            }

            IElementNavigator PocoBundel = new PocoNavigator(Bundle);

            foreach (var RelatedPerson in PocoBundel.Select(@"Bundle.entry.select(resource as RelatedPerson)"))
            {
                ApiRelatedPerson ApiRelatedPerson = new ApiRelatedPerson(RelatedPerson);
                ApiRelatedPersonList.Add(ApiRelatedPerson);
            }
        }
Example #11
0
        // Process request and craft response.
        public override CefReturnValue ProcessRequestAsync(IRequest request, ICallback callback)
        {
            if (request.Method == "OPTIONS")
            {
                // This is the CORS request, and that's good
                base.StatusCode = 200;
                // base.Headers.Add("Access-Control-Allow-Origin", "*");
                base.Headers.Add("Access-Control-Allow-Methods", "GET,POST,PUT,OPTIONS");
                base.Headers.Add("Access-Control-Allow-Headers", "Content-Type, Accept, authorization");
                callback.Continue();
                return(CefReturnValue.Continue);
            }
            var uri = new Uri(request.Url);

            Console.WriteLine($"-----------------\r\n{request.Url}");

            // Check the bearer header
            if (!string.IsNullOrEmpty(_launchContext.Bearer))
            {
                string bearer = request.GetHeaderByName("authorization");
                if (bearer != "Bearer " + _launchContext.Bearer)
                {
                    base.StatusCode = (int)HttpStatusCode.Unauthorized;
                    callback.Continue();
                    return(CefReturnValue.Continue);
                }
            }

            try
            {
                // This is a regular request
                Hl7.Fhir.Rest.FhirClient server = new Hl7.Fhir.Rest.FhirClient("http://localhost:4178");
                server.OnAfterResponse += (sender, args) =>
                {
                    base.Charset = args.RawResponse.CharacterSet;
                    foreach (string header in args.RawResponse.Headers.AllKeys)
                    {
                        base.Headers.Add(header, args.RawResponse.Headers[header]);
                    }
                };
                server.PreferredFormat = Hl7.Fhir.Rest.ResourceFormat.Json;
                string redirectedUrl = server.Endpoint.OriginalString.TrimEnd('/') + uri.PathAndQuery;
                System.Diagnostics.Trace.WriteLine($"{redirectedUrl}");
                var headers = new List <KeyValuePair <string, IEnumerable <string> > >();
                ModelBaseInputs <IServiceProvider> requestDetails = new ModelBaseInputs <IServiceProvider>(null, null, request.Method, uri, new Uri($"https://{AuthProtocolSchemeHandlerFactory.FhirFacadeAddress(_launchContext)}"), null, headers, null);
                if (request.Method == "GET")
                {
                    if (uri.LocalPath == "/metadata")
                    {
                        _facade.GetConformance(requestDetails, Rest.SummaryType.False).ContinueWith <CapabilityStatement>(r =>
                        {
                            if (r.Exception != null)
                            {
                                System.Diagnostics.Trace.WriteLine($"Error: {r.Exception.Message}");
                                if (r.Exception.InnerException is Hl7.Fhir.Rest.FhirOperationException fe)
                                {
                                    base.StatusCode = (int)fe.Status;
                                    if (fe.Outcome != null)
                                    {
                                        base.Stream = new MemoryStream(new Hl7.Fhir.Serialization.FhirJsonSerializer(new Hl7.Fhir.Serialization.SerializerSettings()
                                        {
                                            Pretty = true
                                        }).SerializeToBytes(fe.Outcome));
                                        base.MimeType = "application/fhir+json";
                                    }
                                    callback.Continue();
                                    System.Diagnostics.Trace.WriteLine($"Error (inner): {fe.Message}");
                                    return(null);
                                }
                            }
                            base.StatusCode = 200;

                            // As per the documentation http://hl7.org/fhir/smart-app-launch/conformance/index.html
                            CapabilityStatement cs = r.Result;

                            // Update the security node with our internal security node
                            if (cs.Rest[0].Security == null)
                            {
                                cs.Rest[0].Security = new Hl7.Fhir.Model.CapabilityStatement.SecurityComponent();
                            }
                            Hl7.Fhir.Model.CapabilityStatement.SecurityComponent security = cs.Rest[0].Security;
                            if (!security.Service.Any(cc => cc.Coding.Any(c => c.System == "http://hl7.org/fhir/restful-security-service" && c.Code == "SMART-on-FHIR")))
                            {
                                security.Service.Add(new Hl7.Fhir.Model.CodeableConcept("http://hl7.org/fhir/restful-security-service", "SMART-on-FHIR"));
                            }
                            var extension = security.GetExtension("http://fhir-registry.smarthealthit.org/StructureDefinition/oauth-uris");
                            if (extension == null)
                            {
                                extension = new Extension()
                                {
                                    Url = "http://fhir-registry.smarthealthit.org/StructureDefinition/oauth-uris"
                                };
                                security.Extension.Add(extension);
                            }
                            // remove the existing authentications, and put in our own
                            extension.Extension.Clear();
                            extension.AddExtension("token", new FhirUri($"https://{AuthProtocolSchemeHandlerFactory.AuthAddress(_launchContext)}/token"));
                            extension.AddExtension("authorize", new FhirUri($"https://{AuthProtocolSchemeHandlerFactory.AuthAddress(_launchContext)}/authorize"));

                            base.Stream = new MemoryStream(new Hl7.Fhir.Serialization.FhirJsonSerializer(new Hl7.Fhir.Serialization.SerializerSettings()
                            {
                                Pretty = true
                            }).SerializeToBytes(r.Result));
                            Console.WriteLine($"Success: {base.Stream.Length}");
                            base.MimeType = "application/fhir+json";
                            callback.Continue();
                            return(r.Result);
                        });
                        return(CefReturnValue.ContinueAsync);
                    }

                    if (!uri.LocalPath.StartsWith("/$") && !uri.LocalPath.StartsWith("/_") && uri.LocalPath.Length > 2)
                    {
                        // This is not an operation or history, so it must be a resource type
                        string resourceType = uri.LocalPath.Substring(1);
                        if (resourceType.Contains("/"))
                        {
                            resourceType = resourceType.Substring(0, resourceType.IndexOf("/"));
                        }
                        var rs = _facade.GetResourceService(requestDetails, resourceType);
                        if (rs == null)
                        {
                            System.Diagnostics.Trace.WriteLine($"Error: resource type not handled {resourceType}");
                            base.StatusCode = (int)HttpStatusCode.BadRequest;
                            //    base.Stream = new MemoryStream(new Hl7.Fhir.Serialization.FhirJsonSerializer(new Hl7.Fhir.Serialization.SerializerSettings() { Pretty = true }).SerializeToBytes(fe.Outcome));
                            //    base.MimeType = "application/fhir+json";
                            callback.Continue();
                            return(CefReturnValue.Continue);
                        }

                        // GET for a specific resource
                        ResourceIdentity ri = new ResourceIdentity(uri);
                        if (ri.IsRestResourceIdentity())
                        {
                            rs.Get(ri.Id, ri.VersionId, SummaryType.False).ContinueWith(r =>
                            {
                                if (r.Exception != null)
                                {
                                    System.Diagnostics.Trace.WriteLine($"Error: {r.Exception.Message}");
                                    if (r.Exception.InnerException is Hl7.Fhir.Rest.FhirOperationException fe)
                                    {
                                        base.StatusCode = (int)fe.Status;
                                        if (fe.Outcome != null)
                                        {
                                            base.Stream = new MemoryStream(new Hl7.Fhir.Serialization.FhirJsonSerializer(new Hl7.Fhir.Serialization.SerializerSettings()
                                            {
                                                Pretty = true
                                            }).SerializeToBytes(fe.Outcome));
                                            base.MimeType = "application/fhir+json";
                                        }
                                        callback.Continue();
                                        System.Diagnostics.Trace.WriteLine($"Error (inner): {fe.Message}");
                                        return(null);
                                    }
                                }
                                if (r.Result.HasAnnotation <HttpStatusCode>())
                                {
                                    base.StatusCode = (int)r.Result.Annotation <HttpStatusCode>();
                                }
                                else
                                {
                                    base.StatusCode = 200;
                                }

                                base.Stream = new MemoryStream(new Hl7.Fhir.Serialization.FhirJsonSerializer(new Hl7.Fhir.Serialization.SerializerSettings()
                                {
                                    Pretty = true
                                }).SerializeToBytes(r.Result));
                                Console.WriteLine($"Success: {base.Stream.Length}");
                                base.MimeType = "application/fhir+json";
                                callback.Continue();
                                return(r.Result);
                            });
                            return(CefReturnValue.ContinueAsync);
                        }

                        // Search for the resource type
                        var parameters = TupledParameters(uri, SearchQueryParameterNames);
                        int?pagesize   = GetIntParameter(uri, FhirParameter.COUNT);
                        var summary    = GetSummaryParameter(uri);
                        rs.Search(parameters, pagesize, summary).ContinueWith(r =>
                        {
                            if (r.Exception != null)
                            {
                                System.Diagnostics.Trace.WriteLine($"Error: {r.Exception.Message}");
                                if (r.Exception.InnerException is Hl7.Fhir.Rest.FhirOperationException fe)
                                {
                                    base.StatusCode = (int)fe.Status;
                                    if (fe.Outcome != null)
                                    {
                                        base.Stream = new MemoryStream(new Hl7.Fhir.Serialization.FhirJsonSerializer(new Hl7.Fhir.Serialization.SerializerSettings()
                                        {
                                            Pretty = true
                                        }).SerializeToBytes(fe.Outcome));
                                        base.MimeType = "application/fhir+json";
                                    }
                                    callback.Continue();
                                    System.Diagnostics.Trace.WriteLine($"Error (inner): {fe.Message}");
                                    return(null);
                                }
                            }
                            if (r.Result.HasAnnotation <HttpStatusCode>())
                            {
                                base.StatusCode = (int)r.Result.Annotation <HttpStatusCode>();
                            }
                            else
                            {
                                base.StatusCode = 200;
                            }

                            base.Stream = new MemoryStream(new Hl7.Fhir.Serialization.FhirJsonSerializer(new Hl7.Fhir.Serialization.SerializerSettings()
                            {
                                Pretty = true
                            }).SerializeToBytes(r.Result));
                            Console.WriteLine($"Success: {base.Stream.Length}");
                            base.MimeType = "application/fhir+json";
                            callback.Continue();
                            return(r.Result);
                        });
                        return(CefReturnValue.ContinueAsync);
                    }

                    System.Threading.Tasks.Task <Hl7.Fhir.Model.Resource> t = server.GetAsync(redirectedUrl).ContinueWith <Hl7.Fhir.Model.Resource>(r =>
                    {
                        if (r.Exception != null)
                        {
                            System.Diagnostics.Trace.WriteLine($"Error: {r.Exception.Message}");
                            if (r.Exception.InnerException is Hl7.Fhir.Rest.FhirOperationException fe)
                            {
                                base.StatusCode = (int)fe.Status;
                                if (fe.Outcome != null)
                                {
                                    base.Stream = new MemoryStream(new Hl7.Fhir.Serialization.FhirJsonSerializer(new Hl7.Fhir.Serialization.SerializerSettings()
                                    {
                                        Pretty = true
                                    }).SerializeToBytes(fe.Outcome));
                                    base.MimeType = "application/fhir+json";
                                }
                                callback.Continue();
                                System.Diagnostics.Trace.WriteLine($"Error (inner): {fe.Message}");
                                return(null);
                            }
                        }
                        base.StatusCode = 200;

                        if (r.Result is Hl7.Fhir.Model.CapabilityStatement cs)
                        {
                            // As per the documentation http://hl7.org/fhir/smart-app-launch/conformance/index.html

                            // Update the security node with our internal security node
                            if (cs.Rest[0].Security == null)
                            {
                                cs.Rest[0].Security = new Hl7.Fhir.Model.CapabilityStatement.SecurityComponent();
                            }
                            Hl7.Fhir.Model.CapabilityStatement.SecurityComponent security = cs.Rest[0].Security;
                            if (!security.Service.Any(cc => cc.Coding.Any(c => c.System == "http://hl7.org/fhir/restful-security-service" && c.Code == "SMART-on-FHIR")))
                            {
                                security.Service.Add(new Hl7.Fhir.Model.CodeableConcept("http://hl7.org/fhir/restful-security-service", "SMART-on-FHIR"));
                            }
                            var extension = security.GetExtension("http://fhir-registry.smarthealthit.org/StructureDefinition/oauth-uris");
                            if (extension == null)
                            {
                                extension = new Extension()
                                {
                                    Url = "http://fhir-registry.smarthealthit.org/StructureDefinition/oauth-uris"
                                };
                                security.Extension.Add(extension);
                            }
                            // remove the existing authentications, and put in our own
                            extension.Extension.Clear();
                            extension.AddExtension("token", new FhirUri($"https://{AuthProtocolSchemeHandlerFactory.AuthAddress(_launchContext)}/token"));
                            extension.AddExtension("authorize", new FhirUri($"https://{AuthProtocolSchemeHandlerFactory.AuthAddress(_launchContext)}/authorize"));
                        }

                        base.Stream = new MemoryStream(new Hl7.Fhir.Serialization.FhirJsonSerializer(new Hl7.Fhir.Serialization.SerializerSettings()
                        {
                            Pretty = true
                        }).SerializeToBytes(r.Result));
                        Console.WriteLine($"Success: {base.Stream.Length}");
                        base.MimeType = "application/fhir+json";
                        callback.Continue();
                        return(r.Result);
                    });
                }
                if (request.Method == "POST")
                {
                    if (uri.LocalPath == "/")
                    {
                        Bundle b = null;
                        if (request.PostData != null)
                        {
                            var data = request.PostData.Elements.FirstOrDefault();
                            var body = data.GetBody();
                            if (request.GetHeaderByName("Content-Type").Contains("xml"))
                            {
                                b = new Hl7.Fhir.Serialization.FhirXmlParser().Parse <Bundle>(body);
                            }
                            else
                            {
                                b = new Hl7.Fhir.Serialization.FhirJsonParser().Parse <Bundle>(body);
                            }
                        }

                        _facade.ProcessBatch(requestDetails, b).ContinueWith(r =>
                        {
                            if (r.Exception != null)
                            {
                                System.Diagnostics.Trace.WriteLine($"Error: {r.Exception.Message}");
                                if (r.Exception.InnerException is Hl7.Fhir.Rest.FhirOperationException fe)
                                {
                                    base.StatusCode = (int)fe.Status;
                                    if (fe.Outcome != null)
                                    {
                                        base.Stream = new MemoryStream(new Hl7.Fhir.Serialization.FhirJsonSerializer(new Hl7.Fhir.Serialization.SerializerSettings()
                                        {
                                            Pretty = true
                                        }).SerializeToBytes(fe.Outcome));
                                        base.MimeType = "application/fhir+json";
                                    }
                                    callback.Continue();
                                    System.Diagnostics.Trace.WriteLine($"Error (inner): {fe.Message}");
                                    return(null);
                                }
                            }
                            if (r.Result.HasAnnotation <HttpStatusCode>())
                            {
                                base.StatusCode = (int)r.Result.Annotation <HttpStatusCode>();
                            }
                            else
                            {
                                base.StatusCode = 200;
                            }

                            base.Stream = new MemoryStream(new Hl7.Fhir.Serialization.FhirJsonSerializer(new Hl7.Fhir.Serialization.SerializerSettings()
                            {
                                Pretty = true
                            }).SerializeToBytes(r.Result));
                            Console.WriteLine($"Success: {base.Stream.Length}");
                            base.MimeType = "application/fhir+json";
                            callback.Continue();
                            return(r.Result);
                        });
                        return(CefReturnValue.ContinueAsync);
                    }

                    System.Net.Http.HttpClient client = new System.Net.Http.HttpClient();
                    client.DefaultRequestHeaders.Add("Accept", request.GetHeaderByName("Accept"));
                    // client.DefaultRequestHeaders.Add("Content-Type", request.GetHeaderByName("Content-Type"));
                    HttpContent content = null;
                    if (request.PostData != null)
                    {
                        var data = request.PostData.Elements.FirstOrDefault();
                        var body = data.GetBody();
                        content = new System.Net.Http.StringContent(body, System.Text.Encoding.UTF8, request.GetHeaderByName("Content-Type"));
                    }
                    else
                    {
                        content = new System.Net.Http.StreamContent(null);
                    }
                    client.PostAsync(redirectedUrl, content).ContinueWith((System.Threading.Tasks.Task <HttpResponseMessage> r) =>
                    {
                        if (r.Exception != null)
                        {
                            Console.WriteLine($"Error: {r.Exception.Message}");
                            //if (r.Exception.InnerException is Hl7.Fhir.Rest.FhirOperationException fe)
                            //{
                            //    base.StatusCode = (int)fe.Status;
                            //    if (fe.Outcome != null)
                            //        base.Stream = new MemoryStream(r.Result.Content.ReadAsStringAsync().GetAwaiter().GetResult());
                            //    callback.Continue();
                            //    System.Diagnostics.Trace.WriteLine($"Error (inner): {fe.Message}");
                            //    return;
                            //}
                        }
                        base.StatusCode = (int)r.Result.StatusCode;

                        base.Stream = r.Result.Content.ReadAsStreamAsync().GetAwaiter().GetResult();
                        Console.WriteLine($"Success: {base.Stream.Length}");
                        base.MimeType = r.Result.Content.Headers.ContentType.MediaType;
                        callback.Continue();
                        return;
                    });
                }
                if (request.Method == "PUT")
                {
                    System.Net.Http.HttpClient client = new System.Net.Http.HttpClient();
                    client.DefaultRequestHeaders.Add("Accept", request.GetHeaderByName("Accept"));
                    // client.DefaultRequestHeaders.Add("Content-Type", request.GetHeaderByName("Content-Type"));
                    HttpContent content = null;
                    if (request.PostData != null)
                    {
                        var data = request.PostData.Elements.FirstOrDefault();
                        var body = data.GetBody();
                        content = new System.Net.Http.StringContent(body, System.Text.Encoding.UTF8, request.GetHeaderByName("Content-Type"));
                    }
                    else
                    {
                        content = new System.Net.Http.StreamContent(null);
                    }
                    client.PutAsync(redirectedUrl, content).ContinueWith((System.Threading.Tasks.Task <HttpResponseMessage> r) =>
                    {
                        if (r.Exception != null)
                        {
                            Console.WriteLine($"Error: {r.Exception.Message}");
                            //if (r.Exception.InnerException is Hl7.Fhir.Rest.FhirOperationException fe)
                            //{
                            //    base.StatusCode = (int)fe.Status;
                            //    if (fe.Outcome != null)
                            //        base.Stream = new MemoryStream(r.Result.Content.ReadAsStringAsync().GetAwaiter().GetResult());
                            //    callback.Continue();
                            //    System.Diagnostics.Trace.WriteLine($"Error (inner): {fe.Message}");
                            //    return;
                            //}
                        }
                        base.StatusCode = (int)r.Result.StatusCode;

                        base.Stream = r.Result.Content.ReadAsStreamAsync().GetAwaiter().GetResult();
                        Console.WriteLine($"Success: {base.Stream.Length}");
                        base.MimeType = r.Result.Content.Headers.ContentType.MediaType;
                        callback.Continue();
                        return;
                    });
                }
                return(CefReturnValue.ContinueAsync);
            }
            catch (Exception ex)
            {
                Console.WriteLine($"{ex.Message}");
                callback.Dispose();
                return(CefReturnValue.Cancel);
            }
        }