/// <summary> /// 生成测试数据 /// </summary> /// <returns></returns> private async Task <List <Customer> > InsertRangeCustomer(int rows) { var list = new List <Customer>(); for (int i = 0; i < rows; i++) { var id = IdGenerater.GetNextId(); var customer = new Customer() { Id = id, Account = "alpha2008", Nickname = IdGenerater.GetNextId().ToString(), Realname = IdGenerater.GetNextId().ToString() }; customer.FinanceInfo = new CustomerFinance { Account = "alpha2008", Id = id, Balance = 0 }; list.Add(customer); } await _cusRsp.InsertRangeAsync(list); return(list); }
protected override async ETTask Run(Session session, G2M_CreateUnit request, M2G_CreateUnit response, Action reply) { //并且生成ID 创建Unit实体对象 Unit unit = ComponentFactory.CreateWithId <Unit>(IdGenerater.GenerateId()); unit.AddComponent <MoveComponent>(); unit.AddComponent <UnitPathComponent>(); //设置实体位置 unit.Position = new Vector3(-10, 0, -10); //添加邮箱 await unit.AddComponent <MailBoxComponent>().AddLocation(); //添加单位网关组件 主要是缓存该单位在网关服务器的Session Id //GateSessionActorId = request.GateSessionId unit.AddComponent <UnitGateComponent, long>(request.GateSessionId); //缓存这个单位 Game.Scene.GetComponent <UnitComponent>().Add(unit); //设置响应的字段 UnitId response.UnitId = unit.Id; // 广播协议:创建unit M2C_CreateUnits createUnits = new M2C_CreateUnits(); //获取所有的玩家 然后进行广播 Unit[] units = Game.Scene.GetComponent <UnitComponent>().GetAll(); foreach (Unit u in units) { UnitInfo unitInfo = new UnitInfo(); unitInfo.X = u.Position.x; unitInfo.Y = u.Position.y; unitInfo.Z = u.Position.z; unitInfo.UnitId = u.Id; createUnits.Units.Add(unitInfo); } MessageHelper.Broadcast(createUnits); //响应网关的请求 reply(); }
protected async ETVoid RunAsync(Session session, G2M_CreateUnit message, Action <M2G_CreateUnit> reply) { //NOTE 第二时间 游戏服务器收到创建Unit的请求 M2G_CreateUnit response = new M2G_CreateUnit(); try { Unit unit = ComponentFactory.CreateWithId <Unit>(IdGenerater.GenerateId()); unit.AddComponent <MoveComponent>(); unit.AddComponent <UnitPathComponent>(); unit.Position = new Vector3(-10, 0, -10); await unit.AddComponent <MailBoxComponent>().AddLocation(); unit.AddComponent <UnitGateComponent, long>(message.GateSessionId); Game.Scene.GetComponent <UnitComponent>().Add(unit); response.UnitId = unit.Id; // 广播创建的unit M2C_CreateUnits createUnits = new M2C_CreateUnits(); Unit[] units = Game.Scene.GetComponent <UnitComponent>().GetAll(); foreach (Unit u in units) { UnitInfo unitInfo = new UnitInfo(); unitInfo.X = u.Position.x; unitInfo.Y = u.Position.y; unitInfo.Z = u.Position.z; unitInfo.UnitId = u.Id; createUnits.Units.Add(unitInfo); } MessageHelper.Broadcast(createUnits); reply(response); } catch (Exception e) { ReplyError(response, e, reply); } }
private void Start() { if (ID == 0) { ID = IdGenerater.GenerateId(); } UnitManager.Instance.Add(this); Animator = GetComponent <Animator>(); Collider = GetComponent <Collider>(); AnimatorController animatorController = Animator.runtimeAnimatorController as AnimatorController; AnimatorStateMachine animatorStateMachine = animatorController.layers[0].stateMachine; for (int i = 0; i < animatorStateMachine.states.Length; i++) { ChildAnimatorState childAnimatorState = animatorStateMachine.states[i]; string stateName = childAnimatorState.state.name; int nameHash = childAnimatorState.state.nameHash; StateDic.Add(nameHash, stateName); if (childAnimatorState.state.behaviours.Length == 0) { childAnimatorState.state.AddStateMachineBehaviour <UnitStateBehaviour>(); } AnimatorStateTransition[] transitions = childAnimatorState.state.transitions; if (transitions.Length > 1) { throw new Exception($"State:{stateName},不能包含多个Tansition"); } if (transitions.Length == 1) { AnimatorStateTransition transition = transitions[0]; TransitionStateDic.Add(nameHash, transition.destinationState.name); } } }
protected async ETVoid RunAsync(Session session, G2M_CreateShip message, Action <M2G_CreateShip> reply) { //NOTE 第二时间 游戏服务器收到创建Unit的请求 M2G_CreateShip response = new M2G_CreateShip(); try { Ship ship = ComponentFactory.CreateWithId <Ship>(IdGenerater.GenerateId()); ship.AddComponent <MoveComponent>(); ship.AddComponent <ShipSkillComponent>(); ship.Position = new Vector3(-10, 0, -10); await ship.AddComponent <MailBoxComponent>().AddLocation(); ship.AddComponent <ShipGateComponent, long>(message.GateSessionId); Game.Scene.GetComponent <ShipComponent>().Add(ship); response.ShipId = ship.Id; // 广播创建的unit M2C_CreateShips createShips = new M2C_CreateShips(); Ship[] ships = Game.Scene.GetComponent <ShipComponent>().GetAll(); foreach (Ship itemShip in ships) { ShipInfo shipInfo = new ShipInfo(); shipInfo.X = itemShip.Position.x; shipInfo.Y = itemShip.Position.y; shipInfo.Z = itemShip.Position.z; shipInfo.ShipId = itemShip.Id; createShips.Ships.Add(shipInfo); } MessageHelper.Broadcast(createShips); reply(response); } catch (Exception e) { ReplyError(response, e, reply); } }
protected override async void Run(Session session, RegisterRt message, Action <RegisterRe> reply) { RegisterRe response = new RegisterRe(); try { //数据库操作对象 DBProxyComponent dbProxy = Game.Scene.GetComponent <DBProxyComponent>(); Log.Debug("RegisterRt:" + message.Account + " - " + message.Password); //查询账号是否存在 List <AccountInfo> result = await dbProxy.QueryJson <AccountInfo>($"{"{'Account':'"}{message.Account}{"'}"}"); if (result.Count > 0) { response.Error = ErrorCode.ErrAccountAlreadyRegister; reply(response); return; } //新建账号和用户信息 AccountInfo newAccount = EntityFactory.CreateWithId <AccountInfo>(IdGenerater.GenerateId()); newAccount.Account = message.Account; newAccount.Password = message.Password; UserInfo newUser = EntityFactory.CreateWithId <UserInfo>(newAccount.Id); newUser.NickName = $"用户{IdGenerater.GenerateId()}"; newUser.Money = 10000; await dbProxy.Save(newAccount); await dbProxy.Save(newUser); reply(response); } catch (Exception e) { ReplyError(response, e, reply); } }
/// <summary> /// 分配货架给商品 /// </summary> /// <param name="shelf"></param> /// <param name="productId"></param> /// <returns></returns> public async Task AllocateShelfToProductAsync(Shelf shelf, Product product) { var existShelf = await _shelfRepo.FetchAsync(x => x, x => x.ProductId == product.Id, noTracking : false); //一个商品只能分配一个货架,但可以调整货架。 if (existShelf != null && existShelf.Id != shelf.Id) { throw new AdncArgumentException("AssignedWarehouseId", nameof(shelf)); } shelf.SetProductId(product.Id); //发布领域事件,Product会订阅该事件,调整商品对应的货架号。 var eventId = IdGenerater.GetNextId(IdGenerater.DatacenterId, IdGenerater.WorkerId); var eventData = new ShelfToProductAllocatedEvent.EventData() { ShelfId = shelf.Id, ProductId = product.Id }; var eventSource = System.Reflection.MethodBase.GetCurrentMethod().DeclaringType.FullName; await _eventPublisher.PublishAsync(new ShelfToProductAllocatedEvent(eventId, eventData, eventSource)); }
public async Task TestInsert() { var id = IdGenerater.GetNextId(); var radmon = (long)(DateTime.UtcNow - new DateTime(1970, 1, 1, 0, 0, 0, DateTimeKind.Utc)).TotalMilliseconds; var cusotmer = new Customer { Id = id , Account = $"a{radmon}" , Realname = $"r{radmon}" , Nickname = $"n{radmon}" , FinanceInfo = new CustomerFinance { Id = id, Account = $"a{radmon}", Balance = 0 } }; await _customerRsp.InsertAsync(cusotmer); }
public async Task TestDbContext() { var account = "alpha008"; using (var db = await _dbContext.Database.BeginTransactionAsync()) { //_unitOfWork.BeginTransaction(); await _customerRsp.DeleteRangeAsync(x => x.Id <= 10000); var id = IdGenerater.GetNextId(); var customer = new Customer() { Id = id, Account = account, Nickname = "招财猫", Realname = "张发财", FinanceInfo = new CustomerFinance { Id = id, Account = account, Balance = 0 } }; _dbContext.Add <Customer>(customer); await _dbContext.SaveChangesAsync(); var id2 = IdGenerater.GetNextId(); var customer2 = new Customer() { Id = id2, Account = account, Nickname = "招财猫02", Realname = "张发财02", FinanceInfo = new CustomerFinance { Id = id2, Account = account, Balance = 0 } }; _dbContext.Add <Customer>(customer2); //_unitOfWork.Commit(); await _dbContext.SaveChangesAsync(); await db.CommitAsync(); } }
/// <summary> /// 使用帳號密碼註冊 /// </summary> /// <param name="email"></param> /// <param name="password"></param> /// <returns></returns> public static async ETTask <int> SignUp(string email, string password, User.Identity identity = User.Identity.Player) { ThirdPartyUser thirdPartyUser = await FindOneThirdPartyUser(email, tagJPlay); if (thirdPartyUser != null) { return(ErrorCode.ERR_SignUpFailed); } else { long now = DateTimeOffset.UtcNow.ToUnixTimeMilliseconds(); string salt = CryptographyHelper.GenerateRandomId(); string hashPassword = CryptographyHelper.MD5Encoding(password, salt); User user = ComponentFactory.CreateWithId <User>(IdGenerater.GenerateId()); user.salt = salt; user.email = email; user.hashPassword = hashPassword; user.createAt = now; user.name = $"{user.Id}"; user.playerCharSetting = new PlayerCharSetting(); user.playerCharSetting.CharacterId = 1L; user.playerRideTotalInfo = new RideTotalInfo(); user.identity = (int)identity; await SinUserUp(user); thirdPartyUser = ComponentFactory.CreateWithId <ThirdPartyUser>(IdGenerater.GenerateId()); thirdPartyUser.uid = user.Id; thirdPartyUser.party = tagJPlay; thirdPartyUser.userId = user.email; thirdPartyUser.name = ""; thirdPartyUser.gender = ""; thirdPartyUser.location = ""; thirdPartyUser.email = email; thirdPartyUser.birthday = ""; thirdPartyUser.createAt = now; await UpsertThirdPartyUser(thirdPartyUser); return(ErrorCode.ERR_Success); } }
private List <SysDict> GetSubDicts(long pid, string dictValues) { List <SysDict> subDicts = new List <SysDict>(); if (!string.IsNullOrWhiteSpace(dictValues)) { //var snowflake = new Snowflake(1, 1); var values = dictValues.Split(";", StringSplitOptions.RemoveEmptyEntries); subDicts = values.Select((s, Index) => new SysDict { //ID = snowflake.NextId() ID = IdGenerater.GetNextId() , Pid = pid , Name = s.Split(":", StringSplitOptions.RemoveEmptyEntries)[1] , Num = s.Split(":", StringSplitOptions.RemoveEmptyEntries)[0] }).ToList(); } return(subDicts); }
public async Task Save(DictSaveInputDto saveDto) { //add if (saveDto.ID == 0) { //long Id = new Snowflake(1, 1).NextId(); long Id = IdGenerater.GetNextId(); var subDicts = GetSubDicts(Id, saveDto.DictValues); await _dictRepository.InsertRangeAsync(subDicts.Append(new SysDict { ID = Id, Pid = 0, Name = saveDto.DictName, Tips = saveDto.Tips, Num = "0" })); } //update else { var dict = new SysDict { Name = saveDto.DictName, Tips = saveDto.Tips, ID = saveDto.ID, Pid = 0 }; var subDicts = GetSubDicts(saveDto.ID, saveDto.DictValues); await _maintManagerService.UpdateDicts(dict, subDicts); } }
public override void EndInit() { try { this.InstanceId = IdGenerater.GenerateId(); this.componentDict.Clear(); if (this.components != null) { foreach (Component component in this.components) { component.Parent = this; this.componentDict.Add(component.GetType(), component); } } } catch (Exception e) { Log.Error(e); } }
public static ETTask <IActorResponse> CallWithoutException(this ActorMessageSenderComponent self, long actorId, IActorRequest message) { if (actorId == 0) { throw new Exception($"actor id is 0: {MongoHelper.ToJson(message)}"); } string address = StartConfigComponent.Instance.GetProcessInnerAddress(IdGenerater.GetProcessId(actorId)); Session session = NetInnerComponent.Instance.Get(address); message.ActorId = actorId & IdGenerater.HeadMask | IdGenerater.Head; message.RpcId = ++self.RpcId; var tcs = new ETTaskCompletionSource <IActorResponse>(); self.requestCallback.Add(message.RpcId, new ActorMessageSender((response) => { tcs.SetResult(response); })); session.Send(message); return(tcs.Task); }
private async ETVoid RunAsync(Session session, G2B_CreateTank message, Action <B2G_CreateTank> reply) { B2G_CreateTank response = new B2G_CreateTank(); try { Battle battle = Game.Scene.GetComponent <BattleComponent>().Get(message.BattleId); // 随机生成一辆坦克,id和instanceId不相等 Tank tank = ComponentFactory.CreateWithId <Tank>(IdGenerater.GenerateId()); tank.PlayerId = message.PlayerId; tank.Battle = battle; tank.Name = message.Name; tank.Level = message.Level; tank.AddComponent <NumericComponent>(); battle.Add(tank); tank.TankCamp = message.Camp == 1? TankCamp.Left : TankCamp.Right; await tank.AddComponent <MailBoxComponent>().AddLocation(); tank.AddComponent <TankGateComponent, long>(message.GateSessionId); response.TankId = tank.Id; reply(response); } catch (Exception e) { ReplyError(response, e, reply); } }
public static async ETVoid HandleIActorRequest(Session session, IActorRequest iActorRequest) { long replyId = IdGenerater.GetProcessId(iActorRequest.ActorId); iActorRequest.ActorId = iActorRequest.ActorId & IdGenerater.HeadMask | IdGenerater.Head; string address = StartConfigComponent.Instance.GetProcessInnerAddress(replyId); Session ss = NetInnerComponent.Instance.Get(address); Entity entity = Game.EventSystem.Get(iActorRequest.ActorId); if (entity == null) { Log.Warning($"not found actor: {MongoHelper.ToJson(iActorRequest)}"); ActorResponse response = new ActorResponse { Error = ErrorCode.ERR_NotFoundActor, RpcId = iActorRequest.RpcId, }; ss.Reply(response); return; } MailBoxComponent mailBoxComponent = entity.GetComponent <MailBoxComponent>(); if (mailBoxComponent == null) { ActorResponse response = new ActorResponse { Error = ErrorCode.ERR_ActorNoMailBoxComponent, RpcId = iActorRequest.RpcId, }; ss.Reply(response); Log.Error($"actor not add MailBoxComponent: {entity.GetType().Name} {iActorRequest}"); return; } await mailBoxComponent.Handle(ss, iActorRequest); }
protected override async ETTask Run(Session session, G2M_CreateUnit request, M2G_CreateUnit response, Action reply) { Unit unit = ComponentFactory.CreateWithId <Unit>(IdGenerater.GenerateId()); unit.Position = new Vector3(-10, 0, -10); SyncType type = Game.Scene.GetComponent <NetSyncComponent>().type; if (type == SyncType.State) { unit.AddComponent <MoveComponent>(); unit.AddComponent <UnitPathComponent>(); } await unit.AddComponent <MailBoxComponent>().AddLocation(); unit.AddComponent <UnitGateComponent, long>(request.GateSessionId); Game.Scene.GetComponent <UnitComponent>().Add(unit); response.UnitId = unit.Id; // 广播创建的unit M2C_CreateUnits createUnits = new M2C_CreateUnits(); Unit[] units = Game.Scene.GetComponent <UnitComponent>().GetAll(); foreach (Unit u in units) { UnitInfo unitInfo = new UnitInfo(); unitInfo.X = u.Position.x; unitInfo.Y = u.Position.y; unitInfo.Z = u.Position.z; unitInfo.UnitId = u.Id; createUnits.Units.Add(unitInfo); } MessageHelper.Broadcast(createUnits); reply(); }
public async Task <AppSrvResult> UpdateAsync(long id, DictUpdationDto input) { var exists = (await _cacheService.GetAllDictsFromCacheAsync()).Exists(x => x.Name.EqualsIgnoreCase(input.Name) && x.Id != id); if (exists) { return(Problem(HttpStatusCode.BadRequest, "字典名字已经存在")); } var dict = new SysDict { Name = input.Name, Value = input.Value, Id = id, Pid = 0, Ordinal = input.Ordinal }; var subDicts = new List <SysDict>(); input.Children?.ForEach(x => { subDicts.Add(new SysDict { Id = IdGenerater.GetNextId(), Pid = id, Name = x.Name, Value = x.Value, Ordinal = x.Ordinal }); }); await _dictRepository.UpdateAsync(dict, UpdatingProps <SysDict>(d => d.Name, d => d.Value, d => d.Ordinal)); await _dictRepository.DeleteRangeAsync(d => d.Pid == dict.Id); if (subDicts.IsNotNullOrEmpty()) { await _dictRepository.InsertRangeAsync(subDicts); } return(AppSrvResult()); }
public async Task <AppSrvResult <long> > CreateAsync(UserCreationDto input) { if (await _userRepository.AnyAsync(x => x.Account == input.Account)) { return(Problem(HttpStatusCode.BadRequest, "账号已经存在")); } var user = Mapper.Map <SysUser>(input); user.Id = IdGenerater.GetNextId(); user.Account = user.Account.ToLower(); user.Salt = SecurityHelper.GenerateRandomCode(5); user.Password = HashHelper.GetHashedString(HashType.MD5, user.Password, user.Salt); var cacheKey = _cacheService.ConcatCacheKey(CachingConsts.UserValidateInfoKeyPrefix, user.Id); await _cacheService.BloomFilters.CacheKeys.AddAsync(cacheKey); await _cacheService.BloomFilters.Accounts.AddAsync(user.Account); await _userRepository.InsertAsync(user); return(user.Id); }
public async Task TestAutoTransactions() { var defaultAutoTransaction = _dbContext.Database.AutoTransactionsEnabled; if (defaultAutoTransaction == false) { _dbContext.Database.AutoTransactionsEnabled = true; } var id = IdGenerater.GetNextId(IdGenerater.DatacenterId, IdGenerater.WorkerId); var radmon = (long)(DateTime.UtcNow - new DateTime(1970, 1, 1, 0, 0, 0, DateTimeKind.Utc)).TotalMilliseconds; var cusotmer = new Customer { Id = id , Account = $"a{radmon}" , Realname = $"r{radmon}" , Nickname = $"n{radmon}" }; _dbContext.Add(cusotmer); //不受自动事务控制 await _customerRsp.DeleteAsync(10000); //不受自动事务控制 await _customerRsp.DeleteRangeAsync(x => x.Id == id); _dbContext.SaveChanges(); if (defaultAutoTransaction == false) { _dbContext.Database.AutoTransactionsEnabled = false; } }
public async Task <AppSrvResult <long> > CreateAsync(DictCreationDto input) { var exists = (await _cacheService.GetAllDictsFromCacheAsync()).Exists(x => x.Name.EqualsIgnoreCase(input.Name)); if (exists) { return(Problem(HttpStatusCode.BadRequest, "字典名字已经存在")); } var dists = new List <SysDict>(); long id = IdGenerater.GetNextId(); //var subDicts = GetSubDicts(id, input.DictValues); var dict = new SysDict { Id = id, Name = input.Name, Value = input.Value, Ordinal = input.Ordinal, Pid = 0 }; dists.Add(dict); input.Children?.ForEach(x => { dists.Add(new SysDict { Id = IdGenerater.GetNextId() , Pid = id , Name = x.Name , Value = x.Value , Ordinal = x.Ordinal }); }); await _dictRepository.InsertRangeAsync(dists); return(id); }
public async Task Save(TaskSaveInputDto saveDto) { if (saveDto.Name.IsNullOrWhiteSpace()) { throw new BusinessException(new ErrorModel(ErrorCode.BadRequest, "请输入任务名称")); } //add if (saveDto.ID == 0) { var exist = await _taskRepository.ExistAsync(c => c.Name == saveDto.Name); if (exist) { throw new BusinessException(new ErrorModel(ErrorCode.BadRequest, "任务名称已经存在")); } var enity = _mapper.Map <SysTask>(saveDto); //enity.ID = new Snowflake(1, 1).NextId(); enity.ID = IdGenerater.GetNextId(); await _taskRepository.InsertAsync(enity); } //update else { var exist = await _taskRepository.ExistAsync(c => c.Name == saveDto.Name && c.ID != saveDto.ID); if (exist) { throw new BusinessException(new ErrorModel(ErrorCode.BadRequest, "任务名称已经存在")); } var enity = _mapper.Map <SysTask>(saveDto); await _taskRepository.UpdateAsync(enity); } }
public async Task <AppSrvResult> UpdateAsync(long id, DictUpdationDto input) { var exists = (await _cacheService.GetAllDictsFromCacheAsync()).Exists(x => x.Name.EqualsIgnoreCase(input.Name) && x.Id != id); if (exists) { return(Problem(HttpStatusCode.BadRequest, "字典名字已经存在")); } var dict = new SysDict { Name = input.Name, Value = input.Value, Id = id, Pid = 0, Ordinal = input.Ordinal }; var subDicts = new List <SysDict>(); input.Children?.ForEach(x => { subDicts.Add(new SysDict { Id = IdGenerater.GetNextId() , Pid = id , Name = x.Name , Value = x.Value , Ordinal = x.Ordinal }); }); // 这里需要事务处理 await _maintManager.UpdateDictsAsync(dict, subDicts); return(AppSrvResult()); }
/// <summary> /// 设置相应等级的对象 /// </summary> protected virtual void SetLevel(int level, int upgradeBranch = 0) { if (upgradeBranch > agentLevels[currentLevel].Count) { return; } if (level < 0 || level >= agentLevels.Count) { return; } this.currentLevel = level; this.upgradeBranch = upgradeBranch; if (currentAgentLevel != null) { RemoveAllBuff(); Destroy(currentAgentLevel); } currentAgentLevel = Create(); list_skill.Clear(); //foreach (int skillId in currentTargetLevelData.monster.SkillList) //{ // list_skill.Add(skillId, new CoolDown(0, GameData.skills[skillId])); //} list_skill.Add(2002, new CoolDown(0, ConfigService.Instance.SkillCfgList.GetOne(2002))); list_skill.Add(2003, new CoolDown(0, ConfigService.Instance.SkillCfgList.GetOne(2003))); //测试 this.configuration.SetMaxHealth(currentTargetLevelData.monster.MaxHealth); this.configuration.SetHealth(currentTargetLevelData.monster.MaxHealth); InstanceId = IdGenerater.GenerateInstanceId(); }
// 给玩家发送好友房钥匙 // endTime为“-1”代表永久有效 public static async Task AddFriendKey(long uid, int num, string endTime, string reason) { try { DBProxyComponent proxyComponent = Game.Scene.GetComponent <DBProxyComponent>(); for (int i = 0; i < num; i++) { FriendKey friendKey = ComponentFactory.CreateWithId <FriendKey>(IdGenerater.GenerateId()); friendKey.Uid = uid; friendKey.endTime = endTime; await proxyComponent.Save(friendKey); } await Log_ChangeWealth(uid, 112, num, reason); //Log.Info("修改完后玩家:" + uid + "钥匙数量为:" + await GetUserFriendKeyNum(uid)); } catch (Exception e) { Log.Error("AddFriendKey异常:" + e); } }
public async Task <SimpleDto <string> > Recharge(RechargeInputDto inputDto) { if (inputDto.Amount == 0) { throw new BusinessException(new ErrorModel(ErrorCode.BadRequest, "充值金额不能等于0")); } var customer = await _customerRepo.FindAsync(new object[] { inputDto.ID }); if (customer == null) { throw new BusinessException(new ErrorModel(ErrorCode.Forbidden, "不存在该账号")); } var cusTransactionLog = new CusTransactionLog() { ID = IdGenerater.GetNextId(IdGenerater.DatacenterId, IdGenerater.WorkerId) , Account = customer.Account , ExchangeType = "100" , Remark = "" , Amount = inputDto.Amount , ExchageStatus = "10" }; await _cusManagerService.Recharge(customer.ID, inputDto.Amount, cusTransactionLog); return(new SimpleDto <string>() { Result = cusTransactionLog.ID.ToString() }); }
public async Task TestInsertRange() { var customer = await _customerRsp.FetchAsync(x => x, x => x.Id > 1); var id0 = IdGenerater.GetNextId(); var id1 = IdGenerater.GetNextId(); var logs = new List <CustomerTransactionLog> { new CustomerTransactionLog { Id = id0, Account = customer.Account, ChangedAmount = 0, Amount = 0, ChangingAmount = 0, CustomerId = customer.Id, ExchangeType = ExchangeTypeEnum.Recharge, ExchageStatus = ExchageStatusEnum.Finished, Remark = "test" } , new CustomerTransactionLog { Id = id1, Account = customer.Account, ChangedAmount = 0, Amount = 0, ChangingAmount = 0, CustomerId = customer.Id, ExchangeType = ExchangeTypeEnum.Recharge, ExchageStatus = ExchageStatusEnum.Finished, Remark = "test" } }; await _custLogsRsp.InsertRangeAsync(logs); var logsFromDb = await _custLogsRsp.Where(x => x.Id == id0 || x.Id == id1).ToListAsync(); Assert.NotEmpty(logsFromDb); Assert.Equal(2, logsFromDb.Count); }
/// <summary> /// 生成测试数据 /// </summary> /// <returns></returns> private async Task <Customer> InsertCustomer() { var id = IdGenerater.GetNextId(IdGenerater.DatacenterId, IdGenerater.WorkerId); var customer = new Customer() { ID = id, Account = "alpha2008", Nickname = IdGenerater.GetNextId().ToString(), Realname = IdGenerater.GetNextId().ToString() }; await _cusRsp.InsertAsync(customer); return(customer); }
public async Task <UserValidateDto> Login(UserValidateInputDto inputDto, CurrenUserInfoDto currentUser) { //var user4 = _userRepository.GetAll<SysMenu>().FirstOrDefault(); //var user0 = _rsp.GetAll<SysUser>().FirstOrDefault(); var user = await _userRepository.FetchAsync(x => new { x.Password, x.Salt, x.Name, x.Email, x.RoleId, x.Account, x.ID, x.Status }, x => x.Account == inputDto.Account); dynamic log = new ExpandoObject(); log.ID = IdGenerater.GetNextId(IdGenerater.DatacenterId, IdGenerater.WorkerId); log.Account = inputDto.Account; log.CreateTime = DateTime.Now; log.Device = currentUser.Device; log.RemoteIpAddress = currentUser.RemoteIpAddress; log.Message = string.Empty; log.Succeed = false; log.UserId = user?.ID; log.UserName = user?.Name; if (user == null) { var errorModel = new ErrorModel(ErrorCode.NotFound, "用户名或密码错误"); log.Message = JsonSerializer.Serialize(errorModel); throw new BusinessException(errorModel); } else { if (user.Status != 1) { var errorModel = new ErrorModel(ErrorCode.TooManyRequests, "账号已锁定"); log.Message = JsonSerializer.Serialize(errorModel); _mqProducer.BasicPublish(MqExchanges.Logs, MqRoutingKeys.Loginlog, log); throw new BusinessException(errorModel); } //var logins = await _loginLogRepository.SelectAsync(5, x => new { x.ID, x.Succeed,x.CreateTime }, x => x.UserId == user.ID, x => x.ID, false); //var failLoginCount = logins.Count(x => x.Succeed == false); var failLoginCount = 2; if (failLoginCount == 5) { var errorModel = new ErrorModel(ErrorCode.TooManyRequests, "连续登录失败次数超过5次,账号已锁定"); log.Message = JsonSerializer.Serialize(errorModel); await _userRepository.UpdateAsync(new SysUser() { ID = user.ID, Status = 2 }, x => x.Status); throw new BusinessException(errorModel); } if (HashHelper.GetHashedString(HashType.MD5, inputDto.Password, user.Salt) != user.Password) { var errorModel = new ErrorModel(ErrorCode.NotFound, "用户名或密码错误"); log.Message = JsonSerializer.Serialize(errorModel); _mqProducer.BasicPublish(MqExchanges.Logs, MqRoutingKeys.Loginlog, log); throw new BusinessException(errorModel); } if (string.IsNullOrEmpty(user.RoleId)) { var errorModel = new ErrorModel(ErrorCode.Forbidden, "未分配任务角色,请联系管理员"); log.Message = JsonSerializer.Serialize(errorModel); _mqProducer.BasicPublish(MqExchanges.Logs, MqRoutingKeys.Loginlog, log); throw new BusinessException(errorModel); } } log.Message = "登录成功"; log.Succeed = true; _mqProducer.BasicPublish(MqExchanges.Logs, MqRoutingKeys.Loginlog, log); return(_mapper.Map <UserValidateDto>(user)); }
public void Update() { var localUnit = Unit.LocalUnit; if (localUnit == null) { return; } if (localUnit.BodyView == null) { return; } if (localUnit.SkillDiretorTrm != null) { var ray = Camera.main.ScreenPointToRay(Input.mousePosition); RaycastHit hit; if (Physics.Raycast(ray, out hit, 1000, this.MapMask)) { localUnit.SkillDiretorTrm.position = localUnit.Position; var trmP = localUnit.SkillDiretorTrm.position; var direction = new Vector3(hit.point.x, trmP.y, hit.point.z) - trmP; //var dist = Vector3.Distance(direction, _lastDirection); localUnit.SkillDiretorTrm.forward = _lastDirection = direction; } } msg.UnitId = localUnit.Id; msg.Index++; msg.Operation = 0; var p = localUnit.Position; msg.X = (int)(p.x * 100); msg.Y = (int)(p.y * 100); msg.Z = (int)(p.z * 100); msg.AngleY = (int)(localUnit.Rotation.y * 100); if (Input.GetMouseButtonDown(0)) { localUnit.Firing = true; } if (Input.GetMouseButtonUp(0)) { localUnit.Firing = false; } if (localUnit.Firing) { if (TimeHelper.Now() - localUnit.LastFireTime < 200) { return; } if (localUnit.SkillDiretorTrm) { localUnit.LastFireTime = TimeHelper.Now(); //if (!localUnit.PreviousFiring) //{ // localUnit.PreviousFiring = true; // localUnit.CharacterController.MaxStableMoveSpeed = 4; // localUnit.CharacterController.LockRotation(localUnit.SkillDiretorTrm.localEulerAngles); //} //localUnit.CharacterController.SetRotation(localUnit.SkillDiretorTrm.localEulerAngles); msg.Operation = OperaType.Fire; msg.AngleY = (int)(localUnit.Rotation.y * 100); p = localUnit.SkillDiretorTrm.Find("TargetPoint").position; msg.IntParams.Clear(); msg.LongParams.Clear(); var x = (int)(p.x * 100); var y = (int)(p.y * 100); var z = (int)(p.z * 100); msg.IntParams.Add(x); msg.IntParams.Add(y); msg.IntParams.Add(z); var bulletId = IdGenerater.GenerateId(); msg.IntParams.Add(1); msg.LongParams.Add(bulletId); SessionHelper.HotfixSend(msg); } return; } else { //if (localUnit.PreviousFiring) //{ // localUnit.PreviousFiring = false; // await TimerComponent.Instance.WaitAsync(100); // localUnit.CharacterController.MaxStableMoveSpeed = 10; // localUnit.CharacterController.CancelLockRotation(); //} } if (TimeHelper.Now() - lastSendTime > 100) { lastSendTime = TimeHelper.Now(); if (Vector3.Distance(localUnit.LastPosition, p) < 0.05f) { return; } localUnit.LastPosition = p; SessionHelper.HotfixSend(msg); } }