public void CreateInstanceUsesRegisteredFactoriesForExistence()
        {
            // Arrange
            var path = "~/index.cshtml";
            var factory1 = new Mock<IVirtualPathFactory>();
            factory1.Setup(c => c.Exists(path)).Returns(false).Verifiable();
            var factory2 = new Mock<IVirtualPathFactory>();
            factory2.Setup(c => c.Exists(path)).Returns(true).Verifiable();
            var factory3 = new Mock<IVirtualPathFactory>();
            factory3.Setup(c => c.Exists(path)).Throws(new Exception("This factory should not be called since the page has already been found in 2"));
            var defaultFactory = new Mock<IVirtualPathFactory>();
            defaultFactory.Setup(c => c.Exists(path)).Throws(new Exception("This factory should not be called since it always called last"));

            var vpfm = new VirtualPathFactoryManager(defaultFactory.Object);
            vpfm.RegisterVirtualPathFactoryInternal(factory1.Object);
            vpfm.RegisterVirtualPathFactoryInternal(factory2.Object);
            vpfm.RegisterVirtualPathFactoryInternal(factory3.Object);

            // Act
            var result = vpfm.Exists(path);

            // Assert
            Assert.True(result);

            factory1.Verify();
            factory2.Verify();
        }
        public void DefaultFactoryIsListedInRegisteredFactories()
        {
            // Arrange
            var factory = new HashVirtualPathFactory();

            // Act
            var factoryManager = new VirtualPathFactoryManager(factory);

            // Assert
            Assert.Equal(factory, factoryManager.RegisteredFactories.Single());
        }
예제 #3
0
        public static void Start()
        {
            var engine = new PrecompiledMvcEngine(typeof(RazorGeneratorMvcStart).Assembly)
            {
                UsePhysicalViewsIfNewer = HttpContext.Current.Request.IsLocal
            };

            ViewEngines.Engines.Insert(0, engine);

            // StartPage lookups are done by WebPages.
            VirtualPathFactoryManager.RegisterVirtualPathFactory(engine);
        }
        public void GenericCreateInstanceReturnsNullIfNoFactoryCanCreateVirtualPath()
        {
            // Arrange
            var factory1 = new HashVirtualPathFactory(Utils.CreatePage(_ => { }, "~/index.cshtml"));
            var factory2 = new HashVirtualPathFactory(Utils.CreatePage(null, "~/_admin/index.cshtml"));

            // Act
            var factoryManager = new VirtualPathFactoryManager(factory2);
            factoryManager.RegisterVirtualPathFactoryInternal(factory1);
            var page = factoryManager.CreateInstance<WebPageBase>("~/does-not-exist.cshtml");

            // Assert
            Assert.Null(page);
        }
        public static void RazorGeneratorMvcInit()
        {
            var engineAssemblies = AppDomain.CurrentDomain.GetAssemblies()
                                   .Where(assembly => assembly.GetTypes().Any(t => t.BaseType == typeof(ModuleTag)));

            engineAssemblies.ForEach(assembly =>
            {
                var engine = new PrecompiledMvcEngine(assembly)
                {
                    UsePhysicalViewsIfNewer = HttpContext.Current.Request.IsLocal
                };
                ViewEngines.Engines.Insert(0, engine);
                VirtualPathFactoryManager.RegisterVirtualPathFactory(engine);
            });
        }
예제 #6
0
        public void GenericCreateInstanceReturnsNullIfNoFactoryCanCreateVirtualPath()
        {
            // Arrange
            var factory1 = new HashVirtualPathFactory(Utils.CreatePage(_ => { }, "~/index.cshtml"));
            var factory2 = new HashVirtualPathFactory(Utils.CreatePage(null, "~/_admin/index.cshtml"));

            // Act
            var factoryManager = new VirtualPathFactoryManager(factory2);

            factoryManager.RegisterVirtualPathFactoryInternal(factory1);
            var page = factoryManager.CreateInstance <WebPageBase>("~/does-not-exist.cshtml");

            // Assert
            Assert.Null(page);
        }
예제 #7
0
        // Helper to test smarty route match, null match string is used for no expected match
        private void ConstraintTest(IEnumerable<string> validFiles, IEnumerable<string> supportedExt, string url, string match, string pathInfo) {
            HashyVPP vpp = new HashyVPP(validFiles);
            var virtualPathFactoryManager = new VirtualPathFactoryManager(vpp);

            WebPageMatch smartyMatch = WebPageRoute.MatchRequest(url, supportedExt, virtualPathFactoryManager);
            if (match != null) {
                Assert.IsNotNull(smartyMatch, "Should have found a match: "+match);
                Assert.AreEqual(match, smartyMatch.MatchedPath);
                Assert.AreEqual(pathInfo, smartyMatch.PathInfo);
            }
            else {
                Assert.IsNull(smartyMatch, "unexpected match");
            }

        }
예제 #8
0
        /// <summary>
        /// Loads available assemblies.
        /// </summary>
        internal static void LoadAssemblies()
        {
            using (var container = ContextScopeProvider.CreateChildContainer())
            {
                if (container == null)
                {
                    throw new CmsException("Better CMS dependencies container is not initialized.");
                }

                if (HostingEnvironment.IsHosted)
                {
                    HostingEnvironment.RegisterVirtualPathProvider(new EmbeddedResourcesVirtualPathProvider(container.Resolve <IEmbeddedResourcesProvider>()));
                }
                else
                {
                    throw new CmsException("Failed to register EmbeddedResourcesVirtualPathProvider as a virtual path provider.");
                }

                ControllerBuilder.Current.SetControllerFactory(container.Resolve <DefaultCmsControllerFactory>());

                IAssemblyManager assemblyManager = container.Resolve <IAssemblyManager>();

                // First add referenced modules...
                assemblyManager.AddReferencedModules();

                // ...then scan and register uploaded modules.
                assemblyManager.AddUploadedModules();

                var moduleRegistration = container.Resolve <IModulesRegistration>();
                moduleRegistration.InitializeModules();

                // Register precompiled views for all the assemblies
                var precompiledAssemblies = new List <PrecompiledViewAssembly>();
                moduleRegistration.GetModules().Select(m => m.ModuleDescriptor).Distinct().ForEach(
                    descriptor =>
                {
                    var precompiledAssembly = new PrecompiledViewAssembly(descriptor.GetType().Assembly, string.Format("~/Areas/{0}/", descriptor.AreaName))
                    {
                        UsePhysicalViewsIfNewer = false
                    };
                    precompiledAssemblies.Add(precompiledAssembly);
                });

                var engine = new CompositePrecompiledMvcEngine(precompiledAssemblies.ToArray());
                ViewEngines.Engines.Insert(0, engine);
                VirtualPathFactoryManager.RegisterVirtualPathFactory(engine);
            }
        }
예제 #9
0
        public static void Start()
        {
            if (_startMethodExecuted == true)
            {
                return;
            }

            var engine = new PrecompiledMvcEngine(typeof(MvcSample.PreApplicationStartCode).Assembly);

            ViewEngines.Engines.Insert(0, engine);

            // StartPage lookups are done by WebPages.
            VirtualPathFactoryManager.RegisterVirtualPathFactory(engine);

            _startMethodExecuted = true;
        }
        public void GenericCreateInstanceLoopsOverAllRegisteredFactories()
        {
            // Arrange
            var virtualPath = "~/index.cshtml";
            var mockPage = Utils.CreatePage(_ => { }, virtualPath);
            var factory1 = new HashVirtualPathFactory(mockPage);
            var factory2 = new HashVirtualPathFactory(Utils.CreatePage(null, "~/_admin/index.cshtml"));

            // Act
            var factoryManager = new VirtualPathFactoryManager(factory2);
            factoryManager.RegisterVirtualPathFactoryInternal(factory1);
            var page = factoryManager.CreateInstance<WebPageBase>(virtualPath);

            // Assert
            Assert.Equal(mockPage, page);
        }
        public void VirtualPathFactoryExtensionsSpecialCasesVirtualPathFactoryManager()
        {
            // Arrange
            var virtualPath = "~/index.cshtml";
            var mockPage = Utils.CreatePage(_ => { }, virtualPath);
            var factory = new Mock<IVirtualPathFactory>();
            factory.Setup(c => c.Exists(virtualPath)).Returns(true).Verifiable();
            factory.Setup(c => c.CreateInstance(virtualPath)).Returns(mockPage);

            // Act
            var factoryManager = new VirtualPathFactoryManager(factory.Object);
            var page = factoryManager.CreateInstance<WebPageBase>(virtualPath);

            // Assert
            Assert.Equal(mockPage, page);
            factory.Verify();
        }
예제 #12
0
        protected override void OnStartProvider()
        {
            var property = typeof(VirtualPathFactoryManager).GetProperty("Instance", BindingFlags.NonPublic | BindingFlags.Static);

            if (property != null)
            {
                var member = typeof(VirtualPathFactoryManager).GetField("_virtualPathFactories", BindingFlags.NonPublic | BindingFlags.Instance);
                if (member != null)
                {
                    var instance = (VirtualPathFactoryManager)property.GetValue(null);
                    var list     = (LinkedList <IVirtualPathFactory>)member.GetValue(instance);
                    var factory  = list.First.Value;
                    _previousPathFactory = factory;
                    VirtualPathFactoryManager.RegisterVirtualPathFactory(this);
                }
            }
        }
예제 #13
0
        public void GenericCreateInstanceLoopsOverAllRegisteredFactories()
        {
            // Arrange
            var virtualPath = "~/index.cshtml";
            var mockPage    = Utils.CreatePage(_ => { }, virtualPath);
            var factory1    = new HashVirtualPathFactory(mockPage);
            var factory2    = new HashVirtualPathFactory(Utils.CreatePage(null, "~/_admin/index.cshtml"));

            // Act
            var factoryManager = new VirtualPathFactoryManager(factory2);

            factoryManager.RegisterVirtualPathFactoryInternal(factory1);
            var page = factoryManager.CreateInstance <WebPageBase>(virtualPath);

            // Assert
            Assert.Equal(mockPage, page);
        }
        public static void Start()
        {
            var engine = new PrecompiledMvcEngine(typeof(RazorGeneratorMvcStart).Assembly)
            {
#if DEBUG
                UsePhysicalViewsIfNewer = true
#else
                UsePhysicalViewsIfNewer = false
#endif
            };

            ViewEngines.Engines.Insert(0, engine);

            // StartPage lookups are done by WebPages.
            VirtualPathFactoryManager.RegisterVirtualPathFactory(engine);
        }
    }
        public static void Start()
        {
            bool usePrecompiledViews;

            if (!bool.TryParse(ConfigurationManager.AppSettings["UsePrecompiledViews"] ?? "", out usePrecompiledViews))
            {
                usePrecompiledViews = false;
            }

            if (usePrecompiledViews)
            {
                // use dynamically compiled views
                var engine = new PrecompiledMvcEngine(typeof(PrecompiledMvcViewEngineStart).Assembly);
                ViewEngines.Engines.Insert(0, engine);
                // StartPage lookups are done by WebPages.
                VirtualPathFactoryManager.RegisterVirtualPathFactory(engine);
            }
        }
예제 #16
0
        // Helper to test smarty route match, null match string is used for no expected match
        private void ConstraintTest(IEnumerable <string> validFiles, IEnumerable <string> supportedExt, string url, string match, string pathInfo)
        {
            HashyVPP vpp = new HashyVPP(validFiles);
            var      virtualPathFactoryManager = new VirtualPathFactoryManager(vpp);

            WebPageMatch smartyMatch = WebPageRoute.MatchRequest(url, supportedExt, virtualPathFactoryManager);

            if (match != null)
            {
                Assert.IsNotNull(smartyMatch, "Should have found a match: " + match);
                Assert.AreEqual(match, smartyMatch.MatchedPath);
                Assert.AreEqual(pathInfo, smartyMatch.PathInfo);
            }
            else
            {
                Assert.IsNull(smartyMatch, "unexpected match");
            }
        }
예제 #17
0
        public static PrecompiledMvcEngine Initialize(Type t, ContainerBuilder container)
        {
            var pathProvider = GetPathProvider(t);
            var engine       = new PhysicalWrapperEngine(t.Assembly, pathProvider)
            {
                UsePhysicalViewsIfNewer = true,
                AreaViewLocationFormats = new[] { "~/{2}/{1}/{0}.cshtml" }
            };

            ViewEngines.Engines.Insert(0, engine);

            // StartPage lookups are done by WebPages.
            VirtualPathFactoryManager.RegisterVirtualPathFactory(engine);

            container.RegisterInstance(pathProvider).AsImplementedInterfaces();

            return(engine);
        }
예제 #18
0
        public void VirtualPathFactoryExtensionsSpecialCasesVirtualPathFactoryManager()
        {
            // Arrange
            var virtualPath = "~/index.cshtml";
            var mockPage    = Utils.CreatePage(_ => { }, virtualPath);
            var factory     = new Mock <IVirtualPathFactory>();

            factory.Setup(c => c.Exists(virtualPath)).Returns(true).Verifiable();
            factory.Setup(c => c.CreateInstance(virtualPath)).Returns(mockPage);

            // Act
            var factoryManager = new VirtualPathFactoryManager(factory.Object);
            var page           = factoryManager.CreateInstance <WebPageBase>(virtualPath);

            // Assert
            Assert.Equal(mockPage, page);
            factory.Verify();
        }
예제 #19
0
        /// <summary>
        /// Loads available assemblies.
        /// </summary>
        public static void LoadAssemblies()
        {
            ApplicationContext.LoadAssemblies();

            using (var container = ContextScopeProvider.CreateChildContainer())
            {
                if (HostingEnvironment.IsHosted)
                {
                    HostingEnvironment.RegisterVirtualPathProvider(new EmbeddedResourcesVirtualPathProvider(container.Resolve <IEmbeddedResourcesProvider>()));
                }
                else
                {
                    if (!IsTestMode)
                    {
                        throw new CoreException("Failed to register EmbeddedResourcesVirtualPathProvider as a virtual path provider.");
                    }
                }

                ControllerBuilder.Current.SetControllerFactory(container.Resolve <DefaultWebControllerFactory>());

                // Register precompiled views for all the assemblies
                var precompiledAssemblies = new List <PrecompiledViewAssembly>();

                var moduleRegistration = container.Resolve <IModulesRegistration>();
                moduleRegistration.GetModules().Select(m => m.ModuleDescriptor).Distinct().ToList().ForEach(
                    descriptor =>
                {
                    var webDescriptor = descriptor as WebModuleDescriptor;
                    if (webDescriptor != null)
                    {
                        var precompiledAssembly = new PrecompiledViewAssembly(descriptor.GetType().Assembly, string.Format("~/Areas/{0}/", webDescriptor.AreaName))
                        {
                            UsePhysicalViewsIfNewer = false
                        };
                        precompiledAssemblies.Add(precompiledAssembly);
                    }
                });

                var engine = new CompositePrecompiledMvcEngine(precompiledAssemblies.ToArray());
                ViewEngines.Engines.Add(engine);
                VirtualPathFactoryManager.RegisterVirtualPathFactory(engine);
            }
        }
        public void CreateInstanceLooksThroughAllRegisteredFactoriesForExistence()
        {
            // Arrange
            var page     = Utils.CreatePage(null);
            var factory1 = new Mock <IVirtualPathFactory>();

            factory1.Setup(c => c.Exists(page.VirtualPath)).Returns(false).Verifiable();
            var factory2 = new Mock <IVirtualPathFactory>();

            factory2.Setup(c => c.Exists(page.VirtualPath)).Returns(true).Verifiable();
            factory2.Setup(c => c.CreateInstance(page.VirtualPath)).Returns(page).Verifiable();
            var factory3 = new Mock <IVirtualPathFactory>();

            factory3
            .Setup(c => c.Exists(page.VirtualPath))
            .Throws(
                new Exception(
                    "This factory should not be called since the page has already been found in 2"
                    )
                );
            var defaultFactory = new Mock <IVirtualPathFactory>();

            defaultFactory
            .Setup(c => c.Exists(page.VirtualPath))
            .Throws(
                new Exception("This factory should not be called since it always called last")
                );

            var vpfm = new VirtualPathFactoryManager(defaultFactory.Object);

            vpfm.RegisterVirtualPathFactoryInternal(factory1.Object);
            vpfm.RegisterVirtualPathFactoryInternal(factory2.Object);
            vpfm.RegisterVirtualPathFactoryInternal(factory3.Object);

            // Act
            var result = vpfm.CreateInstance(page.VirtualPath);

            // Assert
            Assert.Equal(page, result);

            factory1.Verify();
            factory2.Verify();
        }
예제 #21
0
        public static void ApplicationStart()
        {
            DatabaseBootstrapper.Bootstrap();

            MvcHandler.DisableMvcResponseHeader = true;

            //AreaRegistration.RegisterAllAreas();
            RegisterGlobalFilters(GlobalFilters.Filters);
            RegisterRoutes(RouteTable.Routes);
            RegisterBundles(BundleTable.Bundles);

            ViewEngines.Engines.Clear();
            var engine = new ViewModelSpecifiedViewEngine();

            ViewEngines.Engines.Insert(0, engine);
            VirtualPathFactoryManager.RegisterVirtualPathFactory(engine);

            SetupMiniProfiler();
        }
예제 #22
0
        private void RegisterViewEngine()
        {
            var engine = new PhysicalWrapperEngine(GetType().Assembly, CreateCorePathProvider());

            engine.ViewLocationFormats = engine.ViewLocationFormats.Concat(new[]
            {
                "~/{1}Module/{0}.cshtml",
            }).ToArray();

            engine.PartialViewLocationFormats = engine.PartialViewLocationFormats.Concat(new string[]
            {
                "~/{1}Module/{0}.cshtml",
            }).ToArray();

            ViewEngines.Engines.Insert(0, engine);

            // StartPage lookups are done by WebPages.
            VirtualPathFactoryManager.RegisterVirtualPathFactory(engine);
        }
예제 #23
0
        private static string GetRouteLevelMatch(string pathValue, IEnumerable<string> supportedExtensions, VirtualPathFactoryManager virtualPathFactoryManager) {
            foreach (string supportedExtension in supportedExtensions) {
                string virtualPath = pathValue;

                // Only add the extension if it's not already there
                if (!virtualPath.EndsWith("." + supportedExtension, StringComparison.OrdinalIgnoreCase)) {
                    virtualPath += "." + supportedExtension;
                }
                if (FileExists(virtualPath, virtualPathFactoryManager)) {
                    // If there's an exact match on disk, return it unless it starts with an underscore
                    if (Path.GetFileName(pathValue).StartsWith("_", StringComparison.OrdinalIgnoreCase)) {
                        throw new HttpException(WebPageResources.WebPageRoute_UnderscoreBlocked);
                    }

                    return virtualPath;
                }
            }

            return null;
        }
        public void RegisterFactoryEnsuresDefaultFactoryRemainsTheLast()
        {
            // Arrange
            var defaultFactory = new HashVirtualPathFactory();
            var factory1 = new HashVirtualPathFactory();
            var factory2 = new HashVirtualPathFactory();
            var factory3 = new HashVirtualPathFactory();

            // Act
            var factoryManager = new VirtualPathFactoryManager(defaultFactory);
            factoryManager.RegisterVirtualPathFactoryInternal(factory1);
            factoryManager.RegisterVirtualPathFactoryInternal(factory2);
            factoryManager.RegisterVirtualPathFactoryInternal(factory3);

            // Assert
            Assert.Equal(factory1, factoryManager.RegisteredFactories.ElementAt(0));
            Assert.Equal(factory2, factoryManager.RegisteredFactories.ElementAt(1));
            Assert.Equal(factory3, factoryManager.RegisteredFactories.ElementAt(2));
            Assert.Equal(defaultFactory, factoryManager.RegisteredFactories.Last());
        }
예제 #25
0
        protected void Application_Start()
        {
            var engine = new PrecompiledMvcEngine(typeof(MvcApplication).Assembly)
            {
                UsePhysicalViewsIfNewer = false,
                PreemptPhysicalFiles    = true
            };

            ViewEngines.Engines.Insert(0, engine);

            // StartPage lookups are done by WebPages.
            VirtualPathFactoryManager.RegisterVirtualPathFactory(engine);

            AreaRegistration.RegisterAllAreas();

            RegisterGlobalFilters(GlobalFilters.Filters);
            RegisterRoutes(RouteTable.Routes);

            ControllerBuilder.Current.SetControllerFactory(new DependencyControllerFactory());
        }
        internal static IHttpHandler CreateFromVirtualPath(string virtualPath, VirtualPathFactoryManager virtualPathFactoryManager) {
            // Instantiate the page from the virtual path
            object instance = virtualPathFactoryManager.CreateInstance<object>(virtualPath);

            WebPage page = instance as WebPage;

            // If it's not a page, assume it's a regular handler
            if (page == null) {
                return (IHttpHandler)instance;
            }

            // Mark it as a 'top level' page (as opposed to a user control or master)
            page.TopLevelPage = true;

            // Give it its virtual path
            page.VirtualPath = virtualPath;

            // Return a handler over it
            return new WebPageHttpHandler(page);
        }
        public static void Start()
        {
            var engine = new PrecompiledMvcEngine(typeof(RazorGeneratorMvcStart).Assembly)
            {
                UsePhysicalViewsIfNewer = HttpContext.Current.Request.IsLocal
            };

            ViewEngines.Engines.Insert(0, engine);

            // StartPage lookups are done by WebPages.
            VirtualPathFactoryManager.RegisterVirtualPathFactory(engine);

            // ³õʼ»¯¿ò¼Ü
            App.Init();
            App.OperationLogger = (position, target, type, message) => AppSettings.Entrance.Logger(position, target, type, message);

            WebApiConfigBase.Register(GlobalConfiguration.Configuration);
            FilterConfigBase.RegisterGlobalFilters(GlobalFilters.Filters);
            RouteConfigBase.RegisterRoutes(RouteTable.Routes);
            BundleConfigBase.RegisterBundles(BundleTable.Bundles);
        }
        public void RegisterFactoryEnsuresDefaultFactoryRemainsTheLast()
        {
            // Arrange
            var defaultFactory = new HashVirtualPathFactory();
            var factory1       = new HashVirtualPathFactory();
            var factory2       = new HashVirtualPathFactory();
            var factory3       = new HashVirtualPathFactory();

            // Act
            var factoryManager = new VirtualPathFactoryManager(defaultFactory);

            factoryManager.RegisterVirtualPathFactoryInternal(factory1);
            factoryManager.RegisterVirtualPathFactoryInternal(factory2);
            factoryManager.RegisterVirtualPathFactoryInternal(factory3);

            // Assert
            Assert.Equal(factory1, factoryManager.RegisteredFactories.ElementAt(0));
            Assert.Equal(factory2, factoryManager.RegisteredFactories.ElementAt(1));
            Assert.Equal(factory3, factoryManager.RegisteredFactories.ElementAt(2));
            Assert.Equal(defaultFactory, factoryManager.RegisteredFactories.Last());
        }
예제 #29
0
        /// <summary>
        /// Initializes the application.
        /// </summary>
        public static void Init()
        {
            // Register precompiled views
            var assemblies = new List <Assembly>();

            // Check if any modules have registered for precompiled views.
            if (Hooks.RegisterPrecompiledViews != null)
            {
                Hooks.RegisterPrecompiledViews(assemblies);
            }

            // Create precompiled view engines for all requested modules.
            foreach (var assembly in assemblies)
            {
                var engine = new PrecompiledMvcEngine(assembly)
                {
                    UsePhysicalViewsIfNewer = true
                };
                ViewEngines.Engines.Add(engine);
                VirtualPathFactoryManager.RegisterVirtualPathFactory(engine);
            }
        }
예제 #30
0
        private static void RegisterRazorGeneratedViewEngine()
        {
            var areaNames = RouteTableHelper.GetApplicationAreaNames();

            foreach (var areaName in areaNames)
            {
                var engine = new PrecompiledMvcEngine(typeof(PizzaMvcPostApplicationStart).Assembly, $"~/Areas/{areaName}/")
                {
                    UsePhysicalViewsIfNewer = HttpContext.Current.Request.IsLocal,
                };

                ViewEngines.Engines.Add(engine);
                VirtualPathFactoryManager.RegisterVirtualPathFactory(engine);
            }

            var mainEngine = new PrecompiledMvcEngine(typeof(PizzaMvcPostApplicationStart).Assembly)
            {
                UsePhysicalViewsIfNewer = HttpContext.Current.Request.IsLocal,
            };

            ViewEngines.Engines.Add(mainEngine);
            VirtualPathFactoryManager.RegisterVirtualPathFactory(mainEngine);
        }
예제 #31
0
        public static void Start()
        {
            try
            {
                var engine = new PrecompiledMvcEngine(typeof(RazorGeneratorMvcStart).Assembly)
                {
                    UsePhysicalViewsIfNewer = HttpContext.Current.Request.IsLocal
                };

                ViewEngines.Engines.Insert(0, engine);
                VirtualPathFactoryManager.RegisterVirtualPathFactory(engine);
            }
            catch (ReflectionTypeLoadException e)
            {
                var exceptions = new StringBuilder("The following DLL load exceptions occurred:");
                foreach (var x in e.LoaderExceptions)
                {
                    exceptions.AppendFormat("{0},\n\n", x.Message);
                }

                throw new Exception($"Error loading Razor Generator Stuff:\n{exceptions}");
            }
        }
        public static void Start()
        {
            if (_startMethodExecuted == true)
            {
                return;
            }

            var engine = new PrecompiledMvcEngine(typeof(PreApplicationStartCode).Assembly);

            // If you have multiple assemblies with precompiled views,
            // use CompositePrecompiledMvcEngine:
            //
            //var engine = new CompositePrecompiledMvcEngine(
            //    PrecompiledViewAssembly.OfType<YourType>(),
            //    PrecompiledViewAssembly.OfType<PreApplicationStartCode>(
            //        usePhysicalViewsIfNewer: HttpContext.Current.IsDebuggingEnabled));

            ViewEngines.Engines.Insert(0, engine);

            // StartPage lookups are done by WebPages.
            VirtualPathFactoryManager.RegisterVirtualPathFactory(engine);

            _startMethodExecuted = true;
        }
예제 #33
0
        protected virtual void BaseApplication_Start()
        {
            DependencyResolver.SetResolver(
                type =>
            {
                try { return((HttpContext.Current.Composition() ?? _composition.RootScope).Get(type)); }
                catch (CompositionException) { return(null); }
            },
                type =>
            {
                try { return((HttpContext.Current.Composition() ?? _composition.RootScope).GetMany(type)); }
                catch (CompositionException) { return(null); }
            });

            ControllerBuilder.Current.SetControllerFactory(new FullTypeNameControllerFactory());
            VirtualPathFactoryManager.RegisterVirtualPathFactory(new FullyQualifiedTypeVirtualPathFactory());

            ViewEngines.Engines.Clear();
            ViewEngines.Engines.Add(new CompiledViewEngine());

            RegisterModelBinders(ModelBinderProviders.BinderProviders, System.Web.Mvc.ModelBinders.Binders);
            RegisterGlobalFilters(GlobalFilters.Filters);
            RegisterRoutes(RouteTable.Routes);
        }
        public static void Start()
        {
            var engine = new PrecompiledMvcEngine(typeof(RazorGeneratorMvcStart).Assembly)
            {
                UsePhysicalViewsIfNewer = HttpContext.Current.Request.IsLocal
            };

            ViewEngines.Engines.Insert(0, engine);

            // StartPage lookups are done by WebPages.
            VirtualPathFactoryManager.RegisterVirtualPathFactory(engine);

            // regist bundles
            var jsList = new string[] {
                "Code.js",
                "Config.js",
                "Generator.js",
                "Menu.js",
                "Organize.js",
                "Parameter.js",
                "Permission.js",
                "Role.js",
                "User.js"
            };

            foreach (var js in jsList)
            {
                BundleTable.Bundles.Add(new ScriptBundle("~/Resource/Sys/" + js).Include("~/Resource/Zephyr.Web.Sys/Areas/Sys/ViewModels/" + js));
            }

            App.GetDefaultConnectionName = DbCreatorBase.GetDefaultConnectionName;
            if (AppSettings.Entrance.GetType() == typeof(DefaultWebEntrance))
            {
                AppSettings.Entrance = new SysEntrance();
            }
        }
예제 #35
0
 private static bool FileExists(string virtualPath, VirtualPathFactoryManager virtualPathFactoryManager) {
     var path = "~/" + virtualPath;
     return virtualPathFactoryManager.PageExists(path);
 }
예제 #36
0
        static AreaRegistrationBase()
        {
            XTrace.WriteLine("{0} Start 初始化魔方 {0}", new String('=', 32));
            Assembly.GetExecutingAssembly().WriteVersion();

            var ioc = ObjectContainer.Current;

#if !NET4
            // 外部管理提供者需要手工覆盖
            ioc.Register <IManageProvider, DefaultManageProvider>();
#endif

            // 遍历所有引用了AreaRegistrationBase的程序集
            var list = new List <PrecompiledViewAssembly>();
            foreach (var asm in FindAllArea())
            {
                XTrace.WriteLine("注册区域视图程序集:{0}", asm.FullName);

                list.Add(new PrecompiledViewAssembly(asm));
            }
            PrecompiledEngines = list.ToArray();

            var engine = new CompositePrecompiledMvcEngine(PrecompiledEngines);
            XTrace.WriteLine("注册复合预编译引擎,共有视图程序集{0}个", list.Count);
            //ViewEngines.Engines.Insert(0, engine);
            // 预编译引擎滞后,让其它引擎先工作
            ViewEngines.Engines.Add(engine);

            // StartPage lookups are done by WebPages.
            VirtualPathFactoryManager.RegisterVirtualPathFactory(engine);

            // 注册绑定提供者
            ioc.Register <IModelBinderProvider, EntityModelBinderProvider>("Entity");
            ioc.Register <IModelBinderProvider, PagerModelBinderProvider>("Pager");
            var providers = ModelBinderProviders.BinderProviders;
            var prv       = ioc.Resolve <IModelBinderProvider>("Entity");
            if (prv != null)
            {
                XTrace.WriteLine("注册实体模型绑定器:{0}", prv.GetType().FullName);
                providers.Add(prv);
            }
            prv = ioc.Resolve <IModelBinderProvider>("Pager");
            if (prv != null)
            {
                XTrace.WriteLine("注册页面模型绑定器:{0}", prv.GetType().FullName);
                providers.Add(prv);
            }

            // 注册过滤器
            //ioc.Register<HandleErrorAttribute, MvcHandleErrorAttribute>();
            ioc.Register <AuthorizeAttribute, EntityAuthorizeAttribute>("Cube");
            var filters = GlobalFilters.Filters;
            var f1      = ioc.Resolve <HandleErrorAttribute>();
            if (f1 != null)
            {
                XTrace.WriteLine("注册异常过滤器:{0}", f1.GetType().FullName);
                filters.Add(f1);
            }
            //var f2 = ioc.Resolve<AuthorizeAttribute>();
            //if (f2 != null)
            //{
            //    XTrace.WriteLine("注册授权过滤器:{0}", f2.GetType().FullName);
            //    if (f2 is EntityAuthorizeAttribute eaa) eaa.IsGlobal = true;
            //    filters.Add(f2);
            //}
            foreach (var item in ioc.ResolveAll(typeof(AuthorizeAttribute)))
            {
                var auth = item.Instance;
                XTrace.WriteLine("注册[{0}]授权过滤器:{1}", item.Identity, auth.GetType().FullName);
                if (auth is EntityAuthorizeAttribute eaa)
                {
                    eaa.IsGlobal = true;
                }
                filters.Add(auth);
            }

            // 从数据库或者资源文件加载模版页面的例子
            //HostingEnvironment.RegisterVirtualPathProvider(new ViewPathProvider());

            //var routes = RouteTable.Routes;
            //routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
            //routes.MapMvcAttributeRoutes();

            //routes.MapRoute(
            //    name: "Virtual",
            //    url: "{*viewName}",
            //    defaults: new { controller = "Frontend", action = "Default" },
            //    constraints: new { controller = "Frontend", action = "Default" }
            //);

            // 自动检查并下载魔方资源
            ThreadPoolX.QueueUserWorkItem(CheckContent);

            XTrace.WriteLine("{0} End   初始化魔方 {0}", new String('=', 32));
        }
예제 #37
0
        internal static WebPageMatch MatchRequest(string pathValue, IEnumerable<string> supportedExtensions, VirtualPathFactoryManager virtualPathFactoryManager) {
            string currentLevel = String.Empty;
            string currentPathInfo = pathValue;

            // We can skip the file exists check and normal lookup for empty paths, but we still need to look for default pages
            if (!String.IsNullOrEmpty(pathValue)) {
                // If the file exists and its not a supported extension, let the request go through
                if (FileExists(pathValue, virtualPathFactoryManager)) {
                    // TODO: Look into switching to RawURL to eliminate the need for this issue
                    bool foundSupportedExtension = false;
                    foreach (string supportedExtension in supportedExtensions) {
                        if (pathValue.EndsWith("." + supportedExtension, StringComparison.OrdinalIgnoreCase)) {
                            foundSupportedExtension = true;
                            break;
                        }
                    }

                    if (!foundSupportedExtension) {
                        return null;
                    }
                }

                // For each trimmed part of the path try to add a known extension and
                // check if it matches a file in the application.
                currentLevel = pathValue;
                currentPathInfo = String.Empty;
                while (true) {
                    // Does the current route level patch any supported extension?
                    string routeLevelMatch = GetRouteLevelMatch(currentLevel, supportedExtensions, virtualPathFactoryManager);
                    if (routeLevelMatch != null) {
                        return new WebPageMatch(routeLevelMatch, currentPathInfo);
                    }

                    // Try to remove the last path segment (e.g. go from /foo/bar to /foo)
                    int indexOfLastSlash = currentLevel.LastIndexOf('/');
                    if (indexOfLastSlash == -1) {
                        // If there are no more slashes, we're done
                        break;
                    }
                    else {
                        // Chop off the last path segment to get to the next one
                        currentLevel = currentLevel.Substring(0, indexOfLastSlash);

                        // And save the path info in case there is a match
                        currentPathInfo = pathValue.Substring(indexOfLastSlash + 1);
                    }
                }
            }

            // If we haven't found anything yet, now try looking for default.* or index.* at the current url
            currentLevel = pathValue;
            string currentLevelDefault;
            string currentLevelIndex;
            if (String.IsNullOrEmpty(currentLevel)) {
                currentLevelDefault = "default";
                currentLevelIndex = "index";
            }
            else {
                if (currentLevel[currentLevel.Length - 1] != '/')
                    currentLevel += "/";
                currentLevelDefault = currentLevel + "default";
                currentLevelIndex = currentLevel + "index";
            }

            // Does the current route level match any supported extension?
            string defaultMatch = GetRouteLevelMatch(currentLevelDefault, supportedExtensions, virtualPathFactoryManager);
            if (defaultMatch != null) {
                return new WebPageMatch(defaultMatch, String.Empty);
            }

            string indexMatch = GetRouteLevelMatch(currentLevelIndex, supportedExtensions, virtualPathFactoryManager);
            if (indexMatch != null) {
                return new WebPageMatch(indexMatch, String.Empty);
            }

            return null;
        }
예제 #38
0
 public static void Start(MarkdownPagesOptions options, IVirtualPathFactory virtualPathFactory)
 {
     WebPageHttpHandlerExtensions.RegisterExtensions(options.MarkdownExtensions.Select(ext => ext.RemoveLeadingDot()));
     VirtualPathFactoryManager.RegisterVirtualPathFactory(virtualPathFactory);
 }
예제 #39
0
        internal static WebPageBase CreateInstanceFromVirtualPath(string virtualPath, VirtualPathFactoryManager virtualPathFactoryManager) {
            // Get the compiled object (through the VPP)
            try {
                WebPageBase webPage = virtualPathFactoryManager.CreateInstance<WebPageBase>(virtualPath);

                // Give it its virtual path
                webPage.VirtualPath = virtualPath;

                return webPage;
            }
            catch (HttpException e) {
                Util.ThrowIfUnsupportedExtension(virtualPath, e);
                throw;
            }
        }
예제 #40
0
        static AreaRegistrationBase()
        {
            XTrace.WriteLine("{0} Start 初始化魔方 {0}", new String('=', 32));
            Assembly.GetExecutingAssembly().WriteVersion();

            var ioc      = ObjectContainer.Current;
            var services = ioc.BuildServiceProvider();

            //#if !NET4
            //            // 外部管理提供者需要手工覆盖
            //            ioc.AddSingleton<IManageProvider, DefaultManageProvider>();
            //#endif
            if (ManageProvider.Provider == null)
            {
                ManageProvider.Provider = new DefaultManageProvider();
            }

            // 遍历所有引用了AreaRegistrationBase的程序集
            var list = new List <PrecompiledViewAssembly>();

            foreach (var asm in FindAllArea())
            {
                XTrace.WriteLine("注册区域视图程序集:{0}", asm.FullName);

                list.Add(new PrecompiledViewAssembly(asm));
            }
            PrecompiledEngines = list.ToArray();

            var engine = new CompositePrecompiledMvcEngine(PrecompiledEngines);

            XTrace.WriteLine("注册复合预编译引擎,共有视图程序集{0}个", list.Count);
            //ViewEngines.Engines.Insert(0, engine);
            // 预编译引擎滞后,让其它引擎先工作
            ViewEngines.Engines.Add(engine);

            // StartPage lookups are done by WebPages.
            VirtualPathFactoryManager.RegisterVirtualPathFactory(engine);

            // 注册绑定提供者
            //ioc.Register<IModelBinderProvider, EntityModelBinderProvider>("Entity");
            //ioc.Register<IModelBinderProvider, PagerModelBinderProvider>("Pager");
            var providers = ModelBinderProviders.BinderProviders;
            //var prv = ioc.Resolve<IModelBinderProvider>("Entity");
            var prv = services.GetService(typeof(EntityModelBinderProvider)) as IModelBinderProvider;

            if (prv == null)
            {
                prv = new EntityModelBinderProvider();
            }
            if (prv != null)
            {
                XTrace.WriteLine("注册实体模型绑定器:{0}", prv.GetType().FullName);
                providers.Add(prv);
            }
            //prv = ioc.Resolve<IModelBinderProvider>("Pager");
            var prv2 = services.GetService(typeof(PagerModelBinderProvider)) as IModelBinderProvider;

            if (prv2 == null)
            {
                prv2 = new PagerModelBinderProvider();
            }
            if (prv2 != null)
            {
                XTrace.WriteLine("注册页面模型绑定器:{0}", prv2.GetType().FullName);
                providers.Add(prv2);
            }

            // 注册过滤器
            //ioc.Register<HandleErrorAttribute, MvcHandleErrorAttribute>();
            //ioc.Register<AuthorizeAttribute, EntityAuthorizeAttribute>("Cube");
            var filters = GlobalFilters.Filters;
            //var f1 = ioc.Resolve<HandleErrorAttribute>();
            var f1 = services.GetService(typeof(HandleErrorAttribute)) as HandleErrorAttribute;

            if (f1 != null)
            {
                XTrace.WriteLine("注册异常过滤器:{0}", f1.GetType().FullName);
                filters.Add(f1);
            }
            //var f2 = ioc.Resolve<AuthorizeAttribute>();
            var f2 = services.GetService(typeof(AuthorizeAttribute)) as AuthorizeAttribute;

            if (f2 == null)
            {
                f2 = new EntityAuthorizeAttribute();
            }
            if (f2 != null)
            {
                XTrace.WriteLine("注册授权过滤器:{0}", f2.GetType().FullName);
                if (f2 is EntityAuthorizeAttribute eaa)
                {
                    eaa.IsGlobal = true;
                }
                filters.Add(f2);
            }
            //foreach (var item in ioc.ResolveAll(typeof(AuthorizeAttribute)))
            //{
            //    var auth = item.Instance;
            //    XTrace.WriteLine("注册[{0}]授权过滤器:{1}", item.Identity, auth.GetType().FullName);
            //    if (auth is EntityAuthorizeAttribute eaa) eaa.IsGlobal = true;
            //    filters.Add(auth);
            //}

            // 从数据库或者资源文件加载模版页面的例子
            //HostingEnvironment.RegisterVirtualPathProvider(new ViewPathProvider());

            //var routes = RouteTable.Routes;
            //routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
            //routes.MapMvcAttributeRoutes();

            //routes.MapRoute(
            //    name: "Virtual",
            //    url: "{*viewName}",
            //    defaults: new { controller = "Frontend", action = "Default" },
            //    constraints: new { controller = "Frontend", action = "Default" }
            //);

            var routes = RouteTable.Routes;

            if (routes["Cube"] == null)
            {
                // 为魔方注册默认首页,启动魔方站点时能自动跳入后台,同时为Home预留默认过度视图页面
                routes.MapRoute(
                    name: "CubeHome",
                    url: "CubeHome/{action}/{id}",
                    defaults: new { controller = "CubeHome", action = "Index", id = UrlParameter.Optional },
                    namespaces: new[] { typeof(CubeHomeController).Namespace }
                    );
                routes.MapRoute(
                    name: "Cube",
                    url: "Cube/{action}/{id}",
                    defaults: new { controller = "Cube", action = "Info", id = UrlParameter.Optional },
                    namespaces: new[] { typeof(CubeController).Namespace }
                    );
            }
            if (routes["Sso"] == null)
            {
                routes.MapRoute(
                    name: "Sso",
                    url: "Sso/{action}/{id}",
                    defaults: new { controller = "Sso", action = "Index", id = UrlParameter.Optional },
                    namespaces: new[] { typeof(CubeHomeController).Namespace }
                    );
            }

            // 自动检查并下载魔方资源
            ThreadPoolX.QueueUserWorkItem(CheckContent);

            XTrace.WriteLine("{0} End   初始化魔方 {0}", new String('=', 32));
        }
예제 #41
0
        static AreaRegistrationBase()
        {
            // 预热XCode
            Task.Run(() => ManageProvider.Init());

            XTrace.WriteLine("{0} Start 初始化魔方 {0}", new String('=', 32));
            Assembly.GetExecutingAssembly().WriteVersion();

            // 遍历所有引用了AreaRegistrationBase的程序集
            var list = new List <PrecompiledViewAssembly>();

            foreach (var asm in FindAllArea())
            {
                XTrace.WriteLine("注册区域视图程序集:{0}", asm.FullName);

                var pva = new PrecompiledViewAssembly(asm);
                list.Add(pva);
            }
            PrecompiledEngines = list.ToArray();

            var engine = new CompositePrecompiledMvcEngine(PrecompiledEngines);

            XTrace.WriteLine("注册复合预编译引擎,共有视图程序集{0}个", list.Count);
            //ViewEngines.Engines.Insert(0, engine);
            // 预编译引擎滞后,让其它引擎先工作
            ViewEngines.Engines.Add(engine);

            // StartPage lookups are done by WebPages.
            VirtualPathFactoryManager.RegisterVirtualPathFactory(engine);

            // 注册绑定提供者
            EntityModelBinderProvider.Register();

            // 注册过滤器
            XTrace.WriteLine("注册过滤器:{0}", typeof(MvcHandleErrorAttribute).FullName);
            XTrace.WriteLine("注册过滤器:{0}", typeof(EntityAuthorizeAttribute).FullName);
            var filters = GlobalFilters.Filters;

            filters.Add(new MvcHandleErrorAttribute());
            filters.Add(new EntityAuthorizeAttribute()
            {
                IsGlobal = true
            });

            // 从数据库或者资源文件加载模版页面的例子
            //HostingEnvironment.RegisterVirtualPathProvider(new ViewPathProvider());

            //var routes = RouteTable.Routes;
            //routes.IgnoreRoute("{resource}.axd/{*pathInfo}");

            //routes.MapRoute(
            //    name: "Virtual",
            //    url: "{*viewName}",
            //    defaults: new { controller = "Frontend", action = "Default" },
            //    constraints: new { controller = "Frontend", action = "Default" }
            //);

            // 自动检查并下载魔方资源
            Task.Factory.StartNew(CheckContent, TaskCreationOptions.LongRunning).LogException();

            XTrace.WriteLine("{0} End   初始化魔方 {0}", new String('=', 32));
        }