Esempio n. 1
0
        private HttpWebResponse SendHttpWebRequest_(
            string path, string method, MemoryStream body, string contentType, string accept, string contentEncoding)
        {
            HttpWebRequest  request  = null;
            HttpWebResponse response = null;

            void send()
            {
                request  = null;
                response = null;

                Stopwatch sw = Stopwatch.StartNew();

                try
                {
                    try
                    {
                        var requestUri = string.IsNullOrEmpty(path) ?
                                         ServerUrl : new Uri(ServerUrl, path);

                        request = CreateHttpWebRequest_(
                            requestUri, method, body, contentType, accept, contentEncoding);

                        if (request == null)
                        {
                            throw new NullReferenceException("request is null");
                        }
                        response = (HttpWebResponse)request.GetResponse();
                    }
                    catch (WebException ex)
                    {
                        if (request == null || ex.Response == null)
                        {
                            throw;
                        }

                        response = (HttpWebResponse)ex.Response;
                    }
                }
                catch (Exception ex2)
                {
                    if (request != null && RequestFailed != null)
                    {
                        var args = new HttpRequestFailedEventArgs(sw.Elapsed, request, ex2);
                        CommonUtils.DontThrow(() => RequestFailed(this, args));
                    }

                    throw;
                }

                if (RequestCompleted != null)
                {
                    var args = new HttpRequestCompletedEventArgs(
                        sw.Elapsed, request, response);
                    CommonUtils.DontThrow(() => RequestCompleted(this, args));
                }
            }

            int wait        = 500;
            int retriesLeft = 2;

            do
            {
                try
                {
                    send();
                    retriesLeft = 0;
                }
                catch
                {
                    CommonUtils.DontThrow(() => response?.Close());

                    Thread.Sleep(wait);
                    wait *= 2;
                    wait  = Math.Min(10000, wait);
                }
            } while (retriesLeft-- > 0);

            if (response == null)
            {
                throw new NullReferenceException("response is null");
            }

            //while (Retry != null && Retry(request, response))
            //{
            //    CommonUtils.DontThrow(() => response.Close());

            //    Thread.Sleep(wait);
            //    wait *= 2;
            //    wait = Math.Min(10000, wait);

            //    send();
            //}

            if (response == null)
            {
                throw new NullReferenceException("response object is null.");
            }
            if (AcceptLongRunningTasks)
            {
                var statusUrl = response.Headers[HttpResponseHeader.Location];
                if (statusUrl != null && response.StatusCode == HttpStatusCode.Accepted)
                {
                    response.Close();

                    wait = 500;
                    while (true)
                    {
                        using (response = Get(statusUrl))
                        {
                            if (response.StatusCode == HttpStatusCode.Created)
                            {
                                return(Delete(
                                           response.Headers[HttpResponseHeader.Location], accept));
                            }

                            if (response.StatusCode == HttpStatusCode.OK)
                            {
                                Thread.Sleep(wait);
                                wait *= 2;
                                wait  = Math.Min(10000, wait);
                                continue;
                            }

                            // Something went wrong.
                            return(response);
                        }
                    }
                }
            }

            return(response);
        }
        private void SendLongRequest_(TaskListener <HttpResponseMessage> listener,
                                      string path, string method, Stream body, string contentType, string accept, string contentEncoding)
        {
            Stopwatch          sw      = Stopwatch.StartNew();
            HttpRequestMessage request = null;

            try
            {
                try
                {
                    Uri requestUri = string.IsNullOrEmpty(path) ?
                                     ServerUrl : new Uri(ServerUrl, path);

                    request = CreateHttpRequestMessage(
                        requestUri, method, body, contentType, accept, contentEncoding);

                    if (request == null)
                    {
                        throw new NullReferenceException("request is null");
                    }
                    CancellationTokenSource cts         = new CancellationTokenSource(Timeout);
                    IAsyncResult            asyncResult = GetHttpClient().SendAsync(request, cts.Token).
                                                          AsApm(ar => OnLongRequestResponse_(ar, request), request, Logger);

                    if (asyncResult != null && asyncResult.CompletedSynchronously)
                    {
                        Logger.Log(TraceLevel.Notice, Stage.General,
                                   new { message = "request.BeginGetResponse completed synchronously" });
                        OnLongRequestResponse_(asyncResult, request);
                    }
                }
                catch (WebException ex)
                {
                    if (request == null || ex.Response == null)
                    {
                        throw;
                    }

                    listener.OnFail(ex);
                }
            }
            catch (Exception ex2)
            {
                if (request != null && RequestFailed != null)
                {
                    var args = new HttpRequestFailedEventArgs(sw.Elapsed, request, ex2);
                    CommonUtils.DontThrow(() => RequestFailed(this, args));
                }

                throw;
            }

            void OnLongRequestResponse_(IAsyncResult result, HttpRequestMessage originalRequest)
            {
                if (!result.IsCompleted)
                {
                    Logger.Log(TraceLevel.Notice, Stage.General, new { message = "long request not complete" });
                    return;
                }
                try
                {
                    Task <HttpResponseMessage> resultAsTask = (Task <HttpResponseMessage>)result;
                    if (resultAsTask.IsFaulted)
                    {
                        listener.OnFail(
                            new EyesException($"HttpRequestMessage request failed: {originalRequest.Method} {originalRequest.RequestUri}",
                                              resultAsTask.Exception));
                        return;
                    }
                    HttpResponseMessage response = resultAsTask.Result;
                    if (response == null)
                    {
                        throw new NullReferenceException("response is null");
                    }

                    Uri statusUrl = response.Headers.Location;
                    RequestPollingTaskListener requestPollingListener = new RequestPollingTaskListener(this, statusUrl, listener);
                    SendAsyncRequest(requestPollingListener, statusUrl, "GET");
                }
                catch (Exception ex)
                {
                    CommonUtils.LogExceptionStackTrace(Logger, Stage.General, ex);
                    listener.OnFail(ex);
                }
            }
        }