public void RequestNotMatchingAnyBlog_ButWithASingleBlogInSystemWithLocalHostButNotMatchingSubfolder_ReturnsUpdatesItsHostThenRedirectsToSubfolder()
        {
            //arrange
            var onlyBlog = new Blog { Host = "localhost", Subfolder = "sub" };
            var pagedCollection = new PagedCollection<Blog> { onlyBlog };
            pagedCollection.MaxItems = 1;

            var repository = new Mock<ObjectRepository>();
            repository.Setup(r => r.GetBlog("example.com", It.IsAny<string>())).Returns((Blog)null);
            repository.Setup(r => r.GetPagedBlogs(null, 0, It.IsAny<int>(), ConfigurationFlags.None)).Returns(
                pagedCollection);
            var appSettings = new NameValueCollection();
            appSettings.Add("AggregateEnabled", "false");
            var hostInfo = new HostInfo(appSettings);
            var service = new BlogLookupService(repository.Object, new LazyNotNull<HostInfo>(() => hostInfo));
            var blogRequest = new BlogRequest("example.com", string.Empty, new Uri("http://example.com/foo/bar"), false);

            //act
            BlogLookupResult result = service.Lookup(blogRequest);

            //assert
            Assert.IsNull(result.Blog);
            Assert.IsNotNull(result.AlternateUrl);
            Assert.AreEqual("http://example.com/sub/foo/bar", result.AlternateUrl.ToString());
            Assert.AreEqual("example.com", onlyBlog.Host);
            repository.Verify(r => r.UpdateBlog(It.IsAny<Blog>()));
        }
        public void AuthenticateRequest_WithRequestHavingValidAuthCookies_SetsUserToGenericPrincipalWithRoles()
        {
            // arrange
            var module = new AuthenticationModule();
            const string roles = "Admins|HostAdmins|Users";
            var ticket = new FormsAuthenticationTicket(1, ".ASPXAUTH.42", DateTime.Now, DateTime.Now.AddDays(60), true,
                                                       roles);
            string cookieValue = FormsAuthentication.Encrypt(ticket);
            var authCookie = new HttpCookie(".ASPXAUTH.42") { Value = cookieValue };
            var cookies = new HttpCookieCollection { authCookie };
            var httpContext = new Mock<HttpContextBase>();
            httpContext.Stub(c => c.User);
            httpContext.Setup(c => c.Request.Path).Returns("/");
            httpContext.Setup(c => c.Request.QueryString).Returns(new NameValueCollection());
            httpContext.Setup(c => c.Request.Cookies).Returns(cookies);
            httpContext.Setup(c => c.Response.Cookies).Returns(cookies);
            var blogRequest = new BlogRequest("localhost", string.Empty, new Uri("http://localhost"), false,
                                              RequestLocation.Blog, "/") { Blog = new Blog { Id = 42 } };

            // act
            module.AuthenticateRequest(httpContext.Object, blogRequest);

            // assert
            var principal = httpContext.Object.User as GenericPrincipal;
            Assert.IsNotNull(principal);
            Assert.IsTrue(principal.IsInRole("Admins"));
            Assert.IsTrue(principal.IsInRole("HostAdmins"));
            Assert.IsTrue(principal.IsInRole("Users"));
        }
Exemple #3
0
        public void HandleInstallationStatus(HttpContextBase context, BlogRequest blogRequest)
        {
            string redirectUrl = GetInstallationRedirectUrl(blogRequest);

            if (!String.IsNullOrEmpty(redirectUrl))
            {
                context.Response.Redirect(redirectUrl);
            }
        }
        public void Ctor_WithRequestForInstallation_SetsBlogNotRequiredTrue()
        {
            //arrange, act
            var blogRequest = new BlogRequest(null, null, new Uri("http://example.com"), false,
                                              RequestLocation.Installation, "/");

            //assert
            Assert.IsTrue(blogRequest.BlogNotRequired);
        }
        public void Ctor_WithRequestForHostAdmin_SetsRequestLocationToHostAdmin()
        {
            //arrange
            Mock<HttpRequestBase> request = CreateRequest("example.com", "/", "/HostAdmin/anything.aspx", true);

            //act
            var blogRequest = new BlogRequest(request.Object);

            //assert
            Assert.AreEqual(RequestLocation.HostAdmin, blogRequest.RequestLocation);
        }
        public void AuthenticateRequest(HttpContextBase httpContext, BlogRequest blogRequest)
        {
            if(blogRequest.RequestLocation == RequestLocation.StaticFile)
            {
                return;
            }

            HttpCookie authCookie = httpContext.Request.SelectAuthenticationCookie(blogRequest.Blog);
            FormsAuthenticationTicket authTicket = GetFormsAuthenticationTicket(authCookie);
            HandleFormsAuthenticationTicket(blogRequest, httpContext, authTicket);
        }
        public void Ctor_WithRequestForInstallDirectoryRoot_SetsRequestLocationToInstallDirectory()
        {
            //arrange
            Mock<HttpRequestBase> request = CreateRequest("example.com", "/", "/Install", true);

            //act
            var blogRequest = new BlogRequest(request.Object);

            //assert
            Assert.AreEqual(RequestLocation.Installation, blogRequest.RequestLocation);
        }
        public void Ctor_WithHostHavingPort_StripsPort()
        {
            //arrange
            Mock<HttpRequestBase> request = CreateRequest("example.com:1234", "/", "/foo/bar", true);

            //act
            var blogRequest = new BlogRequest(request.Object);

            //assert
            Assert.AreEqual("example.com", blogRequest.Host);
        }
        public void AuthenticateRequest(HttpContextBase httpContext, BlogRequest blogRequest)
        {
            if (blogRequest.RequestLocation == RequestLocation.StaticFile)
            {
                return;
            }

            HttpCookie authCookie = httpContext.Request.SelectAuthenticationCookie(blogRequest.Blog);
            FormsAuthenticationTicket authTicket = GetFormsAuthenticationTicket(authCookie);

            HandleFormsAuthenticationTicket(blogRequest, httpContext, authTicket);
        }
        public void GetInstallationRedirectUrl_ForStaticFiles_ReturnsNull()
        {
            // arrange
            var module = new InstallationCheckModule(new Mock<IInstallationManager>().Object, new LazyNotNull<HostInfo>(() => null));
            var blogRequest = new BlogRequest("localhost", string.Empty, new Uri("http://localhost/whatever/foo.jpg"),
                                              true, RequestLocation.Blog, "/");
            // act
            string redirectUrl = module.GetInstallationRedirectUrl(blogRequest);

            // assert
            Assert.IsNull(redirectUrl);
        }
        public void AuthenticateRequest_WithRequestForStaticFile_ReturnsImmediately()
        {
            // arrange
            var module = new AuthenticationModule();
            var httpContext = new Mock<HttpContextBase>();
            httpContext.Setup(c => c.Request.Cookies).Throws(new InvalidOperationException());
            var blogRequest = new BlogRequest("localhost", string.Empty, new Uri("http://localhost"), false,
                                              RequestLocation.StaticFile, "/");

            // act, assert
            module.AuthenticateRequest(httpContext.Object, blogRequest);
        }
        public void HandleFormsAuthenticationTicket(BlogRequest blogRequest, HttpContextBase httpContext, FormsAuthenticationTicket authTicket)
        {
            if (authTicket != null)
            {
                if (FormsAuthentication.SlidingExpiration)
                {
                    authTicket = FormsAuthentication.RenewTicketIfOld(authTicket);
                }

                // When the ticket was created, the UserData property was assigned a
                // pipe delimited string of role names.
                SetHttpContextUser(httpContext, authTicket);
            }
        }
        public void GetInstallationRedirectUrl_WhenHostInfoNotNullAndInstallRequiredButInInstallDirectory_ReturnsNull()
        {
            // arrange
            var installManager = new Mock<IInstallationManager>();
            installManager.Setup(m => m.InstallationActionRequired(It.IsAny<Version>(), null)).Returns(true);
            var module = new InstallationCheckModule(installManager.Object, new LazyNotNull<HostInfo>(CreateHostInfo));
            var blogRequest = new BlogRequest("localhost", string.Empty, new Uri("http://localhost/Install/foo.aspx"),
                                              true, RequestLocation.Installation, "/");

            // act
            string redirectUrl = module.GetInstallationRedirectUrl(blogRequest);

            // assert
            Assert.IsNull(redirectUrl);
        }
Exemple #14
0
        public void GetRouteData_MatchingTheImplicitSubfolderRoute_ReturnsParentDirectoryRoute()
        {
            //arrange
            var route = new PageRoute("url", "~/aspx/Dtp.aspx", new[] { "foo" }, new Mock<ISubtextPageBuilder>().Object,
                                      new Mock<IDependencyResolver>().Object);
            var httpContext = new Mock<HttpContextBase>();
            httpContext.FakeRequest("~/subfolder/url");
            var blogRequest = new BlogRequest("localhost", "subfolder", new Uri("http://localhost"), false);

            //act
            RouteData routeData = route.GetRouteData(httpContext.Object, blogRequest);

            //assert
            Assert.AreEqual(route, routeData.Route);
        }
        public void GetRouteData_MatchingTheImplicitSubfolderRoute_ReturnsParentDirectoryRoute()
        {
            //arrange
            var route = new DirectoryRoute("dir", new Mock<IServiceLocator>().Object);
            ;
            var httpContext = new Mock<HttpContextBase>();
            httpContext.FakeRequest("~/subfolder/dir/foo.aspx");
            var blogRequest = new BlogRequest("localhost", "subfolder", new Uri("http://localhost"), false);

            //act
            RouteData routeData = route.GetRouteData(httpContext.Object, blogRequest);

            //assert
            Assert.AreEqual(route, routeData.Route);
        }
        public void GetInstallationRedirectUrl_WhenHostInfoNotNullInstallationActionRequiredAndInLoginPage_ReturnsInstallDirectory()
        {
            // arrange
            var installManager = new Mock<IInstallationManager>();
            installManager.Setup(m => m.GetInstallationStatus(It.IsAny<Version>())).Returns(
                InstallationState.NeedsInstallation);
            installManager.Setup(m => m.InstallationActionRequired(It.IsAny<Version>(), null)).Returns(true);
            var module = new InstallationCheckModule(installManager.Object, new LazyNotNull<HostInfo>(UnitTestHelper.CreateHostInfo));
            var blogRequest = new BlogRequest("localhost", string.Empty, new Uri("http://localhost/Install/foo.aspx"),
                                              true, RequestLocation.LoginPage, "/");

            // act
            string redirectUrl = module.GetInstallationRedirectUrl(blogRequest);

            // assert
            Assert.AreEqual("~/install/default.aspx", redirectUrl);
        }
Exemple #17
0
        public BlogRequest ConvertRequestToBlogRequest(HttpContextBase httpContext)
        {
            string redirectUrl = httpContext.Request.GetFileNotFoundRedirectUrl(HttpRuntime.UsingIntegratedPipeline);

            if (!String.IsNullOrEmpty(redirectUrl))
            {
                httpContext.Response.Redirect(redirectUrl, true);
                return(null);
            }

            // REVIEW: Maybe the BlogLookup.Lookup should take in an HttpContextBase
            // and return the BlogRequest as part of the result.
            var blogRequest = new BlogRequest(httpContext.Request);

            if (blogRequest.BlogNotRequired)
            {
                return(blogRequest);
            }
            BlogLookupResult result = BlogLookup.Lookup(blogRequest);

            if (result == null)
            {
                if (blogRequest.RequestLocation != RequestLocation.LoginPage)
                {
                    httpContext.Response.Redirect("~/install/BlogNotConfiguredError.aspx", true);
                }
                return(blogRequest);
            }

            if (result.Blog == null && result.AlternateUrl != null)
            {
                httpContext.Response.RedirectPermanent(result.AlternateUrl.ToString(), true);
                return(null);
            }

            if (result.Blog != null && !result.Blog.IsActive && blogRequest.RequestLocation == RequestLocation.Blog)
            {
                httpContext.Response.Redirect("~/SystemMessages/BlogNotActive.aspx", true);
                return(null);
            }

            blogRequest.Blog = result.Blog;
            return(blogRequest);
        }
Exemple #18
0
        public virtual RouteData GetRouteData(HttpContextBase httpContext, BlogRequest blogRequest)
        {
            RouteData routeData;
            if (String.IsNullOrEmpty(blogRequest.Subfolder))
            {
                routeData = base.GetRouteData(httpContext);
                if (routeData != null)
                {
                    //Add current subfolder info.
                    routeData.Values.Add("subfolder", string.Empty);
                }
            }
            else
            {
                routeData = RouteForSubfolder.GetRouteData(httpContext, blogRequest.Subfolder);
            }

            return routeData;
        }
        public BlogRequest ConvertRequestToBlogRequest(HttpContextBase httpContext)
        {
            string redirectUrl = httpContext.Request.GetFileNotFoundRedirectUrl(HttpRuntime.UsingIntegratedPipeline);
            if (!String.IsNullOrEmpty(redirectUrl))
            {
                httpContext.Response.Redirect(redirectUrl, true);
                return null;
            }

            // REVIEW: Maybe the BlogLookup.Lookup should take in an HttpContextBase
            // and return the BlogRequest as part of the result.
            var blogRequest = new BlogRequest(httpContext.Request);
            if (blogRequest.BlogNotRequired)
            {
                return blogRequest;
            }
            BlogLookupResult result = BlogLookup.Lookup(blogRequest);

            if (result == null)
            {
                if (blogRequest.RequestLocation != RequestLocation.LoginPage)
                {
                    httpContext.Response.Redirect("~/install/BlogNotConfiguredError.aspx", true);
                }
                return blogRequest;
            }

            if (result.Blog == null && result.AlternateUrl != null)
            {
                httpContext.Response.RedirectPermanent(result.AlternateUrl.ToString(), true);
                return null;
            }

            if (result.Blog != null && !result.Blog.IsActive && blogRequest.RequestLocation == RequestLocation.Blog)
            {
                httpContext.Response.Redirect("~/SystemMessages/BlogNotActive.aspx", true);
                return null;
            }

            blogRequest.Blog = result.Blog;
            return blogRequest;
        }
        public void GetVirtualPath_WithoutSubolder_ReturnsUrlWithoutSubfolder()
        {
            //arrange
            var route = new DirectoryRoute("admin", new Mock<IServiceLocator>().Object);
            var httpContext = new Mock<HttpContextBase>();
            httpContext.FakeRequest("~/admin/posts/foo.aspx");
            var blogRequest = new BlogRequest("localhost", null, new Uri("http://localhost"), true);
            var routeData = new RouteData();
            var requestContext = new RequestContext(httpContext.Object, routeData);

            //act
            VirtualPathData virtualPath = route.GetVirtualPath(requestContext
                                                               ,
                                                               new RouteValueDictionary(
                                                                   new {pathInfo = "posts/foo.aspx"}));

            //assert
            Assert.IsNotNull(virtualPath);
            Assert.AreEqual("admin/posts/foo.aspx", virtualPath.VirtualPath);
        }
Exemple #21
0
        /// <summary>
        /// Checks the installation status and redirects if necessary.
        /// </summary>
        public string GetInstallationRedirectUrl(BlogRequest blogRequest)
        {
            const string installUrl = "~/install/default.aspx";

            // Bypass for static files.
            if (blogRequest.RawUrl.IsStaticFileRequest())
            {
                return(null);
            }

            if (_hostInfo.Value == null && blogRequest.RequestLocation != RequestLocation.Installation)
            {
                return(installUrl);
            }

            // Want to redirect to install if installation is required,
            // or if we're missing a HostInfo record.
            if ((InstallationManager.InstallationActionRequired(VersionInfo.CurrentAssemblyVersion, null) || _hostInfo.Value == null))
            {
                InstallationState state = InstallationManager.GetInstallationStatus(VersionInfo.CurrentAssemblyVersion);
                if (state == InstallationState.NeedsInstallation &&
                    !blogRequest.IsHostAdminRequest &&
                    blogRequest.RequestLocation != RequestLocation.Installation)
                {
                    return(installUrl);
                }

                if (state == InstallationState.NeedsUpgrade)
                {
                    if (blogRequest.RequestLocation != RequestLocation.Upgrade &&
                        blogRequest.RequestLocation != RequestLocation.LoginPage &&
                        blogRequest.RequestLocation != RequestLocation.SystemMessages &&
                        blogRequest.RequestLocation != RequestLocation.HostAdmin)
                    {
                        return("~/SystemMessages/UpgradeInProgress.aspx");
                    }
                }
            }
            return(null);
        }
        /// <summary>
        /// Checks the installation status and redirects if necessary.
        /// </summary>
        public string GetInstallationRedirectUrl(BlogRequest blogRequest)
        {
            const string installUrl = "~/install/default.aspx";

            // Bypass for static files.
            if (blogRequest.RawUrl.IsStaticFileRequest())
            {
                return null;
            }

            if (_hostInfo.Value == null && blogRequest.RequestLocation != RequestLocation.Installation)
            {
                return installUrl;
            }

            // Want to redirect to install if installation is required,
            // or if we're missing a HostInfo record.
            if ((InstallationManager.InstallationActionRequired(VersionInfo.CurrentAssemblyVersion, null) || _hostInfo.Value == null))
            {
                InstallationState state = InstallationManager.GetInstallationStatus(VersionInfo.CurrentAssemblyVersion);
                if (state == InstallationState.NeedsInstallation
                   && !blogRequest.IsHostAdminRequest
                   && blogRequest.RequestLocation != RequestLocation.Installation)
                {
                    return installUrl;
                }

                if (state == InstallationState.NeedsUpgrade)
                {
                    if (blogRequest.RequestLocation != RequestLocation.Upgrade
                       && blogRequest.RequestLocation != RequestLocation.LoginPage
                       && blogRequest.RequestLocation != RequestLocation.SystemMessages
                       && blogRequest.RequestLocation != RequestLocation.HostAdmin)
                    {
                        return "~/SystemMessages/UpgradeInProgress.aspx";
                    }
                }
            }
            return null;
        }
        public void RequestNotMatchingAnyBlog_ButWithAggregateBlogsEnabledAndActiveBlogsInTheSystem_ReturnsAggregateBlog()
        {
            //arrange
            var repository = new Mock<ObjectProvider>();
            repository.Setup(r => r.GetBlog("example.com", It.IsAny<string>())).Returns((Blog)null);
            var onlyBlog = new Blog {Host = "example.com", Subfolder = "not-sub"};
            var pagedCollection = new PagedCollection<Blog> {onlyBlog};
            pagedCollection.MaxItems = 1;
            repository.Setup(r => r.GetPagedBlogs(null, 0, It.IsAny<int>(), ConfigurationFlags.None)).Returns(
                pagedCollection);
            var aggregateBlog = new Blog();
            var service = new BlogLookupService(repository.Object,
                                                new HostInfo
                                                {BlogAggregationEnabled = true, AggregateBlog = aggregateBlog});
            var blogRequest = new BlogRequest("example.com", string.Empty, new Uri("http://example.com/foo/bar"), false);

            //act
            BlogLookupResult result = service.Lookup(blogRequest);

            //assert
            Assert.AreSame(aggregateBlog, result.Blog);
        }
        public void HandleFormsAuthenticationTicket(BlogRequest blogRequest, HttpContextBase httpContext, FormsAuthenticationTicket authTicket)
        {
            if (authTicket != null)
            {
                if (FormsAuthentication.SlidingExpiration)
                {
                    FormsAuthentication.RenewTicketIfOld(authTicket);
                }

                // When the ticket was created, the UserData property was assigned a
                // pipe delimited string of role names.
                SetHttpContextUser(httpContext, authTicket);
            }
            else
            {
                httpContext.Response.Cookies.Add(httpContext.Request.GetExpiredCookie(blogRequest.Blog));
                //if(blogRequest.RequestLocation != RequestLocation.LoginPage && blogRequest.RequestLocation == RequestLocation.)
                //{
                //    RedirectToLogin(blogRequest, httpContext);
                //}
            }
        }
        public void RequestNotMatchingAnyBlog_ButWithASingleBlogInSystemWithLocalHost_ReturnsThatBlogAndUpdatesItsHost()
        {
            //arrange
            var onlyBlog = new Blog {Host = "localhost", Subfolder = ""};
            var pagedCollection = new PagedCollection<Blog> {onlyBlog};
            pagedCollection.MaxItems = 1;

            var repository = new Mock<ObjectProvider>();
            repository.Setup(r => r.GetBlog("example.com", It.IsAny<string>())).Returns((Blog)null);
            repository.Setup(r => r.GetPagedBlogs(null, 0, It.IsAny<int>(), ConfigurationFlags.None)).Returns(
                pagedCollection);
            var service = new BlogLookupService(repository.Object, new HostInfo {BlogAggregationEnabled = false});
            var blogRequest = new BlogRequest("example.com", string.Empty, new Uri("http://example.com/foo/bar"), false);

            //act
            BlogLookupResult result = service.Lookup(blogRequest);

            //assert
            Assert.IsNotNull(result.Blog);
            Assert.IsNull(result.AlternateUrl);
            Assert.AreEqual("example.com", result.Blog.Host);
            Assert.AreEqual("example.com", onlyBlog.Host);
            repository.Verify(r => r.UpdateBlog(It.IsAny<Blog>()));
        }
        public void Ctor_WithRequestForStaticFile_SetsRequestLocationToStaticFile()
        {
            //arrange
            Mock<HttpRequestBase> request = CreateRequest("example.com", "/", "/Install/anything.css", true);

            //act
            var blogRequest = new BlogRequest(request.Object);

            //assert
            Assert.AreEqual(RequestLocation.StaticFile, blogRequest.RequestLocation);
        }
        public void Ctor_WithRequestForLoginPage_SetsRequestLocationToLogin()
        {
            //arrange
            Mock<HttpRequestBase> request = CreateRequest("example.com", "/", "/login.aspx", true);

            //act
            var blogRequest = new BlogRequest(request.Object);

            //assert
            Assert.AreEqual(RequestLocation.LoginPage, blogRequest.RequestLocation);
        }
        public void Ctor_WithRequestHavingNoHostInParameters_CreatesBlogRequestWithHostAuthority()
        {
            //arrange
            Mock<HttpRequestBase> request = CreateRequest("example.com", "/", "/foo/bar", true);

            //act
            var blogRequest = new BlogRequest(request.Object);

            //assert
            Assert.AreEqual("example.com", blogRequest.Host);
        }
        public void Ctor_WithRequestForSystemMessage_SetsRequestLocationToSystemMessages()
        {
            //arrange
            Mock<HttpRequestBase> request = CreateRequest("example.com", "/", "/SystemMessages/anything.aspx", true);

            //act
            var blogRequest = new BlogRequest(request.Object);

            //assert
            Assert.AreEqual(RequestLocation.SystemMessages, blogRequest.RequestLocation);
        }
        public void HandleFormsAuthenticationTicket_WithRequestHavingNullAuthTicket_WritesExpiredCookie()
        {
            // arrange
            Func<BlogRequest, HttpContextBase, string> loginFunc = (r, c) => "/foo/login.aspx";
            var module = new AuthenticationModule();
            var authCookie = new HttpCookie(".ASPXAUTH.42") { Value = null };
            var cookies = new HttpCookieCollection { authCookie };
            var httpContext = new Mock<HttpContextBase>();
            httpContext.Stub(c => c.User);
            httpContext.Setup(c => c.Request.Path).Returns("/");
            httpContext.Setup(c => c.Request.QueryString).Returns(new NameValueCollection());
            httpContext.Setup(c => c.Request.Cookies).Returns(cookies);
            httpContext.Setup(c => c.Response.Redirect(It.IsAny<string>(), true));
            var responseCookies = new HttpCookieCollection();
            httpContext.Setup(c => c.Response.Cookies).Returns(responseCookies);
            var blogRequest = new BlogRequest("localhost", string.Empty, new Uri("http://localhost"), false,
                                              RequestLocation.Blog, "/") { Blog = new Blog { Id = 42 } };

            // act
            module.HandleFormsAuthenticationTicket(blogRequest, httpContext.Object, null);

            // assert
            var principal = httpContext.Object.User as GenericPrincipal;
            Assert.IsNull(principal);
            Assert.AreEqual(1, responseCookies.Count);
            HttpCookie cookie = responseCookies[".ASPXAUTH.42"];
            Assert.IsTrue(cookie.Expires.AddYears(20) < DateTime.Now);
        }
        public void Ctor_WithRequestWithSubfolder_CreatesBlogRequestWithSubfolder()
        {
            //arrange
            Mock<HttpRequestBase> request = CreateRequest("example.com", "/", "/foo/bar", true);

            //act
            var blogRequest = new BlogRequest(request.Object);

            //assert
            Assert.AreEqual("foo", blogRequest.Subfolder);
        }
 public void HandleInstallationStatus(HttpContextBase context, BlogRequest blogRequest)
 {
     string redirectUrl = GetInstallationRedirectUrl(blogRequest);
     if (!String.IsNullOrEmpty(redirectUrl))
     {
         context.Response.Redirect(redirectUrl);
     }
 }
        public BlogLookupResult Lookup(BlogRequest blogRequest)
        {
            if(Host == null)
            {
                return new BlogLookupResult(null, null);
            }

            string host = blogRequest.Host;
            Blog blog = Repository.GetBlog(host, blogRequest.Subfolder);
            if(blog != null)
            {
                if(!String.Equals(host, blog.Host, StringComparison.OrdinalIgnoreCase)
                   || !String.Equals(blogRequest.Subfolder, blog.Subfolder, StringComparison.OrdinalIgnoreCase))
                {
                    UriBuilder alternateUrl = ReplaceHost(blogRequest.RawUrl, blog.Host);
                    alternateUrl = ReplaceSubfolder(alternateUrl, blogRequest, blog.Subfolder);
                    return new BlogLookupResult(null, alternateUrl.Uri);
                }
                return new BlogLookupResult(blog, null);
            }

            IPagedCollection<Blog> pagedBlogs = Repository.GetPagedBlogs(null, 0, 10, ConfigurationFlags.None);
            int totalBlogCount = pagedBlogs.MaxItems;
            if(Host.BlogAggregationEnabled && totalBlogCount > 0)
            {
                if(!String.IsNullOrEmpty(blogRequest.Subfolder))
                {
                    return null;
                }
                return new BlogLookupResult(Host.AggregateBlog, null);
            }

            if(totalBlogCount == 1)
            {
                Blog onlyBlog = pagedBlogs.First();
                if(onlyBlog.Host == blogRequest.Host)
                {
                    Uri onlyBlogUrl =
                        ReplaceSubfolder(new UriBuilder(blogRequest.RawUrl), blogRequest, onlyBlog.Subfolder).Uri;
                    return new BlogLookupResult(null, onlyBlogUrl);
                }

                //Extra special case to deal with a common deployment problem where dev uses "localhost" on
                //dev machine. But deploys to real domain.
                if(OnlyBlogIsLocalHostNotCurrentHost(host, onlyBlog))
                {
                    onlyBlog.Host = host;
                    Repository.UpdateBlog(onlyBlog);

                    if(onlyBlog.Subfolder != blogRequest.Subfolder)
                    {
                        Uri onlyBlogUrl =
                            ReplaceSubfolder(new UriBuilder(blogRequest.RawUrl), blogRequest, onlyBlog.Subfolder).Uri;
                        return new BlogLookupResult(null, onlyBlogUrl);
                    }
                    return new BlogLookupResult(onlyBlog, null);
                }

                //TODO: What about case where you've pulled the prod blog down to localhost?
            }

            return null;
        }
        private static UriBuilder ReplaceSubfolder(UriBuilder originalUrl, BlogRequest blogRequest, string newSubfolder)
        {
            if(!String.Equals(blogRequest.Subfolder, newSubfolder, StringComparison.OrdinalIgnoreCase))
            {
                string appPath = blogRequest.ApplicationPath;
                if(!appPath.EndsWith("/"))
                {
                    appPath += "/";
                }

                int indexAfterAppPath = appPath.Length;
                if(!String.IsNullOrEmpty(blogRequest.Subfolder))
                {
                    originalUrl.Path = originalUrl.Path.Remove(indexAfterAppPath, blogRequest.Subfolder.Length + 1);
                }
                if(!String.IsNullOrEmpty(newSubfolder))
                {
                    originalUrl.Path = originalUrl.Path.Substring(0, indexAfterAppPath) + newSubfolder + "/" +
                                       originalUrl.Path.Substring(indexAfterAppPath);
                }
            }
            return originalUrl;
        }
        public void RequestNotMatchingAnyBlog_ButWithASingleBlogInSystemWithMatchingHostButDifferentSubfolder_RedirectsToOnlyBlog()
        {
            //arrange
            var onlyBlog = new Blog { Host = "example.com", Subfolder = "not-sub" };
            var pagedCollection = new PagedCollection<Blog> { onlyBlog };
            pagedCollection.MaxItems = 1;

            var repository = new Mock<ObjectRepository>();
            repository.Setup(r => r.GetBlog("example.com", "sub")).Returns((Blog)null);
            repository.Setup(r => r.GetBlog("example.com", "not-sub")).Returns(onlyBlog);
            repository.Setup(r => r.GetPagedBlogs(null, 0, It.IsAny<int>(), ConfigurationFlags.None)).Returns(
                pagedCollection);
            var appSettings = new NameValueCollection();
            appSettings.Add("AggregateEnabled", "false");
            var hostInfo = new HostInfo(appSettings);
            var service = new BlogLookupService(repository.Object, new LazyNotNull<HostInfo>(() => hostInfo));
            var blogRequest = new BlogRequest("example.com", "sub", new Uri("http://example.com/Subtext.Web/sub/bar"),
                                              false, RequestLocation.Blog, "/Subtext.Web");

            //act
            BlogLookupResult result = service.Lookup(blogRequest);

            //assert
            Assert.IsNull(result.Blog);
            Assert.AreEqual("http://example.com/Subtext.Web/not-sub/bar", result.AlternateUrl.ToString());
        }
        public void RequestWithSubfolderNotMatchingAnyBlog_ButWithAggregateBlogsEnabledAndMoreThanOneActiveBlogsInTheSystem_ReturnsNull()
        {
            //arrange
            var repository = new Mock<ObjectRepository>();
            repository.Setup(r => r.GetBlog("example.com", It.IsAny<string>())).Returns((Blog)null);
            var blog1 = new Blog { Host = "example.com", Subfolder = "not-sub" };
            var blog2 = new Blog { Host = "example.com", Subfolder = "not-sub-2" };
            var pagedCollection = new PagedCollection<Blog> { blog1, blog2 };
            pagedCollection.MaxItems = 2;
            repository.Setup(r => r.GetPagedBlogs(null, 0, It.IsAny<int>(), ConfigurationFlags.None)).Returns(
                pagedCollection);
            var appSettings = new NameValueCollection();
            appSettings.Add("AggregateEnabled", "true");
            var hostInfo = new HostInfo(appSettings);
            var service = new BlogLookupService(repository.Object,
                                                new LazyNotNull<HostInfo>(() => hostInfo));
            var blogRequest = new BlogRequest("example.com", "blog1234", new Uri("http://example.com/foo/bar"), false);

            //act
            BlogLookupResult result = service.Lookup(blogRequest);

            //assert
            Assert.IsNull(result);
        }