Inheritance: Controller
コード例 #1
0
        /// <summary>
        /// Render the first page which has this tag. Admin locked pages have priority.
        /// </summary>
        /// <param name="tag">the tagname</param>
        /// <returns>html</returns>
        /// <example>
        /// usage:   @Html.RenderPageByTag("secondMenu")
        /// </example>
        public static MvcHtmlString RenderPageByTag(this HtmlHelper helper, string tag)
        {
            string html = "";

            ControllerBase controller     = helper.ViewContext.Controller as ControllerBase;
            WikiController wikiController = controller as WikiController;

            if (wikiController != null)
            {
                PageService pageService = wikiController.PageService;

                IEnumerable <PageViewModel> pages = pageService.FindByTag(tag);
                if (pages.Count() > 0)
                {
                    // Find the page, first search for a locked page.
                    PageViewModel model = pages.FirstOrDefault(h => h.IsLocked);
                    if (model == null)
                    {
                        model = pages.FirstOrDefault();
                    }

                    if (model != null)
                    {
                        html = model.ContentAsHtml;
                    }
                }
            }

            return(MvcHtmlString.Create(html));
        }
コード例 #2
0
        public void Setup()
        {
            // WikiController setup (use WikiController as it's the one typically used by views)
            _container = new MocksAndStubsContainer();

            _applicationSettings = _container.ApplicationSettings;
            _context             = _container.UserContext;
            _repository          = _container.Repository;
            _pluginFactory       = _container.PluginFactory;
            _settingsService     = _container.SettingsService;
            _userService         = _container.UserService;
            _historyService      = _container.HistoryService;
            _pageService         = _container.PageService;

            _wikiController = new WikiController(_applicationSettings, _userService, _pageService, _context, _settingsService);
            _wikiController.SetFakeControllerContext("~/wiki/index/1");

            // HtmlHelper setup
            var viewDataDictionary = new ViewDataDictionary();

            _viewContext = new ViewContext(_wikiController.ControllerContext, new Mock <IView>().Object, viewDataDictionary, new TempDataDictionary(), new StringWriter());
            var mockViewDataContainer = new Mock <IViewDataContainer>();

            mockViewDataContainer.Setup(v => v.ViewData).Returns(viewDataDictionary);

            _htmlHelper = new HtmlHelper(_viewContext, mockViewDataContainer.Object);
        }
コード例 #3
0
        public async Task PatchWiki400TestAsync(string wikiURL)
        {
            string dbString = Guid.NewGuid().ToString();

            //ARRANGE
            using var context = InMemoryDbContextFactory.GetViewzDbContext(dbString);
            IMdToHtmlAndContentsFactory factory = new MdToHtmlAndContentsFactory();
            var wrepo           = new WikiRepositoryStoring(context, factory);
            var prepo           = new PageRepositoryStoring(context, factory);
            var wiki_controller = new WikiController(wrepo, prepo, w_logger);

            var WIKI = await context.Wiki.Where(w => w.Url == wikiURL).SingleOrDefaultAsync();

            //ACT
            var status = await wiki_controller.PatchAsync(wikiURL, new ViewzApi.Models.Wiki());

            if (WIKI != null)
            {
                //ASSERT
                Assert.IsType <BadRequestObjectResult>(status);
            }
            else
            {
                //ASSERT
                Assert.IsType <BadRequestObjectResult>(status);
            }
        }
コード例 #4
0
        public void Should_Have_304_Http_Status_Code_If_Response_Has_Modified_Since_Header_Matching_Page_Modified_Date()
        {
            // The file date and the browser date always match for a 304 status, the browser will never send back a more recent date,
            // i.e. "Has the file changed since this date I've stored for the last time it was changed?"
            // and *not* "has the file changed since the time right now?".

            // Arrange
            BrowserCacheAttribute attribute = new BrowserCacheAttribute();

            attribute.SettingsService = GetSettingsService();

            WikiController        controller    = CreateWikiController(attribute);
            ResultExecutedContext filterContext = CreateContext(controller);

            // (page modified date is set in CreateWikiController)
            filterContext.HttpContext.Request.Headers.Add("If-Modified-Since", DateTime.Today.ToString("r"));

            // Act
            attribute.OnResultExecuted(filterContext);

            // Assert
            HttpStatusCodeResult result = filterContext.Result as HttpStatusCodeResult;

            Assert.That(filterContext.HttpContext.Response.StatusCode, Is.EqualTo(304));
            Assert.That(result.StatusCode, Is.EqualTo(304));
            Assert.That(result.StatusDescription, Is.EqualTo("Not Modified"));
        }
コード例 #5
0
        public async Task PatchWiki204TestAsync(string wikiURL)
        {
            string dbString = Guid.NewGuid().ToString();

            //ARRANGE
            using var context = InMemoryDbContextFactory.GetViewzDbContext(dbString);
            IMdToHtmlAndContentsFactory factory = new MdToHtmlAndContentsFactory();
            var wrepo           = new WikiRepositoryStoring(context, factory);
            var prepo           = new PageRepositoryStoring(context, factory);
            var wiki_controller = new WikiController(wrepo, prepo, w_logger);
            var wiki            = new ViewzApi.Models.Wiki()
            {
                PageName    = "I'm Hungry",
                Description = "This is a description"
            };

            var WIKI = await context.Wiki.Where(w => w.Url == wikiURL).SingleOrDefaultAsync();

            //ACT
            var status = await wiki_controller.PatchAsync(wikiURL, wiki);

            if (WIKI != null)
            {
                //ASSERT
                Assert.IsType <NoContentResult>(status);
            }
            else
            {
                Assert.IsType <NotFoundResult>(status);
            }
        }
コード例 #6
0
        public async Task PostWikiTestAsync(string wikiURL)
        {
            string dbString = Guid.NewGuid().ToString();

            //ARRANGE
            using var context = InMemoryDbContextFactory.GetViewzDbContext(dbString);
            IMdToHtmlAndContentsFactory factory = new MdToHtmlAndContentsFactory();
            var prepo           = new PageRepositoryStoring(context, factory);
            var wrepo           = new WikiRepositoryStoring(context, factory);
            var wiki_controller = new WikiController(wrepo, prepo, w_logger);

            var wiki = await context.Wiki.Where(w => w.Url == wikiURL).SingleOrDefaultAsync();

            var content = new PageHtmlContent();
            var W       = new ViewzApi.Models.Wiki()
            {
                Url         = wikiURL,
                Description = "",
                PageName    = wikiURL
            };

            var status = await wiki_controller.PostAsync(wikiURL, W);

            if (wiki == null)
            {
                //ASSERT
                Assert.IsType <CreatedAtActionResult>(status);
            }
            else
            {
                Assert.IsType <ConflictObjectResult>(status);
            }
        }
コード例 #7
0
        public async Task GetWikiTestAsync(string wikiURL)
        {
            string dbString = Guid.NewGuid().ToString();

            //ARRANGE
            using var context = InMemoryDbContextFactory.GetViewzDbContext(dbString);
            IMdToHtmlAndContentsFactory factory = new MdToHtmlAndContentsFactory();
            var wrepo           = new WikiRepositoryStoring(context, factory);
            var prepo           = new PageRepositoryStoring(context, factory);
            var wiki_controller = new WikiController(wrepo, prepo, w_logger);

            var wiki = await context.Wiki.Where(w => w.Url == wikiURL).SingleOrDefaultAsync();

            //ACT
            var status = await wiki_controller.GetAsync(wikiURL);

            if (wiki != null)
            {
                //ASSERT - status 200 (OK)
                Assert.IsType <OkObjectResult>(status);
            }
            else
            {
                //ASSERT - status 404 (OK)
                Assert.IsType <NotFoundResult>(status);
            }
        }
コード例 #8
0
 public void SetUp()
 {
     Controller = new WikiController(SettingsProvider)
     {
         Repository        = Repository,
         SpamChecker       = Substitute.For <ISpamChecker>(),
         ControllerContext = ControllerContext,
         SettingsProvider  = SettingsProvider
     };
 }
コード例 #9
0
        protected void Application_Start()
        {
            AreaRegistration.RegisterAllAreas();
            GlobalConfiguration.Configure(WebApiConfig.Register);
            FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);
            RouteConfig.RegisterRoutes(RouteTable.Routes);
            BundleConfig.RegisterBundles(BundleTable.Bundles);

            var controller = new WikiController();

            controller.SavePagesFromDb();
        }
コード例 #10
0
        public void Setup()
        {
            _container = new MocksAndStubsContainer();

            _applicationSettings = _container.ApplicationSettings;
            _context             = _container.UserContext;
            _repository          = _container.Repository;
            _pluginFactory       = _container.PluginFactory;
            _settingsService     = _container.SettingsService;
            _userService         = _container.UserService;
            _historyService      = _container.HistoryService;
            _pageService         = _container.PageService;

            _wikiController = new WikiController(_applicationSettings, _userService, _pageService, _context, _settingsService);
            _wikiController.SetFakeControllerContext();
        }
コード例 #11
0
        public void should_have_200_http_status_code_if_no_modified_since_header()
        {
            // Arrange
            BrowserCacheAttribute attribute = new BrowserCacheAttribute();

            attribute.SettingsService = _settingsService;

            WikiController        controller    = CreateWikiController(attribute);
            ResultExecutedContext filterContext = CreateContext(controller);

            // Act
            attribute.OnResultExecuted(filterContext);

            // Assert
            Assert.That(filterContext.HttpContext.Response.StatusCode, Is.EqualTo(200));
            Assert.That(filterContext.Result, Is.Not.TypeOf <HttpStatusCodeResult>());
        }
コード例 #12
0
        public void Should_Have_200_Http_Status_Code_If_No_Modified_Since_Header()
        {
            // Arrange
            BrowserCacheAttribute attribute = new BrowserCacheAttribute();

            attribute.SettingsService = GetSettingsService();

            WikiController        controller    = CreateWikiController(attribute);
            ResultExecutedContext filterContext = CreateContext(controller);

            // Act
            attribute.OnResultExecuted(filterContext);

            // Assert
            Assert.That(filterContext.HttpContext.Response.StatusCode, Is.EqualTo(200));
            Assert.That(filterContext.Result, Is.Not.TypeOf <HttpStatusCodeResult>());
        }
コード例 #13
0
        public void Should_Not_Set_ViewResult_If_User_Is_Logged_In()
        {
            // Arrange
            BrowserCacheAttribute attribute = new BrowserCacheAttribute();

            attribute.SettingsService = GetSettingsService();

            WikiController        controller    = CreateWikiController(attribute);
            ResultExecutedContext filterContext = CreateContext(controller);

            attribute.Context.CurrentUser = Guid.NewGuid().ToString();

            // Act
            attribute.OnResultExecuted(filterContext);

            // Assert
            Assert.That(filterContext.Result, Is.Not.TypeOf <HttpStatusCodeResult>());
        }
コード例 #14
0
        public void should_not_set_viewresult_if_user_is_logged_in()
        {
            // Arrange
            BrowserCacheAttribute attribute = new BrowserCacheAttribute();

            attribute.SettingsService = _settingsService;

            WikiController        controller    = CreateWikiController(attribute);
            ResultExecutedContext filterContext = CreateContext(controller);

            attribute.Context.CurrentUser = Guid.NewGuid().ToString();

            // Act
            attribute.OnResultExecuted(filterContext);

            // Assert
            Assert.That(filterContext.Result, Is.Not.TypeOf <HttpStatusCodeResult>());
        }
コード例 #15
0
        public void should_not_set_viewresult_if_usebrowsercache_is_disabled()
        {
            // Arrange
            BrowserCacheAttribute attribute = new BrowserCacheAttribute();

            attribute.SettingsService = _settingsService;

            WikiController        controller    = CreateWikiController(attribute);
            ResultExecutedContext filterContext = CreateContext(controller);

            attribute.ApplicationSettings.UseBrowserCache = false;

            // Act
            attribute.OnResultExecuted(filterContext);

            // Assert
            Assert.That(filterContext.Result, Is.Not.TypeOf <HttpStatusCodeResult>());
        }
コード例 #16
0
        public void Should_Not_Set_ViewResult_If_UseBrowserCache_Is_Disabled()
        {
            // Arrange
            BrowserCacheAttribute attribute = new BrowserCacheAttribute();

            attribute.SettingsService = GetSettingsService();

            WikiController        controller    = CreateWikiController(attribute);
            ResultExecutedContext filterContext = CreateContext(controller);

            attribute.ApplicationSettings.UseBrowserCache = false;

            // Act
            attribute.OnResultExecuted(filterContext);

            // Assert
            Assert.That(filterContext.Result, Is.Not.TypeOf <HttpStatusCodeResult>());
        }
コード例 #17
0
        public async Task GetPopWiki200TestAsync()
        {
            //ARRANGE
            string dbString = Guid.NewGuid().ToString();

            //ARRANGE
            using var context = InMemoryDbContextFactory.GetViewzDbContext(dbString);
            IMdToHtmlAndContentsFactory factory = new MdToHtmlAndContentsFactory();
            var prepo           = new PageRepositoryStoring(context, factory);
            var wrepo           = new WikiRepositoryStoring(context, factory);
            var wiki_controller = new WikiController(wrepo, prepo, w_logger);

            var status = await wiki_controller.GetAsync(5);

            //ACT
            //ASSERT
            Assert.IsType <OkObjectResult>(status);
        }
コード例 #18
0
        public void Should_Have_304_Http_Status_Code_If_PluginsSaved_Is_Equal_To_Header_Last_Modified_Date()
        {
            // Arrange
            BrowserCacheAttribute attribute = new BrowserCacheAttribute();

            attribute.SettingsService = GetSettingsService();
            _repositoryMock.SiteSettings.PluginLastSaveDate = DateTime.Today.ToUniversalTime().AddHours(1);

            WikiController        controller    = CreateWikiController(attribute);
            ResultExecutedContext filterContext = CreateContext(controller);

            filterContext.HttpContext.Request.Headers.Add("If-Modified-Since", DateTime.Today.AddHours(1).ToUniversalTime().ToString("r"));

            // Act
            attribute.OnResultExecuted(filterContext);

            // Assert
            Assert.That(filterContext.HttpContext.Response.StatusCode, Is.EqualTo(304));
            Assert.That(filterContext.Result, Is.TypeOf <HttpStatusCodeResult>());
        }
コード例 #19
0
        public void should_have_304_http_status_code_if_pluginssaved_is_equal_to_header_last_modified_date()
        {
            // Arrange
            BrowserCacheAttribute attribute = new BrowserCacheAttribute();

            attribute.SettingsService = _settingsService;
            _settingsRepository.SiteSettings.PluginLastSaveDate = DateTime.Today.ToUniversalTime().AddHours(1);

            WikiController        controller    = CreateWikiController(attribute);
            ResultExecutedContext filterContext = CreateContext(controller);

            filterContext.HttpContext.Request.Headers.Add("If-Modified-Since", DateTime.Today.AddHours(1).ToUniversalTime().ToString("r"));

            // Act
            attribute.OnResultExecuted(filterContext);

            // Assert
            Assert.That(filterContext.HttpContext.Response.StatusCode, Is.EqualTo(304));
            Assert.That(filterContext.Result, Is.TypeOf <HttpStatusCodeResult>());
        }
コード例 #20
0
        public void Setup()
        {
            // WikiController setup (use WikiController as it's the one typically used by views)
            _container = new MocksAndStubsContainer();

            _applicationSettings = _container.ApplicationSettings;
            _context             = _container.UserContext;
            _repository          = _container.Repository;
            _pluginFactory       = _container.PluginFactory;
            _settingsService     = _container.SettingsService;
            _siteSettings        = _settingsService.GetSiteSettings();
            _siteSettings.Theme  = "Mediawiki";

            _userService    = _container.UserService;
            _historyService = _container.HistoryService;
            _pageService    = _container.PageService;

            _wikiController = new WikiController(_applicationSettings, _userService, _pageService, _context, _settingsService);
            _wikiController.SetFakeControllerContext("~/wiki/index/1");
            _urlHelper = _wikiController.Url;
        }
コード例 #21
0
        private WikiController CreateWikiController(BrowserCacheAttribute attribute)
        {
            // Settings
            ApplicationSettings appSettings = new ApplicationSettings()
            {
                Installed = true, UseBrowserCache = true
            };
            UserContextStub userContext = new UserContextStub()
            {
                IsLoggedIn = false
            };

            // PageService
            PageViewModelCache pageViewModelCache = new PageViewModelCache(appSettings, CacheMock.RoadkillCache);
            ListCache          listCache          = new ListCache(appSettings, CacheMock.RoadkillCache);
            SiteCache          siteCache          = new SiteCache(appSettings, CacheMock.RoadkillCache);
            SearchServiceMock  searchService      = new SearchServiceMock(appSettings, _repositoryMock, _pluginFactory);
            PageHistoryService historyService     = new PageHistoryService(appSettings, _repositoryMock, userContext, pageViewModelCache, _pluginFactory);
            PageService        pageService        = new PageService(appSettings, _repositoryMock, searchService, historyService, userContext, listCache, pageViewModelCache, siteCache, _pluginFactory);

            // WikiController
            SettingsService settingsService = new SettingsService(appSettings, _repositoryMock);
            UserServiceStub userManager     = new UserServiceStub();
            WikiController  wikiController  = new WikiController(appSettings, userManager, pageService, userContext, settingsService);

            // Create a page that the request is for
            Page page = new Page()
            {
                Title = "title", ModifiedOn = _pageModifiedDate
            };

            _repositoryMock.AddNewPage(page, "text", "user", _pageCreatedDate);

            // Update the BrowserCacheAttribute
            attribute.ApplicationSettings = appSettings;
            attribute.Context             = userContext;
            attribute.PageService         = pageService;

            return(wikiController);
        }
コード例 #22
0
        private ResultExecutedContext CreateContext(WikiController wikiController)
        {
            // HTTP Context
            ControllerContext controllerContext = new Mock <ControllerContext>().Object;
            MvcMockContainer  container         = new MvcMockContainer();
            HttpContextBase   context           = MvcMockHelpers.FakeHttpContext(container);

            controllerContext.HttpContext = context;

            // ResultExecutedContext
            ActionResult result    = new ViewResult();
            Exception    exception = new Exception();
            bool         cancelled = true;

            ResultExecutedContext filterContext = new ResultExecutedContext(controllerContext, result, cancelled, exception);

            filterContext.Controller = wikiController;
            filterContext.RouteData.Values.Add("id", 1);
            filterContext.HttpContext = context;

            return(filterContext);
        }
コード例 #23
0
        public override void OnResultExecuted(ResultExecutedContext filterContext)
        {
            if (!ApplicationSettings.Installed || !ApplicationSettings.UseBrowserCache || Context.IsLoggedIn)
            {
                return;
            }

            WikiController wikiController = filterContext.Controller as WikiController;
            HomeController homeController = filterContext.Controller as HomeController;

            if (wikiController == null && homeController == null)
            {
                return;
            }

            PageViewModel page = null;

            // Find the page for the action we're on
            if (wikiController != null)
            {
                int id = 0;
                if (int.TryParse(filterContext.RouteData.Values["id"].ToString(), out id))
                {
                    page = PageService.GetById(id, true);
                }
            }
            else
            {
                page = PageService.FindHomePage();
            }

            if (page != null && page.IsCacheable)
            {
                string   modifiedSinceHeader = filterContext.HttpContext.Request.Headers["If-Modified-Since"];
                DateTime modifiedSinceDate   = ResponseWrapper.GetLastModifiedDate(modifiedSinceHeader);

                // Check if any plugins have been recently updated as saving their settings invalidates the browser cache.
                // This is necessary because, for example, enabling the TOC plugin will mean the content
                // should have {TOC} parsed now, but the browser cache content will contain the un-cached version still.
                SiteSettings siteSettings       = SettingsService.GetSiteSettings();
                DateTime     pluginLastSaveDate = siteSettings.PluginLastSaveDate.ClearMilliseconds();

                if (pluginLastSaveDate > modifiedSinceDate)
                {
                    // Update the browser's modified since date, and a 200
                    SetRequiredCacheHeaders(filterContext);
                    filterContext.HttpContext.Response.Cache.SetLastModified(pluginLastSaveDate.ToUniversalTime());
                    filterContext.HttpContext.Response.StatusCode = 200;

                    return;
                }

                //
                // Is the page's last modified date after the plugin last save date?
                //
                DateTime pageModifiedDate = page.ModifiedOn.ToUniversalTime();

                if (pageModifiedDate > pluginLastSaveDate)
                {
                    // [Yes] - check if the page's last modified date is more recent than the header. If it isn't then a 304 is returned.
                    filterContext.HttpContext.Response.Cache.SetLastModified(pageModifiedDate);
                    filterContext.HttpContext.Response.StatusCode = ResponseWrapper.GetStatusCodeForCache(pageModifiedDate, modifiedSinceHeader);
                }
                else
                {
                    // [No]  - check if the plugin's last saved date is more recent than the header. If it isn't then a 304 is returned.
                    filterContext.HttpContext.Response.Cache.SetLastModified(pluginLastSaveDate.ToUniversalTime());
                    filterContext.HttpContext.Response.StatusCode = ResponseWrapper.GetStatusCodeForCache(pluginLastSaveDate, modifiedSinceHeader);
                }

                SetRequiredCacheHeaders(filterContext);

                // Lastly, if the status code is 304 then return an empty body (HttpStatusCodeResult 304), or the
                // browser will try to read the entire response body again.
                if (filterContext.HttpContext.Response.StatusCode == 304)
                {
                    filterContext.Result = new HttpStatusCodeResult(304, "Not Modified");
                }
            }
        }