Exemplo n.º 1
0
        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;
             */
        }
Exemplo n.º 2
0
        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()), pubnubConfig.LogVerbosity);
            var taskComplete = new TaskCompletionSource <string>();

            try
            {
                request.Method      = "POST";
                request.ContentType = "application/json";

                byte[] data = Encoding.UTF8.GetBytes(postData);
                //request.ContentLength = data.Length;
#if !NET35 && !NET40 && !NET45 && !NET461
                using (var requestStream = await Task <Stream> .Factory.FromAsync(request.BeginGetRequestStream, request.EndGetRequestStream, pubnubRequestState))
                {
                    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(
                                                                        (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()));
                        HttpWebResponse asyncWebResponse = (HttpWebResponse)asyncWebRequest.EndGetResponse(asynchronousResult);
                        asyncRequestState.Response       = asyncWebResponse;
                        System.Diagnostics.Debug.WriteLine(string.Format("DateTime {0}, After EndGetResponse With POST ", DateTime.Now.ToString()));
                        using (StreamReader streamReader = new StreamReader(asyncWebResponse.GetResponseStream()))
                        {
                            System.Diagnostics.Debug.WriteLine(string.Format("DateTime {0}, Inside StreamReader With POST ", 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 With POST ", 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 || NET40
                        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  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)
                {
                    taskComplete.TrySetException(ex);
                }
                return("");
            }
            catch (Exception ex)
            {
                taskComplete.TrySetException(ex);
                return("");
            }
        }
Exemplo n.º 3
0
        protected override string EncryptOrDecrypt(bool type, string plainStr)
        {
            //Demo params
            string keyString = GetEncryptionKey();

#if NET35
            Aes aesAlg = Aes.Create();
            aesAlg.KeySize   = 256;
            aesAlg.BlockSize = 128;
            aesAlg.Mode      = CipherMode.CBC;
            aesAlg.Padding   = PaddingMode.PKCS7;
            aesAlg.IV        = System.Text.Encoding.UTF8.GetBytes("0123456789012345");
            aesAlg.Key       = System.Text.Encoding.UTF8.GetBytes(keyString);
#else
            string input = plainStr;
            byte[] inputBytes;
            byte[] iv       = System.Text.Encoding.UTF8.GetBytes("0123456789012345");
            byte[] keyBytes = System.Text.Encoding.UTF8.GetBytes(keyString);

            //Set up
            AesEngine                 engine         = new AesEngine();
            CbcBlockCipher            blockCipher    = new CbcBlockCipher(engine);                 //CBC
            PaddedBufferedBlockCipher cipher         = new PaddedBufferedBlockCipher(blockCipher); //Default scheme is PKCS5/PKCS7
            KeyParameter              keyParam       = new KeyParameter(keyBytes);
            ParametersWithIV          keyParamWithIV = new ParametersWithIV(keyParam, iv, 0, iv.Length);
#endif


            if (type)
            {
                // Encrypt
#if NET35
                byte[] cipherText = null;
                plainStr = EncodeNonAsciiCharacters(plainStr);
                ICryptoTransform crypto    = aesAlg.CreateEncryptor();
                byte[]           plainText = Encoding.UTF8.GetBytes(plainStr);

                cipherText = crypto.TransformFinalBlock(plainText, 0, plainText.Length);

                return(Convert.ToBase64String(cipherText));
#else
                input      = EncodeNonAsciiCharacters(input);
                inputBytes = Encoding.UTF8.GetBytes(input);
                cipher.Init(true, keyParamWithIV);
                byte[] outputBytes = new byte[cipher.GetOutputSize(inputBytes.Length)];
                int    length      = cipher.ProcessBytes(inputBytes, outputBytes, 0);
                cipher.DoFinal(outputBytes, length); //Do the final block
                string encryptedInput = Convert.ToBase64String(outputBytes);

                return(encryptedInput);
#endif
            }
            else
            {
                try
                {
                    //Decrypt
#if NET35
                    string           decrypted      = "";
                    byte[]           decryptedBytes = Convert.FromBase64CharArray(plainStr.ToCharArray(), 0, plainStr.Length);
                    ICryptoTransform decrypto       = aesAlg.CreateDecryptor();

                    var data = decrypto.TransformFinalBlock(decryptedBytes, 0, decryptedBytes.Length);
                    decrypted = System.Text.Encoding.UTF8.GetString(data, 0, data.Length);
                    return(decrypted);
#else
                    inputBytes = Convert.FromBase64CharArray(input.ToCharArray(), 0, input.Length);
                    cipher.Init(false, keyParamWithIV);
                    byte[] encryptedBytes   = new byte[cipher.GetOutputSize(inputBytes.Length)];
                    int    encryptLength    = cipher.ProcessBytes(inputBytes, encryptedBytes, 0);
                    int    numOfOutputBytes = cipher.DoFinal(encryptedBytes, encryptLength); //Do the final block
                    int    len = Array.IndexOf(encryptedBytes, (byte)0);
                    len = (len == -1) ? encryptedBytes.Length : len;
                    string actualInput = Encoding.UTF8.GetString(encryptedBytes, 0, len);
                    return(actualInput);
#endif
                }
                catch (Exception ex)
                {
                    if (config != null)
                    {
                        LoggingMethod.WriteToLog(string.Format("DateTime {0} Decrypt Error. {1}", DateTime.Now.ToString(), ex.ToString()), config.LogVerbosity);
                    }
                    throw ex;
                    //LoggingMethod.WriteToLog(string.Format("DateTime {0} Decrypt Error. {1}", DateTime.Now.ToString(), ex.ToString()), pubnubConfig.LogVerbosity);
                    //return "**DECRYPT ERROR**";
                }
            }
        }
Exemplo n.º 4
0
        async Task <string> SendRequestAndGetJsonResponseClassicHttp <T>(Uri requestUri, RequestState <T> pubnubRequestState, HttpWebRequest request)
        {
            //HttpWebResponse response = null;
            LoggingMethod.WriteToLog(pubnubLog, string.Format("DateTime: {0}, Inside SendRequestAndGetJsonResponseClassicHttp", DateTime.Now.ToString()), pubnubConfig.LogVerbosity);
            var taskComplete = new TaskCompletionSource <string>();

            try
            {
                request.Method = (pubnubRequestState != null && pubnubRequestState.ResponseType == PNOperationType.PNDeleteMessageOperation) ? "DELETE" : "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 || NET40
                        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("");
            }
        }
Exemplo n.º 5
0
        private async Task <bool> CheckSocketConnect <T>(object internetState)
        {
            lock (internetCheckLock)
            {
                isInternetCheckRunning = true;
            }
            LoggingMethod.WriteToLog(pubnubLog, string.Format("DateTime {0} CheckSocketConnect Entered", DateTime.Now.ToString(CultureInfo.InvariantCulture)), pubnubConfig.LogVerbosity);

            Action <bool>   internalCallback = null;
            PNCallback <T>  pubnubCallback   = null;
            PNOperationType type             = PNOperationType.None;

            string[] channels      = null;
            string[] channelGroups = null;

            var t = new TaskCompletionSource <bool>();

            InternetState <T> state = internetState as InternetState <T>;

            if (state != null)
            {
                internalCallback = state.InternalCallback;
                type             = state.ResponseType;
                pubnubCallback   = state.PubnubCallbacck;
                channels         = state.Channels;
                channelGroups    = state.ChannelGroups;
            }

            PubnubApi.Interface.IUrlRequestBuilder urlBuilder = new UrlRequestBuilder(pubnubConfig, jsonLib, unit, pubnubLog, null);
            Uri requestUri = urlBuilder.BuildTimeRequest();

            try
            {
#if !NET35 && !NET40 && !NET45 && !NET461 && !NETSTANDARD10
                var response = await httpClient.GetAsync(requestUri);

                if (response.IsSuccessStatusCode)
                {
                    LoggingMethod.WriteToLog(pubnubLog, string.Format("DateTime {0} HttpClient CheckSocketConnect Resp {1}", DateTime.Now.ToString(CultureInfo.InvariantCulture), response.StatusCode.ToString()), pubnubConfig.LogVerbosity);
                    networkStatus = true;
                    t.TrySetResult(true);
                }
                else
                {
                    LoggingMethod.WriteToLog(pubnubLog, string.Format("DateTime {0} HttpClient CheckSocketConnect Resp {1}", DateTime.Now.ToString(CultureInfo.InvariantCulture), response.StatusCode.ToString()), pubnubConfig.LogVerbosity);
                    networkStatus = false;
                    t.TrySetResult(false);
                }
#else
                HttpWebRequest myRequest = null;
                myRequest        = (HttpWebRequest)System.Net.WebRequest.Create(requestUri);
                myRequest.Method = "GET";
                using (HttpWebResponse response = await Task.Factory.FromAsync <HttpWebResponse>(myRequest.BeginGetResponse, asyncPubnubResult => (HttpWebResponse)myRequest.EndGetResponse(asyncPubnubResult), null))
                {
                    if (response != null && response.StatusCode == HttpStatusCode.OK)
                    {
                        LoggingMethod.WriteToLog(pubnubLog, string.Format("DateTime {0} WebRequest CheckSocketConnect Resp {1}", DateTime.Now.ToString(CultureInfo.InvariantCulture), response.StatusCode.ToString()), pubnubConfig.LogVerbosity);
                        networkStatus = true;
                        t.TrySetResult(true);
                    }
                }
#endif
            }
            catch (Exception ex)
            {
                networkStatus = false;
                LoggingMethod.WriteToLog(pubnubLog, string.Format("DateTime {0} CheckSocketConnect (HttpClient Or Task.Factory) Failed {1}", DateTime.Now.ToString(CultureInfo.InvariantCulture), ex.Message), pubnubConfig.LogVerbosity);
                if (!networkStatus)
                {
                    t.TrySetResult(false);
                    isInternetCheckRunning = false;
                    ParseCheckSocketConnectException <T>(ex, type, pubnubCallback, internalCallback);
                }
            }
            finally
            {
                isInternetCheckRunning = false;
            }
            return(await t.Task.ConfigureAwait(false));
        }
Exemplo n.º 6
0
        async Task <string> SendRequestAndGetJsonResponseTaskFactory <T>(Uri requestUri, RequestState <T> pubnubRequestState, HttpWebRequest request)
        {
            HttpWebResponse response = null;

            LoggingMethod.WriteToLog(pubnubLog, string.Format("DateTime: {0}, Inside SendRequestAndGetJsonResponseTaskFactory", DateTime.Now.ToString()), pubnubConfig.LogVerbosity);
            try
            {
                request.Method = (pubnubRequestState != null && pubnubRequestState.ResponseType == PNOperationType.PNDeleteMessageOperation) ? "DELETE" : "GET";
                Timer webRequestTimer = 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);

                stopWatch.Stop();
                if (pubnubConfig.EnableTelemetry && pubnubTelemetryMgr != null)
                {
                    pubnubTelemetryMgr.StoreLatency(stopWatch.ElapsedMilliseconds, pubnubRequestState.ResponseType);
                }
                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 || NET40
                    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 || NET40
                        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;
            }
        }
Exemplo n.º 7
0
        private static async Task <bool> CheckSocketConnect <T>(object internetState)
        {
            lock (internetCheckLock)
            {
                isInternetCheckRunning = true;
            }
            LoggingMethod.WriteToLog(pubnubLog, string.Format("DateTime {0} CheckSocketConnect Entered", DateTime.Now.ToString(CultureInfo.InvariantCulture)), pubnubConfig.LogVerbosity);

            Action <bool>   internalCallback = null;
            PNCallback <T>  pubnubCallback   = null;
            PNOperationType type             = PNOperationType.None;

            string[] channels      = null;
            string[] channelGroups = null;

            var t = new TaskCompletionSource <bool>();

            InternetState <T> state = internetState as InternetState <T>;

            if (state != null)
            {
                internalCallback = state.InternalCallback;
                type             = state.ResponseType;
                pubnubCallback   = state.PubnubCallbacck;
                channels         = state.Channels;
                channelGroups    = state.ChannelGroups;
            }

            PubnubApi.Interface.IUrlRequestBuilder urlBuilder = new UrlRequestBuilder(pubnubConfig, jsonLib, unit, pubnubLog, null);
            Uri requestUri = urlBuilder.BuildTimeRequest(null);

            try
            {
                bool gotTimeResp = false;
                if (pubnubConfig.UseClassicHttpWebRequest)
                {
                    gotTimeResp = await GetTimeWithClassicHttp <T>(requestUri).ConfigureAwait(false);

                    t.TrySetResult(gotTimeResp);
                }
                else
                {
#if !NET35 && !NET40 && !NET45 && !NET461 && !NETSTANDARD10
                    if (pubnubConfig.UseTaskFactoryAsyncInsteadOfHttpClient)
                    {
                        gotTimeResp = await GetTimeWithTaskFactoryAsync(requestUri).ConfigureAwait(false);
                    }
                    else
                    {
                        gotTimeResp = await GetTimeWithHttpClient(requestUri).ConfigureAwait(false);
                    }
                    t.TrySetResult(gotTimeResp);
#else
                    gotTimeResp = await GetTimeWithTaskFactoryAsync(requestUri).ConfigureAwait(false);

                    t.TrySetResult(gotTimeResp);
#endif
                }
            }
            catch (Exception ex)
            {
                networkStatus = false;
                LoggingMethod.WriteToLog(pubnubLog, string.Format("DateTime {0} CheckSocketConnect (HttpClient Or Task.Factory) Failed {1}", DateTime.Now.ToString(CultureInfo.InvariantCulture), ex.Message), pubnubConfig.LogVerbosity);
                if (!networkStatus)
                {
                    t.TrySetResult(false);
                    isInternetCheckRunning = false;
                    ParseCheckSocketConnectException <T>(ex, type, pubnubCallback, internalCallback);
                }
            }
            finally
            {
                isInternetCheckRunning = false;
            }
            return(await t.Task.ConfigureAwait(false));
        }
Exemplo n.º 8
0
 protected override async Task <HttpResponseMessage> SendAsync(HttpRequestMessage request, CancellationToken cancellationToken)
 {
     cancellationToken.ThrowIfCancellationRequested();
     LoggingMethod.WriteToLog(pubnubLog, string.Format("DateTime {0} PubnubHttpClientHandler {1} SendAsync ", DateTime.Now.ToString(CultureInfo.InvariantCulture), pubnubHandlerName), pubnubConfig.LogVerbosity);
     return(await base.SendAsync(request, cancellationToken));
 }