Exemple #1
0
        public string RenderResourceFile(string resourcePath)
        {
            string      text;
            VirtualFile file = VirtualPathProvider.GetFile(resourcePath);

            using (Stream stream = file.Open())
                using (StreamReader reader = new StreamReader(stream))
                {
                    text = reader.ReadToEnd();
                }

            Regex regex = new Regex("\\(=makeFileUrl\\(\"(.+?)\"\\)\\)");

            text = regex.Replace(text, match =>
                                 UrlHelper.Content(match.Groups[1].Value));

            regex = new Regex("\\(=makeurl\\(\"(.*?)\"\\)\\)");
            text  = regex.Replace(text, match =>
                                  UrlHelper.Content(match.Groups[1].Value.Length > 0 ? match.Groups[1].Value : "/"));

            regex = new Regex("\\(@(.*?)\\)");
            text  = regex.Replace(text, match =>
                                  LocalizationManager.Instance.Translate(resourcePath /*TODO*/, match.Groups[1].Value));

            return(text);
        }
Exemple #2
0
 // Overload used mainly for testing
 public FileExistenceCache(
     VirtualPathProvider virtualPathProvider,
     int milliSecondsBeforeReset = 1000
     ) : this(() => virtualPathProvider, milliSecondsBeforeReset)
 {
     Contract.Assert(virtualPathProvider != null);
 }
        /// <summary>
        /// Cria a parte de uma view.
        /// </summary>
        /// <param name="controllerContext"></param>
        /// <param name="partialPath"></param>
        /// <returns></returns>
        protected override IView CreatePartialView(ControllerContext controllerContext, string partialPath)
        {
            IView result = null;
            var   exists = false;

            lock (_partialViews)
                exists = _partialViews.TryGetValue(partialPath, out result);
            if (exists)
            {
                return(result);
            }
            var   file    = VirtualPathProvider.GetFile(partialPath);
            IView result2 = null;

            if (file != null)
            {
                result2 = new RazorPartialView(file, _engineService);
            }
            lock (_partialViews)
                if (!_partialViews.TryGetValue(partialPath, out result))
                {
                    _partialViews.Add(partialPath, result = result2);
                }
            return(result);
        }
        internal BuildManagerViewEngine(IViewPageActivator viewPageActivator, IResolver <IViewPageActivator> activatorResolver,
                                        IDependencyResolver dependencyResolver, VirtualPathProvider pathProvider)
        {
            if (viewPageActivator != null)
            {
                _viewPageActivator = viewPageActivator;
            }
            else
            {
                _activatorResolver = activatorResolver ?? new SingleServiceResolver <IViewPageActivator>(
                    () => null,
                    new DefaultViewPageActivator(dependencyResolver),
                    "BuildManagerViewEngine constructor");
            }

            if (pathProvider != null)
            {
                Func <VirtualPathProvider> providerFunc = () => pathProvider;
                _fileExistsCache        = new FileExistenceCache(providerFunc);
                VirtualPathProviderFunc = providerFunc;
            }
            else
            {
                if (_sharedFileExistsCache == null)
                {
                    // Startup initialization race is OK providing service remains read-only
                    _sharedFileExistsCache = new FileExistenceCache(() => HostingEnvironment.VirtualPathProvider);
                }

                _fileExistsCache = _sharedFileExistsCache;
            }
        }
Exemple #5
0
        internal void DoRuntimeValidation()
        {
            string directoryName = this.DirectoryName;

            if (!BuildManager.IsPrecompiledApp)
            {
                FindFileData data;
                if (!Util.IsValidFileName(directoryName))
                {
                    throw new ConfigurationErrorsException(System.Web.SR.GetString("Invalid_CodeSubDirectory", new object[] { directoryName }), base.ElementInformation.Properties["directoryName"].Source, base.ElementInformation.Properties["directoryName"].LineNumber);
                }
                VirtualPath virtualDir = HttpRuntime.CodeDirectoryVirtualPath.SimpleCombineWithDir(directoryName);
                if (!VirtualPathProvider.DirectoryExistsNoThrow(virtualDir))
                {
                    throw new ConfigurationErrorsException(System.Web.SR.GetString("Invalid_CodeSubDirectory_Not_Exist", new object[] { virtualDir }), base.ElementInformation.Properties["directoryName"].Source, base.ElementInformation.Properties["directoryName"].LineNumber);
                }
                FindFileData.FindFile(virtualDir.MapPathInternal(), out data);
                if (!System.Web.Util.StringUtil.EqualsIgnoreCase(directoryName, data.FileNameLong))
                {
                    throw new ConfigurationErrorsException(System.Web.SR.GetString("Invalid_CodeSubDirectory", new object[] { directoryName }), base.ElementInformation.Properties["directoryName"].Source, base.ElementInformation.Properties["directoryName"].LineNumber);
                }
                if (BuildManager.IsReservedAssemblyName(directoryName))
                {
                    throw new ConfigurationErrorsException(System.Web.SR.GetString("Reserved_AssemblyName", new object[] { directoryName }), base.ElementInformation.Properties["directoryName"].Source, base.ElementInformation.Properties["directoryName"].LineNumber);
                }
            }
        }
Exemple #6
0
 public VideoFile(VirtualPathProvider provider, Video vippyVideo)
     : base(provider.RootDirectory, provider, CreateVideoPath(provider, vippyVideo), true)
 {
     _provider = provider;
     _vippyVideo = vippyVideo;
     _videoSummary = new VideoSummary(this, vippyVideo);
 }
        /// <summary>
        /// Initializes a new instance of the <see cref="ConfigMapPath"/> class.
        /// </summary>
        /// <param name="virtualPathProvider"><see cref="T:TcmDevelopment.VirtualPathProvider.VirtualPathProvider" /></param>
        public ConfigMapPath(VirtualPathProvider virtualPathProvider)
        {
            mProvider = virtualPathProvider;

            // Initialize the custom ConfigMapPath hook
            HookMapPath();
        }
Exemple #8
0
        public void FileExists_VPPRegistrationChanging()
        {
            // Arrange
            Mock <VirtualPathProvider> provider1 = new Mock <VirtualPathProvider>(MockBehavior.Strict);

            provider1.Setup(vpp => vpp.FileExists(It.IsAny <string>())).Returns(true);
            Mock <VirtualPathProvider> provider2 = new Mock <VirtualPathProvider>(MockBehavior.Strict);

            provider2.Setup(vpp => vpp.FileExists(It.IsAny <string>())).Returns(true);
            VirtualPathProvider provider = provider1.Object;

            string            path    = "~/Index.cshtml";
            ControllerContext context = CreateContext();
            TestableVirtualPathProviderViewEngine viewEngine =
                new TestableVirtualPathProviderViewEngine(skipVPPInitialization: true)
            {
                VirtualPathProviderFunc = () => provider,
            };

            // Act
            bool fileExists1 = viewEngine.FileExists(context, path);

            // The moral equivalent of HostingEnvironment.RegisterVirtualPathProvider(provider2.Object)
            provider = provider2.Object;

            bool fileExists2 = viewEngine.FileExists(context, path);

            // Assert
            Assert.True(fileExists1);
            provider1.Verify(vpp => vpp.FileExists(path), Times.Once());
            Assert.True(fileExists2);
            provider2.Verify(vpp => vpp.FileExists(path), Times.Once());
        }
        /// <summary>
        /// Transforms a assets
        /// </summary>
        /// <param name="assets">Set of assets</param>
        /// <param name="bundleContext">Object BundleContext</param>
        /// <param name="bundleResponse">Object BundleResponse</param>
        /// <param name="virtualPathProvider">Virtual path provider</param>
        /// <param name="isDebugMode">Flag that web application is in debug mode</param>
        protected virtual void Transform(IList <IAsset> assets, BundleContext bundleContext,
                                         BundleResponse bundleResponse, VirtualPathProvider virtualPathProvider, bool isDebugMode)
        {
            ValidateAssetTypes(assets);
            assets = RemoveDuplicateAssets(assets);
            assets = RemoveUnnecessaryAssets(assets);
            assets = ReplaceFileExtensions(assets, isDebugMode);
            assets = Translate(assets, isDebugMode);
            assets = PostProcess(assets, isDebugMode);

            IAsset combinedAsset;

            if (CombineFilesBeforeMinification)
            {
                combinedAsset = Combine(assets, bundleContext.BundleVirtualPath, isDebugMode);
                if (!isDebugMode)
                {
                    combinedAsset = Minify(combinedAsset);
                }
            }
            else
            {
                if (!isDebugMode)
                {
                    assets = Minify(assets);
                }
                combinedAsset = Combine(assets, bundleContext.BundleVirtualPath, isDebugMode);
            }

            ConfigureBundleResponse(combinedAsset, bundleResponse, virtualPathProvider);
        }
Exemple #10
0
        private string GetImportedPath(HttpContext context, VirtualPathProvider vpp, string path, string line)
        {
            if (Resources.Register.Debug)
            {
                return(null);
            }
            if (!line.StartsWith("@import"))
            {
                return(null);
            }

            string url = importUrlExpression.Match(line).Groups["url"].Value;

            if (!string.IsNullOrEmpty(url))
            {
                bool isRelative = !url.StartsWith("~") && !url.StartsWith("/");
                if (!isRelative)
                {
                    return(null);
                }

                url = Normalize(url, VirtualPathUtility.GetDirectory(path));
                if (vpp.FileExists(url))
                {
                    return(url);
                }
            }
            return(null);
        }
        public object CreateInstance(string virtualPath)
        {
            var routeData = ((MvcHandler)HttpContext.Current.Handler).RequestContext.RouteData;

            ViewMapping mapping;

            if (!_mappings[_assemblySelector(routeData.Values, _mappings.Keys)].TryGetValue(virtualPath, out mapping))
            {
                return(null);
            }

            if (!mapping.ViewAssembly.PreemptPhysicalFiles && VirtualPathProvider.FileExists(virtualPath))
            {
                // If we aren't pre-empting physical files, use the BuildManager to create _ViewStart instances if the file exists on disk.
                return(BuildManager.CreateInstanceFromVirtualPath(virtualPath, typeof(WebPageRenderingBase)));
            }

            if (mapping.ViewAssembly.UsePhysicalViewsIfNewer && mapping.ViewAssembly.IsPhysicalFileNewer(virtualPath))
            {
                // If the physical file on disk is newer and the user's opted in this behavior, serve it instead.
                return(BuildManager.CreateInstanceFromVirtualPath(virtualPath, typeof(WebViewPage)));
            }

            return(_viewPageActivator.Create((ControllerContext)null, mapping.Type));
        }
Exemple #12
0
        /// <summary>文件是否存在。如果存在,则由当前引擎创建视图</summary>
        /// <param name="controllerContext"></param>
        /// <param name="virtualPath"></param>
        /// <returns></returns>
        protected override Boolean FileExists(ControllerContext controllerContext, String virtualPath)
        {
            virtualPath = EnsureVirtualPathPrefix(virtualPath);

            // 如果映射表不存在,就不要掺合啦
            if (!Exists(virtualPath))
            {
                return(false);
            }

            // 两个条件任意一个满足即可使用物理文件
            // 如果不要求取代物理文件,并且虚拟文件存在,则使用物理文件创建
            if (!PreemptPhysicalFiles && VirtualPathProvider.FileExists(virtualPath))
            {
                return(false);
            }

            // 如果使用较新的物理文件,且物理文件的确较新,则使用物理文件创建
            if (UsePhysicalViewsIfNewer && IsPhysicalFileNewer(virtualPath))
            {
                return(false);
            }

            return(true);
        }
        private static IEnumerable <string> ReadDependencies(string path)
        {
            // read dependencies for .js files only
            if (!path.ToLower().EndsWith(".js"))
            {
                return(new List <string>());
            }

            try
            {
                var deps = new List <string>();
                using (var str = VirtualPathProvider.OpenFile(path))
                    using (var r = new StreamReader(str))
                    {
                        var l = r.ReadLine();
                        var parsedDependency = ParseDependency(l);
                        while (parsedDependency != null)
                        {
                            deps.Add(parsedDependency);
                            l = r.ReadLine();
                            parsedDependency = ParseDependency(l);
                        }
                    }
                return(deps);
            }
            catch (Exception e)
            {
                Logger.WriteException(e);
            }

            return(null);
        }
Exemple #14
0
        protected string FindMaster(string masterName)
        {
            if (masterName.StartsWith("~/") && VirtualPathProvider.FileExists(masterName))
            {
                return(masterName);
            }

            if (masterName.StartsWith("~/") && VirtualPathProvider.FileExists(masterName + ".master"))
            {
                return(masterName + ".master");
            }

            if (VirtualPathProvider.FileExists("~/Views/" + masterName))
            {
                return("~/Views/" + masterName);
            }

            if (VirtualPathProvider.FileExists("~/Views/" + masterName + ".master"))
            {
                return("~/Views/" + masterName + ".master");
            }

            if (VirtualPathProvider.FileExists("~/Views/Shared/" + masterName))
            {
                return("~/Views/Shared" + masterName);
            }

            if (VirtualPathProvider.FileExists("~/Views/Shared/" + masterName + ".master"))
            {
                return("~/Views/Shared" + masterName + ".master");
            }

            return(null);
        }
Exemple #15
0
        internal static bool RemapHandlerForBundleRequests(HttpApplication app)
        {
            HttpContextBase context = new HttpContextWrapper(app.Context);

            // Don't block requests to existing files or directories
            string requestPath      = context.Request.AppRelativeCurrentExecutionFilePath;
            VirtualPathProvider vpp = HostingEnvironment.VirtualPathProvider;

            if (vpp.FileExists(requestPath) || vpp.DirectoryExists(requestPath))
            {
                return(false);
            }

            string bundleRequestPath = GetBundleUrlFromContext(context);

            // Check if this request matches a bundle in the app
            Bundle requestBundle = BundleTable.Bundles.GetBundleFor(bundleRequestPath);

            if (requestBundle != null)
            {
                context.RemapHandler(new BundleHandler(requestBundle, bundleRequestPath));
                return(true);
            }

            return(false);
        }
Exemple #16
0
        /// <summary>
        /// Try and find a file in the specified folder that matches name.
        /// </summary>
        /// <returns>The full path to the file that matches the requested file
        /// or null if no matching file is found</returns>
        internal static string FindMatchingFile(VirtualPathProvider vpp, string folder, string name)
        {
            Debug.Assert(vpp != null);
            Debug.Assert(!String.IsNullOrEmpty(folder));
            Debug.Assert(!String.IsNullOrEmpty(name));

            // Get the virtual path information
            VirtualDirectory directory = vpp.GetDirectory(folder);

            // If the folder specified doesn't exist
            // or it doesn't contain any files
            if (directory == null || directory.Files == null)
            {
                return(null);
            }

            // Go through every file in the directory
            foreach (VirtualFile file in directory.Files)
            {
                string path = file.VirtualPath;

                // Compare the filename to the filename that we passed
                if (Path.GetFileName(path).Equals(name, StringComparison.OrdinalIgnoreCase))
                {
                    return(path);
                }
            }

            // If no matching files, return null
            return(null);
        }
        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());
            });
        }
Exemple #18
0
        public void AddPage(ViewPageRef page)
        {
            try
            {
                TemplateProvider.QueuePageToCompile(page);
                AddViewPage(page);
            }
            catch (Exception ex)
            {
                HandleCompilationException(page, ex);
            }

            try
            {
                var templatePath = page.Template;
                if (page.Template == null)
                {
                    return;
                }

                if (MasterPageTemplates.ContainsKey(templatePath))
                {
                    return;
                }

                var templateFile     = VirtualPathProvider.GetFile(templatePath);
                var templateContents = GetPageContents(templateFile);
                AddTemplate(templatePath, templateContents);
            }
            catch (Exception ex)
            {
                Log.Error("Error compiling template " + page.Template + ": " + ex.Message, ex);
            }
        }
        private HandlebarsView GetViewFromCache(ControllerContext controllerContext, string virtualPath)
        {
            CacheKey templateCacheKey = new CacheKey(CacheConfigurationCategoryNames.HandlebarsView)
            {
                Key = virtualPath.Substring(virtualPath.LastIndexOf('/') + 1)
            };

            return(CacheProvider.GetOrAdd(templateCacheKey, () =>
            {
                //First, let's make sure the dependencies exist
                Dictionary <string, HandlebarsView> dependencies = GetDependenciesFromCache(controllerContext,
                                                                                            virtualPath);

                //Then let's compile
                Action <TextWriter, object> compiledTemplate;
                var file = VirtualPathProvider.GetFile(virtualPath);
                using (TextReader template = new StreamReader(file.Open()))
                {
                    compiledTemplate = _handlebars.Compile(template);
                }

                InitMonitorTamplateFiles();

                return new HandlebarsView(compiledTemplate, virtualPath, dependencies);
            }));
        }
Exemple #20
0
        private static bool IsNonUpdatablePrecompiledAppNoCache()
        {
            if (HostingEnvironment.VirtualPathProvider == null)
            {
                return(false);
            }
            string virtualPath = VirtualPathUtility.ToAbsolute("~/PrecompiledApp.config");

            if (!HostingEnvironment.VirtualPathProvider.FileExists(virtualPath))
            {
                return(false);
            }
            XmlDocument document = new XmlDocument();

            document.Load(VirtualPathProvider.OpenFile(virtualPath));
            XmlNode documentElement = document.DocumentElement;

            if ((documentElement == null) || (documentElement.Name != "precompiledApp"))
            {
                return(false);
            }
            XmlNode namedItem = documentElement.Attributes.GetNamedItem("updatable");

            return((namedItem != null) && (namedItem.Value == "false"));
        }
Exemple #21
0
        public MarkdownTemplate AddTemplate(string templatePath, string templateContents)
        {
            MarkdownTemplate template;

            if (MasterPageTemplates.TryGetValue(templatePath, out template))
            {
                return(template);
            }

            var templateFile = VirtualPathProvider.GetFile(templatePath);
            var templateName = templateFile.Name.WithoutExtension();

            template = new MarkdownTemplate(templatePath, templateName, templateContents)
            {
                LastModified = templateFile.LastModified,
            };

            MasterPageTemplates.Add(templatePath, template);

            try
            {
                template.Prepare();
                return(template);
            }
            catch (Exception ex)
            {
                Log.Error("AddViewPage() template.Prepare(): " + ex.Message, ex);
                return(null);
            }
        }
        public void ProcessRequest(HttpContext context)
        {
            var routeDataValues = _routeData.Values;

            var folder = routeDataValues["root"].ToString();

            if (PatternProvider.FolderNameData.EndsWith(folder, StringComparison.InvariantCultureIgnoreCase))
            {
                folder = string.Concat(PatternProvider.IdentifierHidden, folder);
            }

            var filePath    = routeDataValues["path"] != null ? routeDataValues["path"].ToString() : string.Empty;
            var fileName    = Path.GetFileName(filePath);
            var virtualPath = string.Format("/{0}/{1}", folder, filePath);

            using (var stream = VirtualPathProvider.OpenFile(virtualPath))
            {
                if (stream.Length <= 0)
                {
                    return;
                }

                context.Response.Clear();
                context.Response.ContentType = MimeMapping.GetMimeMapping(fileName);

                stream.CopyTo(context.Response.OutputStream);
            }
        }
Exemple #23
0
        public virtual IEnumerable <ViewTemplateDescription> FindRegistrations(VirtualPathProvider vpp, HttpContextBase httpContext, IEnumerable <ViewTemplateSource> sources)
        {
            foreach (var source in sources)
            {
                string virtualDir = "~/Views/" + source.ControllerName;
                if (!vpp.DirectoryExists(virtualDir))
                {
                    continue;
                }

                List <ViewTemplateDescription> descriptions = new List <ViewTemplateDescription>();
                foreach (var file in vpp.GetDirectory(virtualDir).Files.OfType <VirtualFile>().Where(f => f.Name.EndsWith(source.ViewFileExtension)))
                {
                    var description = AnalyzeView(httpContext, file, source.ControllerName, source.ModelType);
                    if (description != null)
                    {
                        descriptions.Add(description);
                    }
                }

                foreach (var description in descriptions)
                {
                    yield return(description);
                }
            }
        }
Exemple #24
0
        public void AddPage(MarkdownPage page)
        {
            try
            {
                page.Compile();
                AddViewPage(page);
            }
            catch (Exception ex)
            {
                Log.Error("AddViewPage() page.Prepare(): " + ex.Message, ex);
            }

            try
            {
                var templatePath = page.Template;
                if (page.Template == null)
                {
                    return;
                }

                if (MasterPageTemplates.ContainsKey(templatePath))
                {
                    return;
                }

                var templateFile     = VirtualPathProvider.GetFile(templatePath);
                var templateContents = GetPageContents(templateFile);
                AddTemplate(templatePath, templateContents);
            }
            catch (Exception ex)
            {
                Log.Error("Error compiling template " + page.Template + ": " + ex.Message, ex);
            }
        }
        public void IsNonPrecompiledAppReturnsTrue_VPPRegistrationChanging()
        {
            // Arrange
            string fileContent = @"<precompiledApp version=""2"" updatable=""false""/>";
            IVirtualPathUtility pathUtility = GetVirtualPathUtility();

            Mock <VirtualPathProvider> mockProvider1 = new Mock <VirtualPathProvider>();

            mockProvider1.Setup(c => c.FileExists(It.Is <string>(p => p.Equals(_precompileConfigFileName)))).Returns(true).Verifiable();
            mockProvider1.Setup(c => c.GetFile(It.Is <string>(p => p.Equals(_precompileConfigFileName)))).Returns(GetFile(fileContent)).Verifiable();

            Mock <VirtualPathProvider> mockProvider2 = new Mock <VirtualPathProvider>();

            mockProvider2.Setup(c => c.FileExists(It.Is <string>(p => p.Equals(_precompileConfigFileName)))).Returns(true).Verifiable();
            mockProvider2.Setup(c => c.GetFile(It.Is <string>(p => p.Equals(_precompileConfigFileName)))).Returns(GetFile(fileContent)).Verifiable();

            VirtualPathProvider provider = mockProvider1.Object;

            // Act; uses one VirtualPathProvider in constructor and the other when IsNonUpdatablePrecompiledApp() is called directly
            BuildManagerWrapper buildManagerWrapper = new BuildManagerWrapper(() => provider, pathUtility);

            // The moral equivalent of HostingEnvironment.RegisterVirtualPathProvider(provider2.Object)
            provider = mockProvider2.Object;

            bool isPrecompiled = buildManagerWrapper.IsNonUpdatablePrecompiledApp();

            // Assert
            Assert.True(isPrecompiled);
            mockProvider1.Verify();
            mockProvider1.Verify(vpp => vpp.FileExists(It.IsAny <string>()), Times.Once());
            mockProvider1.Verify(vpp => vpp.GetFile(It.IsAny <string>()), Times.Once());
            mockProvider2.Verify();
            mockProvider2.Verify(vpp => vpp.FileExists(It.IsAny <string>()), Times.Once());
            mockProvider2.Verify(vpp => vpp.GetFile(It.IsAny <string>()), Times.Once());
        }
Exemple #26
0
        protected string TryFindViewFromViewModel(Cache cache, object viewModel)
        {
            if (viewModel != null)
            {
                var viewModelType = viewModel.GetType();
                var cacheKey      = "ViewModelViewName_" + viewModelType.FullName;
                var cachedValue   = (string)cache.Get(cacheKey);
                if (cachedValue != null)
                {
                    return(cachedValue != NoVirtualPathCacheValue ? cachedValue : null);
                }
                while (viewModelType != typeof(object))
                {
                    var viewModelName = viewModelType.Name;
                    var namespacePart = viewModelType.Namespace.Substring("FODT.".Length);
                    var virtualPath   = "~/" + namespacePart.Replace(".", "/") + "/" + viewModelName.Replace("ViewModel", "") + ".cshtml";
                    if (Exists(virtualPath) || VirtualPathProvider.FileExists(virtualPath))
                    {
                        cache.Insert(cacheKey, virtualPath, null /* dependencies */, Cache.NoAbsoluteExpiration, _defaultCacheTimeSpan);
                        return(virtualPath);
                    }
                    viewModelType = viewModelType.BaseType;
                }

                // no view found
                cache.Insert(cacheKey, NoVirtualPathCacheValue, null /* dependencies */, Cache.NoAbsoluteExpiration, _defaultCacheTimeSpan);
            }
            return(null);
        }
Exemple #27
0
        public ViewPageRef AddTemplate(string templatePath, string templateContents)
        {
            var templateFile = VirtualPathProvider.GetFile(templatePath);
            var templateName = templateFile.Name.WithoutExtension();

            TemplateService templateService;

            if (!templateServices.TryGetValue(templateFile.Extension, out templateService))
            {
                throw new ConfigurationErrorsException(
                          "No BaseType registered with extension " + templateFile.Extension + " for template " + templateFile.Name);
            }

            var template = new ViewPageRef(this, templatePath, templateName, templateContents, RazorPageType.Template)
            {
                LastModified = templateFile.LastModified,
                Service      = templateService,
            };

            MasterPageTemplates.Add(templatePath, template);

            try
            {
                //template.Compile();
                TemplateProvider.QueuePageToCompile(template);
                return(template);
            }
            catch (Exception ex)
            {
                Log.Error("AddViewPage() template.Prepare(): " + ex.Message, ex);
                return(null);
            }
        }
Exemple #28
0
        /// <summary>
        /// 在指定虚拟路径上溯搜索指定文件名的文件
        /// </summary>
        /// <param name="provider">自定义的虚拟路径提供程序</param>
        /// <param name="virtualPath">要搜索的虚拟路径</param>
        /// <param name="fileNames">要搜索的文件名列表</param>
        /// <returns>返回找到的文件路径,若无法找到匹配的文件,则返回null</returns>
        internal static string FallbackSearch(VirtualPathProvider provider, string virtualPath, params string[] fileNames)
        {
            if (!VirtualPathUtility.IsAppRelative(virtualPath))
            {
                throw VirtualPathFormatError("virtualPath");
            }

            var directory = VirtualPathUtility.GetDirectory(virtualPath);

            while (true)
            {
                foreach (var name in fileNames)
                {
                    var filePath = VirtualPathUtility.Combine(directory, name);
                    if (provider.FileExists(filePath))
                    {
                        return(filePath);
                    }
                }

                if (directory == "~/")
                {
                    break;
                }

                directory = VirtualPathUtility.Combine(directory, "../");
            }

            return(null);
        }
        public object CreateInstance(string virtualPath)
        {
            virtualPath = PrecompiledMvcEngine.EnsureVirtualPathPrefix(virtualPath);

            ViewMapping mapping;

            if (!_mappings.TryGetValue(virtualPath, out mapping))
            {
                return(null);
            }

            if (!mapping.ViewAssembly.PreemptPhysicalFiles && VirtualPathProvider.FileExists(virtualPath))
            {
                // If we aren't pre-empting physical files, use the BuildManager to create _ViewStart instances if the file exists on disk.
                return(BuildManager.CreateInstanceFromVirtualPath(virtualPath, typeof(WebPageRenderingBase)));
            }

            if (mapping.ViewAssembly.UsePhysicalViewsIfNewer && mapping.ViewAssembly.IsPhysicalFileNewer(virtualPath))
            {
                // If the physical file on disk is newer and the user's opted in this behavior, serve it instead.
                return(BuildManager.CreateInstanceFromVirtualPath(virtualPath, typeof(WebViewPage)));
            }

            return(_viewPageActivator.Create((ControllerContext)null, mapping.Type));
        }
Exemple #30
0
        private static string ResolveThemedContent(RequestContext requestContext, VirtualPathProvider vpp, string contentPath)
        {
            string themeFolderPath = requestContext.RouteData.DataTokens["ThemeViewEngine.ThemeFolderPath"] as string
                                     ?? Url.ResolveTokens(Url.ThemesUrlToken);

            string theme = requestContext.HttpContext.GetTheme();

            if (!string.IsNullOrEmpty(theme))
            {
                string themeContentPath = themeFolderPath + theme + contentPath.TrimStart('~');
                if (vpp.FileExists(themeContentPath))
                {
                    return(Url.ToAbsolute(themeContentPath));
                }
            }

            string defaultThemeContentPath = themeFolderPath + "Default" + contentPath.TrimStart('~');

            if (vpp.FileExists(defaultThemeContentPath))
            {
                return(Url.ToAbsolute(defaultThemeContentPath));
            }

            return(Url.ToAbsolute(contentPath));
        }
Exemple #31
0
 internal static void Authorize(
     StartPage page,
     VirtualPathProvider vpp,
     Func <string, string> makeAppRelative
     )
 {
     if (!IsAuthenticated(page.Request))
     {
         if (HasAdminPassword(vpp))
         {
             // If there is a password file (Password.config) then we redirect to the login page
             RedirectSafe(page, SiteAdmin.LoginVirtualPath, makeAppRelative);
         }
         else if (HasTemporaryPassword(vpp))
         {
             // Dev 10 941521: Admin: Pass through returnurl into page that tells the user to rename _password.config
             // If there is a disabled password file (_Password.config) then we redirect to the instructions page
             RedirectSafe(page, SiteAdmin.EnableInstructionsVirtualPath, makeAppRelative);
         }
         else
         {
             // The user hasn't done anything so redirect to the register page.
             RedirectSafe(page, SiteAdmin.RegisterVirtualPath, makeAppRelative);
         }
     }
 }
Exemple #32
0
        /// <summary>创建实例。Start和Layout会调用这里</summary>
        /// <param name="virtualPath"></param>
        /// <returns></returns>
        public Object CreateInstance(String virtualPath)
        {
            virtualPath = EnsureVirtualPathPrefix(virtualPath);

            // 两个条件任意一个满足即可使用物理文件
            // 如果不要求取代物理文件,并且虚拟文件存在,则使用物理文件创建
            if (!PreemptPhysicalFiles && VirtualPathProvider.FileExists(virtualPath))
            {
                return(BuildManager.CreateInstanceFromVirtualPath(virtualPath, typeof(WebPageRenderingBase)));
            }

            // 如果使用较新的物理文件,且物理文件的确较新,则使用物理文件创建
            if (UsePhysicalViewsIfNewer && IsPhysicalFileNewer(virtualPath))
            {
                return(BuildManager.CreateInstanceFromVirtualPath(virtualPath, typeof(WebViewPage)));
            }

            // 最后使用内嵌类创建
            Type type;

            if (_mappings.TryGetValue(virtualPath, out type))
            {
                return(ViewPageActivator.Create(null, type));
            }

            return(null);
        }
        public void TestDiscoverFiles()
        {
            var vpp = new VirtualPathProvider(new string[] { "~/Layout/" });

            var files = vpp.GetFiles();

            Assert.IsTrue(vpp.FileExists("~/Layout/Basic.master"));
        }
Exemple #34
0
 public RootDirectory(VirtualPathProvider provider)
     : base(provider, provider.VirtualPathRoot, null, true)
 {
     _provider = provider;
 }
Exemple #35
0
 public VideoFile(VirtualPathProvider provider, string filename)
     : base(provider.RootDirectory, provider, CreateVideoPathFromFileName(provider, filename), true)
 {
     _provider = provider;
     _videoSummary = new VideoSummary(this, filename);
 }
	public static void RegisterVirtualPathProvider(VirtualPathProvider virtualPathProvider) {}
 protected void Application_Start(object sender, EventArgs e)
 {
     var pathProvider = new VirtualPathProvider();
     RubyEngine = Core.RubyEngine.InitializeIronRubyMvc(pathProvider, "~/routes.rb");
     OnStart();
 }
Exemple #38
0
 private static string CreateVideoPathFromFileName(VirtualPathProvider provider, string filename)
 {
     return provider.CombineVirtualPaths(provider.RootDirectory.VirtualPath, filename);
 }