public void UpdateEdition(IEdition iedition, string sourceName, string name, bool hasFoil, string code, int?idBlock, int?blockPosition, int?cardNumber, DateTime?releaseDate)
        {
            using (new WriterLock(_lock))
            {
                if (iedition is not Edition edition || string.IsNullOrWhiteSpace(sourceName) || string.IsNullOrWhiteSpace(name))
                {
                    return;
                }

                name       = name.Trim();
                sourceName = sourceName.Trim();

                if (_editions.FirstOrDefault(e => edition.Id != e.Id && string.Compare(e.GathererName, sourceName, StringComparison.InvariantCultureIgnoreCase) == 0) != null)
                {
                    return;
                }

                //No need to update referencial because instance is still the same
                edition.Name          = name;
                edition.GathererName  = sourceName;
                edition.HasFoil       = hasFoil;
                edition.Code          = code;
                edition.IdBlock       = idBlock;
                edition.BlockPosition = idBlock.HasValue ? blockPosition : null;
                edition.CardNumber    = cardNumber;
                edition.ReleaseDate   = releaseDate;

                using (IDbConnection cnx = _databaseConnection.GetMagicConnection())
                {
                    Mapper <Edition> .UpdateOne(cnx, edition);
                }
            }
        }
Esempio n. 2
0
        protected override string ToLine(IImportExportCardCount cardCount)
        {
            //Ignore AltArt
            if (cardCount == null || (cardCount.FoilNumber == 0 && cardCount.Number == 0))
            {
                return(null);
            }

            ICard    card    = MagicDatabase.GetCard(cardCount.IdGatherer);
            IEdition edition = MagicDatabase.GetEdition(cardCount.IdGatherer);

            if (card == null || edition == null)
            {
                throw new ImportExportException("Can't find card with IdGatherer={0}", cardCount.IdGatherer);
            }

            string ret = string.Empty;

            if (cardCount.Number > 0)
            {
                ret += string.Format("{0}#{1}#{2}#False\n", card, edition.AlternativeCode(Format), cardCount.Number);
            }

            if (cardCount.FoilNumber > 0)
            {
                ret += string.Format("{0}#{1}#{2}#True\n", card, edition.AlternativeCode(Format), cardCount.FoilNumber);
            }

            return(ret);
        }
        public void InsertNewEdition(string sourceName, string name, bool hasFoil, string code, int?idBlock, int?blockPosition, int?cardNumber, DateTime?releaseDate, byte[] icon)
        {
            using (new WriterLock(_lock))
            {
                IEdition edition = GetEdition(sourceName);
                if (edition == null)
                {
                    Edition realEdition = new Edition
                    {
                        Name          = name,
                        GathererName  = sourceName,
                        Completed     = false,
                        HasFoil       = hasFoil,
                        Code          = code,
                        IdBlock       = idBlock,
                        BlockPosition = idBlock.HasValue ? blockPosition : null,
                        CardNumber    = cardNumber,
                        ReleaseDate   = releaseDate
                    };
                    if (realEdition.IdBlock.HasValue)
                    {
                        realEdition.Block = _blocks.GetOrDefault(realEdition.IdBlock.Value);
                    }

                    AddToDbAndUpdateReferential(realEdition, InsertInReferential);
                }
                InsertNewTreePicture(name, icon);
            }
        }
Esempio n. 4
0
        private bool CheckEdition(ICardAllDbInfo cai)
        {
            if (ExcludeFunEditions)
            {
                if (_magicDatabase.GetEdition(cai.IdGatherer).IdBlock == _idBlockFun)
                {
                    return(false);
                }
            }
            if (ExcludeOnlineOnlyEditions)
            {
                if (_magicDatabase.GetEdition(cai.IdGatherer).IdBlock == _idBlockOnlineOnly)
                {
                    return(false);
                }
            }

            if (EditionsSelected.Count == 0)
            {
                return(true);
            }

            IEdition edition = _magicDatabase.GetEdition(cai.IdGatherer);

            return(EditionsSelected.Contains(edition));
        }
Esempio n. 5
0
        private void RefreshDisplayedData(bool full)
        {
            IEdition editionSelected = EditionSelected;

            if (full)
            {
                foreach (CardCollectionInputGraphicViewModel c in _cards)
                {
                    c.PropertyChanged -= ItemChanged;
                }
                _cards.Clear();
            }

            if (editionSelected == null)
            {
                return;
            }

            List <CardCollectionInputGraphicViewModel> toSort = new List <CardCollectionInputGraphicViewModel>();

            if (full)
            {
                foreach (ICardAllDbInfo cardInfo in _allCardInfos.Where(cadi => cadi.Edition == editionSelected))
                {
                    CardCollectionInputGraphicViewModel newCard = new CardCollectionInputGraphicViewModel(new CardViewModel(cardInfo));
                    newCard.PropertyChanged += ItemChanged;
                    toSort.Add(newCard);
                }
            }
            else
            {
                toSort.AddRange(_cards);
                _cards.Clear();
            }

            foreach (CardCollectionInputGraphicViewModel ccigvm in toSort)
            {
                CardViewModel card = ccigvm.Card;
                _allCardTranslation.TryGetValue(card.Card, out string name);
                int count = 0;

                foreach (ICardInCollectionCount cardInCollectionCount in _magicDatabase.GetCollectionStatisticsForCard(CardCollection, card.Card)
                         .Where(cicc => cicc.IdLanguage == InputLanguage.Id && _magicDatabase.GetEdition(cicc.IdGatherer).Id == editionSelected.Id))
                {
                    if (AltArt)
                    {
                        count += Foil ? cardInCollectionCount.FoilAltArtNumber : cardInCollectionCount.AltArtNumber;
                    }
                    else
                    {
                        count += Foil ? cardInCollectionCount.FoilNumber : cardInCollectionCount.Number;
                    }
                }
                ccigvm.SetInfo(name, count);
            }

            toSort.Sort(CardCollectionInputGraphicViewModel.GetComparer(DisplayOrder));
            _cards.AddRange(toSort);
        }
 /// <summary>
 /// События при загрузке формы
 /// </summary>
 /// <param name="sender"></param>
 /// <param name="e"></param>
 private void AddingEditionForm_Load(object sender, EventArgs e)
 {
     SelectEdition.SelectedIndex   = 0;
     UniversityTextBox.Enabled     = false;
     SpecialityCodeTextBox.Enabled = false;
     SpecialityTextBox.Enabled     = false;
     _edition = new Book();
 }
Esempio n. 7
0
        public EditionInfoViewModel(string baseEditionUrl, EditionInfoWithBlock editionInfoWithBlock)
        {
            _edition = editionInfoWithBlock.Edition;

            string seachUrl = WebAccess.ToAbsoluteUrl(baseEditionUrl, editionInfoWithBlock.BaseSearchUrl, true);

            Url = string.Format("{0}?output=checklist&action=advanced&special=true&set=[\"{1}\"]", seachUrl, editionInfoWithBlock.Edition.GathererName);
            DownloadReporter = new DownloadReporterViewModel();
        }
Esempio n. 8
0
        protected override IImportExportCardCount ParseLine(string line)
        {
            Match m = _regLine.Match(line);

            if (!m.Success)
            {
                return(new ErrorImportExportCardInfo(line, "Can't parse line"));
            }

            int count     = 0;
            int foilCount = 0;

            if (!int.TryParse(m.Groups["Count"].Value, out int tmpcount) || tmpcount <= 0)
            {
                return(new ErrorImportExportCardInfo(line, "Invalid value for count"));
            }

            if (m.Groups["Foil"].Value.ToUpper() == "TRUE")
            {
                foilCount = tmpcount;
            }
            else
            {
                count = tmpcount;
            }


            ICard card = MagicDatabase.GetCard(m.Groups["Name"].Value, null);

            if (card == null)
            {
                return(new ErrorImportExportCardInfo(line, string.Format("Can't find card named {0}", m.Groups["Name"].Value)));
            }

            IEdition edition = MagicDatabase.GetEditionFromCode(m.Groups["Edition"].Value);

            if (edition == null)
            {
                return(new ErrorImportExportCardInfo(line, string.Format("Can't find edition named {0}", m.Groups["Edition"].Value)));
            }

            int idGatherer = MagicDatabase.GetIdGatherer(card, edition);

            if (idGatherer == 0)
            {
                return(new ErrorImportExportCardInfo(line, string.Format("Can't find gatherer id for card {0} edition {1}", card, edition)));
            }

            CardCount cardCount = new CardCount
            {
                { CardCountKeys.Standard, count },
                { CardCountKeys.Foil, foilCount }
            };

            return(new ImportExportCardInfo(idGatherer, cardCount, 0));
        }
Esempio n. 9
0
        /// <summary>
        /// Метод добавляющий новое издание в список
        /// </summary>
        /// <param name="edition">Новое издание</param>
        internal void AddEdition(IEdition edition)
        {
            editions.Add(edition);
            gridEditions.Rows.Clear();
            editions.ForEach(x =>
                             gridEditions.Rows.Add(x.StandartName));

            gridEditions.Update();
            gridEditions.Refresh();

            SetButtonsEnable();
        }
        public PreconstructedDeckViewModel(IPreconstructedDeck preconstructedDeck, IEdition edition, IEnumerable <KeyValuePair <CardViewModel, int> > cards)
        {
            PreconstructedDeck = preconstructedDeck;
            Name     = preconstructedDeck.Name;
            _edition = edition;
            IDictionary <CardViewModel, int> temp = new Dictionary <CardViewModel, int>();

            foreach (KeyValuePair <CardViewModel, int> kv in cards)
            {
                temp.Add(kv);
            }
            Composition = new ReadOnlyDictionary <CardViewModel, int>(temp);
        }
Esempio n. 11
0
 //Insert one new
 public void InsertNewEdition(string sourceName)
 {
     using (new WriterLock(_lock))
     {
         IEdition edition = GetEdition(sourceName);
         if (edition == null)
         {
             Edition realEdition = new Edition {
                 Name = sourceName, GathererName = sourceName, Completed = false, HasFoil = true
             };
             AddToDbAndUpdateReferential(realEdition, InsertInReferential);
         }
     }
 }
Esempio n. 12
0
        public int GetIdGatherer(ICard card, IEdition edition)
        {
            if (card == null || edition == null)
            {
                return(0);
            }

            CheckReferentialLoaded();
            using (new ReaderLock(_lock))
            {
                ICardEdition cardEdition = _cardEditions.Values.FirstOrDefault(ce => ce.IdCard == card.Id && ce.IdEdition == edition.Id);
                return(cardEdition == null ? 0 : cardEdition.IdGatherer);
            }
        }
Esempio n. 13
0
 public PriceViewModel(IPrice price, IEdition edition)
 {
     AddDate = price.AddDate;
     if (Enum.TryParse(price.Source, out PriceValueSource source))
     {
         Source = source;
     }
     else
     {
         Source = PriceValueSource.Unknown;
     }
     Foil        = price.Foil;
     Value       = price.Value;
     EditionName = edition.Name;
 }
Esempio n. 14
0
        public IEnumerable <EditionInfoWithBlock> GetEditionList(string url)
        {
            string htmltext = _webAccess.GetHtml(url);

            foreach (EditionInfo editionInfo in Parser.ParseEditionsList(htmltext))
            {
                IEdition edition = MagicDatabase.GetEdition(editionInfo.Name);
                if (edition == null)
                {
                    OnNewEditionCreated(editionInfo.Name);
                    edition = MagicDatabase.GetEdition(editionInfo.Name);
                }
                yield return(new EditionInfoWithBlock(editionInfo, edition));
            }
        }
Esempio n. 15
0
        private void InitWindow()
        {
            switch (InputMode)
            {
            case InputMode.ByCard:
            {
                Cards.Clear();
                Cards.AddRange(_allCardSorted.Keys);

                Editions.Clear();
                EditionSelected  = null;
                CardSelectedName = null;
                break;
            }

            case InputMode.ByEdition:
            {
                Cards.Clear();

                IEdition save = EditionSelected;
                Editions.Clear();
                Editions.AddRange(_allEditions);

                CardSelectedName = null;
                EditionSelected  = save;
                break;
            }

            case InputMode.None:

                Cards.Clear();
                Editions.Clear();
                EditionSelected  = null;
                CardSelectedName = null;
                break;
            }

            Languages.Clear();
            CurrentCollectionDetail = null;
            LanguageSelected        = null;
            Count    = _defaultQuantity;
            IsFoil   = false;
            IsAltArt = false;
            ResetFocus();
        }
Esempio n. 16
0
        public void ChangeCardEditionFoilAltArtLanguage(ICardCollection collection, ICard card, int countToChange, IEdition editionSource, ICardCountKey cardCountKeySource, ILanguage languageSource,
                                                        IEdition editionDestination, ICardCountKey cardCountKeyDestination, ILanguage languageDestination)
        {
            if (countToChange <= 0)
            {
                return;
            }

            using (new WriterLock(_lock))
            {
                if (languageSource == null || languageDestination == null || cardCountKeySource == null || cardCountKeyDestination == null)
                {
                    return;
                }

                int idGathererSource      = GetIdGatherer(card, editionSource);
                int idGathererDestination = GetIdGatherer(card, editionDestination);
                ICardInCollectionCount cardInCollectionCount = GetCardCollection(collection, idGathererSource, languageSource.Id);

                if (cardInCollectionCount == null || idGathererDestination == 0)
                {
                    return;
                }

                if (cardInCollectionCount.GetCount(cardCountKeySource) < countToChange)
                {
                    return;
                }

                CardCount cardCountSource = new CardCount
                {
                    { cardCountKeySource, -countToChange }
                };

                CardCount cardCountDestination = new CardCount
                {
                    { cardCountKeyDestination, countToChange }
                };

                InsertOrUpdateCardInCollection(collection.Id, idGathererSource, languageSource.Id, cardCountSource);
                InsertOrUpdateCardInCollection(collection.Id, idGathererDestination, languageDestination.Id, cardCountDestination);
            }
        }
        private IEdition GetEdition(string deckName, Match m)
        {
            string cardEdition = m.Groups["edition"].Value.TrimEnd();

            IEdition edition = MagicDatabase.GetEditionFromCode(cardEdition);

            if (edition == null)
            {
                //Special case for guild pack
                string cardEdition2 = cardEdition + "_" + deckName;
                if (cardEdition2.Length > 10)
                {
                    cardEdition2 = cardEdition2.Substring(0, 10);
                }
                edition = MagicDatabase.GetEditionFromCode(cardEdition2);
            }

            return(edition);
        }
Esempio n. 18
0
        private IEnumerable <AuditInfo> GetAudit()
        {
            foreach (IAudit audit in _allAudit.Where(a => a.OperationDate >= MinDate && a.OperationDate < MaxDate.AddDays(1)))
            {
                AuditInfo info = new AuditInfo
                {
                    Quantity      = audit.Quantity,
                    OperationDate = audit.OperationDate.ToLocalTime().ToString("G"),
                    IsFoil        = audit.IsFoil.HasValue && audit.IsFoil.Value,
                    IsAltArt      = audit.IsAltArt.HasValue && audit.IsAltArt.Value,
                };

                ICardCollection cardCollection = _magicDatabase.GetCollection(audit.IdCollection);
                info.CollectionName = cardCollection == null ? "(Deleted) " + audit.IdCollection : cardCollection.Name;

                if (audit.IdGatherer.HasValue)
                {
                    ICard card = _magicDatabase.GetCard(audit.IdGatherer.Value);
                    if (card == null)
                    {
                        info.CardName    = "(Not found) " + audit.IdGatherer.Value;
                        info.EditionName = "(Not found) " + audit.IdGatherer.Value;
                    }
                    else
                    {
                        info.CardName = card.Name;
                        IEdition edition = _magicDatabase.GetEdition(audit.IdGatherer.Value);
                        info.EditionName = edition == null ? "(Not found) " + audit.IdGatherer.Value : edition.Name;
                    }
                    if (audit.IdLanguage.HasValue)
                    {
                        ILanguage language = _magicDatabase.GetLanguage(audit.IdLanguage.Value);
                        info.Language = language == null ? "(Not found) " + audit.IdLanguage.Value : language.Name;
                    }
                    else
                    {
                        info.Language = "(Missing language)";
                    }
                }

                yield return(info);
            }
        }
Esempio n. 19
0
        private CardViewModel(ICardAllDbInfo cardAllDbInfo, bool otherPart)
        {
            CardAllDbInfo = cardAllDbInfo;
            Card          = otherPart ? cardAllDbInfo.CardPart2 : cardAllDbInfo.Card;
            IEdition edition = cardAllDbInfo.Edition;

            Statistics           = cardAllDbInfo.Statistics.Select(s => new StatisticViewModel(s)).ToArray();
            Prices               = cardAllDbInfo.Prices.Select(p => new PriceViewModel(p, edition)).ToArray();
            IsDownSide           = false;
            Edition              = edition;
            Rarity               = cardAllDbInfo.Rarity;
            IdGatherer           = otherPart ? cardAllDbInfo.IdGathererPart2 : cardAllDbInfo.IdGatherer;
            VariationIdGatherers = otherPart ? cardAllDbInfo.VariationIdGatherers2.ToArray() : cardAllDbInfo.VariationIdGatherers.ToArray();
            IsMultiPart          = MultiPartCardManager.Instance.HasMultiPart(Card);
            Is90DegreeSide       = MultiPartCardManager.Instance.Is90DegreeSide(Card);
            if (!string.IsNullOrWhiteSpace(Card.Power) && !string.IsNullOrWhiteSpace(Card.Toughness))
            {
                PowerToughnessLoyalty     = string.Format("{0}/{1}", Card.Power, Card.Toughness);
                PowerToughnessLoyaltyText = "Power/Toughness";
            }
            else if (!string.IsNullOrWhiteSpace(Card.Loyalty))
            {
                PowerToughnessLoyalty     = Card.Loyalty;
                PowerToughnessLoyaltyText = "Loyalty";
            }

            if (!string.IsNullOrWhiteSpace(CastingCost))
            {
                DisplayedCastingCost = CastingCost.Split(new[] { ' ' }, StringSplitOptions.RemoveEmptyEntries);
            }

            if (IsMultiPart && !otherPart)
            {
                OtherCardPart = new CardViewModel(cardAllDbInfo, true);
                if (MultiPartCardManager.Instance.IsDownSide(cardAllDbInfo.CardPart2))
                {
                    OtherCardPart.IsDownSide = true;
                }
            }
        }
Esempio n. 20
0
        public int InsertNewCardEditionWithFakeGathererId(int idEdition, int idCard, int idRarity, string url)
        {
            using (new WriterLock(_lock))
            {
                IEdition edition = _editions.FirstOrDefault(e => e.Id == idEdition);
                IRarity  rarity  = _rarities.Values.FirstOrDefault(r => r.Id == idRarity);
                ICard    card    = _cardsbyId.GetOrDefault(idCard);

                if (rarity == null || card == null || edition == null)
                {
                    throw new ApplicationDbException("Data are not filled correctedly");
                }
                if (!edition.IsNoneGatherer())
                {
                    throw new ApplicationDbException("InsertNewCardEditionWithFakeGathererId could only used for NoneGatherer edition");
                }
                int existingIdGatherer = GetIdGatherer(card, edition);
                if (existingIdGatherer != 0)
                {
                    // could have been inserted by another thread
                    return(existingIdGatherer);
                }

                int idGatherer = GetNextFakeGathererId();

                CardEdition cardEdition = new CardEdition
                {
                    IdCard     = idCard,
                    IdGatherer = idGatherer,
                    IdEdition  = idEdition,
                    IdRarity   = idRarity,
                    Url        = url
                };

                AddToDbAndUpdateReferential(cardEdition, InsertInReferential);

                return(idGatherer);
            }
        }
        /// <summary>
        /// События при изменении желаемого для ввода издания
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void SelectEdition_SelectedIndexChanged(object sender, EventArgs e)
        {
            switch (SelectEdition.SelectedIndex)
            {
            case 0:
            {
                DoVisibleField(true, false, false,
                               false, true, true,
                               true, true, true, true);
                _edition = new Book();
                break;
            }

            case 1:
            {
                DoVisibleField(true, true, false, false, false, false,
                               false, false, false, false);
                _edition = new CollectedPaper();
                break;
            }

            case 2:
            {
                DoVisibleField(false, true, true, true, false, false,
                               true, true, false, false);
                _edition = new Dissertation();
                break;
            }

            case 3:
            {
                DoVisibleField(true, false, false, false, false, false,
                               false, false, false, false);
                _edition = new Journal();
                break;
            }
            }
        }
Esempio n. 22
0
        private IList <PreconstructedDeckViewModel> LoadReferentialData()
        {
            List <PreconstructedDeckViewModel> ret = new List <PreconstructedDeckViewModel>();
            IDictionary <int, CardViewModel>   allCardsViewModel = _magicDatabase.GetAllInfos().ToDictionary(cai => cai.IdGatherer, cai => new CardViewModel(cai));

            foreach (IPreconstructedDeck preconstructedDeck in _magicDatabase.GetAllPreconstructedDecks())
            {
                ICollection <IPreconstructedDeckCardEdition> deckComposition = _magicDatabase.GetPreconstructedDeckCards(preconstructedDeck);
                IEdition edition = _magicDatabase.GetEditionById(preconstructedDeck.IdEdition);

                ret.Add(new PreconstructedDeckViewModel(preconstructedDeck, edition,
                                                        deckComposition.Select(pdce => new KeyValuePair <CardViewModel, int>(allCardsViewModel[pdce.IdGatherer], pdce.Number))));
            }

            ret.Sort((x, y) =>
            {
                //Most recent set first
                if (!x.EditionDate.HasValue)
                {
                    return(y.EditionDate.HasValue ? 1 : 0);
                }
                if (!y.EditionDate.HasValue)
                {
                    return(-1);
                }
                int comp = y.EditionDate.Value.CompareTo(x.EditionDate.Value);
                if (comp == 0)
                {
                    //Alphabet order
                    comp = x.Name.CompareTo(y.Name);
                }


                return(comp);
            });

            return(ret.AsReadOnly());
        }
Esempio n. 23
0
        private void RefreshDisplayedData(InputMode modifyData)
        {
            UpdateCurrentCollectionDetailAndTranslate();

            //None one the key changed, nothing to recompute
            if (modifyData == InputMode.None)
            {
                return;
            }

            //Change one of the key but no the reference one
            if (InputMode != modifyData)
            {
                Languages.Clear();
                IEdition editionSelected  = EditionSelected;
                ICard    cardNameSelected = _cardSelected;
                if (editionSelected == null || cardNameSelected == null)
                {
                    return;
                }

                ICardAllDbInfo cardAllDbInfo = _allCardInfos.First(cadi => cadi.Edition == editionSelected && cadi.Card == cardNameSelected);
                if (cardAllDbInfo == null)
                {
                    return;
                }

                foreach (ILanguage language in _magicDatabase.GetLanguages(cardAllDbInfo.IdGatherer))
                {
                    Languages.Add(language);
                }

                if (Languages.Count > 0)
                {
                    if (_inputLanguage != null && Languages.Contains(_inputLanguage))
                    {
                        LanguageSelected = _inputLanguage;
                    }
                    else
                    {
                        LanguageSelected = Languages[0];
                    }
                }
            }
            else
            {
                //Change the reference
                switch (InputMode)
                {
                case InputMode.ByEdition:

                    IEdition editionSelected = EditionSelected;
                    Cards.Clear();
                    Languages.Clear();
                    if (editionSelected == null)
                    {
                        return;
                    }

                    List <string> sorted = new List <string>();
                    //Could not call directly GetAllCardsOrderByTranslation because the key must be the same as in all card even if there is no duplicate traduction in the subset
                    foreach (KeyValuePair <string, ICard> kv in _allCardInfos.Where(cadi => cadi.Edition == editionSelected).GetAllCardWithTranslation(_inputLanguage))
                    {
                        //Normal case
                        if (_allCardSorted.ContainsKey(kv.Key))
                        {
                            sorted.Add(kv.Key);
                        }
                        else
                        {
                            //Key was changed because of duplicate traduction, we need to look for the card
                            sorted.Add(_allCardSorted.First(acsKv => kv.Value == acsKv.Value).Key);
                        }
                    }
                    sorted.Sort();
                    Cards.AddRange(sorted);
                    break;

                case InputMode.ByCard:

                    ICard cardNameSelected = _cardSelected;
                    Editions.Clear();
                    Languages.Clear();
                    if (cardNameSelected == null)
                    {
                        return;
                    }

                    foreach (IEdition edition in _allCardInfos.GetAllEditionIncludingCardOrdered(cardNameSelected))
                    {
                        Editions.Add(edition);
                    }

                    if (Editions.Count > 0)
                    {
                        EditionSelected = Editions[0];
                    }

                    break;
                }
            }
        }
Esempio n. 24
0
 private void InsertInReferential(IEdition edition)
 {
     _editions.Add(edition);
     _cacheForAllDbInfos = null;
 }
        internal DeckInfo ParseDeckPage(string html)
        {
            string htmltext = WebUtility.HtmlDecode(html);
            Match  m        = _deckNameRegex.Match(htmltext);

            if (!m.Success)
            {
                throw new ParserException("Could not find Title");
            }

            string deckName = m.Groups["name"].Value;

            m = _deckEditionRegex.Match(htmltext);
            if (!m.Success)
            {
                throw new ParserException("Could not find edition");
            }

            if (string.IsNullOrWhiteSpace(deckName))
            {
                return(null);
            }

            IEdition deckEdition = GetEdition(deckName, m);

            if (deckEdition == null)
            {
                throw new ParserException("Could not find edition with name " + deckName);
            }
            if (MagicDatabase.GetPreconstructedDeck(deckEdition.Id, deckName) != null)
            {
                return(null);
            }

            //Split in block
            IList <DeckCardInfo> cards = new List <DeckCardInfo>();

            string[] tokens = htmltext.Split(new string[] { CardSplitter }, StringSplitOptions.RemoveEmptyEntries);

            //Start at 1 because cards start by CardSplitter
            for (int i = 1; i < tokens.Length; i++)
            {
                string[] lines = tokens[i].Split(new[] { '\n' }, StringSplitOptions.RemoveEmptyEntries);

                if (!int.TryParse(lines[0], out int number))
                {
                    throw new ParserException("Could not find Number");
                }

                foreach (string line in lines)
                {
                    m = _cardInfoRegex.Match(line);
                    if (m.Success)
                    {
                        ICard    card    = GetCard(m);
                        IEdition edition = GetEdition(deckName, m);

                        if (edition == null)
                        {
                            throw new ParserException("Could not find edition for card in " + deckName);
                        }

                        int idGatherer = MagicDatabase.GetIdGatherer(card, edition);
                        if (idGatherer == 0)
                        {
                            //It is not a gatherer edition, we will add the card to it
                            if (edition.IsNoneGatherer() && _getExtraInfo != null)
                            {
                                Tuple <string, IRarity> t = ExtractExtraInfo(m.Groups["url"].Value);
                                cards.Add(new DeckCardInfo(edition.Id, card.Id, number, t.Item2.Id, t.Item1));
                                break;
                            }

                            throw new ParserException(string.Format("Could not find card with idCard {0} and idEdition {1}", card.Id, edition.Id));
                        }
                        else
                        {
                            cards.Add(new DeckCardInfo(idGatherer, number));
                            break;
                        }
                    }
                }
            }

            if (cards.Count == 0)
            {
                return(null);
            }
            DeckInfo deckInfo  = new DeckInfo(deckEdition.Id, deckName, cards);
            int      cardCount = deckInfo.Count;

            //  60 Usual
            //  75 Usual with side board
            //  62 Deckmasters
            //  61 Beatdown
            // 100 Commander
            //  15 or 22 or 26 or 30 or 35 or 40 or 41 Welcome Pack / Portal
            //  80 Archenemy
            //  70 Planechase
            //  20 Jumpstart
            if (cardCount != 60 && cardCount != 75 &&
                cardCount != 62 &&
                cardCount != 61 &&
                cardCount != 100 &&
                cardCount != 15 && cardCount != 22 && cardCount != 26 && cardCount != 30 && cardCount != 35 && cardCount != 40 && cardCount != 41 &&
                cardCount != 80 &&
                cardCount != 70 &&
                cardCount != 20
                )
            {
                throw new ParserException(string.Format("Deck {0} contains {1} cards", deckName, cardCount));
            }

            return(deckInfo);
        }
Esempio n. 26
0
        /// <summary>
        /// Загружает содержимое файла типа .bib
        /// в список изданий
        /// </summary>
        private void btnLoad_Click(object sender, EventArgs e)
        {
            Stream         fileStream;
            OpenFileDialog openFileDialog = new OpenFileDialog();
            string         filePath;
            string         fileContent = string.Empty;

            openFileDialog.Filter           = "bib files (*.bib)|*.bib";
            openFileDialog.InitialDirectory = Directory.GetCurrentDirectory();
            openFileDialog.RestoreDirectory = true;

            if (openFileDialog.ShowDialog() == DialogResult.OK)
            {
                filePath   = openFileDialog.FileName;
                fileStream = openFileDialog.OpenFile();

                using (StreamReader streamReader = new StreamReader(fileStream))
                {
                    fileContent = streamReader.ReadToEnd();
                }

                gridEditions.Rows.Clear();
                editions.Clear();

                XElement xRoot = XElement.Parse(
                    fileContent,
                    LoadOptions.SetLineInfo);

                var      allNodes         = xRoot.DescendantNodesAndSelf();
                var      nodesToSerialize = new List <XElement>();
                string[] arrEditionTypes  = Enum.GetNames(typeof(EditionTypes));

                foreach (var node in allNodes)
                {
                    if (node is XElement)
                    {
                        string name = ((XElement)node).Name.LocalName;
                        if (arrEditionTypes.Contains(name))
                        {
                            nodesToSerialize.Add((XElement)node);
                        }
                    }
                }

                XmlSerializer reader      = null;
                Type          editionType = null;
                IEdition      edition     = null;
                Assembly      assembly    = typeof(IEdition).Assembly;
                string        typeName;
                List <Person> authors          = new List <Person>();
                string        exceptionMessage = string.Empty;

                XmlAttributes attrs = new XmlAttributes();
                attrs.XmlIgnore = true;
                attrs.XmlElements.Add(
                    new XmlElementAttribute()
                {
                    ElementName = "Authors"
                });

                XmlAttributeOverrides attrOverrides =
                    new XmlAttributeOverrides();

                assembly.GetTypes().ToList().
                Where(x => x.IsClass &&
                      x.GetInterfaces().Contains(typeof(IEdition))).
                ToList().ForEach(type =>
                {
                    attrOverrides.Add(type, "Authors", attrs);
                });

                foreach (var xml in nodesToSerialize)
                {
                    try
                    {
                        typeName    = "Model." + xml.Name.LocalName;
                        editionType = assembly.GetType(typeName);
                        reader      = new XmlSerializer(editionType, attrOverrides);
                        authors     = new List <Person>();

                        using (TextReader stream = new StringReader(xml.ToString()))
                        {
                            edition = (IEdition)(Convert.ChangeType(
                                                     reader.Deserialize(stream), editionType));
                        }
                        using (TextReader stream = new StringReader(xml.ToString()))
                        {
                            XmlReaderSettings settings = new XmlReaderSettings
                            {
                                IgnoreComments   = true,
                                IgnoreWhitespace = true
                            };

                            using (XmlReader xmlReader =
                                       XmlReader.Create(stream, settings))
                            {
                                while (!xmlReader.EOF)
                                {
                                    if (xmlReader.Name != "Person")
                                    {
                                        xmlReader.ReadToFollowing("Person");
                                    }

                                    if (!xmlReader.EOF)
                                    {
                                        XElement person = (XElement)XNode.ReadFrom(xmlReader);
                                        Person   author = new Person
                                        {
                                            FirstName  = (string)person.Element("FirstName"),
                                            SecondName = (string)person.Element("SecondName"),
                                            Patronymic = (string)person.Element("Patronymic")
                                        };
                                        authors.Add(author);
                                    }
                                }

                                editionType.GetProperty("Authors").SetValue(
                                    Convert.ChangeType(edition, editionType),
                                    authors);

                                editions.Add(edition);
                                gridEditions.Rows.Add(edition.StandartName);
                            }
                        }
                    }
                    catch (Exception ex)
                    {
                        exceptionMessage += "Error while loading file \n";
                    }
                }

                gridEditions.Update();
                gridEditions.Refresh();

                if (!string.IsNullOrEmpty(exceptionMessage))
                {
                    MessageBox.Show(
                        "Error while parsing " + exceptionMessage,
                        "Loading Error",
                        MessageBoxButtons.OK,
                        MessageBoxIcon.Information);
                }
                SetButtonsEnable();
            }
        }
Esempio n. 27
0
        public void MoveCardToOtherCollection(ICardCollection collection, ICard card, IEdition edition, ILanguage language, ICardCount cardCount, ICardCollection collectionDestination)
        {
            if (cardCount == null)
            {
                return;
            }

            using (new WriterLock(_lock))
            {
                int idGatherer = GetIdGatherer(card, edition);
                int idLanguage = language.Id;
                MoveCardToOtherCollection(collection, idGatherer, idLanguage, cardCount, collectionDestination);
            }
        }
Esempio n. 28
0
 internal EditionInfoWithBlock(EditionInfo setInfo, IEdition edition)
 {
     BaseSearchUrl = setInfo.BaseSearchUrl;
     Edition       = edition;
 }