public ProductDetail CardDetailsRequest(int productId) { using (var db = new FortyLifeDbContext()) { //if (db.ProductDetails.Any(i => i.ProductId == productId && DbFunctions.DiffDays(i.CacheDate, DateTime.Now) < 7)) //{ // return db.ProductDetails.FirstOrDefault(i => i.ProductId == productId); //} // Rate limit to be a good samaritan Thread.Sleep(200); // TODO: find a better way to do this without shutting down the thread var jsonResult = Get($"{productDetailsRequestUri}{productId}", ReadAccessToken()); var productDetail = JsonConvert.DeserializeObject <ProductDetailsResults>(jsonResult).Results.First(); if (productDetail != null) { productDetail.CacheDate = DateTime.Now; //db.ProductDetails.AddOrUpdate(productDetail); //db.SaveChanges(); } return(productDetail); } }
public List <Ruling> RulingsRequest(string rulingsUri) { using (var db = new FortyLifeDbContext()) { //if (db.Rulings.Any(i => i.RulingsUri == rulingsUri && DbFunctions.DiffDays(i.CacheDate, DateTime.Now) < 7)) //{ // return db.Rulings.Where(i => i.RulingsUri == rulingsUri).ToList(); //} var rulings = Request <ScryfallList <Ruling> >(rulingsUri).Data; if (rulings != null) { foreach (var ruling in rulings) { ruling.RulingsUri = rulingsUri; ruling.CacheDate = DateTime.Now; //db.Rulings.AddOrUpdate(ruling); //db.SaveChanges(); } } return(rulings); } }
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 void DeleteAllCardsInCollection(int collectionId) { using (var db = new FortyLifeDbContext()) { foreach (var card in db.CollectionCards.Where(i => i.CollectionId == collectionId)) { db.CollectionCards.Remove(card); } db.SaveChanges(); } }
private static void RegenerateActivationKey(string email) { using (var db = new FortyLifeDbContext()) { var user = db.ApplicationUsers.FirstOrDefault(i => i.Email == email); if (user != null) { user.ActivationKey = RemoveReservedUnsafeCharacters(UserAuthenticator.GetHashString(DateTime.Now.ToString("G"))); db.SaveChanges(); } } }
public static void ActivateUser(string email) { using (var db = new FortyLifeDbContext()) { var user = db.ApplicationUsers.FirstOrDefault(i => i.Email == email); if (user != null) { user.ActivationKey = null; db.SaveChanges(); } } }
public static bool IsValid(string email, string rawPassword) { using (var db = new FortyLifeDbContext()) { var user = db.ApplicationUsers.FirstOrDefault(i => i.Email == email); if (user == null) { return(false); } return(ComputeHash(rawPassword, user.PasswordSalt) == user.PasswordHash); } }
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()); }
public static ApplicationUser GetApplicationUser(int id) { using (var db = new FortyLifeDbContext()) { var users = db.ApplicationUsers.Include(i => i.Collections.Select(j => j.Cards)); var user = users.FirstOrDefault(i => i.Id == id); if (user != null) { if (ApplicationUserCache.Contains(user.Email)) { return((ApplicationUser)ApplicationUserCache[user.Email]); } ApplicationUserCache.Set(user.Email, user, DateTimeOffset.Now.AddDays(7)); return(user); } return(null); } }
public static void AddOrUpdateUserCollection(string email, Collection collection, out string error) { error = ""; using (var db = new FortyLifeDbContext()) { var users = db.ApplicationUsers.Include(i => i.Collections.Select(j => j.Cards)); var user = users.FirstOrDefault(i => i.Email == email); if (user != null) { if (user.Collections == null) { user.Collections = new List <Collection>(); } var collectionToUpdate = user.Collections.FirstOrDefault(i => i.CollectionId == collection.CollectionId); if (collectionToUpdate != null) { collectionToUpdate.CreateDate = collection.CreateDate; collectionToUpdate.LastEditDate = collection.LastEditDate; collectionToUpdate.Name = collection.Name; collectionToUpdate.Description = collection.Description; } else { collection.Cards = null; user.Collections.Add(collection); } db.SaveChanges(); } else { error = "Error! No known user exists with an email address matching the current session claim."; } } }
public static void DeleteUserCollection(string email, Collection collection, out string error) { error = ""; using (var db = new FortyLifeDbContext()) { var users = db.ApplicationUsers.Include(i => i.Collections.Select(j => j.Cards)); var user = users.FirstOrDefault(i => i.Email == email); if (user != null) { if (user.Collections.Exists(i => i.CollectionId == collection.CollectionId)) { // remove it from the object in memory user.Collections.RemoveAll(i => i.CollectionId == collection.CollectionId); // remove all cards associated with the collection in the db foreach (var card in db.CollectionCards.Where(i => i.CollectionId == collection.CollectionId)) { db.CollectionCards.Remove(card); } // remove the collection from the db db.Collections.Remove(db.Collections.First(i => i.CollectionId == collection.CollectionId)); db.SaveChanges(); } else { error = "Error! Collection doesn't exist."; } } else { error = "Error! No known user exists with an email address matching the current session claim."; } } }
public static bool CreateAccount(string email, string password) { if (GetApplicationUser(email) != null) { return(false); } var salt = UserAuthenticator.GetHashString(DateTime.Now.Ticks.ToString()); var passwordHash = UserAuthenticator.ComputeHash(password, salt); var newUser = new ApplicationUser { Email = email, DisplayName = email.Split('@')[0], PasswordHash = passwordHash, PasswordSalt = salt, CreateDate = DateTime.Now, ActivationKey = RemoveReservedUnsafeCharacters(UserAuthenticator.GetHashString(DateTime.Now.ToString("G"))) }; using (var db = new FortyLifeDbContext()) { try { db.ApplicationUsers.AddOrUpdate(newUser); db.SaveChanges(); SendActivationEmail(email); return(true); } catch (Exception e) { // TODO: implement proper logger for exceptions return(false); } } }
public List <Card> GetCardList(Collection collection) { var cardNames = new List <string>(); var setCodes = new List <string>(); foreach (var collectionCard in collection.Cards) { cardNames.Add(collectionCard.Name); setCodes.Add(collectionCard.SetCode); } using (var db = new FortyLifeDbContext()) { var query = string.Empty; for (var i = 0; i < cardNames.Count; i++) { query += $"\"{cardNames[i]}\" " + (!string.IsNullOrEmpty(setCodes[i]) ? $"set:{setCodes[i]}" : string.Empty) + " or "; } var searchResultList = CardListRequest(query); if (searchResultList != null) { var cards = searchResultList.Data; foreach (var card in cards) { if (card != null) { card.CacheDate = DateTime.Now; if (card.ImageUris == null) { card.ImageUris = new ImageUris(); } if (card.IsDoubleFaced) { card.CardFaces[0].CacheDate = DateTime.Now; card.CardFaces[1].CacheDate = DateTime.Now; if (card.CardFaces[0].ImageUris == null) { card.CardFaces[0].ImageUris = new ImageUris(); } if (card.CardFaces[1].ImageUris == null) { card.CardFaces[1].ImageUris = new ImageUris(); } foreach (var i in card.CardFaces) { if (i.Colors != null) { i.ColorsString = PrimitiveListHandler.ToString(i.Colors); } } } if (card.Colors != null) { card.ColorsString = PrimitiveListHandler.ToString(card.Colors); } if (card.ColorIdentity != null) { card.ColorIdentityString = PrimitiveListHandler.ToString(card.ColorIdentity); } if (card.Games != null) { card.GamesString = PrimitiveListHandler.ToString(card.Games); } if (card.MultiverseIds != null) { card.MultiverseIdsString = PrimitiveListHandler.ToString(card.MultiverseIds); } //db.Cards.AddOrUpdate(card); //try //{ // db.SaveChanges(); //} //catch (DbEntityValidationException dbEx) //{ // foreach (var validationErrors in dbEx.EntityValidationErrors) // { // foreach (var validationError in validationErrors.ValidationErrors) // { // Trace.TraceInformation("Property: {0} Error: {1}", // validationError.PropertyName, // validationError.ErrorMessage); // } // } // throw; //} } } return(cards); } } return(null); }
public Card GetCard(string cardName, string setCode = "") { using (var db = new FortyLifeDbContext()) { Card card; //if (!string.IsNullOrEmpty(setCode)) //{ // if (db.Cards.Any(i => i.Name == cardName && i.Set == setCode && DbFunctions.DiffDays(i.CacheDate, DateTime.Now) < 7)) // { // var cards = db.Cards.Include(i => i.CardFaces); // card = cards.FirstOrDefault(i => i.Name == cardName && i.Set == setCode); // if (card != null) // { // // prep list data by parsing string data from db // foreach (var i in card.CardFaces) // { // if (i.ColorsString != null) // { // i.Colors = i.ColorsString.Split(',').ToList(); // } // } // card.Colors = card.ColorsString?.Split(',').ToList(); // card.ColorIdentity = card.ColorIdentityString?.Split(',').ToList(); // card.Games = card.GamesString?.Split(',').ToList(); // card.MultiverseIds = card.MultiverseIdsString?.Split(',').ToList(); // // return prepped card // return card; // } // } //} //else //{ // if (db.Cards.Any(i => i.Name == cardName && DbFunctions.DiffDays(i.CacheDate, DateTime.Now) < 7)) // { // var cards = db.Cards.Include(i => i.CardFaces); // card = cards.FirstOrDefault(i => i.Name == cardName); // if (card != null) // { // // prep list data by parsing string data from db // foreach (var i in card.CardFaces) // { // if (i.ColorsString != null) // { // i.Colors = i.ColorsString.Split(',').ToList(); // } // } // card.Colors = card.ColorsString?.Split(',').ToList(); // card.ColorIdentity = card.ColorIdentityString?.Split(',').ToList(); // card.Games = card.GamesString?.Split(',').ToList(); // card.MultiverseIds = card.MultiverseIdsString?.Split(',').ToList(); // // return prepped card // return card; // } // } //} var searchResultList = CardPrintingsRequest(cardName); if (searchResultList != null) { card = !string.IsNullOrEmpty(setCode) ? searchResultList.Data?.FirstOrDefault(i => string.Equals(i.Name, cardName, StringComparison.CurrentCultureIgnoreCase) && string.Equals(i.Set, setCode, StringComparison.CurrentCultureIgnoreCase)) : searchResultList.Data?.FirstOrDefault(i => string.Equals(i.Name, cardName, StringComparison.CurrentCultureIgnoreCase)); if (card != null) { card.CacheDate = DateTime.Now; if (card.ImageUris == null) { card.ImageUris = new ImageUris(); } if (card.IsDoubleFaced) { card.CardFaces[0].CacheDate = DateTime.Now; card.CardFaces[1].CacheDate = DateTime.Now; if (card.CardFaces[0].ImageUris == null) { card.CardFaces[0].ImageUris = new ImageUris(); } if (card.CardFaces[1].ImageUris == null) { card.CardFaces[1].ImageUris = new ImageUris(); } foreach (var i in card.CardFaces) { if (i.Colors != null) { i.ColorsString = PrimitiveListHandler.ToString(i.Colors); } } } if (card.Colors != null) { card.ColorsString = PrimitiveListHandler.ToString(card.Colors); } if (card.ColorIdentity != null) { card.ColorIdentityString = PrimitiveListHandler.ToString(card.ColorIdentity); } if (card.Games != null) { card.GamesString = PrimitiveListHandler.ToString(card.Games); } if (card.MultiverseIds != null) { card.MultiverseIdsString = PrimitiveListHandler.ToString(card.MultiverseIds); } //db.Cards.AddOrUpdate(card); //try //{ // db.SaveChanges(); //} //catch (DbEntityValidationException dbEx) //{ // foreach (var validationErrors in dbEx.EntityValidationErrors) // { // foreach (var validationError in validationErrors.ValidationErrors) // { // Trace.TraceInformation("Property: {0} Error: {1}", // validationError.PropertyName, // validationError.ErrorMessage); // } // } // throw; //} } return(card); } } return(null); }
public int ProductIdRequest(string cardName, string setName) { setName = SanitizeSetName(setName); using (var db = new FortyLifeDbContext()) { if (db.CardProductIds.Any(i => i.CardName == cardName && i.SetName == setName)) { return(db.CardProductIds.First(i => i.CardName == cardName && i.SetName == setName).ProductId); } // Rate limit to be a good samaritan Thread.Sleep(200); // TODO: find a better way to do this without shutting down the thread // when searching for products in the TCG Player API, it only accepts the name of the front face of double faced cards if (cardName.Contains("//")) { cardName = cardName.Split(new[] { "//" }, StringSplitOptions.RemoveEmptyEntries)[0].Trim(); } var searchCriteria = new CategoryProductsSearchBody { Sort = "name", Limit = 5, Offset = 0, Filters = new List <Filter> { new Filter { Name = Filter.FilterName.ProductName.ToString(), Values = new List <string> { cardName } } } }; //if (!string.IsNullOrEmpty(setName)) //{ // searchCriteria.Filters.Add(new Filter // { // Name = Filter.FilterName.SetName.ToString(), // Values = new List<string> {setName} // }); //} var body = JsonConvert.SerializeObject(searchCriteria); var jsonResult = Post(categoryProductSearchUri, body, RequestBodyType.Json, ReadAccessToken()); if (!string.IsNullOrEmpty(jsonResult)) { var productIdResult = JsonConvert.DeserializeObject <CategoryProductsResult>(jsonResult).Results .OrderBy(i => i).FirstOrDefault(); if (productIdResult > 0) { var newProductId = new CardProductId { CardName = cardName, SetName = setName, ProductId = productIdResult }; db.CardProductIds.AddOrUpdate(newProductId); db.SaveChanges(); return(productIdResult); } } return(0); } }