public void SetShowScreenEvent(IEventBase obj) { if (obj is ShowUIScreenEvent) { ShowScreen(((ShowUIScreenEvent)obj)._screen); } }
private void OnCharacterDeath(IEventBase eventBase) { if (eventBase is CharacterDeath e) { Time.timeScale = 0; } }
private void UpdateSummary(IEventBase obj) { var userSummary = user.UserSummary; var total = 0m; var exchangeTotals = new Dictionary <string, decimal>(); foreach (var item in user.UserCoins) { var coin = availableCoins.Coins.Get(item.Value.Coin); if (coin == null) { Logger.LogDebug($"UserCoin not fetched from any exchange: {item.Value.Coin}"); continue; } var coinTicker = coin.Tickers.Get(item.Value.Exchange); if (coin.Symbol == UserTickerMarket) { userSummary.RemainingBtc[item.Value.Exchange] = item.Value.Quantity; var btcTickers = coinTicker.MarketTickers.SingleOrDefault(); userSummary.BtcTickers[item.Value.Exchange] = btcTickers.Equals(default) ? null : btcTickers.Value;
/// <summary> /// Enqueues an event onto the event queue /// </summary> public void ThrowEvent(object sender, IEventBase thrownEvent) { if (sender.IsNull() || thrownEvent.IsNull()) { return; } if (!_events.ContainsKey(thrownEvent.GetType())) { return; } Log.DebugFormat("Locate Event to Throw {0}", thrownEvent.GetType()); IList <EventListener> tupleList; _events.TryGetValue(thrownEvent.GetType(), out tupleList); if (tupleList.IsNull() || tupleList.Count == 0) { return; } Log.DebugFormat("ThrowEvent {0}/{1}", sender.GetType(), thrownEvent.GetType()); thrownEvent.Sender = sender; _eventQueue.Enqueue(thrownEvent); if (!Timer.IsNotNull() || Timer.Enabled) { return; } Log.DebugFormat("Starting the Event Timer with interval frequency of {0}", Timer.Interval); Timer.Start(); }
public async Task <bool> SaveAsync(IEventBase <K> data, byte[] bytes, string uniqueId = null) { var mEvent = new MongoEvent <K> { Id = new ObjectId(), StateId = data.StateId, Version = data.Version, TypeCode = data.TypeCode, Data = bytes, UniqueId = string.IsNullOrEmpty(uniqueId) ? data.GetUniqueId() : uniqueId }; try { await mongoStorage.GetCollection <MongoEvent <K> >(grainConfig.EventDataBase, grainConfig.GetCollection(mongoStorage, mongoStorage.Config.SysStartTime, data.Timestamp).Name).InsertOneAsync(mEvent); return(true); } catch (MongoWriteException ex) { if (ex.WriteError.Category != ServerErrorCategory.DuplicateKey) { throw ex; } else { logger.LogError(ex, $"Event Duplicate,Event:{Newtonsoft.Json.JsonConvert.SerializeObject(data)}"); } } return(false); }
private void OnZombieKilledByPlayer(IEventBase eventBase) { if (eventBase is ZombieKilledByPlayer e) { Exp += e.Exp; } }
public IEventBase Dequeue(string queueName) { if (null == queueName) { throw new ArgumentNullException(nameof(queueName)); } var result = _database.ListLeftPop(GetQueueCacheKey(queueName)); if (result.HasValue) { IEventBase @event = null; try { @event = result.ToString().ToEvent(); } catch (Exception e) { _logger.LogError(e, $"dequeue event exception, queueName:{queueName}"); } return(@event); } return(null); }
private void DiceRollAnimationComplete(IEventBase a_Event) { EventDiceRollAnimationComplete data = a_Event as EventDiceRollAnimationComplete; if (data == null) { Debug.LogError("[InGameUIManager] Dice Roll trigger is null"); return; } StartCoroutine(AnimationSequence()); IEnumerator AnimationSequence() { m_arrAnimController[(int)GameManager.Instance.EnumPlayerToken - 1].SetBool("RollDice", false); yield return(new WaitForSeconds(0.25f)); m_arrAnimController[(int)GameManager.Instance.EnumPlayerToken - 1].enabled = false; yield return(new WaitForEndOfFrame()); m_imgCurrentDiceRoll = m_arrDiceImage[(int)GameManager.Instance.EnumPlayerToken - 1]; GameManager.Instance.CheckResult(); Debug.Log("[InGameUIManager] The Dice Roll value: " + GameManager.Instance.ICurrentDiceValue); yield return(new WaitForEndOfFrame()); //This will show the current roll sprite on the dice image m_imgCurrentDiceRoll.sprite = m_arrDiceSprite[GameManager.Instance.ICurrentDiceValue - 1]; } }
private void GetSummaryData(IEventBase obj) { var userSummary = userManager.GetSummary(); var btcTickers = new List <TickerModel>(); foreach (var btcTicker in userSummary.BtcTickers) { btcTickers.Add(new TickerModel { Coin = btcTicker.Value.Coin, Exchange = btcTicker.Value.Exchange, Ticker = btcTicker.Value.Last, TickerSymbol = Util.GetCurrencySymbol(btcTicker.Value.TickerSymbol) }); } var userSummaryModel = new SummaryModel { TotalBalance = userSummary.TotalBalance, Balance = userSummary.Balance, RemainingBtc = userSummary.RemainingBtc, BtcTickers = btcTickers }; MainController.MainHub.SendMessage("summary", userSummaryModel); }
protected async Task <bool> Release(IEventBase @event) { var limiter = RedisManager.GetRateLimiterClient($"{@event.GetType().FullName}_{@event.EventId}", TimeSpan.FromMinutes(2)); return(await limiter.ReleaseAsync()); }
protected virtual async Task AfterEventSavedHandle(IEventBase <K> @event, byte[] bytes, int recursion = 0, string hashKey = null) { try { if (string.IsNullOrEmpty(hashKey)) { hashKey = GrainId.ToString(); } //消息写入消息队列 await MQService.Publish(@event, bytes, hashKey); //更改消息状态 await EventStorage.CompleteAsync(@event); } catch (Exception e) { if (recursion > 5) { throw e; } this.GetLogger("Event_Raise").Log(LogCodes.EventCompleteError, Orleans.Runtime.Severity.Error, "事件complate操作出现致命异常:" + string.Format("Grain类型={0},GrainId={1},StateId={2},Version={3},错误信息:{4}", ThisType.FullName, GrainId, @event.StateId, @event.Version, e.Message), null, e); int newRecursion = recursion + 1; await Task.Delay(newRecursion * 200); await AfterEventSavedHandle(@event, bytes, newRecursion, hashKey : hashKey); } }
/// <summary> /// Triggers the event causing the delegates to be called /// </summary> /// <param name="a_eEvent"> Enumerated event name</param> /// <param name="args">array of arguments that are passed to the delegates</param> public void TriggerEvent <T>(IEventBase a_refEvent) where T : IEventBase { Type t = typeof(T); if (m_bEnableLogs) { Debug.Log("[EventManager] trigger Event " + t.ToString()); } if (m_lstEventRegistry.ContainsKey(t)) { AppEventDelegate d = m_lstEventRegistry[t]; if (d != null) { d(a_refEvent); if (m_bEnableLogs) { Debug.Log("[EventManager] trigger Event " + t.ToString()); } } else { //This an error. Console.WriteLine("Could not trigger event: "); } } }
public void GetPositions(IEventBase obj) { var positions = userManager.GetPositions(); var temp = new List <PositionGridModel>(); foreach (var position in positions) { var ticker = userManager.GetTicker(position.Coin, position.Exchange); temp.Add(new PositionGridModel { Coin = position.Coin, UniqueName = position.UniqueName.ToString(), Balance = position.Quantity * ticker?.Last ?? 0, Exchange = position.Exchange, LastPrice = ticker?.Last ?? 0, TickerSymbol = ticker?.TickerSymbol, Quantity = position.Quantity, Volume = ticker?.Volume ?? 0, Price = position.BuyPrice, Notes = position.Notes, Change = ticker?.PriceChange24Hr ?? 0, ProfitPercentage = userManager.GetProfitPercentage(ticker, position), TotalPercentage = userManager.GetTotalPercentage(ticker, position) }); } temp.Sort((lhs, rhs) => rhs.TotalPercentage.CompareTo(lhs.TotalPercentage)); MainController.MainHub.SendMessage("position", temp); }
public async Task <bool> SaveAsync(IEventBase <K> data, byte[] bytes, string uniqueId = null) { var table = await tableInfo.GetTable(data.Timestamp); var saveSql = $"INSERT INTO {table.Name}(Id,stateid,msgid,typecode,data,version) VALUES(@Id,@StateId,@MsgId,@TypeCode,@Data,@Version)"; data.Id = OGuid.GenerateNewId().ToString(); string msgId = uniqueId; if (string.IsNullOrEmpty(msgId)) { msgId = data.Id; } try { using (var conn = tableInfo.CreateConnection()) { await conn.ExecuteAsync(saveSql, new { data.Id, StateId = data.StateId.ToString(), MsgId = msgId, data.TypeCode, Data = bytes, data.Version }); } return(true); } catch (Exception ex) { if (!(ex is Npgsql.PostgresException e && e.SqlState == "23505")) { throw ex; } } return(false); }
protected async Task <bool> RaiseEvent(IEventBase <K> @event, string uniqueId = null, string mqHashKey = null) { try { @event.StateId = GrainId; @event.Version = this.State.Version + 1; @event.Timestamp = DateTime.Now; using (var ms = new MemoryStream()) { Serializer.Serialize(ms, @event); var bytes = ms.ToArray(); var result = await EventStorage.InsertAsync(@event, bytes, uniqueId, SendEventToMQ); if (result) { @event.Apply(this.State); await EventInsertAfterHandle(@event, bytes, mqHashKey : mqHashKey); RaiseEventAfter(@event, bytes); return(true); } } } catch (Exception ex) { this.GetLogger("Event_Raise").Log(LogCodes.EventRaiseError, Orleans.Runtime.Severity.Error, $"applay event {@event.TypeCode} error, eventId={@event.Version}", null, ex); throw ex; } return(false); }
/// <summary> /// 向一个脚本中注册一条消息 /// </summary> /// <param name="id"></param> /// <param name="mono"></param> public void RegistMsg(ushort id, IEventBase mono) { //生成需要添加的节点 EventNode newNode = new EventNode(mono); //当前链表是null if (!nodeTree.ContainsKey(id)) { nodeTree.Add(id, newNode); } else//当前链表不为null { //指向链表的第一个节点 EventNode temp = nodeTree[id]; //定位最后一个node while (temp.Next != null) { temp = temp.Next; } temp.Next = newNode; } Debug.Log("<color=green>消息注册成功!</color>" + id + " " + mono); }
}//UnRegist End #endregion #region RegistMsg 注册消息 /// <summary> /// 向一个脚本中注册的多条消息 /// </summary> /// <param name="ids"></param> /// <param name="mono"></param> public void RegistMsg(ushort[] ids, IEventBase mono) { for (int i = 0; i < ids.Length; i++) { RegistMsg(ids[i], mono); } }
private async Task EventInsertAfterHandle(IEventBase <K> @event, byte[] bytes, int recursion = 0, string mqHashKey = null) { try { if (SendEventToMQ) { if (string.IsNullOrEmpty(mqHashKey)) { mqHashKey = GrainId.ToString(); } //消息写入消息队列 await MQService.Send(@event, bytes, mqHashKey); } //更改消息状态 await EventStorage.Complete(@event); //保存快照 await SaveSnapshotAsync(); } catch (Exception e) { if (recursion > 5) { throw e; } this.GetLogger("Event_Raise").Log(LogCodes.EventCompleteError, Orleans.Runtime.Severity.Error, "事件complate操作出现致命异常:" + string.Format("Grain类型={0},GrainId={1},StateId={2},Version={3},错误信息:{4}", ThisType.FullName, GrainId, @event.StateId, @event.Version, e.Message), null, e); int newRecursion = recursion + 1; await Task.Delay(newRecursion * 200); await EventInsertAfterHandle(@event, bytes, newRecursion, mqHashKey : mqHashKey); } }
private void OnCharacterLevelReached(IEventBase eventBase) { if (eventBase is CharacterLevelReached e) { ButtonLvlUp.gameObject.SetActive(true); } }
private void OnCharacterDeath(IEventBase eventBase) { if (eventBase is CharacterDeath e) { CanvasDeath.gameObject.SetActive(true); } }
protected override async ValueTask OnEventDelivered(IEventBase <long> @event) { switch (@event) { case AmountTransferEvent value: await AmountAddEventHandler(value); break; } }
private void OnCharacterDamaged(IEventBase eventBase) { if (eventBase is CharacterDamaged e) { CurrentHP -= e.Value; } }
private void OnSpaceClicked(IEventBase eventBase) { SpaceClicked ev = eventBase as SpaceClicked; if (ev != null) { handle.Complete(); for (int i = 0; i < enemyCount; i++) { float x = UnityEngine.Random.Range(transform.position.x + firstPosition.x, transform.position.x + endPostion.x); float y = UnityEngine.Random.Range(firstPosition.y + transform.position.y, endPostion.y + transform.position.y); var obj = Instantiate(enemyPrefab, new Vector3(x, y, transform.position.z), Quaternion.identity) as GameObject; if (obj is null) { Debug.LogError($"failed to create enemy!"); } else { transforms.Add(obj.transform); } } } }
protected async ValueTask<bool> RaiseEvent(IEventBase<K> @event, string uniqueId = null, string hashKey = null) { try { this.State.IncrementDoingVersion();//标记将要处理的Version @event.StateId = GrainId; @event.Version = this.State.Version + 1; @event.Timestamp = DateTime.UtcNow; using (var ms = new PooledMemoryStream()) { Serializer.Serialize(ms, @event); var bytes = ms.ToArray(); var result = await EventStorage.SaveAsync(@event, bytes, uniqueId); if (result) { EventHandle.Apply(this.State, @event); await AfterEventSavedHandle(@event, bytes, hashKey: hashKey); this.State.UpdateVersion(@event);//更新处理完成的Version await SaveSnapshotAsync(); return true; } else this.State.DecrementDoingVersion();//还原doing Version } } catch (Exception ex) { this.GetLogger("Event_Raise").Log(LogCodes.EventRaiseError, Orleans.Runtime.Severity.Error, $"applay event {@event.TypeCode} error, eventId={@event.Version}", null, ex); await OnActivateAsync();//重新激活Actor throw ex; } return false; }
//public void BroadcastMsgDealy(MsgBase msg, float delayTime) //{ // DelayActionManager.Instance.AddDelayAction(BroadcastMsg, delayTime, msg); //} #endregion #region UnRegistMsg 注销消息 /// <summary> /// 向一个脚本中注销的多条消息 /// </summary> /// <param name="ids"></param> /// <param name="mono"></param> public void UnRegistMsg(ushort[] msgs, IEventBase mono) { for (int i = 0; i < msgs.Length; i++) { UnRegistMsg(msgs[i], mono); } }
public async Task <bool> SaveAsync(IEventBase <K> evt, byte[] bytes, string uniqueId = null) { var table = await tableInfo.GetTable(evt.Timestamp); if (!saveSqlDict.TryGetValue(table.Name, out var saveSql)) { saveSql = $"INSERT INTO {table.Name}(stateid,uniqueId,typecode,data,version) VALUES(@StateId,@UniqueId,@TypeCode,@Data,@Version)"; saveSqlDict.TryAdd(table.Name, saveSql); } if (string.IsNullOrEmpty(uniqueId)) { uniqueId = evt.GetUniqueId(); } try { using (var conn = tableInfo.CreateConnection()) { await conn.ExecuteAsync(saveSql, new { StateId = evt.StateId.ToString(), UniqueId = uniqueId, evt.TypeCode, Data = bytes, evt.Version }); } return(true); } catch (Exception ex) { if (!(ex is PostgresException e && e.SqlState == "23505")) { throw ex; } } return(false); }
public void OnSubmitLayerScoreEvent(IEventBase obj) { if (obj is SubmitLayerScoreEvent) { SubmitLayerScoreEvent ls = (SubmitLayerScoreEvent)obj; if (ls.layerID > 0 && ls.layerID <= NoOfLayers) { scores[ls.layerID - 1].correctAns = ls.correctAns; scores[ls.layerID - 1].bonusPoints = ls.BonusScore; scores[ls.layerID - 1].TotalPoints = ls.score; scores[ls.layerID - 1].TimeTaken = ls.timeTaken; screen = UIScreenType.Layer1; switch (ls.layerID) { case 1: screen = UIScreenType.Layer2; break; case 2: screen = UIScreenType.Layer3; break; case 3: screen = UIScreenType.Layer4; break; case 4: screen = UIScreenType.YourScore; break; } sendShowScreen = true; } } }
public void OnInstructionsEvent(IEventBase obj) { sendShowScreen = true; screen = UIScreenType.Instructions; //string val = GetString("This is a string for Unity"); //UIManager.SetDebugText(1, "String from JS " + val); }
public void OnSubmitSignInCredentialsEvent(IEventBase obj) { if (obj is SubmitSignInCredentialsEvent) { SubmitSignInCredentialsEvent signInCred = (SubmitSignInCredentialsEvent)obj; WebServerManager.UpdateSignInCredentials(signInCred.userName, signInCred.email, OnSignInSuccessfully, OnSignInFailed); } }
protected override void OnRaiseSuccess(IEventBase <K> @event, byte[] bytes) { using (var dms = new MemoryStream(bytes)) { Apply(BackupState, (IEventBase <K>)Serializer.Deserialize(@event.GetType(), dms)); } BackupState.FullUpdateVersion(@event, GrainType);//更新处理完成的Version }
public static void RaiseEvent( IEventBase raisedEvent ) { Events.OnNext( raisedEvent ); }