Example #1
0
        public void StartApplicationTest()
        {
            AppDomainUtils.RunInSeparateAppDomain(
                () =>
            {
                var moduleEvents = new ModuleEvents();
                var app          = new MyHttpApplication();
                WebPageHttpModule.StartApplication(
                    app,
                    moduleEvents.ExecuteStartPage,
                    moduleEvents.ApplicationStart
                    );
                Assert.Equal(1, moduleEvents.CalledExecuteStartPage);
                Assert.Equal(1, moduleEvents.CalledApplicationStart);

                // Call a second time to make sure the methods are only called once
                WebPageHttpModule.StartApplication(
                    app,
                    moduleEvents.ExecuteStartPage,
                    moduleEvents.ApplicationStart
                    );
                Assert.Equal(1, moduleEvents.CalledExecuteStartPage);
                Assert.Equal(1, moduleEvents.CalledApplicationStart);
            }
                );
        }
Example #2
0
        public void GetProviderHtml_DoesNotContainBadRazorCompilation()
        {
            AppDomainUtils.RunInSeparateAppDomain(
                () =>
            {
                // Arrange
                var stubbedContext = new Mock <HttpContextBase>();
                var contextItems   = new Hashtable();
                stubbedContext.SetupGet(x => x.Items).Returns(contextItems);
                Maps.GetCurrentHttpContext = () => stubbedContext.Object;

                // Act
                string bingResults = Maps.GetBingHtml(
                    "somekey",
                    latitude: "100",
                    longitude: "10"
                    )
                                     .ToHtmlString();
                string googleResults = Maps.GetGoogleHtml(latitude: "100", longitude: "10")
                                       .ToHtmlString();
                string mapQuestResults = Maps.GetMapQuestHtml(
                    "somekey",
                    latitude: "100",
                    longitude: "10"
                    )
                                         .ToHtmlString();

                // Assert
                Assert.DoesNotContain("<text>", bingResults);
                Assert.DoesNotContain("<text>", googleResults);
                Assert.DoesNotContain("<text>", mapQuestResults);
            }
                );
        }
Example #3
0
 public void UrlAnonymousObjectTest()
 {
     AppDomainUtils.RunInSeparateAppDomain(
         () =>
     {
         using (
             IDisposable _ = Utils.CreateHttpContext(
                 "default.aspx",
                 "http://localhost/"
                 ),
             __ = Utils.CreateHttpRuntime("/")
             )
         {
             Assert.Equal(
                 "/world/test.cshtml?Prop1=value1",
                 UrlUtil.GenerateClientUrl(
                     new HttpContextWrapper(HttpContext.Current),
                     "~/world/page.cshtml",
                     "test.cshtml",
                     new { Prop1 = "value1" }
                     )
                 );
             Assert.Equal(
                 "/world/test.cshtml?Prop1=value1&Prop2=value2",
                 UrlUtil.GenerateClientUrl(
                     new HttpContextWrapper(HttpContext.Current),
                     "~/world/page.cshtml",
                     "test.cshtml",
                     new { Prop1 = "value1", Prop2 = "value2" }
                     )
                 );
         }
     }
         );
 }
Example #4
0
        public void CreateUserAndAccount_WillAcceptBothObjectsAndDictionariesForExtendedParameters()
        {
            // since it is a static helper - you gotta love 'em
            AppDomainUtils.RunInSeparateAppDomain(() =>
            {
                // we need that in order to make sure the Membership static class is initialized correctly
                var discard = Membership.Provider as ProviderBase;

                // Arrange
                var providerMock = new Mock <ExtendedMembershipProvider>();
                providerMock.Setup(
                    p => p.CreateUserAndAccount(It.IsAny <string>(), It.IsAny <string>(), It.IsAny <bool>(), It.IsAny <IDictionary <string, object> >()))
                .Returns((string username, string password, bool requireConfirmation, IDictionary <string, object> values) => "foo = " + values["foo"]);
                typeof(Membership).GetField("s_Provider", BindingFlags.Static | BindingFlags.NonPublic).SetValue(null, providerMock.Object);

                // Act
                var resultWithObject     = WebSecurity.CreateUserAndAccount("name", "pass", new { foo = "bar" });
                var resultWithDictionary = WebSecurity.CreateUserAndAccount("name", "pass", new Dictionary <string, object> {
                    { "foo", "baz" }
                });

                // Assert
                Assert.Equal("foo = bar", resultWithObject);
                Assert.Equal("foo = baz", resultWithDictionary);
            });
        }
Example #5
0
        public void StartTest()
        {
            AppDomainUtils.RunInSeparateAppDomain(
                () =>
            {
                AppDomainUtils.SetPreAppStartStage();
                PreApplicationStartCode.Start();
                // Call a second time to ensure multiple calls do not cause issues
                PreApplicationStartCode.Start();

                Assert.False(
                    RouteTable.Routes.RouteExistingFiles,
                    "We should not be setting RouteExistingFiles"
                    );
                Assert.Empty(RouteTable.Routes);

                Assert.False(PageParser.EnableLongStringsAsResources);

                string formsAuthLoginUrl = (string)typeof(FormsAuthentication)
                                           .GetField("_LoginUrl", BindingFlags.Static | BindingFlags.NonPublic)
                                           .GetValue(null);
                Assert.Null(formsAuthLoginUrl);
            }
                );
        }
        public void HtmlEncodeTest()
        {
            AppDomainUtils.RunInSeparateAppDomain(
                () =>
            {
                // Set HideRequestResponse to true to simulate the condition in IIS 7/7.5
                var context = new HttpContext(
                    new HttpRequest("default.cshtml", "http://localhost/default.cshtml", null),
                    new HttpResponse(new StringWriter(new StringBuilder()))
                    );
                var hideRequestResponse = typeof(HttpContext).GetField(
                    "HideRequestResponse",
                    BindingFlags.NonPublic | BindingFlags.Instance
                    );
                hideRequestResponse.SetValue(context, true);

                HttpContext.Current = context;
                var page            = new ApplicationStartPageTest().CreateStartPage(
                    p =>
                {
                    p.Write("test");
                }
                    );
                page.ExecuteStartPage();
            }
                );
        }
        public void GetVersionReturnsLowerVersionIfSpecifiedInConfigAndNotExplicitlyDisabled()
        {
            AppDomainUtils.RunInSeparateAppDomain(
                () =>
            {
                // Arrange - Load v2 Config
                Assembly asm = Assembly.LoadFrom(
                    Path.Combine(
                        _tempPath,
                        @"ConfigTestAssemblies\V2_Signed\System.Web.WebPages.Deployment.dll"
                        )
                    );
                Assert.Equal(new Version(2, 0, 0, 0), asm.GetName().Version);
                Assert.Equal("System.Web.WebPages.Deployment", asm.GetName().Name);

                using (WebUtils.CreateHttpRuntime(@"~\foo", "."))
                {
                    string path = Path.Combine(_tempPath, @"ConfigTestSites\NoCshtmlConfigV1");

                    // Act
                    Version ver             = WebPagesDeployment.GetVersionWithoutEnabledCheck(path);
                    Version explicitVersion = WebPagesDeployment.GetExplicitWebPagesVersion(
                        path
                        );

                    // Assert
                    Assert.Equal(new Version(1, 0, 0, 0), ver);
                    Assert.Equal(new Version(1, 0, 0, 0), explicitVersion);
                }
            }
                );
        }
        public void GetVersionIgnoresUnsignedConfigDll()
        {
            AppDomainUtils.RunInSeparateAppDomain(
                () =>
            {
                // Arrange - Load v2 Config
                Assembly asm = Assembly.LoadFrom(
                    Path.Combine(
                        _tempPath,
                        @"ConfigTestAssemblies\V2_Unsigned\System.Web.WebPages.Deployment.dll"
                        )
                    );
                Assert.Equal(new Version(2, 0, 0, 0), asm.GetName().Version);
                Assert.Equal("System.Web.WebPages.Deployment", asm.GetName().Name);

                using (WebUtils.CreateHttpRuntime(@"~\foo", "."))
                {
                    // Act
                    Version ver = WebPagesDeployment.GetVersionWithoutEnabledCheck(
                        Path.Combine(_tempPath, @"ConfigTestSites\CshtmlFileNoVersion")
                        );

                    // Assert
                    Assert.Equal(new Version("1.0.0.0"), ver);
                }
            }
                );
        }
Example #9
0
        public void ExecuteWithinInitTest()
        {
            AppDomainUtils.RunInSeparateAppDomain(
                () =>
            {
                Utils.CreateHttpRuntime("/subfolder1/website1");
                new HostingEnvironment();
                var stringSet = Activator.CreateInstance(
                    typeof(BuildManager).Assembly.GetType("System.Web.Util.StringSet"),
                    true
                    );
                typeof(BuildManager)
                .GetField(
                    "_forbiddenTopLevelDirectories",
                    BindingFlags.Instance | BindingFlags.NonPublic
                    )
                .SetValue(new MockInitPage().GetBuildManager(), stringSet);
                ;

                var init = new MockInitPage()
                {
                    VirtualPath   = "~/_pagestart.cshtml",
                    ExecuteAction = p => { },
                };
                var page = Utils.CreatePage(p => { });

                Utils.AssignObjectFactoriesAndDisplayModeProvider(page, init);

                var result = Utils.RenderWebPage(page);
            }
                );
        }
Example #10
0
        public void IsWithinAppRootTest()
        {
            AppDomainUtils.RunInSeparateAppDomain(
                () =>
            {
                var root = "/website1";
                using (Utils.CreateHttpRuntime(root))
                {
                    Assert.True(PathUtil.IsWithinAppRoot(root, "~/"));
                    Assert.True(PathUtil.IsWithinAppRoot(root, "~/default.cshtml"));
                    Assert.True(PathUtil.IsWithinAppRoot(root, "~/test/default.cshtml"));
                    Assert.True(PathUtil.IsWithinAppRoot(root, "/website1"));
                    Assert.True(PathUtil.IsWithinAppRoot(root, "/website1/"));
                    Assert.True(PathUtil.IsWithinAppRoot(root, "/website1/default.cshtml"));
                    Assert.True(
                        PathUtil.IsWithinAppRoot(root, "/website1/test/default.cshtml")
                        );

                    Assert.False(PathUtil.IsWithinAppRoot(root, "/"));
                    Assert.False(PathUtil.IsWithinAppRoot(root, "/website2"));
                    Assert.False(PathUtil.IsWithinAppRoot(root, "/subfolder1/"));
                }
            }
                );
        }
        public void GetVersionReturnsV1IfCshtmlFilePresentButNoVersionIsSpecifiedInConfigOrBin()
        {
            AppDomainUtils.RunInSeparateAppDomain(
                () =>
            {
                // Arrange - Load v2 Config
                Assembly asm = Assembly.LoadFrom(
                    Path.Combine(
                        _tempPath,
                        @"ConfigTestAssemblies\V2_Signed\System.Web.WebPages.Deployment.dll"
                        )
                    );
                Assert.Equal(new Version(2, 0, 0, 0), asm.GetName().Version);
                Assert.Equal("System.Web.WebPages.Deployment", asm.GetName().Name);

                using (WebUtils.CreateHttpRuntime(@"~\foo", "."))
                {
                    string path = Path.Combine(
                        _tempPath,
                        @"ConfigTestSites\CshtmlFileNoVersion"
                        );

                    // Act
                    Version ver             = WebPagesDeployment.GetVersionWithoutEnabledCheck(path);
                    Version explicitVersion = WebPagesDeployment.GetExplicitWebPagesVersion(
                        path
                        );

                    // Assert
                    Assert.Equal(new Version("1.0.0.0"), ver);
                    Assert.Null(explicitVersion);
                }
            }
                );
        }
        public void GenerateClientUrl_ResolvesRelativePathToSubfolder_WithApplicationPath()
        {
            AppDomainUtils.RunInSeparateAppDomain(() =>
            {
                using (IDisposable _ = Utils.CreateHttpContext("default.aspx", "http://localhost/WebSite1/subfolder1/default.aspx"),
                       __ = Utils.CreateHttpRuntime("/WebSite1/"))
                {
                    // Arrange
                    var vpath    = "~/subfolder1/default.aspx";
                    var href     = "world/test.aspx";
                    var expected = "/WebSite1/subfolder1/world/test.aspx";
                    var context  = new HttpContextWrapper(HttpContext.Current);
                    var page     = new MockPage()
                    {
                        VirtualPath = vpath, Context = context
                    };

                    // Act
                    var actual1 = UrlUtil.GenerateClientUrl(context, vpath, href);
                    var actual2 = page.Href(href);

                    // Assert
                    Assert.Equal(expected, actual1);
                    Assert.Equal(expected, actual2);
                }
            });
        }
        public void FileExistsReturnsTrueForExistingPath_VPPRegistrationChanging()
        {
            AppDomainUtils.RunInSeparateAppDomain(() =>
            {
                // Arrange
                AppDomainUtils.SetAppData();
                new HostingEnvironment();

                // Expect null beforeProvider since hosting environment hasn't been initialized
                VirtualPathProvider beforeProvider = HostingEnvironment.VirtualPathProvider;
                string testPath = "/Path.txt";
                VirtualPathProvider afterProvider       = CreatePathProvider(testPath);
                Mock <VirtualPathProvider> mockProvider = Mock.Get(afterProvider);

                TestableBuildManagerViewEngine engine = new TestableBuildManagerViewEngine();

                // Act
                VirtualPathProvider beforeEngineProvider = engine.VirtualPathProvider;
                HostingEnvironment.RegisterVirtualPathProvider(afterProvider);

                bool result = engine.FileExists(testPath);
                VirtualPathProvider afterEngineProvider = engine.VirtualPathProvider;

                // Assert
                Assert.True(result);
                Assert.Equal(beforeProvider, beforeEngineProvider);
                Assert.Equal(afterProvider, afterEngineProvider);

                mockProvider.Verify();
                mockProvider.Verify(c => c.FileExists(It.IsAny <String>()), Times.Once());
            });
        }
 public void StartTest()
 {
     AppDomainUtils.RunInSeparateAppDomain(() => {
         AppDomainUtils.SetPreAppStartStage();
         PreApplicationStartCode.Start();
         var buildProviders = typeof(BuildProvider).GetField("s_dynamicallyRegisteredProviders", BindingFlags.Static | BindingFlags.NonPublic).GetValue(null);
         Assert.AreEqual(2, buildProviders.GetType().GetProperty("Count", BindingFlags.Public | BindingFlags.Instance).GetValue(buildProviders, new object[] { }));
     });
 }
Example #15
0
 public void StartCanRunTwice()
 {
     AppDomainUtils.RunInSeparateAppDomain(() => {
         AppDomainUtils.SetPreAppStartStage();
         PreApplicationStartCode.Start();
         // Call a second time to ensure multiple calls do not cause issues
         PreApplicationStartCode.Start();
     });
 }
Example #16
0
 public void FileExistsTest()
 {
     AppDomainUtils.RunInSeparateAppDomain(() => {
         var path = "~/index.cshtml";
         Utils.SetupVirtualPathInAppDomain(path, "");
         var cache = FileExistenceCache.GetInstance();
         Assert.IsTrue(cache.FileExists(path));
         Assert.IsFalse(cache.FileExists("~/test.cshtml"));
     });
 }
Example #17
0
 public void InitializeApplicationTest()
 {
     AppDomainUtils.RunInSeparateAppDomain(() => {
         var moduleEvents = new ModuleEvents();
         var app          = new MyHttpApplication();
         WebPageHttpModule.InitializeApplication(app,
                                                 moduleEvents.OnApplicationPostResolveRequestCache,
                                                 moduleEvents.Initialize);
         Assert.IsTrue(moduleEvents.CalledInitialize);
     });
 }
        public void StartInitializesFormsAuthByDefault()
        {
            AppDomainUtils.RunInSeparateAppDomain(() =>
            {
                AppDomainUtils.SetPreAppStartStage();
                PreApplicationStartCode.Start();

                string formsAuthLoginUrl = (string)typeof(FormsAuthentication).GetField("_LoginUrl", BindingFlags.Static | BindingFlags.NonPublic).GetValue(null);
                Assert.Equal(FormsAuthenticationSettings.DefaultLoginUrl, formsAuthLoginUrl);
            });
        }
Example #19
0
 public void StartPageBasicTest()
 {
     AppDomainUtils.RunInSeparateAppDomain(() => {
         var page = new ApplicationStartPageTest().CreateStartPage(p => {
             p.AppState["x"] = "y";
             p.WriteLiteral("test");
         });
         page.ExecuteInternal();
         Assert.AreEqual("y", page.ApplicationState["x"]);
         Assert.AreEqual("test", ApplicationStartPage.Markup.ToHtmlString());
     });
 }
Example #20
0
 public void ExceptionTest()
 {
     AppDomainUtils.RunInSeparateAppDomain(() =>
     {
         var msg  = "This is an error message";
         var e    = new InvalidOperationException(msg);
         var page = new ApplicationStartPageTest().CreateStartPage(p => { throw e; });
         var ex   = Assert.Throws <HttpException>(() => page.ExecuteStartPage());
         Assert.Equal(msg, ex.InnerException.Message);
         Assert.Equal(e, ApplicationStartPage.Exception);
     });
 }
        public void StartDoesNotInitializeFormsAuthWhenDisabled()
        {
            AppDomainUtils.RunInSeparateAppDomain(() =>
            {
                AppDomainUtils.SetPreAppStartStage();
                ConfigurationManager.AppSettings[WebSecurity.EnableSimpleMembershipKey] = "False";
                PreApplicationStartCode.Start();

                string formsAuthLoginUrl = (string)typeof(FormsAuthentication).GetField("_LoginUrl", BindingFlags.Static | BindingFlags.NonPublic).GetValue(null);
                Assert.Null(formsAuthLoginUrl);
            });
        }
        public void StartTest()
        {
            AppDomainUtils.RunInSeparateAppDomain(() => {
                // Act
                AppDomainUtils.SetPreAppStartStage();
                PreApplicationStartCode.Start();

                // Assert
                var imports = WebPageRazorHost.GetGlobalImports();
                Assert.IsTrue(imports.Any(ns => ns.Equals("Microsoft.Web.Helpers")));
            });
        }
Example #23
0
        public void ServerInfoDoesNotProduceLegacyCasForHomogenousAppDomain()
        {
            // Act and Assert
            Action action = () =>
            {
                IDictionary <string, string> configValue = ServerInfo.LegacyCAS(AppDomain.CurrentDomain);

                Assert.NotNull(configValue);
                Assert.Equal(0, configValue.Count);
            };

            AppDomainUtils.RunInSeparateAppDomain(GetAppDomainSetup(legacyCasEnabled: false), action);
        }
        public void StartInitializesSimpleMembershipByDefault()
        {
            AppDomainUtils.RunInSeparateAppDomain(() =>
            {
                AppDomainUtils.SetPreAppStartStage();
                PreApplicationStartCode.Start();

                // Verify simple membership
                var providers = Membership.Providers;
                Assert.NotEmpty(providers.OfType <SimpleMembershipProvider>());
                Assert.True(Roles.Enabled);
            });
        }
        public void StartDoesNotInitializeSimpleMembershipWhenDisabled()
        {
            AppDomainUtils.RunInSeparateAppDomain(() =>
            {
                AppDomainUtils.SetPreAppStartStage();
                ConfigurationManager.AppSettings[WebSecurity.EnableSimpleMembershipKey] = "False";
                PreApplicationStartCode.Start();

                // Verify simple membership
                var providers = Membership.Providers;
                Assert.Empty(providers.OfType <SimpleMembershipProvider>());
                Assert.False(Roles.Enabled);
            });
        }
Example #26
0
        public void ServerInfoProducesLegacyCasForNonHomogenousAppDomain()
        {
            // Arrange
            Action action = () => {
                // Act and Assert
                IDictionary <string, string> configValue = ServerInfo.LegacyCAS(AppDomain.CurrentDomain);

                // Assert
                Assert.IsTrue(configValue.ContainsKey("Legacy Code Access Security"));
                Assert.AreEqual(configValue["Legacy Code Access Security"], "Legacy Code Access Security has been detected on your system. Microsoft WebPage features require the ASP.NET 4 Code Access Security model. For information about how to resolve this, contact your server administrator.");
            };

            AppDomainUtils.RunInSeparateAppDomain(GetAppDomainSetup(legacyCasEnabled: true), action);
        }
Example #27
0
 public void FileExistsTimeExceededTest()
 {
     AppDomainUtils.RunInSeparateAppDomain(() => {
         var path = "~/index.cshtml";
         Utils.SetupVirtualPathInAppDomain(path, "");
         var cache                     = FileExistenceCache.GetInstance();
         var cacheInternal             = cache.CacheInternal;
         cache.MilliSecondsBeforeReset = 5;
         Thread.Sleep(300);
         Assert.IsTrue(cache.FileExists(path));
         Assert.IsFalse(cache.FileExists("~/test.cshtml"));
         Assert.AreNotEqual(cacheInternal, cache.CacheInternal);
     });
 }
        public void StartRegistersRazorNamespaces()
        {
            AppDomainUtils.RunInSeparateAppDomain(() =>
            {
                AppDomainUtils.SetPreAppStartStage();
                PreApplicationStartCode.Start();
                // Call a second time to ensure multiple calls do not cause issues
                PreApplicationStartCode.Start();

                // Verify namespaces
                var imports = WebPageRazorHost.GetGlobalImports();
                Assert.Contains(imports, ns => ns.Equals("WebMatrix.Data"));
                Assert.Contains(imports, ns => ns.Equals("WebMatrix.WebData"));
            });
        }
Example #29
0
 public void ExecuteStartPageTest()
 {
     AppDomainUtils.RunInSeparateAppDomain(() => {
         var startPage = new MockStartPage()
         {
             ExecuteAction = p => p.AppState["x"] = "y"
         };
         ApplicationStartPage.ExecuteStartPage(new WebPageHttpApplication(),
                                               p => { },
                                               path => path == "~/_appstart.vbhtml",
                                               p => startPage,
                                               new string[] { "cshtml", "vbhtml" });
         Assert.AreEqual("y", startPage.ApplicationState["x"]);
     });
 }
Example #30
0
        public void ViewContextGlobalValidationMessageElementAffectsLocalOne()
        {
            // Arrange
            AppDomainUtils.RunInSeparateAppDomain(
                () =>
            {
                var httpContext = new Mock <HttpContextBase>();
                ScopeStorageDictionary localScope = null;
                var globalViewContext             = new ViewContext
                {
                    ScopeThunk  = () => ScopeStorage.GlobalScope,
                    HttpContext = httpContext.Object
                };
                var localViewContext = new ViewContext
                {
                    ScopeThunk = () =>
                    {
                        if (localScope == null)
                        {
                            localScope = new ScopeStorageDictionary(ScopeStorage.GlobalScope);
                        }
                        ;
                        return(localScope);
                    },
                    HttpContext = httpContext.Object
                };
                // A ScopeCache object will be stored into the hash table but the ScopeCache class is private,
                // so we cannot get the validation message element from it for Assert.
                httpContext.Setup(c => c.Items).Returns(new Hashtable());

                // Act
                globalViewContext.ValidationMessageElement = "label";

                // Assert
                // Global element was changed from "span" to "label".
                Assert.Equal("label", HtmlHelper.ValidationMessageElement);
                Assert.Equal("label", globalViewContext.ValidationMessageElement);
                object value;
                ScopeStorage.GlobalScope.TryGetValue("ValidationMessageElement", out value);
                Assert.Equal("label", value);

                // Local element was also changed to "label".
                Assert.Equal("label", localViewContext.ValidationMessageElement);
                localScope.TryGetValue("ValidationMessageElement", out value);
                Assert.Equal("label", value);
            }
                );
        }