Пример #1
0
        //
        // GET: /Article/
        public ActionResult Index()
        {
            var articleService = new ArticleService();
            var articlesList = articleService.GetArticlesList(100, 0);

            return View(articlesList);
        }
Пример #2
0
        public ActionResult Create(Article article)
        {
            try
            {
                if (ModelState.IsValid)
                {
                    var articleService = new ArticleService();
                    articleService.Create(article);
                    return RedirectToAction("Index");
                }

                return View();
            }
            catch
            {
                return View();
            }
        }
Пример #3
0
    protected void Page_Load(object sender, EventArgs e)
    {
        string appDataPath = Path.Combine(System.AppDomain.CurrentDomain.BaseDirectory, "App_Data");
        luceneDBPath = Path.Combine(appDataPath, directoryName);

        if (!IsPostBack)
        {
            DateTime startDate = new DateTime(2008, 1, 1, 0, 0, 0);
            FromTextBox.Text = startDate.ToShortDateString();
            FromTextBox_CalendarExtender.SelectedDate = startDate;
            DateTime now = DateTime.Now;
            ToTextBox.Text = now.ToShortDateString();
            ToTextBox_CalendarExtender.SelectedDate = now;

            ArticleService a = new ArticleService();
            DataList1.DataSource = a.GetArticles();
            DataList1.DataBind();
        }
    }
 /// <summary>
 ///
 /// </summary>
 /// <param name="serivce"></param>
 /// <param name="author"></param>
 /// <param name="catalog"></param>
 /// <param name="pageNumber"></param>
 /// <param name="getNumber"></param>
 /// <param name="calculateCount">第一次查询的时候需要设置为true 去计算ItemCount</param>
 /// <returns></returns>
 private IList <ArticleEntity> getArticlesForAdmin(ArticleService serivce, string author, String catalog, int pageNumber, int getNumber, Boolean calculateCount)
 {
     if (catalog == null)
     {
         if (calculateCount)
         {
             this.ItemCount = serivce.getArticleListByAuthorForNumber(author);
         }
         return(serivce.getArticleListByAuthor(author, pageNumber, PageSize));
     }
     else
     {
         if (calculateCount)
         {
             this.ItemCount = serivce.getArticleListByCatalogAndAuthorForNumber(author, catalog);
         }
         return(serivce.getArticleListByCatalogAndAuthor(author, catalog, pageNumber, getNumber));
     }
 }
 private IList <ArticleEntity> getArticlesForSuperAdmin(ArticleService service, string catalog, int pageNumber, int getNumber, Boolean calculateCount)
 {
     if (catalog == null)
     {
         if (calculateCount)
         {
             this.ItemCount = service.getAllArticleListNumber();
         }
         return(service.getAllArticleList(pageNumber, PageSize));
     }
     else
     {
         if (calculateCount)
         {
             this.ItemCount = service.getArticleListByCatalogNameForNumber(catalog);
         }
         return(service.getArticleListByCatalogName(catalog, pageNumber, getNumber));
     }
 }
Пример #6
0
        public async void GetArticleAsync_ShouldReturnArticleById()
        {
            var options = new DbContextOptionsBuilder <TechAndToolsDbContext>()
                          .UseInMemoryDatabase(databaseName: "GetArticleAsync_ShouldReturnArticleById")
                          .Options;

            TechAndToolsDbContext context = new TechAndToolsDbContext(options);

            IArticleService articleService = new ArticleService(context);

            await this.SeedData(context);

            int articleId = 1;

            var actualResult = await articleService.GetArticleAsync(articleId);

            Assert.NotNull(actualResult);
            Assert.Equal(articleId, actualResult.Id);
        }
        public void ShouldReturnExactlyTwoArticles()
        {
            // Arrange
            var db             = Tests.GetDatabase();
            var articleService = new ArticleService(db);

            var articleData = this.GetArticleData();

            db.AddRange(articleData);
            db.SaveChanges();

            // Act
            var result = articleService.All();

            // Assert
            result
            .Should().AllBeOfType <ArticlesListingsServiceModel>()
            .And.HaveCount(2);
        }
Пример #8
0
        public void GetArticlesPaginationTest()
        {
            var request = new ArticleListRequest(this.connectionSettings.AccessToken, this.connectionSettings.ClientSecret);

            request.Limit = 50;
            request.Page  = 1;

            var articles = new List <ArticleSubset>();
            ListedResourceResponse <ArticleSubset> response;

            do
            {
                response = ArticleService.GetArticlesAsync(request).GetAwaiter().GetResult();
                articles.AddRange(response.Data);
                request.Page = response.MetaInformation.CurrentPage + 1;
            } while (response.MetaInformation.CurrentPage != response.MetaInformation.TotalPages);

            Assert.IsTrue(articles.Count > 10);
        }
        public void Should_Get_Article_By_Invalid_Id_Should_Fail()
        {
            #region Arrange

            var invalidArticleId          = 6;
            IArticleRepository repository = new ArticleRepository();
            IArticleService    service    = new ArticleService(repository);
            var controller = new ArticleController(service);

            #endregion

            #region Act

            controller.Get(invalidArticleId);

            #endregion

            // Assert by [ExpectedException] attr.
        }
Пример #10
0
        public void TestGetArticleByTags()
        {
            //Test getting CSharp will return 2 articles
            var articleService = new ArticleService(_articleRepository.Object);

            IList <ArticleSummary> cSharpArticles = articleService.GetArticles(_cSharp);

            Assert.AreEqual(2, cSharpArticles.Count);

            //Test getting VB will return 1
            IList <ArticleSummary> vbArticles = articleService.GetArticles(_vb);

            Assert.AreEqual(1, vbArticles.Count);

            //Test getting JavaScript returns none
            IList <ArticleSummary> javaScriptArticles = articleService.GetArticles(_javaScript);

            Assert.AreEqual(0, javaScriptArticles.Count);
        }
Пример #11
0
        private static void StartupDomainApplication(ArticleService service, IHostingEnvironment env)
        {
            var services = new ServiceCollection();

            services.AddTransient <RazorViewToStringRenderer>();

            var articles       = service.GetArticles();
            int i              = 1;
            int nombreArticles = articles.Count;

            articles.ForEach(article =>
            {
                DirectoryInfo repertoireDest = CreerRepertoireArticle(article, env);
                CreerContratsFormationsHtml(article, repertoireDest, env);
                _logger.LogInformation($"{i++}/{nombreArticles}: {article.Titre}");
                CopierImages(article, repertoireDest);
                CopierPdfs(article, repertoireDest);
            });
        }
Пример #12
0
        public ActionResult NewPost(string tabId, int parentId, string backendActionCode, bool?boundToExternal)
        {
            var data  = ArticleService.NewForSave(parentId);
            var model = ArticleViewModel.Create(data, tabId, parentId, boundToExternal);

            TryUpdateModel(model);
            model.Validate(ModelState);
            if (ModelState.IsValid)
            {
                try
                {
                    model.Data = ArticleService.Create(model.Data, backendActionCode, boundToExternal, HttpContext.IsXmlDbUpdateReplayAction());

                    // ReSharper disable once PossibleInvalidOperationException
                    PersistFromId(model.Data.Id, model.Data.UniqueId.Value);
                    PersistResultId(model.Data.Id, model.Data.UniqueId.Value);
                    var union = model.Data.AggregatedArticles.Any()
                        ? model.Data.FieldValues.Union(model.Data.AggregatedArticles.SelectMany(f => f.FieldValues))
                        : model.Data.FieldValues;
                    foreach (var fv in union.Where(f => new[] { FieldExactTypes.O2MRelation, FieldExactTypes.M2MRelation, FieldExactTypes.M2ORelation }.Contains(f.Field.ExactType)))
                    {
                        AppendFormGuidsFromIds($"field_{fv.Field.Id}", $"field_uniqueid_{fv.Field.Id}");
                    }

                    return(Redirect("Properties", new
                    {
                        tabId,
                        parentId,
                        id = model.Data.Id,
                        successfulActionCode = backendActionCode,
                        boundToExternal
                    }));
                }
                catch (ActionNotAllowedException nae)
                {
                    ModelState.AddModelError("OperationIsNotAllowedForAggregated", nae);
                    return(JsonHtml("Properties", model));
                }
            }

            return(JsonHtml("Properties", model));
        }
Пример #13
0
        /// <summary>
        /// 文章查询
        /// </summary>
        /// <param name="GroupType">1 资讯,2 笔记,3 网络资源</param>
        /// <param name="page">当前页(1开始)</param>
        /// <param name="rows">每页显示多少条数据</param>
        /// <param name="Title">文章标题</param>
        /// <param name="TypeIds">文章所属分类(,分隔)</param>
        /// <param name="startime">开始时间</param>
        /// <param name="endtime">结束时间</param>
        /// <returns></returns>
        public JsonResult Query(int GroupType = 0, int page = 1, int rows = 20, string Title = "", string TypeIds = "0", string startime = "", string endtime = "")
        {
            DateTime regStartTime;
            DateTime regEndTime;

            if (!DateTime.TryParse(startime, out regStartTime))
            {
                regStartTime = DateTime.MinValue;
            }

            if (!DateTime.TryParse(endtime, out regEndTime))
            {
                regEndTime = DateTime.MaxValue;
            }

            int total = 0;
            Expression <Func <Article, bool> > whereLambada =
                a => (GroupType == 0 || a.GroupType == (GroupEnum)GroupType) &&
                (string.IsNullOrEmpty(Title) || a.Title.Contains(Title)) &&
                (TypeIds == "0" || a.TypeIds == TypeIds || a.TypeIds.IndexOf(TypeIds) == 0) &&
                (startime == string.Empty || a.CreateTime >= regStartTime) &&
                (endtime == string.Empty || a.CreateTime <= regEndTime);

            var articleList = ArticleService.PageLoad(whereLambada, a => new { a.CreateTime }, true, page, rows, out total).ToList().Select(a => new ArticleTemp
            {
                Id          = a.Id,
                Title       = a.Title,
                ArticleType = GetArticleType(a.TypeIds),
                Sort        = a.Sort,
                CreateTime  = a.CreateTime.ToString("yyyy-MM-dd HH:mm"),
                UpdateTime  = a.UpdateTime.ToString("yyyy-MM-dd HH:mm"),
                Status      = a.Status
            });

            var obj = new AjaxResponse <ListData <ArticleTemp> >();

            obj.IsSuccess  = true;
            obj.Data       = new ListData <ArticleTemp>();
            obj.Data.rows  = articleList;
            obj.Data.total = total;
            return(Json(obj));
        }
Пример #14
0
        protected int SetupM2ORelation(CloningMode?cloningMode, DeletingMode?deletingMode)
        {
            if (cloningMode != null || deletingMode != null)
            {
                var field = new EntityField();
                field.FieldId      = 1;
                field.CloningMode  = cloningMode == null ? default(CloningMode) : cloningMode.Value;
                field.DeletingMode = deletingMode == null ? default(DeletingMode) : deletingMode.Value;
                ProductService.Content.Fields.Add(field);
            }

            var referencedArticle = ArticleService.New(ContentId);

            InitializeArticle(referencedArticle);
            ArticleService.Save(referencedArticle);

            var rootArticle = ArticleService.New(ContentId);

            InitializeArticle(rootArticle);
            var fv = new Quantumart.QP8.BLL.FieldValue
            {
                Article = rootArticle, Field = new Quantumart.QP8.BLL.Field {
                    Id = 1, ContentId = ContentId
                }
            };

            fv.Field.Init();
            fv.Field.RelateToContentId = ContentId;
            fv.Field.ExactType         = Quantumart.QP8.Constants.FieldExactTypes.M2ORelation;
            fv.UpdateValue(referencedArticle.Id.ToString());
            rootArticle.FieldValues.Add(fv);
            ArticleService.Save(rootArticle);
            Context.ContentItemIds = new[] { rootArticle.Id };
            ProductService.Article = GetProductM2ORelation(rootArticle.Id);

            ArticleService.ArticleSaved += (s, e) => VerifyArticleOnSave(e.Article);
            Action.Process(Context);

            VerifyTransaction();

            return(rootArticle.Id);
        }
Пример #15
0
        private void LoadExtensionInfo(CategoryInfo currentCatInfo)
        {
            CategoryInfo rootCatInfo = currentCatInfo;

            //获取当前节点的顶级父节点
            //可以是未启用的,因为有的列表就是页面顶部导航不显示,但是左边需要显示
            //不显示已删除的
            var _rootCatInfo = CategoryService.ListUpById(currentCatInfo.Id).Where(p => p.IsDeleted == false).FirstOrDefault();

            if (_rootCatInfo != null)
            {
                rootCatInfo = _rootCatInfo;
            }
            //是否显示子分类的首节点
            //如果是,当前节点更改为子节点
            //只显示启用的以及未删除的
            if (currentCatInfo.IsShowFirstChildNode)
            {
                var firstChildNode = CategoryService.ListByParentId(currentCatInfo.Id).Where(p => (p.IsDeleted == false && p.IsEnabled == true)).FirstOrDefault();
                if (firstChildNode != null)
                {
                    currentCatInfo = firstChildNode;
                }
            }
            ViewBag.RootCategoryInfo    = rootCatInfo;
            ViewBag.CurrentCategoryInfo = currentCatInfo;

            //模板类型
            switch (currentCatInfo.TemplateType)
            {
            case (int)TemplateType.ArticleList:
            case (int)TemplateType.ArticleListWithImage:
                int pageIndex = CECRequest.GetQueryInt("page", 1);
                ViewBag.ArticleList = ArticleService.List(new ArticleSearchSetting
                {
                    PageIndex           = pageIndex,
                    CategoryId          = currentCatInfo.Id,
                    IsOnlyShowPublished = true
                });
                break;
            }
        }
Пример #16
0
        public void CheckRelationProductsDuplicate(ArticleService articleService, string idFieldName, int contentProductsId, int[] relationsIds)
        {
            var servicesFieldName  = GetSettingStringValue(SettingsTitles.SERVICE_FIELD_NAME);
            var relatedProductsIds = articleService.List(contentProductsId, relationsIds, true).Select(x =>
                                                                                                       x.FieldValues.Single(a => a.Field.Name == servicesFieldName))
                                     .Select(s => int.Parse(s.Value)).ToArray();
            var duplicateServices = relatedProductsIds.Where(relId => relatedProductsIds.Count(r => r == relId) > 1).Distinct().ToArray();

            if (duplicateServices.Any())
            {
                var result = new ActionTaskResultMessage()
                {
                    ResourceClass = ResourceClass,
                    ResourceName  = nameof(RemoteValidationMessages.DuplicateRelationsProducts),
                    Parameters    = new object[] { string.Join(",", duplicateServices) }
                };

                Result.AddModelError(GetPropertyName(idFieldName), ToString(result));
            }
        }
Пример #17
0
        void setupView()
        {
            listItems     = ItemService.getItems();
            listArticles  = ArticleService.getArticles();
            listLocations = LocationService.getLocations();
            listLocations.Insert(0, new Location()
            {
                Id = 0, Name = "Warehouse", Items = ItemService.getUnAssignedItems().Where(x => !x.IsDeleted).ToList()
            });



            listJobs = JobService.getJobs();

            CB_Jobs.ItemsSource = null;
            CB_Jobs.ItemsSource = listJobs;

            CB_Locations.ItemsSource = null;
            CB_Locations.ItemsSource = listLocations;
        }
Пример #18
0
        public int DeleteArticleCategoryById(int id)
        {
            // 删除栏目的同时 删除栏目下属的文章
            IArticleCategoryService articleCategoryService = new ArticleCategoryService();

            var articleCategory = articleCategoryService.GetArticleCategoryById(id);

            if (articleCategory != null)
            {
                IArticleService articleService = new ArticleService();
                //WHERE Lft BETWEEN @MyLeft AND @MyRight;
                var all = articleCategoryService.GetAllArticleCategory().Where(s => s.Lft >= articleCategory.Lft && s.Lft <= articleCategory.Rgt);
                foreach (ArticleCategoryInfo articleCategoryInfo in all)
                {
                    articleService.DeleteByCategoryId(articleCategory.Id);
                }
            }

            return(articleCategoryService.Delete(id));
        }
        public ArticleListWindowViewModel(ArticleService articleService, CategoryService categoryService)
        {
            this.articleService = articleService;

            LoadedCommand       = new DelegateCommand(async() => await LoadListAsync());
            ItemSelectedCommand = new DelegateCommand(() =>
            {
                if (SelectedArticle?.Id != null)
                {
                    var window = new ArticleDetailWindow
                    {
                        DataContext = new ArticleDetailWindowViewModel(articleService, categoryService)
                        {
                            OpenArticleId = SelectedArticle.Id
                        }
                    };
                    window.Show();
                }
            });
        }
Пример #20
0
        public async void GetLastThreeArticles_ShouldReturnLastThreeArticlesExceptArticleWithArticleId()
        {
            var options = new DbContextOptionsBuilder <TechAndToolsDbContext>()
                          .UseInMemoryDatabase(databaseName: "GetLastThreeArticles_ShouldReturnLastThreeArticlesExceptArticleWithArticleId")
                          .Options;

            TechAndToolsDbContext context = new TechAndToolsDbContext(options);

            IArticleService articleService = new ArticleService(context);

            await this.SeedData(context);

            int articleId = 1;

            int expectedResult = 3;

            List <ArticleServiceModel> actualResult = await articleService.GetLastThreeArticles(articleId).ToListAsync();

            Assert.Equal(expectedResult, actualResult.Count);
        }
Пример #21
0
        public void GetAllArticlesFromDbSetWrapper()
        {
            // Arrange
            var dbSetWrapperMock = new Mock <IEfDbSetWrapper <Article> >();
            IQueryable <Article> expectedArticles = new List <Article>()
            {
                new Article(),
                new Article()
            }.AsQueryable();

            dbSetWrapperMock.Setup(x => x.All).Returns(expectedArticles);

            ArticleService service = new ArticleService(dbSetWrapperMock.Object);

            // Act
            IQueryable <Article> actualArticles = service.GetAll();

            // Assert
            CollectionAssert.AreEquivalent(expectedArticles, actualArticles);
        }
        public void CallSaveChanges_WhenParamsAreValid()
        {
            // Arrange
            var contextMock        = new Mock <ITravelGuideContext>();
            var factoryMock        = new Mock <IArticleFactory>();
            var commentFactoryMock = new Mock <IArticleCommentFactory>();
            var article            = new Article();

            article.IsDeleted = false;
            var initialValue = article.IsDeleted;
            var service      = new ArticleService(contextMock.Object, factoryMock.Object, commentFactoryMock.Object);

            contextMock.Setup(x => x.Articles.Find(It.IsAny <Guid>())).Returns(article);

            // Act
            service.DeleteArticle(article);

            // Assert
            contextMock.Verify(x => x.SaveChanges(), Times.Once);
        }
        public void ProcessRequest(HttpContext context)
        {
            context.Response.ContentType = "text/plain";
            Article article = new Article()
            {
                Author     = context.Session["CurrentUser"].ToString(),
                Title      = context.Request["articleTitle"].ToString(),
                Content    = HttpUtility.UrlDecode(context.Request["articleContent"].ToString()),
                CreateTime = DateTime.Now
            };

            if (ArticleService.Create(article))
            {
                context.Response.Write("ok");
            }
            else
            {
                context.Response.Write("error");
            }
        }
Пример #24
0
        public ActionResult GetArticleById(int id)
        {
            var article = ArticleService.GetModal(a => a.id.Equals(id));

            if (article == null)
            {
                return(Content("null"));
            }

            var jsonObj = new
            {
                article.id,
                title  = Server.HtmlDecode(article.title),
                from   = Server.HtmlDecode(article.@from),
                author = Server.HtmlDecode(article.author),
                body   = Server.HtmlDecode(article.body)
            };

            return(Json(jsonObj, JsonRequestBehavior.AllowGet));
        }
Пример #25
0
        public void GetAllArticles()
        {
            // Arrange
            var mockedUnitOfWork = new Mock <IUnitOfWork>();
            var mockedRepository = new Mock <IEfGenericRepository <Article> >();

            IEnumerable <Article> expected = new List <Article> {
                new Article()
            };

            mockedRepository.Setup(x => x.GetAll()).Returns(expected);

            var articleService = new ArticleService(mockedRepository.Object, mockedUnitOfWork.Object);

            // Act
            var actual = articleService.GetAllArticles();

            // Assert
            CollectionAssert.AreEquivalent(expected, actual);
        }
Пример #26
0
        public async Task GetSectionItemsByDateAsync_Valid_ResurnResponse()
        {
            var expectedResult = new List <ArticleView>
            {
                new ArticleView
                {
                    Heading = "Title2",
                    Updated = DateTime.Parse("2020-05-02T06:40:13-04:00"),
                    Link    = "https://nyti.ms/title2"
                }
            };
            var articleHttpClientMock = new Mock <IArticleHttpClient>();

            articleHttpClientMock.Setup(x => x.GetItemsAsync("section")).ReturnsAsync(articles);
            var articleService = new ArticleService(articleHttpClientMock.Object);

            var response = await articleService.GetSectionItemsByDateAsync("section", "2020-05-02");

            Assert.AreEqual(SerializeHelper.Serialize(expectedResult), SerializeHelper.Serialize(response));
        }
Пример #27
0
        static void Main()
        {
            List <Article> articles     = ArticleService.DownloadArticlesFromTelex();
            List <string>  jsonArticles = ArticleService.ArticlesToJson(articles);

            Token token = ModexService.ObtainToken().Result;

            File.WriteAllText("token.dat", JsonSerializer.Serialize(token));
            Console.WriteLine("Token obtained!");

            Console.Write("Enter a name for the schema: ");
            string schemaName = Console.ReadLine();

            EntityContainer entityContainer = UploadData(jsonArticles, schemaName, token);

            File.WriteAllText("entities.dat", JsonSerializer.Serialize(entityContainer));

            Console.WriteLine("Process finished");
            Console.ReadKey();
        }
        public void ReturnsArticleByIDNotFound()
        {
            var mockUnit = new Mock <IUnitOfWork>();

            mockUnit.Setup(u => u.ArticlesRepository.GetById(It.IsAny <int>())).ReturnsAsync(new Article());
            ArticleService articleService = new ArticleService(mockUnit.Object);



            using (var context = new ApplicationDbContext(options))
            {
                var http       = new Mock <IHttpContextAccessor>();
                var controller = new ArticlesController(articleService, context, http.Object);
                // Act
                var result = controller.Details(null);
                // Assert

                var viewResult = Assert.IsType <NotFoundResult>(result.Result);
            }
        }
Пример #29
0
        public async Task OnSaveArticleClicked()
        {
            Article.Content = await RichTextEditor.GetContentAsync();

            if (string.IsNullOrEmpty(Article.Id))
            {
                Article.Id = Guid.NewGuid().ToString();
            }

            if (string.IsNullOrEmpty(Id))
            {
                await ArticleService.CreateArticle(Article);
            }
            else
            {
                await ArticleService.UpdateArticle(Article);
            }

            NavigationManager.NavigateTo("articles");
        }
Пример #30
0
        public void CallUnitOfWorkMethodCommitOnce()
        {
            // Arrange
            var  mockedUnitOfWork = new Mock <IUnitOfWork>();
            var  mockedRepository = new Mock <IEfGenericRepository <Article> >();
            Guid articleId        = Guid.NewGuid();
            var  article          = new Article()
            {
                Id = articleId
            };

            mockedRepository.Setup(x => x.GetById(articleId)).Returns(article);
            var articleService = new ArticleService(mockedRepository.Object, mockedUnitOfWork.Object);

            // Act
            articleService.DeleteArticle(articleId.ToString());

            // Assert
            mockedUnitOfWork.Verify(x => x.Commit(), Times.Once);
        }
Пример #31
0
        public void then_sql_exception_should_be_thrown_and_logged()
        {
            using (var uow = new UnitOfWork <IEIndexContext>(_mockContext.Object))
            {
                var mockRepo = new Mock <Repository <Article> >(uow);

                var exception = FormatterServices.GetUninitializedObject(typeof(SqlException)) as SqlException;

                mockRepo.SetupGet(x => x.All).Throws(exception);
                mockRepo.Setup(x => x.AllIncluding(It.IsAny <Expression <Func <Article, object> >[]>())).Throws(exception);

                var mockLog = new Mock <ILog>();
                var sut     = new ArticleService(mockRepo.Object, new Mock <IMapper>().Object, mockLog.Object);

                Assert.Throws <SqlException>(() => sut.GetEntities());
                Assert.Throws <SqlException>(() => sut.GetFullEntities());

                mockLog.Verify(log => log.Error(It.IsAny <string>()), Times.Exactly(2));
            }
        }
Пример #32
0
        public async Task GetAllShouldReturnAllArticlesInCorrectOrder()
        {
            this.SetupSqlite();
            await this.SeedDatabase();

            using var context = new ApplicationDbContext(this.ContextOptions);

            var repository     = new EfDeletableEntityRepository <Article>(context);
            var articleService = new ArticleService(repository);

            var articlesFromDb = await articleService.GetAll().ToListAsync();

            var generatedArticles = this.GetTestArticles();

            Assert.Equal(generatedArticles.Length, articlesFromDb.Count);
            for (var i = 0; i < generatedArticles.Length; i++)
            {
                Assert.Equal(generatedArticles[i].Id, articlesFromDb[articlesFromDb.Count - 1 - i].Id);
            }
        }
Пример #33
0
        public async void GetArticleByIdTest()
        {
            _mock.Setup(a => a.GetArticleInfoAsync(It.IsIn("232"))).Returns(Task.FromResult(_infoList[0]));
            _mock.Setup(a => a.GetArticleInfoAsync(It.IsIn("333"))).Returns(Task.FromResult(_infoList[1]));
            _mock.Setup(a => a.GetArticleInfoAsync(It.IsIn("133"))).Returns(Task.FromResult(_infoList[2]));
            ArticleService   articleService = new ArticleService(_mock.Object);
            ArticleInfoModel result         = await articleService.GetArticleByIdAsync("232");

            Assert.Equal(_infoList[0], result);

            result = await articleService.GetArticleByIdAsync("333");

            Assert.Equal(_infoList[1], result);

            result = await articleService.GetArticleByIdAsync("133");

            Assert.Equal(_infoList[2], result);

            await Assert.ThrowsAsync <NullReferenceException>(async() => { await articleService.GetArticleByIdAsync(null); });
        }
Пример #34
0
 public GroupService(ICommonRepository<ArticleGroup> repository,ArticleService service)
 {
     _repository = repository;
     _service = service;
 }
Пример #35
0
 public static void ToggleToXml()
 {
     _appKernel = new StandardKernel(new ArticleXmlModule());
     _service = null;
 }
Пример #36
0
        public void ToggleToXml(bool needOverrideToggle = false)
        {
            if (needOverrideToggle)
            {
                CurrentToggle = "xml";
            }
            if (!AppKernel.HasModule(typeof (ArticleXmlModule).FullName))
            {
                AppKernel.Load(new ArticleXmlModule());
                AppKernel.Unload(typeof(ArticleDbModule).FullName);
            }
            if (!AppKernel.HasModule(typeof (ArticleGroupXmlModule).FullName))
            {
                AppKernel.Load(new ArticleGroupXmlModule());
                AppKernel.Unload(typeof(ArticleGroupModule).FullName);
            }

            if (AppKernel.HasModule(typeof (ArticleGroupXmlModule).FullName) &&
                AppKernel.HasModule(typeof (ArticleDbModule).FullName))
            {
                //AppKernel.Load(new ArticleXmlModule());
                AppKernel.Unload(typeof(ArticleDbModule).FullName);
            }
            _service = null;
        }
        public void TestAddArticle()
        {
            var articleService = new ArticleService(_articleRepository.Object);

            var article = new ArticleOld(ArticleType.Full, new FullArticleValidator(), new ArticlePublishingRules())
                {
                    Id = Guid.NewGuid()
                };

            Assert.IsNull(articleService.GetArticle(article.Id));

            articleService.SaveArticle(article);

            ArticleOld returnedArticleOld = articleService.GetArticle(article.Id);
            Assert.IsNotNull(returnedArticleOld);
            Assert.AreEqual(article.Id, returnedArticleOld.Id);
        }
        public void TestCountTags()
        {
            var articleService = new ArticleService(_articleRepository.Object);
            var countTags = articleService.CountTags();

            Assert.IsNotNull(countTags);
            Assert.AreEqual(2, countTags.Count);

            Assert.AreEqual(2, countTags[_cSharp]);
            Assert.AreEqual(1, countTags[_vb]);
        }
        public void TestDeleteArticle()
        {
            var articleService = new ArticleService(_articleRepository.Object);

            var article = new ArticleOld(ArticleType.Full, new FullArticleValidator(), new ArticlePublishingRules()) { Id = Guid.NewGuid(), Title = "my new article to be deleted" };
            int articleCount = articleService.GetArticles().Count;

            articleService.SaveArticle(article);
            Assert.AreEqual(articleCount + 1, articleService.GetArticles().Count);

            var testArticle = articleService.GetArticle(article.Id);
            Assert.IsNotNull(testArticle);

            articleService.DeleteArticle(article);
            Assert.AreEqual(articleCount, articleService.GetArticles().Count);
            Assert.IsNull(articleService.GetArticle(article.Id));
        }
        public void TestEditArticle()
        {
            ArticleOld testArticleOld = _articles.FirstOrDefault(a => a.Title.Equals(ArticleTitle));
            Assert.IsNotNull(testArticleOld); //this gets the article with the given title for us to edit.. i.e. we now have the ID.

            var articleService = new ArticleService(_articleRepository.Object);

            var article = articleService.GetArticle(testArticleOld.Id);
            Assert.IsNotNull(article);

            string newTitle = "My New Title";
            Assert.AreNotEqual(testArticleOld.Title, newTitle);
            article.Title = newTitle;
            articleService.SaveArticle(article);

            var newArticle = articleService.GetArticle(testArticleOld.Id);
            Assert.IsNotNull(newArticle);
            Assert.AreEqual(newTitle, newArticle.Title);
        }
        public void TestGetArticle()
        {
            //test will not return an article for random GUID
            Guid unkonwnId = Guid.NewGuid();
            while (_articleRepository.Object.GetAllArticles().FirstOrDefault(a => a.Id.Equals(unkonwnId)) != null)
            {
                unkonwnId = Guid.NewGuid();
            }

            var articleService = new ArticleService(_articleRepository.Object);
            Assert.IsNull(articleService.GetArticle(unkonwnId));

            //test will return an article for known GUID
            Guid knownId = _articleRepository.Object.GetAllArticles().First().Id;
            ArticleOld articleOld = articleService.GetArticle(knownId);
            Assert.IsNotNull(articleOld);
            Assert.AreEqual(knownId, articleOld.Id);
        }
Пример #42
0
        public async Task CreateArticleAsync()
        {
            // arrange
            var unitOfWork = this.CreateMockUnitOfWork();
            var articleService = new ArticleService(unitOfWork, new NullExceptionHandler());

            var request = new ArticleEditDto
            {
                LanguageId = 2,
                Title = "Title",
                Content = "Content",
                Publish = true
            };

            // act
            var result = await this.articleService.CreateArticleAsync(request);

            // assert
            Assert.IsNotNull(result);
            Assert.AreEqual(StatusCode.OK, result.Status);

            var article = result.Article;
            Assert.AreEqual(4, article.ArticleId);
            Assert.AreEqual(8, article.ArticleVersionId);
            Assert.AreEqual("Title", article.Title);
            Assert.AreEqual("Content", article.Content);
        }
        public void TestGetArticleByTags()
        {
            //Test getting CSharp will return 2 articles
            var articleService = new ArticleService(_articleRepository.Object);

            IList<ArticleSummary> cSharpArticles = articleService.GetArticles(_cSharp);
            Assert.AreEqual(2, cSharpArticles.Count);

            //Test getting VB will return 1
            IList<ArticleSummary> vbArticles = articleService.GetArticles(_vb);
            Assert.AreEqual(1, vbArticles.Count);

            //Test getting JavaScript returns none
            IList<ArticleSummary> javaScriptArticles = articleService.GetArticles(_javaScript);
            Assert.AreEqual(0, javaScriptArticles.Count);
        }
Пример #44
0
 public void ShouldSearch()
 {
     var artService = new ArticleService(rep, "http://localhost/fwd/entity/type-article/id-{0}");
     var res = artService.GetBySearchString("Хабр", c => c.ArticleName, 0, 1, "http://localhost/fwd/entity/type-article/id-{0}");
     res.Count().Should(Be.GreaterThan(0));
 }
        public void TestGetArticles()
        {
            int repoArticleCount = _articleRepository.Object.GetAllArticles().Count;

            var articleService = new ArticleService(_articleRepository.Object);

            Assert.AreEqual(repoArticleCount, articleService.GetArticles().Count);
        }
        public void TestGetAllTags()
        {
            var articleService = new ArticleService(_articleRepository.Object);
            IList<Tag> tags = articleService.GetTags();

            Assert.IsNotNull(tags);
            Assert.AreEqual(3, tags.Count);
            Assert.Contains(_cSharp, tags.ToArray());
            Assert.Contains(_vb, tags.ToArray());
            Assert.Contains(_javaScript, tags.ToArray());
        }