private BackgroundParseTask(RazorTemplateEngine engine, string sourceFileName, TextChange change) { Change = change; Engine = engine; SourceFileName = sourceFileName; InnerTask = new Task(() => Run(_cancelSource.Token), _cancelSource.Token); }
public void ConstructorInitializesHost() { // Arrange RazorEngineHost host = new RazorEngineHost(new CSharpRazorCodeLanguage()); // Act RazorTemplateEngine engine = new RazorTemplateEngine(host); // Assert Assert.AreSame(host, engine.Host); }
public void CreateParserMethodSetsParserContextToDesignTimeModeIfHostSetToDesignTimeMode() { // Arrange RazorEngineHost host = CreateHost(); RazorTemplateEngine engine = new RazorTemplateEngine(host); host.DesignTimeMode = true; // Act RazorParser parser = engine.CreateParser(); // Assert Assert.IsTrue(parser.DesignTimeMode); }
public void CreateParserMethodIsConstructedFromHost() { // Arrange RazorEngineHost host = CreateHost(); RazorTemplateEngine engine = new RazorTemplateEngine(host); // Act RazorParser parser = engine.CreateParser(); // Assert Assert.IsInstanceOfType(parser.CodeParser, typeof(CSharpCodeParser)); Assert.IsInstanceOfType(parser.MarkupParser, typeof(HtmlMarkupParser)); }
public void CreateParserMethodSetsParserContextToDesignTimeModeIfHostSetToDesignTimeMode() { // Arrange var host = CreateHost(); var engine = new RazorTemplateEngine(host); host.DesignTimeMode = true; // Act var parser = engine.CreateParser("some-file"); // Assert Assert.True(parser.DesignTimeMode); }
public void CreateParserMethodIsConstructedFromHost() { // Arrange var host = CreateHost(); var engine = new RazorTemplateEngine(host); // Act var parser = engine.CreateParser("some-file"); // Assert Assert.IsType<CSharpCodeParser>(parser.CodeParser); Assert.IsType<HtmlMarkupParser>(parser.MarkupParser); }
public void CreateChunkGeneratorMethodPassesChunkGeneratorThroughDecorateMethodOnHost() { // Arrange var mockHost = new Mock<RazorEngineHost>(new CSharpRazorCodeLanguage()) { CallBase = true }; var expected = new Mock<RazorChunkGenerator>("Foo", "Bar", "Baz", mockHost.Object).Object; mockHost.Setup(h => h.DecorateChunkGenerator(It.IsAny<RazorChunkGenerator>())) .Returns(expected); var engine = new RazorTemplateEngine(mockHost.Object); // Act var actual = engine.CreateChunkGenerator("Foo", "Bar", "Baz"); // Assert Assert.Equal(expected, actual); }
public void CreateParserMethodPassesParsersThroughDecoratorMethodsOnHost() { // Arrange CodeParser expectedCode = new Mock<CodeParser>().Object; MarkupParser expectedMarkup = new Mock<MarkupParser>().Object; var mockHost = new Mock<RazorEngineHost>(new CSharpRazorCodeLanguage()) { CallBase = true }; mockHost.Setup(h => h.DecorateCodeParser(It.IsAny<CSharpCodeParser>())) .Returns(expectedCode); mockHost.Setup(h => h.DecorateMarkupParser(It.IsAny<HtmlMarkupParser>())) .Returns(expectedMarkup); RazorTemplateEngine engine = new RazorTemplateEngine(mockHost.Object); // Act RazorParser actual = engine.CreateParser(); // Assert Assert.AreEqual(expectedCode, actual.CodeParser); Assert.AreEqual(expectedMarkup, actual.MarkupParser); }
private GeneratorResults ParseChange(ITextBuffer buffer, CancellationToken token) { EnsureOnThread(); // Create a template engine RazorTemplateEngine engine = new RazorTemplateEngine(_host); // Seek the buffer to the beginning buffer.Position = 0; try { return(engine.GenerateCode( input: buffer, className: null, rootNamespace: null, sourceFileName: _fileName, cancelToken: token)); } catch (OperationCanceledException) { return(null); } }
public void GetChangeToken_WatchesAllCshtmlFilesUnderSpecifiedRootDirectory(string rootDirectory) { // Arrange var fileProvider = new Mock <IFileProvider>(); fileProvider.Setup(f => f.Watch(It.IsAny <string>())) .Returns(Mock.Of <IChangeToken>()); var accessor = Mock.Of <IRazorViewEngineFileProviderAccessor>(a => a.FileProvider == fileProvider.Object); var templateEngine = new RazorTemplateEngine( RazorEngine.Create(), new FileProviderRazorProjectFileSystem(accessor, _hostingEnvironment)); var options = Options.Create(new RazorPagesOptions()); options.Value.RootDirectory = rootDirectory; var changeProvider = new PageActionDescriptorChangeProvider(templateEngine, accessor, options); // Act var changeToken = changeProvider.GetChangeToken(); // Assert fileProvider.Verify(f => f.Watch("/pages-base-dir/**/*.cshtml")); }
public void GetChangeToken_WatchesViewImportsOutsidePagesRoot_WhenAreaFeatureIsDisabled() { // Arrange var fileProvider = new TestFileProvider(); var accessor = Mock.Of <IRazorViewEngineFileProviderAccessor>(a => a.FileProvider == fileProvider); var templateEngine = new RazorTemplateEngine( RazorEngine.Create(), new FileProviderRazorProjectFileSystem(accessor, _hostingEnvironment)); templateEngine.Options.ImportsFileName = "_ViewImports.cshtml"; var options = Options.Create(new RazorPagesOptions { AllowAreas = false }); var changeProvider = new PageActionDescriptorChangeProvider(templateEngine, accessor, options); // Act & Assert var compositeChangeToken = Assert.IsType <CompositeChangeToken>(changeProvider.GetChangeToken()); Assert.Collection(compositeChangeToken.ChangeTokens, changeToken => Assert.Same(fileProvider.GetChangeToken("/_ViewImports.cshtml"), changeToken), changeToken => Assert.Same(fileProvider.GetChangeToken("/Pages/**/*.cshtml"), changeToken)); }
public Type PrepareView(TextReader viewText, string viewFileName) { var currrentCount = Interlocked.Increment(ref _count); var className = "_view" + currrentCount.ToString(CultureInfo.InvariantCulture); RazorTemplateEngine razor = new RazorTemplateEngine(_host); var parseResult = razor.GenerateCode(viewText, className, "MiniMVC._generated", viewFileName); if (!parseResult.Success) { throw new ViewCompilerException(parseResult.ParserErrors, viewFileName); } var codeProvider = new CSharpCodeProvider(); var compilerParams = new CompilerParameters(new string[] { typeof(Tuple).Assembly.Location, typeof(Engine).Assembly.Location, typeof(Microsoft.CSharp.RuntimeBinder.RuntimeBinderException).Assembly.Location, typeof(System.Runtime.CompilerServices.CallSite).Assembly.Location, }.Concat(References).ToArray()); compilerParams.GenerateInMemory = true; var code = new StringWriter(); codeProvider.GenerateCodeFromCompileUnit(parseResult.GeneratedCode, code, new CodeGeneratorOptions()); System.Diagnostics.Debug.Write(code.ToString()); var compileResult = codeProvider.CompileAssemblyFromDom(compilerParams, parseResult.GeneratedCode); if (compileResult.Errors.HasErrors) { throw new ViewCompilerException(compileResult.Errors, viewFileName); } return(compileResult.CompiledAssembly.GetType("MiniMVC._generated." + className)); }
public async Task RenderView_WithServiceInjection() { // Arrange var model = new ExampleModel() { PlainText = "Lorem Ipsium", HtmlContent = "<em>Lorem Ipsium</em>" }; // Add dependencies to the service collection and add razor templating to the collection var services = new ServiceCollection(); services.AddTransient <ExampleService>(); // Add after registering all dependencies // this is important for the razor template engine to find the injected services services.AddRazorTemplating(); // Act var html = await RazorTemplateEngine.RenderAsync("~/Views/ExampleViewServiceInjection.cshtml"); // Assert Assert.IsNotNull(html); Assert.IsTrue(html.Contains("Injected Service Data: Some Random Value - ")); }
public static BackgroundParseTask StartNew(RazorTemplateEngine engine, string sourceFileName, TextChange change) { BackgroundParseTask task = new BackgroundParseTask(engine, sourceFileName, change); task.Start(); return task; }
public void CreateCodeGenerator_PassesChunkGeneratorThroughDecorateMethodOnHost() { // Arrange var mockHost = new Mock<RazorEngineHost>(new CSharpRazorCodeLanguage()) { CallBase = true }; var codeGeneratorContext = new CodeGeneratorContext( mockHost.Object, "different-class", "different-ns", string.Empty, shouldGenerateLinePragmas: true, errorSink: new ErrorSink()); var expected = new CSharpCodeGenerator(codeGeneratorContext); mockHost.Setup(h => h.DecorateCodeGenerator(It.IsAny<CSharpCodeGenerator>(), codeGeneratorContext)) .Returns(expected); var engine = new RazorTemplateEngine(mockHost.Object); // Act var actual = engine.CreateCodeGenerator(codeGeneratorContext); // Assert Assert.Equal(expected, actual); }
public void GenerateOutputsResultsOfParsingAndGeneration() { // Arrange var engine = new RazorTemplateEngine(CreateHost()); // Act var results = engine.GenerateCode(new StringTextBuffer("foo @bar(")); // Assert Assert.False(results.Success); Assert.Single(results.ParserErrors); Assert.NotNull(results.Document); Assert.NotNull(results.GeneratedCode); }
public void GenerateOutputsDesignTimeMappingsIfDesignTimeSetOnHost() { // Arrange RazorTemplateEngine engine = new RazorTemplateEngine(CreateHost(designTime: true)); // Act GeneratorResults results = engine.GenerateCode(new StringTextBuffer("foo @bar()"), className: null, rootNamespace: null, sourceFileName: "foo.cshtml"); // Assert Assert.IsTrue(results.Success); Assert.AreEqual(0, results.ParserErrors.Count); Assert.IsNotNull(results.Document); Assert.IsNotNull(results.GeneratedCode); Assert.IsNotNull(results.DesignTimeLineMappings); }
public static void Setup(TestContext context) { //Optionally call this to create cache of the renderer //Otherwise, render time will be more than usual on first time only RazorTemplateEngine.Initialize(); }
private Type compile(Stream stream, Type base_type) { var key = "c" + Guid.NewGuid().ToString("N"); var parser = new HtmlMarkupParser(); var host = new RazorEngineHost(new CSharpRazorCodeLanguage(), () => parser) { DefaultBaseClass = base_type.FullName, DefaultClassName = key, DefaultNamespace = "Skight.Arch.Presentation.Web.Core.ViewEngins.Razor.dynamic", GeneratedClassContext = new GeneratedClassContext("Execute", "Write", "WriteLiteral", "WriteTo", "WriteLiteralTo", "tinyweb.viewengine.razor.RazorCompiler.TemplateBase") }; //always include this one host.NamespaceImports.Add("Skight.Arch.Presentation.Web.Core.ViewEngins"); host.NamespaceImports.Add("System"); //read web.config pages/namespaces if (File.Exists("\\web.config")) { var config = WebConfigurationManager.OpenWebConfiguration("\\web.config"); var pages = config.GetSection("system.web/pages"); if (pages != null) { PagesSection pageSection = (PagesSection)pages; for (int i = 0; i < pageSection.Namespaces.Count; i++) { //this automatically ignores namespaces already added host.NamespaceImports.Add(pageSection.Namespaces[i].Namespace); } } } CodeCompileUnit code; using (var reader = new StreamReader(stream)) { var generatedCode = new RazorTemplateEngine(host).GenerateCode(reader); code = generatedCode.GeneratedCode; } var @params = new CompilerParameters { IncludeDebugInformation = false, TempFiles = new TempFileCollection(AppDomain.CurrentDomain.DynamicDirectory), CompilerOptions = "/target:library /optimize", GenerateInMemory = false }; var assemblies = AppDomain.CurrentDomain .GetAssemblies() .Where(a => !a.IsDynamic) .Select(a => a.Location) .ToArray(); @params.ReferencedAssemblies.AddRange(assemblies); var provider = new CSharpCodeProvider(); var compiled = provider.CompileAssemblyFromDom(@params, code); if (compiled.Errors.Count > 0) { var compileErrors = string.Join("\r\n", compiled.Errors.Cast <object>().Select(o => o.ToString())); throw new ApplicationException("Failed to compile Razor:" + compileErrors); } return(compiled.CompiledAssembly.GetType("Skight.Arch.Presentation.Web.Core.ViewEngins.Razor.dynamic." + key)); }
public void ParseTemplateOutputsResultsOfParsingProvidedTemplateSource() { // Arrange RazorTemplateEngine engine = new RazorTemplateEngine(CreateHost()); // Act ParserResults results = engine.ParseTemplate(new StringTextBuffer("foo @bar(")); // Assert Assert.IsFalse(results.Success); Assert.AreEqual(1, results.ParserErrors.Count); Assert.IsNotNull(results.Document); }
public void ParseTemplateOutputsResultsOfParsingProvidedTemplateSource() { // Arrange var engine = new RazorTemplateEngine(CreateHost()); // Act var results = engine.ParseTemplate(new StringTextBuffer("foo @bar(")); // Assert Assert.False(results.Success); Assert.Single(results.ParserErrors); Assert.NotNull(results.Document); }
private string GetGeneratorResult(RazorEngineHost host, TypeContext context) { var engine = new RazorTemplateEngine(host); GeneratorResults result; using (var reader = context.TemplateContent.GetTemplateReader()) result = engine.GenerateCode(reader, null, null, context.TemplateContent.TemplateFile); return InspectSource(result, context); }
/// <summary>Initializes a new instance of the <see cref="RazorTemplater" /> class.</summary> /// <param name="templateAssemblyPath">The template assembly path. This is the path where the generated templates are stored/cached. /// If shadow copy is enabled this path will be ignored and the shadow copy path will be used.</param> /// <param name="renderTimeout">The render timeout. This is the time in ms a template is allowed to render itself.</param> /// <param name="templateNamespace">The template namespace.</param> /// <param name="allowedDirectories">The directories the templates are allowed to read from.</param> /// <param name="baseType">Type of the template base class. Defaults to <see cref="TemplateBase" />.</param> /// <param name="defaultNamespaces">The default namespaces. Defaults to "System", "System.Collections.Generic", "System.Linq" and "System.Text".</param> /// <param name="forbiddenTypes">The forbidden types (FQDN). Defaults to "Task", "Thread", "System.Activator" and "System.Reflection.Assembly".</param> /// <param name="language">The language. Defaults to C#.</param> /// <param name="sponsor">The sponsor to keep the object alive.</param> /// <param name="persistTemplates">If set to <c>true</c> the generated templates are persisted over multiple application runs. Otherwise they are deleted when disposing.</param> public RazorTemplater(string templateAssemblyPath, int renderTimeout = 5000, string templateNamespace = "IsolatedRazor.RazorTemplate", List <string> allowedDirectories = null, Type baseType = null, List <string> defaultNamespaces = null, List <string> forbiddenTypes = null, RazorCodeLanguage language = null, ClientSponsor sponsor = null, bool persistTemplates = false) { RenderTimeout = renderTimeout; this.templateNamespace = templateNamespace; this.persistTemplates = persistTemplates; DefaultNamespaces = defaultNamespaces ?? new List <string>() { "System", "System.Collections.Generic", "System.Net", "System.Linq", "System.Text", "IsolatedRazor" }; ForbiddenTypes = forbiddenTypes ?? new List <string>() { "System.Threading.Tasks.Task", "System.Threading.Tasks.Task`1", "System.Threading.Thread", "System.Activator", "System.Reflection.Assembly" }; clientSponsor = sponsor ?? new ClientSponsor(TimeSpan.FromMinutes(1)); defaultBaseClass = (baseType ?? typeof(TemplateBase)).FullName; var host = new RazorEngineHost(language ?? new CSharpRazorCodeLanguage()) { DefaultNamespace = templateNamespace }; DefaultNamespaces.ForEach(n => host.NamespaceImports.Add(n)); engine = new RazorTemplateEngine(host); provider = host.CodeLanguage.LanguageName == "vb" ? (CodeDomProvider) new VBCodeProvider() : new CSharpCodeProvider(); adSetup = new AppDomainSetup(); if (AppDomain.CurrentDomain.SetupInformation.ShadowCopyFiles == "true") { isShadowCopied = true; templatePath = Path.Combine(AppDomain.CurrentDomain.SetupInformation.CachePath, AppDomain.CurrentDomain.SetupInformation.ApplicationName); var shadowCopyDir = Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location); if (shadowCopyDir.Contains("assembly")) { shadowCopyDir = shadowCopyDir.Substring(0, shadowCopyDir.LastIndexOf("assembly")); } var privatePaths = new List <string>(); foreach (var assemblyLocation in AppDomain.CurrentDomain.GetAssemblies().Where(a => !a.IsDynamic && a.Location.StartsWith(shadowCopyDir)).Select(a => a.Location)) { privatePaths.Add(Path.GetDirectoryName(assemblyLocation)); } adSetup.ApplicationBase = shadowCopyDir; adSetup.PrivateBinPath = String.Join(";", privatePaths); } else { isShadowCopied = false; templatePath = templateAssemblyPath; adSetup.ApplicationBase = AppDomain.CurrentDomain.SetupInformation.ApplicationBase; adSetup.PrivateBinPath = AppDomain.CurrentDomain.SetupInformation.PrivateBinPath; } var resolver = new DefaultAssemblyResolver(); resolver.AddSearchDirectory(Path.GetDirectoryName(adSetup.ApplicationBase)); readerParameters = new ReaderParameters() { AssemblyResolver = resolver }; if (templateCache == null) { var path = Path.Combine(templatePath, TEMPLATE_CACHE_FILE); if (persistTemplates && File.Exists(path)) { using (var filestream = File.Open(path, FileMode.Open)) { var formatter = new BinaryFormatter(); templateCache = (TemplateCache)formatter.Deserialize(filestream); } } else { templateCache = new TemplateCache(); } } Directory.CreateDirectory(templatePath); permissionSet = new PermissionSet(PermissionState.None); permissionSet.AddPermission(new SecurityPermission(SecurityPermissionFlag.Execution)); // run the code permissionSet.AddPermission(new SecurityPermission(SecurityPermissionFlag.RemotingConfiguration)); // remoting lifetime (sponsor) permissionSet.AddPermission(new FileIOPermission(FileIOPermissionAccess.Read, templatePath)); // read templates permissionSet.AddPermission(new ReflectionPermission(ReflectionPermissionFlag.RestrictedMemberAccess)); // support dynamic if (allowedDirectories != null) { allowedDirectories.ForEach(dir => permissionSet.AddPermission(new FileIOPermission(FileIOPermissionAccess.Read, dir))); } RecycleAppDomain(); }
/// <summary> /// Function that builds the contents of the generated file based on the contents of the input file /// </summary> /// <param name="inputFileContent">Content of the input file</param> /// <returns>Generated file as a byte array</returns> protected override byte[] GenerateCode(string inputFileContent) { var references = GetVSProject().References; //add reference to our buildprovider and virtualpathprovider var buildprovAssembly = typeof(CompiledVirtualPathProvider).Assembly; if (references.Find(buildprovAssembly.GetName().Name) == null) { references.Add(buildprovAssembly.Location); } // Get the root folder of the project var appRoot = Path.GetDirectoryName(GetProject().FullName); // Determine the project-relative path string projectRelativePath = InputFilePath.Substring(appRoot.Length); // Turn it into a virtual path by prepending ~ and fixing it up string virtualPath = VirtualPathUtility.ToAppRelative("~" + projectRelativePath); var vdm = new VirtualDirectoryMapping(appRoot, true); var wcfm = new WebConfigurationFileMap(); wcfm.VirtualDirectories.Add("/", vdm); var config = WebConfigurationManager.OpenMappedWebConfiguration(wcfm, projectRelativePath); //System.Configuration.ConfigurationManager.OpenExeConfiguration(configFile); var sectGroup = new RazorWebSectionGroup { Host = (HostSection)config.GetSection(HostSection.SectionName) ?? new HostSection { FactoryType = typeof(MvcWebRazorHostFactory).AssemblyQualifiedName }, Pages = (RazorPagesSection)config.GetSection(RazorPagesSection.SectionName) }; // Create the same type of Razor host that's used to process Razor files in App_Code var host = IsHelper ? new WebCodeRazorHost(virtualPath, InputFilePath) : WebRazorHostFactory.CreateHostFromConfig(sectGroup, virtualPath, InputFilePath); // Set the namespace to be the same as what's used by default for regular .cs files host.DefaultNamespace = FileNameSpace; host.NamespaceImports.Remove("WebMatrix.Data"); host.NamespaceImports.Remove("WebMatrix.WebData"); var systemWebPages = config.GetSection("system.web/pages") as PagesSection; if (systemWebPages != null) { foreach (NamespaceInfo ns in systemWebPages.Namespaces) { if (!host.NamespaceImports.Contains(ns.Namespace)) { host.NamespaceImports.Add(ns.Namespace); } } } var compilationSection = config.GetSection("system.web/compilation") as CompilationSection; if (compilationSection != null) { foreach (AssemblyInfo assembly in compilationSection.Assemblies) { if (assembly.Assembly != "*" && references.Find(assembly.Assembly) == null) { references.Add(assembly.Assembly); } } } // Create a Razor engine and pass it our host var engine = new RazorTemplateEngine(host); // Generate code GeneratorResults results = null; try { using (TextReader reader = new StringReader(inputFileContent)) { results = engine.GenerateCode(reader, null, null, InputFilePath); } } catch (Exception e) { this.GeneratorError(4, e.ToString(), 1, 1); //Returning null signifies that generation has failed return(null); } // Output errors foreach (RazorError error in results.ParserErrors) { GeneratorError(4, error.Message, (uint)error.Location.LineIndex + 1, (uint)error.Location.CharacterIndex + 1); } CodeDomProvider provider = GetCodeProvider(); try { if (this.CodeGeneratorProgress != null) { //Report that we are 1/2 done this.CodeGeneratorProgress.Progress(50, 100); } using (StringWriter writer = new StringWriter(new StringBuilder())) { CodeGeneratorOptions options = new CodeGeneratorOptions(); options.BlankLinesBetweenMembers = false; options.BracingStyle = "C"; // Add a GeneratedCode attribute to the generated class CodeCompileUnit generatedCode = results.GeneratedCode; var ns = generatedCode.Namespaces[0]; CodeTypeDeclaration generatedType = ns.Types[0]; generatedType.CustomAttributes.Add( new CodeAttributeDeclaration( new CodeTypeReference(typeof(GeneratedCodeAttribute)), new CodeAttributeArgument(new CodePrimitiveExpression("MvcRazorClassGenerator")), new CodeAttributeArgument(new CodePrimitiveExpression("1.0")))); if (!IsHelper) { generatedType.CustomAttributes.Add( new CodeAttributeDeclaration( new CodeTypeReference(typeof(PageVirtualPathAttribute)), new CodeAttributeArgument(new CodePrimitiveExpression(virtualPath)))); } //Generate the code provider.GenerateCodeFromCompileUnit(generatedCode, writer, options); if (this.CodeGeneratorProgress != null) { //Report that we are done this.CodeGeneratorProgress.Progress(100, 100); } writer.Flush(); // Save as UTF8 Encoding enc = Encoding.UTF8; //Get the preamble (byte-order mark) for our encoding byte[] preamble = enc.GetPreamble(); int preambleLength = preamble.Length; //Convert the writer contents to a byte array byte[] body = enc.GetBytes(writer.ToString()); //Prepend the preamble to body (store result in resized preamble array) Array.Resize <byte>(ref preamble, preambleLength + body.Length); Array.Copy(body, 0, preamble, preambleLength, body.Length); //Return the combined byte array return(preamble); } } catch (Exception e) { this.GeneratorError(4, e.ToString(), 1, 1); //Returning null signifies that generation has failed return(null); } }
public CustomTemplateBase Generate(string defaultClassName, string defaultNamespace, TextReader reader, IEnumerable <string> additionalDlls) { var defaultBaseClass = "TemplateEngine.CustomTemplateBase"; //CREATE THE HOST var language = new CSharpRazorCodeLanguage(); var host = new RazorEngineHost(language) { DefaultBaseClass = defaultBaseClass, DefaultClassName = defaultClassName, DefaultNamespace = defaultNamespace, }; 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"); //CREATE THE ENGINE var engine = new RazorTemplateEngine(host); //Generate the code var razorResult = engine.GenerateCode(reader); var compileParameters = new CompilerParameters(); var dlls = new List <string> { "mscorlib.dll", "system.dll", "system.core.dll", "microsoft.csharp.dll", "TemplateEngine.dll" }; dlls.AddRange(additionalDlls); foreach (var reference in dlls) { compileParameters.ReferencedAssemblies.Add(reference); } //Compile it var compilerResults = new CSharpCodeProvider() .CompileAssemblyFromDom( compileParameters, razorResult.GeneratedCode ); foreach (var error in compilerResults.Errors) { Console.WriteLine("Error: {0}", error); } var template = (CustomTemplateBase)compilerResults.CompiledAssembly .CreateInstance(string.Format("{0}.{1}", defaultNamespace, defaultClassName)); if (template == null) { throw new InvalidOperationException("Cannot generate template"); } return(template); }
public TagHelperTemplateEngine(RazorTemplateEngine engine, IEnumerable<TagHelperDescriptor> tagHelperDescriptors) : base(engine.Host) { _tagHelperDescriptors = tagHelperDescriptors; }
private void RunTestInternal(string name, string baselineName, bool generatePragmas, bool designTimeMode, IList <LineMapping> expectedDesignTimePragmas, TestSpan[] spans, bool withTabs, Func <RazorEngineHost, RazorEngineHost> hostConfig, Func <RazorTemplateEngine, RazorTemplateEngine> templateEngineConfig, Action <GeneratorResults> onResults = null) { // Load the test files if (baselineName == null) { baselineName = name; } var sourceLocation = string.Format("TestFiles/CodeGenerator/{1}/Source/{0}.{2}", name, LanguageName, FileExtension); var expectedOutput = TestFile.Create(string.Format("TestFiles/CodeGenerator/CS/Output/{0}.{1}", baselineName, BaselineExtension)).ReadAllText(); // Set up the host and engine var host = CreateHost(); host.NamespaceImports.Add("System"); host.DesignTimeMode = designTimeMode; host.StaticHelpers = true; host.DefaultClassName = name; // Add support for templates, etc. host.GeneratedClassContext = new GeneratedClassContext(GeneratedClassContext.DefaultExecuteMethodName, GeneratedClassContext.DefaultWriteMethodName, GeneratedClassContext.DefaultWriteLiteralMethodName, "WriteTo", "WriteLiteralTo", "Template", "DefineSection", "Instrumentation.BeginContext", "Instrumentation.EndContext", new GeneratedTagHelperContext()) { LayoutPropertyName = "Layout", ResolveUrlMethodName = "Href" }; if (hostConfig != null) { host = hostConfig(host); } host.IsIndentingWithTabs = withTabs; host.EnableInstrumentation = true; var engine = new RazorTemplateEngine(host); if (templateEngineConfig != null) { engine = templateEngineConfig(engine); } // Generate code for the file GeneratorResults results = null; using (var source = TestFile.Create(sourceLocation).OpenRead()) { var sourceFileName = generatePragmas ? String.Format("{0}.{1}", name, FileExtension) : null; results = engine.GenerateCode(source, className: name, rootNamespace: TestRootNamespaceName, sourceFileName: sourceFileName); } // Only called if GENERATE_BASELINES is set, otherwise compiled out. BaselineWriter.WriteBaseline(String.Format(@"test\Microsoft.AspNet.Razor.Test\TestFiles\CodeGenerator\{0}\Output\{1}.{2}", LanguageName, baselineName, BaselineExtension), results.GeneratedCode); #if !GENERATE_BASELINES var textOutput = results.GeneratedCode; if (onResults != null) { onResults(results); } //// Verify code against baseline Assert.Equal(expectedOutput, textOutput); #endif IEnumerable <Span> generatedSpans = results.Document.Flatten(); foreach (var span in generatedSpans) { VerifyNoBrokenEndOfLines(span.Content); } // Verify design-time pragmas if (designTimeMode) { if (spans != null) { Assert.Equal(spans, generatedSpans.Select(span => new TestSpan(span)).ToArray()); } if (expectedDesignTimePragmas != null) { Assert.True(results.DesignTimeLineMappings != null && results.DesignTimeLineMappings.Count > 0); Assert.Equal(expectedDesignTimePragmas.Count, results.DesignTimeLineMappings.Count); for (var i = 0; i < expectedDesignTimePragmas.Count; i++) { if (!expectedDesignTimePragmas[i].Equals(results.DesignTimeLineMappings[i])) { Assert.True(false, String.Format("Line mapping {0} is not equivalent.", i)); } } } } }
public ICompiledRazorTemplate Compile(string razorTemplateText, RazorEngineCompileSettings settings, string templateName = null) { RazorEngineHost razorEngineHost = new RazorEngineHost(new CSharpRazorCodeLanguage()); razorEngineHost.DefaultNamespace = settings.DefaultNamespace; razorEngineHost.DefaultClassName = settings.DefaultClassName; razorEngineHost.DefaultBaseClass = settings.DefaultBaseClass; razorEngineHost.GeneratedClassContext = new GeneratedClassContext( GeneratedClassContext.DefaultExecuteMethodName, GeneratedClassContext.DefaultWriteMethodName, GeneratedClassContext.DefaultWriteLiteralMethodName, "WriteTo", "WriteLiteralTo", "Syborg.Razor.HelperResult", "DefineSection"); foreach (string namespaceImport in settings.NamespaceImports) { razorEngineHost.NamespaceImports.Add(namespaceImport); } RazorTemplateEngine razorTemplateEngine = new RazorTemplateEngine(razorEngineHost); using (StringReader templateReader = new StringReader(razorTemplateText)) { GeneratorResults generatorResults = razorTemplateEngine.GenerateCode(templateReader); Contract.Assume(generatorResults != null); if (!generatorResults.Success) { throw new RazorException(generatorResults); } // do this only for debug purposes if (templateName != null && settings.DebugMode) { lock (log) { string generatedTemplateFileName = Path.Combine(Path.GetTempPath(), templateName + ".cs"); using (StreamWriter sourceCodeWriter = new StreamWriter(generatedTemplateFileName)) using (CSharpCodeProvider provider = new CSharpCodeProvider()) { CodeGeneratorOptions codeGeneratorOptions = new CodeGeneratorOptions(); provider.GenerateCodeFromCompileUnit(generatorResults.GeneratedCode, sourceCodeWriter, codeGeneratorOptions); if (log.IsDebugEnabled) { log.DebugFormat("Writing the generated template to '{0}", generatedTemplateFileName); } } } } CompilerParameters compilerParameters = new CompilerParameters(); compilerParameters.GenerateInMemory = true; compilerParameters.IncludeDebugInformation = true; compilerParameters.ReferencedAssemblies.Add(typeof(InMemoryRazorCompiler).Assembly.Location); compilerParameters.TreatWarningsAsErrors = true; foreach (Assembly referenceAssembly in settings.ReferenceAssemblies) { compilerParameters.ReferencedAssemblies.Add(referenceAssembly.Location); } using (CSharpCodeProvider codeProvider = new CSharpCodeProvider()) { CompilerResults compilerResults = codeProvider.CompileAssemblyFromDom(compilerParameters, generatorResults.GeneratedCode); Contract.Assume(compilerResults != null); if (compilerResults.Errors.HasErrors) { throw new RazorException(generatorResults, compilerResults); } return(new CompiledRazorTemplate(generatorResults, compilerResults)); } } }
protected void RunTest(string name, string baselineName = null, bool generatePragmas = true, bool designTimeMode = false, IList <GeneratedCodeMapping> expectedDesignTimePragmas = null, Action <RazorEngineHost> hostConfig = null) { // Load the test files if (baselineName == null) { baselineName = name; } string source = TestFile.Create(String.Format("CodeGenerator.{1}.Source.{0}.{2}", name, LanguageName, FileExtension)).ReadAllText(); string expectedOutput = TestFile.Create(String.Format("CodeGenerator.{1}.Output.{0}.{2}", baselineName, LanguageName, BaselineExtension)).ReadAllText(); // Set up the host and engine RazorEngineHost host = CreateHost(); host.NamespaceImports.Add("System"); host.DesignTimeMode = designTimeMode; host.StaticHelpers = true; host.DefaultClassName = name; // Add support for templates, etc. host.GeneratedClassContext = new GeneratedClassContext(GeneratedClassContext.DefaultExecuteMethodName, GeneratedClassContext.DefaultWriteMethodName, GeneratedClassContext.DefaultWriteLiteralMethodName, "WriteTo", "WriteLiteralTo", "Template", "DefineSection", "BeginContext", "EndContext") { LayoutPropertyName = "Layout", ResolveUrlMethodName = "Href" }; if (hostConfig != null) { hostConfig(host); } RazorTemplateEngine engine = new RazorTemplateEngine(host); // Generate code for the file GeneratorResults results = null; using (StringTextBuffer buffer = new StringTextBuffer(source)) { results = engine.GenerateCode(buffer, className: name, rootNamespace: TestRootNamespaceName, sourceFileName: generatePragmas ? String.Format("{0}.{1}", name, FileExtension) : null); } // Generate code CodeCompileUnit ccu = results.GeneratedCode; CodeDomProvider codeProvider = (CodeDomProvider)Activator.CreateInstance(host.CodeLanguage.CodeDomProviderType); CodeGeneratorOptions options = new CodeGeneratorOptions(); // Both run-time and design-time use these settings. See: // * $/Dev10/pu/SP_WebTools/venus/html/Razor/Impl/RazorCodeGenerator.cs:204 // * $/Dev10/Releases/RTMRel/ndp/fx/src/xsp/System/Web/Compilation/BuildManagerHost.cs:373 options.BlankLinesBetweenMembers = false; options.IndentString = String.Empty; StringBuilder output = new StringBuilder(); using (StringWriter writer = new StringWriter(output)) { codeProvider.GenerateCodeFromCompileUnit(ccu, writer, options); } WriteBaseline(String.Format(@"test\System.Web.Razor.Test\TestFiles\CodeGenerator\{0}\Output\{1}.{2}", LanguageName, baselineName, BaselineExtension), MiscUtils.StripRuntimeVersion(output.ToString())); // Verify code against baseline #if !GENERATE_BASELINES Assert.Equal(expectedOutput, MiscUtils.StripRuntimeVersion(output.ToString())); #endif // Verify design-time pragmas if (designTimeMode) { Assert.True(expectedDesignTimePragmas != null || results.DesignTimeLineMappings == null || results.DesignTimeLineMappings.Count == 0); Assert.True(expectedDesignTimePragmas == null || (results.DesignTimeLineMappings != null && results.DesignTimeLineMappings.Count > 0)); if (expectedDesignTimePragmas != null) { Assert.Equal( expectedDesignTimePragmas.ToArray(), results.DesignTimeLineMappings .OrderBy(p => p.Key) .Select(p => p.Value) .ToArray()); } } }
public void GenerateOutputsResultsOfParsingAndGeneration() { // Arrange RazorTemplateEngine engine = new RazorTemplateEngine(CreateHost()); // Act GeneratorResults results = engine.GenerateCode(new StringTextBuffer("foo @bar(")); // Assert Assert.IsFalse(results.Success); Assert.AreEqual(1, results.ParserErrors.Count); Assert.IsNotNull(results.Document); Assert.IsNotNull(results.GeneratedCode); Assert.IsNull(results.DesignTimeLineMappings); }
protected void RunTest(string name, string baselineName = null, bool generatePragmas = true, bool designTimeMode = false, IList <LinePragmaCodeInfo> expectedDesignTimePragmas = null, Action <RazorEngineHost> hostConfig = null) { // Load the test files if (baselineName == null) { baselineName = name; } string source = TestFile.Create(String.Format("CodeGenerator.{1}.Source.{0}.{2}", name, LanguageName, FileExtension)).ReadAllText(); string expectedOutput = TestFile.Create(String.Format("CodeGenerator.{1}.Output.{0}.txt", baselineName, LanguageName)).ReadAllText(); // Set up the host and engine RazorEngineHost host = CreateHost(); host.NamespaceImports.Add("System"); host.DesignTimeMode = designTimeMode; host.StaticHelpers = true; if (hostConfig != null) { hostConfig(host); } RazorTemplateEngine engine = new RazorTemplateEngine(host); // Add support for templates, etc. host.GeneratedClassContext = new GeneratedClassContext(GeneratedClassContext.DefaultExecuteMethodName, GeneratedClassContext.DefaultWriteMethodName, GeneratedClassContext.DefaultWriteLiteralMethodName, "WriteTo", "WriteLiteralTo", "Template", "DefineSection"); // Generate code for the file GeneratorResults results = null; using (StringTextBuffer buffer = new StringTextBuffer(source)) { results = engine.GenerateCode(buffer, className: name, rootNamespace: TestRootNamespaceName, sourceFileName: generatePragmas ? String.Format("{0}.{1}", name, FileExtension) : null); } // Generate code CodeCompileUnit ccu = results.GeneratedCode; CodeDomProvider codeProvider = (CodeDomProvider)Activator.CreateInstance(host.CodeLanguage.CodeDomProviderType); CodeGeneratorOptions options = new CodeGeneratorOptions(); // Both run-time and design-time use these settings. See: // * $/Dev10/pu/SP_WebTools/venus/html/Razor/Impl/RazorCodeGenerator.cs:204 // * $/Dev10/Releases/RTMRel/ndp/fx/src/xsp/System/Web/Compilation/BuildManagerHost.cs:373 options.BlankLinesBetweenMembers = false; options.IndentString = string.Empty; StringBuilder output = new StringBuilder(); using (StringWriter writer = new StringWriter(output)) { codeProvider.GenerateCodeFromCompileUnit(ccu, writer, options); } #if GENERATE_BASELINES // Update baseline // IMPORTANT! Replace this path with the local path on your machine to the baseline files! string baselineFile = String.Format(@"D:\dd\Plan9\Main\test\System.Web.Razor.Test\TestFiles\CodeGenerator\{0}\Output\{1}.txt", LanguageName, baselineName); File.Delete(baselineFile); File.WriteAllText(baselineFile, MiscUtils.StripRuntimeVersion(output.ToString())); #else // Verify code against baseline Assert.AreEqual(expectedOutput, MiscUtils.StripRuntimeVersion(output.ToString())); #endif // Verify design-time pragmas if (designTimeMode) { Assert.IsTrue(expectedDesignTimePragmas != null || results.DesignTimeLineMappings == null || results.DesignTimeLineMappings.Count == 0); Assert.IsTrue(expectedDesignTimePragmas == null || (results.DesignTimeLineMappings != null && results.DesignTimeLineMappings.Count > 0)); Enumerable.Zip(expectedDesignTimePragmas, results.DesignTimeLineMappings, (expected, actual) => { Assert.AreEqual(expected.CodeLength, actual.Value.CodeLength, "CodeLength values are not equal for pragma {0}!", actual.Key); Assert.AreEqual(expected.StartColumn, actual.Value.StartColumn, "StartColumn values are not equal for pragma {0}!", actual.Key); Assert.AreEqual(expected.StartGeneratedColumn, actual.Value.StartGeneratedColumn, "StartGeneratedColumn values are not equal for pragma {0}!", actual.Key); Assert.AreEqual(expected.StartLine, actual.Value.StartLine, "StartLine values are not equal for pragma {0}!", actual.Key); return((object)null); }).ToList(); Assert.AreEqual(expectedDesignTimePragmas.Count, results.DesignTimeLineMappings.Count); } }
internal TemplateEngine(string templateText) { this.templateText = templateText ?? string.Empty; this.engine = this.GetRazorTemplateEngine(); this.Template = this.CreateTemplate(); }
public TagHelperTemplateEngine(RazorTemplateEngine engine, IEnumerable <TagHelperDescriptor> tagHelperDescriptors) : base(engine.Host) { _tagHelperDescriptors = tagHelperDescriptors; }
public DynamicRazorViewCompiler( IFileProvider fileProvider, RazorTemplateEngine templateEngine, CSharpCompiler csharpCompiler, Action <RoslynCompilationContext> compilationCallback, IList <CompiledViewDescriptor> precompiledViews, IMemoryCache memoryCache, ILogger logger) { if (fileProvider == null) { throw new ArgumentNullException(nameof(fileProvider)); } if (templateEngine == null) { throw new ArgumentNullException(nameof(templateEngine)); } if (csharpCompiler == null) { throw new ArgumentNullException(nameof(csharpCompiler)); } if (compilationCallback == null) { throw new ArgumentNullException(nameof(compilationCallback)); } if (precompiledViews == null) { throw new ArgumentNullException(nameof(precompiledViews)); } if (logger == null) { throw new ArgumentNullException(nameof(logger)); } _fileProvider = fileProvider; _templateEngine = templateEngine; _csharpCompiler = csharpCompiler; _compilationCallback = compilationCallback; _logger = logger; _normalizedPathLookup = new ConcurrentDictionary <string, string>(StringComparer.Ordinal); _cache = memoryCache; _precompiledViewLookup = new Dictionary <string, Task <CompiledViewDescriptor> >( precompiledViews.Count, StringComparer.OrdinalIgnoreCase); foreach (var precompiledView in precompiledViews) { if (_precompiledViewLookup.TryGetValue(precompiledView.RelativePath, out var otherValue)) { throw new InvalidOperationException("ViewPathsDifferOnlyInCase"); } _precompiledViewLookup.Add(precompiledView.RelativePath, Task.FromResult(precompiledView)); } }
public void GenerateCode_UsesDecoratedRazorParser() { // Arrange Mock<RazorParser> parser = null; var host = new Mock<RazorEngineHost>(new CSharpRazorCodeLanguage()) { CallBase = true }; host.Setup(p => p.DecorateRazorParser(It.IsAny<RazorParser>(), "foo.cshtml")) .Returns((RazorParser p, string file) => { parser = new Mock<RazorParser>(p) { CallBase = true }; return parser.Object; }) .Verifiable(); var engine = new RazorTemplateEngine(host.Object); // Act var results = engine.GenerateCode(Stream.Null, "some-class", "some-ns", "foo.cshtml"); // Assert Assert.NotNull(parser); parser.Verify(v => v.Parse(It.IsAny<ITextDocument>()), Times.Once()); host.Verify(); }
private void RunTestInternal( string name, string baselineName, bool generatePragmas, bool designTimeMode, IList <LineMapping> expectedDesignTimePragmas, TestSpan[] spans, bool withTabs, Func <RazorEngineHost, RazorEngineHost> hostConfig, Func <RazorTemplateEngine, RazorTemplateEngine> templateEngineConfig, Action <GeneratorResults> onResults = null) { // Load the test files if (baselineName == null) { baselineName = name; } var sourceLocation = string.Format("TestFiles/CodeGenerator/Source/{0}.{1}", name, FileExtension); var testFile = TestFile .Create(string.Format("TestFiles/CodeGenerator/Output/{0}.{1}", baselineName, BaselineExtension)); string expectedOutput; #if GENERATE_BASELINES if (testFile.Exists()) { expectedOutput = testFile.ReadAllText(); } else { expectedOutput = null; } #else expectedOutput = testFile.ReadAllText(); #endif // Set up the host and engine var host = CreateHost(); host.NamespaceImports.Add("System"); host.DesignTimeMode = designTimeMode; host.StaticHelpers = true; host.DefaultClassName = name; // Add support for templates, etc. host.GeneratedClassContext = new GeneratedClassContext( GeneratedClassContext.DefaultExecuteMethodName, GeneratedClassContext.DefaultWriteMethodName, GeneratedClassContext.DefaultWriteLiteralMethodName, "WriteTo", "WriteLiteralTo", "Template", "DefineSection", "Instrumentation.BeginContext", "Instrumentation.EndContext", new GeneratedTagHelperContext()); if (hostConfig != null) { host = hostConfig(host); } host.IsIndentingWithTabs = withTabs; host.EnableInstrumentation = true; var engine = new RazorTemplateEngine(host); if (templateEngineConfig != null) { engine = templateEngineConfig(engine); } // Generate code for the file GeneratorResults results = null; using (var source = TestFile.Create(sourceLocation).OpenRead()) { var sourceFile = NormalizeNewLines(source); var sourceFileName = generatePragmas ? string.Format("{0}.{1}", name, FileExtension) : null; results = engine.GenerateCode( sourceFile, className: name, rootNamespace: TestRootNamespaceName, sourceFileName: sourceFileName); } var textOutput = results.GeneratedCode; #if GENERATE_BASELINES var outputFile = string.Format( @"test\Microsoft.AspNet.Razor.Test\TestFiles\CodeGenerator\Output\{0}.{1}", baselineName, BaselineExtension); // Update baseline files if files do not already match. if (!string.Equals(expectedOutput, textOutput, StringComparison.Ordinal)) { BaselineWriter.WriteBaseline(outputFile, textOutput); } #else if (onResults != null) { onResults(results); } // Verify code against baseline Assert.Equal(expectedOutput, textOutput); #endif var generatedSpans = results.Document.Flatten(); foreach (var span in generatedSpans) { VerifyNoBrokenEndOfLines(span.Content); } // Verify design-time pragmas if (designTimeMode) { if (spans != null) { Assert.Equal(spans, generatedSpans.Select(span => new TestSpan(span)).ToArray()); } if (expectedDesignTimePragmas != null) { Assert.NotNull(results.DesignTimeLineMappings); // Guard #if GENERATE_BASELINES if (expectedDesignTimePragmas == null || !Enumerable.SequenceEqual(expectedDesignTimePragmas, results.DesignTimeLineMappings)) { var lineMappingFile = Path.ChangeExtension(outputFile, "lineMappings.cs"); var lineMappingCode = GetDesignTimeLineMappingsCode(results.DesignTimeLineMappings); BaselineWriter.WriteBaseline(lineMappingFile, lineMappingCode); } #else for (var i = 0; i < expectedDesignTimePragmas.Count && i < results.DesignTimeLineMappings.Count; i++) { Assert.Equal(expectedDesignTimePragmas[i], results.DesignTimeLineMappings[i]); } Assert.Equal(expectedDesignTimePragmas.Count, results.DesignTimeLineMappings.Count); #endif } } }
public string GenerateCode() { _codeTransformer.Initialize(this, _directives); // Create the engine RazorTemplateEngine engine = new RazorTemplateEngine(this); // Generate code GeneratorResults results = null; try { Stream stream = File.OpenRead(_fullPath); using (var reader = new StreamReader(stream, Encoding.UTF8)) { results = engine.GenerateCode(reader, className: DefaultClassName, rootNamespace: DefaultNamespace, sourceFileName: _fullPath); } } catch (Exception e) { OnGenerateError(4, e.ToString(), 1, 1); //Returning null signifies that generation has failed return(null); } // Output errors foreach (RazorError error in results.ParserErrors) { OnGenerateError(4, error.Message, (uint)error.Location.LineIndex + 1, (uint)error.Location.CharacterIndex + 1); } try { OnCodeCompletion(50, 100); using (StringWriter writer = new StringWriter()) { CodeGeneratorOptions options = new CodeGeneratorOptions(); options.BlankLinesBetweenMembers = false; options.BracingStyle = "C"; //Generate the code writer.WriteLine("#pragma warning disable 1591"); _codeDomProvider.GenerateCodeFromCompileUnit(results.GeneratedCode, writer, options); writer.WriteLine("#pragma warning restore 1591"); OnCodeCompletion(100, 100); writer.Flush(); // Perform output transformations and return string codeContent = writer.ToString(); codeContent = _codeTransformer.ProcessOutput(codeContent); //TridionVSRazorExtension hack : transform into partial class string baseNamespace = _directives["VsNamespace"].Split('.')[0]; codeContent = codeContent.Replace("namespace " + DefaultNamespace, "namespace " + baseNamespace); codeContent = codeContent.Replace( "public partial class " + DefaultClassName + " : " + baseNamespace + ".WrappedTridionRazorTemplate<dynamic>", "public partial class WrappedTridionRazorTemplate" ); int intConstructorStart = codeContent.IndexOf("public " + DefaultClassName + "()"); if (intConstructorStart > -1) { string strConstructor = codeContent.Substring(intConstructorStart, codeContent.IndexOf("}", intConstructorStart) - intConstructorStart + 1); codeContent = codeContent.Replace(strConstructor, ""); } int intExecuteStart = codeContent.IndexOf("public override void Execute()"); if (intExecuteStart > -1) { string strExecute = codeContent.Substring(intExecuteStart, codeContent.IndexOf("}", intExecuteStart) - intExecuteStart + 1); codeContent = codeContent.Replace(strExecute, ""); } int intAttribute1Start = codeContent.IndexOf("[System.CodeDom.Compiler.GeneratedCodeAttribute("); if (intAttribute1Start > -1) { string strAttribute1 = codeContent.Substring(intAttribute1Start, codeContent.IndexOf("]", intAttribute1Start) - intAttribute1Start + 1); codeContent = codeContent.Replace(strAttribute1, ""); } int intAttribute2Start = codeContent.IndexOf("[System.Web.WebPages.PageVirtualPathAttribute("); if (intAttribute2Start > -1) { string strAttribute2 = codeContent.Substring(intAttribute2Start, codeContent.IndexOf("]", intAttribute2Start) - intAttribute2Start + 1); codeContent = codeContent.Replace(strAttribute2, ""); } return(codeContent); } } catch (Exception e) { OnGenerateError(4, e.ToString(), 1, 1); //Returning null signifies that generation has failed return(null); } }
/// <summary> /// Renders the specified template and model. /// </summary> /// <typeparam name="T">The model type.</typeparam> /// <param name="template">The template.</param> /// <param name="model">The model.</param> /// <returns>The rendered template output.</returns> /// <exception cref="TemplateCompileException">Thrown when template compiling fails.</exception> public static string Render <T>(string template, T model) { var anonymous = model.GetType().IsAnonymousType(); var host = new RazorEngineHost(new CSharpRazorCodeLanguage()) { DefaultBaseClass = anonymous ? "TemplateBase<dynamic>" : string.Format("TemplateBase<{0}>", typeof(T).FullName), DefaultClassName = "GeneratedTemplate", DefaultNamespace = "SimpleRazor" }; host.NamespaceImports.Add("System"); host.NamespaceImports.Add("System.Collections.Generic"); host.NamespaceImports.Add("System.Linq"); var engine = new RazorTemplateEngine(host); var reader = new StringReader(template); var razorResult = engine.GenerateCode(reader); reader.Dispose(); var codeProvider = new CSharpCodeProvider(); using (var writer = new StringWriter()) { codeProvider.GenerateCodeFromCompileUnit(razorResult.GeneratedCode, writer, new CodeGeneratorOptions()); LastGeneratedCode = writer.ToString(); } var referencedAssemblies = new List <string> { Assembly.GetExecutingAssembly().Location, // Hack: Ensure System.Linq and Microsoft.CSharp are loaded typeof(System.Linq.Enumerable).Assembly.Location, typeof(Microsoft.CSharp.RuntimeBinder.RuntimeBinderException).Assembly.Location }; referencedAssemblies.AddRange(GetReferencedAssemblies <T>()); var compilerParameters = new CompilerParameters(referencedAssemblies.Distinct().ToArray()) { GenerateInMemory = true }; var compilerResults = codeProvider.CompileAssemblyFromDom(compilerParameters, razorResult.GeneratedCode); if (compilerResults.Errors.HasErrors) { throw new TemplateCompileException(compilerResults.Errors); } dynamic templateInstance; if (anonymous) { templateInstance = (TemplateBase <dynamic>)compilerResults.CompiledAssembly.CreateInstance("SimpleRazor.GeneratedTemplate"); templateInstance.Model = model.ToExpando(); } else { templateInstance = (TemplateBase <T>)compilerResults.CompiledAssembly.CreateInstance("SimpleRazor.GeneratedTemplate"); templateInstance.Model = model; } return(templateInstance.ToString()); }
public int Generate(string wszInputFilePath, string bstrInputFileContents, string wszDefaultNamespace, IntPtr[] rgbOutputFileContents, out uint pcbOutput, IVsGeneratorProgress pGenerateProgress) { string templatebasename = "RazorEngine.Templating.TemplateBase"; FileInfo fitemplate = new FileInfo(wszInputFilePath); FileInfo ficode = new FileInfo(wszInputFilePath.Replace(".cshtml", ".cs")); if (!ficode.Exists || ficode.LastWriteTimeUtc < fitemplate.LastWriteTimeUtc) { // get classname from path var cn = fitemplate.Name.Substring(0, fitemplate.Name.IndexOf('.')); // var pt = fitemplate.DirectoryName.Split(new char[] { Path.DirectorySeparatorChar }, StringSplitOptions.RemoveEmptyEntries); var ns = wszDefaultNamespace; string template = File.ReadAllText(fitemplate.FullName); var host = new WebPageRazorHost(wszInputFilePath); //new WebPageRazorHost("~" + , fitemplate.FullName); //new RazorEngineHost(new CSharpRazorCodeLanguage()); //new WebCodeRazorHost("~"+prp, fitemplate.FullName); var rte = new RazorTemplateEngine(host); //Razor.SetTemplateBaseType(typeof(TemplateBase<>)); string baseTypeName = templatebasename; if (template.StartsWith("@model")) { var l1 = template.IndexOf("\n"); var modelTypeName = template.Substring(6, l1 - 6).Trim(); template = template.Substring(l1).Trim(); baseTypeName = templatebasename + "<" + modelTypeName + ">"; } //else if (cn == "_ViewStart") //{ // baseTypeName = "System.Web.WebPages.StartPage"; //} else { baseTypeName = templatebasename + "<dynamic>"; } //host.DefaultNamespace = ""; host.DefaultPageBaseClass = baseTypeName; host.NamespaceImports.Add("System.Web.Mvc"); host.NamespaceImports.Add("System.Web.Mvc.Html"); //string result = //Razor.ParseToCode(template, null, cn, baseTypeName, ns); GeneratorResults results = null; using (var reader = new StringReader(template)) { results = rte.GenerateCode(reader, cn, ns, null); } StringBuilder builder = new StringBuilder(); //builder.AppendLine("using System.Web.Mvc;"); //builder.AppendLine("using System.Web.Mvc.Html;"); using (var writer = new StringWriter(builder)) { new CSharpCodeProvider().GenerateCodeFromCompileUnit(results.GeneratedCode, writer, null); } builder.Replace("#line hidden", "#line 1 \"" + fitemplate.Name + "\""); File.WriteAllText(ficode.FullName, builder.ToString()); Console.WriteLine("Updated {0}.{1}", ns, cn); byte[] bytes = Encoding.UTF8.GetBytes(builder.ToString()); int length = bytes.Length; rgbOutputFileContents[0] = Marshal.AllocCoTaskMem(length); Marshal.Copy(bytes, 0, rgbOutputFileContents[0], length); pcbOutput = (uint)length; return(VSConstants.S_OK); } else { rgbOutputFileContents = new IntPtr[] { }; pcbOutput = 0; return(0); } }
public string GenerateCode() { _codeTransformer.Initialize(this, _directives); // Create the engine RazorTemplateEngine engine = new RazorTemplateEngine(this); // Generate code GeneratorResults results = null; try { Stream stream = File.OpenRead(_fullPath); using (var reader = new StreamReader(stream, Encoding.UTF8)) { results = engine.GenerateCode(reader, className: DefaultClassName, rootNamespace: DefaultNamespace, sourceFileName: _fullPath); } } catch (Exception e) { OnGenerateError(4, e.ToString(), 1, 1); //Returning null signifies that generation has failed return(null); } // Output errors foreach (RazorError error in results.ParserErrors) { OnGenerateError(4, error.Message, (uint)error.Location.LineIndex + 1, (uint)error.Location.CharacterIndex + 1); } try { OnCodeCompletion(50, 100); using (StringWriter writer = new StringWriter()) { CodeGeneratorOptions options = new CodeGeneratorOptions(); options.BlankLinesBetweenMembers = false; options.BracingStyle = "C"; //Generate the code writer.WriteLine(CodeLanguageUtil.GetPreGeneratedCodeBlock()); _codeDomProvider.GenerateCodeFromCompileUnit(results.GeneratedCode, writer, options); writer.WriteLine(CodeLanguageUtil.GetPostGeneratedCodeBlock()); OnCodeCompletion(100, 100); writer.Flush(); // Perform output transformations and return string codeContent = writer.ToString(); codeContent = _codeTransformer.ProcessOutput(codeContent); return(codeContent); } } catch (Exception e) { OnGenerateError(4, e.ToString(), 1, 1); //Returning null signifies that generation has failed return(null); } }
public RazorXSyntaxTreeParser() { var host = new RazorEngineHost(new CSharpRazorCodeLanguage()); engine = new RazorTemplateEngine(host); }
private string GetGeneratorResultBak(IEnumerable <string> namespaces, TypeContext context) { #pragma warning disable 612, 618 var razorCompiledItemAssembly = typeof(RazorCompiledItemAttribute).Assembly; //手动加载程序集,防止编译 Razor 类时找不到 DLL var razorEngine = RazorEngine.Create(builder => { InheritsDirective.Register(builder); FunctionsDirective.Register(builder); SectionDirective.Register(builder); builder .SetNamespace(DynamicTemplateNamespace) //.SetBaseType("Microsoft.Extensions.RazorViews.BaseView") .SetBaseType(BuildTypeName(context.TemplateType, context.ModelType)) .ConfigureClass((document, @class) => { @class.ClassName = context.ClassName; //if (!str ing.IsNullOrWhiteSpace(document.Source.FilePath)) //{ // @class.ClassName = Path.GetFileNameWithoutExtension(document.Source.FilePath); //} @class.Modifiers.Clear(); @class.Modifiers.Add("internal"); }); builder.Features.Add(new SuppressChecksumOptionsFeature()); }); string importString = @" @using System @using System.Threading.Tasks "; importString += String.Join("\r\n", namespaces.Select(n => "@using " + n.Trim())) + "\r\n"; using (var reader = context.TemplateContent.GetTemplateReader()) { string path = null; if (string.IsNullOrWhiteSpace(context.TemplateContent.TemplateFile)) { path = Directory.GetCurrentDirectory(); } else { path = Path.GetDirectoryName(context.TemplateContent.TemplateFile); } var razorProject = RazorProjectFileSystem.Create(path); var templateEngine = new RazorTemplateEngine(razorEngine, razorProject); templateEngine.Options.DefaultImports = RazorSourceDocument.Create(importString, fileName: null); RazorPageGeneratorResult result; if (string.IsNullOrWhiteSpace(context.TemplateContent.TemplateFile)) { var item = RazorSourceDocument.Create(context.TemplateContent.Template, string.Empty); var imports = new List <RazorSourceDocument>(); imports.Add(templateEngine.Options.DefaultImports); var doc = RazorCodeDocument.Create(item, imports); result = GenerateCodeFile(templateEngine, doc); } else { var item = razorProject.GetItem(context.TemplateContent.TemplateFile); result = GenerateCodeFile(templateEngine, item); } return(InspectSource(result, context)); } }
private static Type CreateTypeForEmbeddedRazor(RequesterTypeAndResourcePath data) { // Getting razor code from resource. string code = null; string resourceName = data.ResourcePath.Replace('\\', '.'); using (var stream = data.RequesterType.Assembly.GetManifestResourceStream(resourceName)) if (stream != null) { using (var reader = new StreamReader(stream)) code = reader.ReadToEnd(); } if (code == null) { throw new Exception("Resource was not found. Maybe it has not been embedded."); } var virtualPath = string.Format("~/{0}", data.ResourcePath.Replace('\\', '/')); var className = resourceName.Replace('.', '_'); // Creating compile unit, using Mvc Razor syntax. // These settings must match those of 'web.config' file, section 'system.web.webPages.razor' var factory = new MvcWebRazorHostFactory(); var host = factory.CreateHost(virtualPath, data.ResourcePath); host.DefaultPageBaseClass = typeof(CerebelloViewPage).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.Web.Routing"); host.NamespaceImports.Add("CerebelloWebRole.Code"); host.NamespaceImports.Add("CerebelloWebRole.Models"); var engine = new RazorTemplateEngine(host); GeneratorResults results; using (TextReader reader = new StringReader(code)) results = engine.GenerateCode(reader, className, rootNamespace: null, sourceFileName: host.PhysicalPath); if (!results.Success) { throw CreateExceptionFromParserError(results.ParserErrors.Last(), virtualPath); } // Compiling an assembly with the code. var codeProvider = new CSharpCodeProvider(); var compilerParams = new CompilerParameters { GenerateInMemory = true, GenerateExecutable = false, #if DEBUG IncludeDebugInformation = true, #endif }; // loading a required assembly, before creating the list of 'ReferencedAssemblies' // reference: http://razorengine.codeplex.com/discussions/242605 if (typeof(Microsoft.CSharp.RuntimeBinder.Binder).Assembly == null) { throw new Exception("Could not load required assembly."); } compilerParams.ReferencedAssemblies.AddRange( AppDomain.CurrentDomain .GetAssemblies() .Where(a => !a.IsDynamic) .GroupBy(a => a.FullName) .Select(grp => grp.First()) .Select(a => a.Location) .ToArray()); var compilerResult = codeProvider.CompileAssemblyFromDom(compilerParams, results.GeneratedCode); // Returning the compiled type. var type = compilerResult.CompiledAssembly.GetTypes().Single(t => t.Name == className); return(type); }
/// <summary> /// Initializes a new instance of the <see cref="RazorViewEngine"/> class. /// </summary> /// <param name="configuration"></param> public RazorViewEngine(IRazorConfiguration configuration) { this.razorConfiguration = configuration; this.engine = this.GetRazorTemplateEngine(); this.codeDomProvider = new CSharpCodeProvider(); }
public PageActionDescriptorChangeProvider( RazorTemplateEngine templateEngine, IRazorViewEngineFileProviderAccessor fileProviderAccessor, IOptions <RazorPagesOptions> razorPagesOptions) { if (templateEngine == null) { throw new ArgumentNullException(nameof(templateEngine)); } if (fileProviderAccessor == null) { throw new ArgumentNullException(nameof(fileProviderAccessor)); } if (razorPagesOptions == null) { throw new ArgumentNullException(nameof(razorPagesOptions)); } _fileProvider = fileProviderAccessor.FileProvider; var rootDirectory = razorPagesOptions.Value.RootDirectory; Debug.Assert(!string.IsNullOrEmpty(rootDirectory)); rootDirectory = rootDirectory.TrimEnd('/'); // Search pattern that matches all cshtml files under the Pages RootDirectory var pagesRootSearchPattern = rootDirectory + "/**/*.cshtml"; // pagesRootSearchPattern will miss _ViewImports outside the RootDirectory despite these influencing // compilation. e.g. when RootDirectory = /Dir1/Dir2, the search pattern will ignore changes to // [/_ViewImports.cshtml, /Dir1/_ViewImports.cshtml]. We need to additionally account for these. var importFileAtPagesRoot = rootDirectory + "/" + templateEngine.Options.ImportsFileName; var additionalImportFilePaths = templateEngine.GetImportItems(importFileAtPagesRoot) .Select(item => item.FilePath); if (razorPagesOptions.Value.AllowAreas) { // Search pattern that matches all cshtml files under the Pages AreaRootDirectory var areaRootSearchPattern = "/Areas/**/*.cshtml"; var importFileAtAreaPagesRoot = $"/Areas/{templateEngine.Options.ImportsFileName}"; var importPathsOutsideAreaPagesRoot = templateEngine.GetImportItems(importFileAtAreaPagesRoot) .Select(item => item.FilePath); additionalImportFilePaths = additionalImportFilePaths .Concat(importPathsOutsideAreaPagesRoot) .Distinct(StringComparer.OrdinalIgnoreCase); _searchPatterns = new[] { pagesRootSearchPattern, areaRootSearchPattern }; } else { _searchPatterns = new[] { pagesRootSearchPattern, }; } _additionalFilesToTrack = additionalImportFilePaths.ToArray(); }
public Form1() { InitializeComponent(); _engine = SetupRazorEngine(); }
protected override async Task <TemplateResult> ProcessSingleTemplate(string content, dynamic templateModel) { var razorEngine = RazorEngine.Create((builder) => { RazorExtensions.Register(builder); }); // Don't care about the RazorProject as we already have the content of the .cshtml file // and don't need to deal with imports. var razorProject = RazorProject.Create(Directory.GetCurrentDirectory()); var razorTemplateEngine = new RazorTemplateEngine(razorEngine, razorProject); var imports = new RazorSourceDocument[] { RazorSourceDocument.Create(@" @using System @using System.Threading.Tasks ", fileName: null) }; var razorDocument = RazorCodeDocument.Create(RazorSourceDocument.Create(content, "Template"), imports); var generatorResults = razorTemplateEngine.GenerateCode(razorDocument); if (generatorResults.Diagnostics.Any()) { var messages = generatorResults.Diagnostics.Select(d => d.GetMessage()); return(new TemplateResult() { GeneratedText = string.Empty, ProcessingException = new TemplateProcessingException(messages, generatorResults.GeneratedCode) }); } var templateResult = _compilationService.Compile(generatorResults.GeneratedCode); if (templateResult.Messages.Any()) { return(new TemplateResult() { GeneratedText = string.Empty, ProcessingException = new TemplateProcessingException(templateResult.Messages, generatorResults.GeneratedCode) }); } var compiledObject = Activator.CreateInstance(templateResult.CompiledType); var razorTemplate = compiledObject as RazorTemplateBase; string result = String.Empty; if (razorTemplate != null) { razorTemplate.Model = templateModel; //ToDo: If there are errors executing the code, they are missed here. result = await razorTemplate.ExecuteTemplate(); } return(new TemplateResult() { GeneratedText = result, ProcessingException = null }); }
/// <summary> /// Gets the code compile unit used to compile a type. /// </summary> /// <param name="className">The class name.</param> /// <param name="template">The template to compile.</param> /// <param name="namespaceImports">The set of namespace imports.</param> /// <param name="templateType">The template type.</param> /// <param name="modelType">The model type.</param> /// <returns>A <see cref="CodeCompileUnit"/> used to compile a type.</returns> public CodeCompileUnit GetCodeCompileUnit(string className, string template, ISet <string> namespaceImports, Type templateType, Type modelType) { if (string.IsNullOrEmpty(className)) { throw new ArgumentException("Class name is required."); } if (string.IsNullOrEmpty(template)) { throw new ArgumentException("Template is required."); } templateType = templateType ?? ((modelType == null) ? typeof(TemplateBase) : typeof(TemplateBase <>)); var host = new RazorEngineHost(CodeLanguage) { DefaultBaseClass = BuildTypeName(templateType, modelType), DefaultClassName = className, DefaultNamespace = "CompiledRazorTemplates.Dynamic", GeneratedClassContext = new GeneratedClassContext( "Execute", "Write", "WriteLiteral", "WriteTo", "WriteLiteralTo", "ServiceStack.Razor2.Templating.TemplateWriter", "WriteSection") { ResolveUrlMethodName = "Href" } }; var templateNamespaces = templateType.GetCustomAttributes(typeof(RequireNamespacesAttribute), true) .Cast <RequireNamespacesAttribute>() .SelectMany(att => att.Namespaces); foreach (string ns in templateNamespaces) { namespaceImports.Add(ns); } foreach (string @namespace in namespaceImports) { host.NamespaceImports.Add(@namespace); } var engine = new RazorTemplateEngine(host); GeneratorResults result; using (var reader = new StringReader(template)) { result = engine.GenerateCode(reader); } var type = result.GeneratedCode.Namespaces[0].Types[0]; if (modelType != null) { if (CompilerServices.IsAnonymousType(modelType)) { type.CustomAttributes.Add(new CodeAttributeDeclaration( new CodeTypeReference(typeof(HasDynamicModelAttribute)))); } } GenerateConstructors(CompilerServices.GetConstructors(templateType), type); var statement = new CodeMethodInvokeExpression(new CodeThisReferenceExpression(), "Clear"); foreach (CodeTypeMember member in type.Members) { if (member.Name.Equals("Execute")) { ((CodeMemberMethod)member).Statements.Insert(0, new CodeExpressionStatement(statement)); break; } } return(result.GeneratedCode); }
private GeneratorResults ParseChange(ITextBuffer buffer, CancellationToken token) { EnsureOnThread(); // Create a template engine var engine = new RazorTemplateEngine(_host); // Seek the buffer to the beginning buffer.Position = 0; try { return engine.GenerateCode( input: buffer, className: null, rootNamespace: null, sourceFileName: _fileName, cancelToken: token); } catch (OperationCanceledException) { return null; } }