Ejemplo n.º 1
0
        private void InstallSet(string fname, Octgn.Data.Game SelectedGame)
        {
            string shortName = Path.GetFileName(fname);

            UpdateStatus("Installing Set " + shortName);
            string path = Path.Combine(Prefs.DataDirectory, "Games", SelectedGame.Id.ToString(), "Sets");

            if (!Directory.Exists(path))
            {
                Directory.CreateDirectory(path);
            }



            try
            {
                if (shortName != null)
                {
                    string copyto = Path.Combine(path, shortName);
                    if (fname.ToLower() != copyto.ToLower())
                    {
                        File.Copy(fname, copyto, true);
                    }
                    SelectedGame.InstallSet(copyto);
                }
                UpdateStatus(string.Format("Set '{0}' installed.", shortName));
            }
            catch (Exception ex)
            {
                UpdateStatus(string.Format("'{0}' an error occured during installation:", shortName));
                UpdateStatus(ex.Message);
            }
        }
Ejemplo n.º 2
0
        public void Apply(GamesRepository repository, bool patchInstalledSets, string patchFolder)
        {
            if (!patchInstalledSets && patchFolder == null) return;

              using (var package = Package.Open(filename, FileMode.Open, FileAccess.Read))
              {
            ReadPackageDescription(package);

            // Get the list of sets to potentially patch
            game = repository.Games.FirstOrDefault(g => g.Id == gameId);
            var installedSets = game.Sets.Select(s => s.packageName).ToList();
            List<string> uninstalledSets;

            if (patchFolder != null)
            {
              string[] files = Directory.GetFiles(patchFolder, "*.o8s");
              uninstalledSets = files.Except(installedSets).ToList();
              if (!patchInstalledSets)
            installedSets = files.Intersect(installedSets).ToList();
            }
            else
              uninstalledSets = new List<string>(0);

            current = 0;
            max = installedSets.Count + uninstalledSets.Count;
            OnProgress();

            foreach (string set in installedSets)
              SafeApply(package, set, true);

            foreach (string set in uninstalledSets)
              SafeApply(package, set, false);
              }
        }
Ejemplo n.º 3
0
        public static Deck Load(string file, Game game)
        {
            if (game == null) throw new ArgumentNullException("game");

            Guid gameId;
            XDocument doc = LoadDoc(file, out gameId);
            if (gameId != game.Id) throw new WrongGameException(gameId, game.Id.ToString());

            return LoadCore(doc, game);
        }
Ejemplo n.º 4
0
 internal static MarkerModel FromDataRow(Game game, IVistaDBRow row)
 {
     var result = new MarkerModel
     {
         id = (Guid)row["id"].Value,
         name = (string)row["name"].Value,
         iconUri = (string)row["icon"].Value,
         set = game.GetSet((Guid)row["setId"].Value)
     };
     return result;
 }
        /// <summary>
        /// Matches the cards.
        /// </summary>
        /// <param name="octgnGame">The octgn game.</param>
        /// <param name="cardModels">The card models.</param>
        /// <param name="octgnCards">The octgn cards.</param>
        /// <param name="parsedCards">The parsed cards.</param>
        /// <returns>A collectoin of matched cards.</returns>
        /// <exception cref="System.InvalidOperationException">
        /// This exception will be thrown when cards cannot be matched.
        /// </exception>
        public static IEnumerable<Deck.Element> MatchCards(
            Game octgnGame,
            IEnumerable<CardModel> cardModels,
            IEnumerable<CardData> octgnCards,
            IEnumerable<CardData> parsedCards)
        {
            var result = new List<Deck.Element>();
            var errorCards = new StringBuilder();

            foreach (var parsedCard in parsedCards)
            {
                var trimmedName = parsedCard.Name.Trim();
                var found = octgnCards.FirstOrDefault(c => c.Name.Trim().Equals(trimmedName, StringComparison.OrdinalIgnoreCase));
                if (found == null)
                {
                    errorCards.AppendLine(parsedCard.Name);
                }
                else
                {
                    var card = cardModels.FirstOrDefault(c => c.Id.ToString().Equals(found.Id));
                    result.Add(new Deck.Element()
                    {
                        Card = card,
                        Quantity = (byte)parsedCard.Count,
                    });
                }
            }

            if (!string.IsNullOrEmpty(errorCards.ToString()))
            {
                var details = new InvalidOperationException(Localization.ErrorCannotFindCards + Environment.NewLine + errorCards.ToString());
                details.Data.Add("Cards", result);

                throw details;
            }

            return result;
        }
Ejemplo n.º 6
0
 internal static Set FromDataRow(Game game, IVistaDBRow row)
 {
     return new Set
     {
         Id = (Guid)row["id"].Value,
         Name = (string)row["name"].Value,
         Game = game,
         GameVersion = new Version((string)row["gameVersion"].Value),
     Version = new Version((string)row["version"].Value),
         PackageName = (string)row["package"].Value
     };
 }
Ejemplo n.º 7
0
        private Game ReadGameFromTable(IDataRecord read)
        {
            object temp = read["shared_deck_sections"];
            string sharedDeckSections;
            if (temp == DBNull.Value)
                sharedDeckSections = null;
            else
                sharedDeckSections = (string) read["shared_deck_sections"];

            var g = new Game
                        {
                            Id = Guid.Parse((string) read["id"]),
                            Name = (string) read["name"],
                            Version = new Version((string) read["version"]),
                            Filename = (string) read["filename"],
                            CardWidth = (int) ((long) read["card_width"]),
                            CardHeight = (int) ((long) read["card_height"]),
                            CardBack = (string) read["card_back"],
                            DeckSections = DeserializeList((string) read["deck_sections"]),
                            SharedDeckSections =
                                sharedDeckSections == null ? null : DeserializeList(sharedDeckSections),
                            Repository = this,
                            FileHash = read["file_hash"] == DBNull.Value ? "" : (string) read["file_hash"]
                        };

            return g;
        }
Ejemplo n.º 8
0
 public void UpdateGameHash(Game game, string hash)
 {
     try
     {
         using (var com = DatabaseConnection.CreateCommand())
         {
             com.CommandText = "UPDATE games SET file_hash=@file_hash WHERE id=@id";
             com.Parameters.AddWithValue("@file_hash", hash);
             com.Parameters.AddWithValue("@id", game.Id.ToString());
             com.ExecuteNonQuery();
         }
     }
     catch (Exception)
     {
         if(Debugger.IsAttached)Debugger.Break();
     }
 }
Ejemplo n.º 9
0
        public void InstallGame(Game game, IEnumerable<PropertyDef> properties)
        {
            SQLiteTransaction trans = null;
            try
            {
                var sb = new StringBuilder();
                trans = DatabaseConnection.BeginTransaction();
                using (SQLiteCommand com = DatabaseConnection.CreateCommand())
                {
                    //Build Query
                    sb.Append("INSERT OR REPLACE INTO [games](");
                    sb.Append(
                        "[id],[name],[filename],[version], [card_width],[card_height],[card_back],[deck_sections],[shared_deck_sections],[file_hash]");
                    sb.Append(") VALUES(");
                    sb.Append(
                        "@id,@name,@filename,@version,@card_width,@card_height,@card_back,@deck_sections,@shared_deck_sections,@file_hash");
                    sb.Append(");\n");
                    com.CommandText = sb.ToString();

                    com.Parameters.AddWithValue("@id", game.Id.ToString());
                    com.Parameters.AddWithValue("@name", game.Name);
                    com.Parameters.AddWithValue("@filename", game.Filename);
                    com.Parameters.AddWithValue("@version", game.Version.ToString());
                    com.Parameters.AddWithValue("@card_width", game.CardWidth);
                    com.Parameters.AddWithValue("@card_height", game.CardHeight);
                    com.Parameters.AddWithValue("@card_back", game.CardBack);
                    com.Parameters.AddWithValue("@deck_sections", SerializeList(game.DeckSections));
                    if (game.SharedDeckSections != null)
                        com.Parameters.AddWithValue("@shared_deck_sections", SerializeList(game.SharedDeckSections));
                    else
                        com.Parameters.AddWithValue("@shared_deck_sections", DBNull.Value);
                    com.Parameters.AddWithValue("@file_hash", game.FileHash);

                    com.ExecuteNonQuery();
                    if (!Directory.Exists(Path.Combine(BasePath, "Decks")))
                        Directory.CreateDirectory(Path.Combine(BasePath, "Decks"));

                    game.CopyDecks(game.Filename);
                }
                //Add custom properties for the card.
                sb = new StringBuilder();
                sb.Append("INSERT OR REPLACE INTO [custom_properties](");
                sb.Append("[id],[card_real_id],[game_id],[name], [type],[vint],[vstr]");
                sb.Append(") VALUES(");
                sb.Append(
                    "@id,(SELECT real_id FROM cards WHERE id = @card_id LIMIT 1),@game_id,@name,@type,@vint,@vstr");
                sb.Append(");\n");
                string command = sb.ToString();
                foreach (PropertyDef pair in properties)
                {
                    using (SQLiteCommand com = DatabaseConnection.CreateCommand())
                    {
                        com.CommandText = command;
                        com.Parameters.AddWithValue("@card_id", "");
                        com.Parameters.AddWithValue("@vint", 0);
                        com.Parameters.AddWithValue("@vstr", " ");
                        com.Parameters.AddWithValue("@id", pair.Name + game.Id);
                        com.Parameters.AddWithValue("@game_id", game.Id.ToString());
                        com.Parameters.AddWithValue("@name", pair.Name);
                        switch (pair.Type)
                        {
                            case PropertyType.String:
                                com.Parameters.AddWithValue("@type", 0);
                                break;
                            case PropertyType.Integer:
                                com.Parameters.AddWithValue("@type", 1);
                                break;
                            default:
                                com.Parameters.AddWithValue("@type", 2);
                                break;
                        }
                        com.ExecuteNonQuery();
                    }
                }
             /*           //special case of "Alternate" property - removing this operation will result in requiring the Game Def to have
                    //"Alternate" listed as a custom property in order to use it
                using (SQLiteCommand com = DatabaseConnection.CreateCommand())
                    {
                        com.CommandText = command;
                        com.Parameters.AddWithValue("@card_id", "");
                        com.Parameters.AddWithValue("@vint", 0);
                        com.Parameters.AddWithValue("@vstr", " ");
                        com.Parameters.AddWithValue("@id", "Alternate" + game.Id);
                        com.Parameters.AddWithValue("@game_id", game.Id.ToString());
                        com.Parameters.AddWithValue("@name", "Alternate");
                        com.Parameters.AddWithValue("@type", 0);
                        com.ExecuteNonQuery();
                    }
                using (SQLiteCommand com = DatabaseConnection.CreateCommand())
                {
                    com.CommandText = command;
                    com.Parameters.AddWithValue("@card_id", "");
                    com.Parameters.AddWithValue("@vint", 0);
                    com.Parameters.AddWithValue("@vstr", " ");
                    com.Parameters.AddWithValue("@id", "Dependent" + game.Id);
                    com.Parameters.AddWithValue("@game_id", game.Id.ToString());
                    com.Parameters.AddWithValue("@name", "Dependent");
                    com.Parameters.AddWithValue("@type", 0); //string
                    com.ExecuteNonQuery();
                }
               */     trans.Commit();
            }
            catch (Exception)
            {
                if (trans != null)
                    trans.Rollback();
                if (Debugger.IsAttached) Debugger.Break();
                return;
            }
            Game existingGame = _cachedGames.FirstOrDefault(g => g.Id == game.Id);
            if (existingGame != null) _cachedGames.Remove(existingGame);
            _cachedGames.Add(game);
            if (GameInstalled != null)
                GameInstalled.Invoke(game, new EventArgs());
        }
Ejemplo n.º 10
0
 public static void Open(GameDef game, bool readOnly)
 {
     OpenedGame = Program.GamesRepository.Games.First(g => g.Id == game.Id);
 }
Ejemplo n.º 11
0
        private static Deck LoadCore(XDocument doc, Game game)
        {
            Deck deck;
            try
            {
                var isShared = doc.Root.Attr<bool>("shared");
                IEnumerable<string> defSections = isShared ? game.SharedDeckSections : game.DeckSections;

                deck = new Deck {GameId = game.Id, IsShared = isShared};
                if (doc.Root != null)
                {
                    IEnumerable<Section> sections = from section in doc.Root.Elements("section")
                                                    let xAttribute = section.Attribute("name")
                                                    where xAttribute != null
                                                    select new Section(false)
                                                               {
                                                                   Name = xAttribute.Value,
                                                                   Cards = new ObservableCollection<Element>
                                                                       (from card in section.Elements("card")
                                                                        select new Element
                                                                                   {
                                                                                       LoadedId =
                                                                                           card.Attr<string>("id"),
                                                                                       LoadedName = card.Value,
                                                                                       Quantity =
                                                                                           card.Attr<byte>("qty", 1)
                                                                                   })
                                                               };
                    var allSections = new Section[defSections.Count()];
                    int i = 0;
                    foreach (string sectionName in defSections)
                    {
                        allSections[i] = sections.FirstOrDefault(x => x.Name == sectionName);
                        if (allSections[i] == null) allSections[i] = new Section {Name = sectionName};
                        ++i;
                    }
                    deck.Sections = allSections;
                }
            }
            catch
            {
                throw new InvalidFileFormatException();
            }

            // Matches with actual cards in database
            foreach (Element e in deck.Sections.SelectMany(s => s.Cards))
                try
                {
                    //TODO: This can be done better or in batch. Future implementation idea!
                    // First try by id, if one is provided
                    if (e.LoadedId != null) e.Card = game.GetCardById(new Guid(e.LoadedId));
                    // If there's no id, or if it doesn't match a card in the database, try to fallback on the name
                    if (e.Card == null) e.Card = game.GetCardByName(e.LoadedName);
                    // If we still can't find the card, report an error
                    if (e.Card == null)
                        throw new UnknownCardException(e.LoadedId, e.LoadedName);
                }
                catch (FormatException)
                {
                    throw new InvalidFileFormatException(string.Format("Could not parse card id {0}.",
                                                                       e.LoadedId));
                }
            return deck;
        }
Ejemplo n.º 12
0
 private bool CheckCompatibility(Game game, IEnumerable<PropertyDef> properties)
 {
     return properties.SequenceEqual(game.CustomProperties);
 }
Ejemplo n.º 13
0
        public void InstallGame(Game game, IEnumerable<PropertyDef> properties)
        {
            game.basePath = Path.Combine(BasePath, game.Id.ToString());
              game.repository = this;
              using (var dda = VistaDBEngine.Connections.OpenDDA())
              using (var masterDb = dda.OpenDatabase(masterDbPath, VistaDBDatabaseOpenMode.NonexclusiveReadWrite, null))
              using (var gamesTable = masterDb.OpenTable("Game", false, false))
              {
            masterDb.BeginTransaction();
            bool previousCompatibleVersion = false;
            try
            {
              if (!gamesTable.Find("id:'" + game.Id.ToString() + "'", "GamePK", false, false))
            gamesTable.Insert();
              else
            previousCompatibleVersion = CheckCompatibility(ReadGameFromTable(gamesTable), properties);
              gamesTable.PutGuid("id", game.Id);
              gamesTable.PutString("name", game.Name);
              gamesTable.PutString("version", game.Version.ToString());
              gamesTable.PutString("filename", game.Filename);
              gamesTable.PutInt32("cardWidth", game.CardWidth);
              gamesTable.PutInt32("cardHeight", game.CardHeight);
              gamesTable.PutString("cardBack", game.CardBack);
              gamesTable.PutString("deckSections", SerializeList(game.DeckSections));
              if (game.SharedDeckSections != null)
            gamesTable.PutString("sharedDeckSections", SerializeList(game.SharedDeckSections));
              gamesTable.Post();

              string gamePath = Path.Combine(BasePath, game.Id.ToString());
              Directory.CreateDirectory(Path.Combine(gamePath, "Decks"));
              //Directory.CreateDirectory(Path.Combine(gamePath, "Sets"));
              game.CopyDecks(game.Filename);
              if (!previousCompatibleVersion)
            CreateGameDatabase(dda, gamePath, properties);

              masterDb.CommitTransaction();
            }
            catch
            {
              masterDb.RollbackTransaction();
              throw;
            }
              }
              var existingGame = cachedGames.FirstOrDefault(g => g.Id == game.Id);
              if (existingGame != null) cachedGames.Remove(existingGame);
              cachedGames.Add(game);
            if(GameInstalled != null)
            GameInstalled.Invoke(game,new EventArgs());
        }
Ejemplo n.º 14
0
 public static void Open(Definitions.GameDef game, bool readOnly)
 {
     openedGame = Program.GamesRepository.Games.First(g => g.Id == game.Id);
     openedGame.OpenDatabase(readOnly);
 }
Ejemplo n.º 15
0
 public static void Open(GameDef game, bool readOnly)
 {
     OpenedGame = Program.GamesRepository.Games.First(g => g.Id == game.Id);
 }
Ejemplo n.º 16
0
 public void SetLoadedGame(Game game)
 {
     Game = game;
 }
Ejemplo n.º 17
0
 public Deck(Game game)
 {
     GameId = game.Id;
     Sections = game.DeckSections.Select(s => new Section {Name = s}).ToArray();
 }
Ejemplo n.º 18
0
        public void UninstallGame(Game game)
        {
            if (!_cachedGames.Any(g => g.Id == game.Id)) return;

            SQLiteTransaction trans = null;
            try
            {
                trans = DatabaseConnection.BeginTransaction();

                #region remove the custom properties from the database
                using (SQLiteCommand com = DatabaseConnection.CreateCommand())
                {
                    //Build Query
                    com.CommandText = @"DELETE FROM [custom_properties] WHERE [game_id]=@id;";
                    com.Parameters.AddWithValue("@id", game.Id.ToString());
                    com.ExecuteNonQuery();
                }
                #endregion

                #region remove the game from the database
                using (SQLiteCommand com = DatabaseConnection.CreateCommand())
                {
                    //Build Query
                    com.CommandText = @"DELETE FROM [games] WHERE [id]=@id;";
                    com.Parameters.AddWithValue("@id", game.Id.ToString());
                    com.ExecuteNonQuery();
                }
                #endregion

                //remove obsolete columns from the cards table
                DatabaseHandler.RebuildCardTable(DatabaseConnection);

                trans.Commit();
            }
            catch (Exception ex)
            {
                if (trans != null)
                    trans.Rollback();
                if (Debugger.IsAttached) Debugger.Break();
                return;
            }

            var existingGame = _cachedGames.FirstOrDefault(g => g.Id == game.Id);
            if (existingGame != null) _cachedGames.Remove(existingGame);
        }
Ejemplo n.º 19
0
 public void SetLoadedGame(Game game)
 {
     this.LoadedGame = game;
 }
Ejemplo n.º 20
0
        public void UpdateGameDefinition(Game game, IEnumerable<PropertyDef> properties)
        {
            StringBuilder sb = new StringBuilder();
            using (SQLiteCommand com = DatabaseConnection.CreateCommand())
            {
                //Build Query
                sb.Append("UPDATE [games] SET ");
                sb.Append("[filename]=@filename, [version]=@version, ");
                sb.Append("[card_width]=@card_width, [card_height]=@card_height, [card_back]=@card_back, ");
                sb.Append("[deck_sections]=@deck_sections, [shared_deck_sections]=@shared_deck_sections, [file_hash]=@file_hash");
                sb.Append(" WHERE [id]=@id;");
                com.CommandText = sb.ToString();

                com.Parameters.AddWithValue("@id", game.Id.ToString());
                com.Parameters.AddWithValue("@filename", game.Filename);
                com.Parameters.AddWithValue("@version", game.Version.ToString());
                com.Parameters.AddWithValue("@card_width", game.CardWidth);
                com.Parameters.AddWithValue("@card_height", game.CardHeight);
                com.Parameters.AddWithValue("@card_back", game.CardBack);
                com.Parameters.AddWithValue("@deck_sections", SerializeList(game.DeckSections));
                if (game.SharedDeckSections != null)
                    com.Parameters.AddWithValue("@shared_deck_sections", SerializeList(game.SharedDeckSections));
                else
                    com.Parameters.AddWithValue("@shared_deck_sections", DBNull.Value);
                com.Parameters.AddWithValue("@file_hash", game.FileHash);

                com.ExecuteNonQuery();

                com.CommandText = "DELETE FROM [custom_properties] WHERE [game_id]=@game_id";
                com.Parameters.AddWithValue("@game_id", game.Id.ToString());
                com.ExecuteNonQuery();
            }
        }
Ejemplo n.º 21
0
        public void BeginHostGame(Game game, string gamename)
        {
            var data = String.Format("{0},:,{1},:,{2}",game.Id.ToString(),game.Version.ToString(),gamename);
			var m = new Message(new Jid("gameserv@" + Host), Me.User, MessageType.normal, data, "hostgame");
            m.GenerateId();
            Xmpp.Send(m);
        }
Ejemplo n.º 22
0
        private static Deck LoadCore(XDocument doc, Game game)
        {
            Deck deck;
            try
            {
            var isShared = doc.Root.Attr<bool>("shared");
            var defSections = isShared ? game.SharedDeckSections : game.DeckSections;

            deck = new Deck { GameId = game.Id, IsShared = isShared };
                var sections = from section in doc.Root.Elements("section")
                                             select new Section(false)
                                             {
                                                 Name = section.Attribute("name").Value,
                                                 Cards = new ObservableCollection<Element>
                                                                 (from card in section.Elements("card")
                                                                    select new Element
                                                                    {
                                                                        loadedId = card.Attr<string>("id"),
                                                                        loadedName = card.Value,
                                                                        Quantity = card.Attr<byte>("qty", 1)
                                                                    })
                                             };
                Section[] allSections = new Section[defSections.Count()];
                int i = 0;
                foreach (string sectionName in defSections)
                {
                    allSections[i] = sections.FirstOrDefault(x => x.Name == sectionName);
                    if (allSections[i] == null) allSections[i] = new Section { Name = sectionName };
                    ++i;
                }
                deck.Sections = allSections;
            }
            catch
            { throw new InvalidFileFormatException(); }

            bool isDbClosed = !game.IsDatabaseOpen;
            try
            {
                if (isDbClosed)
                    game.OpenDatabase(true);
                // Matches with actual cards in database
                foreach (Section s in deck.Sections)
                    foreach (Element e in s.Cards)
                        try
                        {
                            // First try by id, if one is provided
                            if (e.loadedId != null) e.Card = game.GetCardById(new Guid(e.loadedId));
                            // If there's no id, or if it doesn't match a card in the database, try to fallback on the name
                            if (e.Card == null) e.Card = game.GetCardByName(e.loadedName);
                            // If we still can't find the card, report an error
                            if (e.Card == null)
                                throw new UnknownCardException(e.loadedId, e.loadedName);
                        }
                        catch (FormatException)
                        { throw new InvalidFileFormatException(string.Format("Could not parse card id {0}.", e.loadedId)); }
            }
            finally
            {
                if (isDbClosed)
                    game.CloseDatabase();
            }

            return deck;
        }