/// <summary> /// Adds the specified page to the search index. /// </summary> /// <param name="model">The page to add.</param> /// <exception cref="SearchException">An error occured with the lucene.net IndexWriter while adding the page to the index.</exception> public virtual void Add(PageViewModel model) { try { EnsureDirectoryExists(); StandardAnalyzer analyzer = new StandardAnalyzer(LUCENEVERSION); using (IndexWriter writer = new IndexWriter(FSDirectory.Open(new DirectoryInfo(IndexPath)), analyzer, false, IndexWriter.MaxFieldLength.UNLIMITED)) { Document document = new Document(); document.Add(new Field("id", model.Id.ToString(), Field.Store.YES, Field.Index.ANALYZED)); document.Add(new Field("content", model.Content, Field.Store.YES, Field.Index.ANALYZED)); document.Add(new Field("contentsummary", GetContentSummary(model), Field.Store.YES, Field.Index.NO)); document.Add(new Field("title", model.Title, Field.Store.YES, Field.Index.ANALYZED)); document.Add(new Field("tags", model.SpaceDelimitedTags(), Field.Store.YES, Field.Index.ANALYZED)); document.Add(new Field("createdby", model.CreatedBy, Field.Store.YES, Field.Index.NOT_ANALYZED)); document.Add(new Field("createdon", model.CreatedOn.ToShortDateString(), Field.Store.YES, Field.Index.NOT_ANALYZED)); document.Add(new Field("contentlength", model.Content.Length.ToString(), Field.Store.YES, Field.Index.NO)); writer.AddDocument(document); writer.Optimize(); } } catch (Exception ex) { if (!ApplicationSettings.IgnoreSearchIndexErrors) throw new SearchException(ex, "An error occured while adding page '{0}' to the search index", model.Title); } }
/// <summary> /// Updates the home page item in the cache. /// </summary> /// <param name="item">The updated homepage item.</param> public void UpdateHomePage(PageViewModel item) { if (!_applicationSettings.UseObjectCache) return; _cache.Remove(CacheKeys.HomepageKey()); _cache.Add(CacheKeys.HomepageKey(), item, new CacheItemPolicy()); }
public void PageContent_Constructor_Should_Throw_Exception_When_MarkupConverter_IsNull() { // Arrange PageContent content = new PageContent(); content.Page = new Page(); // Act + Assert PageViewModel model = new PageViewModel(content, null); }
public void empty_constructor_should_fill_property_defaults() { // Arrange + act PageViewModel model = new PageViewModel(); // Assert Assert.That(model.IsCacheable, Is.True); Assert.That(model.PluginHeadHtml, Is.EqualTo("")); Assert.That(model.PluginFooterHtml, Is.EqualTo("")); }
public void IsNew_Should_Be_True_When_Id_Is_Not_Set() { // Arrange PageViewModel model = new PageViewModel(); // Act model.Id = 0; // Assert Assert.That(model.IsNew, Is.True); }
public void Content_Should_Be_Empty_And_Not_Null_When_Set_To_Null() { // Arrange PageViewModel model = new PageViewModel(); // Act model.Content = null; // Assert Assert.That(model.Content, Is.EqualTo(string.Empty)); }
public void VerifyRawTags_With_Ok_Characters_Should_Succeed() { // Arrange PageViewModel model = new PageViewModel(); model.RawTags = "tagone, anothertag, tag-2, code, c++"; // Act ValidationResult result = PageViewModel.VerifyRawTags(model, null); // Assert Assert.That(result, Is.EqualTo(ValidationResult.Success)); }
public void VerifyRawTags_With_Empty_String_Should_Succeed() { // Arrange PageViewModel model = new PageViewModel(); model.RawTags = ""; // Act ValidationResult result = PageViewModel.VerifyRawTags(model, null); // Assert Assert.That(result, Is.EqualTo(ValidationResult.Success)); }
public void VerifyRawTags_With_Bad_Characters_Should_Fail() { // Arrange PageViewModel model = new PageViewModel(); model.RawTags = "&&+some,tags,only,^^,!??malicious,#monkey,would,use"; // Act ValidationResult result = PageViewModel.VerifyRawTags(model, null); // Assert Assert.That(result, Is.Not.EqualTo(ValidationResult.Success)); }
public void CommaDelimitedTags_Should_Return_Tags_In_Csv_Form() { // Arrange PageViewModel model = new PageViewModel(); model.RawTags = "tag1, tag2, tag3"; // Act string joinedTags = model.CommaDelimitedTags(); // Assert Assert.That(joinedTags, Is.EqualTo("tag1,tag2,tag3")); }
// <summary> /// Adds an item to the cache. /// </summary> /// <param name="id">The page's Id.</param> /// <param name="version">The pages content's version.</param> /// <param name="item">The page.</param> public void Add(int id, int version, PageViewModel item) { if (!_applicationSettings.UseObjectCache) return; if (!item.IsCacheable) return; string key = CacheKeys.PageViewModelKey(id, version); _cache.Add(key, item, new CacheItemPolicy()); Log("Added key {0} to cache [Id={1}, Version{2}]", key, id, version); }
public void Post_Should_Add_Page() { // Arrange PageViewModel model = new PageViewModel(); model.Title = "Hello world"; model.RawTags = "tag1, tag2"; model.Content = "Some content"; // Act _pagesController.Post(model); // Assert Assert.That(_pageService.AllPages().Count(), Is.EqualTo(1)); }
/// <summary> /// Adds the page to the database. /// </summary> /// <param name="model">The summary details for the page.</param> /// <returns>A <see cref="PageViewModel"/> for the newly added page.</returns> /// <exception cref="DatabaseException">An databaseerror occurred while saving.</exception> /// <exception cref="SearchException">An error occurred adding the page to the search index.</exception> public PageViewModel AddPage(PageViewModel model) { try { string currentUser = _context.CurrentUsername; Page page = new Page(); page.Title = model.Title; page.Tags = model.CommaDelimitedTags(); page.CreatedBy = AppendIpForDemoSite(currentUser); page.CreatedOn = DateTime.UtcNow; page.ModifiedOn = DateTime.UtcNow; page.ModifiedBy = AppendIpForDemoSite(currentUser); page.ProjectStart = model.ProjectStart; page.ProjectEnd = model.ProjectEnd; page.ProjectEstimatedTime = model.ProjectEstimatedTime; page.ProjectLanguage = model.ProjectLanguage; page.ProjectStatus = model.ProjectStatus; page.orgID = model.orgID; // Double check, incase the HTML form was faked. if (_context.IsAdmin) page.IsLocked = model.IsLocked; PageContent pageContent = Repository.AddNewPage(page, model.Content, AppendIpForDemoSite(currentUser), DateTime.UtcNow, model.ProjectStart, model.ProjectEnd, model.ProjectEstimatedTime, model.ProjectStatus, model.ProjectLanguage, model.orgID); _listCache.RemoveAll(); _pageViewModelCache.RemoveAll(); // completely clear the cache to update any reciprocal links. // Update the lucene index PageViewModel savedModel = new PageViewModel(pageContent, _markupConverter); try { _searchService.Add(savedModel); } catch (SearchException) { // TODO: log } return savedModel; } catch (DatabaseException e) { throw new DatabaseException(e, "An error occurred while adding page '{0}' to the database", model.Title); } }
public void put_should_update_page() { // Arrange PageContent pageContent = AddPage("test", "this is page 1"); PageViewModel viewModel = new PageViewModel(pageContent.Page); viewModel.Title = "New title"; WebApiClient apiclient = new WebApiClient(); // Act WebApiResponse response = apiclient.Put<PageViewModel>("Pages/Put", viewModel); // Assert IPageRepository repository = GetRepository(); Page page = repository.AllPages().FirstOrDefault(); Assert.That(page.Title, Is.EqualTo("New title"), response); }
/// <summary> /// Compares a page version to the previous version. /// </summary> /// <param name="mainVersionId">The id of the version to compare</param> /// <returns>Returns a IEnumerable of two versions, where the 2nd item is the previous version. /// If the current version is 1, or a previous version cannot be found, then the 2nd item will be null.</returns> /// <exception cref="HistoryException">An database error occurred while comparing the two versions.</exception> public IEnumerable<PageViewModel> CompareVersions(Guid mainVersionId) { try { List<PageViewModel> versions = new List<PageViewModel>(); PageContent mainContent = Repository.GetPageContentById(mainVersionId); versions.Add(new PageViewModel(mainContent, _markupConverter)); if (mainContent.VersionNumber == 1) { versions.Add(null); } else { PageViewModel model = _pageViewModelCache.Get(mainContent.Page.Id, mainContent.VersionNumber - 1); if (model == null) { PageContent previousContent = Repository.GetPageContentByPageIdAndVersionNumber(mainContent.Page.Id, mainContent.VersionNumber - 1); if (previousContent == null) { model = null; } else { model = new PageViewModel(previousContent, _markupConverter); _pageViewModelCache.Add(mainContent.Page.Id, mainContent.VersionNumber - 1, model); } } versions.Add(model); } return versions; } catch (ArgumentNullException ex) { throw new HistoryException(ex, "An ArgumentNullException occurred comparing the version history for version id {0}", mainVersionId); } catch (DatabaseException ex) { throw new HistoryException(ex, "A HibernateException occurred comparing the version history for version id {0}", mainVersionId); } }
public ActionResult Index() { // Get the first locked homepage PageViewModel model = PageService.FindHomePage(); if (model == null) { model = new PageViewModel(); model.Title = SiteStrings.NoMainPage_Title; model.Content = SiteStrings.NoMainPage_Label; model.ContentAsHtml = _markupConverter.ToHtml(SiteStrings.NoMainPage_Label).Html; model.CreatedBy = ""; model.CreatedOn = DateTime.UtcNow; model.RawTags = "homepage"; model.ModifiedOn = DateTime.UtcNow; model.ModifiedBy = ""; } return View(model); }
public void addpage_should_not_set_islocked_if_user_is_editor() { // Arrange PageViewModel model = new PageViewModel() { Id = 1, Title = "Homepage", Content = "**Homepage**", RawTags = "1;2;3;", CreatedBy = AdminUsername, CreatedOn = DateTime.UtcNow, IsLocked = true }; SetUserContext(_editorUser); // Act PageViewModel newModel = _pageService.AddPage(model); // Assert Assert.That(newModel.IsLocked, Is.False); }
public void post_should_add_page() { // Arrange PageViewModel page = new PageViewModel() { Title = "Hello", CreatedBy = "admin", CreatedOn = DateTime.UtcNow, Content = "some content", RawTags = "tag1,tag2" }; WebApiClient apiclient = new WebApiClient(); // Act WebApiResponse response = apiclient.Post<PageViewModel>("Pages", page); // Assert IPageRepository repository = GetRepository(); IEnumerable<Page> pages = repository.AllPages(); Assert.That(pages.Count(), Is.EqualTo(1), response); }
public void Put_Should_Update_Page() { // Arrange DateTime version1Date = DateTime.Today.AddDays(-1); // stops the getlatestcontent acting up when add+update are the same time Page page = new Page(); page.Title = "Hello world"; page.Tags = "tag1, tag2"; page.CreatedOn = version1Date; page.ModifiedOn = version1Date; PageContent pageContent = _repositoryMock.AddNewPage(page, "Some content1", "editor", version1Date); PageViewModel model = new PageViewModel(pageContent.Page); model.Title = "New title"; model.Content = "Some content2"; model.ModifiedOn = DateTime.UtcNow; // Act _pagesController.Put(model); // Assert Assert.That(_pageService.AllPages().Count(), Is.EqualTo(1)); PageViewModel actualPage = _pageService.GetById(1, true); Assert.That(actualPage.Title, Is.EqualTo("New title")); Assert.That(actualPage.Content, Is.EqualTo("Some content2")); }
public void new_post_with_invalid_data_should_return_view_and_invalid_modelstate() { // Arrange PageViewModel model = new PageViewModel(); model.Title = ""; // Act _pagesController.ModelState.AddModelError("Title", "You forgot it"); ActionResult result = _pagesController.New(model); // Assert Assert.That(result, Is.TypeOf<ViewResult>(), "ViewResult"); Assert.False(_pagesController.ModelState.IsValid); }
/// <summary> /// Creates a new page in the database. /// </summary> /// <param name="model">The page details.</param> public void Post(PageViewModel model) { _pageService.AddPage(model); }
public ActionResult New(string title = "", string tags = "") { PageViewModel model = new PageViewModel() { Title = title, RawTags = tags, }; model.AllTags = _pageService.AllTags().ToList(); return View("Edit", model); }
private PageViewModel CreatePageViewModel(string createdBy = "admin") { PageViewModel model = new PageViewModel(); model.Title = "my title"; model.Id = 1; model.CreatedBy = createdBy; model.VersionNumber = PageViewModelCache.LATEST_VERSION_NUMBER; return model; }
/// <summary> /// Updates the provided page. /// </summary> /// <param name="model">The summary.</param> /// <exception cref="DatabaseException">An databaseerror occurred while updating.</exception> /// <exception cref="SearchException">An error occurred adding the page to the search index.</exception> public void UpdatePage(PageViewModel model) { try { string currentUser = _context.CurrentUsername; Page page = Repository.GetPageById(model.Id); page.Title = model.Title; page.Tags = model.CommaDelimitedTags(); page.ModifiedOn = DateTime.UtcNow; page.ModifiedBy = AppendIpForDemoSite(currentUser); page.ProjectStart = model.ProjectStart; page.ProjectEnd = model.ProjectEnd; page.ProjectEstimatedTime = model.ProjectEstimatedTime; page.ProjectLanguage = model.ProjectLanguage; page.ProjectStatus = model.ProjectStatus; page.orgID = model.orgID; // A second check to ensure a fake IsLocked POST doesn't work. if (_context.IsAdmin) page.IsLocked = model.IsLocked; Repository.SaveOrUpdatePage(page); // // Update the cache - updating a page is expensive for the cache right now // this could be improved by updating the item in the listcache instead of invalidating it // _pageViewModelCache.Remove(model.Id, 0); if (model.Tags.Contains("homepage")) _pageViewModelCache.RemoveHomePage(); _listCache.RemoveAll(); int newVersion = _historyService.MaxVersion(model.Id) + 1; PageContent pageContent = Repository.AddNewPageContentVersion(page, model.Content, AppendIpForDemoSite(currentUser), DateTime.UtcNow, newVersion, model.ProjectStart, model.ProjectEnd, model.ProjectEstimatedTime, model.ProjectStatus, model.ProjectLanguage, model.orgID); // Update all links to this page (if it has had its title renamed). Case changes don't need any updates. if (model.PreviousTitle != null && model.PreviousTitle.ToLower() != model.Title.ToLower()) { UpdateLinksToPage(model.PreviousTitle, model.Title); } // Update the lucene index PageViewModel updatedModel = new PageViewModel(Repository.GetLatestPageContent(page.Id), _markupConverter); _searchService.Update(updatedModel); } catch (DatabaseException ex) { throw new DatabaseException(ex, "An error occurred updating the page with title '{0}' in the database", model.Title); } }
/// <summary> /// Retrieves the page by its id. /// </summary> /// <param name="id">The id of the page</param> /// <returns>A <see cref="PageViewModel"/> for the page.</returns> /// <exception cref="DatabaseException">An databaseerror occurred while getting the page.</exception> public PageViewModel GetById(int id, bool loadContent = false) { try { PageViewModel pageModel = _pageViewModelCache.Get(id); if (pageModel != null) { return pageModel; } else { Page page = Repository.GetPageById(id); if (page == null) { return null; } else { // If object caching is enabled, ignore the "loadcontent" parameter as the cache will be // used on the second call anyway, so performance isn't an issue. if (ApplicationSettings.UseObjectCache) { pageModel = new PageViewModel(Repository.GetLatestPageContent(page.Id), _markupConverter); } else { if (loadContent) { pageModel = new PageViewModel(Repository.GetLatestPageContent(page.Id), _markupConverter); } else { pageModel = new PageViewModel(page); } } _pageViewModelCache.Add(id, pageModel); return pageModel; } } } catch (DatabaseException ex) { throw new DatabaseException(ex, "An error occurred getting the page with id '{0}' from the database", id); } }
/// <summary> /// Finds the first page with the tag 'homepage'. Any pages that are locked by an administrator take precedence. /// </summary> /// <returns>The homepage.</returns> public PageViewModel FindHomePage() { try { PageViewModel pageModel = _pageViewModelCache.GetHomePage(); if (pageModel == null) { Page page = Repository.FindPagesContainingTag("homepage").FirstOrDefault(x => x.IsLocked == true); if (page == null) { page = Repository.FindPagesContainingTag("homepage").FirstOrDefault(); } if (page != null) { pageModel = new PageViewModel(Repository.GetLatestPageContent(page.Id), _markupConverter); _pageViewModelCache.UpdateHomePage(pageModel); } } return pageModel; } catch (DatabaseException ex) { throw new DatabaseException(ex, "An error occurred finding the tag 'homepage' in the database"); } }
/// <summary> /// Deletes a page from the database. /// </summary> /// <param name="pageId">The id of the page to remove.</param> /// <exception cref="DatabaseException">An databaseerror occurred while deleting the page.</exception> public void DeletePage(int pageId) { try { // Avoid grabbing all the pagecontents coming back each time a page is requested, it has no inverse relationship. Page page = Repository.GetPageById(pageId); // Update the lucene index before we actually delete the page. try { PageViewModel model = new PageViewModel(Repository.GetLatestPageContent(page.Id), _markupConverter); _searchService.Delete(model); } catch (SearchException ex) { Log.Error(ex, "Unable to delete page with id {0} from the lucene index", pageId); } IList<PageContent> children = Repository.FindPageContentsByPageId(pageId).ToList(); for (int i = 0; i < children.Count; i++) { Repository.DeletePageContent(children[i]); } Repository.DeletePage(page); // Remove everything for now, to avoid reciprocal link issues _listCache.RemoveAll(); _pageViewModelCache.RemoveAll(); } catch (DatabaseException ex) { throw new DatabaseException(ex, "An error occurred while deleting the page id {0} from the database", pageId); } }
public ActionResult New(PageViewModel model) { if (!ModelState.IsValid) return View("Edit", model); model = _pageService.AddPage(model); return RedirectToAction("Index", "Wiki", new { id = model.Id }); }
/// <summary> /// Updates an existing page. /// </summary> /// <param name="model">The page details, which should contain a valid ID.</param> public void Put(PageViewModel model) { _pageService.UpdatePage(model); }
public void new_post_should_return_redirectresult_and_call_pageservice() { // Arrange PageViewModel model = new PageViewModel(); model.RawTags = "newtag1,newtag2"; model.Title = "New page title"; model.Content = "*Some new content here*"; _pageServiceMock.Setup(x => x.AddPage(model)).Returns(() => { _pageRepository.Pages.Add(new Page() { Id = 50, Title = model.Title, Tags = model.RawTags }); _pageRepository.PageContents.Add(new PageContent() { Id = Guid.NewGuid(), Text = model.Content }); model.Id = 50; return model; }); // Act ActionResult result = _pagesController.New(model); // Assert Assert.That(result, Is.TypeOf<RedirectToRouteResult>(), "RedirectToRouteResult not returned"); RedirectToRouteResult redirectResult = result as RedirectToRouteResult; Assert.NotNull(redirectResult, "Null RedirectToRouteResult"); Assert.That(redirectResult.RouteValues["action"], Is.EqualTo("Index")); Assert.That(redirectResult.RouteValues["controller"], Is.EqualTo("Wiki")); Assert.That(_pageRepository.Pages.Count, Is.EqualTo(1)); _pageServiceMock.Verify(x => x.AddPage(model)); }