private void AddStructures(DbGame game, DbTurn turn, JArray structures, DbRegion region, Dictionary <string, string> structuresMemory, Dictionary <int, string> unitMemory, Dictionary <int, string> orders)
        {
            int structureOrder = 0;

            foreach (JObject structure in structures)
            {
                var str = structure["structure"] as JObject;
                var s   = new DbStructure {
                    GameId   = game.Id,
                    TurnId   = turn.Id,
                    Sequence = structureOrder,
                    Number   = str.Value <int>("number"),
                    Type     = str.Value <string>("type"),
                    Name     = str.Value <string>("name"),
                    Units    = new List <DbUnit>(),
                    Json     = str.ToString()
                };

                var emphId = DbStructure.GetEmpheralId(region.X, region.Y, region.Z, s.Number, s.Type);
                s.Memory = structuresMemory.TryGetValue(emphId, out var structMem)
                    ? structMem
                    : null;

                var units = structure["units"] as JArray;
                if (units != null)
                {
                    AddUnits(game, turn, units, region, s, unitMemory, orders);
                }

                region.Structures.Add(s);
                turn.Structures.Add(s);

                structureOrder++;
            }
        }
        private static Tuple <string, string> RefreshThumb(DbGame game)
        {
            lock (Lock)
            {
                var uri = new Uri(game.ThumbImageUrl);

                var filename = $"/Images/Thumb/{Path.GetFileName(uri.LocalPath)}";

                string contentType;
                byte[] data;

                using (var wc = new WebClient())
                {
                    wc.Headers.Add("user-agent", "MTXZoneThumbCacher/1.0");
                    data        = wc.DownloadData(game.ThumbImageUrl);
                    contentType = wc.ResponseHeaders["Content-Type"];
                }

                if (!new[] { "image/png", "image/jpeg" }.Contains(contentType))
                {
                    return(null);
                }

                var path = $"{HostingEnvironment.ApplicationPhysicalPath}{filename.Substring(1).Replace("/", @"\")}";
                File.WriteAllBytes(path, data);

                DbAccess.SaveThumb(game.Id, filename, contentType);

                return(new Tuple <string, string>(filename, contentType));
            }
        }
        /// <summary>
        /// Creates a DbGame object for insertion into the database.
        /// Should only be used for games that are not already in the Db,
        /// as otherwise, their ratings will be reset.
        /// </summary>
        /// <param name="input"></param>
        /// <returns></returns>
        public static DbGame CreateDbGameObjectWithoutNavigation(Game input)
        {
            var retval = new DbGame
            {
                Id              = input.Id,
                Name            = input.Name,
                Summary         = input.Deck,
                LastUpdated     = DateTime.UtcNow,
                SmallImageUrl   = input.Image.SmallUrl,
                ThumbImageUrl   = input.Image.ThumbUrl,
                GbSiteDetailUrl = input.SiteDetailUrl,
                Aliases         = input.Aliases
            };

            var nameCharArray = input.Name.ToCharArray();

            if (nameCharArray.Any(x => char.IsSymbol(x) || char.IsPunctuation(x)))
            {
                var strippedName = new string(nameCharArray.Where(x => !char.IsSymbol(x) && !char.IsPunctuation(x)).ToArray());

                if (!retval.Aliases?.Contains(strippedName) ?? false)
                {
                    if (string.IsNullOrEmpty(retval.Aliases))
                    {
                        retval.Aliases = strippedName;
                    }
                    else
                    {
                        retval.Aliases += $"{Environment.NewLine}{strippedName}";
                    }
                }
            }

            if (input.OriginalReleaseDate.HasValue)
            {
                retval.ReleaseDate = input.OriginalReleaseDate.Value.Date;
            }
            else if (input.ExpectedReleaseYear.HasValue)
            {
                var releaseDate = DateTime.MinValue;

                releaseDate = releaseDate.AddYears(input.ExpectedReleaseYear.Value - 1);

                if (input.ExpectedReleaseQuarter.HasValue && !input.ExpectedReleaseMonth.HasValue)
                {
                    releaseDate = releaseDate.AddMonths((input.ExpectedReleaseQuarter.Value * 3) - 1);
                }
                else
                {
                    releaseDate = releaseDate.AddMonths((input.ExpectedReleaseMonth ?? 1) - 1);
                }

                releaseDate = releaseDate.AddDays((input.ExpectedReleaseDay ?? 1) - 1);

                retval.ReleaseDate = releaseDate;
            }

            return(retval);
        }
예제 #4
0
        public override void Save(Game entity)
        {
            var dbGame = DbGame.FromDomainModel(entity);

            _unitOfWork.Store(dbGame, tran => GameDatabase.Temp(tran).GamesTable);
            foreach (var dbPlayer in entity.Players.Select(p => DbPlayer.FromDomainModel(p, entity.Id)))
            {
                _unitOfWork.Store(dbPlayer, tran => GameDatabase.Temp(tran).PlayersTable);
            }
        }
        private void GameListView_ItemClick(object sender, AdapterView.ItemClickEventArgs e)
        {
            GameListAdapter ad   = gameListView.Adapter as GameListAdapter;
            DbGame          game = ad.GetItem(e.Position);

            MainViewModel.Instance.CurrentGame = game;
            Intent intent = new Intent(this, typeof(GameStatisticsActivity));

            StartActivity(intent);
        }
예제 #6
0
        public void CreateGame(Player plr, MyDbContext ctx, string gameLog)
        {
            var user      = ctx.Users.FirstOrDefault(u => u.UserId == plr.UserId);
            var gameToAdd = new DbGame {
                User = user, GameTime = DateTime.Now, GameMoves = gameLog
            };

            ctx.Games.Add(gameToAdd);
            ctx.SaveChanges();
        }
예제 #7
0
 public GameDetailsPage(DbGame dbGame)
 {
     InitializeComponent();
     BindingContext    = dbGame;
     AddItem.Text      = "";
     AddItem.IsEnabled = false;
     startbt.IsVisible = true;
     this.dbGame       = dbGame;
     _ = StartDbGame();
 }
예제 #8
0
        public async Task <DbGame> DeleteGameAsync(DbGame game)
        {
            if (ReferenceEquals(game, null))
            {
                throw new ArgumentNullException(nameof(game));
            }

            var deletedItem = _context.Games.Remove(game);
            await _context.SaveChangesAsync().ConfigureAwait(false);

            return(deletedItem);
        }
예제 #9
0
        public async Task <DbGame> UpdateGameAsync(DbGame game)
        {
            if (ReferenceEquals(game, null))
            {
                throw new ArgumentNullException(nameof(game));
            }

            var updateItem = await GetGameByIdAsync(game.Id).ConfigureAwait(false);

            _context.Entry(updateItem).CurrentValues.SetValues(game);
            await _context.SaveChangesAsync().ConfigureAwait(false);

            return(updateItem);
        }
예제 #10
0
        public void CreateGame(string opponent, DateTime date, bool isHome)
        {
            DbGame game = new DbGame
            {
                Id       = Guid.NewGuid(),
                Opponent = opponent,
                TeamId   = MainViewModel.Instance.Team.Id,
                IsHome   = isHome,
                Status   = "H1",
                Date     = date
            };

            myGameDbManager.AddGame(game);
            GetGames();
        }
예제 #11
0
        protected override void OnAppearing()
        {
            base.OnAppearing();

            BindingContext = App.DbGame;
            dbGame         = App.DbGame;
            dbAthlete      = App.DbAthlete;

            Title = dbAthlete.Name;

            _ = BackgroundAsync();

            if (isGameRunning)
            {
                btn_isRunning.Text = "Pause";
            }
            else
            {
                btn_isRunning.Text = "Resume";
            }
        }
        private static void AddUnits(DbGame game, DbTurn turn, JArray units, DbRegion region, DbStructure structure, Dictionary <int, string> unitMemory, Dictionary <int, string> orders)
        {
            int unitOrder = 0;

            foreach (JObject unit in units)
            {
                var unitFaction = unit["faction"] as JObject;
                var u           = new DbUnit
                {
                    GameId        = game.Id,
                    TurnId        = turn.Id,
                    Number        = unit.Value <int>("number"),
                    Name          = unit.Value <string>("name"),
                    FactionNumber = unitFaction != null
                        ? unitFaction.Value <int>("number")
                        : (int?)null,
                    Sequence = unitOrder
                };

                u.Own    = game.PlayerFactionNumber == u.FactionNumber;
                u.Memory = u.Own && unitMemory.TryGetValue(u.Number, out var unitMem)
                    ? unitMem
                    : null;
                u.Orders = orders.TryGetValue(u.Number, out var unitOrders)
                    ? unitOrders
                    : null;

                unit["own"] = u.Own;    // because could be loaded several reports from different factions
                u.Json      = unit.ToString();

                region.Units.Add(u);
                turn.Units.Add(u);
                if (structure != null)
                {
                    structure.Units.Add(u);
                }

                unitOrder++;
            }
        }
예제 #13
0
        public static void SaveGame(DbGame input)
        {
            lock (Lock)
            {
                using (var ctx = new DIHMTEntities())
                {
                    var existingRecord = ctx.DbGames.FirstOrDefault(x => x.Id == input.Id);

                    if (existingRecord != null)
                    {
                        ctx.Entry(existingRecord).CurrentValues.SetValues(input);
                        ctx.Entry(existingRecord).State = EntityState.Modified;
                    }
                    else
                    {
                        ctx.DbGames.Add(input);
                    }

                    ctx.SaveChanges();
                }
            }
        }
예제 #14
0
        private void ExecuteAddGame(DbGame game)
        {
            string query = CreateInsertStatement(game, "Game");

            ExecuteSingleQuery(query);
        }
예제 #15
0
 public void AddGame(DbGame game)
 {
     RemoteConsumer.AddAction(() => ExecuteAddGame(game));
 }
        private void ExecuteInsertGameData(DbGame game)
        {
            game.IsSynchronised = true;
            LocalConnection.Update(game);

            Guid gameId = game.Id;

            List <DbAttackGoal>    goals    = new List <DbAttackGoal>();
            List <DbAttack>        attacks  = new List <DbAttack>();
            List <DbAttackRebound> rebounds = new List <DbAttackRebound>();
            List <DbAttackShot>    shots    = new List <DbAttackShot>();

            MySqlCommand     remoteCommand = new MySqlCommand();
            MySqlTransaction transaction   = RemoteConnection.BeginTransaction();

            remoteCommand.Transaction = transaction;
            try {
                var           localAttacks = LocalConnection;
                string        query        = "SELECT * FROM Attack WHERE GameId = ?";
                SQLiteCommand command      = LocalConnection.CreateCommand(query, gameId);
                attacks = command.ExecuteQuery <DbAttack>();

                string getGoalsQuery = "SELECT ag.* FROM Attack a" +
                                       " JOIN AttackGoal ag" +
                                       " on a.GoalId = ag.Id" +
                                       " WHERE a.GameId = ? AND a.IsSynchronised = 0";
                command = LocalConnection.CreateCommand(getGoalsQuery, gameId);
                goals   = command.ExecuteQuery <DbAttackGoal>();

                string insertGoalsQuery = CreateInsertStatement(goals, "Attack_Goal");

                string insertAttacksQuery = CreateInsertStatement(attacks, "Attack");


                string localShotsQuery = "SELECT ash.* FROM Attack a" +
                                         " join AttackShot ash" +
                                         " on a.Id = ash.AttackId" +
                                         " WHERE a.GameId = ? AND a.IsSynchronised = 0";

                command = LocalConnection.CreateCommand(localShotsQuery, gameId);
                shots   = command.ExecuteQuery <DbAttackShot>();
                string insertShotsQuery = CreateInsertStatement(shots, "Attack_Shot");

                string localReboundsQuery = "SELECT ash.* FROM Attack a" +
                                            " join AttackShot ash " +
                                            " on a.Id = ash.AttackId" +
                                            " WHERE a.GameId = ? AND a.IsSynchronised = 0";

                command  = LocalConnection.CreateCommand(localReboundsQuery, gameId);
                rebounds = command.ExecuteQuery <DbAttackRebound>();
                string insertReboundsQuery = CreateInsertStatement(rebounds, "Attack_Rebound");

                remoteCommand.Connection = RemoteConnection;

                remoteCommand.CommandText = insertGoalsQuery;
                remoteCommand.ExecuteNonQuery();

                remoteCommand.CommandText = insertAttacksQuery;
                remoteCommand.ExecuteNonQuery();

                remoteCommand.CommandText = insertReboundsQuery;
                remoteCommand.ExecuteNonQuery();

                remoteCommand.CommandText = insertShotsQuery;
                remoteCommand.ExecuteNonQuery();

                transaction.Commit();

                goals.ForEach(g => g.IsSynchronised    = true);
                attacks.ForEach(a => a.IsSynchronised  = true);
                rebounds.ForEach(r => r.IsSynchronised = true);
                shots.ForEach(s => s.IsSynchronised    = true);

                LocalConnection.UpdateAll(goals);
                LocalConnection.UpdateAll(attacks);
                LocalConnection.UpdateAll(rebounds);
                LocalConnection.UpdateAll(shots);
            } catch (Exception e)
            {
                transaction.Rollback();
                throw new Exception(e.Message);
            }
        }
        private static void CopyInvisibleRegions(long gameId, DbTurn turn, DbTurn lastTurn, DbGame game)
        {
            var visibleRegions = turn.Regions.ToDictionary(k => k.EmpheralId);
            var allRegions     = lastTurn.Regions.ToDictionary(k => k.EmpheralId);

            foreach (var key in allRegions.Keys.Except(visibleRegions.Keys))
            {
                var invisibleRegion = allRegions[key];
                var regCopy         = new DbRegion
                {
                    GameId        = gameId,
                    TurnId        = turn.Id,
                    UpdatedAtTurn = invisibleRegion.UpdatedAtTurn,
                    X             = invisibleRegion.X,
                    Y             = invisibleRegion.Y,
                    Z             = invisibleRegion.Z,
                    Label         = invisibleRegion.Label,
                    Province      = invisibleRegion.Province,
                    Terrain       = invisibleRegion.Terrain,
                    Structures    = new List <DbStructure>(),
                    Units         = new List <DbUnit>(),
                    Json          = invisibleRegion.Json,
                    Memory        = invisibleRegion.Memory
                };

                if (invisibleRegion.Structures != null)
                {
                    foreach (var str in invisibleRegion.Structures)
                    {
                        var strCopy = new DbStructure
                        {
                            GameId   = game.Id,
                            TurnId   = turn.Id,
                            Sequence = str.Sequence,
                            Number   = str.Number,
                            Type     = str.Type,
                            Name     = str.Name,
                            Units    = new List <DbUnit>(),
                            Json     = str.Json
                        };

                        regCopy.Structures.Add(strCopy);
                        turn.Structures.Add(strCopy);
                    }
                }

                turn.Regions.Add(regCopy);
            }
        }
 public void InsertGameData(DbGame game)
 {
     RemoteConsumer.AddAction(() => ExecuteInsertGameData(game));
 }
예제 #19
0
 public DbGameWithClub(DbGame dbGame)
 {
     DbGame        = dbGame;
     DbClubHome    = new DbClub();
     DbClubVisitor = new DbClub();
 }