public async Task OneUserShouldBeAbleToAddMultipleAutoparts()
        {
            var list           = new List <Favorite>();
            var mockRepository = new Mock <IDeletableEntityRepository <Favorite> >();

            mockRepository
            .Setup(x => x.AllAsNoTracking())
            .Returns(list.AsQueryable());

            mockRepository
            .Setup(x => x.AddAsync(It.IsAny <Favorite>())).Callback(
                (Favorite favorite) => list.Add(favorite));

            mockRepository
            .Setup(x => x.HardDelete(It.IsAny <Favorite>())).Callback(
                (Favorite favorite) => list.Remove(favorite));

            var service = new FavoritesService(mockRepository.Object);

            var userId = "User_01";

            var favoritesCount = 4;

            for (int i = 0; i < favoritesCount; i++)
            {
                await service.AddToFavoriteAsync(userId, i);
            }

            Assert.Equal(favoritesCount, list.Count);
        }
        public async Task AddToFavoritesListShouldBeEmptyAutopartAddedToFavoritesTwice()
        {
            var list           = new List <Favorite>();
            var mockRepository = new Mock <IDeletableEntityRepository <Favorite> >();

            mockRepository
            .Setup(x => x.AllAsNoTracking())
            .Returns(list.AsQueryable());

            mockRepository
            .Setup(x => x.AddAsync(It.IsAny <Favorite>()))
            .Callback(
                (Favorite favorite) => list.Add(favorite));

            mockRepository
            .Setup(x => x.HardDelete(It.IsAny <Favorite>()))
            .Callback(
                (Favorite favorite) => list.Remove(favorite));

            var service = new FavoritesService(mockRepository.Object);

            var userId = "User_01";

            await service.AddToFavoriteAsync(userId, 1);

            await service.AddToFavoriteAsync(userId, 1);

            Assert.Empty(list);
        }
Beispiel #3
0
        public string ToHtml()
        {
            var service      = new FavoritesService();
            var isInFavorite = service.IsAnnouncementAlreadyInFavorites(Auth.user().Id, _announcement.Id);

            return
                (@"<a id=""annoucementItem"" data-id=""" + _announcement.Id + @""" data-is-favorite=""" + isInFavorite + @""" data-title=""" + HttpUtility.HtmlEncode(_announcement.Title) + @""" data-venue=""" + HttpUtility.HtmlEncode(_announcement.Venue) + @""" data-start-date=""" + _announcement.FormattedStartDate + @""" data-start-time=""" + _announcement.StartTime + @""" data-end-date=""" + _announcement.FormattedEndDate + @""" data-end-time=""" + _announcement.EndTime + @""" data-content=""" + HttpUtility.HtmlEncode(_announcement.Description) + @""" data-image=""" + _announcement.ImagePath + @""" href=""#"">" +
                 @"<div class=""row"">
                        <div class=""col-md-2"">
                            <img class=""img-responsive"" style=""height: 130px;"" src=""" + _announcement.ImagePath + @""" />
                        </div>
                        <div class=""col-md-6"">
                            <h4 class=""text-danger"">" + _announcement.Title + @"</h4>
                            <p class=""text-muted"">" + _announcement.Venue + @"</p>
                            <p>" +
                 _announcement.FormattedStartDate + " " +
                 _announcement.StartTime + " - " +
                 _announcement.FormattedEndDate + " " +
                 _announcement.EndTime +
                 "</p>" +
                 "</div>" +
                 @"<div class=""col-md-4""> 
                        <p>" +
                 _announcement.Description + "</p>" +

                 "</p>" +

                 "</div>" +
                 "</div>" +
                 "</a>");
        }
        public async Task Remove_WithNonExistingProduct_MethodShouldReturnFalse()
        {
            string onTrueErrorMessage = "The method does not return false upon non-existing product.";

            var context = ApplicationDbContextInMemoryFactory.InitializeContext();

            // Gets the user(Usermanager accepts the id and returns the whole user) and a fake productId
            var user      = this.GetUser();
            var productId = "FakeProductId";

            var userManager = UserManagerInitializer.InitializeMockedUserManager();

            userManager.Setup(x => x.FindByIdAsync(user.Id)).ReturnsAsync(user);

            var favoritesService = new FavoritesService(context, userManager.Object);

            // Seeding user, product and favorite product (not matching productId)
            await this.SeedUser(context);

            await this.SeedProduct(context);

            await this.SeedFavoriteProduct(context);

            var methodResult = await favoritesService.Remove(productId, user.Id);

            Assert.False(methodResult, onTrueErrorMessage);
        }
        public void GetUserFavoritePhotos_ShouldReturnFavoritePhotos()
        {
            var user    = UserCreator.Create("test");
            var visitor = UserCreator.Create("visitor");
            var photo1  = PhotoCreator.Create(user, false, false);
            var photo2  = PhotoCreator.Create(user, false, false);
            var photo3  = PhotoCreator.Create(visitor, false, false);

            var favorites = new List <PhotoFavorite>()
            {
                PhotoFavoriteCreator.Create(photo1, visitor),
                PhotoFavoriteCreator.Create(photo2, visitor),
                PhotoFavoriteCreator.Create(photo3, user),
            };

            var photosRepo = DeletableEntityRepositoryMock.Get <Photo>(new List <Photo>()
            {
                photo1, photo2, photo3
            });
            var favoritesRepo = EfRepositoryMock.Get <PhotoFavorite>(favorites);

            var service          = new FavoritesService(favoritesRepo.Object, photosRepo.Object);
            var userFavorites    = service.GetUserFavoritePhotos <PhotoViewModel>(user.Id);
            var visitorFavorites = service.GetUserFavoritePhotos <PhotoViewModel>(visitor.Id);

            Assert.Single(userFavorites);
            Assert.Equal(2, visitorFavorites.Count);
        }
        public async Task Add_WithCorrectData_ShouldProvideCorrectResult()
        {
            string onFalseErrorMessage = "Service method returned false.";
            string onNullErrorMessage  = "The favorite product not found in database.";

            var context = ApplicationDbContextInMemoryFactory.InitializeContext();

            // Gets the user(Usermanager accepts the id and returns the whole user) and productId only
            var user      = this.GetUser();
            var productId = this.GetProduct().Id;

            var userManager = UserManagerInitializer.InitializeMockedUserManager();

            userManager.Setup(x => x.FindByIdAsync(user.Id)).ReturnsAsync(user);

            var favoritesService = new FavoritesService(context, userManager.Object);

            // Seed both user and product
            await this.SeedUser(context);

            await this.SeedProduct(context);

            var methodResult = await favoritesService.Add(productId, user.Id);

            Assert.True(methodResult, onFalseErrorMessage);

            var favoriteProductFromDb = context
                                        .UsersFavoriteProducts
                                        .SingleOrDefaultAsync(x => x.ProductId == productId && x.ApplicationUserId == user.Id);

            AssertExtensions.NotNullWithMessage(favoriteProductFromDb, onNullErrorMessage);
        }
        private async void PopulatePortalItemCollection(ObservableCollection <ArcGISPortalItem> portalCollection, PortalQuery portalQuery)
        {
            if (portalCollection == null || portalQuery == PortalQuery.MyGroups)
            {
                return;
            }

            FavoritesService currentFavoritesService = new FavoritesService();
            await currentFavoritesService.SetFavoritesCollection();

            SearchParameters sp = null;

            if (portalQuery == PortalQuery.Favorites)
            {
                sp = SearchService.CreateSearchParameters("", portalQuery, 0, 20, currentFavoritesService.GetFavoritesIds());
            }
            else
            {
                sp = SearchService.CreateSearchParameters("", portalQuery);
            }

            IsLoadingData = true;
            IList <ArcGISPortalItem> portalItems = await PortalService.CurrentPortalService.GetPortalItems(sp);

            if (portalItems != null)
            {
                portalCollection.Clear();

                foreach (ArcGISPortalItem pi in portalItems)
                {
                    portalCollection.Add(pi);
                }
            }
            IsLoadingData = false;
        }
Beispiel #8
0
        public async Task <IActionResult> FollowProfile([FromRoute] string username)
        {
            if (string.IsNullOrWhiteSpace(username))
            {
                return(NotFound());
            }

            try
            {
                var tokenHeader = Request.Headers["Authorization"];
                var token       = tokenHeader.Count > 0
                    ? tokenHeader.First().Split(' ')[1]
                    : null;

                User currentUser = null;

                if (!string.IsNullOrWhiteSpace(token))
                {
                    currentUser = UserService.GetCurrentUser(token);
                }

                var result = await FavoritesService.AddFavoriteProfile(username, token);

                return(result
                    ? Ok()
                    : (IActionResult)Unauthorized());
            }
            catch (Exception ex)
            {
                var genericErrorModel = new GenericErrorModel(new GenericErrorModelErrors(new[] { ex.ToString() }));
                return(BadRequest(genericErrorModel));
            }
        }
Beispiel #9
0
        private FavoritesService CreateFavoriteService()
        {
            var userId  = Guid.Parse(User.Identity.GetUserId());
            var service = new FavoritesService(userId);

            return(service);
        }
        public async void FavortiesServiceTests_GetLoggedUserFavCurrencies_Should_Return_1_USD()
        {
            //Arrange
            FavoritesService favoritesService = CreateFavoritesService();
            ClaimsIdentity   claims           = new ClaimsIdentity(new Claim[] { new Claim(ClaimTypes.Name, _testUserName) });
            Currency         expectedCurrency = new Currency()
            {
                Id   = _firstTestCurrencyId,
                Name = _firstTestCurrencyName
            };
            ClaimsPrincipal user   = new ClaimsPrincipal(claims);
            bool            result = false;

            //Act
            var loggedUserFavService = await favoritesService.GetLoggedUserFavCurrencies(user);

            if (loggedUserFavService.Count == 1)
            {
                if (loggedUserFavService[0].Id == expectedCurrency.Id &&
                    loggedUserFavService[0].Name == expectedCurrency.Name)
                {
                    result = true;
                }
            }

            //Assert
            Assert.True(result);
        }
        public async Task Remove_WithCorrectData_ShouldRemoveProductSuccessfully()
        {
            string onFalseMethodReturnErrorMessage   = "The method does not return true upon successfull remove.";
            string onFalseDatabaseReturnErrorMessage = "The favorite product is not deleted from the database.";

            var context = ApplicationDbContextInMemoryFactory.InitializeContext();

            // Gets the user(Usermanager accepts the id and returns the whole user) and a fake productId
            var user      = this.GetUser();
            var productId = this.GetProduct().Id;

            var userManager = UserManagerInitializer.InitializeMockedUserManager();

            userManager.Setup(x => x.FindByIdAsync(user.Id)).ReturnsAsync(user);

            var favoritesService = new FavoritesService(context, userManager.Object);

            // Seeding user, product and favorite product
            await this.SeedUser(context);

            await this.SeedProduct(context);

            await this.SeedFavoriteProduct(context);

            var methodResult = await favoritesService.Remove(productId, user.Id);

            Assert.True(methodResult, onFalseMethodReturnErrorMessage);

            var doesExistInDatabase = context
                                      .UsersFavoriteProducts
                                      .FirstOrDefaultAsync(x => x.ProductId == productId && x.ApplicationUserId == user.Id);

            Assert.True(doesExistInDatabase.Result == null, onFalseDatabaseReturnErrorMessage);
        }
Beispiel #12
0
        public void DeleteShouldDeleteFavoriteProduct()
        {
            var options = new DbContextOptionsBuilder <XeonDbContext>()
                          .UseInMemoryDatabase(databaseName: "Delete_Favorites_Database")
                          .Options;
            var dbContext = new XeonDbContext(options);

            var username = "******";

            dbContext.Users.Add(new XeonUser {
                UserName = username
            });


            var productNameForDelete = "USB";
            var products             = new List <Product>
            {
                new Product {
                    Name = productNameForDelete
                },
                new Product {
                    Name = "Phone Samsung"
                },
                new Product {
                    Name = "Phone Nokia"
                },
                new Product {
                    Name = "Phone Iphone"
                },
                new Product {
                    Name = "Tablet Galaxy"
                }
            };

            dbContext.Products.AddRange(products);
            dbContext.SaveChanges();

            var favoriteService = new FavoritesService(dbContext);

            foreach (var product in products.Take(3))
            {
                favoriteService.Add(product.Id, username);
            }

            var productId = products.FirstOrDefault(x => x.Name == productNameForDelete).Id;

            favoriteService.Delete(productId, username);

            var userFavoriteProduxts = dbContext.Users
                                       .FirstOrDefault(x => x.UserName == username)
                                       .FavoriteProducts
                                       .ToList();

            var isProductExist = userFavoriteProduxts.Any(x => x.Product.Name == productNameForDelete);

            Assert.Equal(2, userFavoriteProduxts.Count());
            Assert.False(isProductExist);
        }
        private FavoritesService CreateFavoritesService()
        {
            UserManager <User>      userManagerMock        = CreateUserManagerMock();
            IUserCurrencyRepository userCurrencyRepository = CreateUserCurrencyRepository();
            ICurrencyRepository     currencyRepository     = CreateCurrencyRepositoryMock();
            FavoritesService        favoritesService       = new FavoritesService(userManagerMock, userCurrencyRepository, currencyRepository);

            return(favoritesService);
        }
Beispiel #14
0
 public FavoritesController(
     ArticleService articleService,
     FavoritesService favoritesService,
     UserService userService)
 {
     ArticleService   = articleService;
     FavoritesService = favoritesService;
     UserService      = userService;
 }
        protected void Page_Load(object sender, EventArgs e)
        {
            if (Request["id"] == null && Page.RouteData.Values["saint-id"] == null)
            {
                return;
            }

            var saintId = 0;

            if (Request["id"] != null)
            {
                saintId = Convert.ToInt32(Request["id"]);
            }
            else if (Page.RouteData.Values["saint-id"] != null)
            {
                saintId = Convert.ToInt32(Page.RouteData.Values["saint-id"]);
            }
            else
            {
                return;
            }

            var saintlistService = new SaintService();
            var saintlist        = saintlistService.Find(saintId);

            FeaturedSaint.InnerHtml = saintlist.Name;
            FeastDay.InnerHtml      = saintlist.FeastDay;
            PatronOf.InnerHtml      = saintlist.Patron;
            SaintID.Value           = saintId.ToString();


            BirthDate.InnerHtml     = saintlist.BirthDate;
            DeathDate.InnerHtml     = saintlist.DeathDate;
            SaintBio.InnerHtml      = saintlist.Biography;
            CanonizedDate.InnerHtml = saintlist.CanonizeDate;
            ImagePath.Src           = saintlist.ImagePath;

            if (Auth.Check())
            {
                var service = new FavoritesService();

                if (service.IsSaintAlreadyInFavorites(Auth.user().Id, saintId))
                {
                    AddFav.Attributes.Add("style", "display: none;");
                    RemoveFav.Attributes.Add("style", "display: block;");
                }
                else
                {
                    AddFav.Attributes.Add("style", "display: block;");
                    RemoveFav.Attributes.Add("style", "display: none;");
                }
            }
            else
            {
                RemoveFav.Attributes.Add("style", "display: none;");
            }
        }
Beispiel #16
0
 void UpdateFavoriteSwitch()
 {
     if (FavoritesService.GetIsFavorites(s_poemData.m_key))
     {
         SetText("Text_FavoriteSwitch", LanguageManager.GetContent(LanguageManager.c_defaultModuleKey, "AddToFavorites"));
     }
     else
     {
         SetText("Text_FavoriteSwitch", LanguageManager.GetContent(LanguageManager.c_defaultModuleKey, "RemoveTheFavorite"));
     }
 }
 public ArticlesController(
     ArticleService articleService,
     FavoritesService favoritesService,
     UserService userService,
     CommentsService commentsService)
 {
     ArticleService   = articleService;
     FavoritesService = favoritesService;
     UserService      = userService;
     CommentsService  = commentsService;
 }
        private void Announcement_ChurchAnnouncementPublished(object sender, NotificationEventArgs e)
        {
            var notification = notificationService.Create(e.Notification);

            var favoritesService = new FavoritesService();

            var followers = favoritesService.GetChurchFollowers(e.Id);

            foreach (Tuple <ChurchInfo, User> follower in followers)
            {
                notificationService.CreateUserNotification(notification.Id, follower.Item2.Id);
            }
        }
        public async Task CheckAddingPostToFavourites()
        {
            var options = new DbContextOptionsBuilder <ApplicationDbContext>()
                          .UseInMemoryDatabase(Guid.NewGuid().ToString());
            var mockRepository = new EfDeletableEntityRepository <FavoritePost>(new ApplicationDbContext(options.Options));
            var service        = new FavoritesService(mockRepository);

            await service.FavorAsync("d3946347-0005-45e0-8a02-ad8179d2ece6", "0a9ec75c-0560-4e5b-94d4-c44429bb7379");

            var postFavouritesCount = service.GetCount("d3946347-0005-45e0-8a02-ad8179d2ece6");

            Assert.Equal(1, postFavouritesCount);
        }
Beispiel #20
0
    void OnClickFavoriteSwitch(InputUIOnClickEvent e)
    {
        UpdateFavoriteSwitch();

        if (FavoritesService.GetIsFavorites(s_poemData.m_key))
        {
            FavoritesService.RemoveFavoite(s_poemData.m_key);
        }
        else
        {
            FavoritesService.AddFavorites(s_poemData.m_key);
        }
    }
    void OnClickExercise(InputUIOnClickEvent e)
    {
        Dictionary <string, object> data = new Dictionary <string, object>();

        data.Add("GameType", "FavoritesList");
        data.Add("FavoritesListCount", FavoritesService.GetFavoritesList().Count);
        SDKManager.Log("StartGame", data);

        UIManager.CloseUIWindow(this);

        GameLogic.s_GameModel = GameModel.normal;
        PoemLibrary.SetPoemByFavorite(FavoritesService.GetFavoritesList());
        ApplicationStatusManager.EnterStatus <GameStatus>();
    }
        public void Toggle_ShouldThrowErrorWhenPhotoDoesNotExists()
        {
            var user      = UserCreator.Create("test");
            var photo     = PhotoCreator.Create(user, false, false);
            var favorites = new List <PhotoFavorite>();

            var photosRepo    = DeletableEntityRepositoryMock.Get <Photo>(new List <Photo>());
            var favoritesRepo = EfRepositoryMock.Get <PhotoFavorite>(favorites);

            var       service = new FavoritesService(favoritesRepo.Object, photosRepo.Object);
            Exception ex      = Assert.Throws <AggregateException>(() => service.ToggleAsync(photo.Id, user.Id).Wait());

            Assert.Contains("Photo does not exist", ex.Message);
        }
        public static void OnFavoriteBasicCatholicPrayer(int basicCatholicPrayerId)
        {
            var userId = Auth.user().Id;

            var service = new FavoritesService();

            if (service.IsBasicCatholicPrayerAlreadyInFavorites(userId, basicCatholicPrayerId))
            {
                service.RemoveBasicCatholicPrayer(userId, basicCatholicPrayerId);
            }
            else
            {
                service.AddBasicCatholicPrayer(userId, basicCatholicPrayerId);
            }
        }
Beispiel #24
0
        public static void OnFavoriteOtherCatholicPrayer(int otherCatholicPrayerId)
        {
            var userId = Auth.user().Id;

            var service = new FavoritesService();

            if (service.IsOtherCatholicPrayerAlreadyInFavorites(userId, otherCatholicPrayerId))
            {
                service.RemoveOtherCatholicPrayer(userId, otherCatholicPrayerId);
            }
            else
            {
                service.AddOtherCatholicPrayer(userId, otherCatholicPrayerId);
            }
        }
        private void Review_ChurchReviewPublished(object sender, NotificationEventArgs e)
        {
            var notification = notificationService.Create(e.Notification);

            var favoritesService = new FavoritesService();

            // Get the list of users who 'subscribe' to the church that this review was published on.
            var followers = favoritesService.GetChurchFollowers(e.Id);

            // Create a notifacation instance for every one of the 'subscribers'
            foreach (Tuple <ChurchInfo, User> follower in followers)
            {
                notificationService.CreateUserNotification(notification.Id, follower.Item2.Id);
            }
        }
        public static void OnFavoriteMusicalInspiration(int musicalInspirationId)
        {
            int userId = Auth.user().Id;

            FavoritesService service = new FavoritesService();

            if (service.IsInspirationalMusicAlreadyInFavorites(userId, musicalInspirationId))
            {
                service.RemoveInspirationalMusic(userId, musicalInspirationId);
            }
            else
            {
                service.AddInspirationalMusic(userId, musicalInspirationId);
            }
        }
Beispiel #27
0
        public static void OnFavoriteDevotion(int devotionId)
        {
            var userId = Auth.user().Id;

            var favoritesService = new FavoritesService();

            if (favoritesService.IsDevotionAlreadyInFavorites(userId, devotionId))
            {
                favoritesService.RemoveDevotion(userId, devotionId);
            }
            else
            {
                favoritesService.AddDevotion(userId, devotionId);
            }
        }
Beispiel #28
0
        public static void OnFavoriteBibleVerse(int bibleVerseId)
        {
            var userId = Auth.user().Id;

            var service = new FavoritesService();

            if (service.IsBibleVerseAlreadyInFavorites(userId, bibleVerseId))
            {
                service.RemoveBibleVerse(userId, bibleVerseId);
            }
            else
            {
                service.AddBibleVerse(userId, bibleVerseId);
            }
        }
        public static bool OnFavoriteOrgAnnouncements(int organnouncementId)
        {
            var service = new FavoritesService();

            if (service.IsOrgAnnouncementAlreadyInFavorites(Auth.user().Id, organnouncementId))
            {
                service.RemoveOrgAnnouncement(Auth.user().Id, organnouncementId);
            }
            else
            {
                service.AddOrgAnnouncement(Auth.user().Id, organnouncementId);
            }

            return(true);
        }
        public static void OnFavoriteBibleVerse(int religiousQuoteId)
        {
            var userId = Auth.user().Id;

            var service = new FavoritesService();

            if (service.IsReligiousQuoteAlreadyInFavorites(userId, religiousQuoteId))
            {
                service.RemoveReligiousQuote(userId, religiousQuoteId);
            }
            else
            {
                service.AddReligiousQuote(userId, religiousQuoteId);
            }
        }