public async Task GetAllArticles_WithInitialDataOrderedByAuthorNameAscending_ShouldReturnCorrectResult() { string errorMessagePrefix = "ArticlesService Method GetAllArticlesByAuthorNameAscending() does not work properly."; var context = CDGBulgariaInmemoryFactory.InitializeContext(); await SeedData(context); this.articlesService = new ArticlesService(context); List <ArticleServiceModel> actualResults = await this.articlesService.GetAllArticles("authorname-a-to-z").ToListAsync(); List <ArticleServiceModel> expectedResults = context.Articles.OrderBy(a => a.Author.FullName.ToLower()).To <ArticleServiceModel>().ToList(); for (int i = 0; i < expectedResults.Count; i++) { var expectedEntry = expectedResults[i]; var actualEntry = actualResults[i]; Assert.True(expectedEntry.Title == actualEntry.Title, errorMessagePrefix + " " + "Title is not returned properly"); Assert.True(expectedEntry.Content == actualEntry.Content, errorMessagePrefix + " " + "Content is not returned properly"); Assert.True(expectedEntry.AuthorId == actualEntry.AuthorId, errorMessagePrefix + " " + "AuthorId is not returned properly"); Assert.True(expectedEntry.Author.FullName.ToLower() == actualEntry.Author.FullName.ToLower(), errorMessagePrefix + " " + "AuthorFullName is not returned properly"); } }
public JsonResult GetModelWithCategory(long id) { ArticleWithCategory result = new ArticleWithCategory(); Articles model = new Articles(); ArticlesService Article = new ArticlesService(); var entity = Article.Reposity.FirstOrDefault(id); if (entity != null) { model = entity; } else { model.UpdateTime = DateTime.Now; } CategoriesService Category = new CategoriesService(); CategoriesController cateCtrl = new CategoriesController(); var lists = Category.Reposity.GetPageList(1, 0, (o => o.TenantId == TenantId)); result.Article = Mapper.Map <Dto.ArticleInput>(model); result.Category = cateCtrl.GetCategoryTree(TenantId); return(Json(result)); }
public async Task CheckUpdatingArticleAsync() { ApplicationDbContext db = GetDb(); var repository = new EfDeletableEntityRepository <Article>(db); var service = new ArticlesService( repository, this.commentsRepository.Object, this.clientArticleLikesRepository.Object, this.cloudinaryService.Object); string articleId = await this.GetArticleAsync(service); var pictureNew = this.mockPicture.Object; await service.UpdateAsync("new title", "content test article", "2", pictureNew, articleId); var updatedResult = await repository .All() .FirstOrDefaultAsync(a => a.Id == articleId); var getPictureUrl = await service.GetPictureUrlAsync(articleId); Assert.Same("new title", updatedResult.Title); Assert.Same("content test article", updatedResult.Content); Assert.Same("2", updatedResult.CategoryId); Assert.Same(getPictureUrl, updatedResult.Picture); Assert.Same(this.stylist.Id, updatedResult.StylistId); }
public IActionResult GetDetailJS(int id) { string ControllerName = this.ControllerContext.RouteData.Values["controller"].ToString(); var Item = ArticlesService.GetItem(id, API.Models.Settings.SecretId + ControllerName); return(Json(Item)); }
public void GetById_ReturnCorrectArticle() { // Arrange var context = this.ServiceProvider.GetRequiredService <WmipDbContext>(); var article1 = new Article { Id = 1, Title = "ar1", Ratings = new List <Rating>() }; var article2 = new Article { Id = 2, Title = "art2", Ratings = new List <Rating>() }; var article3 = new Article { Id = 3, Title = "art3", Ratings = new List <Rating>() }; context.Articles.AddRange(article1, article2, article3); context.SaveChanges(); var articlesService = new ArticlesService(context); // Act var result = articlesService.GetById(1); var resultDto = articlesService.GetById(1, ""); //Assert Assert.Equal("ar1", result.Title); Assert.Equal("ar1", resultDto.Title); Assert.Equal(RatingType.Neutral, resultDto.CurrentUserRating); }
public void GetLatest_ReturnsCorrectArticles() { // Arrange var context = this.ServiceProvider.GetRequiredService <WmipDbContext>(); var article1 = new Article { Id = 1, Title = "ar1", User = new User { UserName = "******" }, Ratings = new List <Rating>(), CreatedOn = DateTime.UtcNow.AddDays(-1) }; var article2 = new Article { Id = 2, Title = "art2", User = new User { UserName = "******" }, Ratings = new List <Rating>(), CreatedOn = DateTime.UtcNow.AddDays(-2) }; var article3 = new Article { Id = 3, Title = "art3", User = new User { UserName = "******" }, Ratings = new List <Rating>(), CreatedOn = DateTime.UtcNow.AddDays(1) }; context.Articles.AddRange(article1, article2, article3); context.SaveChanges(); var articlesService = new ArticlesService(context); // Act var results = articlesService.GetLatest(1, "aaa"); //Assert Assert.Single(results); Assert.Equal(3, results.First().Id); }
public void Test() { //所有的业务逻辑都是通过调用数据仓储服务Reposity,写在Controller里,如下示例: //定义一个数据仓储服务,它将继承数据仓储Reposity的所有增删查改方法 CategoriesService Categ = new CategoriesService(); //新建对象,通常是定义一个DTO对象,然后将其映射成真实的模型 Categories obj = new Categories(); obj.CategoryIndex = "News"; obj.CategoryName = "News"; obj.Childs = 0; obj.Layout = "Articles"; obj.TenantId = 1; //调用数据仓储服务Reposity的Insert方法 Categ.Reposity.Insert(obj); //调用数据仓储服务Reposity的同步方法GetAllList var result = Categ.Reposity.GetAllList(); //调用数据仓储服务Reposity的异步方法GetAllListAsync Task.Run(async() => { var lists = await Categ.Reposity.GetAllListAsync(); }); ArticlesService Article = new ArticlesService(); //调用Service自身的函数 var articleList = Article.GetArticleWithCate(1, 10, (A => A.CategoryId == 1)); //Mapper.Initialize(x => x.CreateMap<Articles, Dto.Articles>()); //var lists = Mapper.Map<ResultDto<List<Dto.Articles>>>(result); }
public async Task CkeckIfDeleteAsyncFindsArticleObjectInDB() { var options = new DbContextOptionsBuilder <ElectricTravelDbContext>() .UseInMemoryDatabase(databaseName: "ArticlesTestDb").Options; using var dbContext = new ElectricTravelDbContext(options); using var repo = new EfDeletableEntityRepository <Article>(dbContext); var service = new ArticlesService(repo); var userId = "stefkaasd"; var articleToAdd = new Article { ShortDescription = "asdasdasd", Content = "asdasdadasd", CreatedById = userId, Title = "asdasasd", }; await repo.AddAsync(articleToAdd); await repo.SaveChangesAsync(); var id = articleToAdd.Id; var article = await dbContext.Articles .FirstOrDefaultAsync(x => x.Id == id && x.CreatedById == userId); Assert.NotNull(article); }
public void GetAllOrderedByDate_ReturnsItemsInCorrectOrder() { // Arrange var context = this.ServiceProvider.GetRequiredService <WmipDbContext>(); var article1 = new Article { Id = 1, Title = "ar1", User = new User { UserName = "******" }, Ratings = new List <Rating>() }; var article2 = new Article { Id = 2, Title = "art2", User = new User { UserName = "******" }, Ratings = new List <Rating>() }; var article3 = new Article { Id = 3, Title = "art3", User = new User { UserName = "******" }, Ratings = new List <Rating>() }; context.Articles.AddRange(article1, article2, article3); context.SaveChanges(); var articlesService = new ArticlesService(context); // Act var result = articlesService.GetAllOrderedByDate("aaa").ToList(); //Assert Assert.Equal(3, result.Count); }
public async Task GetAllArticles_WithInitialData_ShouldReturnCorrectResult() { string errorMessagePrefix = "ArticlesService Method GetAllArticles() does not work properly."; var context = MyLifeStyleInmemoryFactory.InitializeContext(); await SeedData(context); this.articlesService = new ArticlesService(context); IEnumerable <ArticleServiceModel> actualResultsEnumerable = await this.articlesService.GetAllArticles <ArticleServiceModel>(); List <ArticleServiceModel> actualResults = actualResultsEnumerable.ToList(); List <ArticleServiceModel> expectedResults = context.Articles.OrderByDescending(x => x.Publication.CreatedOn).To <ArticleServiceModel>().ToList(); for (int i = 0; i < expectedResults.Count; i++) { var expectedEntry = expectedResults[i]; var actualEntry = actualResults[i]; Assert.True(expectedEntry.PublicationTitle == actualEntry.PublicationTitle, errorMessagePrefix + " " + "Title is not returned properly"); Assert.True(expectedEntry.Description == actualEntry.Description, errorMessagePrefix + " " + "Description is not returned properly"); Assert.True(expectedEntry.CategoryId == actualEntry.CategoryId, errorMessagePrefix + " " + "CategoryId is not returned properly"); Assert.True(expectedEntry.UserId == actualEntry.UserId, errorMessagePrefix + " " + "UserId is not returned properly"); } }
public HomeController() { _artilesService = new ArticlesService(); _topicService = new TopicService(); _pictureService = new PictureService(); _configService = new ConfigService(); }
public async Task CheckingIfClientLikeTheArticleAsync() { ApplicationDbContext db = GetDb(); var repository = new EfDeletableEntityRepository <Article>(db); var clientArticleLikesRepository = new EfRepository <ClientArticleLike>(db); var service = new ArticlesService( repository, this.commentsRepository.Object, clientArticleLikesRepository, this.cloudinaryService.Object); string articleId = await this.GetArticleAsync(service); var likeCase = await service.LikeArticleAsync(articleId, this.client.Id); var isFavourite = await service.CheckFavouriteArticlesAsync(articleId, this.client.Id); var dislikeCase = await service.LikeArticleAsync(articleId, this.client.Id); Assert.True(likeCase); Assert.True(isFavourite); Assert.True(!dislikeCase); }
public async Task TestGetByIdMethod() { MapperInitializer.InitializeMapper(); var context = ApplicationDbContextInMemoryFactory.InitializeContext(); var articleRepository = new EfDeletableEntityRepository <Article>(context); var articlesService = new ArticlesService(articleRepository); var articlesId = new List <int>(); var inputModel = new CreateArticleViewModel { ImgUrl = $"TT{2}{2 * 2}asd", Content = $"Ten{2}{2 * 2}", Title = $"Article{2}", }; var id = await articlesService.CreateAsync(inputModel, "2"); var articleId = articleRepository.All().First(x => x.Id == id); var article = articlesService.GetById <IndexArticleViewModel>(id); Assert.True(article != null); Assert.True(article.Id == id); }
public ActionResult Detail(long id) { ArticlesService article = new ArticlesService(); var model = article.Reposity.Get(id); return(View(model)); }
public ActionResult UpdateFeaturedHome([FromQuery] string Ids, Boolean FeaturedHome) { string ControllerName = this.ControllerContext.RouteData.Values["controller"].ToString() + "_" + HttpContext.Request.Headers["UserName"]; Articles item = new Articles() { Id = Int32.Parse(MyModels.Decode(Ids, API.Models.Settings.SecretId + ControllerName).ToString()), FeaturedHome = FeaturedHome }; try { if (item.Id > 0) { item.CreatedBy = int.Parse(HttpContext.Request.Headers["Id"]); item.ModifiedBy = int.Parse(HttpContext.Request.Headers["Id"]); dynamic UpdateFeatured = ArticlesService.UpdateFeaturedHome(item); TempData["MessageSuccess"] = "Cập nhật Featured Home thành công"; return(Json(new MsgSuccess())); } else { TempData["MessageError"] = "Cập nhật Featured Home Không thành công"; return(Json(new MsgError())); } } catch { TempData["MessageSuccess"] = "Cập nhật Featured không thành công"; return(Json(new MsgError())); } }
public IActionResult Index([FromQuery] SearchArticles dto) { int TotalItems = 0; string ControllerName = this.ControllerContext.RouteData.Values["controller"].ToString() + "_" + HttpContext.Request.Headers["UserName"]; dto.IdCoQuan = int.Parse(HttpContext.Request.Headers["IdCoQuan"]); ArticlesModel data = new ArticlesModel() { SearchData = dto }; data.ListItems = ArticlesService.GetListPagination(data.SearchData, API.Models.Settings.SecretId + ControllerName); data.ListItemsDanhMuc = CategoriesArticlesService.GetListItems(); data.ListItemsAuthors = API.Areas.Admin.Models.USUsers.USUsersService.GetListItemsAuthor(4); data.ListItemsCreatedBy = API.Areas.Admin.Models.USUsers.USUsersService.GetListItemsAuthor(3); data.ListItemsStatus = ArticlesService.GetListItemsStatus(); if (data.ListItems != null && data.ListItems.Count() > 0) { TotalItems = data.ListItems[0].TotalRows; } HttpContext.Session.SetString("STR_Action_Link_" + ControllerName, Request.QueryString.ToString()); data.Pagination = new Models.Partial.PartialPagination() { CurrentPage = data.SearchData.CurrentPage, ItemsPerPage = data.SearchData.ItemsPerPage, TotalItems = TotalItems, QueryString = Request.QueryString.ToString() }; return(View(data)); }
public void DontShowUnapprovedArticles() { Mock <IImagesService> imagesServiceMock = new Mock <IImagesService>(); imagesServiceMock .Setup(ls => ls.UploadImageAsync(new StreamMock())) .Returns(Task.FromResult("url")); using (ApplicationDbContext dbContext = serviceProvider.GetService <ApplicationDbContext>()) { Article article = new Article { Title = "zeroViewsArticle", Content = "testContent", }; dbContext.Articles.Add(article); dbContext.SaveChangesAsync().GetAwaiter().GetResult(); ArticlesService articlesService = new ArticlesService(dbContext, serviceProvider.GetService <IMapper>(), serviceProvider.GetService <IConfiguration>(), imagesServiceMock.Object); CarWashPOI.ViewModels.Articles.ArticlesIndexOutputModel resultFromService = articlesService.GetArticlesAsync(0, 2, "views").GetAwaiter().GetResult(); Assert.True(resultFromService.Articles.Count() == 0); } }
public async Task GetArticlesByUser() { var articleService = new ArticlesService(BaseUri, HttpClient); var articles = await articleService.GetArticlesByUserAsync("ben"); Assert.IsTrue(articles.Any()); }
public ActionResult DeleteItem(string Id) { string ControllerName = this.ControllerContext.RouteData.Values["controller"].ToString() + "_" + HttpContext.Request.Headers["UserName"]; Articles model = new Articles() { Id = Int32.Parse(MyModels.Decode(Id, API.Models.Settings.SecretId + ControllerName).ToString()) }; try { if (model.Id > 0) { model.CreatedBy = int.Parse(HttpContext.Request.Headers["Id"]); model.ModifiedBy = int.Parse(HttpContext.Request.Headers["Id"]); ArticlesService.DeleteItem(model); TempData["MessageSuccess"] = "Xóa thành công"; return(Json(new MsgSuccess())); } else { TempData["MessageError"] = "Xóa Không thành công"; return(Json(new MsgError())); } } catch { TempData["MessageSuccess"] = "Xóa không thành công"; return(Json(new MsgError())); } }
public IActionResult SaveItem(string Id = null) { ArticlesModel data = new ArticlesModel(); string ControllerName = this.ControllerContext.RouteData.Values["controller"].ToString() + "_" + HttpContext.Request.Headers["UserName"]; int IdDC = Int32.Parse(MyModels.Decode(Id, API.Models.Settings.SecretId + ControllerName).ToString()); data.SearchData = new SearchArticles() { CurrentPage = 0, ItemsPerPage = 10, Keyword = "" }; data.ListItemsDanhMuc = CategoriesArticlesService.GetListItems(); data.ListItemsAuthors = API.Areas.Admin.Models.USUsers.USUsersService.GetListItemsAuthor(4); data.ListItemType = ArticlesService.GetListItemsType(); Articles Item = new Articles() { PublishUp = DateTime.Now, PublishUpShow = DateTime.Now.ToString("dd/MM/yyyy"), Status = true }; if (IdDC > 0) { Item = ArticlesService.GetItem(IdDC, API.Models.Settings.SecretId + ControllerName); } data.Item = Item; return(View(data)); }
public async Task GetArticle() { var articleService = new ArticlesService(BaseUri, HttpClient); var article = await articleService.GetArticleAsync(5); Assert.IsNotNull(article); }
public IActionResult SaveItem(string Id = null, int IdCoQuan = 1) { MenusModel data = new MenusModel(); string ControllerName = this.ControllerContext.RouteData.Values["controller"].ToString(); int IdDC = Int32.Parse(MyModels.Decode(Id, API.Models.Settings.SecretId + ControllerName).ToString()); data.SearchData = new SearchMenus() { CurrentPage = 0, ItemsPerPage = 10, Keyword = "", IdCoQuan = IdCoQuan }; data.ListItemsArticle = ArticlesService.GetListStaticArticle(); data.ListType = MenusService.GetListType(); data.ListCategoriesArticles = CategoriesArticlesService.GetList(); data.ListCategoriesProducts = ProductsCategoriesService.GetList(); data.ListItemsMenus = MenusService.GetListItems(true, IdCoQuan); if (IdDC == 0) { data.Item = new Menus(); } else { data.Item = MenusService.GetItem(IdDC, API.Models.Settings.SecretId + ControllerName); } return(View(data)); }
public async Task TestGetArticlesByPageMethod() { var context = ApplicationDbContextInMemoryFactory.InitializeContext(); var articleRepository = new EfDeletableEntityRepository <Article>(context); var articlesService = new ArticlesService(articleRepository); for (int i = 0; i < 10; i++) { var inputModel = new CreateArticleViewModel { ImgUrl = $"TT{i}{i * 2}asd", Content = $"Ten{i}{i * 2}", Title = $"Article{i}", }; await articlesService.CreateAsync(inputModel, i.ToString()); } var result1 = articlesService.GetArticlesByPage <IndexArticleViewModel>(5, 5); var result2 = articlesService.GetArticlesByPage <IndexArticleViewModel>(5, 0); Assert.Equal(5, result2.Count()); Assert.Equal(5, result1.Count()); }
public async Task ChecksIfGetArticleByIdReturnsCorrectResult() { var options = new DbContextOptionsBuilder <ElectricTravelDbContext>() .UseInMemoryDatabase(databaseName: "ArticlesTestDb").Options; using var dbContext = new ElectricTravelDbContext(options); var user = new ElectricTravelUser { UserName = "******", }; var articleToAdd = new Article { ShortDescription = "asdasd", Content = "asdasdad", CreatedBy = user, Title = "asdas", }; dbContext.Users.Add(user); dbContext.Articles.Add(articleToAdd); dbContext.SaveChanges(); using var repo = new EfDeletableEntityRepository <Article>(dbContext); var service = new ArticlesService(repo); var article = await service.GetArticleById <ArticleViewModel>(articleToAdd.Id); Assert.NotNull(article); }
public UserOwnsArticle(UsersService userService, ArticlesService articlesService, IHttpContextAccessor httpContextAccessor) { _userService = userService; _articlesService = articlesService; _httpContextAccessor = httpContextAccessor; }
public async Task GetArticlesByTag() { var articleService = new ArticlesService(BaseUri, HttpClient); var articles = await articleService.GetArticlesByTagAsync("react"); Assert.IsNotNull(articles); Assert.IsTrue(articles.All(a => a.TagList.Contains("react", StringComparer.OrdinalIgnoreCase))); }
public JsonResult GetLists(int page, int pageSize) { using (ArticlesService Article = new ArticlesService()) { var result = Article.Reposity.GetPageList(page, pageSize); return(Json(result)); } }
public JsonResult GetLists(int page, int pageSize) { ArticlesService Article = new ArticlesService(); var result = Article.GetListOrderByTime(page, pageSize, (o => o.TenantId == TenantId)); var lists = Mapper.Map <ResultDto <List <Dto.ArticleDto> > >(result); return(Json(lists)); }
private async Task <string> GetArticleAsync(ArticlesService service) { var picture = this.mockPicture.Object; var articleId = await service.CreateAsync("title", "content test article", this.category.Id, picture, this.stylist.Id); return(articleId); }
public JsonResult InsertOrUpdate(SignUpBespeak input) { Studio.Dto.ResultDto <SignUpBespeak> result = new Studio.Dto.ResultDto <SignUpBespeak>(); using (SignUpBespeakService subkS = new SignUpBespeakService()) { try { ArticlesService articleS = new ArticlesService(); var article = articleS.Reposity.Get(input.ActvID); if (article != null) { if (article.SignUpNums < article.LimitSignUp || article.LimitSignUp == 0) { if (article.SignUpEndTime != null && article.SignUpEndTime.Value < DateTime.Now) { result.code = 103; } else { var ishas = subkS.Reposity.GetPageList(1, 0, (o => o.UserName == input.UserName && o.ActvID == input.ActvID)).total; if (ishas > 0) { result.code = 101; result.message = "Cannot repeat or make an appointment"; } else { if (input.Id == 0) { input.TenantId = tenant.Id; input.CreationTime = DateTime.Now; } input.MemberName = Member != null ? Member.UserName : ""; var data = subkS.Reposity.InsertOrUpdate(input); article.SignUpNums += 1; articleS.Reposity.Update(article); result.code = 100; result.message = "success"; } } } else { result.code = 102; } } } catch (Exception ex) { result.code = 500; result.message = ex.Message; } return(Json(result)); } }
static ArticlesController() { VKAppId = ConfigurationManager.AppSettings["social:VKAppId"]; FBAppId = ConfigurationManager.AppSettings["social:FBAppId"]; articlesService = new ArticlesService(); }
public ArticlesController() { service = new ArticlesService(); }