public static void AddOrUpdateUserCollectionCard(int collectionId, IEnumerable <CollectionCard> cards, out string error) { error = ""; using (var db = new FortyLifeDbContext()) { var scryfallRequestEngine = new ScryfallRequestEngine(); var collectionCards = db.CollectionCards; var cardList = cards.ToList(); // fill in set codes for entries that don't have one foreach (var card in cardList) { if (string.IsNullOrEmpty(card.SetCode)) { card.SetCode = scryfallRequestEngine.GetCard(card.Name).Set.ToUpper(); } // also fill in the set name card.SetName = new ScryfallRequestEngine().SetRequest(card.SetCode).Name; } var duplicates = cardList.GroupBy(i => new { i.Name, i.SetCode, i.Foil }) .Where(i => i.Count() > 1) .Select(i => i.Key); var duplicateList = duplicates.ToList(); if (!duplicateList.Any()) { DeleteAllCardsInCollection(collectionId); foreach (var card in cardList) { card.CollectionId = collectionId; collectionCards.AddOrUpdate(card); } db.SaveChanges(); } else { var errorCard = duplicateList.First(); var errorCardName = errorCard.Name; // find the second occurence of any duplicated item var firstOcc = cardList.FindIndex(i => i.Name == errorCard.Name && i.SetCode == errorCard.SetCode) + 1; var errorLine = cardList.FindIndex(firstOcc, i => i.Name == errorCard.Name && i.SetCode == errorCard.SetCode) + 1; error = $"Duplicate card detected: {errorCardName}. (Lines {firstOcc} and {errorLine})"; } } }
public static Collection GetCollection(int id, out string error) { error = ""; var priceRequestEngine = new TcgPlayerRequestEngine(); var cardRequestEngine = new ScryfallRequestEngine(); using (var db = new FortyLifeDbContext()) { var collection = db.Collections.Include(i => i.Cards).FirstOrDefault(i => i.CollectionId == id); if (collection != null) { // We need to update pertinent information about the collection collection.TcgMidValue = 0; foreach (var card in collection.Cards) { var setName = cardRequestEngine.GetCard(card.Name, card.SetCode).SetName; Price price; if (card.Foil) { price = priceRequestEngine.CardPriceRequest(card.Name, setName)? .First(i => i.SubTypeName == "Foil"); } else { price = priceRequestEngine.CardPriceRequest(card.Name, setName)? .First(i => i.SubTypeName == "Normal"); } if (price?.MidPrice != null) { collection.TcgMidValue += price.MidPrice.Value; } return(collection); } } } error = "This collection does not exist or is private."; return(new Collection()); }