protected void Error(System.Exception e) { ErrorEvent evt = new ErrorEvent(this); evt.exception = e; eventQueue.Enqueue(evt); }
protected void Error(System.Exception e) { ErrorEvent evt = new ErrorEvent(); evt.session = this; evt.error = e; eventQueue.Enqueue(evt); }
public void Send(byte[] buffer, int bufferSize, int deviceId, String address) { //STrace.Debug(GetType().FullName, deviceId, String.Format("Send size={0} ip={1} text={2}", buffer_size, address, StringUtils.MakeString(buffer))); _outgoingStream.Enqueue(new StreamBlock { ContentType = StreamBlock.ContentTypes.StreamData, Data = buffer, TotalBytes = bufferSize }); }
public virtual void EnqueueBlock(StreamBlock block) { TRACE("ENQUEUE BLOCK [{0}]", block.ContentType); if (outgoing_stream.Enqueue(block)) { DispatchBlock(block); } }
public void Log(string message, Exception exception, LoggingLevel level) { if (_queue.Count > MAX_QUEUE_RECORD_LIMIT) { if (!QueueIsOverloadedWarning) { QueueIsOverloadedWarning = true; _queue.Enqueue(new LogItem(String.Format("MAX QUEUE COUNT WAS EXCEEDED (CURRENT: {0})! ADDING NEW MSG INTO QUEUE IS STOPPED!\r\n", _queue.Count), null, LoggingLevel.Fatal)); } return; } if (QueueIsOverloadedWarning) { QueueIsOverloadedWarning = false; _queue.Enqueue(new LogItem("MAX QUEUE COUNT IS NORMALIZED! CONTINUE TO ADD NEW MSG INTO QUEUE!\r\n", null, LoggingLevel.Fatal)); } _queue.Enqueue(new LogItem(message, exception, level)); }
public IAsyncResult BeginExecute(string command, Dictionary <string, object> parameters, ExecutionOptions options, AsyncCallback callback, object asyncState) { AsyncCommandResult asyncCommandResult = new AsyncCommandResult(command, parameters, options, callback, asyncState); Queue.Enqueue(asyncCommandResult); return(asyncCommandResult); }
/// /// Run 'task' on the main rendering thread. /// /// If we are alreay on the main thread, the task will be run right away. /// /// Otherwise it's added to a tasks queue, and will be run on the main threads /// N frames later. /// public static void Run(Task task) { if (Thread.CurrentThread == mainThread) { /* already on main thread, run right away !*/ task(); return; } /* add to work thread, so we can run it later from main thread */ Tasks.Enqueue(task); }
private void PostSend(byte[] buf) { if (ConnectionState.Connected == state) { SendStateObject sendObj = new SendStateObject(); sendObj.buffer = new Gamnet.Buffer(buf); _socket.BeginSend(sendObj.buffer.data, 0, sendObj.buffer.Size(), 0, new AsyncCallback(Callback_OnSend), sendObj); } else { sendQueue.Enqueue(buf); } }
public async Task <string> Report() { if (HttpContext.Request.Headers["authkey"] == key) { string data; using (StreamReader reader = new StreamReader(Request.Body, Encoding.UTF8)) { data = await reader.ReadToEndAsync(); } var path = RouteData.Values["Id"].ToString(); ReportItem[] items = JsonConvert.DeserializeObject <ReportItem[]>(data); foreach (var item in items) { item.Time = DateTime.Today.Date; } var action = new Action(() => { db.Create(items, path); }); _processQueue.Enqueue(action); } return("Ok"); }
private void PostSend(byte[] buf) { if (State.Connected == state) { SendStateObject sendObj = new SendStateObject(); sendObj.socket = _socket; sendObj.buffer = new Gamnet.Buffer(); sendObj.buffer.Copy(buf); _socket.BeginSend(buf, 0, buf.Length, 0, new AsyncCallback(Callback_OnSend), sendObj); } else { sendQueue.Enqueue(buf); } }
public void Write(Type type, eLoggerLevel level, string sMessage, object[] args) { int iLevel = (int)level; if ((iLevel & m_iAllowedLevels) > 0) { try { LoggerRecord record = new LoggerRecord(type, level, sMessage, args); m_sqMessages.Enqueue(record); } catch (Exception excp) { Console.ForegroundColor = ConsoleColor.Red; Console.WriteLine(ExcpHelper.FormatException(excp, "LiveLog.WriteConsole('{0}') ERROR", m_sLogleFilePath)); } } }
private bool CrackPassword(string password) { _mutex.WaitOne(); if (_passwordsToCrack.All(p => p.Value == true)) { _mutex.ReleaseMutex(); return(false); } var pass = new HashedPassword(password); var hashedPass = pass.HashedPass; if (_passwordsToCrack.ContainsKey(hashedPass) && _passwordsToCrack[hashedPass] == false) { _crackedPasswords.Enqueue(pass); } _mutex.ReleaseMutex(); return(true); }
public static void SaveXml(LineContainer slc, string sline) { savingQueue.Enqueue(new LineMessage(slc, sline)); if (savingThread == null) { savingThread = new Thread(() => { while (true) { if (savingQueue.Count == 0) { Thread.Sleep(10); continue; } var linemsg = savingQueue.Dequeue(); var time = DateTime.Now; var folderPath = ConfigurationManager.AppSettings["betradar_xml_files"] + linemsg.Line + "\\" + time.Year + "_" + time.Month + "_" + time.Day + "_" + time.Hour + "_00" + "\\"; if (!Directory.Exists(folderPath)) { Directory.CreateDirectory(folderPath); } var timestamp = time.ToFileTime().ToString(); var filename = folderPath + linemsg.LineContainer.Attributes["type"] + timestamp; int index = 1; var tempfilename = filename; while (!SaveFile(linemsg.LineContainer, tempfilename)) { tempfilename = filename + " " + index++; } } }); savingThread.Start(); } }
public override async Task <T> ExecuteAsync() { T savedEntity = default(T); NetworkRequest <T> request = null; string entityID = null;; JToken idToken = JObject.FromObject(entity) ["_id"]; if (idToken != null && !String.IsNullOrEmpty(idToken.ToString())) { entityID = idToken.ToString(); request = Client.NetworkFactory.buildUpdateRequest(Collection, entity, entityID); } else { request = Client.NetworkFactory.buildCreateRequest(Collection, entity); } switch (Policy) { case WritePolicy.FORCE_LOCAL: // sync PendingWriteAction pendingAction = PendingWriteAction.buildFromRequest(request); string saveModeLocal = request.RequestMethod; string tempIdLocal = null; if (String.Equals("POST", saveModeLocal)) { tempIdLocal = PrepareCacheSave(ref entity); savedEntity = Cache.Save(entity); pendingAction.entityId = tempIdLocal; } else { savedEntity = Cache.Update(entity); } SyncQueue.Enqueue(pendingAction); break; case WritePolicy.FORCE_NETWORK: // network savedEntity = await request.ExecuteAsync(); break; case WritePolicy.NETWORK_THEN_LOCAL: // cache string saveModeNetworkThenLocal = request.RequestMethod; string tempIdNetworkThenLocal = null; if (String.Equals("POST", saveModeNetworkThenLocal)) { tempIdNetworkThenLocal = PrepareCacheSave(ref entity); Cache.Save(entity); } else { Cache.Update(entity); } // network save savedEntity = await request.ExecuteAsync(); if (tempIdNetworkThenLocal != null) { Cache.UpdateCacheSave(savedEntity, tempIdNetworkThenLocal); } break; case WritePolicy.LOCAL_THEN_NETWORK: string saveModeLocalThenNetwork = request.RequestMethod; // cache if (String.Equals("POST", saveModeLocalThenNetwork)) { entityID = PrepareCacheSave(ref entity); savedEntity = Cache.Save(entity); } else { savedEntity = Cache.Update(entity); } KinveyException kinveyException = null; Exception exception = null; try { // network save savedEntity = await request.ExecuteAsync(); } catch (KinveyException kinveyEx) { kinveyException = kinveyEx; } catch (Exception ex) { exception = ex; } if (kinveyException != null || exception != null) { // if the network request fails, save data to sync queue var localPendingAction = PendingWriteAction.buildFromRequest(request); localPendingAction.entityId = entityID; SyncQueue.Enqueue(localPendingAction); if (kinveyException != null) { throw kinveyException; } } else { Cache.UpdateCacheSave(savedEntity, entityID); } break; default: throw new KinveyException(EnumErrorCategory.ERROR_GENERAL, EnumErrorCode.ERROR_GENERAL, "Invalid write policy"); } return(savedEntity); }
internal void AddFailData(T data) { _allFailQueue.Enqueue(data); }
/// <summary> /// 添加数据 level:数据类型 fail:是否下载失败的数据 /// </summary> /// <param name="data"></param> /// <param name="level"></param> /// <param name="fail"></param> internal void AddData(T data, DataLevel level, bool fail = false) { lock (this._lockObj) { switch (level) { case DataLevel.High: if (fail) { _highPriorityFailQueue.Enqueue(data); } else { _highPriorityQueue.Enqueue(data); } break; case DataLevel.CurScene: if (fail) { _curSceneFailQueue.Enqueue(data); } else { _curSceneQueue.Enqueue(data); } break; case DataLevel.NextScene: if (fail) { _nextSceneFailQueue.Enqueue(data); } else { _nextSceneQueue.Enqueue(data); } break; case DataLevel.Low: if (fail) { _lowFailQueue.Enqueue(data); } else { _lowQueue.Enqueue(data); } break; default: if (fail) { _lowFailQueue.Enqueue(data); } else { _lowQueue.Enqueue(data); } break; } } }
public virtual void EnqueueBlock(StreamBlock block) { TRACE("ENQUEUE BLOCK [{0}] OF {1} BYTES", block.ContentType, block.TotalBytes); outgoing_stream.Enqueue(block); }
private static void ReaderThread(ThreadContext tc) { RemoveLiveMatches(eServerSourceType.BtrPre); RemoveLiveMatches(eServerSourceType.BtrLive); DateTime dtLastReceived = DateTime.Now; bool bDisabled = false; bool bRemoved = false; var lineReseiveCopy = ""; while (m_bRunning && !tc.IsToStop) { m_dtConnected = DateTime.Now; try { string sServerMessage = ""; while (m_bRunning && !tc.IsToStop && m_liveClient.IsAlive) { lineReseiveCopy = LinesToReceive; //if (m_liveClient.HaveData) sServerMessage = m_liveClient.ReadLine(); ExcpHelper.ThrowIf(string.IsNullOrEmpty(sServerMessage), "Received Empty Message"); m_logger.Debug("received live message " + sServerMessage.Length); m_liveClient.WriteLine(lineReseiveCopy); if (sServerMessage == LIVEBET_MSG_HELLO || sServerMessage == LIVEBET_MSG_EMPTY) { m_logger.DebugFormat("Received '{0}'", sServerMessage); dtLastReceived = DateTime.Now; LineSr.LiveBetConnected = true; } else { try { var originalLength = sServerMessage.Length; if (sServerMessage.StartsWith(COMPRESSED)) { string sPrefix = sServerMessage.Substring(0, COMPRESSED_MASK_SIZE); string sSize = sPrefix.Substring(COMPRESSED.Length); int iCompressedMessageSize = 0; bool bSizeParsed = int.TryParse(sSize, out iCompressedMessageSize); Debug.Assert(bSizeParsed && iCompressedMessageSize > 0); //Debug.Assert(iCompressedMessageSize + COMPRESSED_MASK_SIZE == sServerMessage.Length); sServerMessage = TextUtil.DecompressBase64String(sServerMessage.Substring(COMPRESSED_MASK_SIZE)); } int startIndex = sServerMessage.IndexOf('<'); ExcpHelper.ThrowIf(startIndex < 0, "Cannot find start xml point '<'"); sServerMessage = sServerMessage.Substring(startIndex); TimeSpan tsDuration = DateTime.Now - m_dtConnected; LineContainer lc = LineContainer.FromXml(sServerMessage); ExcpHelper.ThrowIf <NullReferenceException>(lc == null, "LineContainer is Null"); //lc.Duration = tsDuration; m_sqMessages.Enqueue(lc); int iQueueCount = m_sqMessages.Count; ExcpHelper.ThrowIf(iQueueCount > DalStationSettings.Instance.LiveErrorQueueSize, "Live Client Queue size ({0}) is too big.", iQueueCount); if (iQueueCount > DalStationSettings.Instance.LiveWarnQueueSize) { m_logger.Warn("Live Client Queue size = " + iQueueCount); } dtLastReceived = DateTime.Now; bDisabled = false; bRemoved = false; string sType = lc.Attributes.ContainsKey("line") ? lc.Attributes["line"] : "none"; m_logger.DebugFormat("Enqueueing message {0} (Total messages in queue {1}; Connected {2}; Duration {3},type {4},length {5},compressedLength {6})", lc.GetDocId(), m_sqMessages.Count, m_dtConnected, tsDuration, sType, sServerMessage.Length, originalLength); } catch (Exception excp) { m_logger.Warn(ExcpHelper.FormatException(excp, "Could not process incoming server message (Size={0})", sServerMessage.Length)); throw; } } LineSr.LiveBetConnected = true; Thread.Sleep(10); } } catch (Exception excp) { m_logger.Error(excp.Message, excp); m_sqMessages.Clear(); m_logger.Excp(excp, "Connection to server lost after importing time ({0}) ms bacause of {1}", DateTime.Now - m_dtConnected, excp.GetType()); LineSr.LiveBetConnected = false; } if (dtLastReceived + LIVE_TIME_OUT_TO_DISABLE < DateTime.Now && !bDisabled) { LineSr.SyncRoutines(eUpdateType.LiveBet, "Connection lost. SportRadar LiveMarket is disabled.", DalStationSettings.Instance.UseDatabaseForLiveMatches, null, delegate(object obj) { LineSr.Instance.DisableLiveMatches(eServerSourceType.BtrLive); return(false); }); LineSr.ProcessDataSqlUpdateSucceeded(eUpdateType.LiveBet, "Connection lost. SportRadar LiveMarket is cleared."); bDisabled = true; } else if (dtLastReceived + LIVE_TIME_OUT_TO_REMOVE < DateTime.Now && !bRemoved) { m_logger.ErrorFormat("Removing all live matches because last message ('{0}') were too long time ago (TimeOut='{1}')", new Exception(), dtLastReceived, LIVE_TIME_OUT_TO_REMOVE); RemoveLiveMatches(eServerSourceType.BtrPre); RemoveLiveMatches(eServerSourceType.BtrLive); bRemoved = true; } Thread.Sleep(10); EnsureConnection(); } }
protected void SendTaskControlMessage(TaskExecutionEvents.TaskControlCommand msg) { ValidateMessage(msg); SyncQueue.Enqueue(msg); }
/// <summary> /// Executes a multi insert request. /// </summary> /// <returns>An async task with the request result.</returns> public override async Task <KinveyMultiInsertResponse <T> > ExecuteAsync() { var kinveyDataStoreResponse = new KinveyMultiInsertResponse <T> { Entities = new List <T>(), Errors = new List <Error>() }; switch (Policy) { case WritePolicy.FORCE_LOCAL: //local cache for (var index = 0; index < entities.Count; index++) { try { var cacheSaveResult = CacheSave(entities[index]); SyncQueue.Enqueue(cacheSaveResult.Item1); kinveyDataStoreResponse.Entities.Add(cacheSaveResult.Item2); } catch (Exception ex) { kinveyDataStoreResponse.Entities.Add(default(T)); var error = new Error { Index = index, Code = 0, Errmsg = ex.Message }; kinveyDataStoreResponse.Errors.Add(error); } } ThrowExceptionIfOnlyErrors(kinveyDataStoreResponse, EnumErrorCategory.ERROR_DATASTORE_CACHE, EnumErrorCode.ERROR_DATASTORE_CACHE_MULTIPLE_SAVE); break; case WritePolicy.FORCE_NETWORK: // network kinveyDataStoreResponse = await HandleNetworkRequestAsync(entities).ConfigureAwait(false); ThrowExceptionIfOnlyErrors(kinveyDataStoreResponse, EnumErrorCategory.ERROR_BACKEND, EnumErrorCode.ERROR_JSON_RESPONSE); break; case WritePolicy.LOCAL_THEN_NETWORK: //local cache KinveyMultiInsertResponse <T> kinveyDataStoreNetworkResponse = null; var pendingWriteActions = new List <PendingWriteAction>(); for (var index = 0; index < entities.Count; index++) { try { var cacheSaveResult = CacheSave(entities[index]); pendingWriteActions.Add(cacheSaveResult.Item1); kinveyDataStoreResponse.Entities.Add(cacheSaveResult.Item2); } catch (Exception ex) { kinveyDataStoreResponse.Entities.Add(default(T)); var error = new Error { Index = index, Code = 0, Errmsg = ex.Message }; kinveyDataStoreResponse.Errors.Add(error); } } ThrowExceptionIfOnlyErrors(kinveyDataStoreResponse, EnumErrorCategory.ERROR_DATASTORE_CACHE, EnumErrorCode.ERROR_DATASTORE_CACHE_MULTIPLE_SAVE); KinveyException kinveyException = null; Exception exception = null; try { // network kinveyDataStoreNetworkResponse = await HandleNetworkRequestAsync(entities).ConfigureAwait(false); } catch (KinveyException kinveyEx) { kinveyException = kinveyEx; } catch (Exception ex) { exception = ex; } if (kinveyException != null || exception != null) { foreach (var pendingAction in pendingWriteActions) { SyncQueue.Enqueue(pendingAction); } if (kinveyException != null) { throw kinveyException; } } else { for (var index = 0; index < kinveyDataStoreResponse.Entities.Count; index++) { if (kinveyDataStoreNetworkResponse.Entities[index] != null) { if (kinveyDataStoreResponse.Entities[index] != null) { var obj = JObject.FromObject(kinveyDataStoreResponse.Entities[index]); var id = obj["_id"].ToString(); Cache.UpdateCacheSave(kinveyDataStoreNetworkResponse.Entities[index], id); } else { CacheSave(kinveyDataStoreNetworkResponse.Entities[index]); } } else { if (kinveyDataStoreResponse.Entities[index] != null) { var obj = JObject.FromObject(kinveyDataStoreResponse.Entities[index]); var id = obj["_id"].ToString(); var existingPendingWriteAction = pendingWriteActions.Find(e => e.entityId.Equals(id)); if (existingPendingWriteAction != null) { SyncQueue.Enqueue(existingPendingWriteAction); } } } } kinveyDataStoreResponse = kinveyDataStoreNetworkResponse; } ThrowExceptionIfOnlyErrors(kinveyDataStoreResponse, EnumErrorCategory.ERROR_BACKEND, EnumErrorCode.ERROR_JSON_RESPONSE); break; default: throw new KinveyException(EnumErrorCategory.ERROR_GENERAL, EnumErrorCode.ERROR_GENERAL, "Invalid write policy"); } return(kinveyDataStoreResponse); }
public override async Task <KinveyDeleteResponse> ExecuteAsync() { var kdr = default(KinveyDeleteResponse); switch (Policy) { case WritePolicy.FORCE_LOCAL: // sync if (_query == null) { // cache kdr = Cache.DeleteByID(entityID); var request = Client.NetworkFactory.buildDeleteRequest <KinveyDeleteResponse>(Collection, entityID); var pendingAction = PendingWriteAction.buildFromRequest(request); SyncQueue.Enqueue(pendingAction); } else { // cache kdr = Cache.DeleteByQuery(_query); foreach (var id in kdr.IDs) { var request = Client.NetworkFactory.buildDeleteRequest <KinveyDeleteResponse>(Collection, id); var pendingAction = PendingWriteAction.buildFromRequest(request); SyncQueue.Enqueue(pendingAction); } } break; case WritePolicy.FORCE_NETWORK: // network if (_query == null) { kdr = await Client.NetworkFactory.buildDeleteRequest <KinveyDeleteResponse>(Collection, entityID).ExecuteAsync(); } else { var mongoQuery = KinveyMongoQueryBuilder.GetQueryForRemoveOperation <T>(_query); kdr = await Client.NetworkFactory.buildDeleteRequestWithQuery <KinveyDeleteResponse>(Collection, mongoQuery).ExecuteAsync(); } break; case WritePolicy.NETWORK_THEN_LOCAL: if (_query == null) { // cache kdr = Cache.DeleteByID(entityID); // network kdr = await Client.NetworkFactory.buildDeleteRequest <KinveyDeleteResponse>(Collection, entityID).ExecuteAsync(); } else { // cache kdr = Cache.DeleteByQuery(_query); // network var mongoQuery = KinveyMongoQueryBuilder.GetQueryForRemoveOperation <T>(_query); kdr = await Client.NetworkFactory.buildDeleteRequestWithQuery <KinveyDeleteResponse>(Collection, mongoQuery).ExecuteAsync(); } break; case WritePolicy.LOCAL_THEN_NETWORK: if (_query == null) { // cache kdr = Cache.DeleteByID(entityID); var deleteRequest = Client.NetworkFactory.buildDeleteRequest <KinveyDeleteResponse>(Collection, entityID); KinveyException kinveyException = null; Exception exception = null; try { // network kdr = await deleteRequest.ExecuteAsync(); } catch (KinveyException kinveyEx) { kinveyException = kinveyEx; } catch (Exception ex) { exception = ex; } if (kinveyException != null || exception != null) { var pendingAction = PendingWriteAction.buildFromRequest(deleteRequest); SyncQueue.Enqueue(pendingAction); if (kinveyException != null) { throw kinveyException; } } } else { // cache kdr = Cache.DeleteByQuery(_query); // network KinveyException kinveyException = null; Exception exception = null; try { var mongoQuery = KinveyMongoQueryBuilder.GetQueryForRemoveOperation <T>(_query); kdr = await Client.NetworkFactory.buildDeleteRequestWithQuery <KinveyDeleteResponse>(Collection, mongoQuery).ExecuteAsync(); } catch (KinveyException kinveyEx) { kinveyException = kinveyEx; } catch (Exception ex) { exception = ex; } if (kinveyException != null || exception != null) { foreach (var id in kdr.IDs) { var request = Client.NetworkFactory.buildDeleteRequest <KinveyDeleteResponse>(Collection, id); var pendingAction = PendingWriteAction.buildFromRequest(request); SyncQueue.Enqueue(pendingAction); } if (kinveyException != null) { throw kinveyException; } } } break; default: throw new KinveyException(EnumErrorCategory.ERROR_GENERAL, EnumErrorCode.ERROR_GENERAL, "Invalid write policy"); } return(kdr); }
public void NotifyTaskEvent(TaskExecutionEvents.TaskExecEvent ev) { ValidateMessage(ev); SyncQueue.Enqueue(ev); }
public void AdviseALL(string values) { valuesTosend.Enqueue(values); }