private IEnumerable <CompilerResults> CompileResourcesByLanguage(IEnumerable <IGrouping <RazorCodeLanguage, string> > resourcesGroupedByLanguage) { var compilerResults = new List <CompilerResults>(); foreach (var resourceNameGroup in resourcesGroupedByLanguage.ToArray()) { RazorCodeLanguage language = resourceNameGroup.Key; string languageDisplayName = language.GetType().Name; IEnumerable <string> resourceNames = resourceNameGroup; Log.Debug("Compiling {0} {1} resources", resourceNames.Count(), languageDisplayName); _compilationResultMessage.EmbeddedRazorViews.Add(languageDisplayName, resourceNames); var codeCompileUnits = GenerateCode(resourceNames).ToArray(); _compilationResultMessage.CodeCompileUnits.Add(languageDisplayName, codeCompileUnits); var compilerResult = CompileGeneratedCode(language, codeCompileUnits); compilerResults.Add(compilerResult); } _compilationResultMessage.CompilerResults = compilerResults; return(compilerResults); }
public RazorMachine( Type baseType = null, string rootOperatorPath = null, RazorCodeLanguage language = null, string defaultExtension = null, string autoIncludeName = null, string sharedLocation = null, bool?includeGeneratedSourceCode = null, bool?htmlEncode = null, IEnumerable <string> references = null, IEnumerable <string> namespaces = null, IEnumerable <Func <IContentProvider> > contentProviders = null, bool replaceReferences = false, bool replaceNamespaces = false, bool replaceContentProviders = false ) { Context = new RazorContext(new RazorConfig().InitializeIfSet( baseType, rootOperatorPath, language, defaultExtension, autoIncludeName, sharedLocation, includeGeneratedSourceCode, htmlEncode, references, namespaces, contentProviders, replaceReferences, replaceNamespaces, replaceContentProviders )); }
protected CompilerServiceBase(RazorCodeLanguage codeLanguage, ParserBaseCreator markupParserFactory) { this.CodeLanguage = codeLanguage; this.MarkupParserFactory = markupParserFactory ?? new ParserBaseCreator(null); this.ReferenceResolver = new UseCurrentAssembliesReferenceResolver(); AppDomain.CurrentDomain.AssemblyResolve += this.CurrentDomain_AssemblyResolve; }
public OpenRastaRazorHost(RazorCodeLanguage codeLanguage) { NamespaceImports.Add("System"); NamespaceImports.Add("System.Collections.Generic"); NamespaceImports.Add("System.IO"); NamespaceImports.Add("System.Linq"); NamespaceImports.Add("System.Net"); NamespaceImports.Add("System.Web"); //NamespaceImports.Add("System.Web.Helpers"); NamespaceImports.Add("System.Web.Security"); NamespaceImports.Add("System.Web.UI"); NamespaceImports.Add("System.Web.WebPages"); DefaultNamespace = WebDefaultNamespace; GeneratedClassContext = new GeneratedClassContext(GeneratedClassContext.DefaultExecuteMethodName, GeneratedClassContext.DefaultWriteMethodName, GeneratedClassContext.DefaultWriteLiteralMethodName, WriteToMethodName, WriteLiteralToMethodName, TemplateTypeName, DefineSectionMethodName); DefaultBaseClass = typeof(RazorViewBase <>).AssemblyQualifiedName; DefaultDebugCompilation = true; CodeLanguage = codeLanguage; }
/// <summary> /// Initialises a new instance of <see cref="CompilerServiceBase"/> /// </summary> /// <param name="codeLanguage">The code language.</param> /// <param name="markupParserFactory">The markup parser factory.</param> protected CompilerServiceBase(RazorCodeLanguage codeLanguage, Func <MarkupParser> markupParserFactory) { Contract.Requires(codeLanguage != null); CodeLanguage = codeLanguage; MarkupParserFactory = markupParserFactory ?? (() => new HtmlMarkupParser()); }
protected RazorCodeLanguage GetCodeLanguage(string resourceName) { var extension = new FileInfo(resourceName).Extension; var language = RazorCodeLanguage.GetLanguageByExtension(extension); return(language); }
protected CompilerServiceBase(RazorCodeLanguage codeLanguage, ParserBaseCreator markupParserFactory) { Contract.Requires(codeLanguage != null); CodeLanguage = codeLanguage; MarkupParserFactory = markupParserFactory ?? new ParserBaseCreator(null); ReferenceResolver = new UseCurrentAssembliesReferenceResolver(); }
public SimpleRazorBuildProvider() { this._codeLanguage = new CSharpRazorCodeLanguage(); this._compilerType = GetDefaultCompilerTypeForLanguage(this._codeLanguage.LanguageName); this._host = new SimpleRazorEngineHost(this._codeLanguage); this._virtualPathDependencies = null; this._typeName = string.Format(CultureInfo.InvariantCulture, "{0}.{1}", this._host.DefaultNamespace, "Foot"); }
/// <summary> /// Initialises a new instance of <see cref="CompilerServiceBase"/> /// </summary> /// <param name="codeLanguage">The code language.</param> /// <param name="markupParserFactory">The markup parser factory.</param> protected CompilerServiceBase(RazorCodeLanguage codeLanguage, Func <ParserBase> markupParserFactory) { Contract.Requires(codeLanguage != null); CodeLanguage = codeLanguage; MarkupParserFactory = markupParserFactory ?? (() => new HtmlMarkupParser()); ReferenceResolver = new UseCurrentAssembliesReferenceResolver(); }
protected DirectCompilerServiceBase( RazorCodeLanguage codeLanguage, CodeDomProvider codeDomProvider, Func <ParserBase> markupParserFactory) : base(codeLanguage, new ParserBaseCreator(markupParserFactory)) { this.codeDomProvider = codeDomProvider; }
/// <summary> /// Initializes a new instance of the <see cref="NancyRazorEngineHost"/> class. /// </summary> /// <param name="language">The language.</param> public NancyRazorEngineHost(RazorCodeLanguage language) : base(language) { this.DefaultBaseClass = typeof(NancyRazorViewBase).FullName; this.DefaultNamespace = "RazorOutput"; this.DefaultClassName = "RazorView"; this.GeneratedClassContext = new GeneratedClassContext("Execute", "Write", "WriteLiteral", null, null, null, "DefineSection"); }
protected TemplateCompilationParameters(RazorCodeLanguage language, CodeDomProvider codeProvider, CompilerParameters compilerParameters = null) { Language = language; CodeProvider = codeProvider; CompilerParameters = compilerParameters ?? new CompilerParameters { GenerateInMemory = true }; AddAssemblyReference(typeof(TemplateBase)); }
public RazorPadMvcEngineHost(RazorCodeLanguage language = null) : base("~/WebPage.cshtml", null) { // ReSharper disable DoNotCallOverridableMethodsInConstructor DefaultClassName = "WebPage"; DefaultNamespace = "RazorPad"; CodeLanguage = language ?? CodeLanguage; // ReSharper restore DoNotCallOverridableMethodsInConstructor }
/// <summary> /// Initialises a new instance of <see cref="DirectCompilerServiceBase"/>. /// </summary> /// <param name="codeLanguage">The razor code language.</param> /// <param name="codeDomProvider">The code dom provider used to generate code.</param> /// <param name="markupParser">The markup parser.</param> protected DirectCompilerServiceBase(RazorCodeLanguage codeLanguage, CodeDomProvider codeDomProvider, MarkupParser markupParser) : base(codeLanguage, markupParser) { if (codeDomProvider == null) { throw new ArgumentNullException("codeDomProvider"); } CodeDomProvider = codeDomProvider; }
/// <summary> /// Initialises a new instance of <see cref="CompilerServiceBase"/> /// </summary> /// <param name="codeLanguage">The code language.</param> /// <param name="markupParser">The markup parser.</param> protected CompilerServiceBase(RazorCodeLanguage codeLanguage, MarkupParser markupParser) { if (codeLanguage == null) { throw new ArgumentNullException("codeLanguage"); } CodeLanguage = codeLanguage; MarkupParser = markupParser ?? new HtmlMarkupParser(); }
protected virtual CodeDomProvider GetCodeProvider(RazorCodeLanguage language) { if (language is VBRazorCodeLanguage) { return(new VBCodeProvider()); } else { return(new CSharpCodeProvider()); } }
public void MultipleCallsToGetServiceWithSameExtensionReturnSameObject() { // Arrange RazorCodeLanguage expected = RazorCodeLanguage.GetLanguageByExtension("cshtml"); // Act RazorCodeLanguage actual = RazorCodeLanguage.GetLanguageByExtension("cshtml"); // Assert Assert.AreSame(expected, actual); }
/// <summary> /// Initializes a new instance of the <see cref="RazorEngineHost"/> class. /// </summary> /// <param name="language">The language.</param> public RazorEngineHost(RazorCodeLanguage language) : base(language) { this.DefaultBaseClass = typeof(RazorViewPage).FullName; this.DefaultNamespace = "RazorOutput"; this.DefaultClassName = "RazorView"; var context = new GeneratedClassContext("Execute", "Write", "WriteLiteral", "WriteTo", "WriteLiteralTo", null, "DefineSection"); context.ResolveUrlMethodName = "ResolveUrl"; this.GeneratedClassContext = context; }
protected CompilerServiceBase( CodeDomProvider codeDomProvider, RazorCodeLanguage codeLanguage) { if (codeLanguage == null) { throw new ArgumentNullException("codeLanguage"); } CodeDomProvider = codeDomProvider; CodeLanguage = codeLanguage; }
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); } }
internal RazorConfig InitializeIfSet( Type baseType = null, string rootOperatorPath = null, RazorCodeLanguage language = null, string defaultExtension = null, string autoIncludeNameWithoutExtension = null, string sharedLocation = null, bool?includeGeneratedSourceCode = null, bool?htmlEncode = null, IEnumerable <string> references = null, IEnumerable <string> namespaces = null, IEnumerable <Func <IContentProvider> > contentProviders = null, bool replaceReferences = false, bool replaceNamespaces = false, bool replaceContentProviders = false ) { InitializeDefault(); RootOperator.Path = rootOperatorPath ?? RootOperator.Path; Templates.BaseType = baseType ?? Templates.BaseType; Templates.Language = language ?? Templates.Language; Templates.DefaultExtension = (defaultExtension ?? Templates.DefaultExtension).EmptyAsNull(); Templates.AutoIncludeName = (autoIncludeNameWithoutExtension ?? Templates.AutoIncludeName).EmptyAsNull(); Templates.SharedLocation = (sharedLocation ?? Templates.SharedLocation).EmptyAsNull(); if (includeGeneratedSourceCode != null) { Templates.IncludeGeneratedSourceCode = includeGeneratedSourceCode.Value; } if (htmlEncode != null) { Templates.HtmlEncode = htmlEncode.Value; } if (references != null) { References = replaceReferences ? references.ToList().AsReadOnly() : References.Union(references, StringComparer.InvariantCultureIgnoreCase).ToList().AsReadOnly(); TryResolveWildcardReferences(); } if (namespaces != null) { Namespaces = replaceNamespaces ? namespaces.ToList().AsReadOnly() : Namespaces.Union(namespaces).ToList().AsReadOnly(); } if (contentProviders != null) { ContentProviders = replaceContentProviders ? contentProviders.ToList().AsReadOnly() : ContentProviders.Union(contentProviders).ToList().AsReadOnly(); } return(this); }
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); } }
public RazorPadHost(RazorCodeLanguage language = null) { // ReSharper disable DoNotCallOverridableMethodsInConstructor DefaultBaseClass = typeof(TemplateBase).FullName; DefaultClassName = "CompiledTemplate"; DefaultNamespace = "RazorPad.Runtime"; CodeLanguage = language; GeneratedClassContext = new GeneratedClassContext( GeneratedClassContext.DefaultExecuteMethodName, GeneratedClassContext.DefaultWriteMethodName, GeneratedClassContext.DefaultWriteLiteralMethodName, "WriteTo", "WriteLiteralTo", typeof(HelperResult).FullName); // ReSharper restore DoNotCallOverridableMethodsInConstructor }
/// <summary> /// Initializes a new instance of the <see cref="NancyRazorEngineHost"/> class. /// </summary> public NancyRazorEngineHost(RazorCodeLanguage language, RazorAssemblyProvider razorAssemblyProvider) : base(language) { this.razorAssemblyProvider = razorAssemblyProvider; this.DefaultBaseClass = typeof(NancyRazorViewBase).FullName; this.DefaultNamespace = "RazorOutput"; this.DefaultClassName = "RazorView"; var context = new GeneratedClassContext("Execute", "Write", "WriteLiteral", "WriteTo", "WriteLiteralTo", typeof(HelperResult).FullName, "DefineSection"); context.ResolveUrlMethodName = "ResolveUrl"; this.GeneratedClassContext = context; }
private RazorCodeLanguage GetCodeLanguage() { RazorCodeLanguage language = DetermineCodeLanguage(VirtualPath); if (language == null && !String.IsNullOrEmpty(PhysicalPath)) { language = DetermineCodeLanguage(PhysicalPath); } if (language == null) { throw new InvalidOperationException(String.Format(CultureInfo.CurrentCulture, "Could not determine the code language for '{0}'", VirtualPath)); } return(language); }
protected virtual RazorCodeLanguage GetCodeLanguage() { RazorCodeLanguage language = DetermineCodeLanguage(VirtualPath); if (language == null && !String.IsNullOrEmpty(PhysicalPath)) { language = DetermineCodeLanguage(PhysicalPath); } if (language == null) { throw new InvalidOperationException(String.Format(CultureInfo.CurrentCulture, RazorWebResources.BuildProvider_No_CodeLanguageService_For_Path, VirtualPath)); } return(language); }
private static RazorTemplateEngine CreateRazorEngine <T>(RazorCodeLanguage codeLanguage) { var host = new TemplateRazorEngineHost(codeLanguage) { // todo: should be generic template type that is passed in. DefaultBaseClass = typeof(T).FullName, DefaultNamespace = NamespaceName }; host.NamespaceImports.Add("System"); host.NamespaceImports.Add("System.Collections"); host.NamespaceImports.Add("System.Collections.Generic"); host.NamespaceImports.Add("System.Dynamic"); host.NamespaceImports.Add("System.Linq"); return(new RazorTemplateEngine(host)); }
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); } }
protected DirectCompilerServiceBase(RazorCodeLanguage codeLanguage, CodeDomProvider codeDomProvider, Func<ParserBase> markupParserFactory) : base(codeLanguage, new ParserBaseCreator(markupParserFactory)) { _codeDomProvider = codeDomProvider; }
/// <summary> /// Initialises a new instance of <see cref="RazorEngineHost"/>. /// </summary> /// <param name="language">The code language.</param> /// <param name="markupParserFactory">The markup parser factory delegate.</param> public RazorEngineHost(RazorCodeLanguage language, Func<ParserBase> markupParserFactory) : base(language, markupParserFactory) { }
public CodeGenTestHost(RazorCodeLanguage language) : base(language) { }