EndGetResponse() public méthode

public EndGetResponse ( System asyncResult ) : System.Net.WebResponse
asyncResult System
Résultat System.Net.WebResponse
        public Task<WebResponse> GetResponseAsync(HttpWebRequest request, int timeoutMs)
        {
            if (timeoutMs > 0)
            {
                return GetResponseAsync(request, TimeSpan.FromMilliseconds(timeoutMs));
            }

            var tcs = new TaskCompletionSource<WebResponse>();

            try
            {
                request.BeginGetResponse(iar =>
                {
                    try
                    {
                        var response = (HttpWebResponse)request.EndGetResponse(iar);
                        tcs.SetResult(response);
                    }
                    catch (Exception exc)
                    {
                        tcs.SetException(exc);
                    }
                }, null);
            }
            catch (Exception exc)
            {
                tcs.SetException(exc);
            }

            return tcs.Task;
        }
Exemple #2
0
        /// <summary>
        /// Encapsulates GetResponse so tests don't invoke the request
        /// </summary>
        /// <param name="req">Request to Twitter</param>
        /// <returns>Response to Twitter</returns>
        public static HttpWebResponse AsyncGetResponse(HttpWebRequest req)
        {
            Exception asyncException = null;

            var resetEvent = new ManualResetEvent(/*initialStateSignaled:*/ false);
            HttpWebResponse res = null;

            req.BeginGetResponse(
                new AsyncCallback(
                    ar =>
                    {
                        try
                        {
                            res = req.EndGetResponse(ar) as HttpWebResponse;
                        }
                        catch (Exception ex)
                        {
                            asyncException = ex;
                        }
                        finally
                        {
                            resetEvent.Set();
                        }
                    }), null);

            resetEvent.WaitOne();

            if (asyncException != null)
            {
                throw asyncException;
            }

            return res;
        }
        public void HttpGetStreamCallback(IAsyncResult asynchronousResult, HttpWebRequest request)
        {
            try{

                // End the operation
                HttpWebResponse response = (HttpWebResponse)request.EndGetResponse(asynchronousResult);

                if (response.StatusCode != HttpStatusCode.OK)
                {
                    getAsyncSendFailResult();
                    return;
                }
                Stream streamResponse = response.GetResponseStream();
                StreamReader streamRead = new StreamReader(streamResponse);
                String responseData = streamRead.ReadToEnd();
                getConnectionReceivedHandler(responseData);

                streamResponse.Close();
                streamRead.Close();
                response.Close();
            }
            catch (Exception e)
            {
                log.errorCause( "http get failed ", e);
                getAsyncSendFailResult();
            }
        }
        private void OnResponse(System.IAsyncResult result)
        {
            try
            {
                Net.HttpWebRequest request  = (Net.HttpWebRequest)result.AsyncState;
                Net.WebResponse    response = request.EndGetResponse(result);

                this.ParseTrackerResponse(response.GetResponseStream());
                response.Close();

                if (this.TrackerUpdate != null)
                {
                    this.TrackerUpdate(this.peerList, true, string.Empty);
                }

                if (this.autoUpdate && this.updateTimer == null)
                {
                    this.updateTimer = new Threading.Timer(new Threading.TimerCallback(OnUpdate), null,
                                                           this.updateInterval * 1000, this.updateInterval * 1000);
                }
            }
            catch (System.Exception e)
            {
                if (this.TrackerUpdate != null)
                {
                    this.TrackerUpdate(null, false, e.Message);
                }
                badTracker = true;
            }
        }
 private HttpWebResponse GetResponseAsynch(HttpWebRequest request)
 {
     return AsynchHelper.WaitForAsynchResponse(
         c => request.BeginGetResponse(c, null),
         (r, s) => (HttpWebResponse)request.EndGetResponse(r)
     );
 }
        public async Task<string> receiveHttpResonse(HttpWebRequest request, IAsyncResult asynchronousResult)
        {
            string responseString = String.Empty;
            HttpWebResponse response = (HttpWebResponse)request.EndGetResponse(asynchronousResult);
            Stream streamResponse = response.GetResponseStream();
            StreamReader streamRead = new StreamReader(streamResponse);
            responseString = await streamRead.ReadToEndAsync();

            //var userResp = JsonConvert.DeserializeObject<T>(responseString);
            // Close the stream object

            streamRead.Close();
            streamResponse.Close();
            // Release the HttpWebResponse
            response.Close();

            HttpStatusCode responseCode = response.StatusCode;
            if (responseCode == HttpStatusCode.Created)
            {
                return Constants.SUCCESS;
            }
            else
            {
                return Constants.ERROR;
            }

        }
Exemple #7
0
        public static IEnumerator<object> IssueRequest(HttpWebRequest request)
        {
            var fResponse = new Future<HttpWebResponse>();
            ThreadPool.QueueUserWorkItem(
                (__) => {
                    try {
                        request.BeginGetResponse(
                            (ar) => {
                                try {
                                    var _ = (HttpWebResponse)request.EndGetResponse(ar);
                                    fResponse.SetResult(_, null);
                                } catch (Exception ex) {
                                    fResponse.SetResult(null, ex);
                                }
                            }, null
                        );
                    } catch (Exception ex_) {
                        fResponse.SetResult(null, ex_);
                    }
                }
            );

            yield return fResponse;
            if (fResponse.Failed)
                throw new RequestFailedException(fResponse.Error);

            using (var response = fResponse.Result) {
                var fResponseStream = Future.RunInThread(
                    () => response.GetResponseStream()
                );
                yield return fResponseStream;

                Encoding encoding = AsyncTextReader.DefaultEncoding;
                if (!string.IsNullOrEmpty(response.CharacterSet))
                    encoding = Encoding.GetEncoding(response.CharacterSet);

                string responseText;
                using (var stream = fResponseStream.Result)
                using (var adapter = new AsyncTextReader(new StreamDataAdapter(stream, false), encoding)) {
                    var fText = adapter.ReadToEnd();

                    yield return fText;

                    responseText = fText.Result;
                }

                var cookies = new Cookie[response.Cookies.Count];
                response.Cookies.CopyTo(cookies, 0);

                yield return new Result(new Response {
                    Body = responseText,
                    ContentType = response.ContentType,
                    StatusCode = response.StatusCode,
                    StatusDescription = response.StatusDescription,
                    Cookies = cookies
                });
            }
        }
        /// <summary>
        /// 
        /// </summary>
        /// <param name="key"></param>
        /// <param name="request"></param>
        /// <param name="result"></param>
        /// <param name="statusCode"></param>
        /// <param name="exception"></param>
        /// <returns></returns>
        public Attachment Map(string key, HttpWebRequest request, IAsyncResult result, out HttpStatusCode statusCode,
                              out Exception exception)
        {
            try
            {
                var response = request.EndGetResponse(result) as HttpWebResponse;
                Stream stream = response.GetResponseStream();

                statusCode = response.StatusCode;
                exception = null;

                var headers = new NameValueCollection();
                foreach (string headerKey in response.Headers.AllKeys)
                {
                    headers.Add(headerKey, response.Headers[key]);
                }

                return new Attachment
                           {
                               Data = stream.ReadData(),
                               Etag = new Guid(response.Headers["ETag"]),
                               Metadata = headers.FilterHeaders(isServerDocument: false)
                           };
            }
            catch (WebException ex)
            {
                var httpWebResponse = ex.Response as HttpWebResponse;
                if (httpWebResponse == null)
                {
                    throw;
                }

                statusCode = httpWebResponse.StatusCode;
                exception = AsyncServerClient.ExtractException(httpWebResponse);

                if (httpWebResponse.StatusCode == HttpStatusCode.Conflict)
                {
                    JObject conflictsDoc = JObject.Load(new BsonReader(httpWebResponse.GetResponseStream()));
                    string[] conflictIds =
                        conflictsDoc.Value<JArray>("Conflicts").Select(x => x.Value<string>()).ToArray();

                    throw new ConflictException("Conflict detected on " + key +
                                                ", conflict must be resolved before the attachment will be accessible")
                              {
                                  ConflictedVersionIds = conflictIds
                              };
                }

                if (httpWebResponse.StatusCode == HttpStatusCode.NotFound)
                {
                    return null;
                }

                throw;
            }
        }
Exemple #9
0
 private System.Net.HttpWebResponse GetResponse(System.Net.HttpWebRequest req)
 {
     try {
         var responseAsyncResult = req.BeginGetResponse(null, null);
         var returnValue         = req.EndGetResponse(responseAsyncResult);
         return((System.Net.HttpWebResponse)returnValue);
     } catch (System.Net.WebException wex) {
         return((System.Net.HttpWebResponse)wex.Response);
     }
 }
        private void ResponseCallback(IAsyncResult asyncResult)
        {
           webRequest = (HttpWebRequest)asyncResult.AsyncState;
            HttpWebResponse webResponse = (HttpWebResponse)webRequest.EndGetResponse(asyncResult);
            
            MemoryStream tempStream = new MemoryStream();
            webResponse.GetResponseStream().CopyTo(tempStream);

            Dispatcher.BeginInvoke(() =>
                {
                    BitmapImage image = new BitmapImage();
                    image.CreateOptions = BitmapCreateOptions.None;
                    image.SetSource(tempStream);

                    DownloadResultImage.Source = image;
                    DownloadStatusText.Text = "Download completed.";
                });
        }
 private void ProcessResponse(Action<List<DilbertItem>> success, Action<Exception> error, HttpWebRequest request, IAsyncResult result)
 {
     try
     {
         var response = request.EndGetResponse(result);
         using (var stream = response.GetResponseStream())
         using (var reader = new StreamReader(stream))
         {
             var text = reader.ReadToEnd();
             var list = ParseDilbertItemList(text);
             success(list);
         }
     }
     catch (Exception exception)
     {
         error(exception);
     }
 }
        private static Stream GetPricesStream(IAsyncResult result, HttpWebRequest request)
        {
            Stream pricesStream = new MemoryStream();

            IsolatedStorageFile isolatedStorage = IsolatedStorageFile.GetUserStoreForApplication();

            try
            {
                // Copy resopnse to memory
                HttpWebResponse response = (HttpWebResponse)request.EndGetResponse(result);
                Stream resultStream = response.GetResponseStream();
                resultStream.CopyTo(pricesStream);
                pricesStream.Position = 0;
                resultStream.Close();

                // Copy memory to cache
                IsolatedStorageFileStream pricesCacheStream = isolatedStorage.OpenFile(PricesCacheFileName, FileMode.Create, FileAccess.Write);
                pricesStream.CopyTo(pricesCacheStream);
                pricesStream.Position = 0;
                pricesCacheStream.Close();
            }
            catch (WebException)
            {
                // If there is a problem retreiving the prices from the Internet, load the prices from the cache
                pricesStream.Close();
                if (isolatedStorage.FileExists(PricesCacheFileName))
                {
                    pricesStream = isolatedStorage.OpenFile(PricesCacheFileName, FileMode.Open, FileAccess.Read);
                }
                else
                {
                    pricesStream = null;
                    Deployment.Current.Dispatcher.BeginInvoke(() =>
                    {
                        MessageBox.Show("Unable to retrieve prices.");
                    });

                }
            }
            return pricesStream;
        }
        private void ReceivedData(IAsyncResult asyncResult)
        {
            try
            {
                HttpRequestState requestState = (HttpRequestState)asyncResult.AsyncState;

                System.Net.HttpWebRequest httpWebRequest = requestState.Request;

                requestState.Response = (HttpWebResponse)httpWebRequest.EndGetResponse(asyncResult);
                Stream responseStream = requestState.Response.GetResponseStream();
                requestState.StreamResponse = responseStream;

                responseStream.BeginRead(requestState.BufferRead, 0, HttpRequestState.BUFFER_SIZE, new AsyncCallback(ReadCallBack), requestState);
            }catch (Exception ex)
            {
                error        = ex.Message;
                isDone       = true;
                isError      = true;
                responseCode = 0;
            }
        }
        private void ProcessResponse(Action<List<Dinner>> success, Action<Exception> error, HttpWebRequest request, IAsyncResult result)
        {
            try
            {
                var response = request.EndGetResponse(result);
                using (var stream = response.GetResponseStream())
                {
                    using (StreamReader sr = new StreamReader(stream))
                    {
                        using (JsonReader reader = new JsonTextReader(sr))
                        {
                            JsonSerializer serializer = new JsonSerializer();

                            var list = serializer.Deserialize<List<Dinner>>(reader);
                            success(list);
                        }
                    }
                }
            }
            catch (Exception exception)
            {
                error(exception);
            }
        }
Exemple #15
0
        void GetHttpResponse(HttpWebRequest request, Action<HttpResponse> callback)
        {
            request.BeginGetResponse(ar =>
                {
                    try
                    {
                        var response = (HttpWebResponse)request.EndGetResponse(ar);
                        var result = new HttpResponse();

                        using (response)
                        {
                            result.ContentType = response.ContentType;
                            result.ContentLength = response.ContentLength;
                            result.RawBytes = response.GetResponseStream().ReadAsBytes();
                            result.Content = result.RawBytes.GetString();
                            result.StatusCode = response.StatusCode;
                            result.StatusDescription = response.StatusDescription;
                            result.ResponseUri = response.ResponseUri;
                            result.ResponseStatus = ResponseStatus.Completed;

                            if (response.Cookies != null)
                            {
                                foreach (Cookie cookie in response.Cookies)
                                {
                                    result.Cookies.Add(new HttpCookie
                                    {
                                        Comment = cookie.Comment,
                                        CommentUri = cookie.CommentUri,
                                        Discard = cookie.Discard,
                                        Domain = cookie.Domain,
                                        Expired = cookie.Expired,
                                        Expires = cookie.Expires,
                                        HttpOnly = cookie.HttpOnly,
                                        Name = cookie.Name,
                                        Path = cookie.Path,
                                        Port = cookie.Port,
                                        Secure = cookie.Secure,
                                        TimeStamp = cookie.TimeStamp,
                                        Value = cookie.Value,
                                        Version = cookie.Version
                                    });
                                }
                            }

                            foreach (var headerName in response.Headers.AllKeys)
                            {
                                var headerValue = response.Headers[headerName];
                                result.Headers.Add(new HttpHeader { Name = headerName, Value = headerValue });
                            }

                            response.Close();
                        }

                        this.ExecuteCallback(result, callback);
                    }
                    catch (Exception e)
                    {
                        OnError(e, callback);
                    }


                }, null);
        }
Exemple #16
0
 private static void GetResponseCallback(IAsyncResult asynchronousResult, HttpWebRequest request,
     string filename)
 {
     HttpWebResponse response = (HttpWebResponse)request.EndGetResponse(asynchronousResult);
     HttpStatusCode rcode = response.StatusCode;
     using (IsolatedStorageFile myIsolatedStorage = IsolatedStorageFile.GetUserStoreForApplication())
     {
         myIsolatedStorage.DeleteFile(DIR + "\\" + filename);
     }
     SendAllExceptionsToServer(); //Keep sending files until all are submitted!
 }
 /// <summary>
 /// Gets response text from the specified request.
 /// </summary>
 /// <param name="request">Request object.</param>
 /// <returns>Response from server.</returns>
 public string GetResponse(HttpWebRequest request, IAsyncResult result)
 {
     return ReadResponseString(request.EndGetResponse(result));
 }
        private void EndRequest(IAsyncResult result)
        {
            request = (HttpWebRequest)result.AsyncState;
            response = (HttpWebResponse)request.EndGetResponse(result);
            stream = response.GetResponseStream();

            using (StreamReader reader = new StreamReader(stream, this.encoding))
            {
                StringBuilder sb = new StringBuilder();

                int c = reader.Read();
                while (c > -1)
                {
                    sb.Append((char)c);
                    c = reader.Read();
                }
                reader.Close();
                if (Callback != null)
                {
                    Callback(sb.ToString().Trim());
                }
            }
            did = true;
        }
		private async Task<Stream> GetDataAsync( HttpWebRequest request )
		{
			Task<WebResponse> task = Task.Factory.FromAsync(
				request.BeginGetResponse,
				asyncResult =>
				{
					try
					{
						return request.EndGetResponse( asyncResult );
					}
					catch( WebException )
					{
						return null;
					}
				},
				null );

			var returnTask = await task.ContinueWith( t =>
				   ReadStreamFromResponse( t.Result ) );

			return await returnTask;
		}
 private static Task<HttpWebResponse> GetWebResponseAsync(HttpWebRequest webRequest)
 {
     return Task<HttpWebResponse>.Factory.FromAsync(
         webRequest.BeginGetResponse,
         ar => (HttpWebResponse)webRequest.EndGetResponse(ar),
         null);
 }
Exemple #21
0
        private HttpWebResponse GetResponseWithTimeout(HttpWebRequest req)
        {
            bool m_Ajax = Ajax; Ajax = false;
            AutoResetEvent ev=new AutoResetEvent(false);
            IAsyncResult Japan =req.BeginGetResponse(GetResponseCallback, ev);

            if(!ev.WaitOne(Timeout))
            {
                req.Abort();
                return null;
            }
            if (!m_Ajax) Referer = req.RequestUri.ToString();
            return (HttpWebResponse)req.EndGetResponse(Japan);
        }
        private Response DoRequest(HttpWebRequest req)
        {
            Response res = null;
            AutoResetEvent signal = new AutoResetEvent(false);

            try
            {
                req.BeginGetResponse(respState =>
                {
                    try
                    {
                        HttpWebResponse response = (HttpWebResponse)req.EndGetResponse(respState);
                        res = new Response((int)response.StatusCode, response.StatusDescription, new StreamReader(response.GetResponseStream()).ReadToEnd());
                    }
                    catch (WebException we)
                    {
                        try
                        {
                            var resp = we.Response as HttpWebResponse;
                            res = new Response((int)resp.StatusCode, we.ToString(), null);
                        }
                        catch (Exception ex)
                        {
                            res = new Response(-1, ex.ToString(), null);
                        }
                    }
                    catch (Exception ex)
                    {
                        res = new Response(-1, ex.ToString(), null);
                    }
                    finally
                    {
                        signal.Set();
                    }

                }, null);
            }
            catch (Exception ex)
            {
                res = new Response(-1, ex.ToString(), null);
                signal.Set();
            }

            signal.WaitOne();
            return res;
        }
Exemple #23
0
		static void ReceivedResponse (HttpWebRequest request, IAsyncResult ar, UpdateLevel level, Action<UpdateResult> callback)
		{
			List<Update> updates = null;
			string error = null;
			Exception errorDetail = null;
			
			try {
				using (var response = (HttpWebResponse) request.EndGetResponse (ar)) {
					var encoding = Encoding.GetEncoding (response.CharacterSet);
					using (var reader = new StreamReader (response.GetResponseStream(), encoding)) {
						var doc = System.Xml.Linq.XDocument.Load (reader);
						updates = (from x in doc.Root.Elements ("Application")
							let first = x.Elements ("Update").First ()
							select new Update () {
								Name = x.Attribute ("name").Value,
								Url = first.Attribute ("url").Value,
								Version = first.Attribute ("version").Value,
								Level = first.Attribute ("level") != null
									? (UpdateLevel)Enum.Parse (typeof(UpdateLevel), (string)first.Attribute ("level"))
									: UpdateLevel.Stable,
								Date = DateTime.Parse (first.Attribute ("date").Value),
								Releases = x.Elements ("Update").Select (y => new Release () {
									Version = y.Attribute ("version").Value,
									Date = DateTime.Parse (y.Attribute ("date").Value),
									Notes = y.Value
								}).ToList ()
							}).ToList ();
					}
				}
			} catch (Exception ex) {
				error = GettextCatalog.GetString ("Error retrieving update information");
				errorDetail = ex;
			}
			callback (new UpdateResult (updates, level, error, errorDetail));
		}
Exemple #24
0
        protected byte[] UploadDataCore(Uri address, string method, byte[] data, object userToken)
        {
            uploadDataRequest = (HttpWebRequest)SetupRequest(address);

            // Mono insists that if you have Content-Length set, Keep-Alive must be true.
            // Otherwise the unhelpful exception of "Content-Length not set" will be thrown.
            // The Linden Lab event queue server breaks HTTP 1.1 by always replying with a
            // Connection: Close header, which will confuse the Windows .NET runtime and throw
            // a "Connection unexpectedly closed" exception. This is our cross-platform hack
            if (Helpers.GetRunningRuntime() == Helpers.Runtime.Mono)
                uploadDataRequest.KeepAlive = true;

            try
            {
                // Content-Length
                int contentLength = data.Length;
                uploadDataRequest.ContentLength = contentLength;

                using (Stream stream = uploadDataRequest.GetRequestStream())
                {
                    // Most uploads are very small chunks of data, use an optimized path for these
                    if (contentLength < 4096)
                    {
                        stream.Write(data, 0, contentLength);
                    }
                    else
                    {
                        // Upload chunks directly instead of buffering to memory
                        uploadDataRequest.AllowWriteStreamBuffering = false;

                        MemoryStream ms = new MemoryStream(data);

                        byte[] buffer = new byte[checked((uint)Math.Min(4096, (int)contentLength))];
                        int bytesRead = 0;

                        while ((bytesRead = ms.Read(buffer, 0, buffer.Length)) != 0)
                        {
                            stream.Write(buffer, 0, bytesRead);

                            if (UploadProgressChanged != null)
                            {
                                UploadProgressChanged(this, new UploadProgressChangedEventArgs(0, 0, bytesRead, contentLength, userToken));
                            }
                        }

                        ms.Close();
                    }
                }

                HttpWebResponse response = null;
                Exception responseException = null;

                IAsyncResult result = uploadDataRequest.BeginGetResponse(
                    delegate(IAsyncResult asyncResult)
                    {
                        try { response = (HttpWebResponse)uploadDataRequest.EndGetResponse(asyncResult); }
                        catch (Exception ex) { responseException = ex; }
                    }, null);

                // Not sure if one of these is better than the other, but
                // ThreadPool.RegisterWaitForSingleObject fails to wait on Mono 1.9.1 in this case
                result.AsyncWaitHandle.WaitOne(1000 * 100, false);
                //ThreadPool.RegisterWaitForSingleObject(result.AsyncWaitHandle,
                //    delegate(object state, bool timedOut) { }, null, 1000 * 100, true);

                if (responseException != null)
                {
                    // Exception occurred
                    throw responseException;
                }
                else if (response == null)
                {
                    // No exception, but no response
                    throw new WebException("No response from the CAPS server", WebExceptionStatus.ReceiveFailure);
                }
                else
                {
                    // Server responded
                    Stream st = ProcessResponse(response);
                    contentLength = (int)response.ContentLength;

                    return ReadAll(st, contentLength, userToken, true);
                }
            }
            catch (ThreadInterruptedException)
            {
                if (uploadDataRequest != null)
                    uploadDataRequest.Abort();
                throw;
            }
        }
Exemple #25
0
 /// <summary>
 /// Gets EndGetResponse implementation of the underlying HttpWebRequest class.
 /// </summary>
 public IHttpResponse EndGetResponse(IAsyncResult asyncResult)
 {
     return(new HttpWebResponse((System.Net.HttpWebResponse)request.EndGetResponse(asyncResult)));
 }
Exemple #26
0
        private HttpWebResponse GetResponseWithTimeout(HttpWebRequest req)
        {
            AutoResetEvent ev=new AutoResetEvent(false);
            IAsyncResult result =req.BeginGetResponse(GetResponseCallback, ev);

            if (!ev.WaitOne(ResponseTimeout))
            {
                req.Abort();
                return null;
            }
            /*
            if (!HttpClientParams.WaitOneEmpty)
            {
                if (!ev.WaitOne(ResponseTimeout))
                {
                    req.Abort();
                    return null;
                }
            }
            else
                if (!ev.WaitOne())
                {
                    req.Abort();
                    return null;
                }
             */

            /*if (!m_Ajax) */Referer = req.RequestUri.ToString();
            return (HttpWebResponse)req.EndGetResponse(result);
        }
        private void receiveMessageAsync(IAsyncResult asynchronousResult, HttpWebRequest request, String message, NetConnectionSendFailHandler asyncSendFailResult)
        {
            try{

                // End the operation
                HttpWebResponse response = (HttpWebResponse)request.EndGetResponse(asynchronousResult);

                if (response.StatusCode != HttpStatusCode.OK)
                {
                    log.error( "post failed ");
                    postAsyncSendFailResult();
                    return;
                }

                Stream streamResponse = response.GetResponseStream();
                StreamReader streamRead = new StreamReader(streamResponse);
                String responseData = streamRead.ReadToEnd();
                postConnectionReceivedHandler(responseData);

                streamResponse.Close();
                streamRead.Close();
                response.Close();
                allDone.Set();
            }
            catch (Exception e)
            {
                log.errorCause( " post failed ", e);
                postAsyncSendFailResult();
            }
        }
Exemple #28
0
        private void GetResponse(Stopwatch stopwatch, HttpWebRequest webRequest)
        {
            webRequest.BeginGetResponse(getResponseAsyncResult =>
            {
                try
                {
                    using (var response = webRequest.EndGetResponse(getResponseAsyncResult))
                    {
                        ConsumeResponse(response);

                        stopwatch.Stop();
                        lock (elapsedLock)
                        {
                            elapsed.Add(stopwatch.ElapsedMilliseconds);
                        }
                    }
                }
                catch (WebException webException)
                {
                    Interlocked.Increment(ref faulted);

                    if (!webException.Message.StartsWith("The underlying connection was closed"))
                    {
                        ConsumeResponse(webException.Response);
                    }
                }
                finally
                {
                    Interlocked.Increment(ref completed);
                }
            }, null);
        }
Exemple #29
0
        internal void DoInvoke(object[] parameters, AsyncContinuation continuation, HttpWebRequest request, Func<AsyncCallback, IAsyncResult> beginFunc, 
            Func<IAsyncResult, Stream> getStreamFunc)
        {
            Stream postPayload = null;

            switch (this.Protocol)
            {
                case WebServiceProtocol.Soap11:
                    postPayload = this.PrepareSoap11Request(request, parameters);
                    break;

                case WebServiceProtocol.Soap12:
                    postPayload = this.PrepareSoap12Request(request, parameters);
                    break;

                case WebServiceProtocol.HttpGet:
                    this.PrepareGetRequest(request);
                    break;

                case WebServiceProtocol.HttpPost:
                    postPayload = this.PreparePostRequest(request, parameters);
                    break;
            }

            AsyncContinuation sendContinuation =
                ex =>
                {
                    if (ex != null)
                    {
                        continuation(ex);
                        return;
                    }

                    request.BeginGetResponse(
                        r =>
                        {
                            try
                            {
                                using (var response = request.EndGetResponse(r))
                                {
                                }

                                continuation(null);
                            }
                            catch (Exception ex2)
                            {
                                InternalLogger.Error(ex2, "Error when sending to Webservice.");

                                if (ex2.MustBeRethrown())
                                {
                                    throw;
                                }

                                continuation(ex2);
                            }
                        },
                        null);
                };

            if (postPayload != null && postPayload.Length > 0)
            {
                postPayload.Position = 0;
                beginFunc(
                    result =>
                    {
                        try
                        {
                            using (Stream stream = getStreamFunc(result))
                            {
                                WriteStreamAndFixPreamble(postPayload, stream, this.IncludeBOM, this.Encoding);

                                postPayload.Dispose();
                            }

                            sendContinuation(null);
                        }
                        catch (Exception ex)
                        {
                            postPayload.Dispose();
                            InternalLogger.Error(ex, "Error when sending to Webservice.");

                            if (ex.MustBeRethrown())
                            {
                                throw;
                            }

                            continuation(ex);
                        }
                    });
            }
            else
            {
                sendContinuation(null);
            }
        }
        protected virtual void ProcessResponse(
            MvxRestRequest restRequest,
            HttpWebRequest httpRequest,
            Action<MvxStreamRestResponse> successAction,
            Action<Exception> errorAction)
        {
            httpRequest.BeginGetResponse(result =>
                                         TryCatch(() =>
                    {
                        var response = (HttpWebResponse)httpRequest.EndGetResponse(result);

                        var code = response.StatusCode;
                        var responseStream = response.GetResponseStream();
                        var restResponse = new MvxStreamRestResponse
                        {
                            CookieCollection = response.Cookies,
                            Stream = responseStream,
                            Tag = restRequest.Tag,
                            StatusCode = code
                        };
                        successAction?.Invoke(restResponse);
                    }, errorAction)
                , null);
        }
 private static void GetResponseCallback(IAsyncResult asynchronousResult)
 {
     try
     {
         request = (HttpWebRequest)asynchronousResult.AsyncState;
         response = (HttpWebResponse)request.EndGetResponse(asynchronousResult);
         allDone.Set();
     }
     catch (Exception e)
     {
        //Debug.WriteLine("Got Exception in GetResponseCallback: " + e.Message);
     }
 }
        // 
        private bool TunnelThroughProxy(Uri proxy, HttpWebRequest originalRequest, bool async) {
            GlobalLog.Enter("Connection#" + ValidationHelper.HashString(this) + "::TunnelThroughProxy", "proxy="+proxy+", async="+async+", originalRequest #"+ValidationHelper.HashString(originalRequest));

            bool result = false;
            HttpWebRequest connectRequest = null;
            HttpWebResponse connectResponse = null;

            try {
                (new WebPermission(NetworkAccess.Connect, proxy)).Assert();
                try {
                    connectRequest = new HttpWebRequest(
                        proxy,
                        originalRequest.Address,
                       // new Uri("https://" + originalRequest.Address.GetParts(UriComponents.HostAndPort, UriFormat.UriEscaped)),
                        originalRequest
                        );
                }
                finally {
                    WebPermission.RevertAssert();
                }

                connectRequest.Credentials = originalRequest.InternalProxy == null ? null : originalRequest.InternalProxy.Credentials;
                connectRequest.InternalProxy = null;
                connectRequest.PreAuthenticate = true;

                if(async){
                    TunnelStateObject o = new TunnelStateObject(originalRequest, this);
                    IAsyncResult asyncResult = connectRequest.BeginGetResponse(m_TunnelCallback, o);
                    if(!asyncResult.CompletedSynchronously){
                        GlobalLog.Leave("Connection#" + ValidationHelper.HashString(this) + "::TunnelThroughProxy completed asynchronously", true);
                        return true;
                    }
                    connectResponse = (HttpWebResponse)connectRequest.EndGetResponse(asyncResult);
                }
                else{
                    connectResponse = (HttpWebResponse)connectRequest.GetResponse();
                }

                ConnectStream connectStream = (ConnectStream)connectResponse.GetResponseStream();

                // this stream will be used as the real stream for TlsStream
                NetworkStream = new NetworkStream(connectStream.Connection.NetworkStream, true);
                // This will orphan the original connect stream now owned by tunnelStream
                connectStream.Connection.NetworkStream.ConvertToNotSocketOwner();
                result = true;
            }
            catch (Exception exception) {
                if (m_InnerException == null)
                    m_InnerException = exception;
                GlobalLog.Print("Connection#" + ValidationHelper.HashString(this) + "::TunnelThroughProxy() exception occurred: " + exception);
            }

            GlobalLog.Leave("Connection#" + ValidationHelper.HashString(this) + "::TunnelThroughProxy", result);

            return result;
        }
        protected virtual void ProcessResponse(MvxRestRequest restRequest, HttpWebRequest httpRequest, Action<MvxRestResponse> successAction)
        {
            httpRequest.BeginGetResponse(result =>
            {
                var response = (HttpWebResponse)httpRequest.EndGetResponse(result);

                var code = response.StatusCode;

                var restResponse = new MvxRestResponse
                {
                    CookieCollection = response.Cookies,
                    Tag = restRequest.Tag,
                    StatusCode = code
                };
                successAction?.Invoke(restResponse);
            }, null);
        }
        /// <summary>
        /// Process the web response.
        /// </summary>
        /// <param name="webRequest">The request object.</param>
        /// <returns>The response data.</returns>
        public string WebResponseGet(HttpWebRequest webRequest)
        {
            string responseData = "";

            Exception asyncException = null;

            using (var resetEvent = new ManualResetEvent(/*initialStateSignaled:*/ false))
            {
                HttpWebResponse res = null;

                webRequest.BeginGetResponse(
                    new AsyncCallback(
                        ar =>
                        {
                            try
                            {
                                res = webRequest.EndGetResponse(ar) as HttpWebResponse;
                                using (var respStream = res.GetResponseStream())
                                {
                                    string contentEncoding = res.Headers["Content-Encoding"] ?? "";
                                    if (contentEncoding.ToLower().Contains("gzip"))
                                    {
                                        using (var gzip = new GZipStream(respStream, CompressionMode.Decompress))
                                        {
                                            using (var reader = new StreamReader(gzip))
                                            {
                                                responseData = reader.ReadToEnd();
                                            }
                                        }
                                    }
                                    else
                                    {
                                        using (var respReader = new StreamReader(respStream))
                                        {
                                            responseData = respReader.ReadToEnd();
                                        }
                                    }
                                }
                            }
                            catch (Exception ex)
                            {
                                asyncException = ex;
                            }
                            finally
                            {
                                resetEvent.Set();
                            }
                        }), null);

                resetEvent.WaitOne();
            }

            if (asyncException != null)
            {
                throw asyncException;
            }

            return responseData;
        }