Пример #1
0
        public async Task <RpsData <bool> > UseGoods(ParamUseGoods param)
        {
            var userGood =
                await _context.UserGoods.SingleAsync(x => x.UserId == param.Id && x.GoodsType == param.Type && x.GoodsType != MallGoodsTypeEnum.金币);

            if (userGood.Num > 0)
            {
                userGood.Num -= 1;
                _context.GoodsUseHistories.Add(new GoodsUseHistory()
                {
                    CreateDateTime = DateTime.Now,
                    GoodsType      = userGood.GoodsType,
                    Num            = 1,
                    UserId         = userGood.UserId
                });
                var result = await _context.SaveChangesAsync() > 0;

                if (result)
                {
                    return(RpsData <bool> .Ok(true));
                }
                else
                {
                    return(RpsData <bool> .Error("保存出错"));
                }
            }
            return(RpsData <bool> .Error("数量不足,请先购买"));
        }
        public async Task <IActionResult> PutGame(int id, Game game)
        {
            if (id != game.ID)
            {
                return(BadRequest());
            }

            _context.Entry(game).State = EntityState.Modified;

            try
            {
                await _context.SaveChangesAsync();
            }
            catch (DbUpdateConcurrencyException)
            {
                if (!GameExists(id))
                {
                    return(NotFound());
                }
                else
                {
                    throw;
                }
            }

            return(NoContent());
        }
Пример #3
0
        public async Task <IHttpActionResult> UpdateGame(long id, Game game)
        {
            if (!ModelState.IsValid)
            {
                return(BadRequest(ModelState));
            }

            // Validate IDs are the same
            if (id != game.Id)
            {
                return(BadRequest());
            }

            db.Entry(game).State = EntityState.Modified;

            try
            {
                // Save the changes
                await db.SaveChangesAsync();
            }
            catch (DbUpdateConcurrencyException)
            {
                if (!GameExists(id))
                {
                    return(NotFound());
                }
                else
                {
                    throw;
                }
            }

            return(StatusCode(HttpStatusCode.NoContent));
        }
Пример #4
0
        public async Task <Player> CreatePlayer(Player player)
        {
            _Context.Players.Add(player);
            await _Context.SaveChangesAsync();

            return(player);
        }
Пример #5
0
        public async Task <Game> CreateGame(Game game)
        {
            _Context.Games.Add(game);
            await _Context.SaveChangesAsync();

            return(game);
        }
Пример #6
0
        private async Task OnEnterRole(ForwardMailMessage forwardMail, Func <MailboxMessage, Task> replyMailAction)
        {
            if (forwardMail.Id == (int)GameDBProto.MessageId.EnterRoleRequestId)
            {
                var request = GameDBProto.EnterRoleRequest.Parser.ParseFrom(forwardMail.Content);
                var role    = await _context.GameRole.AsNoTracking().FirstOrDefaultAsync(r => r.UserId == request.UserId);

                if (role == null)
                {
                    var r = _context.GameRole.Add(new GameRole {
                        UserId = request.UserId, NickName = request.NickName
                    });
                    await _context.SaveChangesAsync();

                    role = r.Entity;
                }

                var reply = new GameDBProto.EnterRoleReply {
                    Result = new GameDBProto.ReplayResult {
                        ErrorCode = 1
                    }, RoleId = role.RoleId, NickName = role.NickName
                };
                await replyMailAction(new MailboxMessage { Id      = (int)GameDBProto.MessageId.EnterRoleReplyId, Content = reply.ToByteString(),
                                                           Reserve = forwardMail.Reserve, UserId = forwardMail.UserId, ClientId = forwardMail.ClientId });
            }
        }
Пример #7
0
        public async Task <IActionResult> PutGame([FromRoute] Guid id, [FromBody] Data.Models.Game game)
        {
            if (!ModelState.IsValid)
            {
                return(BadRequest(ModelState));
            }

            if (id != game.Id)
            {
                return(BadRequest());
            }

            _context.Entry(game).State = EntityState.Modified;

            try
            {
                await _context.SaveChangesAsync();
            }
            catch (DbUpdateConcurrencyException)
            {
                if (!GameExists(id))
                {
                    return(NotFound());
                }
                else
                {
                    throw;
                }
            }

            return(NoContent());
        }
Пример #8
0
        public async Task <T> Add <T>(T entity) where T : BaseEntity
        {
            GameDbContext.Set <T>().Add(entity);
            await GameDbContext.SaveChangesAsync();

            return(entity);
        }
Пример #9
0
        private async Task <GameSession> StopGameHandler(GameRoom room, GamerAccount callerAccount)
        {
            var session =
                await _dataContext.GameSessions.FirstOrDefaultAsync(s =>
                                                                    s.RoomId == room.Id && s.State != GameSessionStates.GameOver);

            if (session == null)
            {
                throw new Exception("Игры нет, сначала создай ее, а потом закрывай)");
            }

            if (session.State == GameSessionStates.Playing)
            {
                throw new Exception("Нельзя так! Народ играет!");
            }

            if (session.CreatedByGamerAccountId != callerAccount.Id)
            {
                throw new Exception("Игру может удалить только ее создатель!");
            }

            _dataContext.Remove(session);
            await _dataContext.SaveChangesAsync();

            return(session);
        }
Пример #10
0
        public async Task <IHttpActionResult> UpdatePlayer(long id, Player player)
        {
            if (!ModelState.IsValid)
            {
                return(BadRequest(ModelState));
            }

            // Make sure the IDs match
            if (id != player.Id)
            {
                return(BadRequest());
            }

            db.Entry(player).State = EntityState.Modified;

            try
            {
                // Save the changes
                await db.SaveChangesAsync();
            }
            catch (DbUpdateConcurrencyException)
            {
                if (!PlayerExists(id))
                {
                    return(NotFound());
                }
                else
                {
                    throw;
                }
            }

            return(StatusCode(HttpStatusCode.NoContent));
        }
        public async Task <IActionResult> Post([FromBody] Player player)
        {
            if (await _dBContext.Players.FirstOrDefaultAsync(p => p.Email == player.Email) != null)
            {
                var errors = new Dictionary <string, string[]>
                {
                    { "Email", new string[] { $"Duplicated email ${player.Email}" } }
                };

                var valResult = new ValidationProblemDetails(errors);

                var jsonRes = Json(valResult);
                jsonRes.StatusCode = 400;
                return(jsonRes);
            }

            var hash = new Guid().ToString();

            player.Identity = new PlayerIdentity()
            {
                Hash     = hash,
                Password = Encryption.EncryptPassword(player.Email, hash)
            };

            var result = await _dBContext.Players.AddAsync(player);

            player = result.Entity;


            await _dBContext.SaveChangesAsync();

            return(Json(player));
        }
Пример #12
0
        public async Task <IActionResult> Create(Game game)
        {
            if (ModelState.IsValid)
            {
                _context.Add(game);
                await _context.SaveChangesAsync();

                return(RedirectToAction(nameof(Index)));
            }

            return(View(game));
        }
Пример #13
0
        public async Task <T> UpdateAsync(T entity, int key)
        {
            if (entity == null)
            {
                return(null);
            }
            var exist = await _context.Set <T>().FindAsync(key);

            if (exist != null)
            {
                _context.Entry(exist).CurrentValues.SetValues(entity);
                await _context.SaveChangesAsync();
            }
            return(exist);
        }
Пример #14
0
        // MAPS

        public async Task <IMap> NewMapAsync(IGame game, IMap map)
        {
            var gridMap = (GridMap)map;
            var dbMap   = new DbMap()
            {
                RecordBy    = "notlinktoausercontextyet",
                RecordDate  = DateTimeOffset.Now,
                Name        = map.Name,
                Description = map.Description,
                LocationX   = gridMap.Location.X,
                LocationY   = gridMap.Location.Y,
                LocationZ   = gridMap.Location.Z,
                Exits       = gridMap.Exits.Distinct().Select(exit => new DbMapExit()
                {
                    Direction = (byte)exit
                }).ToList()
            };

            using (var context = new GameDbContext())
            {
                var savedMap = await context.AddAsync(dbMap);

                await context.SaveChangesAsync();

                return(savedMap.Entity.ToMap());
            }
        }
Пример #15
0
        public async Task <ActionResult> CreateBuilding(long Id, long BuildingId)
        {
            Planet planet = await(db.Planets.FindAsync(Id));

            try
            {
                if (ModelState.IsValid)
                {
                    Unit building = new Unit()
                    {
                        PlanetId       = planet.Id,
                        UnitTemplateId = db.UnitTemplates.FirstOrDefault(u => u.Id == BuildingId).Id,
                    };

                    db.Units.Add(building);
                    await db.SaveChangesAsync();
                }
            }
            catch (DataException)
            {
                ModelState.AddModelError("", "Unable to save changes. Try again, and if the problem persists see your system administrator.");
            }

            return(RedirectToAction("Details", new { planet.Id }));
        }
Пример #16
0
        public async Task <Game> CreateGameWithPlayer(string playerSessionId)
        {
            var game = new Game
            {
                Id      = Guid.NewGuid(),
                Player1 = new GameSession
                {
                    Id = playerSessionId
                }
            };

            _gameDbContext.Games.Add(game);
            await _gameDbContext.SaveChangesAsync();

            return(game);
        }
Пример #17
0
        public async Task UpdateSpawnersAsync(IGame game, IEnumerable <ISpawner> spawners)
        {
            var toGet = spawners.Select(item => item.Id).ToList();

            using (var context = new GameDbContext())
            {
                var dbSpawners = await context.Spawners.Where(s => toGet.Contains(s.Id)).ToListAsync();

                if (dbSpawners.Count == 0)
                {
                    return;
                }

                foreach (GridSpawner spawner in spawners)
                {
                    var dbSpawner = dbSpawners.FirstOrDefault(s => s.Id == spawner.Id);
                    if (dbSpawner == null)
                    {
                        continue;
                    }
                    // should we save as new here? .. right now i wont so the current world can hold temporary spawners from events etc etc.
                    dbSpawner.Delay        = spawner.ResetDuration;
                    dbSpawner.MapId        = spawner.MapId;
                    dbSpawner.EntityId     = spawner.Id;
                    dbSpawner.ModifiedBy   = "nousercontextyet";
                    dbSpawner.ModifiedDate = DateTime.Now;
                    dbSpawner.SpawnType    = (byte)spawner.SpawnType;

                    context.Spawners.Update(dbSpawner);
                }
                await context.SaveChangesAsync();
            }
        }
Пример #18
0
        // ITEMS
        public async Task <IItem> NewItemAsync(IGame game, IItem item)
        {
            // use some sort of mapper? to clean this up?
            var gridItem = (GridItem)item;
            var dbItem   = new DbItem()
            {
                RecordBy    = "notlinktoausercontextyet",
                RecordDate  = DateTimeOffset.Now,
                Name        = item.Name,
                Description = item.Description,
                ItemTypes   = gridItem.ItemTypes.Select(it => new DbItemTypes()
                {
                    ItemType = it
                }).ToList()
            };

            using (var context = new GameDbContext())
            {
                var trackedItem = await context.Items.AddAsync(dbItem);

                await context.SaveChangesAsync();

                return(trackedItem.Entity.ToItem());
            }
        }
Пример #19
0
        public override async Task <IdentityResult> UpdateAsync(UserModel user)
        {
            using (var dbContext = new GameDbContext(_dbContextOptions))
            {
                var current = await dbContext.Set <UserModel>().FirstOrDefaultAsync(x => x.Id == user.Id);

                current.AccessFailedCount     = user.AccessFailedCount;
                current.ConcurrencyStamp      = user.ConcurrencyStamp;
                current.Email                 = user.Email;
                current.EmailConfirmationDate = user.EmailConfirmationDate;
                current.EmailConfirmed        = user.EmailConfirmed;
                current.FirstName             = user.FirstName;
                current.LastName              = user.LastName;
                current.LockoutEnabled        = user.LockoutEnabled;
                current.NormalizedEmail       = user.NormalizedEmail;
                current.NormalizedUserName    = user.NormalizedUserName;
                current.PhoneNumber           = user.PhoneNumber;
                current.PhoneNumberConfirmed  = user.PhoneNumberConfirmed;
                current.Score                 = user.Score;
                current.SecurityStamp         = user.SecurityStamp;
                current.TwoFactorEnabled      = user.TwoFactorEnabled;
                current.UserName              = user.UserName;
                await dbContext.SaveChangesAsync();

                return(IdentityResult.Success);
            }
        }
Пример #20
0
        private async void btn_Add_Click(object sender, EventArgs e)
        {
            try
            {
                db = new GameDbContext();
                DbContextTransaction transaction = db.Database.BeginTransaction();
                try
                {
                    Team team = new Team
                    {
                        EstablishmentDate = dtp_estabdate.Value,
                        Name = txbx_name.Text,
                        Logo = (byte[])new ImageConverter().ConvertTo(pictureBox1.Image, typeof(byte[]))
                    };
                    db.Teams.Add(team);
                    await db.SaveChangesAsync();

                    if (selectedPlayersId.Count >= 11)
                    {
                        foreach (int item in selectedPlayersId)
                        {
                            Player selectedPlayer = await db.Players.GetUserByIdAsync(item);

                            selectedPlayer.Id = team.Id;
                        }
                        await db.SaveChangesAsync();
                    }
                    else
                    {
                        MessageBox.Show("You must select 11 players");
                    }


                    transaction.Commit();
                }
                catch (Exception)
                {
                    transaction.Rollback();
                }
            }

            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
        }
Пример #21
0
 public async Task UpdateUser(UserModel userModel)
 {
     using (var gameDbContext = new GameDbContext(_dbContextOptions))
     {
         gameDbContext.Update(userModel);
         await gameDbContext.SaveChangesAsync();
     }
 }
Пример #22
0
        public async Task <bool> Add(ItemModel item)
        {
            var oItem = await _dbContext.Items.FirstOrDefaultAsync(i => i.Id.Equals(item.Id)) ?? await _dbContext.Items.FirstOrDefaultAsync(i => i.Name.Equals(item.Name) && i.Game.Name.Equals(item.Game.Name));

            if (oItem != null && oItem.UserId.Equals(item.UserId) && oItem.Game.Name.Equals(item.Game.Name))
            {
                oItem.Name        = item.Name;
                oItem.Description = item.Description;
                oItem.Category    = item.Category;
                oItem.Behaviour   = item.Behaviour;

                await _dbContext.SaveChangesAsync();

                return(true);
            }

            if (oItem != null)
            {
                return(false);
            }

            var game = await _dbContext.Games.FirstOrDefaultAsync(g => g.Id.Equals(item.Game.Id)) ?? await _dbContext.Games.FirstOrDefaultAsync(g => g.Name.Equals(item.Game.Name));

            if (game == null)
            {
                return(false);
            }

            item.Game = game;

            if (game.Items == null)
            {
                game.Items = new List <ItemModel>();
            }

            if (!game.Items.Contains(item))
            {
                game.Items.Add(item);
            }

            _dbContext.Items.Add(item);
            await _dbContext.SaveChangesAsync();

            return(true);
        }
Пример #23
0
        private async void btn_register_Click(object sender, EventArgs e)
        {
            RegisterModel model = new RegisterModel
            {
                Name            = txbx_name.Text,
                Surname         = txbx_surname.Text,
                BirthDate       = dtp_datebirth.Value,
                Password        = txbx_pwd.Text,
                ConfirmPassword = txbx_cpwd.Text,
                Email           = txbx_email.Text,
                RoleId          = 2
            };
            Tuple <bool, List <ValidationResult> > results = this.CustomValidator(model);

            if (results.Item1)
            {
                try
                {
                    Player user = model;
                    db = new GameDbContext();
                    Player findedUser = await db.Players.GetUserByEmailAsync(user.Email);

                    if (findedUser != null)
                    {
                        MessageBox.Show("There is profile with this email");
                    }
                    else
                    {
                        db.Players.Add(user);
                        await db.SaveChangesAsync();
                    }
                }
                catch (SqlException ex)
                {
                    MessageBox.Show("Database Error :" + " " + ex.Message);
                }
                catch (Exception ex)
                {
                    MessageBox.Show(ex.Message);
                }
                finally
                {
                    if (db != null)
                    {
                        db.Dispose();
                    }
                }
            }
            else
            {
                lbl_errors.Text = "";
                foreach (ValidationResult item in results.Item2)
                {
                    lbl_errors.Text = item.ErrorMessage + "\n";
                }
            }
        }
        //public Task<bool> RegisterUser(UserModel userModel)
        //{
        //    _userStore.Add(userModel);
        //    return Task.FromResult(true);
        //}
        public async Task <bool> RegisterUser(UserModel userModel)
        {
            using (var db = new GameDbContext(_dbContextOptions))
            {
                db.UserModels.Add(userModel);
                await db.SaveChangesAsync();

                return(true);
            }
        }
Пример #25
0
        public static async Task <GameUser> AddNewUser(GameUser newUser)
        {
            await using var dbContext = new GameDbContext();
            dbContext.Add(newUser);
            await dbContext.SaveChangesAsync().ConfigureAwait(false);

            await dbContext.GameUsers.ToListAsync().ConfigureAwait(false);

            return(newUser);
        }
Пример #26
0
        public async Task <bool> AddGameAppAsync(GameApp gameApp)
        {
            if (await GameAppExistsAsync(gameApp.AppId))
            {
                return(false);
            }

            dbContext.Add(gameApp);

            return(await dbContext.SaveChangesAsync() > 0);
        }
        public async Task <IActionResult> Create([FromForm] Comment comment)
        {
            if (ModelState.IsValid)
            {
                _context.Add(comment);
                await _context.SaveChangesAsync();

                return(Ok("Created"));
            }

            return(new BadRequestResult());
        }
Пример #28
0
        public async Task DeleteMapsAsync(IGame game, IEnumerable <IMap> maps)
        {
            var ids = maps.Select(m => m.Id).ToList();

            using (var context = new GameDbContext())
            {
                var dbMaps = await context.Maps.Where(m => ids.Contains(m.Id)).ToListAsync();

                context.Maps.RemoveRange(dbMaps);
                await context.SaveChangesAsync();
            }
        }
Пример #29
0
        public async Task OnPlayerDisconnectedAsync(string gameId, string playerId)
        {
            var lockSecret = Guid.NewGuid().ToString();

            try
            {
                if (!await AcquireGameLock(gameId, lockSecret, TimeSpan.FromSeconds(30)))
                {
                    return;
                }

                var gameState = await _dbContext.GameStates
                                .FirstOrDefaultAsync(x => x.GameId == gameId);

                if (gameState != null)
                {
                    var playerState = gameState.PlayerStates
                                      .FirstOrDefault(x => x.PlayerId == playerId);
                    if (playerState != null)
                    {
                        playerState.CurrentAsk   = null;
                        playerState.CurrentBid   = null;
                        gameState.BestCurrentAsk = gameState.PlayerStates.Select(x => x.CurrentAsk).Min();
                        gameState.BestCurrentBid = gameState.PlayerStates.Select(x => x.CurrentBid).Max();
                        playerState.IsConnected  = false;
                        await _dbContext.SaveChangesAsync();

                        InvokeOnGameUpdate(MakeGameUpdateResponse(gameState));
                    }
                }
            }
            finally
            {
                ReleaseGameLock(gameId, lockSecret);
            }
        }
Пример #30
0
        public async Task UpdateMapsAsync(IGame game, IEnumerable <IMap> maps)
        {
            var toGet = maps.Select(item => item.Id).ToList();

            using (var context = new GameDbContext())
            {
                var dbMaps = await context.Maps.Include(m => m.Exits).Where(i => toGet.Contains(i.Id)).ToListAsync();

                if (dbMaps.Count == 0)
                {
                    return;
                }

                foreach (var map in maps)
                {
                    var dbMap = dbMaps.FirstOrDefault(m => m.Id == map.Id);
                    if (dbMap == null)
                    {
                        continue;
                    }

                    // workaround ..moving on its not important now
                    // i know this is not needed but it was appending to the database instead of clearing and then adding.
                    if (dbMap.Exits.Any())
                    {
                        dbMap.Exits.Clear();
                        dbMap = context.Maps.Update(dbMap).Entity;
                    }

                    var gridMap = (GridMap)map;
                    dbMap.Name         = gridMap.Name;
                    dbMap.Description  = gridMap.Description;
                    dbMap.LocationX    = gridMap.Location.X;
                    dbMap.LocationY    = gridMap.Location.Y;
                    dbMap.LocationZ    = gridMap.Location.Z;
                    dbMap.ModifiedBy   = "nousercontextyet";
                    dbMap.ModifiedDate = DateTime.Now;
                    dbMap.Exits        = gridMap.Exits.Distinct().Select(exit => new DbMapExit()
                    {
                        Direction = (byte)exit
                    }).ToList();

                    context.Maps.Update(dbMap);
                }
                await context.SaveChangesAsync();
            }
        }