private void HandleResponseError <TResponse>(Exception exception, AsyncState <TResponse> state) { var webEx = exception as WebException; if (webEx.IsWebException()) { var errorResponse = ((HttpWebResponse)webEx.Response); Log.Error(webEx); Log.DebugFormat("Status Code : {0}", errorResponse.StatusCode); Log.DebugFormat("Status Description : {0}", errorResponse.StatusDescription); var serviceEx = new WebServiceException(errorResponse.StatusDescription) { StatusCode = (int)errorResponse.StatusCode, }; try { using (var stream = errorResponse.GetResponseStream()) { //Uncomment to Debug exceptions: //var strResponse = new StreamReader(stream).ReadToEnd(); //Console.WriteLine("Response: " + strResponse); //stream.Position = 0; serviceEx.ResponseBody = stream.ReadFully().FromUtf8Bytes(); stream.ResetStream(); serviceEx.ResponseDto = this.StreamDeserializer(typeof(TResponse), stream); state.HandleError((TResponse)serviceEx.ResponseDto, serviceEx); } } catch (Exception innerEx) { // Oh, well, we tried Log.Debug(string.Format("WebException Reading Response Error: {0}", innerEx.Message), innerEx); state.HandleError(default(TResponse), new WebServiceException(errorResponse.StatusDescription, innerEx) { StatusCode = (int)errorResponse.StatusCode, }); } return; } var authEx = exception as AuthenticationException; if (authEx != null) { var customEx = WebRequestUtils.CreateCustomException(state.Url, authEx); Log.Debug(string.Format("AuthenticationException: {0}", customEx.Message), customEx); state.HandleError(default(TResponse), authEx); } Log.Debug(string.Format("Exception Reading Response Error: {0}", exception.Message), exception); state.HandleError(default(TResponse), exception); CancelAsyncFn = null; }
internal static ITimer CreateTimer <TResponse>(this AsyncState <TResponse> state, TimeSpan timeOut) { #if NETFX_CORE return(new NetFxAsyncTimer(ThreadPoolTimer.CreateTimer(request.TimedOut, timeOut))); #else return(new AsyncTimer(new Timer(state.TimedOut, state, (int)timeOut.TotalMilliseconds, Timeout.Infinite))); #endif }
private void SendWebRequestAsync <TResponse>(string httpMethod, object request, AsyncState <TResponse> state, HttpWebRequest client) { client.Accept = ContentType; if (this.EmulateHttpViaPost) { client.Method = "POST"; client.Headers[HttpHeaders.XHttpMethodOverride] = httpMethod; } else { client.Method = httpMethod; } PclExportClient.Instance.AddHeader(client, Headers); //EmulateHttpViaPost is also forced for SL5 clients sending non GET/POST requests PclExport.Instance.Config(client, userAgent: UserAgent); if (this.authInfo != null && !string.IsNullOrEmpty(this.UserName)) { client.AddAuthInfo(this.UserName, this.Password, authInfo); } else if (this.BearerToken != null) { client.Headers[HttpHeaders.Authorization] = "Bearer " + this.BearerToken; } else if (this.Credentials != null) { client.Credentials = this.Credentials; } else if (this.AlwaysSendBasicAuthHeader) { client.AddBasicAuth(this.UserName, this.Password); } ApplyWebRequestFilters(client); try { if (client.Method.HasRequestBody()) { client.ContentType = ContentType; client.BeginGetRequestStream(RequestCallback <TResponse>, state); } else { state.WebRequest.BeginGetResponse(ResponseCallback <TResponse>, state); } } catch (Exception ex) { // BeginGetRequestStream can throw if request was aborted HandleResponseError(ex, state); } }
private void SendWebRequestAsync <TResponse>(string httpMethod, object request, AsyncState <TResponse> state, HttpWebRequest webRequest) { var httpGetOrDeleteOrHead = (httpMethod == "GET" || httpMethod == "DELETE" || httpMethod == "HEAD"); webRequest.Accept = string.Format("{0}, */*", ContentType); //Methods others than GET and POST are only supported by Client request creator, see //http://msdn.microsoft.com/en-us/library/cc838250(v=vs.95).aspx if (this.EmulateHttpViaPost && httpMethod != "GET" && httpMethod != "POST") { webRequest.Method = "POST"; webRequest.Headers[HttpHeaders.XHttpMethodOverride] = httpMethod; } else { webRequest.Method = httpMethod; } PclExportClient.Instance.AddHeader(webRequest, Headers); PclExport.Instance.Config(webRequest, userAgent: UserAgent); if (this.Credentials != null) { webRequest.Credentials = this.Credentials; } if (this.AlwaysSendBasicAuthHeader) { webRequest.AddBasicAuth(this.UserName, this.Password); } ApplyWebRequestFilters(webRequest); try { if (!httpGetOrDeleteOrHead && request != null) { webRequest.ContentType = ContentType; webRequest.BeginGetRequestStream(RequestCallback <TResponse>, state); } else { state.WebRequest.BeginGetResponse(ResponseCallback <TResponse>, state); } } catch (Exception ex) { // BeginGetRequestStream can throw if request was aborted HandleResponseError(ex, state); } }
private void SendWebRequestAsync <TResponse>(string httpMethod, object request, AsyncState <TResponse> state, HttpWebRequest webRequest) { webRequest.Accept = string.Format("{0}, */*", ContentType); if (this.EmulateHttpViaPost) { webRequest.Method = "POST"; webRequest.Headers[HttpHeaders.XHttpMethodOverride] = httpMethod; } else { webRequest.Method = httpMethod; } PclExportClient.Instance.AddHeader(webRequest, Headers); //EmulateHttpViaPost is also forced for SL5 clients sending non GET/POST requests PclExport.Instance.Config(webRequest, userAgent: UserAgent); if (this.Credentials != null) { webRequest.Credentials = this.Credentials; } if (this.AlwaysSendBasicAuthHeader) { webRequest.AddBasicAuth(this.UserName, this.Password); } ApplyWebRequestFilters(webRequest); try { if (webRequest.Method.HasRequestBody()) { webRequest.ContentType = ContentType; webRequest.BeginGetRequestStream(RequestCallback <TResponse>, state); } else { state.WebRequest.BeginGetResponse(ResponseCallback <TResponse>, state); } } catch (Exception ex) { // BeginGetRequestStream can throw if request was aborted HandleResponseError(ex, state); } }
private void SendWebRequest <TResponse>(string httpMethod, string absoluteUrl, object request, CancellationToken token, Action <TResponse> onSuccess, Action <object, Exception> onError, Action <WebResponse> onResponseInit = null) { if (httpMethod == null) { throw new ArgumentNullException(nameof(httpMethod)); } this.PopulateRequestMetadata(request); var requestUri = absoluteUrl; var hasQueryString = request != null && !httpMethod.HasRequestBody(); if (hasQueryString) { var queryString = QueryStringSerializer.SerializeToString(request); if (!string.IsNullOrEmpty(queryString)) { requestUri += "?" + queryString; } } var webRequest = this.CreateHttpWebRequest(requestUri); var requestState = new AsyncState <TResponse>(BufferSize) { HttpMethod = httpMethod, Url = requestUri, WebRequest = webRequest, Request = request, Token = token, OnResponseInit = onResponseInit, OnSuccess = onSuccess, OnError = onError, UseSynchronizationContext = CaptureSynchronizationContext ? SynchronizationContext.Current : null, HandleCallbackOnUIThread = HandleCallbackOnUiThread, }; if (!DisableTimer) { requestState.StartTimer(this.Timeout.GetValueOrDefault(DefaultTimeout)); } SendWebRequestAsync(httpMethod, request, requestState, webRequest); }
private void SendWebRequest <TResponse>(string httpMethod, string absoluteUrl, object request, Action <TResponse> onSuccess, Action <TResponse, Exception> onError) { if (httpMethod == null) { throw new ArgumentNullException("httpMethod"); } var requestUri = absoluteUrl; var httpGetOrDeleteOrHead = (httpMethod == "GET" || httpMethod == "DELETE" || httpMethod == "HEAD"); var hasQueryString = request != null && httpGetOrDeleteOrHead; if (hasQueryString) { var queryString = QueryStringSerializer.SerializeToString(request); if (!string.IsNullOrEmpty(queryString)) { requestUri += "?" + queryString; } } var webRequest = this.CreateHttpWebRequest(requestUri); var requestState = new AsyncState <TResponse>(BufferSize) { HttpMethod = httpMethod, Url = requestUri, WebRequest = webRequest, Request = request, OnSuccess = onSuccess, OnError = onError, UseSynchronizationContext = CaptureSynchronizationContext ? SynchronizationContext.Current : null, HandleCallbackOnUIThread = HandleCallbackOnUiThread, }; requestState.StartTimer(this.Timeout.GetValueOrDefault(DefaultTimeout)); SendWebRequestAsync(httpMethod, request, requestState, webRequest); }
public override ITimer CreateTimer <TResponse>(AsyncState <TResponse> state, TimeSpan timeOut) { return(new AsyncTimer(new System.Threading.Timer(state.TimedOut, state, (int)timeOut.TotalMilliseconds, Timeout.Infinite))); }
private void HandleResponseError <TResponse>(Exception exception, AsyncState <TResponse> state) { var webEx = exception as WebException; if (PclExportClient.Instance.IsWebException(webEx)) { var errorResponse = (HttpWebResponse)webEx.Response; Log.Error(webEx); if (Log.IsDebugEnabled) { Log.DebugFormat("Status Code : {0}", errorResponse.StatusCode); Log.DebugFormat("Status Description : {0}", errorResponse.StatusDescription); } var serviceEx = new WebServiceException(errorResponse.StatusDescription) { StatusCode = (int)errorResponse.StatusCode, StatusDescription = errorResponse.StatusDescription, ResponseHeaders = errorResponse.Headers }; try { using (var stream = errorResponse.GetResponseStream()) { var bytes = stream.ReadFully(); serviceEx.ResponseBody = bytes.FromUtf8Bytes(); var errorResponseType = WebRequestUtils.GetErrorResponseDtoType <TResponse>(state.Request); if (stream.CanSeek) { PclExport.Instance.ResetStream(stream); serviceEx.ResponseDto = this.StreamDeserializer(errorResponseType, stream); } else //Android { using (var ms = MemoryStreamFactory.GetStream(bytes)) { serviceEx.ResponseDto = this.StreamDeserializer(errorResponseType, ms); } } state.HandleError(serviceEx.ResponseDto, serviceEx); } } catch (Exception innerEx) { // Oh, well, we tried Log.Debug(string.Format("WebException Reading Response Error: {0}", innerEx.Message), innerEx); state.HandleError(default(TResponse), new WebServiceException(errorResponse.StatusDescription, innerEx) { StatusCode = (int)errorResponse.StatusCode, StatusDescription = errorResponse.StatusDescription, ResponseHeaders = errorResponse.Headers }); } return; } var authEx = exception as AuthenticationException; if (authEx != null) { var customEx = WebRequestUtils.CreateCustomException(state.Url, authEx); Log.Debug(string.Format("AuthenticationException: {0}", customEx.Message), customEx); state.HandleError(default(TResponse), authEx); } Log.Debug(string.Format("Exception Reading Response Error: {0}", exception.Message), exception); state.HandleError(default(TResponse), exception); CancelAsyncFn = null; }
private void ReadCallBack <T>(Task <int> task, AsyncState <T> requestState) { task.ContinueWith(t => { try { var responseStream = requestState.ResponseStream; int read = t.Result; if (read > 0) { requestState.BytesData.Write(requestState.BufferRead, 0, read); var responeStreamTask = responseStream.ReadAsync(requestState.BufferRead, 0, BufferSize); requestState.ResponseBytesRead += read; if (OnDownloadProgress != null) { OnDownloadProgress(requestState.ResponseBytesRead, requestState.ResponseContentLength); } ReadCallBack(responeStreamTask, requestState); return; } Interlocked.Increment(ref requestState.Completed); var response = default(T); try { requestState.BytesData.Position = 0; if (typeof(T) == typeof(Stream)) { response = (T)(object)requestState.BytesData; } else { var reader = requestState.BytesData; try { if (typeof(T) == typeof(string)) { using (var sr = new StreamReader(reader)) { response = (T)(object)sr.ReadToEnd(); } } else if (typeof(T) == typeof(byte[])) { response = (T)(object)reader.ToArray(); } else { response = (T)this.StreamDeserializer(typeof(T), reader); } } finally { if (reader.CanRead) { reader.Dispose(); // Not yet disposed, but could've been. } } } PclExportClient.Instance.SynchronizeCookies(this); requestState.HandleSuccess(response); } catch (Exception ex) { Log.Debug(string.Format("Error Reading Response Error: {0}", ex.Message), ex); requestState.HandleError(default(T), ex); } finally { PclExportClient.Instance.CloseReadStream(responseStream); CancelAsyncFn = null; } } catch (Exception ex) { HandleResponseError(ex, requestState); } }); }
internal static ITimer CreateTimer <TResponse>(this AsyncState <TResponse> state, TimeSpan timeOut) { return(PclExportClient.Instance.CreateTimer(state.TimedOut, timeOut, state)); }
public override ITimer CreateTimer <TResponse>(AsyncState <TResponse> state, TimeSpan timeOut) { return(new WinStoreAsyncTimer(ThreadPoolTimer.CreateTimer(state.TimedOut, timeOut))); }