/// <summary> /// Recupera a chave do template. /// </summary> /// <param name="name"></param> /// <param name="templateType"></param> /// <param name="context"></param> /// <returns></returns> public ITemplateKey GetKey(string name, ResolveType templateType, ITemplateKey context) { if (System.Web.Hosting.HostingEnvironment.VirtualPathProvider.FileExists(name)) { var virtualFile = System.Web.Hosting.HostingEnvironment.VirtualPathProvider.GetFile(name); var cache = virtualFile as ITemplateCacheSupport; RazorEngine.Templating.ITemplateKey templateKey = null; if (cache != null) { if (cache.TemplateKey == null) { templateKey = new NameOnlyTemplateKey(name, templateType, context); cache.Register(templateKey); } else { templateKey = cache.TemplateKey; } } else { templateKey = new NameOnlyTemplateKey(name, templateType, context); } return(templateKey); } return(new NameOnlyTemplateKey(name, templateType, context)); }
/// <summary> /// 缓存模板助手 /// </summary> /// <param name="template">模板</param> /// <param name="templateKey">模板键</param> /// <param name="modelTypeKey">模板类型键</param> private void CacheTemplateHelper(ICompiledTemplate template, ITemplateKey templateKey, Type modelTypeKey) { var uniqueKey = templateKey.GetUniqueKeyString(); _cache.AddOrUpdate(uniqueKey, key => { // 添加新项 _assemblies.Add(template.TemplateAssembly); var dict = new ConcurrentDictionary <Type, ICompiledTemplate>(); dict.AddOrUpdate(modelTypeKey, template, (t, old) => template); return(dict); }, (key, dict) => { dict.AddOrUpdate(modelTypeKey, t => { // 添加新条目(模板没有编译给定类型) _assemblies.Add(template.TemplateAssembly); return(template); }, (t, old) => { // 项目已经添加 return(template); }); return(dict); }); }
/// <summary> /// Compiles the specified template. /// </summary> /// <param name="key">The string template.</param> /// <param name="modelType">The model type.</param> public ICompiledTemplate Compile(ITemplateKey key, Type modelType) { Contract.Requires(key != null); var source = Resolve(key); var result = CreateTemplateType(source, modelType); return new CompiledTemplate(result.Item2, key, source, result.Item1, modelType); }
public ITemplateKey GetKey(string name, ResolveType resolveType, ITemplateKey context) { if (ManifestResourceHelper.checkExistsManifestResource(name)) { return(new ResourcePathTemplateKey(name, name, resolveType, context)); } var existsResourceNames = layoutRoots.Select(m => { string resourcePath = string.Format(m, name); if (ManifestResourceHelper.checkExistsManifestResource(resourcePath)) { return(resourcePath); } resourcePath += ".cshtml"; if (ManifestResourceHelper.checkExistsManifestResource(resourcePath)) { return(resourcePath); } return(null); }); var resourceName = existsResourceNames.Where(m => !string.IsNullOrEmpty(m)).FirstOrDefault(); if (resourceName == null) { throw new InvalidOperationException(string.Format("Could not resolve template {0}", name)); } return(new ResourcePathTemplateKey(name, resourceName, resolveType, context)); }
public ITemplateKey GetKey(string name, ResolveType resolveType, ITemplateKey context) { // If you can have different templates with the same name depending on the // context or the resolveType you need your own implementation here! // Otherwise you can just use NameOnlyTemplateKey. return(new NameOnlyTemplateKey(name, resolveType, context)); }
/// <summary> /// Get the given key. /// </summary> /// <param name="name"></param> /// <param name="resolveType"></param> /// <param name="context"></param> /// <returns></returns> public new ITemplateKey GetKey(string name, ResolveType resolveType, ITemplateKey context) { var fullPath = ResolveFilePath(name); var modifiedTime = File.GetLastWriteTimeUtc(fullPath); return(new FullPathWithModifiedTimeTemplateKey(name, fullPath, modifiedTime, resolveType, context)); }
public void AddDynamic(ITemplateKey key, ITemplateSource source) { // You can disable dynamic templates completely. // This just means all convenience methods (Compile and RunCompile) with // a TemplateSource will no longer work (they are not really needed anyway). //throw new NotImplementedException("dynamic templates are not supported!"); }
public ITemplateSource Resolve(ITemplateKey key) { var name = key.Name; LoadedTemplateSource loadedTemplate; if (!this.TopLevelTemplates.TryGetValue(name, out loadedTemplate)) { var id = Path.GetFileNameWithoutExtension(name); var extension = Path.GetExtension(name).TrimStart('.'); var layout = RenderingTransaction.Current.Layouts[id]; if (!layout.Extension.Equals(String.IsNullOrEmpty(extension) ? "cshtml" : extension, StringComparison.OrdinalIgnoreCase)) { // TODO: throw new exception. } loadedTemplate = new LoadedTemplateSource(layout.SourceContent, layout.SourcePath); // Do not need to add this loaded template to our list of cached top level templates // because RazorEngine will remember it for us and never ask again. } return(loadedTemplate); }
private void CacheTemplateHelper(ICompiledTemplate template, ITemplateKey templateKey, Type modelTypeKey) { var uniqueKey = templateKey.GetUniqueKeyString(); _cache.AddOrUpdate(uniqueKey, key => { // new item added _assemblies.Add(template.TemplateAssembly); var dict = new ConcurrentDictionary<Type, ICompiledTemplate>(); dict.AddOrUpdate(modelTypeKey, template, (t, old) => { throw new Exception("Expected the dictionary to be empty."); }); return dict; }, (key, dict) => { dict.AddOrUpdate(modelTypeKey, t => { // new item added (template was not compiled with the given type). _assemblies.Add(template.TemplateAssembly); return template; }, (t, old) => { // item was already added before return template; }); return dict; }); }
public ITemplateSource Resolve(ITemplateKey key) { if (_templates.ContainsKey(key)) { return(_templates[key]); } var templatePath = Path.Combine(includesPath, key.Name); var templateExists = fileSystem.File.Exists(templatePath); if (!templateExists) { foreach (var ext in new[] { ".cshtml", ".html", ".htm" }) { var testPath = String.Concat(templatePath, ext); templateExists = fileSystem.File.Exists(testPath); if (templateExists) { templatePath = testPath; break; } } } var template = templateExists ? fileSystem.File.ReadAllText(templatePath) : String.Empty; return(new LoadedTemplateSource(template, null)); }
/// <summary> /// Get the given key. /// </summary> /// <param name="name"></param> /// <param name="resolveType"></param> /// <param name="context"></param> /// <returns></returns> public ITemplateKey GetKey(string name, ResolveType resolveType, ITemplateKey context) { if (File.Exists (name)) { return new FullPathTemplateKey(name, name, resolveType, context); } else { var resolved = layoutRoots.Select(l => { var p = Path.Combine(l, name); if (File.Exists(p)) { return p; } else if (File.Exists(p + ".cshtml")) { return p + ".cshtml"; } else { return null; } }).Where(l => l != null).FirstOrDefault(); if (resolved == null) { throw new InvalidOperationException(string.Format("Could not resolve template {0}", name)); } else { return new FullPathTemplateKey(name, resolved, resolveType, context); } } }
private void CacheTemplateHelper(ICompiledTemplate template, ITemplateKey templateKey, Type modelTypeKey) { var uniqueKey = templateKey.GetUniqueKeyString(); _cache.AddOrUpdate(uniqueKey, key => { // new item added _assemblies.Add(template.TemplateAssembly); var dict = new ConcurrentDictionary <Type, ICompiledTemplate>(); dict.AddOrUpdate(modelTypeKey, template, (t, old) => { throw new Exception("Expected the dictionary to be empty."); }); return(dict); }, (key, dict) => { dict.AddOrUpdate(modelTypeKey, t => { // new item added (template was not compiled with the given type). _assemblies.Add(template.TemplateAssembly); return(template); }, (t, old) => { // item was already added before return(template); }); return(dict); }); }
/// <summary> /// Invalidates all compilations of the given template. /// WARNING: leads to memory leaks /// </summary> /// <param name="templateKey"></param> public void InvalidateCache(ITemplateKey templateKey) { var uniqueKey = templateKey.GetUniqueKeyString(); ConcurrentDictionary <Type, ICompiledTemplate> dict; _cache.TryRemove(uniqueKey, out dict); }
public async Task <MailMessage> CreateMailMessageAsync(IEmail email, ITemplateKey key) { var templateOutput = this.Render(email, key); var mailMessage = await emailParser.ParseAsync(templateOutput, email); return(mailMessage); }
public ITemplateSource Resolve(ITemplateKey key) { var name = key.Name; if (string.IsNullOrEmpty(name)) { throw new ArgumentNullException("ITemplateKey.Name"); } var path = Common.GetViewPath(name); var template = Common.ReadAllText(path); if (key.TemplateType != ResolveType.Layout && !Common.IsLayoutView(path)) { var layout = sLayout; var reg = new System.Text.RegularExpressions.Regex( "[\\n]+\\s*Layout\\s*=\\s*\"~/Views/Shared/_[a-zA-Z]*\\.cshtml\";\\s*[\\n]+", System.Text.RegularExpressions.RegexOptions.IgnoreCase); var rm = reg.Match(template); if (rm != null && rm.Success) { layout = $"@{{{rm.Value.Replace("\"~/Views/Shared/_", "\"Shared/_")}}}"; template = reg.Replace(template, " "); } template = layout + template; } // Resolve your template here (ie read from disk) // if the same templates are often read from disk you propably want to do some caching here. //string template = "Hello @Model.Name, welcome to RazorEngine!"; // Provide a non-null file to improve debugging return(new LoadedTemplateSource(template, null)); }
public ITemplateKey GetKey(string name, ResolveType resolveType, ITemplateKey context) { // If you can have different templates with the same name depending on the // context or the resolveType you need your own implementation here! // Otherwise you can just use NameOnlyTemplateKey. return new NameOnlyTemplateKey(name, resolveType, context); }
public ITemplateKey GetKey(string name, ResolveType resolveType, ITemplateKey context) { var ctx = new KeyNameResolveContext() { OriginalName = name, ResolveType = resolveType, Context = context, ResolvedName = name, NameResolved = false }; // I need to read resolvers from WorkContext here, because if I injected them in the class constructor they wouldn't work properly. // They cache their content throughout multiple requests and fail to update content templates when needed. // This happens because IRazorTemplateManager inherits from ISingletonDependency. var resolvers = _orchardServices.WorkContext .Resolve <IEnumerable <ICustomRazorTemplateResolver> >() .OrderByDescending(r => r.Priority); foreach (var res in resolvers) { if (ctx.NameResolved) { break; } res.GetKeyName(ctx); } return(new NameOnlyTemplateKey(ctx.ResolvedName, resolveType, context)); }
public void AddDynamic(ITemplateKey key, ITemplateSource source) { // You can disable dynamic templates completely, but // then all convenience methods (Compile and RunCompile) with // a TemplateSource will no longer work (they are not really needed anyway). throw new NotImplementedException("dynamic templates are not supported!"); }
/// <summary> /// 使用RazorEngine编译cshtml页面.返回静态内容 /// </summary> /// <param name="temps">temps是一个以路径为键,cshtml文件内容为值的字典.它包含了一个要被编译的cshtml主文件以及其引用的1个母板页和0~多个片段页.</param> /// <param name="mainCshtmlKey">要编译的主cshtml模板文件在temps中的key</param> /// <returns></returns> private static string RazorRun(Dictionary <string, string> temps, string mainCshtmlKey, object model = null) { // 添加要编译的cshtml文件,包括其引用的母板页和片段页 foreach (string key in temps.Keys) { // 如果文件有变化才重新添加模板和编译,因为编译时间比较长 if (!RazorCacheHelpers.IsChange(key, temps[key])) { continue; } // 键是文件的相对路径名,是固定的,每个cshtml的路径是唯一的. ITemplateKey k = serveice.GetKey(key); // 先删除这个键,再添加之.由于键固定,不删除的话,会报键重复. ((DelegateTemplateManager)config.TemplateManager).RemoveDynamic(k); // 添加模板,以键为模板名,以cshtml内容为模板内容 serveice.AddTemplate(k, temps[key]); // 编译之.由于键固定,如果不编译的话,就会使用上一次编译后的缓存(与这固定键对应的缓存).所以添加模板后,一定要重新编译. serveice.Compile(k); } // MainCshtmlKey是cshtml主页面,生成html时,必须以主cshtml模板的名. if (model == null) { return(serveice.Run(serveice.GetKey(mainCshtmlKey))); } return(serveice.Run(serveice.GetKey(mainCshtmlKey), null, model)); }
public ITemplateSource Resolve(ITemplateKey key) { if (_templates.ContainsKey(key)) { return _templates[key]; } var templatePath = Path.Combine(includesPath, key.Name); var templateExists = fileSystem.File.Exists(templatePath); if (!templateExists) { foreach (var ext in new[] { ".cshtml", ".html", ".htm" }) { var testPath = String.Concat(templatePath, ext); templateExists = fileSystem.File.Exists(testPath); if (templateExists) { templatePath = testPath; break; } } } var template = templateExists ? fileSystem.File.ReadAllText(templatePath) : String.Empty; return new LoadedTemplateSource(template, null); }
/// <summary> /// Try to retrieve a template from the cache. See <see cref="ICachingProvider.TryRetrieveTemplate"/>. /// </summary> /// <param name="templateKey"></param> /// <param name="modelType"></param> /// <param name="compiledTemplate"></param> /// <returns></returns> public bool TryRetrieveTemplate(ITemplateKey templateKey, Type modelType, out ICompiledTemplate compiledTemplate) { compiledTemplate = null; if (templateKey == null) { return(false); } var uniqueKey = templateKey.GetUniqueKeyString(); if (string.IsNullOrEmpty(uniqueKey)) { return(false); } var modelTypeKey = GetModelTypeKey(modelType); ConcurrentDictionary <Type, ICompiledTemplate> dict; if (!_cache.TryGetValue(uniqueKey, out dict)) { return(false); } if (modelTypeKey == null) { return(false); } return(dict.TryGetValue(modelTypeKey, out compiledTemplate)); }
private bool KeysHaveEqualModifiedTime(ITemplateKey key1, ITemplateKey key2) { var keyWithTime1 = (FullPathWithModifiedTimeTemplateKey)key1; var keyWithTime2 = (FullPathWithModifiedTimeTemplateKey)key2; return keyWithTime1.ModifiedTime == keyWithTime2.ModifiedTime; }
/// <summary> /// 添加缓存 /// </summary> /// <param name="key">键</param> /// <param name="source">源</param> public void AddDynamic(ITemplateKey key, ITemplateSource source) { _dynamicTemplates.AddOrUpdate(key, source, (k, oldSource) => { return(source); }); }
/// <summary> /// 获取键 /// </summary> /// <param name="name">名称</param> /// <param name="resolveType">解决类型</param> /// <param name="key">键</param> /// <returns>返回键</returns> public ITemplateKey GetKey(string name, ResolveType resolveType, ITemplateKey key) { // 如果你可以有不同的模板具有相同名称的根据 // 上下文或resolveType你需要自己实现! // 否则你可以使用NameOnlyTemplateKey。 return(new NameOnlyTemplateKey(name, resolveType, key)); }
public ITemplateKey GetKey(string name, ResolveType resolveType, ITemplateKey context) { if (ManifestResourceHelper.checkExistsManifestResource(name)) { return new ResourcePathTemplateKey(name, name, resolveType, context); } var existsResourceNames = layoutRoots.Select(m => { string resourcePath = string.Format(m, name); if (ManifestResourceHelper.checkExistsManifestResource(resourcePath)) { return resourcePath; } resourcePath += ".cshtml"; if (ManifestResourceHelper.checkExistsManifestResource(resourcePath)) { return resourcePath; } return null; }); var resourceName = existsResourceNames.Where(m => !string.IsNullOrEmpty(m)).FirstOrDefault(); if (resourceName == null) { throw new InvalidOperationException(string.Format("Could not resolve template {0}", name)); } return new ResourcePathTemplateKey(name, resourceName, resolveType, context); }
public void AddDynamic(ITemplateKey key, ITemplateSource source) { if (!_templates.ContainsKey(key)) { _templates.Add(key, source); } }
/// <summary> /// Get the given key. /// </summary> /// <param name="name"></param> /// <param name="resolveType"></param> /// <param name="context"></param> /// <returns></returns> public new ITemplateKey GetKey(string name, ResolveType resolveType, ITemplateKey context) { var fullPath = ResolveFilePath(name); var modifiedTime = File.GetLastWriteTimeUtc(fullPath); return new FullPathWithModifiedTimeTemplateKey(name, fullPath, modifiedTime, resolveType, context); }
private bool KeysHaveEqualModifiedTime(ITemplateKey key1, ITemplateKey key2) { var keyWithTime1 = (FullPathWithModifiedTimeTemplateKey)key1; var keyWithTime2 = (FullPathWithModifiedTimeTemplateKey)key2; return(keyWithTime1.ModifiedTime == keyWithTime2.ModifiedTime); }
/// <summary> /// Get the given key. /// </summary> /// <param name="name"></param> /// <param name="resolveType"></param> /// <param name="context"></param> /// <returns></returns> public ITemplateKey GetKey(string name, ResolveType resolveType, ITemplateKey context) { if (File.Exists(name)) { return(new FullPathTemplateKey(name, name, resolveType, context)); } else { var resolved = layoutRoots.Select(l => { var p = Path.Combine(l, name); if (File.Exists(p)) { return(p); } else if (File.Exists(p + ".cshtml")) { return(p + ".cshtml"); } else { return(null); } }).Where(l => l != null).FirstOrDefault(); if (resolved == null) { throw new InvalidOperationException(string.Format("Could not resolve template {0}", name)); } else { return(new FullPathTemplateKey(name, resolved, resolveType, context)); } } }
/// <summary> /// Compiles the given template, caches it and returns the result. /// </summary> /// <param name="key"></param> /// <param name="modelType"></param> /// <returns></returns> internal ICompiledTemplate CompileAndCacheInternal(ITemplateKey key, Type modelType) { var compiled = _core_with_cache.Compile(key, modelType); _config.CachingProvider.CacheTemplate(compiled, key); return(compiled); }
public SpaRazorMiddleware(string defaultview) { key = CreateRazorKey(defaultview); if (!AppSettings.TryGet("TestEnvironment", out testEnvironment)) { testEnvironment = false; } }
public ITemplateSource Resolve(ITemplateKey key) { // Resolve your template here string template = "Hello @Model.Name, welcome to RazorEngine!"; // Provide a non-null file to improve debugging return(new LoadedTemplateSource(template, null)); }
//методы public ITemplateSource Resolve(ITemplateKey key) { string filePath = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, _templateFolder, key.Name); string template = File.ReadAllText(filePath); // Provide a non-null file to improve debugging return new LoadedTemplateSource(template, filePath); }
public CompiledTemplate(CompilationData tempFiles, ITemplateKey key, ITemplateSource source, Type templateType, Type modelType) { _tempFiles = tempFiles; _key = key; _source = source; _templateType = templateType; _modelType = modelType; }
public InternalTemplateService(RazorEngineCore service, ITemplateKey template) { Contract.Requires(service != null); Contract.Requires(template != null); _service = service; _template = template; }
public ITemplateSource Resolve(ITemplateKey key) { if (_dynamicTemplates.TryGetValue(key, out ITemplateSource result)) { return(result); } return(null); }
/// <summary> /// Compiles the specified template. /// </summary> /// <param name="key">The string template.</param> /// <param name="modelType">The model type.</param> public ICompiledTemplate Compile(ITemplateKey key, Type modelType) { Contract.Requires(key != null); var source = Resolve(key); var result = CreateTemplateType(source, modelType); return(new CompiledTemplate(result.Item2, key, source, result.Item1, modelType)); }
public ITemplateSource Resolve(ITemplateKey key) { // Resolve your template here (ie read from disk) // if the same templates are often read from disk you propably want to do some caching here. string template = "Hello @Model.Name, welcome to RazorEngine!"; // Provide a non-null file to improve debugging return(new LoadedTemplateSource(template, null)); }
/// <summary> /// Resolve the given key /// </summary> /// <param name="key"></param> /// <returns></returns> public ITemplateSource Resolve(ITemplateKey key) { Stream stream = null; var name = key.Name + ".cshtml"; try { stream = this.RootType.Assembly.GetManifestResourceStream(this.RootType, name); // Assemblies built using .NET Core CLI have their embedded resources named by: // {assembly name}.{folder structure (separated by periods)}.{name} // // ie. Test.RazorEngine.Core.Templating.Templates.Layout.cshtml where: // assembly name: Test.RazorEngine.Core // folder structure: Templating.Templates // name: Layout.cshtml // // If the namespace of the RootType does not use the generated default namespace // then it would be unable to resolve the resource manifest scoped by that RootType. if (stream == null) { var matching = this.RootType.Assembly.GetManifestResourceNames() .Where(x => x.EndsWith(name, StringComparison.Ordinal)) .ToArray(); if (matching.Length == 0) { throw new TemplateLoadingException(string.Format("Couldn't load resource '{0}.{1}.cshtml' from assembly {2}", this.RootType.Namespace, key.Name, this.RootType.Assembly.FullName)); } else if (matching.Length > 1) { throw new TemplateLoadingException(string.Format( "Could not resolve template scoped to root type {0}. Found multiple templates ending with {0} in assembly {2}!" + " Please specify a fully-qualified template name. Matching templates: {3}", this.RootType.Namespace, name, this.RootType.Assembly.FullName, string.Join("; ", matching)) ); } else { stream = RootType.Assembly.GetManifestResourceStream(matching[0]); } } using (var reader = new StreamReader(stream)) { return(new LoadedTemplateSource(reader.ReadToEnd())); } } finally { if (stream != null) { stream.Dispose(); } } }
/// <summary> /// Resolves the template content with the specified key. /// </summary> /// <param name="key">The key of the template to resolve.</param> /// <returns>The template content.</returns> public ITemplateSource Resolve(ITemplateKey key) { ITemplateSource result; if (_dynamicTemplates.TryGetValue(key, out result)) { return result; } var templateString = _resolver.Resolve(key.Name); return new LoadedTemplateSource(templateString); }
/// <summary> /// Resolve the given key /// </summary> /// <param name="key"></param> /// <returns></returns> public ITemplateSource Resolve(ITemplateKey key) { var full = key as FullPathTemplateKey; if (full == null) { throw new NotSupportedException("You can only use FullPathTemplateKey with this manager"); } var template = File.ReadAllText(full.FullPath); return new LoadedTemplateSource(template, full.FullPath); }
/// <summary> /// 解决源 /// </summary> /// <param name="key">键</param> /// <returns>返回资源模板</returns> public ITemplateSource Resolve(ITemplateKey key) { if (_dynamicTemplates.TryGetValue(key, out ITemplateSource result)) { return(result); } var str = _resolver(key.Name); return(new LoadedTemplateSource(str)); }
public ITemplateSource Resolve(ITemplateKey key) { ResourcePathTemplateKey resourcePathTemplateKey = key as ResourcePathTemplateKey; if (resourcePathTemplateKey == null) { throw new NotSupportedException("You can only use ResourcePathTemplateKey with this manager"); } return new LoadedTemplateSource(ManifestResourceHelper.getManifestResourceString(resourcePathTemplateKey.ResourcePath), resourcePathTemplateKey.ResourcePath); }
public ITemplateKey GetKey(string name, ResolveType resolveType, ITemplateKey context) { var itk = context as IdentityTemplateKey; if (itk != null) { return new IdentityTemplateKey(name, itk.ClientId, itk.Tenant, resolveType); } return null; }
/// <summary> /// Resolves the template with the specified key. /// </summary> /// <param name="key">The key which should be resolved to a template source.</param> /// <returns> /// The template content. /// </returns> public ITemplateSource Resolve(ITemplateKey key) { var fullPath = _viewsPathResolver.ResolveFullPath(key.Name); string template; using (var fs = new FileStream(fullPath, FileMode.Open, FileAccess.Read, FileShare.ReadWrite)) using (var sr = new StreamReader(fs, Encoding.UTF8)) { template = sr.ReadToEnd(); } return new LoadedTemplateSource(template); }
internal override ITemplate ResolveInternal(string cacheName, object model, Type modelType, DynamicViewBag viewbag, ResolveType resolveType, ITemplateKey context) { var templateKey = GetKey(cacheName, resolveType, context); ICompiledTemplate compiledTemplate; if (!Configuration.CachingProvider.TryRetrieveTemplate(templateKey, modelType, out compiledTemplate)) { compiledTemplate = Compile(templateKey, modelType); Configuration.CachingProvider.CacheTemplate(compiledTemplate, templateKey); } return CreateTemplate(compiledTemplate, model, viewbag); }
/// <summary> /// Adds a template dynamically. /// </summary> /// <param name="key">the key of the template</param> /// <param name="source">the source of the template</param> public void AddDynamic(ITemplateKey key, ITemplateSource source) { _dynamicTemplates.AddOrUpdate(key, source, (k, oldSource) => { if (oldSource.Template != source.Template) { throw new InvalidOperationException("The same key was used for another template!"); } return source; }); }
public ITemplateSource Resolve(ITemplateKey key) { IdentityTemplateKey itk = (IdentityTemplateKey)key; var templateContent = _razorViewLoader.Load(itk.Name, itk.ClientId, itk.Tenant); if (templateContent != null) { return new LoadedTemplateSource(templateContent, null); } throw new FileNotFoundException(); }
/// <summary> /// Resolve the given key /// </summary> /// <param name="key"></param> /// <returns></returns> public ITemplateSource Resolve(ITemplateKey key) { using (var stream = this.RootType.Assembly.GetManifestResourceStream(this.RootType, key.Name + ".cshtml")) { if(stream == null) throw new TemplateLoadingException(string.Format("Couldn't load resource '{0}.{1}.cshtml' from assembly {2}", this.RootType.Namespace, key.Name, this.RootType.Assembly.FullName)); using (var reader = new StreamReader(stream)) { return new LoadedTemplateSource(reader.ReadToEnd()); } } }
public string RunCompile(ITemplateKey key, Type modelType, object model, DynamicViewBag viewBag) { //判断唯一视图的缓存 string path = (HuberVariable.CurWebDir + key.Name).Replace(@"\\", @"\"); ICompiledTemplate cacheTemplate; cache.TryRetrieveTemplate(key, null, out cacheTemplate); if (cacheTemplate == null || !cacheTemplate.Key.Name.Trim().Equals(key.Name.Trim())) { CompileViewAndLayout(key, null, model, viewBag); } //当缓存存在返回结果 return Engine.Razor.RunCompile(key, null, model, viewBag); }
/// <summary> /// Caches a template. See <see cref="ICachingProvider.CacheTemplate"/>. /// </summary> /// <param name="template"></param> /// <param name="templateKey"></param> public void CacheTemplate(ICompiledTemplate template, ITemplateKey templateKey) { var modelTypeKey = GetModelTypeKey(template.ModelType); CacheTemplateHelper(template, templateKey, modelTypeKey); var typeArgs = template.TemplateType.BaseType.GetGenericArguments(); if (typeArgs.Length > 0) { var alternativeKey = GetModelTypeKey(typeArgs[0]); if (alternativeKey != modelTypeKey) { // could be a template with an @model directive. CacheTemplateHelper(template, templateKey, typeArgs[0]); } } }
/// <summary> /// Try to retrieve a template from the cache. See <see cref="ICachingProvider.TryRetrieveTemplate"/>. /// If cached template has different modification time, then the cache is invalidated. /// </summary> /// <param name="templateKey"></param> /// <param name="modelType"></param> /// <param name="compiledTemplate"></param> /// <returns></returns> public new bool TryRetrieveTemplate(ITemplateKey templateKey, Type modelType, out ICompiledTemplate compiledTemplate) { ICompiledTemplate foundTemplate; if (base.TryRetrieveTemplate(templateKey, modelType, out foundTemplate)) { if (KeysHaveEqualModifiedTime(foundTemplate.Key, templateKey)) { compiledTemplate = foundTemplate; return true; } InvalidateCache(foundTemplate.Key); } compiledTemplate = null; return false; }
public ITemplateSource Resolve(ITemplateKey key) { ITemplateSource result; if (_dynamicTemplates.TryGetValue(key, out result)) { return result; } var htmlContent = _templateRepository.Get(key.Name); if (htmlContent == null) { throw new InvalidOperationException(""); } return new LoadedTemplateSource(htmlContent); }
/// <summary> /// 编译视图和层layout /// </summary> /// <param name="key">视图的唯一路径</param> /// <param name="modelType">视图类型 :视图/layout</param> /// <param name="model">页面 MODEL</param> /// <param name="viewBag">viewBag</param> public void CompileViewAndLayout(ITemplateKey key, Type modelType, object model, DynamicViewBag viewBag) { //获取视图 string FullPath = (HuberVariable.CurWebDir + key.Name.Replace("/", @"\")).Replace(@"\\", @"\"); string content = System.IO.File.ReadAllText(FullPath); //匹配layout var matchs = layoutEx.Matches(content); string layoutPath = string.Empty; if (matchs != null) { foreach (Match m in matchs) { layoutPath = m.Groups[1].Value; } } if (layoutPath != string.Empty) { //添加layout到模板 string FullLayoutPath = (HuberVariable.CurWebDir + layoutPath.Replace("/", @"\")).Replace(@"\\", @"\"); if (File.Exists(FullLayoutPath)) { ITemplateKey layoutKey = Engine.Razor.GetKey(layoutPath, ResolveType.Layout); CompileViewAndLayout(layoutKey, null, model, viewBag); } } if (key.TemplateType == ResolveType.Layout) { Engine.Razor.AddTemplate(key, content); } else { //编译视图 Engine.Razor.RunCompile(content, key, null, model); } }
// private static readonly string usingStatement = "@model dynamic" + Environment.NewLine; public ITemplateSource Resolve(ITemplateKey key) { // Resolve your template here (ie read from disk) // if the same templates are often read from disk you probably want to do some caching here. var relativePath = ""; if (!key.Name.StartsWith("~")) { relativePath = @"~/views/TESTViews/" + key.Name + ".cshtml"; } else { relativePath = (key.Name); } var serverPath = HttpContext.Current.Server.MapPath(relativePath); string templateHtml; try { //templateHtml = usingStatement + File.ReadAllText(serverPath); templateHtml = File.ReadAllText(serverPath); } catch (DirectoryNotFoundException) { templateHtml = "No folder named " + Path.GetDirectoryName(serverPath) + ". in other words add a folder named " + Path.GetDirectoryName(serverPath); } catch (FileNotFoundException) { templateHtml = "No template '" + Path.GetFileName(key.Name) + ". In other words add template named " + Path.GetFileName(key.Name) + ".cshtml in a folder called " + Path.GetDirectoryName(serverPath); } // Provide a non-null file to improve debugging return new LoadedTemplateSource(templateHtml, serverPath); }
internal ITemplateSource Resolve(ITemplateKey key) { return Configuration.TemplateManager.Resolve(key); }
internal virtual ITemplate ResolveInternal(string cacheName, object model, Type modelType, DynamicViewBag viewBag, ResolveType resolveType, ITemplateKey context) { var templateKey = GetKey(cacheName, resolveType, context); var compiledTemplate = Compile(templateKey, modelType); return CreateTemplate(compiledTemplate, model, viewBag); }