Example #1
0
 public Pubnub(PNConfiguration config)
 {
     savedSdkVerion = sdkVersion;
     instanceId     = Guid.NewGuid().ToString();
     pubnubConfig   = config;
     if (config != null)
     {
         pubnubLog = config.PubnubLog;
     }
     jsonPluggableLibrary = new NewtonsoftJsonDotNet(config, pubnubLog);
     if (config != null && config.EnableTelemetry)
     {
         telemetryManager = new EndPoint.TelemetryManager(pubnubConfig, pubnubLog);
     }
     CheckRequiredConfigValues();
     if (config != null && pubnubLog != null)
     {
         PNPlatform.Print(config, pubnubLog);
     }
     if (config != null && config.PresenceTimeout < 20)
     {
         config.PresenceTimeout = 20;
         if (pubnubLog != null)
         {
             LoggingMethod.WriteToLog(pubnubLog, string.Format("DateTime: {0}, WARNING: The PresenceTimeout cannot be less than 20, defaulting the value to 20. Please update the settings in your code.", DateTime.Now.ToString(CultureInfo.InvariantCulture)), config.LogVerbosity);
         }
     }
 }
Example #2
0
        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(CultureInfo.InvariantCulture)), pubnubConfig.LogVerbosity);
                System.Diagnostics.Stopwatch stopWatch = new System.Diagnostics.Stopwatch();
                stopWatch.Start();
                if (pubnubRequestState.ResponseType == PNOperationType.PNSubscribeOperation)
                {
                    response = await httpClientSubscribe.GetAsync(requestUri).ConfigureAwait(false);
                }
                else if (pubnubRequestState.ResponseType == PNOperationType.PNDeleteMessageOperation)
                {
                    response = await httpClientNonsubscribe.DeleteAsync(requestUri).ConfigureAwait(false);
                }
                else
                {
                    response = await httpClientNonsubscribe.GetAsync(requestUri).ConfigureAwait(false);
                }
                if (response.IsSuccessStatusCode || response.Content != null)
                {
                    var stream = await response.Content.ReadAsStreamAsync().ConfigureAwait(false);

                    stopWatch.Stop();
                    if (pubnubTelemetryMgr != null)
                    {
                        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 HttpResponseMessage for {1}", DateTime.Now.ToString(CultureInfo.InvariantCulture), requestUri));
                }
                else
                {
                    stopWatch.Stop();
                    System.Diagnostics.Debug.WriteLine(string.Format("DateTime {0}, No HttpResponseMessage for {1}", DateTime.Now.ToString(CultureInfo.InvariantCulture), requestUri));
                }
            }
            catch
            {
                throw;
            }
            finally
            {
                if (response != null && response.Content != null)
                {
                    response.Content.Dispose();
                    pubnubRequestState.Response = null;
                    pubnubRequestState.Request  = null;
                }
            }
            return(jsonString);
        }
Example #3
0
        public static void Print(PNConfiguration config, IPubnubLog log)
        {
#if NETSTANDARD10
            LoggingMethod.WriteToLog(log, string.Format("DateTime {0} PLATFORM = NETSTANDARD10", DateTime.Now.ToString(CultureInfo.InvariantCulture)), config.LogVerbosity);
#elif NETSTANDARD11
            LoggingMethod.WriteToLog(log, string.Format("DateTime {0} PLATFORM = NETSTANDARD11", DateTime.Now.ToString(CultureInfo.InvariantCulture)), config.LogVerbosity);
#elif NETSTANDARD12
            LoggingMethod.WriteToLog(log, string.Format("DateTime {0} PLATFORM = NETSTANDARD12", DateTime.Now.ToString(CultureInfo.InvariantCulture)), config.LogVerbosity);
#elif NETSTANDARD13
            LoggingMethod.WriteToLog(log, string.Format("DateTime {0} PLATFORM = NETSTANDARD13", DateTime.Now.ToString(CultureInfo.InvariantCulture)), config.LogVerbosity);
#elif NETSTANDARD14
            LoggingMethod.WriteToLog(log, string.Format("DateTime {0} PLATFORM = NETSTANDARD14", DateTime.Now.ToString(CultureInfo.InvariantCulture)), config.LogVerbosity);
#elif UAP
            LoggingMethod.WriteToLog(log, string.Format("DateTime {0} PLATFORM = UAP", DateTime.Now.ToString(CultureInfo.InvariantCulture)), config.LogVerbosity);
#elif NETFX_CORE
            LoggingMethod.WriteToLog(log, string.Format("DateTime {0} PLATFORM = NETFX_CORE", DateTime.Now.ToString(CultureInfo.InvariantCulture)), config.LogVerbosity);
#elif WINDOWS_UWP
            LoggingMethod.WriteToLog(log, string.Format("DateTime {0} PLATFORM = WINDOWS_UWP", DateTime.Now.ToString(CultureInfo.InvariantCulture)), config.LogVerbosity);
#elif PORTABLE111
            LoggingMethod.WriteToLog(log, string.Format("DateTime {0} PLATFORM = PORTABLE111", DateTime.Now.ToString(CultureInfo.InvariantCulture)), config.LogVerbosity);
#elif NET35
            LoggingMethod.WriteToLog(log, string.Format("DateTime {0} PLATFORM = NET35", DateTime.Now.ToString(CultureInfo.InvariantCulture)), config.LogVerbosity);
#elif NET40
            LoggingMethod.WriteToLog(log, string.Format("DateTime {0} PLATFORM = NET40", DateTime.Now.ToString(CultureInfo.InvariantCulture)), config.LogVerbosity);
#elif NET45
            LoggingMethod.WriteToLog(log, string.Format("DateTime {0} PLATFORM = NET45", DateTime.Now.ToString(CultureInfo.InvariantCulture)), config.LogVerbosity);
#elif NET461
            LoggingMethod.WriteToLog(log, string.Format("DateTime {0} PLATFORM = NET461", DateTime.Now.ToString(CultureInfo.InvariantCulture)), config.LogVerbosity);
            #else
            LoggingMethod.WriteToLog(log, string.Format("DateTime {0} PLATFORM = UNKNOWN", DateTime.Now.ToString(CultureInfo.InvariantCulture)), config.LogVerbosity);
            #endif
        }
Example #4
0
        internal bool CheckInternetStatus <T>(bool systemActive, PNOperationType type, PNCallback <T> callback, string[] channels, string[] channelGroups)
        {
            if (unit != null)
            {
                return(unit.InternetAvailable);
            }
            else
            {
                Task[] tasks = new Task[1];

                tasks[0] = Task.Factory.StartNew(async() => await CheckClientNetworkAvailability(CallbackClientNetworkStatus, type, callback, channels, channelGroups).ConfigureAwait(false));
                tasks[0].ConfigureAwait(false);
                try
                {
                    Task.WaitAll(tasks);
                }
                catch (AggregateException ae) {
                    foreach (var ie in ae.InnerExceptions)
                    {
                        LoggingMethod.WriteToLog(pubnubLog, string.Format("DateTime {0} AggregateException CheckInternetStatus Error: {1} {2} ", DateTime.Now.ToString(CultureInfo.InvariantCulture), ie.GetType().Name, ie.Message), pubnubConfig.LogVerbosity);
                    }
                }

                return(networkStatus);
            }
        }
Example #5
0
        private static async Task <bool> GetTimeWithTaskFactoryAsync(Uri requestUri)
        {
            bool successFlag = false;

            try
            {
                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)
                    {
                        LoggingMethod.WriteToLog(pubnubLog, string.Format("DateTime {0} GetTimeWithTaskFactoryAsync Resp {1}", DateTime.Now.ToString(CultureInfo.InvariantCulture), response.StatusCode.ToString()), pubnubConfig.LogVerbosity);
                        successFlag = response.StatusCode == HttpStatusCode.OK;
                    }
                    else
                    {
                        LoggingMethod.WriteToLog(pubnubLog, string.Format("DateTime {0} GetTimeWithTaskFactoryAsync FAILED.", DateTime.Now.ToString(CultureInfo.InvariantCulture)), pubnubConfig.LogVerbosity);
                    }
                }
            }
            finally
            {
                networkStatus = successFlag;
            }
            return(networkStatus);
        }
Example #6
0
 protected void OnPubnubWebRequestTimeout <T>(object state, bool timeout)
 {
     if (timeout && state != null)
     {
         RequestState <T> currentState = state as RequestState <T>;
         if (currentState != null)
         {
             HttpWebRequest request = currentState.Request;
             if (request != null)
             {
                 string currentMultiChannel      = (currentState.Channels == null) ? "" : string.Join(",", currentState.Channels.OrderBy(x => x).ToArray());
                 string currentMultiChannelGroup = (currentState.ChannelGroups == null) ? "" : string.Join(",", currentState.ChannelGroups.OrderBy(x => x).ToArray());
                 LoggingMethod.WriteToLog(pubnubLog, string.Format("DateTime: {0}, OnPubnubWebRequestTimeout: client request timeout reached.Request abort for channel={1} ;channelgroup={2}", DateTime.Now.ToString(CultureInfo.InvariantCulture), currentMultiChannel, currentMultiChannelGroup), pubnubConfig.LogVerbosity);
                 currentState.Timeout = true;
                 try
                 {
                     request.Abort();
                 }
                 catch { /* ignore */ }
             }
         }
         else
         {
             LoggingMethod.WriteToLog(pubnubLog, string.Format("DateTime: {0}, OnPubnubWebRequestTimeout: client request timeout reached. However state is unknown", DateTime.Now.ToString(CultureInfo.InvariantCulture)), pubnubConfig.LogVerbosity);
         }
     }
 }
Example #7
0
        private async Task <bool> CheckClientNetworkAvailability <T>(Action <bool> internalCallback, PNOperationType type, PNCallback <T> callback, string[] channels, string[] channelGroups)
        {
            lock (internetCheckLock)
            {
                if (isInternetCheckRunning)
                {
                    LoggingMethod.WriteToLog(pubnubLog, string.Format("DateTime {0} InternetCheckRunning Already running", DateTime.Now.ToString()), pubnubConfig.LogVerbosity);
                    return(networkStatus);
                }
            }
            //mres = new ManualResetEvent(false);


            InternetState <T> state = new InternetState <T>();

            state.InternalCallback = internalCallback;
            state.PubnubCallbacck  = callback;
            state.ResponseType     = type;
            //state.ErrorCallback = errorCallback;
            state.Channels      = channels;
            state.ChannelGroups = channelGroups;

            networkStatus = await CheckSocketConnect <T>(state);

            return(networkStatus);

            //ThreadPool.QueueUserWorkItem(CheckSocketConnect<T>, state);

            //mres.WaitOne(500);
        }
Example #8
0
        private static void ParseCheckSocketConnectException <T>(Exception ex, PNOperationType type, PNCallback <T> callback, Action <bool> internalcallback)
        {
            PNStatusCategory errorCategory = PNStatusCategoryHelper.GetPNStatusCategory(ex);
            StatusBuilder    statusBuilder = new StatusBuilder(pubnubConfig, jsonLib);
            PNStatus         status        = statusBuilder.CreateStatusResponse <T>(type, errorCategory, null, (int)System.Net.HttpStatusCode.NotFound, new PNException(ex));

            if (callback != null)
            {
                callback.OnResponse(default(T), status);
            }

            LoggingMethod.WriteToLog(pubnubLog, string.Format("DateTime {0} ParseCheckSocketConnectException Error. {1}", DateTime.Now.ToString(CultureInfo.InvariantCulture), ex.Message), pubnubConfig.LogVerbosity);
            internalcallback(false);
        }
Example #9
0
        //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);
        }
Example #10
0
        protected void OnPubnubWebRequestTimeout <T>(System.Object requestState)
        {
            RequestState <T> currentState = requestState as RequestState <T>;

            if (currentState != null && currentState.Response == null && currentState.Request != null)
            {
                currentState.Timeout = true;
                try
                {
                    currentState.Request.Abort();
                }
                catch { }
                LoggingMethod.WriteToLog(string.Format("DateTime: {0}, **WP7 OnPubnubWebRequestTimeout**", DateTime.Now.ToString()), pubnubConfig.LogVerbosity);
            }
        }
Example #11
0
        private static void OnPubnubWebRequestTimeout <T>(System.Object requestState)
        {
            RequestState <T> currentState = requestState as RequestState <T>;

            if (currentState != null && currentState.Response == null && currentState.Request != null)
            {
                currentState.Timeout = true;
                try
                {
                    currentState.Request.Abort();
                }
                catch { /* ignore */ }

                LoggingMethod.WriteToLog(pubnubLog, string.Format("DateTime: {0}, GetTimeWithClassicHttp timedout", DateTime.Now.ToString(CultureInfo.InvariantCulture)), pubnubConfig.LogVerbosity);
            }
        }
Example #12
0
        private string BuildQueryString(PNOperationType type, List <string> urlComponentList, Dictionary <string, string> queryStringParamDic)
        {
            string queryString = "";

            try
            {
                if (queryStringParamDic == null)
                {
                    queryStringParamDic = new Dictionary <string, string>();
                }

                Dictionary <string, string> commonQueryStringParams = GenerateCommonQueryParams(type);
                Dictionary <string, string> queryStringParams       = new Dictionary <string, string>(commonQueryStringParams.Concat(queryStringParamDic).GroupBy(item => item.Key).ToDictionary(item => item.Key, item => item.First().Value));

                string queryToSign = string.Join("&", queryStringParams.OrderBy(kvp => kvp.Key).Select(kvp => string.Format("{0}={1}", kvp.Key, kvp.Value)).ToArray());

                if (this.pubnubConfig.SecretKey.Length > 0)
                {
                    StringBuilder partialUrl = new StringBuilder();
                    for (int componentIndex = 0; componentIndex < urlComponentList.Count; componentIndex++)
                    {
                        partialUrl.Append("/");
                        if (type == PNOperationType.PNPublishOperation && componentIndex == urlComponentList.Count - 1)
                        {
                            partialUrl.Append(new UriUtil().EncodeUriComponent(urlComponentList[componentIndex], type, false, true, false));
                        }
                        else
                        {
                            partialUrl.Append(new UriUtil().EncodeUriComponent(urlComponentList[componentIndex], type, true, false, false));
                        }
                    }

                    string signature = GenerateSignature(queryToSign, partialUrl.ToString());
                    queryString = string.Format("{0}&signature={1}", queryToSign, signature);
                }
                else
                {
                    queryString = queryToSign;
                }
            }
            catch (Exception ex)
            {
                LoggingMethod.WriteToLog(pubnubLog, "UrlRequestBuilder => BuildQueryString error " + ex, pubnubConfig.LogVerbosity);
            }

            return(queryString);
        }
Example #13
0
        internal static bool CheckInternetStatus <T>(bool systemActive, PNOperationType type, PNCallback <T> callback, string[] channels, string[] channelGroups)
        {
            if (unit != null)
            {
                return(unit.InternetAvailable);
            }
            else
            {
                try
                {
#if NETFX_CORE || WINDOWS_UWP || UAP || NETSTANDARD10 || NETSTANDARD11 || NETSTANDARD12
                    Task[] tasks = new Task[1];
                    tasks[0] = Task.Factory.StartNew(async() =>
                    {
                        await CheckClientNetworkAvailability(CallbackClientNetworkStatus, type, callback, channels, channelGroups).ConfigureAwait(false);
                    }, CancellationToken.None, TaskCreationOptions.PreferFairness, TaskScheduler.Default);
                    tasks[0].ConfigureAwait(false);
                    Task.WaitAll(tasks);
#else
                    Thread networkCheckThread = new Thread(async() =>
                    {
                        await CheckClientNetworkAvailability(CallbackClientNetworkStatus, type, callback, channels, channelGroups).ConfigureAwait(false);
                    })
                    {
                        IsBackground = true
                    };
                    networkCheckThread.Start();
                    networkCheckThread.Join(pubnubConfig.NonSubscribeRequestTimeout * 1000);
#endif
                }
                catch (AggregateException ae) {
                    foreach (var ie in ae.InnerExceptions)
                    {
                        LoggingMethod.WriteToLog(pubnubLog, string.Format("DateTime {0} AggregateException CheckInternetStatus Error: {1} {2} ", DateTime.Now.ToString(CultureInfo.InvariantCulture), ie.GetType().Name, ie.Message), pubnubConfig.LogVerbosity);
                    }
                }
                catch (Exception ex)
                {
                    LoggingMethod.WriteToLog(pubnubLog, string.Format("DateTime {0} Exception CheckInternetStatus Error: {1}", DateTime.Now.ToString(CultureInfo.InvariantCulture), ex.Message), pubnubConfig.LogVerbosity);
                }

                return(networkStatus);
            }
        }
Example #14
0
        private void ForceCanonicalPathAndQuery(Uri requestUri)
        {
#if !NETSTANDARD10 && !NETSTANDARD11 && !NETSTANDARD12 && !WP81 && !PORTABLE111
            LoggingMethod.WriteToLog(pubnubLog, "Inside ForceCanonicalPathAndQuery = " + requestUri.ToString(), pubnubConfig.LogVerbosity);
            try
            {
                FieldInfo flagsFieldInfo = typeof(Uri).GetField("m_Flags", BindingFlags.Instance | BindingFlags.NonPublic);
                if (flagsFieldInfo != null)
                {
                    ulong flags = (ulong)flagsFieldInfo.GetValue(requestUri);
                    flags &= ~((ulong)0x30); // Flags.PathNotCanonical|Flags.QueryNotCanonical
                    flagsFieldInfo.SetValue(requestUri, flags);
                }
            }
            catch (Exception ex)
            {
                LoggingMethod.WriteToLog(pubnubLog, "Exception Inside ForceCanonicalPathAndQuery = " + ex, pubnubConfig.LogVerbosity);
            }
#endif
        }
Example #15
0
        private static void PrintUnity(PNConfiguration config, IPubnubLog log)
        {
#if UNITY_IOS || UNITY_IPHONE
            LoggingMethod.WriteToLog(log, string.Format("DateTime {0} PLATFORM = UNITY_IOS", DateTime.Now.ToString(CultureInfo.InvariantCulture)), config.LogVerbosity);
#elif UNITY_STANDALONE_WIN
            LoggingMethod.WriteToLog(log, string.Format("DateTime {0} PLATFORM = UNITY_STANDALONE_WIN", DateTime.Now.ToString(CultureInfo.InvariantCulture)), config.LogVerbosity);
#elif UNITY_STANDALONE_OSX
            LoggingMethod.WriteToLog(log, string.Format("DateTime {0} PLATFORM = UNITY_STANDALONE_OSX", DateTime.Now.ToString(CultureInfo.InvariantCulture)), config.LogVerbosity);
#elif UNITY_ANDROID
            LoggingMethod.WriteToLog(log, string.Format("DateTime {0} PLATFORM = UNITY_ANDROID", DateTime.Now.ToString(CultureInfo.InvariantCulture)), config.LogVerbosity);
#elif UNITY_STANDALONE_LINUX
            LoggingMethod.WriteToLog(log, string.Format("DateTime {0} PLATFORM = UNITY_STANDALONE_LINUX", DateTime.Now.ToString(CultureInfo.InvariantCulture)), config.LogVerbosity);
#elif UNITY_WEBPLAYER
            LoggingMethod.WriteToLog(log, string.Format("DateTime {0} PLATFORM = UNITY_WEBPLAYER", DateTime.Now.ToString(CultureInfo.InvariantCulture)), config.LogVerbosity);
#elif UNITY_WEBGL
            LoggingMethod.WriteToLog(log, string.Format("DateTime {0} PLATFORM = UNITY_WEBGL", DateTime.Now.ToString(CultureInfo.InvariantCulture)), config.LogVerbosity);
#else
            LoggingMethod.WriteToLog(log, string.Format("DateTime {0} PLATFORM = UNITY", DateTime.Now.ToString(CultureInfo.InvariantCulture)), config.LogVerbosity);
#endif
        }
Example #16
0
        protected void OnPubnubWebRequestTimeout <T>(System.Object requestState)
        {
            RequestState <T> currentState = requestState as RequestState <T>;

            if (currentState != null && currentState.Response == null && currentState.Request != null)
            {
                currentState.Timeout = true;
                try
                {
                    currentState.Request.Abort();
                }
                catch { /* ignore */ }

                LoggingMethod.WriteToLog(pubnubLog, string.Format("DateTime: {0}, **WP7 OnPubnubWebRequestTimeout**", DateTime.Now.ToString(CultureInfo.InvariantCulture)), pubnubConfig.LogVerbosity);

                if (currentState.ResponseType != PNOperationType.PNSubscribeOperation &&
                    currentState.ResponseType != PNOperationType.Presence &&
                    currentState.ResponseType != PNOperationType.PNHeartbeatOperation &&
                    currentState.ResponseType != PNOperationType.Leave)
                {
                    PNStatusCategory errorCategory = PNStatusCategory.PNTimeoutCategory;
                    PNStatus         status        = new StatusBuilder(pubnubConfig, jsonLib).CreateStatusResponse <T>(currentState.ResponseType, errorCategory, currentState, (int)HttpStatusCode.NotFound, new PNException("Request timeout"));

                    if (currentState.Channels != null && currentState.Channels.Length > 0)
                    {
                        status.AffectedChannels.AddRange(currentState.Channels);
                    }

                    if (currentState.ChannelGroups != null && currentState.ChannelGroups.Length > 0)
                    {
                        status.AffectedChannels.AddRange(currentState.ChannelGroups);
                    }

                    if (currentState.PubnubCallback != null)
                    {
                        currentState.PubnubCallback.OnResponse(default(T), status);
                    }
                }
            }
        }
Example #17
0
        //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(string.Format("DateTime: {0}, Inside SendRequestAndGetJsonResponseHttpClient", DateTime.Now.ToString()), pubnubConfig.LogVerbosity);
                HttpClient httpClient = new HttpClient();
                httpClient.DefaultRequestHeaders.Accept.Clear();
                httpClient.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
                httpClient.Timeout = TimeSpan.FromSeconds(GetTimeoutInSecondsForResponseType(pubnubRequestState.ResponseType));
                response           = await httpClient.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);
        }
Example #18
0
        private static async Task <bool> CheckClientNetworkAvailability <T>(Action <bool> internalCallback, PNOperationType type, PNCallback <T> callback, string[] channels, string[] channelGroups)
        {
            lock (internetCheckLock)
            {
                if (isInternetCheckRunning)
                {
                    LoggingMethod.WriteToLog(pubnubLog, string.Format("DateTime {0} InternetCheckRunning Already running", DateTime.Now.ToString(CultureInfo.InvariantCulture)), pubnubConfig.LogVerbosity);
                    return(networkStatus);
                }
            }

            InternetState <T> state = new InternetState <T>();

            state.InternalCallback = internalCallback;
            state.PubnubCallbacck  = callback;
            state.ResponseType     = type;
            state.Channels         = channels;
            state.ChannelGroups    = channelGroups;

            networkStatus = await CheckSocketConnect <T>(state).ConfigureAwait(false);

            return(networkStatus);
        }
Example #19
0
        private static async Task <bool> GetTimeWithHttpClient(Uri requestUri)
        {
            bool successFlag = false;

            try
            {
                var response = await httpClient.GetAsync(requestUri);

                successFlag = response.IsSuccessStatusCode;
                if (successFlag)
                {
                    LoggingMethod.WriteToLog(pubnubLog, string.Format("DateTime {0} GetTimeWithHttpClient Resp OK", DateTime.Now.ToString(CultureInfo.InvariantCulture)), pubnubConfig.LogVerbosity);
                }
                else
                {
                    LoggingMethod.WriteToLog(pubnubLog, string.Format("DateTime {0} GetTimeWithHttpClient FAILED", DateTime.Now.ToString(CultureInfo.InvariantCulture)), pubnubConfig.LogVerbosity);
                }
            }
            finally
            {
                networkStatus = successFlag;
            }
            return(networkStatus);
        }
Example #20
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));
        }
Example #21
0
        protected override byte[] EncryptOrDecrypt(bool type, byte[] dataBytes, bool dynamicIV)
        {
            string keyString = GetEncryptionKey();

            byte[] ivBytes = new byte[16];
            if (type)
            {
                                //encrypt
                if (dynamicIV)
                {
                    new Random().NextBytes(ivBytes);
                }
                else
                {
                    ivBytes = Encoding.UTF8.GetBytes("0123456789012345");
                }
            }
            else
            {
                //decrypt - check if random IV is part of the message
                if (dynamicIV)
                {
                    Array.Copy(dataBytes, 0, ivBytes, 0, 16);
                    byte[] receivedBytes = new byte[dataBytes.Length - 16];
                    Array.Copy(dataBytes, 16, receivedBytes, 0, dataBytes.Length - 16);
                    dataBytes = receivedBytes;
                }
                else
                {
                    ivBytes = System.Text.Encoding.UTF8.GetBytes("0123456789012345");
                }
            }
            if (pnUnit != null && pnUnit.IV != null && pnUnit.IV.Length == 16)
            {
                ivBytes = pnUnit.IV;
            }
            if (config != null)
            {
                LoggingMethod.WriteToLog(pubnubLog, string.Format("DateTime {0} IV = {1}", DateTime.Now.ToString(CultureInfo.InvariantCulture), GetDisplayableBytes(ivBytes)), config.LogVerbosity);
            }
#if NET35
            Aes aesAlg = Aes.Create();
            aesAlg.KeySize   = 256;
            aesAlg.BlockSize = 128;
            aesAlg.Mode      = CipherMode.CBC;
            aesAlg.Padding   = PaddingMode.PKCS7;
            aesAlg.IV        = ivBytes;
            aesAlg.Key       = System.Text.Encoding.UTF8.GetBytes(keyString);
#else
            byte[] iv       = ivBytes;
            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
                byte[] outputBytes = null;
#if NET35
                ICryptoTransform crypto     = aesAlg.CreateEncryptor();
                byte[]           plainBytes = dataBytes;
                outputBytes = crypto.TransformFinalBlock(plainBytes, 0, plainBytes.Length);
#else
                byte[] inputBytes = dataBytes;
                cipher.Init(true, keyParamWithIV);
                outputBytes = new byte[cipher.GetOutputSize(inputBytes.Length)];
                int length = cipher.ProcessBytes(inputBytes, outputBytes, 0);
                cipher.DoFinal(outputBytes, length); //Do the final block
#endif
                byte[] newOutputBytes = null;
                if (dynamicIV)
                {
                    newOutputBytes = new byte[ivBytes.Length + outputBytes.Length];
                    Buffer.BlockCopy(ivBytes, 0, newOutputBytes, 0, ivBytes.Length);
                    Buffer.BlockCopy(outputBytes, 0, newOutputBytes, ivBytes.Length, outputBytes.Length);
                }
                else
                {
                    newOutputBytes = outputBytes;
                }

                return(newOutputBytes);
            }
            else
            {
                byte[] newOutputBytes = null;
                try
                {
                    //Decrypt
#if NET35
                    byte[]           decryptedBytes = dataBytes;
                    ICryptoTransform decrypto       = aesAlg.CreateDecryptor();

                    var data = decrypto.TransformFinalBlock(decryptedBytes, 0, decryptedBytes.Length);
                    newOutputBytes = data;
#else
                    byte[] inputBytes = dataBytes;
                    cipher.Init(false, keyParamWithIV);
                    byte[] encryptedBytes   = new byte[cipher.GetOutputSize(inputBytes.Length)];
                    var    encryptLength    = cipher.ProcessBytes(inputBytes, encryptedBytes, 0);
                    var    lastBytesLength  = cipher.DoFinal(encryptedBytes, encryptLength); //Do the final block
                    var    totalBytesLength = encryptLength + lastBytesLength;
                    newOutputBytes = new byte[totalBytesLength];
                    Array.Copy(encryptedBytes, newOutputBytes, totalBytesLength);
#endif
                    return(newOutputBytes);
                }
                catch (Exception ex)
                {
                    if (config != null)
                    {
                        LoggingMethod.WriteToLog(pubnubLog, string.Format("DateTime {0} Decrypt Error. {1}", DateTime.Now.ToString(CultureInfo.InvariantCulture), ex), config.LogVerbosity);
                    }
                    throw;
                }
            }
        }
Example #22
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).ConfigureAwait(false));
 }
Example #23
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(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("");
            }
        }
Example #24
0
        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;
            }
        }
Example #25
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**";
                }
            }
        }
Example #26
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;
             */
        }
Example #27
0
        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("");
            }
        }
Example #28
0
        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);
        }
Example #29
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));
        }