コード例 #1
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);
        }
コード例 #2
0
        public List <object> DecodeDecryptLoop <T>(List <object> message, string[] channels, string[] channelGroups, PNCallback <T> errorCallback)
        {
            List <object> returnMessage = new List <object>();

            if (config.CipherKey.Length > 0)
            {
                PubnubCrypto aes           = new PubnubCrypto(config.CipherKey, config, pubnubLog);
                object[]     myObjectArray = (from item in message
                                              select item as object).ToArray();
                object[] enumerable = myObjectArray[0] as object[];
                if (enumerable != null)
                {
                    List <object> receivedMsg = new List <object>();
                    foreach (object element in enumerable)
                    {
                        string decryptMessage = "";
                        try
                        {
                            Dictionary <string, object> historyEnv = jsonLib.ConvertToDictionaryObject(element);
                            if (historyEnv != null && historyEnv.ContainsKey("message"))
                            {
                                string dictionaryValue = aes.Decrypt(historyEnv["message"].ToString());
                                historyEnv["message"] = jsonLib.DeserializeToObject(dictionaryValue);
                                decryptMessage        = jsonLib.SerializeToJsonString(historyEnv);
                            }
                            else
                            {
                                decryptMessage = aes.Decrypt(element.ToString());
                            }
                        }
                        catch (Exception ex)
                        {
                            decryptMessage = "**DECRYPT ERROR**";

                            PNStatusCategory category = PNStatusCategoryHelper.GetPNStatusCategory(ex);
                            PNStatus         status   = new StatusBuilder(config, jsonLib).CreateStatusResponse <T>(PNOperationType.PNHistoryOperation, category, null, (int)HttpStatusCode.NotFound, new PNException(ex));
                            if (channels != null && channels.Length > 0)
                            {
                                status.AffectedChannels.AddRange(channels);
                            }
                            if (channelGroups != null && channelGroups.Length > 0)
                            {
                                status.AffectedChannelGroups.AddRange(channelGroups);
                            }

                            errorCallback.OnResponse(default(T), status);
                        }
                        object decodeMessage = (decryptMessage == "**DECRYPT ERROR**") ? decryptMessage : jsonLib.DeserializeToObject(decryptMessage);
                        receivedMsg.Add(decodeMessage);
                    }
                    returnMessage.Add(receivedMsg);
                }

                for (int index = 1; index < myObjectArray.Length; index++)
                {
                    returnMessage.Add(myObjectArray[index]);
                }
                return(returnMessage);
            }
            else
            {
                var myObjectArray = (from item in message
                                     select item as object).ToArray();
                IEnumerable enumerable = myObjectArray[0] as IEnumerable;
                if (enumerable != null)
                {
                    List <object> receivedMessage = new List <object>();
                    foreach (object element in enumerable)
                    {
                        receivedMessage.Add(element);
                    }
                    returnMessage.Add(receivedMessage);
                }
                for (int index = 1; index < myObjectArray.Length; index++)
                {
                    returnMessage.Add(myObjectArray[index]);
                }
                return(returnMessage);
            }
        }
コード例 #3
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);
        }
コード例 #4
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));
        }
コード例 #5
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);
            }
        }
コード例 #6
0
ファイル: SecureMessage.cs プロジェクト: sinxsoft/c-sharp
        public List <object> FetchHistoryDecodeDecryptLoop <T>(PNOperationType type, Dictionary <string, object> messageContainer, string[] channels, string[] channelGroups, PNCallback <T> errorCallback)
        {
            List <object> returnMessage = new List <object>();

            Dictionary <string, List <object> > dicMessage = new Dictionary <string, List <object> >();

            foreach (KeyValuePair <string, object> kvp in messageContainer)
            {
                List <object> currentVal = kvp.Value as List <object>;
                if (currentVal != null)
                {
                    object[]      currentValArray = jsonLib.ConvertToObjectArray(currentVal);
                    List <object> decryptList     = (currentValArray != null && currentValArray.Length > 0) ? new List <object>() : null;
                    if (currentValArray != null && decryptList != null)
                    {
                        foreach (object currentObj in currentValArray)
                        {
                            Dictionary <string, object> dicValue = jsonLib.ConvertToDictionaryObject(currentObj);
                            if (dicValue != null && dicValue.Count > 0 && dicValue.ContainsKey("message"))
                            {
                                Dictionary <string, object> dicDecrypt = new Dictionary <string, object>();
                                foreach (KeyValuePair <string, object> kvpValue in dicValue)
                                {
                                    if (kvpValue.Key == "message" && config.CipherKey.Length > 0)
                                    {
                                        PubnubCrypto aes            = new PubnubCrypto(config.CipherKey, config, pubnubLog);
                                        string       decryptMessage = "";
                                        try
                                        {
                                            decryptMessage = aes.Decrypt(kvpValue.Value.ToString());
                                        }
                                        catch (Exception ex)
                                        {
                                            #region "Exception"
                                            decryptMessage = "**DECRYPT ERROR**";

                                            PNStatusCategory category = PNStatusCategoryHelper.GetPNStatusCategory(ex);
                                            PNStatus         status   = new StatusBuilder(config, jsonLib).CreateStatusResponse <T>(type, category, null, (int)HttpStatusCode.NotFound, new PNException(ex));
                                            if (channels != null && channels.Length > 0)
                                            {
                                                status.AffectedChannels.AddRange(channels);
                                            }
                                            if (channelGroups != null && channelGroups.Length > 0)
                                            {
                                                status.AffectedChannelGroups.AddRange(channelGroups);
                                            }

                                            errorCallback.OnResponse(default(T), status);
                                            #endregion
                                        }
                                        object decodeMessage = (decryptMessage == "**DECRYPT ERROR**") ? decryptMessage : jsonLib.DeserializeToObject(decryptMessage);
                                        dicDecrypt.Add(kvpValue.Key, decodeMessage);
                                    }
                                    else
                                    {
                                        dicDecrypt.Add(kvpValue.Key, kvpValue.Value);
                                    }
                                }
                                decryptList.Add(dicDecrypt);
                            }
                        }
                    }
                    dicMessage.Add(kvp.Key, decryptList);
                }
            }
            if (dicMessage.Count > 0)
            {
                returnMessage.Add(dicMessage);
            }
            return(returnMessage);
        }
コード例 #7
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);
            }
        }
コード例 #8
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));
        }
コード例 #9
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);
        }