Exemple #1
0
        public override VirtualFile GetFile(string virtualPath)
        {
            var styleResult = ThemeHelper.IsStyleSheet(virtualPath);

            if (styleResult != null)
            {
                if (styleResult.IsThemeVars)
                {
                    var theme   = ThemeHelper.ResolveCurrentTheme();
                    int storeId = ThemeHelper.ResolveCurrentStoreId();
                    return(new ThemeVarsVirtualFile(virtualPath, styleResult.Extension, theme.ThemeName, storeId));
                }
                else if (styleResult.IsModuleImports)
                {
                    return(new ModuleImportsVirtualFile(virtualPath, ThemeHelper.IsAdminArea()));
                }
            }

            var result = GetResolveResult(virtualPath);

            if (result != null)
            {
                if (!result.IsExplicit)
                {
                    return(new InheritedVirtualThemeFile(result));
                }
                else
                {
                    virtualPath = result.OriginalVirtualPath;
                }
            }

            return(_previous.GetFile(virtualPath));
        }
        public override VirtualFile GetFile(string virtualPath)
        {
            string debugPath = ResolveDebugFilePath(virtualPath);

            if (debugPath != null)
            {
                return(new DebugPluginVirtualFile(virtualPath, debugPath));
            }

            var result = GetResolveResult(virtualPath);

            if (result != null)
            {
                if (!result.IsExplicit)
                {
                    return(new InheritedVirtualThemeFile(result));
                }
                else
                {
                    virtualPath = result.OriginalVirtualPath;
                }
            }

            return(_previous.GetFile(virtualPath));
        }
Exemple #3
0
 public override VirtualFile GetFile(string virtualPath)
 {
     if (IsEmbeddedPath(virtualPath))
     {
         string fileNameWithExtension = virtualPath.Substring(virtualPath.LastIndexOf("/", StringComparison.Ordinal) + 1);
         string path = virtualPath.Replace("~/TraffixCommon/Embedded", "");
         var    bits = path.Split('/');
         bits[2] = bits[2].Replace("-", "_");
         path    = string.Join(".", bits);
         string nameSpace = typeof(EmbeddedResourceHttpHandler)
                            .Assembly
                            .GetName()
                            .Name;// Mostly the default namespace and assembly name are same
         string manifestResourceName = $"{nameSpace}.Content{path}";
         var    stream = typeof(EmbeddedVirtualPathProvider).Assembly.GetManifestResourceStream(manifestResourceName);
         if (stream == null)
         {
             throw new EmbeddedResourceException("Could not find embedded resource:" + manifestResourceName + ", check if the resource has the build action set to 'Embedded Resource'");
         }
         return(new EmbeddedVirtualFile(virtualPath, stream));
     }
     else
     {
         return(_previous.GetFile(virtualPath));
     }
 }
Exemple #4
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);
            }
        }
        /// <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);
        }
Exemple #6
0
        public override VirtualFile GetFile(string virtualPath)
        {
            if (_baseProvider != null && _baseProvider.FileExists(virtualPath))
            {
                return(_baseProvider.GetFile(virtualPath));
            }

            if (IsMeekPath(virtualPath) && IsInternalResource(virtualPath))
            {
                return(GetInternalResource(virtualPath));
            }

            var repository     = _config.GetRepository();
            var pathTranslated = TranslateVirtualPathNoExt(virtualPath);

            if (IsMeekPath(virtualPath) && repository.Exists(pathTranslated))
            {
                return(new ContentVirtualFile(
                           repository,
                           virtualPath,
                           pathTranslated,
                           _config.ViewEngineOptions));
            }

            return(null);
        }
        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 MustacheTemplate LoadTemplate(string virtualPath, Dictionary <string, object> parameters = null)
        {
            var physicalPath = HostingEnvironment.MapPath(virtualPath) ?? string.Empty;
            var serializer   = new JavaScriptSerializer();
            var key          = string.Format("{0}-{1}", virtualPath, serializer.Serialize(parameters));

            // Check cache for template
            if (_controllerContext.HttpContext.Cache[key] != null)
            {
                return((MustacheTemplate)_controllerContext.HttpContext.Cache[key]);
            }

            // Load from disk or assembly embedded resources if not cached
            var embeddedResource = _virtualPathProvider.GetFile(virtualPath) as EmbeddedResource;
            var templateSource   = embeddedResource != null?embeddedResource.ReadAllText() : File.ReadAllText(physicalPath);

            // Pass contents of file into template along with any pattern parameters
            var template = new MustacheTemplate(_parameters);

            template.Load(new StringReader(templateSource));

            // Cache the found template
            _controllerContext.HttpContext.Cache.Insert(key, template,
                                                        embeddedResource != null
                    ? embeddedResource.CacheDependency(DateTime.UtcNow)
                    : new CacheDependency(physicalPath));

            return(template);
        }
        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 #10
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 override VirtualFile GetFile(string virtualPath)
        {
            if (ThemeHelper.PathIsThemeVars(virtualPath))
            {
                var theme   = ThemeHelper.ResolveCurrentTheme();
                int storeId = ThemeHelper.ResolveCurrentStoreId();
                return(new ThemeVarsVirtualFile(virtualPath, theme.ThemeName, storeId));
            }

            var result = GetResolveResult(virtualPath);

            if (result != null)
            {
                if (!result.IsExplicit)
                {
                    return(new InheritedVirtualThemeFile(result));
                }
                else
                {
                    virtualPath = result.OriginalVirtualPath;
                }
            }

            return(_previous.GetFile(virtualPath));
        }
Exemple #12
0
        private MustacheTemplate LoadTemplate(string virtualPath, Dictionary <string, object> parameters = null)
        {
            var physicalPath = HostingEnvironment.MapPath(virtualPath) ?? string.Empty;
            var serializer   = new JavaScriptSerializer();
            var key          = string.Format("{0}-{1}", virtualPath, serializer.Serialize(parameters));

            if (_controllerContext.HttpContext.Cache[key] != null)
            {
                return((MustacheTemplate)_controllerContext.HttpContext.Cache[key]);
            }

            var embeddedResource = _virtualPathProvider.GetFile(virtualPath) as EmbeddedResource;
            var templateSource   = embeddedResource != null?embeddedResource.ReadAllText() : File.ReadAllText(physicalPath);

            var template = new MustacheTemplate(_parameters);

            template.Load(new StringReader(templateSource));

            _controllerContext.HttpContext.Cache.Insert(key, template,
                                                        embeddedResource != null
                    ? embeddedResource.GetCacheDependency(DateTime.UtcNow)
                    : new CacheDependency(physicalPath));

            return(template);
        }
        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 #14
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);
        }
        public override VirtualFile GetFile(string virtualPath)
        {
            VirtualFile file      = null;
            string      debugPath = null;

            var result = GetResolveResult(virtualPath);

            if (result != null)
            {
                // File is an inherited theme file. Set the result virtual path.
                virtualPath = result.ResultVirtualPath ?? result.OriginalVirtualPath;
                if (!result.IsBased)
                {
                    file = new InheritedVirtualThemeFile(result);
                }
            }

            if (result == null || file is InheritedVirtualThemeFile)
            {
                // Handle plugin and symlinked theme folders in debug mode.
                debugPath = ResolveDebugFilePath(virtualPath);
                if (debugPath != null)
                {
                    file = new DebugVirtualFile(file?.VirtualPath ?? virtualPath, debugPath);
                }
            }

            return(file ?? _previous.GetFile(virtualPath));
        }
Exemple #16
0
 public static Stream TryOpen(this VirtualPathProvider vpp, string virtualPath)
 {
     if (vpp == null)
     {
         throw new ArgumentNullException(nameof(vpp));
     }
     return(vpp.FileExists(virtualPath) ? vpp.GetFile(virtualPath).Open() : null);
 }
        VirtualFile GetVirtualFile(string virtualPath)
        {
            if (!vpp.FileExists(virtualPath))
            {
                return(null);
            }

            return(vpp.GetFile(virtualPath));
        }
        /// <summary>
        /// Cria a view.
        /// </summary>
        /// <param name="controllerContext"></param>
        /// <param name="viewPath"></param>
        /// <param name="masterPath"></param>
        /// <returns></returns>
        protected override IView CreateView(ControllerContext controllerContext, string viewPath, string masterPath)
        {
            var file = VirtualPathProvider.GetFile(viewPath);

            if (file != null)
            {
                return(new RazorView(file, null, EngineService));
            }
            return(null);
        }
Exemple #19
0
        private static IEnumerable <SkinTemplate> GetSkinTemplates(VirtualPathProvider virtualPathProvider, string path)
        {
            VirtualFile virtualConfigFile = virtualPathProvider.GetFile(path);

            using (Stream configStream = virtualConfigFile.Open())
            {
                var templates = SerializationHelper.Load <SkinTemplates>(configStream);
                return(templates.Templates);
            }
        }
Exemple #20
0
        public override VirtualFile GetFile(string virtualPath)
        {
            if (!_DefaultProvider.FileExists(virtualPath) && IsEmbeddedView(virtualPath))
            {
                var embeddedView = _EmbeddedViews.FindEmbeddedView(virtualPath);
                return(new AssemblyResourceFile(embeddedView, virtualPath));
            }

            return(_DefaultProvider.GetFile(virtualPath));
        }
        public override VirtualFile GetFile(string virtualPath)
        {
            if (ThemeHelper.PathIsThemeVars(virtualPath))
            {
                string themeName = ResolveCurrentThemeName();
                int    storeId   = ResolveCurrentStoreId();
                return(new ThemeVarsVirtualFile(virtualPath, themeName, storeId));
            }

            return(_previous.GetFile(virtualPath));
        }
 /// <inheritdoc />
 public override VirtualFile GetFile(string virtualPath)
 {
     if (this.IsEmbeddedPath(virtualPath))
     {
         var assetLoader = _assetLoaderLocator();
         var filePath    = virtualPath.Substring(virtualPath.IndexOf(_dynamicAssetsVirtualPath, StringComparison.CurrentCultureIgnoreCase) + _dynamicAssetsVirtualPath.Length);
         var content     = assetLoader.Load(filePath);
         return(new CustomVirtualFile(virtualPath, content));
     }
     return(_previous.GetFile(virtualPath));
 }
Exemple #23
0
 public override VirtualFile GetFile(string virtualPath)
 {
     if (IsAppResourcePath(virtualPath))
     {
         return(new AssemblyResourceVirtualFile(virtualPath));
     }
     else
     {
         return(parent.GetFile(virtualPath));
     }
 }
        public void ProcessRequest(HttpContext context)
        {
            if (File.Exists(context.Request.PhysicalPath))
            {
                var fileModified = File.GetLastWriteTimeUtc(context.Request.PhysicalPath);
                if (CacheUtility.IsUnmodifiedSince(context.Request, fileModified))
                {
                    CacheUtility.NotModified(context.Response);
                }

                N2.Web.CacheUtility.SetValidUntilExpires(context.Response, DateTime.UtcNow);
                context.Response.TransmitFile(context.Request.PhysicalPath);
            }
            else if (vpp.FileExists(context.Request.AppRelativeCurrentExecutionFilePath))
            {
                if (Modified.HasValue && CacheUtility.IsUnmodifiedSince(context.Request, Modified.Value))
                {
                    CacheUtility.NotModified(context.Response);
                }


                byte[] cached = context.Cache["VirtualPathFileHandler:" + context.Request.AppRelativeCurrentExecutionFilePath] as byte[];
                if (cached != null)
                {
                    context.Response.ContentType = GetContentType(context.Request.AppRelativeCurrentExecutionFilePath);
                    context.Response.OutputStream.Write(cached, 0, cached.Length);
                    return;
                }


                var f = vpp.GetFile(context.Request.AppRelativeCurrentExecutionFilePath);
                using (var s = f.Open())
                {
                    byte[] buffer    = new byte[131072];
                    int    readBytes = ReadBlock(s, buffer);
                    if (readBytes <= 0)
                    {
                        return;
                    }

                    N2.Web.CacheUtility.SetValidUntilExpires(context.Response, DateTime.UtcNow);
                    context.Response.ContentType = GetContentType(context.Request.AppRelativeCurrentExecutionFilePath);
                    context.Response.OutputStream.Write(buffer, 0, readBytes);

                    if (readBytes < buffer.Length)
                    {
                        cached = new byte[readBytes];
                        Array.Copy(buffer, cached, readBytes);
                        context.Cache.Add("VirtualPathFileHandler:" + context.Request.AppRelativeCurrentExecutionFilePath, cached, vpp.GetCacheDependency(context.Request.AppRelativeCurrentExecutionFilePath, new[] { context.Request.AppRelativeCurrentExecutionFilePath }, DateTime.UtcNow), DateTime.MaxValue, TimeSpan.FromMinutes(1), System.Web.Caching.CacheItemPriority.BelowNormal, null);
                    }
                    TransferBetweenStreams(buffer, s, context.Response.OutputStream);
                }
            }
        }
Exemple #25
0
        /// <summary>
        ///     Gets the file dependencies (@imports) of the LESS file being parsed.
        /// </summary>
        /// <param name="lessEngine">The LESS engine.</param>
        /// <returns>An array of file references to the dependent file references.</returns>
        private static IEnumerable <BundleFile> GetFileDependencies(LessEngine lessEngine)
        {
            ImportedFilePathResolver pathResolver = lessEngine.Parser.GetPathResolver();
            VirtualPathProvider      vpp          = BundleTable.VirtualPathProvider;

            foreach (string resolvedVirtualPath in lessEngine.GetImports().Select(pathResolver.GetFullPath))
            {
                // the file was successfully imported, therefore no need to check before vpp.GetFile
                yield return(new BundleFile(resolvedVirtualPath, vpp.GetFile(resolvedVirtualPath)));
            }

            lessEngine.ResetImports();
        }
        public override VirtualFile GetFile(string virtualPath)
        {
            if (!IsEmbeddedPath(virtualPath))
            {
                return(_previous.GetFile(virtualPath));
            }
            var prefix               = String.Format("~/{0}/", BundleTable.EnableOptimizations?_settings.AppClientFilesPrefix:_settings.EmbeddedResourceUrl);
            var resourceName         = virtualPath.Replace(prefix, String.Empty).Replace('/', '.');
            var nameSpace            = getNameSpace();
            var manifestResourceName = string.Format("{0}.{1}", nameSpace, resourceName);

            return(getEmbeddedFile(virtualPath, manifestResourceName));
        }
 /// <summary>
 /// Reads the bundle manifest.
 /// </summary>
 /// <param name="vpp">The VPP.</param>
 /// <returns></returns>
 internal static HtmlTemplateBundleManifest ReadBundleManifest(VirtualPathProvider vpp)
 {
     if (vpp == null)
     {
         return((HtmlTemplateBundleManifest)null);
     }
     if (!vpp.FileExists(HtmlTemplateBundleManifest.BundleManifestPath))
     {
         return((HtmlTemplateBundleManifest)null);
     }
     using (Stream bundleStream = vpp.GetFile(HtmlTemplateBundleManifest.BundleManifestPath).Open())
         return(HtmlTemplateBundleManifest.ReadBundleManifest(bundleStream));
 }
        public override VirtualFile GetFile(string virtualPath)
        {
            if (virtualPathProvider.FileExists(virtualPath))
            {
                return(virtualPathProvider.GetFile(virtualPath));
            }
            var compiledType = GetCompiledType(virtualPath);

            if (compiledType != null)
            {
                return(new CompiledVirtualFile(virtualPath, compiledType));
            }
            return(null);
        }
        void AppendFileScriptContents(StringWriter sw, CompositeEntry entry)
        {
            // FIXME: should we limit the script size in any way?
            if (String.IsNullOrEmpty(entry.NameOrPath))
            {
                return;
            }

            string mappedPath;

            if (!HostingEnvironment.HaveCustomVPP)
            {
                // We'll take a shortcut here by bypassing the default VPP layers
                mappedPath = HostingEnvironment.MapPath(entry.NameOrPath);
                if (!File.Exists(mappedPath))
                {
                    return;
                }
                sw.Write(File.ReadAllText(mappedPath));
                return;
            }

            VirtualPathProvider vpp = HostingEnvironment.VirtualPathProvider;

            if (!vpp.FileExists(entry.NameOrPath))
            {
                return;
            }
            VirtualFile file = vpp.GetFile(entry.NameOrPath);

            if (file == null)
            {
                return;
            }
            using (Stream s = file.Open())
            {
                using (var r = new StreamReader(s))
                {
                    string line = r.ReadLine();
                    while (line != null)
                    {
                        sw.WriteLine(line);
                        line = r.ReadLine();
                    }
                }
            }
        }
        internal static bool IsNonUpdateablePrecompiledApp(
            VirtualPathProvider vpp,
            IVirtualPathUtility virtualPathUtility
            )
        {
            var virtualPath = virtualPathUtility.ToAbsolute("~/PrecompiledApp.config");

            if (!vpp.FileExists(virtualPath))
            {
                return(false);
            }

            XDocument document;

            using (Stream stream = vpp.GetFile(virtualPath).Open())
            {
                try
                {
                    document = XDocument.Load(stream);
                }
                catch
                {
                    // If we are unable to load the file, ignore it. The BuildManager behaves identically.
                    return(false);
                }
            }

            if (
                document.Root == null ||
                !document.Root.Name.LocalName.Equals(
                    "precompiledApp",
                    StringComparison.OrdinalIgnoreCase
                    )
                )
            {
                return(false);
            }
            var updatableAttribute = document.Root.Attribute("updatable");

            if (updatableAttribute != null)
            {
                bool result;
                return(Boolean.TryParse(updatableAttribute.Value, out result) && (result == false));
            }
            return(false);
        }