Exemplo n.º 1
0
 public static string ToXml <T>(this T genericFhirResource)
 {
     try
     {
         return(_fhirXmlSerializer.SerializeToString(genericFhirResource as Base));
     }
     catch (Exception e)
     {
         return(_fhirXmlSerializer.SerializeToString(
                    instance: OperationOutcome.ForException(e, OperationOutcome.IssueType.Processing)));
     }
 }
Exemplo n.º 2
0
        public async Task <ActionResult <string> > GetPsPatient()
        {
            FhirClient fhirClient = await _client.ConfigureClient();

            try
            {
                Resource patient = await fhirClient.GetAsync("/Patient");

                return(patient.ToJson());
            }
            catch (Exception exception)
            {
                return(OperationOutcome.ForException(exception,
                                                     OperationOutcome.IssueType.Processing,
                                                     OperationOutcome.IssueSeverity.Fatal).ToJson());
            }
        }
Exemplo n.º 3
0
        public async Task <Bundle.EntryComponent> ExecuteAsync(Bundle.EntryComponent interaction)
        {
            if (interaction == null)
            {
                throw Error.ArgumentNull(nameof(interaction));
            }
            bool compressRequestBody = false;

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

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

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

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

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

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

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

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

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

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

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

                        errorResult.Resource = operationOutcome;
                        LastResult           = errorResult;

                        throw buildFhirOperationException(webResponse.StatusCode, operationOutcome);
                    }
                }
                catch (AggregateException ae)
                {
                    //EK: This code looks weird. Is this correct?
                    if (ae.GetBaseException() is WebException)
                    {
                    }
                    throw ae.GetBaseException();
                }
            }
        }
Exemplo n.º 4
0
        public async Task <JObject> GetAsync(
            string url,
            EventHandler <BeforeRequestEventArgs> onBefore = null,
            EventHandler <AfterResponseEventArgs> onAfter  = null
            )
        {
            // setup TLS and SSL (moved to static constructor)
            ServicePointManager.ServerCertificateValidationCallback =
                (message, cert, chain, errors) => (errors == System.Net.Security.SslPolicyErrors.None) || reIsASEEndpoint.IsMatch(_endpoint);
            ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12;

            // use using(s) to handle disposing of objects. Needs more research.
            using (var op = _client.StartOperation <DependencyTelemetry>("Dependency Name"))
                using (FhirClient fhirClient =
                           new FhirClient(_endpoint)
                {
                    PreferredFormat = ResourceFormat.Json,
                    UseFormatParam = true
                })
                {
                    var dep = op.Telemetry;
                    dep.SetLogLocation(); // location is not really the most accurate metric but has been helpful before
                    dep.Type = "GET";     // type will always be a get

                    // request ID is used for linking logging in dependencies to this call
                    var requestId = RandomID(15);
                    dep.Id = requestId;

                    // stopwatch for logging duration.
                    Stopwatch sw = new Stopwatch();

                    // add dependency logging, blob logging, etc.
                    fhirClient.OnBeforeRequest += delegate(object sender, BeforeRequestEventArgs e)
                    {
                        // add client information and "helpful" headers
                        e.RawRequest.ClientCertificates.Add(_certificate);
                        e.RawRequest.Timeout = _timeout;
                        e.RawRequest.Headers.SetLinkingHeaders(requestId, RandomID(12));
                        sw.Start();
                    };

                    fhirClient.OnAfterResponse += delegate(object sender, AfterResponseEventArgs e)
                    {
                        sw.Stop();

                        // log generic response inforation
                        dep.Duration   = sw.Elapsed;
                        dep.ResultCode = e.RawResponse.StatusCode.ToString();
                        dep.Success    = e.RawResponse.StatusCode.IsSuccessful();

                        // ToDo: log response to blob storage
                    };

                    // add user defined before and after actions
                    if (onBefore != null)
                    {
                        fhirClient.OnBeforeRequest += onBefore;
                    }
                    if (onAfter != null)
                    {
                        fhirClient.OnAfterResponse += onAfter;
                    }

                    // invoke fhir url. if error occurs, cast exception to operation outcome
                    try
                    {
                        Resource resp = await fhirClient.GetAsync(url);

                        return(resp.ToJObject());
                    }
                    catch (Exception ex)
                    {
                        _client.TrackException(ex);
                        return(OperationOutcome.ForException(
                                   ex,
                                   OperationOutcome.IssueType.Processing,
                                   OperationOutcome.IssueSeverity.Fatal
                                   ).ToJObject());
                    }
                }
        }
Exemplo n.º 5
0
        public Bundle.EntryComponent Execute(Bundle.EntryComponent interaction)
        {
            if (interaction == null)
            {
                throw Error.ArgumentNull("interaction");
            }

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

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

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

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

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

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

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

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

                        errorResult.Resource = operationOutcome;
                        LastResult           = errorResult;

                        throw buildFhirOperationException(webResponse.StatusCode, operationOutcome);
                    }
                }
                catch (AggregateException ae)
                {
                    //EK: This code looks weird. Is this correct?
                    if (ae.GetBaseException() is WebException)
                    {
                    }
                    throw ae.GetBaseException();
                }
            }
        }