public IList <long> CreateFavoriteCategory(int categoryId, string title, IList <long> labelIds) { var now = DateTime.UtcNow; var user = TryGetUser(); var category = m_favoritesRepository.Load <Category>(categoryId); var labels = GetFavoriteLabelsAndCheckAuthorization(labelIds, user.Id); var labelsDictionary = labels.ToDictionary(x => x.Id); var itemsToSave = new List <FavoriteCategory>(); foreach (var labelId in labelIds) { var label = labelsDictionary[labelId]; label.LastUseTime = now; var favoriteItem = new FavoriteCategory { Category = category, CreateTime = now, User = user, FavoriteLabel = label, Title = title }; itemsToSave.Add(favoriteItem); } var result = m_favoritesRepository.CreateAll(itemsToSave); return(result.Cast <long>().ToList()); }
public async Task <IActionResult> Edit(int id, [Bind("UserId,GameCategoryId")] FavoriteCategory favoriteCategory) { if (id != favoriteCategory.UserId) { return(NotFound()); } if (ModelState.IsValid) { try { _context.Update(favoriteCategory); await _context.SaveChangesAsync(); } catch (DbUpdateConcurrencyException) { if (!FavoriteCategoryExists(favoriteCategory.UserId)) { return(NotFound()); } else { throw; } } return(RedirectToAction(nameof(Index))); } if (UserHelper.IsLoggedIn(this)) { ViewData["UserId"] = HttpContext.Session.GetInt32("userId"); } ViewData["GameCategoryId"] = new SelectList(_context.GameCategory, "GameCategoryId", "GameCategory1", favoriteCategory.GameCategoryId); return(View(favoriteCategory)); }
public IHttpActionResult PostFavoriteCategory([FromUri] Guid userId, [FromUri] Guid categoryId) { var user = shoppingEntities.Users.FirstOrDefault(t => t.Id == userId); var category = shoppingEntities.Categories.FirstOrDefault(t => t.Id == categoryId); if (user == null) { throw new BadRequestException("User khong ton tai"); } if (category == null) { throw new BadRequestException("Category khong ton tai"); } if (shoppingEntities.FavoriteCategories.FirstOrDefault(t => t.UserId == user.Id && t.CategoryId == category.Id) == null) { FavoriteCategory favoriteCategory = new FavoriteCategory(); favoriteCategory.Id = Guid.NewGuid(); favoriteCategory.Category = category; favoriteCategory.User = user; shoppingEntities.FavoriteCategories.Add(favoriteCategory); shoppingEntities.SaveChanges(); } return(Ok(new CategoryDto(category))); }
public async void TestEdit_InvalidFavoriteCategory_ShouldFail(string value) { // Arrange FavoriteCategoriesController controller = new FavoriteCategoriesController(_context); int userId = int.Parse(value); // Act FavoriteCategory replayCategory = await _context.FavoriteCategory .FirstOrDefaultAsync(a => a.UserId == userId); replayCategory.GameCategoryId = 0; try { var result = await controller.Edit(replayCategory.UserId, replayCategory); // Assert Assert.IsType <ViewResult>(result); ViewResult viewResult = (ViewResult)result; Assert.NotNull(viewResult.ViewData.ModelState); Assert.NotEmpty(viewResult.ViewData.ModelState.Keys); foreach (string item in viewResult.ViewData.ModelState.Keys) { Assert.Equal("", item); } } catch (Exception ex) { Assert.Equal("System.InvalidOperationException", ex.GetType().ToString()); } }
public IHttpActionResult DeleteFavoriteCategory([FromUri] Guid userId, [FromUri] Guid categoryId) { var user = shoppingEntities.Users.FirstOrDefault(t => t.Id == userId); var category = shoppingEntities.Categories.FirstOrDefault(t => t.Id == categoryId); if (user == null) { throw new BadRequestException("User khong ton tai"); } if (category == null) { throw new BadRequestException("Category khong ton tai"); } FavoriteCategory favoriteCategory = shoppingEntities.FavoriteCategories.FirstOrDefault(t => t.UserId == userId && t.CategoryId == categoryId); if (favoriteCategory == null) { throw new BadRequestException("User chua thich Category nay"); } shoppingEntities.FavoriteCategories.Remove(favoriteCategory); shoppingEntities.SaveChanges(); return(Ok(new CategoryDto(category))); }
public static string GetSearchQuery(string keyword, FavoriteCategory filter) { return(JsonConvert.SerializeObject(new SearchResultData() { Keyword = keyword, CategoryIndex = filter?.Index ?? -1 })); }
public IAsyncAction AddToCategoryAsync(IReadOnlyList <ItemIndexRange> items, FavoriteCategory categoty) { if (categoty is null) { throw new ArgumentNullException(nameof(categoty)); } if (items is null || items.Count == 0) { return(AsyncAction.CreateCompleted()); } return(AsyncInfo.Run(async token => { var ddact = default(string); if (categoty.Index < 0) { ddact = "delete"; } else { ddact = $"fav{categoty.Index}"; } var post = Client.Current.HttpClient.PostAsync(this.SearchUri, getParameters()); token.Register(post.Cancel); var r = await post; if (categoty.Index < 0) { this.Reset(); } else { foreach (var range in items) { for (var i = range.FirstIndex; i <= range.LastIndex; i++) { this[i].FavoriteCategory = categoty; } } } IEnumerable <KeyValuePair <string, string> > getParameters() { yield return new KeyValuePair <string, string>("apply", "Apply"); yield return new KeyValuePair <string, string>("ddact", ddact); foreach (var range in items) { for (var i = range.FirstIndex; i <= range.LastIndex; i++) { yield return new KeyValuePair <string, string>("modifygids[]", this[i].ID.ToString()); } } } })); }
internal static FavoritesSearchResult Search(string keyword, FavoriteCategory category) { if (category == null || category.Index < 0) { category = FavoriteCategory.All; } var result = new FavoritesSearchResult(keyword, category); return(result); }
public virtual IList <FavoriteCategory> GetFavoriteLabeledCategories(int userId) { FavoriteCategory favoriteItemAlias = null; FavoriteLabel favoriteLabelAlias = null; return(GetSession().QueryOver(() => favoriteItemAlias) .JoinAlias(() => favoriteItemAlias.FavoriteLabel, () => favoriteLabelAlias) .Fetch(SelectMode.Fetch, x => x.FavoriteLabel) .And(() => favoriteLabelAlias.User.Id == userId) .OrderBy(() => favoriteLabelAlias.Name).Asc .OrderBy(() => favoriteItemAlias.Title).Asc .List()); }
public void AddFavoriteCategory(string id) { if (id == null) { return; } var userId = userRepository.Find(x => x.Email == User.Identity.Name).FirstOrDefault().Id; var favCat = new FavoriteCategory() { UserId = userId, CategoryId = int.Parse(id) }; favCatRepository.AddFavoriteCategory(favCat); }
public async Task AddToCategoryAsync(IReadOnlyList <ItemIndexRange> items, FavoriteCategory categoty, CancellationToken token = default) { if (categoty is null) { throw new ArgumentNullException(nameof(categoty)); } if (items is null || items.Count == 0) { return; } var ddact = categoty.Index < 0 ? "delete" : $"fav{categoty.Index}"; var post = Client.Current.HttpClient.PostAsync(SearchUri, getParameters()); token.Register(post.Cancel); var r = await post; if (categoty.Index < 0) { Reset(); } else { foreach (var range in items) { for (var i = range.FirstIndex; i <= range.LastIndex; i++) { this[i].FavoriteCategory = categoty; } } } IEnumerable <KeyValuePair <string, string> > getParameters() { yield return(new KeyValuePair <string, string>("apply", "Apply")); yield return(new KeyValuePair <string, string>("ddact", ddact)); foreach (var range in items) { for (var i = range.FirstIndex; i <= range.LastIndex; i++) { yield return(new KeyValuePair <string, string>("modifygids[]", this[i].Id.ToString())); } } } }
public async Task <bool> DeleteFavoriteCategoryAsync(FavoriteCategory category) { try { var result = await conn.DeleteAsync(category).ConfigureAwait(continueOnCapturedContext: false); StatusMessage = string.Format("{0} dropped from database [Cat: {1}]", result, category); StatusCode = codes.ok; return(true); } catch (Exception ex) { StatusMessage = string.Format("Failed to delete record: {0}, Error: {1}", category, ex.Message); StatusCode = codes.bad; return(false); } }
public virtual IList <FavoriteCategory> GetFavoriteLabeledCategories(IList <int> categoryIds, int userId) { FavoriteCategory favoriteItemAlias = null; FavoriteLabel favoriteLabelAlias = null; using (var session = GetSession()) { return(session.QueryOver(() => favoriteItemAlias) .JoinAlias(() => favoriteItemAlias.FavoriteLabel, () => favoriteLabelAlias) .Fetch(x => x.FavoriteLabel).Eager .WhereRestrictionOn(() => favoriteItemAlias.Category.Id).IsInG(categoryIds) .And(() => favoriteLabelAlias.User.Id == userId) .OrderBy(() => favoriteLabelAlias.Name).Asc .OrderBy(() => favoriteItemAlias.Title).Asc .List()); } }
private void InitializeFavoriteCategory() { try { _context.Entry(favoriteCategory).State = EntityState.Detached; } catch (Exception) { // TODO: nothing... } favoriteCategory = new FavoriteCategory() { UserId = 26, GameCategoryId = 1 }; }
public async Task <bool> DeleteFavoriteCategoryAsync(string categoryKey) { FavoriteCategory current = conn.Table <FavoriteCategory>().Where(x => x.CategoryKey.Equals(categoryKey)).ToListAsync().Result.First(); try { var result = await conn.DeleteAsync(current).ConfigureAwait(continueOnCapturedContext: false); StatusMessage = string.Format("{0} dropped from database [Cat: {1}]", result, current); StatusCode = codes.ok; return(true); } catch (Exception ex) { StatusMessage = string.Format("Failed to delete record: {0}, Error: {1}", current, ex.Message); StatusCode = codes.bad; return(false); } }
public async Task <IActionResult> Create([Bind("UserId,GameCategoryId")] FavoriteCategory favoriteCategory) { if (ModelState.IsValid) { _context.Add(favoriteCategory); await _context.SaveChangesAsync(); //return RedirectToAction(nameof(Index)); //return View(favoriteCategory); } var userId = UserHelper.GetSessionUserId(this); var favoriteCategoryContext = _context.FavoriteCategory .Include(f => f.GameCategory) .Where(f => f.UserId.Equals(userId)); ViewData["UserId"] = userId; ViewData["FavoriteCategories"] = favoriteCategoryContext.ToList(); ViewData["GameCategories"] = getCategoriesNotInFav(userId); return(View(favoriteCategory)); }
protected override long ExecuteWorkImplementation() { var now = DateTime.UtcNow; var user = m_favoritesRepository.Load <User>(m_userId); var category = m_favoritesRepository.Load <Category>(m_data.CategoryId); var label = GetFavoriteLabelAndCheckAuthorization(m_data.FavoriteLabelId, user.Id); label.LastUseTime = now; var favoriteItem = new FavoriteCategory { Category = category, CreateTime = now, FavoriteLabel = label, Title = m_data.Title }; var resultId = (long)m_favoritesRepository.Create(favoriteItem); return(resultId); }
public IHttpActionResult PostCurrentUserFavoriteCategory([FromUri] Guid categoryId) { var token = ultilityService.GetHeaderToken(HttpContext.Current); var userToken = shoppingEntities.UserTokens.FirstOrDefault(t => t.Name == token); if (userToken == null) { throw new BadRequestException("Access token khong hop le"); } var user = userToken.User; var category = shoppingEntities.Categories.FirstOrDefault(t => t.Id == categoryId); if (user == null) { throw new BadRequestException("User khong ton tai"); } if (category == null) { throw new BadRequestException("Category khong ton tai"); } if (shoppingEntities.FavoriteCategories.FirstOrDefault(t => t.UserId == user.Id && t.CategoryId == category.Id) == null) { FavoriteCategory favoriteCategory = new FavoriteCategory(); favoriteCategory.Id = Guid.NewGuid(); favoriteCategory.Category = category; favoriteCategory.User = user; shoppingEntities.FavoriteCategories.Add(favoriteCategory); shoppingEntities.SaveChanges(); } return(Ok(new CategoryDto(category))); }
private void set(FavoriteCategory category, bool labelVisible) { category = category ?? Client.Current.Favorites.All; var icon = this.Icon; if (icon != null) { icon.Visibility = category.Index < 0 ? Visibility.Collapsed : Visibility.Visible; } this.BorderBrush = category.GetThemeBrush(); if (labelVisible) { var label = this.Label; if (label is null) { label = GetTemplateChild("Label") as TextBlock; if (label is null) { return; } else { this.Label = label; } } label.Visibility = Visibility.Visible; label.Text = category.Name ?? ""; } else { if (this.Label is null) { return; } this.Label.Visibility = Visibility.Collapsed; } }
private FavoritesSearchResult(string keyword, FavoriteCategory category) : base(keyword) { Category = category; SearchUri = new Uri(SearchBaseUri, _GetUriQuery()); }
public void AddFavoriteCategory(FavoriteCategory category) { db.FavoriteCategories.Add(category); db.SaveChanges(); }
public override int DiscoverDynamicCategories() { Settings.Categories.Clear(); List <KeyValuePair <string, uint> > lsSiteIds = OnlineVideoSettings.Instance.FavDB.GetSiteIds(); if (lsSiteIds == null || lsSiteIds.Count == 0) { return(0); } uint sumOfAllVideos = (uint)lsSiteIds.Sum(s => s.Value); if (sumOfAllVideos > 0) // only add the "ALL" category if we have single favorite videos in addition to favorites categories { RssLink all = null; if (!cachedCategories.TryGetValue(Translation.Instance.All, out all)) { all = new RssLink(); all.Name = Translation.Instance.All; all.Url = string.Empty; cachedCategories.Add(all.Name, all); } all.EstimatedVideoCount = sumOfAllVideos; Settings.Categories.Add(all); } foreach (var lsSiteId in lsSiteIds) { SiteUtilBase util = null; if (OnlineVideoSettings.Instance.SiteUtilsList.TryGetValue(lsSiteId.Key, out util)) { SiteSettings aSite = util.Settings; if (aSite.IsEnabled && (!aSite.ConfirmAge || !OnlineVideoSettings.Instance.UseAgeConfirmation || OnlineVideoSettings.Instance.AgeConfirmed)) { RssLink cat = null; if (!cachedCategories.TryGetValue(aSite.Name + " - " + Translation.Instance.Favourites, out cat)) { cat = new RssLink(); cat.Name = aSite.Name + " - " + Translation.Instance.Favourites; cat.Description = aSite.Description; cat.Url = aSite.Name; cat.Thumb = System.IO.Path.Combine(OnlineVideoSettings.Instance.ThumbsDir, @"Icons\" + aSite.Name + ".png"); cachedCategories.Add(cat.Name, cat); } cat.EstimatedVideoCount = lsSiteId.Value; Settings.Categories.Add(cat); // create subcategories if any var favCats = OnlineVideoSettings.Instance.FavDB.GetFavoriteCategories(aSite.Name); if (favCats.Count > 0) { cat.HasSubCategories = true; cat.SubCategoriesDiscovered = true; cat.SubCategories = new List <Category>(); if (lsSiteId.Value > 0) // only add the "ALL" category if we have single favorite videos in addition to favorites categories { cat.SubCategories.Add(new RssLink() { Name = Translation.Instance.All, Url = aSite.Name, ParentCategory = cat, EstimatedVideoCount = lsSiteId.Value }); } foreach (var favCat in favCats) { FavoriteCategory fc = new FavoriteCategory(favCat, util, this) { ParentCategory = cat }; if (String.IsNullOrEmpty(fc.Description)) { string[] parts = favCat.RecursiveName.Split('|'); if (parts.Length > 1) { fc.Description = String.Join(" / ", parts, 0, parts.Length - 1); } } cat.SubCategories.Add(fc); } } } } } // need to always get the categories, because when adding new fav video from a new site, a removing the last one for a site, the categories must be refreshed Settings.DynamicCategoriesDiscovered = false; return(Settings.Categories.Count); }
public override int DiscoverDynamicCategories() { Settings.Categories.Clear(); List<KeyValuePair<string, uint>> lsSiteIds = OnlineVideoSettings.Instance.FavDB.GetSiteIds(); if (lsSiteIds == null || lsSiteIds.Count == 0) return 0; uint sumOfAllVideos = (uint)lsSiteIds.Sum(s => s.Value); if (sumOfAllVideos > 0) // only add the "ALL" category if we have single favorite videos in addition to favorites categories { RssLink all = null; if (!_cachedCategories.TryGetValue(Translation.Instance.All, out all)) { all = new RssLink { Name = Translation.Instance.All, Url = string.Empty }; _cachedCategories.Add(all.Name, all); } all.EstimatedVideoCount = sumOfAllVideos; Settings.Categories.Add(all); } foreach (var lsSiteId in lsSiteIds) { SiteUtilBase util = null; if (OnlineVideoSettings.Instance.SiteUtilsList.TryGetValue(lsSiteId.Key, out util)) { SiteSettings aSite = util.Settings; if (aSite.IsEnabled && (!aSite.ConfirmAge || !OnlineVideoSettings.Instance.UseAgeConfirmation || OnlineVideoSettings.Instance.AgeConfirmed)) { RssLink cat = null; if (!_cachedCategories.TryGetValue(aSite.Name + " - " + Translation.Instance.Favourites, out cat)) { cat = new RssLink(); cat.Name = aSite.Name + " - " + Translation.Instance.Favourites; cat.Description = aSite.Description; cat.Url = aSite.Name; cat.Thumb = System.IO.Path.Combine(OnlineVideoSettings.Instance.ThumbsDir, @"Icons\" + aSite.Name + ".png"); _cachedCategories.Add(cat.Name, cat); } cat.EstimatedVideoCount = lsSiteId.Value; Settings.Categories.Add(cat); // create subcategories if any var favCats = OnlineVideoSettings.Instance.FavDB.GetFavoriteCategories(aSite.Name); if (favCats.Count > 0) { cat.HasSubCategories = true; cat.SubCategoriesDiscovered = true; cat.SubCategories = new List<Category>(); if (lsSiteId.Value > 0) // only add the "ALL" category if we have single favorite videos in addition to favorites categories { cat.SubCategories.Add(new RssLink { Name = Translation.Instance.All, Url = aSite.Name, ParentCategory = cat, EstimatedVideoCount = lsSiteId.Value }); } foreach (var favCat in favCats) { FavoriteCategory fc = new FavoriteCategory(favCat, util, this) { ParentCategory = cat }; if (String.IsNullOrEmpty(fc.Description)) { string[] parts = favCat.RecursiveName.Split('|'); if (parts.Length > 1) fc.Description = String.Join(" / ", parts, 0, parts.Length - 1); } cat.SubCategories.Add(fc); } } } } } // need to always get the categories, because when adding new fav video from a new site, a removing the last one for a site, the categories must be refreshed Settings.DynamicCategoriesDiscovered = false; return Settings.Categories.Count; }