internal static void SendCallbacks <T>(IJsonPluggableLibrary jsonPluggableLibrary, List <ChannelEntity> channelEntities, List <object> itemMessage, CallbackType callbackType, bool checkType) { if (channelEntities != null) { if ((itemMessage != null) && (itemMessage.Count > 0)) { #if (ENABLE_PUBNUB_LOGGING) LoggingMethod.WriteToLog(string.Format("DateTime {0}, SendCallbacks2: itemMessage.Count={1} {2}", DateTime.Now.ToString(), itemMessage.Count.ToString(), channelEntities.Count.ToString() ), LoggingMethod.LevelInfo); #endif foreach (ChannelEntity channelEntity in channelEntities) { SendCallbackChannelEntity <T> (jsonPluggableLibrary, channelEntity, itemMessage, callbackType, checkType); } } #if (ENABLE_PUBNUB_LOGGING) else { LoggingMethod.WriteToLog(string.Format("DateTime {0}, SendCallbacks2: itemMessage null or count <0", DateTime.Now.ToString()), LoggingMethod.LevelInfo); } #endif } #if (ENABLE_PUBNUB_LOGGING) else { LoggingMethod.WriteToLog(string.Format("DateTime {0}, SendCallbacks2: channelEntities null", DateTime.Now.ToString()), LoggingMethod.LevelInfo); } #endif }
protected override bool HandleWebException <T> (WebException webEx, RequestState <T> asynchRequestState, string channel) { bool reconnect = false; if ((webEx.Status == WebExceptionStatus.NameResolutionFailure ||//No network webEx.Status == WebExceptionStatus.ConnectFailure ||//Sending Keep-alive packet failed (No network)/Server is down. webEx.Status == WebExceptionStatus.ServerProtocolViolation ||//Problem with proxy or ISP webEx.Status == WebExceptionStatus.ProtocolError ) && (overrideTcpKeepAlive)) { //LoggingMethod.WriteToLog (string.Format ("DateTime {0}, _urlRequest - Internet connection problem", DateTime.Now.ToString ()), LoggingMethod.LevelError); //internet connection problem. LoggingMethod.WriteToLog(string.Format("DateTime {0}, _urlRequest - Internet connection problem", DateTime.Now.ToString()), LoggingMethod.LevelError); if (base.channelInternetStatus.ContainsKey(channel) && (asynchRequestState.Type == ResponseType.Subscribe || asynchRequestState.Type == ResponseType.Presence)) { reconnect = true; if (base.channelInternetStatus [channel]) { //Reset Retry if previous state is true base.channelInternetRetry.AddOrUpdate(channel, 0, (key, oldValue) => 0); } else { base.channelInternetRetry.AddOrUpdate(channel, 1, (key, oldValue) => oldValue + 1); string multiChannel = (asynchRequestState.Channels != null) ? string.Join(",", asynchRequestState.Channels) : ""; LoggingMethod.WriteToLog(string.Format("DateTime {0} {1} channel = {2} _urlRequest - Internet connection retry {3} of {4}", DateTime.Now.ToString(), asynchRequestState.Type, multiChannel, base.channelInternetRetry [channel], base.NetworkCheckMaxRetries), LoggingMethod.LevelInfo); string message = string.Format("Detected internet connection problem. Retrying connection attempt {0} of {1}", base.channelInternetRetry [channel], base.NetworkCheckMaxRetries); CallErrorCallback(PubnubErrorSeverity.Warn, PubnubMessageSource.Client, multiChannel, asynchRequestState.ErrorCallback, message, PubnubErrorCode.NoInternetRetryConnect, null, null); } base.channelInternetStatus [channel] = false; } } Thread.Sleep(base.NetworkCheckRetryInterval * 1000); return(reconnect); }
internal static Uri BuildPresenceHeartbeatRequest(string[] channels, string channelsJsonState, string uuid, bool ssl, string origin, string authenticationKey, string subscribeKey) { string parameters = ""; if (channelsJsonState != "{}" && channelsJsonState != "") { parameters = string.Format("&state={0}", Utility.EncodeUricomponent(channelsJsonState, ResponseType.PresenceHeartbeat, false, false)); } #if (ENABLE_PUBNUB_LOGGING) LoggingMethod.WriteToLog(string.Format("DateTime {0}, presenceHeartbeatParameters {1}", DateTime.Now.ToString(), parameters), LoggingMethod.LevelInfo); #endif List <string> url = new List <string> (); url.Add("v2"); url.Add("presence"); url.Add("sub_key"); url.Add(subscribeKey); url.Add("channel"); url.Add(string.Join(",", channels)); url.Add("heartbeat"); return(BuildRestApiRequest <Uri> (url, ResponseType.PresenceHeartbeat, uuid, ssl, origin, 0, authenticationKey, parameters)); }
private static void CheckClientNetworkAvailability <T>(Action <bool> callback, Action <PubnubClientError> errorCallback, string[] channels, string[] channelGroups) { lock (_internetCheckLock) { if (isInternetCheckRunning) { LoggingMethod.WriteToLog(string.Format("DateTime {0} InternetCheckRunning Already running", DateTime.Now.ToString()), LoggingMethod.LevelInfo); return; } } mres = new ManualResetEvent(false); InternetState <T> state = new InternetState <T>(); state.Callback = callback; state.ErrorCallback = errorCallback; state.Channels = channels; state.ChannelGroups = channelGroups; #if !PORTABLE151 && !PORTABLE259 && !PORTABLE111 && !WP81 ThreadPool.QueueUserWorkItem(CheckSocketConnect <T>, state); #else CheckSocketConnect <T>(state); #endif mres.WaitOne(500); }
/// <summary> /// Initializes the channel set. /// </summary> /// <param name="log">The log.</param> /// <param name="indexList">The index list.</param> /// <param name="loggingMethod">The logging method.</param> /// <param name="numDataValue">The number data value.</param> public void InitChannelSet(Log log, List <ChannelIndex> indexList, LoggingMethod loggingMethod = LoggingMethod.computed, int numDataValue = 150) { ChannelSet channelSet = LogGenerator.CreateChannelSet(log); channelSet.Index = indexList; bool isDepth = log.TimeDepth.EqualsIgnoreCase(ObjectFolders.Depth); if (isDepth) { var pointMetadataList = List(LogGenerator.CreatePointMetadata("Quality", "Quality", EtpDataType.boolean)); channelSet.Channel.Add(LogGenerator.CreateChannel(log, indexList, "Rate of Penetration", "ROP", UnitOfMeasure.mh, "Velocity", EtpDataType.@double, pointMetadataList: pointMetadataList)); channelSet.Channel.Add(LogGenerator.CreateChannel(log, indexList, "Hookload", "HKLD", UnitOfMeasure.klbf, "Force", EtpDataType.@double, null)); } else { var pointMetadataList = List(LogGenerator.CreatePointMetadata("Confidence", "Confidence", EtpDataType.@float)); channelSet.Channel.Add(LogGenerator.CreateChannel(log, indexList, "Rate of Penetration", "ROP", UnitOfMeasure.mh, "Velocity", EtpDataType.@double, pointMetadataList: pointMetadataList)); } log.ChannelSet = new List <ChannelSet>(); log.ChannelSet.Add(channelSet); LogGenerator.GenerateChannelData(log.ChannelSet, numDataValue: numDataValue); }
internal static void SendCallbacksBasedOnType <T>(SafeDictionary <PubnubChannelCallbackKey, object> channelCallbacks, IJsonPluggableLibrary jsonPluggableLibrary, string currentChannel, List <object> itemMessage) { var callbackKey = PubnubCallbacks.GetPubnubChannelCallbackKey(currentChannel, (Utility.IsPresenceChannel(currentChannel)) ? ResponseType.Presence : ResponseType.Subscribe); #if (ENABLE_PUBNUB_LOGGING) LoggingMethod.WriteToLog(string.Format("DateTime {0}, currentChannel: {1}", DateTime.Now.ToString(), currentChannel.ToString()), LoggingMethod.LevelInfo); #endif if (channelCallbacks.Count > 0 && channelCallbacks.ContainsKey(callbackKey)) { #if (ENABLE_PUBNUB_LOGGING) LoggingMethod.WriteToLog(string.Format("DateTime {0}, typeof(T): {1}", DateTime.Now.ToString(), typeof(T).ToString()), LoggingMethod.LevelInfo); #endif if ((typeof(T) == typeof(string) && channelCallbacks[callbackKey].GetType().Name.Contains("[System.String]")) || (typeof(T) == typeof(object) && channelCallbacks[callbackKey].GetType().Name.Contains("[System.Object]"))) { CallCallback <T>(callbackKey, channelCallbacks, jsonPluggableLibrary, itemMessage); } else if (channelCallbacks[callbackKey].GetType().FullName.Contains("[System.String")) { CallCallbackKnownType <string>(callbackKey, channelCallbacks, jsonPluggableLibrary, itemMessage); } else if (channelCallbacks[callbackKey].GetType().FullName.Contains("[System.Object")) { CallCallbackKnownType <object>(callbackKey, channelCallbacks, jsonPluggableLibrary, itemMessage); } } }
internal static void ResponseToUserCallbackForSubscribeSendCallbacks <T> (List <object> result, string cipherKey, SafeDictionary <PubnubChannelCallbackKey, object> channelCallbacks, IJsonPluggableLibrary jsonPluggableLibrary, object[] messages) { #if (ENABLE_PUBNUB_LOGGING) LoggingMethod.WriteToLog(string.Format("DateTime {0}, messageList typeOF: {1}", DateTime.Now.ToString(), messages [0].GetType().ToString()), LoggingMethod.LevelInfo); #endif var messageList = messages [0] as object[]; messageList = CreateMessageList(result, messageList); string[] messageChannels = messages [2].ToString().Split(','); #if (ENABLE_PUBNUB_LOGGING) LoggingMethod.WriteToLog(string.Format("DateTime {0}, (messageChannels: {1}", DateTime.Now.ToString(), messageChannels.ToString()), LoggingMethod.LevelInfo); #endif if (messageList != null && messageList.Length > 0) { for (int messageIndex = 0; messageIndex < messageList.Length; messageIndex++) { string currentChannel = (messageChannels.Length == 1) ? (string)messageChannels[0] : (string)messageChannels[messageIndex]; var itemMessage = AddMessageToList(cipherKey, jsonPluggableLibrary, messages, messageIndex, currentChannel, messageList); PubnubCallbacks.SendCallbacksBasedOnType <T>(channelCallbacks, jsonPluggableLibrary, currentChannel, itemMessage); } } }
public void StoreLatency(long latencyMillisec, PNOperationType type) { try { string latencyEndPoint = EndpointNameForOperation(type); if (latencyMillisec > 0 && !string.IsNullOrEmpty(latencyEndPoint)) { double epochMillisec = (DateTime.UtcNow - new DateTime(1970, 1, 1, 0, 0, 0, DateTimeKind.Utc)).TotalMilliseconds; if (dicEndpointLatency.ContainsKey(latencyEndPoint)) { dicEndpointLatency[latencyEndPoint].AddOrUpdate(epochMillisec, latencyMillisec, (key, oldValue) => latencyMillisec); } else { ConcurrentDictionary <double, long> elapsedInfo = new ConcurrentDictionary <double, long>(); elapsedInfo.Add(epochMillisec, latencyMillisec); dicEndpointLatency.Add(latencyEndPoint, elapsedInfo); } System.Diagnostics.Debug.WriteLine(string.Format("{0} latency = {1}", type, latencyMillisec)); } } catch (Exception ex) { LoggingMethod.WriteToLog(pubnubLog, string.Format("DateTime {0}, TelemetryManager - StoreLatency error: {1}", DateTime.Now.ToString(CultureInfo.InvariantCulture), ex), pubnubConfig.LogVerbosity); } }
protected override sealed void Init(string publishKey, string subscribeKey, string secretKey, string cipherKey, bool sslOn) { #if (USE_JSONFX) || (USE_JSONFX_UNITY) LoggingMethod.WriteToLog("Using USE_JSONFX", LoggingMethod.LevelInfo); this.JsonPluggableLibrary = new JsonFXDotNet(); #elif (USE_DOTNET_SERIALIZATION) LoggingMethod.WriteToLog("Using USE_DOTNET_SERIALIZATION", LoggingMethod.LevelInfo); this.JsonPluggableLibrary = new JscriptSerializer(); #elif (USE_MiniJSON) LoggingMethod.WriteToLog("USE_MiniJSON", LoggingMethod.LevelInfo); this.JsonPluggableLibrary = new MiniJSONObjectSerializer(); #elif (USE_JSONFX_UNITY_IOS) LoggingMethod.WriteToLog("USE_JSONFX_FOR_UNITY", LoggingMethod.LevelInfo); this.JsonPluggableLibrary = new JsonFxUnitySerializer(); #else LoggingMethod.WriteToLog("Using NewtonsoftJsonDotNet", LoggingMethod.LevelInfo); base.JsonPluggableLibrary = new NewtonsoftJsonDotNet(); #endif LoggingMethod.LogLevel = pubnubLogLevel; base.PubnubLogLevel = pubnubLogLevel; base.PubnubErrorLevel = errorLevel; base.publishKey = publishKey; base.secretKey = secretKey; base.cipherKey = cipherKey; base.subscribeKey = subscribeKey; base.ssl = sslOn; base.VerifyOrSetSessionUUID(); PubnubWebRequest.ServicePointConnectionLimit = 300; }
internal static void CheckSubscribedChannelsAndSendCallbacks <T> (string[] channels, bool isPresence, ResponseType type, int pubnubNetworkCheckRetries, SafeDictionary <PubnubChannelCallbackKey, object> channelCallbacks, PubnubErrorFilter.Level errorLevel) { if (channels != null && channels.Length > 0) { string message = string.Format("Unsubscribed after {0} failed retries", pubnubNetworkCheckRetries);; PubnubErrorCode pnErrorCode = PubnubErrorCode.UnsubscribedAfterMaxRetries; if (isPresence) { message = string.Format("Presence Unsubscribed after {0} failed retries", pubnubNetworkCheckRetries); pnErrorCode = PubnubErrorCode.PresenceUnsubscribedAfterMaxRetries; } PubnubCallbacks.FireErrorCallbacksForAllChannels <T> (message, null, channels, PubnubErrorSeverity.Critical, channelCallbacks, false, pnErrorCode, type, errorLevel); #if (ENABLE_PUBNUB_LOGGING) LoggingMethod.WriteToLog(string.Format("DateTime {0}, {1} Subscribe JSON network error response={2}", DateTime.Now.ToString(), (isPresence)?"Presence":"", message), LoggingMethod.LevelInfo); #endif } }
void HandleTcpClientResponse <T> (StateObject <T> state, RequestState <T> asynchRequestState, string channel, IAsyncResult asynchronousResult) { List <object> result = new List <object> (); if (state.sb.Length > 1) { string jsonString = ParseResponse <T> (state.sb.ToString(), asynchronousResult); LoggingMethod.WriteToLog(string.Format("DateTime {0}, JSON for channel={1} ({2}) ={3}", DateTime.Now.ToString(), channel, asynchRequestState.Type.ToString(), jsonString), LoggingMethod.LevelInfo); if (overrideTcpKeepAlive) { TerminateLocalClientHeartbeatTimer(state.RequestState.Request.RequestUri); } if (jsonString != null && !string.IsNullOrEmpty(jsonString) && !string.IsNullOrEmpty(channel.Trim())) { result = WrapResultBasedOnResponseType <T> (asynchRequestState.Type, jsonString, asynchRequestState.Channels, asynchRequestState.Reconnect, asynchRequestState.Timetoken, asynchRequestState.ErrorCallback); } ProcessResponseCallbacks <T> (result, asynchRequestState); } if (state.tcpClient != null) { state.tcpClient.Close(); } }
private void Unsubscribe(string[] channels, string[] channelGroups) { if ((channels == null || channels.Length == 0) && (channelGroups == null || channelGroups.Length == 0)) { throw new ArgumentException("Either Channel Or Channel Group or Both should be provided."); } string channel = (channels != null) ? string.Join(",", channels.OrderBy(x => x).ToArray()) : ""; string channelGroup = (channelGroups != null) ? string.Join(",", channelGroups.OrderBy(x => x).ToArray()) : ""; LoggingMethod.WriteToLog(pubnubLog, string.Format("DateTime {0}, requested unsubscribe for channel(s)={1}, cg(s)={2}", DateTime.Now.ToString(CultureInfo.InvariantCulture), channel, channelGroup), config.LogVerbosity); #if NETFX_CORE || WINDOWS_UWP || UAP || NETSTANDARD Task.Factory.StartNew(() => { SubscribeManager manager = new SubscribeManager(config, jsonLibrary, unit, pubnubLog, pubnubTelemetryMgr, PubnubInstance); manager.CurrentPubnubInstance(PubnubInstance); manager.MultiChannelUnSubscribeInit <T>(PNOperationType.PNUnsubscribeOperation, channel, channelGroup, this.queryParam); }, CancellationToken.None, TaskCreationOptions.PreferFairness, TaskScheduler.Default).ConfigureAwait(false); #else new Thread(() => { SubscribeManager manager = new SubscribeManager(config, jsonLibrary, unit, pubnubLog, pubnubTelemetryMgr, PubnubInstance); manager.CurrentPubnubInstance(PubnubInstance); manager.MultiChannelUnSubscribeInit <T>(PNOperationType.PNUnsubscribeOperation, channel, channelGroup, this.queryParam); }) { IsBackground = true }.Start(); #endif }
public void ProcessTimeout <T> (CoroutineParams <T> cp) { try { if (!CheckComplete(cp.crt)) { if (cp.typeParameterType == typeof(string)) { FireEvent("Timed out", true, true, cp.requestState, cp.crt); #if (ENABLE_PUBNUB_LOGGING) LoggingMethod.WriteToLog(string.Format("DateTime {0}, WWW Error: {1} sec timeout", DateTime.Now.ToString(), cp.timeout.ToString()), LoggingMethod.LevelInfo); #endif } else if (cp.typeParameterType == typeof(object)) { FireEvent("Timed out", true, true, cp.requestState, cp.crt); #if (ENABLE_PUBNUB_LOGGING) LoggingMethod.WriteToLog(string.Format("DateTime {0}, WWW Error: {1} sec timeout", DateTime.Now.ToString(), cp.timeout.ToString()), LoggingMethod.LevelInfo); #endif } else { throw new Exception("'string' and 'object' are the only types supported in generic method calls"); } } } catch (Exception ex) { #if (ENABLE_PUBNUB_LOGGING) LoggingMethod.WriteToLog(string.Format("DateTime {0}, CheckTimeout: {1} {2}", DateTime.Now.ToString(), ex.ToString(), cp.crt.ToString()), LoggingMethod.LevelError); #endif } }
void SetComplete(CurrentRequestType crt) { try { if (crt == CurrentRequestType.Heartbeat) { StopCoroutine(HeartbeatTimeoutCoroutine); isHearbeatComplete = true; } else if (crt == CurrentRequestType.PresenceHeartbeat) { StopCoroutine(PresenceHeartbeatTimeoutCoroutine); isPresenceHeartbeatComplete = true; } else if (crt == CurrentRequestType.Subscribe) { StopCoroutine(SubTimeoutCoroutine); isSubscribeComplete = true; } else { StopCoroutine(NonSubTimeoutCoroutine); isNonSubscribeComplete = true; } #if (ENABLE_PUBNUB_LOGGING) LoggingMethod.WriteToLog(string.Format("DateTime {0}, SetComplete Complete {1}", DateTime.Now.ToString(), crt.ToString()), LoggingMethod.LevelInfo); #endif } catch (Exception ex) { LoggingMethod.WriteToLog(string.Format("DateTime {0}, SetComplete Exception: ", DateTime.Now.ToString(), ex.ToString()), LoggingMethod.LevelError); } }
public void CallFireEvent <T> (string message, bool isError, bool isTimeout, RequestState <T> pubnubRequestState, CoroutineParams <T> cp) { #if (ENABLE_PUBNUB_LOGGING) LoggingMethod.WriteToLog(string.Format("DateTime {0}, CallFireEvent RequestType {1} {2} {3}", DateTime.Now.ToString(), typeof(T), pubnubRequestState.GetType(), pubnubRequestState.Channels), LoggingMethod.LevelInfo); #endif FireEvent(message, isError, false, pubnubRequestState, cp.crt); }
public IEnumerator SendRequestSub <T> (CoroutineParams <T> cp) { #if (ENABLE_PUBNUB_LOGGING) LoggingMethod.WriteToLog(string.Format("DateTime {0}, URL Sub {1} ", DateTime.Now.ToString(), cp.url.ToString()), LoggingMethod.LevelInfo); #endif WWW www; isSubscribeComplete = false; subscribeWww = new WWW(cp.url); yield return(subscribeWww); if ((subscribeWww != null) && (subscribeWww.isDone)) { www = subscribeWww; } else { www = null; } #if (ENABLE_PUBNUB_LOGGING) LoggingMethod.WriteToLog(string.Format("DateTime {0},After www type {1}", DateTime.Now.ToString(), typeof(T)), LoggingMethod.LevelError); #endif ProcessResponse <T> (www, cp); }
internal static void CommonExceptionHandler <T> (RequestState <T> requestState, string message, bool requestTimeout, PubnubErrorFilter.Level errorLevel ) { if (requestTimeout) { message = "Operation Timeout"; #if (ENABLE_PUBNUB_LOGGING) LoggingMethod.WriteToLog(string.Format("DateTime {0}, {1} CommonExceptionHandler response={2}", DateTime.Now.ToString(), requestState.RespType.ToString(), message), LoggingMethod.LevelInfo); #endif PubnubCallbacks.FireErrorCallbacksForAllChannels <T> (message, requestState, PubnubErrorSeverity.Critical, Helpers.GetTimeOutErrorCode(requestState.RespType), errorLevel); } else { #if (ENABLE_PUBNUB_LOGGING) LoggingMethod.WriteToLog(string.Format("DateTime {0}, {1} CommonExceptionHandler response={2}", DateTime.Now.ToString(), requestState.RespType.ToString(), message), LoggingMethod.LevelInfo); #endif PubnubCallbacks.FireErrorCallbacksForAllChannels <T> (message, requestState, PubnubErrorSeverity.Critical, PubnubErrorCode.None, errorLevel); } }
public async Task <Dictionary <string, string> > GetOperationsLatency() { return(await Task <Dictionary <string, string> > .Factory.StartNew(() => { Dictionary <string, string> dictionaryOpsLatency = new Dictionary <string, string>(); try { lock (operationLatencyDataLock) { if (dicEndpointLatency != null) { foreach (string key in dicEndpointLatency.Keys) { if (dicEndpointLatency[key] != null && dicEndpointLatency[key].Count > 0) { dictionaryOpsLatency.Add(key, Math.Round(((double)dicEndpointLatency[key].Average(kvp => kvp.Value) / 1000.0), 10).ToString(CultureInfo.InvariantCulture)); //Convert millisec to sec } } } } } catch (Exception ex) { LoggingMethod.WriteToLog(pubnubLog, string.Format("DateTime {0}, TelemetryManager - GetOperationsLatency error: {1}", DateTime.Now.ToString(CultureInfo.InvariantCulture), ex), pubnubConfig.LogVerbosity); } return dictionaryOpsLatency; }, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).ConfigureAwait(false)); }
public object GetStoredRequestState(CurrentRequestType aKey) { if (requestStates.ContainsKey(aKey)) { if (requestStates.ContainsKey(aKey)) { #if (ENABLE_PUBNUB_LOGGING) LoggingMethod.WriteToLog(string.Format("DateTime {0}, GetStoredRequestState {1}", DateTime.Now.ToString(), aKey.ToString()), LoggingMethod.LevelInfo); #endif return(requestStates [aKey]); } #if (ENABLE_PUBNUB_LOGGING) LoggingMethod.WriteToLog(string.Format("DateTime {0}, GetStoredRequestState returning false", DateTime.Now.ToString()), LoggingMethod.LevelInfo); #endif } #if (ENABLE_PUBNUB_LOGGING) else { LoggingMethod.WriteToLog(string.Format("DateTime {0}, GetStoredRequestState doesnt contain key {1}", DateTime.Now.ToString(), aKey.ToString()), LoggingMethod.LevelInfo); } #endif return(null); }
public bool RemoveListener(SubscribeCallback listener) { bool ret = false; if (listener != null) { lock (syncLockSubscribeCallback) { try { if (SubscribeCallbackListenerList.ContainsKey(PubnubInstance.InstanceId)) { List <SubscribeCallback> callbackList = SubscribeCallbackListenerList[PubnubInstance.InstanceId]; if (callbackList.Remove(listener)) { ret = true; } SubscribeCallbackListenerList[PubnubInstance.InstanceId] = callbackList; } } catch (Exception ex) { LoggingMethod.WriteToLog(pubnubLog, string.Format("DateTime {0}, ListenerManager RemoveListener => Exception = {1}", DateTime.Now.ToString(CultureInfo.InvariantCulture), ex), pubnubConfig.LogVerbosity); } } } return(ret); }
internal static object[] CreateMessageList(List <object> result, object[] messageList) { int i = 0; foreach (object o in result) { if (i == 0) { IList collection = (IList)o; messageList = new object[collection.Count]; bool added = false; int j = 0; foreach (object c in collection) { if ((c.GetType() == typeof(System.Int32)) || (c.GetType() == typeof(System.Double)) || (c.GetType() == typeof(System.Int64)) || (c.GetType() == typeof(System.Boolean))) { added = true; #if (ENABLE_PUBNUB_LOGGING) LoggingMethod.WriteToLog(string.Format("DateTime {0}, collection: {1} in type: {2}", DateTime.Now.ToString(), c.ToString(), c.GetType().ToString()), LoggingMethod.LevelInfo); #endif messageList[j] = c; } else if (c.GetType() == typeof(System.String)) { added = true; #if (ENABLE_PUBNUB_LOGGING) LoggingMethod.WriteToLog(string.Format("DateTime {0}, collection: {1} in type: {2}", DateTime.Now.ToString(), c.ToString(), c.GetType().ToString()), LoggingMethod.LevelInfo); #endif messageList[j] = c.ToString(); } else { try { messageList[j] = c; added = true; #if (ENABLE_PUBNUB_LOGGING) LoggingMethod.WriteToLog(string.Format("DateTime {0}, collection other types: {1} in type: {2}", DateTime.Now.ToString(), c.ToString(), c.GetType().ToString()), LoggingMethod.LevelInfo); #endif } catch (Exception ex) { added = false; #if (ENABLE_PUBNUB_LOGGING) LoggingMethod.WriteToLog(string.Format("DateTime {0}, collection other types: {1} in type: {2}, exception {3} ", DateTime.Now.ToString(), c.ToString(), c.GetType().ToString(), ex.ToString()), LoggingMethod.LevelInfo); #endif } } j++; } if (!added) { collection.CopyTo(messageList, 0); } } i++; } return(messageList); }
public async Task <PNResult <PNAccessManagerGrantResult> > ExecuteAsync() { if (config != null && pubnubLog != null) { LoggingMethod.WriteToLog(pubnubLog, string.Format("DateTime: {0}, WARNING: Grant() signature has changed! This specific call will be making a request to PAMv2. Please update your code if this is not the intended action.", DateTime.Now.ToString(CultureInfo.InvariantCulture)), config.LogVerbosity); } return(await GrantAccess(this.pubnubChannelNames, this.pubnubChannelGroupNames, this.pamAuthenticationKeys, this.grantRead, this.grantWrite, this.grantDelete, this.grantManage, this.grantTTL, this.queryParam).ConfigureAwait(false)); }
public ScriptResolver(ScriptPathContainer scriptPathContainer, ScriptDepencyContainer scriptDepencyContainer, ScriptAssemblyContainer scriptAssemblyContainer) { this.scriptPathContainer = scriptPathContainer; this.scriptDepencyContainer = scriptDepencyContainer; this.scriptAssemblyContainer = scriptAssemblyContainer; LoggingMethod = LoggingMethod.None; }
protected override string EncryptOrDecrypt(bool type, string plainStr) { //Demo params string keyString = GetEncryptionKey(); 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); if (type) { // Encrypt 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); } else { try { //Decrypt 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 //string actualInput = Encoding.UTF8.GetString(encryptedBytes, 0, encryptedBytes.Length); int len = Array.IndexOf(encryptedBytes, (byte)0); len = (len == -1) ? encryptedBytes.Length : len; string actualInput = Encoding.UTF8.GetString(encryptedBytes, 0, len); return(actualInput); } catch (Exception ex) { #if (ENABLE_PUBNUB_LOGGING) LoggingMethod.WriteToLog(string.Format("DateTime {0} Decrypt Error. {1}", DateTime.Now.ToString(), ex.ToString()), LoggingMethod.LevelVerbose); #endif throw ex; //LoggingMethod.WriteToLog(string.Format("DateTime {0} Decrypt Error. {1}", DateTime.Now.ToString(), ex.ToString()), LoggingMethod.LevelVerbose); //return "**DECRYPT ERROR**"; } } }
public IEnumerator CheckTimeoutHeartbeat <T> (CoroutineParams <T> cp) { #if (ENABLE_PUBNUB_LOGGING) LoggingMethod.WriteToLog(string.Format("DateTime {0}, yielding: {1} sec timeout", DateTime.Now.ToString(), cp.timeout.ToString()), LoggingMethod.LevelInfo); #endif yield return(new WaitForSeconds(cp.timeout)); ProcessTimeout <T> (cp); }
internal static void ProcessResponseCallbackExceptionHandler <T> (Exception ex, RequestState <T> asynchRequestState, PubnubErrorFilter.Level errorLevel) { #if (ENABLE_PUBNUB_LOGGING) LoggingMethod.WriteToLog(string.Format("DateTime {0} Exception= {1} for URL: {2}", DateTime.Now.ToString(), ex.ToString(), asynchRequestState.Request.RequestUri.ToString()), LoggingMethod.LevelInfo); #endif UrlRequestCommonExceptionHandler <T> (ex.Message, asynchRequestState.RespType, asynchRequestState.Channels, asynchRequestState.Timeout, asynchRequestState.UserCallback, asynchRequestState.ConnectCallback, asynchRequestState.ErrorCallback, false, errorLevel); }
protected override sealed void Init(string publishKey, string subscribeKey, string secretKey, string cipherKey, bool sslOn) { #if (USE_JSONFX) LoggingMethod.WriteToLog("Using USE_JSONFX", LoggingMethod.LevelInfo); this.JsonPluggableLibrary = new JsonFXDotNet(); #elif (USE_DOTNET_SERIALIZATION) LoggingMethod.WriteToLog("Using USE_DOTNET_SERIALIZATION", LoggingMethod.LevelInfo); this.JsonPluggableLibrary = new JscriptSerializer(); #else LoggingMethod.WriteToLog("Using NewtonsoftJsonDotNet", LoggingMethod.LevelInfo); base.JsonPluggableLibrary = new NewtonsoftJsonDotNet(); #endif #if (SILVERLIGHT || WINDOWS_PHONE) LoggingMethod.LogLevel = pubnubLogLevel; PubnubErrorFilter.ErrorLevel = errorLevel; #else string configuredLogLevel = ConfigurationManager.AppSettings["PubnubMessaging.LogLevel"]; int logLevelValue; if (!Int32.TryParse(configuredLogLevel, out logLevelValue)) { base.PubnubLogLevel = pubnubLogLevel; } else { base.PubnubLogLevel = (LoggingMethod.Level)logLevelValue; } string configuredErrorFilter = ConfigurationManager.AppSettings["PubnubMessaging.PubnubErrorFilterLevel"]; int errorFilterValue; if (!Int32.TryParse(configuredErrorFilter, out errorFilterValue)) { base.PubnubErrorLevel = errorLevel; } else { base.PubnubErrorLevel = (PubnubErrorFilter.Level)errorFilterValue; } #endif #if (SILVERLIGHT || WINDOWS_PHONE) HttpWebRequest.RegisterPrefix("https://", WebRequestCreator.ClientHttp); HttpWebRequest.RegisterPrefix("http://", WebRequestCreator.ClientHttp); #endif base.publishKey = publishKey; base.subscribeKey = subscribeKey; base.secretKey = secretKey; base.cipherKey = cipherKey; base.ssl = sslOn; base.VerifyOrSetSessionUUID(); //Initiate System Events for PowerModeChanged - to monitor suspend/resume InitiatePowerModeCheck(); }
public void SetRequestState(CurrentRequestType key, object requestState) { object reqState = requestState as object; requestStates.AddOrUpdate(key, reqState, (oldData, newData) => reqState); #if (ENABLE_PUBNUB_LOGGING) LoggingMethod.WriteToLog(string.Format("DateTime {0}, SetStoredRequestState {1}", DateTime.Now.ToString(), key.ToString()), LoggingMethod.LevelInfo); #endif }
public object DeserializeToObject(string jsonString) { #if (ENABLE_PUBNUB_LOGGING) LoggingMethod.WriteToLog(string.Format("DateTime {0}, DeserializeToObject: jsonString: {1}", DateTime.Now.ToString(), jsonString), LoggingMethod.LevelInfo); #endif var output = JsonReader.Deserialize <object> (jsonString) as object; return(output); }
protected override PubnubWebRequest SetProxy <T> (PubnubWebRequest request) { if (pubnubEnableProxyConfig && _pubnubProxy != null) { LoggingMethod.WriteToLog(string.Format("DateTime {0}, ProxyServer={1}; ProxyPort={2}; ProxyUserName={3}", DateTime.Now.ToString(), _pubnubProxy.ProxyServer, _pubnubProxy.ProxyPort, _pubnubProxy.ProxyUserName), LoggingMethod.LevelInfo); WebProxy webProxy = new WebProxy(_pubnubProxy.ProxyServer, _pubnubProxy.ProxyPort); webProxy.Credentials = new NetworkCredential(_pubnubProxy.ProxyUserName, _pubnubProxy.ProxyPassword); request.Proxy = webProxy; } return(request); }
public Logger() { mutex = new Mutex(true, "smcs"); if (mutex.WaitOne(0)) // check if no other process is owning the mutex { loggingMethod = LoggingMethod.Immediate; DeleteLogFileIfTooOld(); } else { pendingLines = new StringBuilder(); loggingMethod = LoggingMethod.Retained; } }
public static void DefineMethod(LoggingMethod m) { _method = m; }
public void Open(LoggingMethod method = LoggingMethod.DateStamped) { if (thread != null && thread.IsAlive) { return; } started = DateTime.Now; this.method = method; OpenFile(); stop = false; thread = new Thread(new ThreadStart(LogMessages)); thread.Start(); }