public ActionResult Requirement() { //getting the project and category id int projId = Convert.ToInt32(Session["projectid"]); int catId = Convert.ToInt32(Session["Catid"]); //checks if a requirement exist ReviseDBEntities con = new ReviseDBEntities(); int req = 0; if (con.requirements.Where(p => p.projid == projId).SingleOrDefault(c => c.catid == catId) != null) { req = con.requirements.Where(p => p.projid == projId).SingleOrDefault(c => c.catid == catId).reqId; } if (req == 0) { Session["ReqExisit"] = 0; return(View()); } else { Session["ReqId"] = req; Session["ReqExisit"] = 1; var repo = new MainRepository(); var Main = repo.Requirement(req); return(View(Main)); } }
public ActionResult EditCategory(int?id, int projid) { var repo = new MainRepository(); var Main = repo.CatEditView(id, projid); return(View(Main)); }
public static async Task StreamCharacterAsync(MainRepository repo, Character character) { // 同じ都市にいる他国の武将への通知、移動前の都市に滞在かつ違う国の武将への都市移動の通知は、以下の処理の中に含まれるので特段の対処は不要 var icon = (await repo.Character.GetCharacterAllIconsAsync(character.Id)).GetMainOrFirst(); var town = await repo.Town.GetByIdAsync(character.TownId); var townCharacters = await repo.Town.GetCharactersAsync(character.TownId); // この武将の所属する国の武将 await StatusStreaming.Default.SendCountryExceptForCharacterAsync(ApiData.From(new CharacterForAnonymous(character, icon.Data, CharacterShareLevel.SameCountry)), character.CountryId, character.Id); // 都市の武将 await StatusStreaming.Default.SendCharacterAsync(ApiData.From(new CharacterForAnonymous(character, icon.Data, character.AiType != CharacterAiType.SecretaryScouter ? CharacterShareLevel.SameTown : CharacterShareLevel.Anonymous)), townCharacters.Where(tc => tc.Id != character.Id && tc.CountryId != character.CountryId).Select(tc => tc.Id)); if (town.HasData && town.Data.CountryId != character.CountryId) { // この都市を所有している国の武将 await StatusStreaming.Default.SendCountryExceptForCharacterAsync(ApiData.From(new CharacterForAnonymous(character, icon.Data, character.AiType != CharacterAiType.SecretaryScouter ? CharacterShareLevel.SameCountryTownOtherCountry : CharacterShareLevel.Anonymous)), town.Data?.CountryId ?? 0, townCharacters.Where(tc => tc.CountryId == town.Data?.CountryId).Select(tc => tc.Id)); } // 本人と違う国で、かつ同じ都市にいない武将 await StatusStreaming.Default.SendAllExceptForCharactersAndCountryAsync(ApiData.From(new CharacterForAnonymous(character, icon.Data, CharacterShareLevel.Anonymous)), townCharacters.Select(tc => tc.Id), new uint[] { town.Data?.CountryId ?? 0, character.CountryId, }); // 本人 await StatusStreaming.Default.SendCharacterAsync(ApiData.From(character), character.Id); }
public override async Task InputAsync(MainRepository repo, uint characterId, IEnumerable <GameDateTime> gameDates, params CharacterCommandParameter[] options) { var direction = (CreateTownDirection)options.FirstOrDefault(p => p.Type == 1).Or(ErrorCode.LackOfCommandParameter).NumberValue; var townType = options.FirstOrDefault(p => p.Type == 2).Or(ErrorCode.LackOfCommandParameter).NumberValue; await repo.CharacterCommand.SetAsync(characterId, this.Type, gameDates, options); }
public static AllItemsFragment NewInstance(MainRepository repository) { return(_instance ?? (_instance = new AllItemsFragment { _repository = repository })); }
public async Task SetCountryPolicyAsync( [FromBody] CountryPolicy param) { ErrorCode.NotSupportedError.Throw(); var info = CountryPolicyTypeInfoes.Get(param.Type); if (!info.HasData) { ErrorCode.InvalidParameterError.Throw(); } using (var repo = MainRepository.WithReadAndWrite()) { var system = await repo.System.GetAsync(); var chara = await repo.Character.GetByIdAsync(this.AuthData.CharacterId).GetOrErrorAsync(ErrorCode.LoginCharacterNotFoundError); var country = await repo.Country.GetAliveByIdAsync(chara.CountryId).GetOrErrorAsync(ErrorCode.CountryNotFoundError); var posts = await repo.Country.GetCharacterPostsAsync(chara.Id); if (!posts.Any(p => p.Type.CanPolicy())) { ErrorCode.NotPermissionError.Throw(); } var isSucceed = await CountryService.SetPolicyAndSaveAsync(repo, country, param.Type); if (!isSucceed) { ErrorCode.InvalidOperationError.Throw(); } } }
public void Save(bool isAddingItem) { if (isAddingItem) { // Logic when adding new item. } else { if (this.Address != null) { MainRepository.Update(this.Address); } if (this.IsPerson) { MainRepository.Update(this.Person); } else { MainRepository.Update(this.Store); } MainRepository.Update(this); MainRepository.SaveChangesAsync(); } this.ReevalateProperties(); }
public void ForgetPassword(EntityHolder <UserForgetPasswordDto> entityHolder) { var userFromDb = MainRepository.FindFirstOrDefault(x => x.Username == entityHolder.Entity.Username && x.Email == entityHolder.Entity.Email); if (userFromDb != null) { userFromDb.ResetPasswordTokenValid = DateTime.Now.AddHours(1); userFromDb.ResetPasswordToken = Guid.NewGuid().ToString("N").ToUpper(); MainRepository.Update(userFromDb); MainRepository.Save(); Mail mail = new Mail { TemplateName = "forget-password.html", MailTo = userFromDb.Email, MailSubject = "Changing forgotten password", Attributes = new Dictionary <string, object> { { "username", userFromDb.Username }, { "passwordChangeLink", $"http://{entityHolder.BaseUrl}/change-password/{userFromDb.ResetPasswordToken}" } } }; _emailService.SendEmail(mail); } else { throw new Exception("Provided username and e-mail do not match."); } }
public async Task PostGlobalChatMessageAsync( [FromBody] ChatMessage param) { var ip = this.HttpContext.Connection.RemoteIpAddress?.ToString(); ChatMessage message; Character chara; if (string.IsNullOrEmpty(param.Message) || param.Message?.Length > 400) { ErrorCode.NumberRangeError.Throw(new ErrorCode.RangeErrorParameter("message", param.Message.Length, 1, 400)); } using (var repo = MainRepository.WithReadAndWrite()) { chara = await repo.Character.GetByIdAsync(this.AuthData.CharacterId).GetOrErrorAsync(ErrorCode.LoginCharacterNotFoundError); if (await repo.BlockAction.IsBlockedAsync(chara.Id, BlockActionType.StopGlobalChat)) { ErrorCode.BlockedActionError.Throw(); } message = await ChatService.PostChatMessageAsync(repo, param, chara, ip, ChatMessageType.Global, param.TypeData); await repo.SaveChangesAsync(); } await StatusStreaming.Default.SendAllAsync(ApiData.From(message)); }
public UserRegistrationDto Register(UserRegistrationDto user) { if (MainRepository.FindFirstOrDefault(x => x.Username == user.Username) != null) { throw new Exception("Username " + user.Username + " is already taken."); } if (MainRepository.FindFirstOrDefault(x => x.Email == user.Email) != null) { throw new Exception("Email " + user.Email + " is already taken."); } var userToInsert = _mapper.Map <User>(user); CreatePasswordHash(user.Password, out byte[] passwordHash, out byte[] passwordSalt); userToInsert.PasswordHash = passwordHash; userToInsert.PasswordSalt = passwordSalt; MainRepository.Add(userToInsert); MainRepository.Save(); // clear passwords user.Password = null; user.MatchPassword = null; return(user); }
private static async Task SendAsync(MainRepository repo, string title, string message, Predicate <PushNotificationKey> predicate) { var keys = await repo.PushNotificationKey.GetAllAsync(); try { // iOS var push = new ApnsServiceBroker(new ApnsConfiguration( ApnsConfiguration.ApnsServerEnvironment.Production, "/home/sangokukmy/push_notification_product.p12", "test")); push.OnNotificationFailed += (sender, e) => { Logger?.LogError(e, "プッシュ通知送信時にエラーが発生しました"); }; push.Start(); foreach (var key in keys.Where(k => k.Platform == PushNotificationPlatform.iOS && predicate(k))) { push.QueueNotification(new ApnsNotification { DeviceToken = key.Key, Payload = JObject.Parse(@"{""aps"":{""alert"":{""title"":""" + title + @""",""body"":""" + message + @"""},""badge"":1,""sound"":""default""}}"), }); } push.Stop(); } catch (Exception ex) { Logger?.LogError(ex, "プッシュ通知で例外が発生しました"); } try { // Android var config = new GcmConfiguration(Config.Database.GcmServerKey) { GcmUrl = "https://fcm.googleapis.com/fcm/send", }; var gcmBroker = new GcmServiceBroker(config); gcmBroker.OnNotificationFailed += (notification, aggregateEx) => { Logger?.LogError(aggregateEx, "プッシュ通知送信時にエラーが発生しました"); }; gcmBroker.Start(); gcmBroker.QueueNotification(new GcmNotification { RegistrationIds = keys.Where(k => k.Platform == PushNotificationPlatform.Android && predicate(k)).Select(k => k.Key).ToList(), Notification = JObject.Parse(@"{""title"":""" + title + @""",""body"":""" + message + @"""}"), }); gcmBroker.Stop(); } catch (Exception ex) { Logger?.LogError(ex, "プッシュ通知で例外が発生しました"); } }
public override async Task InputAsync(MainRepository repo, uint characterId, IEnumerable <GameDateTime> gameDates, params CharacterCommandParameter[] options) { var itemType = (CharacterItemType)options.FirstOrDefault(p => p.Type == 1).Or(ErrorCode.LackOfCommandParameter).NumberValue; var resourceSize = options.FirstOrDefault(p => p.Type == 3)?.NumberValue; var chara = await repo.Character.GetByIdAsync(characterId).GetOrErrorAsync(ErrorCode.LoginCharacterNotFoundError); var items = await repo.Character.GetItemsAsync(chara.Id); if (!items.Any(i => i.Type == itemType && (i.Status == CharacterItemStatus.CharacterHold || i.Status == CharacterItemStatus.CharacterPending))) { ErrorCode.InvalidCommandParameter.Throw(); } var info = CharacterItemInfoes.Get(itemType).GetOrError(ErrorCode.InvalidCommandParameter); if (!info.CanSell) { ErrorCode.InvalidCommandParameter.Throw(); } if (info.IsResource) { if (resourceSize == null) { ErrorCode.LackOfCommandParameter.Throw(); } if (resourceSize > info.DefaultResource) { ErrorCode.InvalidCommandParameter.Throw(); } } await repo.CharacterCommand.SetAsync(characterId, this.Type, gameDates, options); }
public static async Task SetCharacterPendingAsync(MainRepository repo, CharacterItem item, Character chara) { if (item.Status == CharacterItemStatus.CharacterHold || item.Status == CharacterItemStatus.CharacterPending) { if (item.CharacterId == chara.Id) { return; } var oldChara = await repo.Character.GetByIdAsync(item.CharacterId); if (oldChara.HasData) { await ReleaseCharacterAsync(repo, item, oldChara.Data); } } var system = await repo.System.GetAsync(); item.Status = CharacterItemStatus.CharacterPending; item.CharacterId = chara.Id; item.TownId = 0; item.LastStatusChangedGameDate = system.GameDateTime; await CharacterService.StreamCharacterAsync(repo, chara); await StatusStreaming.Default.SendAllAsync(ApiData.From(item)); }
public async Task <Account> CreateAsync( [FromBody] Account data = default) { if (data == null) { ErrorCode.LackOfParameterError.Throw(); } if (string.IsNullOrEmpty(data.AliasId) || data.AliasId.Length < 4 || data.AliasId.Length > 12) { ErrorCode.StringLengthError.Throw(new ErrorCode.RangeErrorParameter("aliasId", data.AliasId?.Length ?? 0, 4, 12)); } if (string.IsNullOrEmpty(data.Password) || data.Password.Length < 4 || data.Password.Length > 12) { ErrorCode.StringLengthError.Throw(new ErrorCode.RangeErrorParameter("password", data.Password?.Length ?? 0, 4, 12)); } if (string.IsNullOrEmpty(data.Name) || data.Name.Length > 12) { ErrorCode.StringLengthError.Throw(new ErrorCode.RangeErrorParameter("name", data.Name?.Length ?? 0, 1, 12)); } using (var repo = MainRepository.WithReadAndWrite()) { var chara = await repo.Character.GetByIdAsync(this.AuthData.CharacterId).GetOrErrorAsync(ErrorCode.LoginCharacterNotFoundError); var sameChara = await repo.Account.GetByCharacterIdAsync(chara.Id); if (sameChara.HasData) { ErrorCode.DuplicateAccountOfCharacterError.Throw(); } var sameAliasId = await repo.Account.GetByAliasIdAsync(data.AliasId); if (sameAliasId.HasData) { ErrorCode.DuplicateAccountNameOrAliasIdError.Throw(); } var sameName = await repo.Account.GetByNameAsync(data.Name); if (sameName.HasData) { ErrorCode.DuplicateAccountNameOrAliasIdError.Throw(); } var account = new Account { AliasId = data.AliasId, Name = data.Name, CharacterId = chara.Id, LoginCount = 1, }; account.SetPassword(data.Password); await repo.Account.AddAsync(account); await repo.SaveChangesAsync(); return(account); } }
public async Task SetMuteKeywordsAsync([FromBody] MuteKeyword keyword) { if (keyword == null) { ErrorCode.LackOfParameterError.Throw(); } using (var repo = MainRepository.WithReadAndWrite()) { var chara = await repo.Character.GetByIdAsync(this.AuthData.CharacterId).GetOrErrorAsync(ErrorCode.LoginCharacterNotFoundError); keyword.CharacterId = this.AuthData.CharacterId; var old = await repo.Mute.GetCharacterKeywordAsync(chara.Id); if (old.HasData) { old.Data.Keywords = keyword.Keywords; } else { await repo.Mute.AddAsync(keyword); } await repo.SaveChangesAsync(); } await StatusStreaming.Default.SendCharacterAsync(ApiData.From(keyword), keyword.CharacterId); }
public override async Task ExecuteAsync(MainRepository repo, Character character, IEnumerable <CharacterCommandParameter> options, CommandSystemData game) { if (character.CountryId == 0) { await game.CharacterLogAsync($"国庫に金を納入しようとしましたが、無所属は実行できません"); return; } var countryOptional = await repo.Country.GetByIdAsync(character.CountryId); if (!countryOptional.HasData) { await game.CharacterLogAsync($"ID: <num>{character.CountryId}</num> の国は存在しません。<emerge>管理者にお問い合わせください</emerge>"); return; } var country = countryOptional.Data; if (country.HasOverthrown) { await game.CharacterLogAsync($"国庫に金を納入しようとしましたが、あなたの所属国 <country>{country.Name}</country> はすでに滅亡しています"); return; } var policies = await repo.Country.GetPoliciesAsync(country.Id); var max = 1000_0000; // CountryService.GetCountrySafeMax(policies.Where(p => p.Status == CountryPolicyStatus.Available).Select(p => p.Type)); var money = options.FirstOrDefault(o => o.Type == 1)?.NumberValue ?? 0; if (money > character.Money) { await game.CharacterLogAsync($"国庫に金 <num>{money}</num> を納入しようとしましたが、所持金が足りません"); return; } if (country.SafeMoney + money > max) { money = max - country.SafeMoney; if (money < 0) { // 支配とか災害とかで上限が下がることがある money = 0; } } country.SafeMoney += money; character.Money -= money; character.Contribution += 30; character.SkillPoint++; await game.CharacterLogAsync($"国庫に金 <num>{money}</num> を納入しました"); await StatusStreaming.Default.SendCountryAsync(ApiData.From(country), country.Id); return; }
public void RemoveProjectRoleState_Succeeds() { var projectGuid = Guid.NewGuid(); const string projectName = "Cool Project"; var roleGuid = Guid.NewGuid(); const string roleName = "Tester"; var inMemoryDatabaseBuilder = new InMemoryDatabaseBuilder(); var options = inMemoryDatabaseBuilder .WithProjectState(projectGuid, projectName) .WithProjectRoleState(roleGuid, roleName, projectGuid) .Build("GetProjectState", true); // Run the test against a clean instance of the context using (var context = new MainContext(options)) { inMemoryDatabaseBuilder.InitializeContext(context); var sut = new MainRepository(context); sut.RemoveRoleFromProjectState(projectGuid, roleGuid); var projectState = sut.GetProjectState(projectGuid); var roleState = projectState.ProjectRoleStates.SingleOrDefault(w => w.Guid == roleGuid); //Assert.Null(roleState); inconsistent testbehavior vs CompanyRole roleState = context.ProjectRoleStates.Find(roleGuid); Assert.Equal(EntityState.Deleted, context.Entry(roleState).State); Assert.Equal(roleName, roleState.Name); } }
/// <summary> /// ログイン処理を行い、アクセストークンを新たに発行する /// </summary> /// <param name="aliasId">ID</param> /// <param name="password">パスワード</param> /// <returns>認証結果</returns> private static async Task <AuthenticationData> LoginAsync(MainRepository repo, string aliasId, string password) { if (string.IsNullOrEmpty(aliasId) || string.IsNullOrEmpty(password)) { ErrorCode.LoginParameterMissingError.Throw(); } var chara = (await repo.Character.GetByAliasIdAsync(aliasId)) .GetOrError(ErrorCode.LoginCharacterNotFoundError); if (chara.HasRemoved || !chara.TryLogin(password)) { ErrorCode.LoginParameterIncorrectError.Throw(); } var data = new AuthenticationData { AccessToken = GenerateAccessToken(aliasId, password), CharacterId = chara.Id, ExpirationTime = DateTime.Now.AddDays(100), Scope = Scope.All, }; await repo.AuthenticationData.AddAsync(data); return(data); }
public ActionResult Add(AddOrEditTodoViewModel model) { if (ModelState.IsValid) { var category = CurrentUser.Categories.First(cat => cat.CategoryId == Int32.Parse(model.CategoryId)); var endDate = DateTime.Now.AddDays(1); if (model.EndDate.HasValue) { endDate = model.EndDate.GetValueOrDefault(); } MainRepository.AddTodo(category, new Todo() { ShortDescription = model.ShortDescription, Description = model.Description, StartDate = model.StartDate, EndDate = endDate, IsDone = model.IsDone, Priority = Int32.Parse(model.Priotiry) }); return(RedirectToAction("Index")); } model.Categories = GetCategories(); model.Priorities = GetPriorities(); return(View(model)); }
public ActionResult Edit(AddOrEditTodoViewModel viewModel) { if (ModelState.IsValid) { var todo = CurrentUser.Categories.First(x => x.CategoryId == Int32.Parse(viewModel.CategoryId)) .Todos.First(t => t.TodoId == viewModel.TodoId); var newTodo = new Todo() { TodoId = todo.TodoId, ShortDescription = viewModel.ShortDescription, Description = viewModel.Description, StartDate = viewModel.StartDate, IsDone = viewModel.IsDone, EndDate = viewModel.EndDate.Value, Category = CurrentUser.Categories.First(x => x.CategoryId == Int32.Parse(viewModel.CategoryId)), Priority = Int32.Parse(viewModel.Priotiry) }; MainRepository.UpdateTodo(CurrentUser, todo, newTodo); return(RedirectToAction("Index")); } viewModel.Categories = GetCategories(); viewModel.Priorities = GetPriorities(); return(View(viewModel)); }
public IRepository ConfigureRepository() { string folder = GetAppDataFolder(); if (!ConfigurationManager.AppSettings.AllKeys.Contains(RepositoryKey)) { Logger.Log.Info("Repository key error. Repository value set to FakeRepository"); } string repositoryName = ConfigurationManager.AppSettings.Get(RepositoryKey); IRepository repository = null; switch (repositoryName) { case "FakeRepository": repository = new FakeRepository(folder); break; case "MainRepository": string connectionString = GetConnectionString(); if (connectionString != null) { repository = new MainRepository(connectionString); } break; default: repository = new FakeRepository(folder); Logger.Log.Info("Created default FakeRepository"); break; } return(repository); }
public async Task RemoveUnitAsync( [FromRoute] uint id) { using (var repo = MainRepository.WithReadAndWrite()) { var member = await repo.Unit.GetByMemberIdAsync(this.AuthData.CharacterId); if (member.Unit.HasData && member.Member.HasData) { var unitMember = member.Member.Data; var unit = member.Unit.Data; if (unitMember.Post != UnitMemberPostType.Leader) { ErrorCode.NotPermissionError.Throw(); } if (unit.Id != id) { ErrorCode.NotPermissionError.Throw(); } } else { ErrorCode.UnitNotFoundError.Throw(); } await UnitService.RemoveAsync(repo, id); await repo.SaveChangesAsync(); } }
public void RemoveCompanyRoleState_Succeeds() { var companyGuid = Guid.NewGuid(); const string companyName = "Cool Company"; var roleGuid = Guid.NewGuid(); const string roleName = "Software Developer 2"; var inMemoryDatabaseBuilder = new InMemoryDatabaseBuilder(); var options = inMemoryDatabaseBuilder .WithCompanyState(companyGuid, companyName) .WithCompanyRoleState(roleGuid, roleName, companyGuid) .Build("GetCompanyState", true); // Run the test against a clean instance of the context using (var context = new MainContext(options)) { inMemoryDatabaseBuilder.InitializeContext(context); var sut = new MainRepository(context); sut.RemoveRoleFromCompanyState(companyGuid, roleGuid); var companyState = sut.GetCompanyState(companyGuid); var roleState = companyState.CompanyRoleStates.SingleOrDefault(w => w.Guid == roleGuid); roleState = context.CompanyRoleStates.Find(roleGuid); Assert.Equal(EntityState.Deleted, context.Entry(roleState).State); Assert.Equal(roleName, roleState.Name); } }
public static async Task <CharacterItem> DivideResourceAndSaveAsync(MainRepository repo, CharacterItem item, int resourceSize) { if (item.Resource <= resourceSize) { return(item); } item.Resource -= resourceSize; var newItem = new CharacterItem { Type = item.Type, Status = item.Status, CharacterId = item.CharacterId, TownId = item.TownId, IntLastStatusChangedGameDate = item.IntLastStatusChangedGameDate, Resource = resourceSize, }; await GenerateItemAndSaveAsync(repo, newItem); await StatusStreaming.Default.SendAllAsync(ApiData.From(newItem)); await StatusStreaming.Default.SendAllAsync(ApiData.From(item)); return(newItem); }
public void CreateCompanyState_Succeeds() { var options = new DbContextOptionsBuilder <MainContext>() .UseInMemoryDatabase(databaseName: "CreateCompanyState_adds_to_context") .Options; // Run the test against one instance of the context using (var context = new MainContext(options)) { var sut = new MainRepository(context); var guid = Guid.NewGuid(); var name = "new"; var state = sut.CreateCompanyState(guid, name); Assert.Equal(state, context.CompanyStates.Local.First()); sut.PersistChanges(); Assert.Equal(state, context.CompanyStates.First()); Assert.Equal(1, context.CompanyStates.Count()); Assert.Equal(guid, context.CompanyStates.First().Guid); } // Use a separate instance of the context to verify correct data was saved to database using (var context = new MainContext(options)) { Assert.Equal(1, context.CompanyStates.Count()); } }
/// <summary> /// Valida o login /// </summary> /// <param name="loginRequest"></param> /// <returns></returns> public LoginResponseModel ValidateLogin(LoginRequestModel loginRequest) { string msgErro = null; MainRepository repository = new MainRepository(); try { // Valida o parâmetro de entrada CheckLoginRequest(loginRequest); // Valida a conexão com o banco de dados repository.CheckDatabaseConnection(loginRequest); // Valida o Login CheckLogin(loginRequest, repository); } catch (Exception ex) { msgErro = ex.Message; } // Define o objeto login de resposta LoginResponseModel loginResponse = new LoginResponseModel(); loginResponse.Login = loginRequest?.Login; loginResponse.Password = loginRequest?.Password; loginResponse.Company = loginRequest?.Company; loginResponse.CredentialAccepted = String.IsNullOrEmpty(msgErro); loginResponse.ErrorMessage = msgErro; return(loginResponse); }
public ActionResult CreateProj() { var repo = new MainRepository(); var Main = repo.ProjCreateView(); return(View(Main)); }
public override async Task ExecuteAsync(MainRepository repo, Character character, IEnumerable <CharacterCommandParameter> options, CommandSystemData game) { var items = await repo.Character.GetItemsAsync(character.Id); var item = items.FirstOrDefault(i => i.Type == CharacterItemType.TimeChanger); if (item == null || item.Resource <= 0) { if (item != null) { await ItemService.SpendCharacterAsync(repo, item, character); } await game.CharacterLogAsync("静養しようとしましたが、コマンド実行に必要なアイテムを所持していません"); return; } var system = await repo.System.GetAsync(); var time = RandomService.Next(0, Config.UpdateTime * 100_000) / 100_000.0; character.LastUpdated = system.CurrentMonthStartDateTime.AddSeconds(time - Config.UpdateTime); item.Resource--; if (item.Resource <= 0) { await ItemService.SpendCharacterAsync(repo, item, character); } else { await StatusStreaming.Default.SendCharacterAsync(ApiData.From(item), character.Id); } await game.CharacterLogAsync($"更新時刻を月開始の <num>{(int)time}</num> 秒後に変更しました。アイテム残り: <num>{item.Resource}</num>"); }
public async Task DeleteCountryBbsAsync( [FromRoute] uint id) { ThreadBbsItem message; Character chara; using (var repo = MainRepository.WithReadAndWrite()) { chara = await repo.Character.GetByIdAsync(this.AuthData.CharacterId).GetOrErrorAsync(ErrorCode.LoginCharacterNotFoundError); var item = await repo.ThreadBbs.GetByIdAsync(id).GetOrErrorAsync(ErrorCode.NodeNotFoundError); if (item.CharacterId != chara.Id) { var posts = await repo.Country.GetCharacterPostsAsync(chara.Id); var characterPosts = posts.Select(p => p.Type); if (!characterPosts.Any(p => p == CountryPostType.Monarch || p == CountryPostType.Warrior)) { ErrorCode.NotPermissionError.Throw(); } } message = item; repo.ThreadBbs.Remove(item); await repo.SaveChangesAsync(); } message.IsRemove = true; await StatusStreaming.Default.SendCountryAsync(ApiData.From(message), chara.CountryId); }
private static async Task ResetTownsAndSaveAsync(MainRepository repo, GameRuleSet ruleSet) { var num = ruleSet == GameRuleSet.Wandering ? 1 : RandomService.Next(15, 16); var initialTowns = MapService.CreateMap(num); var towns = new List <Town>(); foreach (var itown in initialTowns) { var typeId = itown.Type; var town = MapService.CreateTown(typeId); town.Name = itown.Name; town.X = itown.X; town.Y = itown.Y; towns.Add(town); } await repo.Town.AddTownsAsync(towns); await repo.SaveChangesAsync(); if (ruleSet != GameRuleSet.Wandering) { await ItemService.InitializeItemOnTownsAsync(repo, towns); await repo.SaveChangesAsync(); } }
public MainBusiness() { _mainRep = new MainRepository(); }