protected RazorCodeLanguage GetCodeLanguage(string resourceName) { var extension = new FileInfo(resourceName).Extension; var language = RazorCodeLanguage.GetLanguageByExtension(extension); return(language); }
public void MultipleCallsToGetServiceWithSameExtensionReturnSameObject() { // Arrange RazorCodeLanguage expected = RazorCodeLanguage.GetLanguageByExtension("cshtml"); // Act RazorCodeLanguage actual = RazorCodeLanguage.GetLanguageByExtension("cshtml"); // Assert Assert.AreSame(expected, actual); }
public RazorPageHost(IVirtualPathProvider pathProvider, IVirtualFile file, IRazorCodeTransformer codeTransformer, CodeDomProvider codeDomProvider, IDictionary <string, string> directives) : base(RazorCodeLanguage.GetLanguageByExtension(".cshtml")) { this.PathProvider = pathProvider; this.File = file; if (codeTransformer == null) { throw new ArgumentNullException("codeTransformer"); } if (this.PathProvider == null) { throw new ArgumentNullException("pathProvider"); } if (this.File == null) { throw new ArgumentNullException("file"); } if (codeDomProvider == null) { throw new ArgumentNullException("codeDomProvider"); } _codeTransformer = codeTransformer; _codeDomProvider = codeDomProvider; _directives = directives; base.DefaultNamespace = "ASP"; EnableLinePragmas = true; base.GeneratedClassContext = new GeneratedClassContext( executeMethodName: GeneratedClassContext.DefaultExecuteMethodName, writeMethodName: GeneratedClassContext.DefaultWriteMethodName, writeLiteralMethodName: GeneratedClassContext.DefaultWriteLiteralMethodName, writeToMethodName: "WriteTo", writeLiteralToMethodName: "WriteLiteralTo", templateTypeName: typeof(HelperResult).FullName, defineSectionMethodName: "DefineSection", beginContextMethodName: "BeginContext", endContextMethodName: "EndContext" ) { ResolveUrlMethodName = "Href", }; base.DefaultBaseClass = typeof(ViewPage).FullName; foreach (var import in _defaultImports) { base.NamespaceImports.Add(import); } }
public RazorHost(string baseRelativePath, string fullPath, IRazorCodeTransformer codeTransformer, CodeDomProvider codeDomProvider, IDictionary <string, string> directives) : base(RazorCodeLanguage.GetLanguageByExtension(CsHtmlLanguage)) { if (codeTransformer == null) { throw new ArgumentNullException("codeTransformer"); } if (baseRelativePath == null) { throw new ArgumentNullException("baseRelativePath"); } if (fullPath == null) { throw new ArgumentNullException("fullPath"); } if (codeDomProvider == null) { throw new ArgumentNullException("codeDomProvider"); } _codeTransformer = codeTransformer; _baseRelativePath = baseRelativePath; _fullPath = fullPath; _codeDomProvider = codeDomProvider; _directives = directives; _languageUtil = Core.CodeLanguageUtil.GetLanguageUtilFromFileExtension(CsHtmlLanguage); base.DefaultNamespace = "ASP"; EnableLinePragmas = true; base.GeneratedClassContext = new GeneratedClassContext( executeMethodName: GeneratedClassContext.DefaultExecuteMethodName, writeMethodName: GeneratedClassContext.DefaultWriteMethodName, writeLiteralMethodName: GeneratedClassContext.DefaultWriteLiteralMethodName, writeToMethodName: "WriteTo", writeLiteralToMethodName: "WriteLiteralTo", templateTypeName: typeof(HelperResult).FullName, defineSectionMethodName: "DefineSection", beginContextMethodName: "BeginContext", endContextMethodName: "EndContext" ) { ResolveUrlMethodName = "Href" }; base.DefaultBaseClass = typeof(WebPage).FullName; foreach (var import in _defaultImports) { base.NamespaceImports.Add(import); } }
private static string Render<TModel>(HtmlHelper helper, string template, TModel model) { // 1. Create a host for the razor engine // TModel CANNOT be an anonymous class! var host = new RazorEngineHost(RazorCodeLanguage.GetLanguageByExtension("cshtml"); host.DefaultNamespace = typeof(MyTemplateBase<TModel>).Namespace; host.DefaultBaseClass = nameof(MyTemplateBase<TModel>) + "<" + typeof(TModel).FullName + ">"; host.NamespaceImports.Add("System.Web.Mvc.Html"); // 2. Create an instance of the razor engine var engine = new RazorTemplateEngine(host); // 3. Parse the template into a CodeCompileUnit using (var reader = new StringReader(template)) { razorResult = engine.GenerateCode(reader); } if (razorResult.ParserErrors.Count > 0) { throw new InvalidOperationException($"{razorResult.ParserErrors.Count} errors when parsing template string!"); } // 4. Compile the produced code into an assembly var codeProvider = new CSharpCodeProvider(); var compilerParameters = new CompilerParameters { GenerateInMemory = true }; compilerParameters.ReferencedAssemblies.Add(typeof(MyTemplateBase<TModel>).Assembly.Location); compilerParameters.ReferencedAssemblies.Add(typeof(TModel).Assembly.Location); compilerParameters.ReferencedAssemblies.Add(typeof(HtmlHelper).Assembly.Location); var compilerResult = codeProvider.CompileAssemblyFromDom(compilerParameters, razorResult.GeneratedCode); if (compilerResult.Errors.HasErrors) { throw new InvalidOperationException($"{compilerResult.Errors.Count} errors when compiling template string!"); } // 5. Create an instance of the compiled class and run it var templateType = compilerResult.CompiledAssembly.GetType($"{host.DefaultNamespace}.{host.DefaultClassName}"); var templateImplementation = Activator.CreateInstance(templateType) as MyTemplateBase<TModel>; templateImplementation.Model = model; templateImplementation.Html = helper; templateImplementation.Execute(); // 6. Return the html output return templateImplementation.Output.ToString(); }
private Assembly CompileAssembly(string templateContent) { var host = new RazorEngineHost(RazorCodeLanguage.GetLanguageByExtension("cshtml")); host.DefaultBaseClass = typeof(MacroView).FullName; host.NamespaceImports.Add("System.Web.Mvc"); host.NamespaceImports.Add("System.Web.Mvc.Ajax"); host.NamespaceImports.Add("System.Web.Mvc.Html"); host.NamespaceImports.Add("System.Net"); host.NamespaceImports.Add("System"); host.NamespaceImports.Add("System.Web.Routing"); host.NamespaceImports.Add("FunnelWeb.Model"); host.NamespaceImports.Add("FunnelWeb.Web.Application.Extensions"); host.NamespaceImports.Add("FunnelWeb.Web.Application.Mvc"); var eng = new RazorTemplateEngine(host); var res = eng.GenerateCode(new StringReader(templateContent), "TemplateInstance", "Generated", "TemplateInstance.cs"); var compiler = new CSharpCodeProvider(); var param = new CompilerParameters(); param.GenerateInMemory = true; param.ReferencedAssemblies.Add(typeof(MacroView).Assembly.Location); param.ReferencedAssemblies.Add(typeof(Microsoft.CSharp.RuntimeBinder.Binder).Assembly.Location); param.ReferencedAssemblies.Add(typeof(System.Runtime.CompilerServices.CallSite).Assembly.Location); foreach (var assembly in AppDomain.CurrentDomain.GetAssemblies()) { try { param.ReferencedAssemblies.Add(assembly.Location); } catch (NotSupportedException) { } } var results = compiler.CompileAssemblyFromDom(param, res.GeneratedCode); if (results.Errors.HasErrors) { throw new Exception("Error compiling template: " + results.Errors[0].ErrorText); } return(results.CompiledAssembly); }
public PreprocessedRazorHost(string fullPath) : base(RazorCodeLanguage.GetLanguageByExtension(".cshtml")) { if (fullPath == null) { throw new ArgumentNullException("fullPath"); } FullPath = fullPath; _codeDomProvider = new Microsoft.CSharp.CSharpCodeProvider(); DefaultNamespace = "ASP"; EnableLinePragmas = true; StaticHelpers = true; GeneratedClassContext = new GeneratedClassContext( GeneratedClassContext.DefaultExecuteMethodName, GeneratedClassContext.DefaultWriteMethodName, GeneratedClassContext.DefaultWriteLiteralMethodName, "WriteTo", "WriteLiteralTo", "Action<System.IO.TextWriter>", "DefineSection", "BeginContext", "EndContext" ) { ResolveUrlMethodName = "Href" }; codeGeneratorOptions = new CodeGeneratorOptions { // HACK: we use true, even though razor uses false, to work around a mono bug where it omits the // line ending after "#line hidden", resulting in the unparseable "#line hiddenpublic" BlankLinesBetweenMembers = true, BracingStyle = "C", // matches Razor built-in settings IndentString = String.Empty, }; foreach (var import in defaultImports) { NamespaceImports.Add(import); } }
private static RazorCodeLanguage DetermineCodeLanguage(string fileName) { string extension = Path.GetExtension(fileName); // Use an if rather than else-if just in case Path.GetExtension returns null for some reason if (String.IsNullOrEmpty(extension)) { return(null); } if (extension[0] == '.') { extension = extension.Substring(1); // Trim off the dot } // Look up the language // At the moment this only deals with code languages: cs, vb, etc., but in theory we could have MarkupLanguageServices which allow for // interesting combinations like: vbcss, csxml, etc. RazorCodeLanguage language = RazorCodeLanguage.GetLanguageByExtension(extension); return(language); }
public RazorHost(string fullPath, CodeDomProvider codeDomProvider = null, RazorCodeTransformer[] transformers = null, CodeGeneratorOptions codeGeneratorOptions = null) : base(RazorCodeLanguage.GetLanguageByExtension(".cshtml")) { if (fullPath == null) { throw new ArgumentNullException("fullPath"); } _transformers = transformers; _fullPath = fullPath; _codeDomProvider = codeDomProvider ?? new Microsoft.CSharp.CSharpCodeProvider(); base.DefaultNamespace = "ASP"; EnableLinePragmas = true; base.GeneratedClassContext = new GeneratedClassContext( executeMethodName: GeneratedClassContext.DefaultExecuteMethodName, writeMethodName: GeneratedClassContext.DefaultWriteMethodName, writeLiteralMethodName: GeneratedClassContext.DefaultWriteLiteralMethodName, writeToMethodName: "WriteTo", writeLiteralToMethodName: "WriteLiteralTo", templateTypeName: typeof(HelperResult).FullName, defineSectionMethodName: "DefineSection", beginContextMethodName: "BeginContext", endContextMethodName: "EndContext" ) { ResolveUrlMethodName = "Href" }; _codeGeneratorOptions = codeGeneratorOptions ?? new CodeGeneratorOptions() { // HACK: we use true, even though razor uses false, to work around a mono bug where it omits the // line ending after "#line hidden", resulting in the unparseable "#line hiddenpublic" BlankLinesBetweenMembers = true, BracingStyle = "C", // matches Razor built-in settings IndentString = String.Empty, }; }
public RazorViewComponentAssemblyCompilationResults CompileEmbeddedViews() { _compilationResultMessage = new RazorViewComponentAssemblyCompilationResults(); Initialize(); IEnumerable <string> embeddedRazorViewResourceNames = Assembly.GetManifestResourceNames().Where(ResourceIsRazorView).ToArray(); if (!embeddedRazorViewResourceNames.Any()) { Log.Debug("No embedded Razor views were found in this assembly."); return(_compilationResultMessage); } Log.Debug(() => string.Format("Found the following embedded Razor views: {0}", string.Join("\r\n", embeddedRazorViewResourceNames))); IEnumerable <IGrouping <RazorCodeLanguage, string> > resourcesGroupedByLanguage = from resourceName in embeddedRazorViewResourceNames let resourceInfo = new FileInfo(resourceName) let language = RazorCodeLanguage.GetLanguageByExtension(resourceInfo.Extension) group resourceName by language into groupedResources select groupedResources; var compiledAssemblies = CompileResourcesByLanguage(resourcesGroupedByLanguage); bool everythingCompiledSuccessfully = compiledAssemblies.All(x => !x.Errors.HasErrors); if (!everythingCompiledSuccessfully) { throw new RazorViewComponentAssemblyCompilationException(compiledAssemblies); } Log.Debug("Done!"); return(_compilationResultMessage); }
private static RazorCodeLanguage GetLanguageByExtension(string extension) { return(RazorCodeLanguage.GetLanguageByExtension(extension)); }
public RazorHtmlSpans(string html, string fileExtension) { codeLanguage = RazorCodeLanguage.GetLanguageByExtension(fileExtension); ReadHtmlSpans(html); }
public void GetServiceByExtensionReturnsEntryMatchingExtensionWithPreceedingDot() { Assert.IsType <CSharpRazorCodeLanguage>(RazorCodeLanguage.GetLanguageByExtension(".cshtml")); }
public RazorFoldableSpans(string markup, string fileExtension) { codeLanguage = RazorCodeLanguage.GetLanguageByExtension(fileExtension); ReadHtmlSpans(markup); ReadCodeSpans(markup); }
public RazorSpans(string markup, string fileExtension) { codeLanguage = RazorCodeLanguage.GetLanguageByExtension(fileExtension); ReadBlockSpans(markup); }
public void GetServiceByExtensionReturnsNullIfNoServiceForSpecifiedExtension() { Assert.IsNull(RazorCodeLanguage.GetLanguageByExtension("foobar")); }
public void GetServiceByExtensionReturnsEntryMatchingExtensionWithPreceedingDot() { Assert.IsInstanceOfType(RazorCodeLanguage.GetLanguageByExtension(".cshtml"), typeof(CSharpRazorCodeLanguage)); }