public RazorChunkGenerator( string className, string rootNamespaceName, string sourceFileName, RazorEngineHost host) { if (rootNamespaceName == null) { throw new ArgumentNullException(nameof(rootNamespaceName)); } if (host == null) { throw new ArgumentNullException(nameof(host)); } if (string.IsNullOrEmpty(className)) { throw new ArgumentException(CommonResources.Argument_Cannot_Be_Null_Or_Empty, nameof(className)); } ClassName = className; RootNamespaceName = rootNamespaceName; SourceFileName = sourceFileName; GenerateLinePragmas = string.IsNullOrEmpty(SourceFileName) ? false : true; Host = host; }
// internal for unit testing only, not intended to be used directly in code internal static int CalculatePadding(RazorEngineHost host, Span target, int generatedStart) { if (host == null) { throw new ArgumentNullException("host"); } if (target == null) { throw new ArgumentNullException("target"); } int padding; padding = CollectSpacesAndTabs(target, host.TabSize) - generatedStart; // if we add generated text that is longer than the padding we wanted to insert we have no recourse and we have to skip padding // example: // Razor code at column zero: @somecode() // Generated code will be: // In design time: __o = somecode(); // In Run time: Write(somecode()); // // In both cases the padding would have been 1 space to remote the space the @ symbol takes, which will be smaller than the 6 chars the hidden generated code takes. if (padding < 0) { padding = 0; } return padding; }
// Special case for statement padding to account for brace positioning in the editor. public static string PadStatement(RazorEngineHost host, string code, Span target, ref int startGeneratedCode, out int paddingCharCount) { if (host == null) { throw new ArgumentNullException("host"); } if (target == null) { throw new ArgumentNullException("target"); } // We are passing 0 rather than startgeneratedcode intentionally (keeping v2 behavior). int padding = CalculatePadding(host, target, 0); // We treat statement padding specially so for brace positioning, so that in the following example: // @if (foo > 0) // { // } // // the braces shows up under the @ rather than under the if. if (host.DesignTimeMode && padding > 0 && target.Previous.Kind == SpanKind.Transition && // target.Previous is guaranteed to be none null if you got any padding. String.Equals(target.Previous.Content, SyntaxConstants.TransitionString)) { padding--; startGeneratedCode--; } string generatedCode = PadInternal(host, code, padding, out paddingCharCount); return generatedCode; }
public void CodeTreeWithUsings() { var syntaxTreeNode = new Mock<Span>(new SpanBuilder()); var language = new CSharpRazorCodeLanguage(); var host = new RazorEngineHost(language); var codeBuilderContext = new CodeBuilderContext( host, "TestClass", "TestNamespace", "Foo.cs", shouldGenerateLinePragmas: false, errorSink: new ParserErrorSink()); codeBuilderContext.CodeTreeBuilder.AddUsingChunk("FakeNamespace1", syntaxTreeNode.Object); codeBuilderContext.CodeTreeBuilder.AddUsingChunk("FakeNamespace2.SubNamespace", syntaxTreeNode.Object); var codeBuilder = language.CreateCodeBuilder(codeBuilderContext); // Act var result = codeBuilder.Build(); BaselineWriter.WriteBaseline( @"test\Microsoft.AspNet.Razor.Test\TestFiles\CodeGenerator\CS\Output\CSharpCodeBuilder.cs", result.Code); var expectedOutput = TestFile.Create("TestFiles/CodeGenerator/CS/Output/CSharpCodeBuilder.cs").ReadAllText(); // Assert Assert.Equal(expectedOutput, result.Code); }
public BackgroundParser(RazorEngineHost host, string fileName) { _main = new MainThreadState(fileName); _bg = new BackgroundThread(_main, host, fileName); _main.ResultsReady += (sender, args) => OnResultsReady(args); }
internal static CodeGeneratorContext Create(RazorEngineHost host, Func<CodeWriter> writerFactory, string className, string rootNamespace, string sourceFile, bool shouldGenerateLinePragmas) { CodeGeneratorContext context = new CodeGeneratorContext() { Host = host, CodeWriterFactory = writerFactory, SourceFile = shouldGenerateLinePragmas ? sourceFile : null, CompileUnit = new CodeCompileUnit(), Namespace = new CodeNamespace(rootNamespace), GeneratedClass = new CodeTypeDeclaration(className) { IsClass = true }, TargetMethod = new CodeMemberMethod() { Name = host.GeneratedClassContext.ExecuteMethodName, Attributes = MemberAttributes.Override | MemberAttributes.Public }, CodeMappings = new Dictionary<int, GeneratedCodeMapping>() }; context.CompileUnit.Namespaces.Add(context.Namespace); context.Namespace.Types.Add(context.GeneratedClass); context.GeneratedClass.Members.Add(context.TargetMethod); context.Namespace.Imports.AddRange(host.NamespaceImports .Select(s => new CodeNamespaceImport(s)) .ToArray()); return context; }
public void ConstructorInitializesHost() { // Arrange RazorEngineHost host = new RazorEngineHost(new CSharpRazorCodeLanguage()); // Act RazorTemplateEngine engine = new RazorTemplateEngine(host); // Assert Assert.AreSame(host, engine.Host); }
// Internal for testing. internal CodeBuilderContext(RazorEngineHost host, string className, string rootNamespace, string sourceFile, bool shouldGenerateLinePragmas, ParserErrorSink errorSink) : base(host, className, rootNamespace, sourceFile, shouldGenerateLinePragmas) { ErrorSink = errorSink; ExpressionRenderingMode = ExpressionRenderingMode.WriteToOutput; }
public static CodeGeneratorContext Create(RazorEngineHost host, string className, string rootNamespace, string sourceFile, bool shouldGenerateLinePragmas) { return new CodeGeneratorContext() { CodeTreeBuilder = new CodeTreeBuilder(), Host = host, SourceFile = shouldGenerateLinePragmas ? sourceFile : null, RootNamespace = rootNamespace, ClassName = className }; }
private void SetBaseTypeFromHost(RazorEngineHost mvcHost) { if (!mvcHost.DefaultBaseTemplateType.IsGenericType) { SetBaseType(mvcHost.DefaultBaseTemplateType.FullName); } else { var modelTypeName = CompilerServicesUtility.ResolveCSharpTypeName(mvcHost.DefaultModelType); SetBaseType(mvcHost.DefaultBaseClass + "<" + modelTypeName + ">"); } }
public CodeGeneratorContext(RazorEngineHost host, string className, string rootNamespace, string sourceFile, bool shouldGenerateLinePragmas) { CodeTreeBuilder = new CodeTreeBuilder(); Host = host; SourceFile = shouldGenerateLinePragmas ? sourceFile : null; RootNamespace = rootNamespace; ClassName = className; }
public void ConstructorWithCodeLanguageSetsPropertiesAppropriately() { // Arrange RazorCodeLanguage language = new CSharpRazorCodeLanguage(); // Act RazorEngineHost host = new RazorEngineHost(language); // Assert VerifyCommonDefaults(host); Assert.AreSame(language, host.CodeLanguage); Assert.IsInstanceOfType(host.CreateMarkupParser(), typeof(HtmlMarkupParser)); }
public void ConstructorWithCodeLanguageAndMarkupParserSetsPropertiesAppropriately() { // Arrange RazorCodeLanguage language = new CSharpRazorCodeLanguage(); MarkupParser expected = new HtmlMarkupParser(); // Act RazorEngineHost host = new RazorEngineHost(language, () => expected); // Assert VerifyCommonDefaults(host); Assert.AreSame(language, host.CodeLanguage); Assert.AreSame(expected, host.CreateMarkupParser()); }
public void ConstructorWithCodeLanguageSetsPropertiesAppropriately() { // Arrange var language = new CSharpRazorCodeLanguage(); // Act var host = new RazorEngineHost(language); // Assert VerifyCommonDefaults(host); Assert.Same(language, host.CodeLanguage); Assert.IsType<HtmlMarkupParser>(host.CreateMarkupParser()); }
public void CreateCodeGeneratorParserListenerReturnsNewCSharpCodeGeneratorParserListener() { // Arrange RazorCodeLanguage service = new CSharpRazorCodeLanguage(); // Act RazorEngineHost host = new RazorEngineHost(service); RazorCodeGenerator generator = service.CreateCodeGenerator("Foo", "Bar", "Baz", host); // Assert Assert.IsNotNull(generator); Assert.IsInstanceOfType(generator, typeof(CSharpRazorCodeGenerator)); Assert.AreEqual("Foo", generator.ClassName); Assert.AreEqual("Bar", generator.RootNamespaceName); Assert.AreEqual("Baz", generator.SourceFileName); Assert.AreSame(host, generator.Host); }
// there is some duplicity of code here, but its very simple and since this is a host path, I'd rather not create another class to encapsulate the data. public static int PaddingCharCount(RazorEngineHost host, Span target, int generatedStart) { int padding = CalculatePadding(host, target, generatedStart); if (host.DesignTimeMode && host.IsIndentingWithTabs) { int spaces; int tabs = Math.DivRem(padding, host.TabSize, out spaces); return tabs + spaces; } else { return padding; } }
public void CreateCodeBuilder_ReturnsNewCSharpCodeBuilder() { // Arrange var language = new CSharpRazorCodeLanguage(); var host = new RazorEngineHost(language); var context = CodeGeneratorContext.Create(host, "myclass", "myns", string.Empty, shouldGenerateLinePragmas: false); // Act var generator = language.CreateCodeBuilder(context); // Assert Assert.IsType<CSharpCodeBuilder>(generator); }
public void CreateChunkGeneratorParserListenerReturnsNewCSharpChunkGeneratorParserListener() { // Arrange var service = new CSharpRazorCodeLanguage(); // Act var host = new RazorEngineHost(service); var generator = service.CreateChunkGenerator("Foo", "Bar", "Baz", host); // Assert Assert.NotNull(generator); Assert.IsType<RazorChunkGenerator>(generator); Assert.Equal("Foo", generator.ClassName); Assert.Equal("Bar", generator.RootNamespaceName); Assert.Equal("Baz", generator.SourceFileName); Assert.Same(host, generator.Host); }
protected RazorCodeGenerator(string className, string rootNamespaceName, string sourceFileName, RazorEngineHost host) { if (String.IsNullOrEmpty(className)) { throw new ArgumentException(CommonResources.Argument_Cannot_Be_Null_Or_Empty, "className"); } if (rootNamespaceName == null) { throw new ArgumentNullException("rootNamespaceName"); } if (host == null) { throw new ArgumentNullException("host"); } ClassName = className; RootNamespaceName = rootNamespaceName; SourceFileName = sourceFileName; GenerateLinePragmas = String.IsNullOrEmpty(SourceFileName) ? false : true; Host = host; }
internal static CodeGeneratorContext Create(RazorEngineHost host, Func<CodeWriter> writerFactory, string className, string rootNamespace, string sourceFile, bool shouldGenerateLinePragmas) { CodeGeneratorContext context = new CodeGeneratorContext() { Host = host, CodeWriterFactory = writerFactory, SourceFile = shouldGenerateLinePragmas ? sourceFile : null, CompileUnit = new CodeCompileUnit(), Namespace = new CodeNamespace(rootNamespace), GeneratedClass = new CodeTypeDeclaration(className) { IsClass = true }, TargetMethod = new CodeMemberMethod() { Name = host.GeneratedClassContext.ExecuteMethodName, Attributes = MemberAttributes.Override | MemberAttributes.Public }, CodeMappings = new Dictionary<int, GeneratedCodeMapping>() }; var entryPoint = context.TargetMethod; if (entryPoint.Name.EndsWith("Async", StringComparison.Ordinal) && entryPoint.ReturnType.BaseType == "System.Void" && host.NamespaceImports.Contains("System.Threading.Tasks")) { entryPoint.ReturnType = new CodeTypeReference("async global::System.Threading.Tasks.Task"); } context.CompileUnit.Namespaces.Add(context.Namespace); context.Namespace.Types.Add(context.GeneratedClass); context.GeneratedClass.Members.Add(context.TargetMethod); context.Namespace.Imports.AddRange(host.NamespaceImports .Select(s => new CodeNamespaceImport(s)) .ToArray()); return context; }
/// <summary> /// Initializes a new instance of the <see cref="CSharpRazorCodeGenerator"/> class. /// </summary> /// <param name="className">Name of the class.</param> /// <param name="rootNamespaceName">Name of the root namespace.</param> /// <param name="sourceFileName">Name of the source file.</param> /// <param name="host">The host.</param> /// <param name="strictMode">Flag to specify that this generator is running in struct mode.</param> public CSharpRazorCodeGenerator(string className, string rootNamespaceName, string sourceFileName, RazorEngineHost host, bool strictMode) : base(className, rootNamespaceName, sourceFileName, host) { StrictMode = strictMode; var mvcHost = host as Compilation.RazorEngineHost; if (mvcHost != null) { SetBaseTypeFromHost(mvcHost); } }
public DesignTimeCSharpRenderer(RazorEngineHost host) { _paddingBuilder = new RazevolutionPaddingBuilder(host); }
public string GenerateCode(string templateText, RazorEngineHost host = null) { GeneratorResults results; return(GenerateCode(templateText, out results, host)); }
private async Task <Stream> CachedRazorWorker(RazorEngineHost host, TextAndVersion originalText) { var cacheFile = GetCachedFileInfo(); if (cacheFile.Exists) { return(cacheFile.OpenRead()); } else { (var success, var source) = await RazorWorkerImpl(host, originalText); FileStream fs = null; try { if (success) { fs = cacheFile.Create(); await source.CopyToAsync(fs, 4096, _cancellationToken); await fs.FlushAsync(_cancellationToken); } } catch (Exception ex) { ReportDiagnostic(Diagnostic.Create(Compilation.CachingFailed, Location.None, originalText.FilePath, cacheFile.FullName, ex)); for (var i = 0; i < 10 && cacheFile.Exists; i++) { await Task.Delay(100 *i); try { cacheFile.Delete(); } catch { } } if (cacheFile.Exists) { ReportDiagnostic(Diagnostic.Create(Compilation.CachingFailedHard, Location.None, originalText.FilePath, cacheFile.FullName)); } } finally { fs?.Dispose(); source.Position = 0; } return(source); // return the in-memory stream, since it's faster } FileInfo GetCachedFileInfo() { using (var md5 = MD5.Create()) using (var str = new MemoryStream()) using (var sw = new StreamWriter(str)) { // all those things can affect the generated c# // so we need to include them in the hash... sw.WriteLine(host.CodeLanguage.LanguageName); sw.WriteLine(host.CodeLanguage.CodeDomProviderType.FullName); sw.WriteLine(host.DefaultBaseClass); sw.WriteLine(host.DefaultClassName); sw.WriteLine(host.DefaultNamespace); sw.WriteLine(string.Join(";", host.NamespaceImports)); sw.WriteLine(host.StaticHelpers); sw.WriteLine(host.TabSize); sw.WriteLine(originalText.FilePath); originalText.Text.Write(sw, _cancellationToken); // .cshtml content sw.Flush(); str.Position = 0; var hashBytes = md5.ComputeHash(str); var fileName = BitConverter.ToString(hashBytes).Replace("-", "") + ".cs"; var filePath = Path.Combine(_cacheDirectory.FullName, fileName); return(new FileInfo(filePath)); } } }
public CSharpRazorBuildProvider() { this.compilerType = this.GetDefaultCompilerTypeForLanguage("C#"); this.host = new RazorEngineHost(new CSharpRazorCodeLanguage()); }
public MinifyHtmlCSharpCodeGenerator(MinifyHtmlCodeGenerator generator, string className, string rootNamespaceName, string sourceFileName, RazorEngineHost host) : base(className, rootNamespaceName, sourceFileName, host) { _generator = generator; }
public CodeGeneratorReplacingHost(RazorEngineHost originalHost) : base(new CSharpRazorCodeLanguage()) { GeneratedClassContext = originalHost.GeneratedClassContext; }
public BackgroundThread(MainThreadState main, RazorEngineHost host, string fileName) { // Run on MAIN thread! _main = main; _backgroundThread = new Thread(WorkerLoop); _shutdownToken = _main.CancelToken; _host = host; _fileName = fileName; SetThreadId(_backgroundThread.ManagedThreadId); }
public override RazorCodeGenerator CreateCodeGenerator(string className, string rootNamespaceName, string sourceFileName, RazorEngineHost host) { return(new VisualBasicCodeGenerator(className, rootNamespaceName, sourceFileName, host, _throwExceptionOnParserError)); }
/// <summary> /// Generates code for a razor template in the specified namespace. /// </summary> /// <param name="cshtmlFilePath">Full path to razor template.</param> public void Compile(string cshtmlFilePath) { var basePath = Path.GetDirectoryName(cshtmlFilePath); if (Path.IsPathRooted(basePath)) { throw new ArgumentException(".cshtml path must be relative"); } if (basePath.Contains(".")) { throw new ArgumentException(".cshtml path must not contain '.'"); } var fileName = Path.GetFileName(cshtmlFilePath); var fileNameNoExtension = Path.GetFileNameWithoutExtension(fileName); var targetFileName = Path.Combine(TargetDirectory, $"{cshtmlFilePath}.cs"); System.Console.WriteLine(targetFileName); var fullNamespace = $"{Namespace}.{basePath.Replace('/', '.').Replace('\\', '.')}"; if (File.Exists(targetFileName) && File.GetLastWriteTimeUtc(targetFileName) >= File.GetLastWriteTimeUtc(cshtmlFilePath)) { return; } var codeLang = new CSharpRazorCodeLanguage(); var host = new RazorEngineHost(codeLang); host.GeneratedClassContext = new GeneratedClassContext( executeMethodName: GeneratedClassContext.DefaultExecuteMethodName, writeMethodName: GeneratedClassContext.DefaultWriteMethodName, writeLiteralMethodName: GeneratedClassContext.DefaultWriteLiteralMethodName, writeToMethodName: "WriteTo", writeLiteralToMethodName: "WriteLiteralTo", templateTypeName: "HelperResult", defineSectionMethodName: "DefineSection", generatedTagHelperContext: new GeneratedTagHelperContext()); var engine = new RazorTemplateEngine(host); var file = File.ReadAllText(cshtmlFilePath); file = file.Replace("<exception", "«exception"); using (var fileStream = new StringReader(file)) { var code = engine.GenerateCode( input: fileStream, className: fileNameNoExtension, rootNamespace: fullNamespace, sourceFileName: fileName); var source = code.GeneratedCode; source = source.Replace("«exception", "<exception"); source = CopyrightHeader + "\r\n\r\n" + source; var startIndex = 0; while (startIndex < source.Length) { var startMatch = @"<%$ include: "; var endMatch = @" %>"; startIndex = source.IndexOf(startMatch, startIndex); if (startIndex == -1) { break; } var endIndex = source.IndexOf(endMatch, startIndex); if (endIndex == -1) { break; } var includeFileName = source.Substring(startIndex + startMatch.Length, endIndex - (startIndex + startMatch.Length)); var replacement = File.ReadAllText(Path.Combine(basePath, includeFileName)) .Replace("\"", "\\\"") .Replace("\r\n", "\\r\\n"); source = source.Substring(0, startIndex) + replacement + source.Substring(endIndex + endMatch.Length); startIndex = startIndex + replacement.Length; } if (File.Exists(targetFileName)) { var oldFile = File.ReadAllText(targetFileName); if (oldFile == source) { return; } } Directory.CreateDirectory(Path.GetDirectoryName(targetFileName)); File.WriteAllText(targetFileName, source); } }
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); }
public string GenerateCode(string templateText, out GeneratorResults results, RazorEngineHost host = null) { using (var writer = new StringWriter()) { results = GenerateCode(templateText, writer, host); return(writer.GetStringBuilder().ToString()); } }
/// <summary> /// Initializes a new instance of the <see cref="NancyCSharpRazorBuildProvider"/> class. /// </summary> /// <param name="assemblyCatalog"></param> public NancyVisualBasicRazorBuildProvider(IAssemblyCatalog assemblyCatalog) { this.compilerType = this.GetDefaultCompilerTypeForLanguage("VB"); this.host = new NancyRazorEngineHost(new VBRazorCodeLanguage(), assemblyCatalog); }
public RazevolutionPaddingBuilder(RazorEngineHost host) { _host = host; }
public GeneratorResults GenerateCode(string templateText, TextWriter codeWriter, RazorEngineHost host = null) { Log.Info("Generating code..."); host = host ?? RazorEngineHostFactory(CompilationParameters.Language); var engine = new RazorTemplateEngine(host); var results = engine.GenerateCode(templateText.ToTextReader()); if (codeWriter == null) { Log.Debug("No code writer provided -- skipping primary language code generation"); } else { var codeProvider = CompilationParameters.CodeProvider; var generatedCode = results.GeneratedCode; Log.Debug("CodeProvider.GenerateCodeFromCompileUnit()..."); codeProvider.GenerateCodeFromCompileUnit(generatedCode, codeWriter, CodeGeneratorOptions); } return(results); }
public RewritingRazorTemplateEngine(RazorEngineHost host, params ISyntaxTreeRewriter[] rewriters) : base(host) { this.Rewriters = rewriters; }
public CSharpRazorCodeGenerator(string className, string rootNamespaceName, string sourceFileName, RazorEngineHost host) : base(className, rootNamespaceName, sourceFileName, host) { }
public async Task Go() { // Roslyn! var ws = MSBuildWorkspace.Create(); // Store the translation keys... List <string> used = new List <string>(); List <string> delete = new List <string>(); string solutionRoot = @"C:\_Code\PathToProject\"; string sln = solutionRoot + "MySolution.sln"; // Load the solution, and find all the cshtml Razor views... var solution = await ws.OpenSolutionAsync(sln); var mainProj = solution.Projects.Where(x => x.Name == "ConsumerWeb").Single(); FileInfo[] cshtmls = new DirectoryInfo(solutionRoot).GetFiles("*.cshtml", SearchOption.AllDirectories); // Go through each Razor View - generate the equivalent CS and add to the project for compilation. var host = new RazorEngineHost(RazorCodeLanguage.Languages["cshtml"]); var razor = new RazorTemplateEngine(host); var cs = new CSharpCodeProvider(); var csOptions = new CodeGeneratorOptions(); foreach (var cshtml in cshtmls) { using (StreamReader re = new StreamReader(cshtml.FullName)) { try { // Let Razor do it's thang... var compileUnit = razor.GenerateCode(re).GeneratedCode; // Pull the code into a stringbuilder, and append to the main project: StringBuilder sb = new StringBuilder(); using (StringWriter rw = new StringWriter(sb)) { cs.GenerateCodeFromCompileUnit(compileUnit, rw, csOptions); } // Get the new immutable project var doc = mainProj.AddDocument(cshtml.Name + ".cs", sb.ToString()); mainProj = doc.Project; } catch (Exception ex) { Console.WriteLine("Compile fail for: {0}", cshtml.Name); // throw; } continue; } } // We now have a new immutable solution, as we have changed the project instance... solution = mainProj.Solution; // Pull out our application translation list (its in a static class called 'CMS'): var mainCompile = await mainProj.GetCompilationAsync(); var mainModel = mainCompile.GetTypeByMetadataName("Resources.CMS"); var translations = mainModel.GetMembers().Where(x => x.Kind == SymbolKind.Property).ToList(); foreach (var translation in translations) { var references = await SymbolFinder.FindReferencesAsync(translation, solution); if (!references.First().Locations.Any()) { Console.WriteLine("{0} translation is not used!", translation.Name); delete.Add(translation.Name); } else { Console.WriteLine("{0} :in: {1}", translation.Name, references.First().Locations.First().Document.Name); used.Add(translation.Name); } } Console.WriteLine(); Console.WriteLine("Used references {0}. Unused references: {1}", used.Count, delete.Count); return; }
public void RawRazorTest() { string generatedNamespace = "__RazorHosting"; string generatedClassname = "RazorTest"; Type baseClassType = typeof(RazorTemplateBase); // Create an instance of the Razor Engine for a given // template type RazorEngineHost host = new RazorEngineHost(new CSharpRazorCodeLanguage()); host.DefaultBaseClass = baseClassType.FullName; host.DefaultClassName = generatedClassname; host.DefaultNamespace = generatedNamespace; host.NamespaceImports.Add("System"); host.NamespaceImports.Add("System.Text"); host.NamespaceImports.Add("System.Collections.Generic"); host.NamespaceImports.Add("System.Linq"); host.NamespaceImports.Add("System.IO"); // add the library namespace host.NamespaceImports.Add("Westwind.RazorHosting"); var engine = new RazorTemplateEngine(host); // Create and compile Code from the template var reader = new StringReader(Templates.BasicTemplateStringWithPersonModel); // Generate the template class as CodeDom from reader GeneratorResults razorResults = engine.GenerateCode(reader); // Create code from the codeDom and compile CSharpCodeProvider codeProvider = new CSharpCodeProvider(); CodeGeneratorOptions options = new CodeGeneratorOptions(); // Capture Code Generated as a string for error info // and debugging string LastGeneratedCode = null; using (StringWriter writer = new StringWriter()) { codeProvider.GenerateCodeFromCompileUnit(razorResults.GeneratedCode, writer, options); LastGeneratedCode = writer.ToString(); } CompilerParameters compilerParameters = new CompilerParameters(); // Always add Standard Assembly References compilerParameters.ReferencedAssemblies.Add("System.dll"); compilerParameters.ReferencedAssemblies.Add("System.Core.dll"); compilerParameters.ReferencedAssemblies.Add("Microsoft.CSharp.dll"); // dynamic support! compilerParameters.ReferencedAssemblies.Add("System.Web.Razor.dll"); // Must add Razorhosting or whatever assembly holds the template // engine can do this automatically but here we have to do manually compilerParameters.ReferencedAssemblies.Add("Westwind.RazorHosting.dll"); // Add this assembly so model can be found var razorAssembly = Assembly.GetExecutingAssembly().Location; compilerParameters.ReferencedAssemblies.Add(razorAssembly); compilerParameters.GenerateInMemory = true; CompilerResults compilerResults = codeProvider.CompileAssemblyFromDom(compilerParameters, razorResults.GeneratedCode); if (compilerResults.Errors.HasErrors) { var compileErrors = new StringBuilder(); foreach (System.CodeDom.Compiler.CompilerError compileError in compilerResults.Errors) { compileErrors.Append(String.Format("Line: {0}\t Col: {1}\t Error: {2}", compileError.Line, compileError.Column, compileError.ErrorText)); } Assert.Fail(compileErrors.ToString()); } string name = compilerResults.CompiledAssembly.FullName; // Instantiate the template Assembly generatedAssembly = compilerResults.CompiledAssembly; if (generatedAssembly == null) { Assert.Fail("Assembly generation failed."); } // find the generated type to instantiate Type type = null; var types = generatedAssembly.GetTypes() as Type[]; // there's only 1 per razor assembly if (types.Length > 0) { type = types[0]; } object inst = Activator.CreateInstance(type); RazorTemplateBase instance = inst as RazorTemplateBase; if (instance == null) { Assert.Fail("Couldn't activate template: " + type.FullName); return; } // Configure the instance StringWriter outputWriter = new StringWriter(); // Template contains a Response object that writes to the writer instance.Response.SetTextWriter(outputWriter); Person person = new Person() { Name = "Rick Strahl", Company = "West Wind", Entered = DateTime.Now, Address = new Address() { Street = "50 HoHaia", City = "Paia" } }; // Configure the instance with model and // other configuration data // instance.Model = person; instance.InitializeTemplate(person); // Execute the template and clean up instance.Execute(); // template can set its ResultData property to pass data // back to the caller dynamic resultData = instance.ResultData; instance.Dispose(); // read the result from the writer passed in var result = outputWriter.ToString(); Console.WriteLine(result); Console.WriteLine("\r\nResultData: " + resultData.ToString()); }
private Task <Stream> RazorWorker(RazorEngineHost host, TextAndVersion originalText) => RazorWorkerImpl(host, originalText).ContinueWith(x => x.Result.result, TaskContinuationOptions.OnlyOnRanToCompletion);
/// <summary> /// Initializes a new instance of the <see cref="CSharpRazorCodeGenerator"/> class. /// </summary> /// <param name="className">Name of the class.</param> /// <param name="rootNamespaceName">Name of the root namespace.</param> /// <param name="sourceFileName">Name of the source file.</param> /// <param name="host">The host.</param> /// <param name="strictMode">Flag to specify that this generator is running in struct mode.</param> public CSharpRazorCodeGenerator(string className, string rootNamespaceName, string sourceFileName, RazorEngineHost host, bool strictMode) : base(className, rootNamespaceName, sourceFileName, host) { StrictMode = strictMode; var mvcHost = host as Compilation.RazorEngineHost; if (mvcHost != null) { // set the default model type to "dynamic" SetBaseType("dynamic"); } }
public CSharpPaddingBuilder(RazorEngineHost host) { _host = host; }
/// <summary> /// Gets the generator result. /// </summary> /// <param name="host">The razor engine host.</param> /// <param name="template">The template.</param> /// <returns>The generator result.</returns> private static GeneratorResults GetGeneratorResult(RazorEngineHost host, string template) { var engine = new RazorTemplateEngine(host); GeneratorResults result; using (var reader = new StringReader(template)) result = engine.GenerateCode(reader); return result; }
/// <summary> /// Initializes a new instance of the <see cref="NancyCSharpRazorCodeGenerator"/> class. /// </summary> /// <param name="className">Name of the class.</param> /// <param name="rootNamespaceName">Name of the root namespace.</param> /// <param name="sourceFileName">Name of the source file.</param> /// <param name="host">The host.</param> public NancyCSharpRazorCodeGenerator(string className, string rootNamespaceName, string sourceFileName, RazorEngineHost host) : base(className, rootNamespaceName, sourceFileName, host) { SetBaseType(DEFAULT_MODEL_TYPE_NAME); }
private void RunTestInternal(string name, string baselineName, bool generatePragmas, bool designTimeMode, IList <GeneratedCodeMapping> expectedDesignTimePragmas, TestSpan[] spans, bool withTabs, Action <RazorEngineHost> hostConfig) { // 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); } host.IsIndentingWithTabs = withTabs; 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())); #if !GENERATE_BASELINES string textOutput = MiscUtils.StripRuntimeVersion(output.ToString()); //// 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); Assert.Equal( expectedDesignTimePragmas.ToArray(), results.DesignTimeLineMappings .OrderBy(p => p.Key) .Select(p => p.Value) .ToArray()); } } }
private RazorEngineHost CreateHost(Type templateType, Type modelType, string className) { var host = new RazorEngineHost(CodeLanguage, MarkupParserFactory.Create) { DefaultBaseTemplateType = templateType, DefaultModelType = modelType, DefaultBaseClass = BuildTypeName(templateType, modelType), DefaultClassName = className, DefaultNamespace = DynamicTemplateNamespace, GeneratedClassContext = new GeneratedClassContext( "Execute", "Write", "WriteLiteral", "WriteTo", "WriteLiteralTo", "RazorEngine.Templating.TemplateWriter", "DefineSection" #if RAZOR4 , new GeneratedTagHelperContext() #endif ) #if !RAZOR4 { ResolveUrlMethodName = "ResolveUrl" } #endif }; return host; }
/// <summary> /// Initializes a new instance of the <see cref="VBRazorCodeGenerator"/> class. /// </summary> /// <param name="className">Name of the class.</param> /// <param name="rootNamespaceName">Name of the root namespace.</param> /// <param name="sourceFileName">Name of the source file.</param> /// <param name="host">The host.</param> /// <param name="strictMode">Flag to specify that this generator is running in struct mode.</param> public VBRazorCodeGenerator(string className, string rootNamespaceName, string sourceFileName, RazorEngineHost host, bool strictMode) : base(className, rootNamespaceName, sourceFileName, host) { StrictMode = strictMode; }
public CodeBuilderReplacingHost(RazorEngineHost originalHost) : base(new CSharpRazorCodeLanguage()) { GeneratedClassContext = originalHost.GeneratedClassContext; }
public override RazorChunkGenerator CreateChunkGenerator(string className, string rootNamespaceName, string sourceFileName, RazorEngineHost host)
/// <summary> /// Creates a code generator. /// </summary> /// <param name="className">The name of the generated class.</param> /// <param name="rootNamespaceName">The namespace of the generated class.</param> /// <param name="sourceFileName">The source file filename.</param> /// <param name="host">The <see cref="RazorEngineHost"/> instance.</param> /// <returns>A new instance of <see cref="RazorCodeGenerator"/>.</returns> public override RazorCodeGenerator CreateCodeGenerator(string className, string rootNamespaceName, string sourceFileName, RazorEngineHost host) { return new CSharpRazorCodeGenerator(className, rootNamespaceName, sourceFileName, host); }
public override RazorCodeGenerator CreateCodeGenerator(string className, string rootNamespaceName, string sourceFileName, RazorEngineHost host) #endif { return(new CSharpRazorCodeGenerator(className, rootNamespaceName, sourceFileName, host, StrictMode)); }
private static void VerifyCommonDefaults(RazorEngineHost host) { Assert.AreEqual(GeneratedClassContext.Default, host.GeneratedClassContext); Assert.AreEqual(0, host.NamespaceImports.Count); Assert.IsFalse(host.DesignTimeMode); Assert.AreEqual(RazorEngineHost.InternalDefaultClassName, host.DefaultClassName); Assert.AreEqual(RazorEngineHost.InternalDefaultNamespace, host.DefaultNamespace); }
public static string Pad(RazorEngineHost host, string code, Span target, int generatedStart, out int paddingCharCount) { int padding = CalculatePadding(host, target, generatedStart); return(PadInternal(host, code, padding, out paddingCharCount)); }
public MvcCSharpRazorCodeGenerator(string className, string rootNamespaceName, string sourceFileName, RazorEngineHost host) : base(className, rootNamespaceName, sourceFileName, host) { var mvcHost = host as MvcWebPageRazorHost; if (mvcHost != null && !mvcHost.IsSpecialPage) { // set the default model type to "dynamic" (Dev10 bug 935656) // don't set it for "special" pages (such as "_viewStart.cshtml") SetBaseType(DefaultModelTypeName); } }
public MinifyingCSharpRazorCodeGenerator(string className, string rootNamespaceName, string sourceFileName, RazorEngineHost host) : base(className, rootNamespaceName, sourceFileName, host) { }
/// <summary> /// Creates a <see cref="RazorEngineHost"/> used for class generation. /// </summary> /// <param name="templateType">The template base type.</param> /// <param name="modelType">The model type.</param> /// <param name="className">The class name.</param> /// <returns>An instance of <see cref="RazorEngineHost"/>.</returns> private RazorEngineHost CreateHost(Type templateType, Type modelType, string className) { var host = new RazorEngineHost(CodeLanguage, MarkupParserFactory) { DefaultBaseTemplateType = templateType, DefaultBaseClass = BuildTypeName(templateType, modelType), DefaultClassName = className, DefaultNamespace = "CompiledRazorTemplates.Dynamic", GeneratedClassContext = new GeneratedClassContext("Execute", "Write", "WriteLiteral", "WriteTo", "WriteLiteralTo", "RazorEngine.Templating.TemplateWriter", "DefineSection") }; return host; }
public static CodeGeneratorContext Create(RazorEngineHost host, string className, string rootNamespace, string sourceFile, bool shouldGenerateLinePragmas) { return(Create(host, null, className, rootNamespace, sourceFile, shouldGenerateLinePragmas)); }