async Task <string> IPubnubHttp.SendRequestAndGetJsonResponse <T>(Uri requestUri, RequestState <T> pubnubRequestState, HttpWebRequest request) { if (pubnubConfig.UseClassicHttpWebRequest) { return(await SendRequestAndGetJsonResponseClassicHttp(requestUri, pubnubRequestState, request).ConfigureAwait(false)); } else { #if !NET35 && !NET40 && !NET45 && !NET461 && !NETSTANDARD10 if (pubnubConfig.UseTaskFactoryAsyncInsteadOfHttpClient) { return(await SendRequestAndGetJsonResponseTaskFactory(pubnubRequestState, request).ConfigureAwait(false)); } else { return(await SendRequestAndGetJsonResponseHttpClient(requestUri, pubnubRequestState, request).ConfigureAwait(false)); } #else return(await SendRequestAndGetJsonResponseTaskFactory(pubnubRequestState, request).ConfigureAwait(false)); #endif } }
public PNStatus CreateStatusResponse <T>(PNOperationType type, PNStatusCategory category, RequestState <T> asyncRequestState, int statusCode, PNException throwable) { int serverErrorStatusCode = 0; bool serverErrorMessage = false; List <string> serverAffectedChannels = null; List <string> serverAffectedChannelGroups = null; PNStatus status = new PNStatus(asyncRequestState != null ? asyncRequestState.EndPointOperation : null); status.Category = category; status.Operation = type; if ((asyncRequestState != null && !asyncRequestState.GotJsonResponse) || throwable != null) { status.Error = true; } Exception targetException = null; if (throwable != null) { if (throwable.DirectException) { targetException = throwable.InnerException; } else { targetException = throwable as Exception; } } if (targetException != null) { if (targetException.InnerException != null) { PNErrorData errorData = new PNErrorData(jsonLibrary.SerializeToJsonString(targetException.InnerException.Message), targetException); status.ErrorData = errorData; } else { Dictionary <string, object> deserializeStatus = jsonLibrary.DeserializeToDictionaryOfObject(targetException.Message); if (deserializeStatus != null && deserializeStatus.Count >= 1 && deserializeStatus.ContainsKey("error") && string.Equals(deserializeStatus["error"].ToString(), "true", StringComparison.CurrentCultureIgnoreCase) && deserializeStatus.ContainsKey("status") && Int32.TryParse(deserializeStatus["status"].ToString(), out serverErrorStatusCode)) { serverErrorMessage = true; if (deserializeStatus.ContainsKey("payload")) { Dictionary <string, object> payloadDic = jsonLibrary.ConvertToDictionaryObject(deserializeStatus["payload"]); if (payloadDic != null && payloadDic.Count > 0) { if (payloadDic.ContainsKey("channels")) { object[] chDic = jsonLibrary.ConvertToObjectArray(payloadDic["channels"]); if (chDic != null && chDic.Length > 0) { serverAffectedChannels = chDic.Select(x => x.ToString()).ToList(); } } if (payloadDic.ContainsKey("channel-groups")) { object[] cgDic = jsonLibrary.ConvertToObjectArray(payloadDic["channel-groups"]); if (cgDic != null && cgDic.Length > 0) { serverAffectedChannelGroups = cgDic.Select(x => x.ToString()).ToList(); } } } } } PNErrorData errorData = new PNErrorData(jsonLibrary.SerializeToJsonString(targetException.Message), targetException); status.ErrorData = errorData; } } if (asyncRequestState != null) { if (asyncRequestState.Request != null) { status.ClientRequest = asyncRequestState.Request; HttpValueCollection restUriQueryCollection = HttpUtility.ParseQueryString(asyncRequestState.Request.RequestUri.Query); if (restUriQueryCollection.ContainsKey("auth")) { string auth = restUriQueryCollection["auth"]; status.AuthKey = auth; } if (restUriQueryCollection.ContainsKey("uuid")) { string uuid = restUriQueryCollection["uuid"]; status.Uuid = uuid; } } if (serverErrorMessage && serverErrorStatusCode > 0) { status.StatusCode = serverErrorStatusCode; } else if (asyncRequestState.Response != null) { status.StatusCode = (int)asyncRequestState.Response.StatusCode; } else { status.StatusCode = statusCode; } if (serverErrorMessage) { status.AffectedChannels = serverAffectedChannels; status.AffectedChannelGroups = serverAffectedChannelGroups; } else { if (asyncRequestState.ChannelGroups != null) { status.AffectedChannelGroups = asyncRequestState.ChannelGroups.ToList <string>(); } if (asyncRequestState.Channels != null) { status.AffectedChannels = asyncRequestState.Channels.ToList <string>(); } } } else { status.StatusCode = statusCode; } if (status.StatusCode == 403) { status.Category = PNStatusCategory.PNAccessDeniedCategory; } status.Origin = config.Origin; status.TlsEnabled = config.Secure; return(status); }
async Task <string> SendRequestAndGetJsonResponseTaskFactoryWithPOST <T>(RequestState <T> pubnubRequestState, HttpWebRequest request, string postData) { System.Diagnostics.Debug.WriteLine(string.Format("DateTime {0}, Before Task.Factory.FromAsync With POST", DateTime.Now.ToString(CultureInfo.InvariantCulture))); try { request.Method = "POST"; Timer webRequestTimer = new Timer(OnPubnubWebRequestTimeout <T>, pubnubRequestState, GetTimeoutInSecondsForResponseType(pubnubRequestState.ResponseType) * 1000, Timeout.Infinite); System.Diagnostics.Stopwatch stopWatch = new System.Diagnostics.Stopwatch(); stopWatch.Start(); request.ContentType = "application/json"; byte[] data = Encoding.UTF8.GetBytes(postData); using (var requestStream = await Task <Stream> .Factory.FromAsync(request.BeginGetRequestStream, request.EndGetRequestStream, pubnubRequestState).ConfigureAwait(false)) { #if NET35 || NET40 requestStream.Write(data, 0, data.Length); requestStream.Flush(); #else await requestStream.WriteAsync(data, 0, data.Length).ConfigureAwait(false); await requestStream.FlushAsync().ConfigureAwait(false); #endif } WebResponse response = await Task.Factory.FromAsync(request.BeginGetResponse, request.EndGetResponse, pubnubRequestState).ConfigureAwait(false); stopWatch.Stop(); if (pubnubTelemetryMgr != null) { await pubnubTelemetryMgr.StoreLatency(stopWatch.ElapsedMilliseconds, pubnubRequestState.ResponseType); } pubnubRequestState.Response = response as HttpWebResponse; System.Diagnostics.Debug.WriteLine(string.Format("DateTime {0}, Got PubnubWebResponse With POST for {1}", DateTime.Now.ToString(CultureInfo.InvariantCulture), request.RequestUri.ToString())); using (StreamReader streamReader = new StreamReader(response.GetResponseStream())) { //Need to return this response #if NET35 || NET40 string jsonString = streamReader.ReadToEnd(); #else string jsonString = await streamReader.ReadToEndAsync().ConfigureAwait(false); #endif System.Diagnostics.Debug.WriteLine(jsonString); System.Diagnostics.Debug.WriteLine(""); System.Diagnostics.Debug.WriteLine(string.Format("DateTime {0}, Retrieved JSON With POST", DateTime.Now.ToString(CultureInfo.InvariantCulture))); pubnubRequestState.GotJsonResponse = true; if (pubnubRequestState.Response != null) { #if NET35 || NET40 || NET45 || NET461 pubnubRequestState.Response.Close(); #endif pubnubRequestState.Response = null; pubnubRequestState.Request = null; } return(jsonString); } } catch (WebException ex) { if (ex.Response != null) { pubnubRequestState.Response = ex.Response as HttpWebResponse; using (StreamReader streamReader = new StreamReader(ex.Response.GetResponseStream())) { //Need to return this response #if NET35 || NET40 string jsonString = streamReader.ReadToEnd(); #else string jsonString = await streamReader.ReadToEndAsync().ConfigureAwait(false); #endif System.Diagnostics.Debug.WriteLine(jsonString); System.Diagnostics.Debug.WriteLine(""); System.Diagnostics.Debug.WriteLine(string.Format("DateTime {0}, Retrieved JSON With POST from WebException response", DateTime.Now.ToString(CultureInfo.InvariantCulture))); return(jsonString); } } if (ex.Message.IndexOf("The request was aborted: The request was canceled") == -1 && ex.Message.IndexOf("Machine suspend mode enabled. No request will be processed.") == -1) { throw; } return(""); } catch { throw; } }
async Task <string> SendRequestAndGetJsonResponseClassicHttpWithPOST <T>(Uri requestUri, RequestState <T> pubnubRequestState, HttpWebRequest request, string postData) { LoggingMethod.WriteToLog(pubnubLog, string.Format("DateTime: {0}, Inside SendRequestAndGetJsonResponseClassicHttpWithPOST", DateTime.Now.ToString(CultureInfo.InvariantCulture)), pubnubConfig.LogVerbosity); var taskComplete = new TaskCompletionSource <string>(); try { request.Method = "POST"; request.ContentType = "application/json"; byte[] data = Encoding.UTF8.GetBytes(postData); System.Diagnostics.Stopwatch stopWatch = new System.Diagnostics.Stopwatch(); stopWatch.Start(); #if !NET35 && !NET40 && !NET45 && !NET461 using (var requestStream = await Task <Stream> .Factory.FromAsync(request.BeginGetRequestStream, request.EndGetRequestStream, pubnubRequestState).ConfigureAwait(false)) { requestStream.Write(data, 0, data.Length); requestStream.Flush(); } #else using (var requestStream = request.GetRequestStream()) { requestStream.Write(data, 0, data.Length); requestStream.Flush(); } #endif IAsyncResult asyncResult = request.BeginGetResponse(new AsyncCallback( async(asynchronousResult) => { RequestState <T> asyncRequestState = asynchronousResult.AsyncState as RequestState <T>; HttpWebRequest asyncWebRequest = asyncRequestState.Request as HttpWebRequest; if (asyncWebRequest != null) { System.Diagnostics.Debug.WriteLine(string.Format("DateTime {0}, Before EndGetResponse With POST ", DateTime.Now.ToString(CultureInfo.InvariantCulture))); HttpWebResponse asyncWebResponse = (HttpWebResponse)asyncWebRequest.EndGetResponse(asynchronousResult); stopWatch.Stop(); if (pubnubTelemetryMgr != null) { await pubnubTelemetryMgr.StoreLatency(stopWatch.ElapsedMilliseconds, pubnubRequestState.ResponseType); } asyncRequestState.Response = asyncWebResponse; System.Diagnostics.Debug.WriteLine(string.Format("DateTime {0}, After EndGetResponse With POST ", DateTime.Now.ToString(CultureInfo.InvariantCulture))); using (StreamReader streamReader = new StreamReader(asyncWebResponse.GetResponseStream())) { System.Diagnostics.Debug.WriteLine(string.Format("DateTime {0}, Inside StreamReader With POST ", DateTime.Now.ToString(CultureInfo.InvariantCulture))); //Need to return this response string jsonString = streamReader.ReadToEnd(); asyncRequestState.GotJsonResponse = true; System.Diagnostics.Debug.WriteLine(jsonString); System.Diagnostics.Debug.WriteLine(""); System.Diagnostics.Debug.WriteLine(string.Format("DateTime {0}, Retrieved JSON With POST ", DateTime.Now.ToString(CultureInfo.InvariantCulture))); taskComplete.TrySetResult(jsonString); } if (asyncRequestState.Response != null) { #if NET35 || NET40 || NET45 || NET461 pubnubRequestState.Response.Close(); #endif asyncRequestState.Response = null; asyncRequestState.Request = null; } } } ), pubnubRequestState); Timer webRequestTimer = new Timer(OnPubnubWebRequestTimeout <T>, pubnubRequestState, GetTimeoutInSecondsForResponseType(pubnubRequestState.ResponseType) * 1000, Timeout.Infinite); return(taskComplete.Task.Result); } catch (WebException ex) { if (ex.Response != null) { pubnubRequestState.Response = ex.Response as HttpWebResponse; using (StreamReader streamReader = new StreamReader(ex.Response.GetResponseStream())) { //Need to return this response #if NET35 || NET40 await Task.Factory.StartNew(() => { }); string jsonString = streamReader.ReadToEnd(); #else string jsonString = await streamReader.ReadToEndAsync().ConfigureAwait(false); #endif System.Diagnostics.Debug.WriteLine(jsonString); System.Diagnostics.Debug.WriteLine(""); System.Diagnostics.Debug.WriteLine(string.Format("DateTime {0}, Retrieved JSON With POST from WebException response", DateTime.Now.ToString(CultureInfo.InvariantCulture))); return(jsonString); } } if (ex.Message.IndexOf("The request was aborted: The request was canceled") == -1 && ex.Message.IndexOf("Machine suspend mode enabled. No request will be processed.") == -1) { taskComplete.TrySetException(ex); } return(""); } catch (Exception ex) { taskComplete.TrySetException(ex); return(""); } }
async Task <string> SendRequestAndGetJsonResponseHttpClientWithPOST <T>(Uri requestUri, RequestState <T> pubnubRequestState, HttpWebRequest request, string postData) { string jsonString = ""; HttpResponseMessage response = null; CancellationTokenSource cts = new CancellationTokenSource(); try { System.Diagnostics.Debug.WriteLine(string.Format("DateTime {0}, SendRequestAndGetJsonResponseHttpClientPOST Before httpClient.GetAsync", DateTime.Now.ToString(CultureInfo.InvariantCulture))); cts.CancelAfter(GetTimeoutInSecondsForResponseType(pubnubRequestState.ResponseType) * 1000); System.Diagnostics.Stopwatch stopWatch = new System.Diagnostics.Stopwatch(); stopWatch.Start(); StringContent jsonPostString = new StringContent(postData, Encoding.UTF8); if (pubnubRequestState.ResponseType == PNOperationType.PNSubscribeOperation) { response = await httpClientSubscribe.PostAsync(requestUri, jsonPostString, cts.Token).ConfigureAwait(false); } else { response = await httpClientNonsubscribe.PostAsync(requestUri, jsonPostString, cts.Token).ConfigureAwait(false); } if (response.IsSuccessStatusCode || response.Content != null) { var stream = await response.Content.ReadAsStreamAsync().ConfigureAwait(false); stopWatch.Stop(); if (pubnubTelemetryMgr != null) { await pubnubTelemetryMgr.StoreLatency(stopWatch.ElapsedMilliseconds, pubnubRequestState.ResponseType); } using (StreamReader streamReader = new StreamReader(stream)) { jsonString = await streamReader.ReadToEndAsync().ConfigureAwait(false); pubnubRequestState.GotJsonResponse = true; } System.Diagnostics.Debug.WriteLine(string.Format("DateTime {0}, Got POST HttpResponseMessage for {1}", DateTime.Now.ToString(CultureInfo.InvariantCulture), requestUri)); } else { stopWatch.Stop(); System.Diagnostics.Debug.WriteLine(string.Format("DateTime {0}, No POST HttpResponseMessage for {1}", DateTime.Now.ToString(CultureInfo.InvariantCulture), requestUri)); } } catch (HttpRequestException httpReqEx) { if (httpReqEx.InnerException is WebException) { WebException currentWebException = httpReqEx.InnerException as WebException; if (currentWebException != null) { if (currentWebException.Response != null) { pubnubRequestState.Response = currentWebException.Response as HttpWebResponse; using (StreamReader streamReader = new StreamReader(currentWebException.Response.GetResponseStream())) { //Need to return this response jsonString = await streamReader.ReadToEndAsync().ConfigureAwait(false); System.Diagnostics.Debug.WriteLine(jsonString); System.Diagnostics.Debug.WriteLine(""); System.Diagnostics.Debug.WriteLine(string.Format("DateTime {0}, Retrieved JSON from HttpClient POST WebException response", DateTime.Now.ToString(CultureInfo.InvariantCulture))); return(jsonString); } } } LoggingMethod.WriteToLog(pubnubLog, string.Format("DateTime: {0}, SendRequestAndGetJsonResponseHttpClientPOST InnerException WebException status {1}", DateTime.Now.ToString(CultureInfo.InvariantCulture), ((WebException)httpReqEx.InnerException).Status.ToString()), pubnubConfig.LogVerbosity); throw httpReqEx.InnerException; } LoggingMethod.WriteToLog(pubnubLog, string.Format("DateTime: {0}, SendRequestAndGetJsonResponseHttpClientPOST HttpRequestException {1}", DateTime.Now.ToString(CultureInfo.InvariantCulture), httpReqEx.Message), pubnubConfig.LogVerbosity); throw; } catch (Exception ex) { LoggingMethod.WriteToLog(pubnubLog, string.Format("DateTime: {0}, SendRequestAndGetJsonResponseHttpClientPOST Exception {1}", DateTime.Now.ToString(CultureInfo.InvariantCulture), ex.Message), pubnubConfig.LogVerbosity); throw; } finally { if (response != null && response.Content != null) { response.Content.Dispose(); pubnubRequestState.Response = null; pubnubRequestState.Request = null; } } return(jsonString); }
async Task <string> SendRequestAndGetJsonResponseTaskFactory <T>(RequestState <T> pubnubRequestState, HttpWebRequest request) { HttpWebResponse response = null; LoggingMethod.WriteToLog(pubnubLog, string.Format("DateTime: {0}, Inside SendRequestAndGetJsonResponseTaskFactory", DateTime.Now.ToString(CultureInfo.InvariantCulture)), pubnubConfig.LogVerbosity); try { request.Method = (pubnubRequestState != null && pubnubRequestState.ResponseType == PNOperationType.PNDeleteMessageOperation) ? "DELETE" : "GET"; new Timer(OnPubnubWebRequestTimeout <T>, pubnubRequestState, GetTimeoutInSecondsForResponseType(pubnubRequestState.ResponseType) * 1000, Timeout.Infinite); System.Diagnostics.Stopwatch stopWatch = new System.Diagnostics.Stopwatch(); stopWatch.Start(); response = await Task.Factory.FromAsync <HttpWebResponse>(request.BeginGetResponse, asyncPubnubResult => (HttpWebResponse)request.EndGetResponse(asyncPubnubResult), pubnubRequestState).ConfigureAwait(false); stopWatch.Stop(); if (pubnubConfig.EnableTelemetry && pubnubTelemetryMgr != null) { await pubnubTelemetryMgr.StoreLatency(stopWatch.ElapsedMilliseconds, pubnubRequestState.ResponseType); } pubnubRequestState.Response = response; System.Diagnostics.Debug.WriteLine(string.Format("DateTime {0}, Got PubnubWebResponse for {1}", DateTime.Now.ToString(CultureInfo.InvariantCulture), request.RequestUri.ToString())); using (StreamReader streamReader = new StreamReader(response.GetResponseStream())) { //Need to return this response #if NET35 || NET40 string jsonString = streamReader.ReadToEnd(); #else string jsonString = await streamReader.ReadToEndAsync().ConfigureAwait(false); #endif System.Diagnostics.Debug.WriteLine(jsonString); pubnubRequestState.GotJsonResponse = true; System.Diagnostics.Debug.WriteLine(""); System.Diagnostics.Debug.WriteLine(string.Format("DateTime {0}, Retrieved JSON", DateTime.Now.ToString(CultureInfo.InvariantCulture))); if (pubnubRequestState.Response != null) { #if NET35 || NET40 || NET45 || NET461 pubnubRequestState.Response.Close(); #endif pubnubRequestState.Response = null; pubnubRequestState.Request = null; } return(jsonString); } } catch (WebException ex) { if (ex.Response != null) { pubnubRequestState.Response = ex.Response as HttpWebResponse; using (StreamReader streamReader = new StreamReader(ex.Response.GetResponseStream())) { //Need to return this response #if NET35 || NET40 string jsonString = streamReader.ReadToEnd(); #else string jsonString = await streamReader.ReadToEndAsync().ConfigureAwait(false); #endif System.Diagnostics.Debug.WriteLine(jsonString); System.Diagnostics.Debug.WriteLine(""); System.Diagnostics.Debug.WriteLine(string.Format("DateTime {0}, Retrieved JSON from WebException response", DateTime.Now.ToString(CultureInfo.InvariantCulture))); return(jsonString); } } if (ex.Message.IndexOf("The request was aborted: The request was canceled") == -1 && ex.Message.IndexOf("Machine suspend mode enabled. No request will be processed.") == -1) { throw; } return(""); } catch { throw; } }
async Task <string> SendRequestAndGetJsonResponseClassicHttp <T>(Uri requestUri, RequestState <T> pubnubRequestState, HttpWebRequest request) { //HttpWebResponse response = null; LoggingMethod.WriteToLog(string.Format("DateTime: {0}, Inside SendRequestAndGetJsonResponseClassicHttp", DateTime.Now.ToString()), pubnubConfig.LogVerbosity); var taskComplete = new TaskCompletionSource <string>(); try { request.Method = "GET"; System.Diagnostics.Debug.WriteLine(string.Format("DateTime {0}, Before BeginGetResponse", DateTime.Now.ToString())); IAsyncResult asyncResult = request.BeginGetResponse(new AsyncCallback( (asynchronousResult) => { RequestState <T> asyncRequestState = asynchronousResult.AsyncState as RequestState <T>; HttpWebRequest asyncWebRequest = asyncRequestState.Request as HttpWebRequest; if (asyncWebRequest != null) { System.Diagnostics.Debug.WriteLine(string.Format("DateTime {0}, Before EndGetResponse", DateTime.Now.ToString())); HttpWebResponse asyncWebResponse = (HttpWebResponse)asyncWebRequest.EndGetResponse(asynchronousResult); asyncRequestState.Response = asyncWebResponse; System.Diagnostics.Debug.WriteLine(string.Format("DateTime {0}, After EndGetResponse", DateTime.Now.ToString())); using (StreamReader streamReader = new StreamReader(asyncWebResponse.GetResponseStream())) { System.Diagnostics.Debug.WriteLine(string.Format("DateTime {0}, Inside StreamReader", DateTime.Now.ToString())); //Need to return this response string jsonString = streamReader.ReadToEnd(); asyncRequestState.GotJsonResponse = true; System.Diagnostics.Debug.WriteLine(jsonString); System.Diagnostics.Debug.WriteLine(""); System.Diagnostics.Debug.WriteLine(string.Format("DateTime {0}, Retrieved JSON", DateTime.Now.ToString())); taskComplete.TrySetResult(jsonString); } if (asyncRequestState.Response != null) { #if NET35 || NET40 || NET45 || NET461 pubnubRequestState.Response.Close(); #endif asyncRequestState.Response = null; asyncRequestState.Request = null; } } } ), pubnubRequestState); Timer webRequestTimer = new Timer(OnPubnubWebRequestTimeout <T>, pubnubRequestState, GetTimeoutInSecondsForResponseType(pubnubRequestState.ResponseType) * 1000, Timeout.Infinite); return(taskComplete.Task.Result); } catch (WebException ex) { if (ex.Response != null) { pubnubRequestState.Response = ex.Response as HttpWebResponse; using (StreamReader streamReader = new StreamReader(ex.Response.GetResponseStream())) { //Need to return this response #if NET35 await Task.Factory.StartNew(() => { }); string jsonString = streamReader.ReadToEnd(); #else string jsonString = await streamReader.ReadToEndAsync(); #endif System.Diagnostics.Debug.WriteLine(jsonString); System.Diagnostics.Debug.WriteLine(""); System.Diagnostics.Debug.WriteLine(string.Format("DateTime {0}, Retrieved JSON from WebException response", DateTime.Now.ToString())); return(jsonString); } } if (ex.Message.IndexOf("The request was aborted: The request was canceled") == -1 && ex.Message.IndexOf("Machine suspend mode enabled. No request will be processed.") == -1) { taskComplete.TrySetException(ex); } return(""); } catch (Exception ex) { taskComplete.TrySetException(ex); return(""); } }
async Task <string> IPubnubHttp.SendRequestAndGetJsonResponseWithPOST <T>(Uri requestUri, RequestState <T> pubnubRequestState, HttpWebRequest request, string postData) { if (pubnubConfig.UseClassicHttpWebRequest) { return(await SendRequestAndGetJsonResponseClassicHttpWithPOST(requestUri, pubnubRequestState, request, postData)); } else { #if !NET35 && !NET40 && !NET45 && !NET461 && !NETSTANDARD10 return(await SendRequestAndGetJsonResponseHttpClientWithPOST(requestUri, pubnubRequestState, request, postData)); #else return(await SendRequestAndGetJsonResponseTaskFactoryWithPOST(requestUri, pubnubRequestState, request, postData)); #endif } }
async Task <string> SendRequestAndGetJsonResponseTaskFactory <T>(Uri requestUri, RequestState <T> pubnubRequestState, HttpWebRequest request) { HttpWebResponse response = null; LoggingMethod.WriteToLog(string.Format("DateTime: {0}, Inside SendRequestAndGetJsonResponseTaskFactory", DateTime.Now.ToString()), pubnubConfig.LogVerbosity); try { request.Method = "GET"; response = await Task.Factory.FromAsync <HttpWebResponse>(request.BeginGetResponse, asyncPubnubResult => (HttpWebResponse)request.EndGetResponse(asyncPubnubResult), pubnubRequestState); pubnubRequestState.Response = response; System.Diagnostics.Debug.WriteLine(string.Format("DateTime {0}, Got PubnubWebResponse for {1}", DateTime.Now.ToString(), request.RequestUri.ToString())); using (StreamReader streamReader = new StreamReader(response.GetResponseStream())) { //Need to return this response #if NET35 string jsonString = streamReader.ReadToEnd(); #else string jsonString = await streamReader.ReadToEndAsync(); #endif System.Diagnostics.Debug.WriteLine(jsonString); pubnubRequestState.GotJsonResponse = true; System.Diagnostics.Debug.WriteLine(""); System.Diagnostics.Debug.WriteLine(string.Format("DateTime {0}, Retrieved JSON", DateTime.Now.ToString())); if (pubnubRequestState.Response != null) { #if NET35 || NET40 || NET45 || NET461 pubnubRequestState.Response.Close(); #endif pubnubRequestState.Response = null; pubnubRequestState.Request = null; } return(jsonString); } } catch (WebException ex) { if (ex.Response != null) { pubnubRequestState.Response = ex.Response as HttpWebResponse; using (StreamReader streamReader = new StreamReader(ex.Response.GetResponseStream())) { //Need to return this response #if NET35 string jsonString = streamReader.ReadToEnd(); #else string jsonString = await streamReader.ReadToEndAsync(); #endif System.Diagnostics.Debug.WriteLine(jsonString); System.Diagnostics.Debug.WriteLine(""); System.Diagnostics.Debug.WriteLine(string.Format("DateTime {0}, Retrieved JSON from WebException response", DateTime.Now.ToString())); return(jsonString); } } if (ex.Message.IndexOf("The request was aborted: The request was canceled") == -1 && ex.Message.IndexOf("Machine suspend mode enabled. No request will be processed.") == -1) { throw ex; } return(""); } catch (Exception ex) { throw ex; } //return task.ContinueWith(t => ReadStreamFromResponse(t.Result)); /* * System.Diagnostics.Debug.WriteLine(string.Format("DateTime {0}, Before BeginGetResponse", DateTime.Now.ToString())); * var taskComplete = new TaskCompletionSource<string>(); * * IAsyncResult asyncResult = request.BeginGetResponse(new AsyncCallback( * (asynchronousResult) => { * RequestState<T> asyncRequestState = asynchronousResult.AsyncState as RequestState<T>; * PubnubWebRequest asyncWebRequest = asyncRequestState.Request as PubnubWebRequest; * if (asyncWebRequest != null) * { * System.Diagnostics.Debug.WriteLine(string.Format("DateTime {0}, Before EndGetResponse", DateTime.Now.ToString())); * PubnubWebResponse asyncWebResponse = (PubnubWebResponse)asyncWebRequest.EndGetResponse(asynchronousResult); * System.Diagnostics.Debug.WriteLine(string.Format("DateTime {0}, After EndGetResponse", DateTime.Now.ToString())); * using (StreamReader streamReader = new StreamReader(asyncWebResponse.GetResponseStream())) * { * System.Diagnostics.Debug.WriteLine(string.Format("DateTime {0}, Inside StreamReader", DateTime.Now.ToString())); * //Need to return this response * string jsonString = streamReader.ReadToEnd(); * System.Diagnostics.Debug.WriteLine(jsonString); * System.Diagnostics.Debug.WriteLine(""); * System.Diagnostics.Debug.WriteLine(string.Format("DateTime {0}, Retrieved JSON", DateTime.Now.ToString())); * taskComplete.TrySetResult(jsonString); * } * } * } * ), pubnubRequestState); * * Timer webRequestTimer = new Timer(OnPubnubWebRequestTimeout<T>, pubnubRequestState, GetTimeoutInSecondsForResponseType(pubnubRequestState.ResponseType) * 1000, Timeout.Infinite); * * return taskComplete.Task; */ }
async Task <string> SendRequestAndGetJsonResponseTaskFactoryWithPOST <T>(Uri requestUri, RequestState <T> pubnubRequestState, HttpWebRequest request, string postData) { System.Diagnostics.Debug.WriteLine(string.Format("DateTime {0}, Before Task.Factory.FromAsync With POST", DateTime.Now.ToString())); try { request.Method = "POST"; request.ContentType = "application/json"; byte[] data = Encoding.UTF8.GetBytes(postData); //request.ContentLength = data.Length; using (var requestStream = await Task <Stream> .Factory.FromAsync(request.BeginGetRequestStream, request.EndGetRequestStream, pubnubRequestState)) { #if NET35 requestStream.Write(data, 0, data.Length); requestStream.Flush(); #else await requestStream.WriteAsync(data, 0, data.Length); await requestStream.FlushAsync(); #endif } WebResponse response = await Task.Factory.FromAsync(request.BeginGetResponse, request.EndGetResponse, pubnubRequestState); pubnubRequestState.Response = response as HttpWebResponse; System.Diagnostics.Debug.WriteLine(string.Format("DateTime {0}, Got PubnubWebResponse With POST for {1}", DateTime.Now.ToString(), request.RequestUri.ToString())); using (StreamReader streamReader = new StreamReader(response.GetResponseStream())) { //Need to return this response #if NET35 string jsonString = streamReader.ReadToEnd(); #else string jsonString = await streamReader.ReadToEndAsync(); #endif System.Diagnostics.Debug.WriteLine(jsonString); System.Diagnostics.Debug.WriteLine(""); System.Diagnostics.Debug.WriteLine(string.Format("DateTime {0}, Retrieved JSON With POST", DateTime.Now.ToString())); pubnubRequestState.GotJsonResponse = true; if (pubnubRequestState.Response != null) { #if NET35 || NET40 || NET45 || NET461 pubnubRequestState.Response.Close(); #endif pubnubRequestState.Response = null; pubnubRequestState.Request = null; } return(jsonString); } } catch (WebException ex) { if (ex.Response != null) { pubnubRequestState.Response = ex.Response as HttpWebResponse; using (StreamReader streamReader = new StreamReader(ex.Response.GetResponseStream())) { //Need to return this response #if NET35 string jsonString = streamReader.ReadToEnd(); #else string jsonString = await streamReader.ReadToEndAsync(); #endif System.Diagnostics.Debug.WriteLine(jsonString); System.Diagnostics.Debug.WriteLine(""); System.Diagnostics.Debug.WriteLine(string.Format("DateTime {0}, Retrieved JSON With POST from WebException response", DateTime.Now.ToString())); return(jsonString); } } if (ex.Message.IndexOf("The request was aborted: The request was canceled") == -1 && ex.Message.IndexOf("Machine suspend mode enabled. No request will be processed.") == -1) { throw ex; } return(""); } catch (Exception ex) { throw ex; } }
async Task <string> SendRequestAndGetJsonResponseHttpClientWithPOST <T>(Uri requestUri, RequestState <T> pubnubRequestState, HttpWebRequest request, string postData) { string jsonString = ""; HttpResponseMessage response = null; try { System.Diagnostics.Debug.WriteLine(string.Format("DateTime {0}, SendRequestAndGetJsonResponseHttpClientPOST Before httpClient.GetAsync", DateTime.Now.ToString())); HttpClient httpClient = new HttpClient(); httpClient.DefaultRequestHeaders.Accept.Clear(); httpClient.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json")); httpClient.Timeout = TimeSpan.FromSeconds(GetTimeoutInSecondsForResponseType(pubnubRequestState.ResponseType)); StringContent jsonPostString = new StringContent(postData, Encoding.UTF8); response = await httpClient.PostAsync(requestUri, jsonPostString); response.EnsureSuccessStatusCode(); var stream = await response.Content.ReadAsStreamAsync(); using (StreamReader streamReader = new StreamReader(stream)) { jsonString = await streamReader.ReadToEndAsync(); pubnubRequestState.GotJsonResponse = true; } System.Diagnostics.Debug.WriteLine(string.Format("DateTime {0}, Got POST HttpResponseMessage for {1}", DateTime.Now.ToString(), requestUri)); } catch (Exception ex) { throw ex; } finally { if (response != null && response.Content != null) { response.Content.Dispose(); } } return(jsonString); }
//private string ReadStreamFromResponse(HttpWebResponse response) //{ // System.Diagnostics.Debug.WriteLine(string.Format("DateTime {0}, Got PubnubWebResponse", DateTime.Now.ToString())); // using (StreamReader streamReader = new StreamReader(response.GetResponseStream())) // { // //Need to return this response // string jsonString = streamReader.ReadToEnd(); // System.Diagnostics.Debug.WriteLine(jsonString); // System.Diagnostics.Debug.WriteLine(""); // System.Diagnostics.Debug.WriteLine(string.Format("DateTime {0}, Retrieved JSON", DateTime.Now.ToString())); // return jsonString; // } //} #if !NET35 && !NET40 && !NET45 && !NET461 && !NETSTANDARD10 async Task <string> SendRequestAndGetJsonResponseHttpClient <T>(Uri requestUri, RequestState <T> pubnubRequestState, HttpWebRequest request) { string jsonString = ""; HttpResponseMessage response = null; try { LoggingMethod.WriteToLog(pubnubLog, string.Format("DateTime: {0}, Inside SendRequestAndGetJsonResponseHttpClient", DateTime.Now.ToString()), pubnubConfig.LogVerbosity); //HttpClient httpClient = new HttpClient(); //if (httpClient.Timeout != TimeSpan.FromSeconds(GetTimeoutInSecondsForResponseType(pubnubRequestState.ResponseType))) //{ // httpClient.Timeout = TimeSpan.FromSeconds(GetTimeoutInSecondsForResponseType(pubnubRequestState.ResponseType)); //} if (pubnubRequestState.ResponseType == PNOperationType.PNSubscribeOperation) { response = await httpClientSubscribe.GetAsync(requestUri); } else if (pubnubRequestState.ResponseType == PNOperationType.PNDeleteMessageOperation) { response = await httpClientNonsubscribe.DeleteAsync(requestUri); } else { response = await httpClientNonsubscribe.GetAsync(requestUri); } response.EnsureSuccessStatusCode(); var stream = await response.Content.ReadAsStreamAsync(); using (StreamReader streamReader = new StreamReader(stream)) { jsonString = await streamReader.ReadToEndAsync(); pubnubRequestState.GotJsonResponse = true; } System.Diagnostics.Debug.WriteLine(string.Format("DateTime {0}, Got HttpResponseMessage for {1}", DateTime.Now.ToString(), requestUri)); } catch (Exception ex) { throw ex; } finally { if (response != null && response.Content != null) { response.Content.Dispose(); } } return(jsonString); }
public PNStatus CreateStatusResponse <T>(PNOperationType type, PNStatusCategory category, RequestState <T> asyncRequestState, int statusCode, Exception throwable) { PNStatus status = new PNStatus(asyncRequestState != null ? asyncRequestState.EndPointOperation : null); status.Category = category; status.Operation = type; if ((asyncRequestState != null && !asyncRequestState.GotJsonResponse) || throwable != null) { status.Error = true; } if (throwable != null) { if (throwable.InnerException != null) { PNErrorData errorData = new PNErrorData(throwable.InnerException.Message, throwable); status.ErrorData = errorData; } else { PNErrorData errorData = new PNErrorData(throwable.Message, throwable); status.ErrorData = errorData; } } if (asyncRequestState != null) { if (asyncRequestState.Request != null) { status.ClientRequest = asyncRequestState.Request; HttpValueCollection restUriQueryCollection = HttpUtility.ParseQueryString(asyncRequestState.Request.RequestUri.Query); if (restUriQueryCollection.ContainsKey("auth")) { string auth = restUriQueryCollection["auth"]; status.AuthKey = auth; } if (restUriQueryCollection.ContainsKey("uuid")) { string uuid = restUriQueryCollection["uuid"]; status.Uuid = uuid; } } if (asyncRequestState.Response != null) { status.StatusCode = (int)asyncRequestState.Response.StatusCode; } else { status.StatusCode = statusCode; } if (asyncRequestState.ChannelGroups != null) { status.AffectedChannelGroups = asyncRequestState.ChannelGroups.ToList <string>(); } if (asyncRequestState.Channels != null) { status.AffectedChannels = asyncRequestState.Channels.ToList <string>(); } } else { status.StatusCode = statusCode; } status.Origin = config.Origin; status.TlsEnabled = config.Secure; return(status); }
async Task <string> SendRequestAndGetJsonResponseHttpClientWithPOST <T>(Uri requestUri, RequestState <T> pubnubRequestState, HttpWebRequest request, string postData) { string jsonString = ""; HttpResponseMessage response = null; try { System.Diagnostics.Debug.WriteLine(string.Format("DateTime {0}, SendRequestAndGetJsonResponseHttpClientPOST Before httpClient.GetAsync", DateTime.Now.ToString())); System.Diagnostics.Stopwatch stopWatch = new System.Diagnostics.Stopwatch(); stopWatch.Start(); StringContent jsonPostString = new StringContent(postData, Encoding.UTF8); if (pubnubRequestState.ResponseType == PNOperationType.PNSubscribeOperation) { response = await httpClientSubscribe.PostAsync(requestUri, jsonPostString); } else { response = await httpClientNonsubscribe.PostAsync(requestUri, jsonPostString); } response.EnsureSuccessStatusCode(); var stream = await response.Content.ReadAsStreamAsync(); stopWatch.Stop(); if (pubnubTelemetryMgr != null) { pubnubTelemetryMgr.StoreLatency(stopWatch.ElapsedMilliseconds, pubnubRequestState.ResponseType); } using (StreamReader streamReader = new StreamReader(stream)) { jsonString = await streamReader.ReadToEndAsync(); pubnubRequestState.GotJsonResponse = true; } System.Diagnostics.Debug.WriteLine(string.Format("DateTime {0}, Got POST HttpResponseMessage for {1}", DateTime.Now.ToString(), requestUri)); } catch (Exception ex) { throw ex; } finally { if (response != null && response.Content != null) { response.Content.Dispose(); pubnubRequestState.Response = null; pubnubRequestState.Request = null; } } return(jsonString); }
async Task <string> SendRequestAndGetJsonResponseHttpClient <T>(Uri requestUri, RequestState <T> pubnubRequestState, HttpWebRequest request) { string jsonString = ""; HttpResponseMessage response = null; try { LoggingMethod.WriteToLog(pubnubLog, string.Format("DateTime: {0}, Inside SendRequestAndGetJsonResponseHttpClient", DateTime.Now.ToString()), pubnubConfig.LogVerbosity); System.Diagnostics.Stopwatch stopWatch = new System.Diagnostics.Stopwatch(); stopWatch.Start(); if (pubnubRequestState.ResponseType == PNOperationType.PNSubscribeOperation) { response = await httpClientSubscribe.GetAsync(requestUri); } else if (pubnubRequestState.ResponseType == PNOperationType.PNDeleteMessageOperation) { response = await httpClientNonsubscribe.DeleteAsync(requestUri); } else { response = await httpClientNonsubscribe.GetAsync(requestUri); } response.EnsureSuccessStatusCode(); var stream = await response.Content.ReadAsStreamAsync(); stopWatch.Stop(); if (pubnubTelemetryMgr != null) { pubnubTelemetryMgr.StoreLatency(stopWatch.ElapsedMilliseconds, pubnubRequestState.ResponseType); } using (StreamReader streamReader = new StreamReader(stream)) { jsonString = await streamReader.ReadToEndAsync(); pubnubRequestState.GotJsonResponse = true; } System.Diagnostics.Debug.WriteLine(string.Format("DateTime {0}, Got HttpResponseMessage for {1}", DateTime.Now.ToString(), requestUri)); } catch (Exception ex) { throw ex; } finally { if (response != null && response.Content != null) { response.Content.Dispose(); pubnubRequestState.Response = null; pubnubRequestState.Request = null; } } return(jsonString); }