Beispiel #1
0
        public RazorCSharp Generate(string path)
        {
            var razor  = _templateEngine.CreateCodeDocument(path);
            var csharp = _templateEngine.GenerateCode(razor);

            return(new RazorCSharp(csharp, _compilationOptions, _references, _emitOptions));
        }
Beispiel #2
0
        public void ModelVisitor_GeneratesCorrectLineMappings()
        {
            // Arrange
            var host = new MvcRazorHost(new TestFileSystem())
            {
                DesignTimeMode = true
            };

            host.NamespaceImports.Clear();
            var engine               = new RazorTemplateEngine(host);
            var source               = ReadResource("TestFiles/Input/Model.cshtml");
            var expectedCode         = ReadResource("TestFiles/Output/Model.cs");
            var expectedLineMappings = new List <LineMapping>
            {
                BuildLineMapping(7, 0, 7, 151, 6, 7, 30),
            };

            // Act
            GeneratorResults results;

            using (var buffer = new StringTextBuffer(source))
            {
                results = engine.GenerateCode(buffer);
            }

            // Assert
            Assert.True(results.Success);
            Assert.Equal(expectedCode, results.GeneratedCode);
            Assert.Empty(results.ParserErrors);
            Assert.Equal(expectedLineMappings, results.DesignTimeLineMappings);
        }
Beispiel #3
0
        public RazorTemplateBase GetCompiledTemplate(string content)
        {
            RazorTemplatingHost host   = new RazorTemplatingHost(typeof(RazorTemplateBase));
            RazorTemplateEngine engine = new RazorTemplateEngine(host);

            using (var reader = new StringReader(content))
            {
                var generatorResults = engine.GenerateCode(reader);
                if (!generatorResults.Success)
                {
                    using (var newReader = new StringReader(content))
                    {
                        var readerText = newReader.ReadToEnd();
                        File.WriteAllText("c:\\temp\\badreader.txt", readerText);
                    }
                    return(null);
                }

                var templateResult = Compile(generatorResults.GeneratedCode);
                if (templateResult.Messages.Any())
                {
                    File.WriteAllText("c:\\temp\\badtemplate.txt", generatorResults.GeneratedCode);
                    return(null);
                }

                var compiledObject = Activator.CreateInstance(templateResult.CompiledType);
                var razorTemplate  = compiledObject as RazorTemplateBase;

                return(razorTemplate);
            }
        }
        private void EnsureGeneratedCode()
        {
            if (_generatedCode == null)
            {
                RazorTemplateEngine engine  = new RazorTemplateEngine(Host);
                GeneratorResults    results = null;
                using (TextReader reader = InternalOpenReader())
                {
                    results = engine.GenerateCode(
                        reader,
                        className: null,
                        rootNamespace: null,
                        sourceFileName: Host.PhysicalPath
                        );
                }
                if (!results.Success)
                {
                    throw CreateExceptionFromParserError(results.ParserErrors.Last(), VirtualPath);
                }
                _generatedCode = results.GeneratedCode;

                // Run the code gen complete event
                OnCodeGenerationCompleted(_generatedCode);
            }
        }
Beispiel #5
0
        protected virtual Assembly GenerateAssembly(params KeyValuePair <string, string>[] templates)
        {
            var assemblyName = NamespaceName + "." + Guid.NewGuid().ToString("N") + ".dll";

            var templateResults = templates.Select(pair => razorEngine.GenerateCode(new StringReader(pair.Value), pair.Key, NamespaceName, pair.Key + ".cs")).ToList();

            if (templateResults.Any(result => result.ParserErrors.Any()))
            {
                var parseExceptionMessage = string.Join(Environment.NewLine + Environment.NewLine, templateResults.SelectMany(r => r.ParserErrors).Select(e => e.Location + ":" + Environment.NewLine + e.Message).ToArray());

                throw new InvalidOperationException(parseExceptionMessage);
            }

            using (var codeProvider = new CSharpCodeProvider())
            {
                var compilerParameter = new CompilerParameters(referencedAssemblies, assemblyName, false)
                {
                    GenerateInMemory = true,
                    CompilerOptions  = "/optimize"
                };

                var compilerResults = codeProvider.CompileAssemblyFromDom(compilerParameter, templateResults.Select(r => r.GeneratedCode).ToArray());

                if (compilerResults.Errors.HasErrors)
                {
                    var compileExceptionMessage = string.Join(Environment.NewLine + Environment.NewLine, compilerResults.Errors.OfType <CompilerError>().Where(ce => !ce.IsWarning).Select(e => e.FileName + ":" + Environment.NewLine + e.ErrorText).ToArray());

                    throw new InvalidOperationException(compileExceptionMessage);
                }

                return(compilerResults.CompiledAssembly);
            }
        }
Beispiel #6
0
        private static Type InitializeTemplateType(string templateKey)
        {
            // Generate code for the template
            GeneratorResults razorResult;
            var baseDirectory = AppDomain.CurrentDomain.BaseDirectory;

            var fileName = string.Format(@"Templates\{0}.cshtml", templateKey);

            // try to find the file in the local templates folder and fall back to bin folder if can't find anything
            // this is because Web hosts have the base directory as the vroot dir whereas console hosts will have the base directory == bin folder
            var fullPath = Path.Combine(baseDirectory, fileName);

            if (!File.Exists(fullPath))
            {
                fullPath = Path.Combine(baseDirectory, "bin", fileName);
                if (!File.Exists(fullPath))
                {
                    throw new FileNotFoundException(string.Format("Razor template '{0}' was not found.", fullPath));
                }
            }

            var templateText = File.ReadAllText(fullPath);

            using (TextReader rdr = new StringReader(templateText))
            {
                razorResult = Engine.GenerateCode(rdr);
            }

            var codeProvider = new CSharpCodeProvider();

            using (var sw = new StringWriter())
            {
                codeProvider.GenerateCodeFromCompileUnit(razorResult.GeneratedCode, sw, new CodeGeneratorOptions());
            }

            // Compile the generated code into an assembly
            string outputAssemblyName = Path.Combine(baseDirectory, String.Format("Temp_{0}.dll", Guid.NewGuid().ToString("N")));
            var    compilerParameters = new CompilerParameters(new[] { typeof(TemplateEngine).Assembly.CodeBase.Replace("file:///", "").Replace("/", "\\") }, outputAssemblyName);

            compilerParameters.ReferencedAssemblies.Add("System.Core.dll");
            compilerParameters.ReferencedAssemblies.Add("Microsoft.CSharp.dll"); //<- needed to bind to dynamic type

            CompilerResults results = codeProvider.CompileAssemblyFromDom(compilerParameters, razorResult.GeneratedCode);

            if (results.Errors.HasErrors)
            {
                CompilerError err = results.Errors.OfType <CompilerError>().Where(ce => !ce.IsWarning).First();
                throw new InvalidOperationException(string.Format("Error Compiling Template: ({0}, {1}) {2}", err.Line, err.Column, err.ErrorText));
            }

            // Load the assembly
            Assembly asm = Assembly.LoadFrom(outputAssemblyName);

            if (asm == null)
            {
                throw new InvalidOperationException("Error loading template assembly");
            }
            // Get the template type
            return(asm.GetType("RazorOutput.Template"));
        }
        private async Task <CompilationResult> CompileCore(IFileInfo file)
        {
            var host   = new MvcRazorHost();
            var engine = new RazorTemplateEngine(host);
            GeneratorResults results;

            using (TextReader rdr = new StreamReader(file.CreateReadStream()))
            {
                results = engine.GenerateCode(rdr, '_' + Path.GetFileNameWithoutExtension(file.Name), "Asp", file.PhysicalPath ?? file.Name);
            }

            string generatedCode;

            using (var writer = new StringWriter())
                using (var codeProvider = new CSharpCodeProvider())
                {
                    codeProvider.GenerateCodeFromCompileUnit(results.GeneratedCode, writer, new CodeGeneratorOptions());
                    generatedCode = writer.ToString();
                }

            if (!results.Success)
            {
                return(CompilationResult.Failed(generatedCode, results.ParserErrors.Select(e => new CompilationMessage(e.Message))));
            }

            Directory.CreateDirectory(_tempPath);
            string tempFile = Path.Combine(_tempPath, Path.GetRandomFileName() + ".cs");

            File.WriteAllText(tempFile, generatedCode);

            _tempFileSystem.TryGetFileInfo(tempFile, out file);
            return(await _baseCompilationService.Compile(file));
        }
Beispiel #8
0
        string getCSharpCode(string cshtmlFilePath, string rootNamespace)
        {
            var basePath            = Path.GetDirectoryName(cshtmlFilePath);
            var fileName            = Path.GetFileName(cshtmlFilePath);
            var fileNameNoExtension = Path.GetFileNameWithoutExtension(fileName);
            var codeLang            = new CSharpRazorCodeLanguage();
            var host = new RazorEngineHost(codeLang);

            host.DefaultBaseClass      = "TchApp.Razor.TchRazorPage";
            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 cshtmlContent = File.ReadAllText(cshtmlFilePath);

            var generatorResults = engine.GenerateCode(
                input: new StringReader(cshtmlContent),
                className: fileNameNoExtension,
                rootNamespace: Path.GetFileName(rootNamespace),
                sourceFileName: fileName);

            var generatedCode = generatorResults.GeneratedCode;

            return(generatedCode);
        }
        private static GeneratorResults GenerateCode <TModel>(string classFullName, string template, IEnumerable <string> additionalNamespaceImports)
        {
            var    lastIndexOf    = classFullName.LastIndexOf('.');
            string classNamespace = classFullName.Substring(0, lastIndexOf);
            string className      = classFullName.Substring(lastIndexOf + 1);

            var language = new CSharpRazorCodeLanguage();
            var host     = new RazorEngineHost(language)
            {
                DefaultBaseClass = typeof(RazorGeneratorBase <TModel>).FullName,
                DefaultClassName = className,
                DefaultNamespace = classNamespace,
            };

            host.NamespaceImports.Add("System");
            host.NamespaceImports.Add("System.Dynamic");
            host.NamespaceImports.Add("System.Text");
            host.NamespaceImports.Add("System.Linq");
            host.NamespaceImports.Add(typeof(TModel).Namespace ?? throw new InvalidOperationException());
            if (additionalNamespaceImports != null)
            {
                foreach (var additionalNamespaceImport in additionalNamespaceImports)
                {
                    host.NamespaceImports.Add(additionalNamespaceImport);
                }
            }
            var engine = new RazorTemplateEngine(host);

            var tr = new StringReader(template); // here is where the string come in place
            GeneratorResults razorTemplate = engine.GenerateCode(tr);

            return(razorTemplate);
        }
Beispiel #10
0
            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);
                }
            }
Beispiel #11
0
        private Task <(bool success, Stream result)> RazorWorkerImpl(RazorEngineHost host, TextAndVersion originalText)
        {
            var success         = true;
            var generatedStream = new MemoryStream(capacity: originalText.Text.Length * 8); // generated .cs files contain a lot of additional crap vs actualy cshtml
            var viewFullPath    = originalText.FilePath;

            using (var sourceReader = new StreamReader(generatedStream, originalText.Text.Encoding, false, 4096, leaveOpen: true))
                using (var provider = CodeDomProvider.CreateProvider("csharp"))
                    using (var generatedWriter = new StreamWriter(generatedStream, originalText.Text.Encoding, 4096, leaveOpen: true))
                    {
                        // write cshtml into generated stream and rewind
                        originalText.Text.Write(generatedWriter);
                        generatedWriter.Flush();
                        generatedStream.Position = 0;

                        // generated code and clear memory stream
                        var engine   = new RazorTemplateEngine(host);
                        var razorOut = engine.GenerateCode(sourceReader, null, null, viewFullPath);

                        if (!razorOut.Success)
                        {
                            success = false;
                            foreach (var error in razorOut.ParserErrors)
                            {
                                var position = new LinePosition(error.Location.LineIndex, error.Location.CharacterIndex - 1);
                                ReportDiagnostic(Diagnostic.Create(
                                                     Compilation.RazorParserError,
                                                     Location.Create(
                                                         originalText.FilePath,
                                                         new TextSpan(error.Location.AbsoluteIndex, error.Length),
                                                         new LinePositionSpan(position, position)),
                                                     error.Message));
                            }
                        }

                        // add the CompiledFromFileAttribute to the generated class
                        razorOut.GeneratedCode
                        .Namespaces.OfType <CodeNamespace>().FirstOrDefault()?
                        .Types.OfType <CodeTypeDeclaration>().FirstOrDefault()?
                        .CustomAttributes.Add(
                            new CodeAttributeDeclaration(
                                new CodeTypeReference(typeof(CompiledFromFileAttribute)),
                                new CodeAttributeArgument(new CodePrimitiveExpression(viewFullPath))
                                ));

                        // reuse the memory stream for code generation
                        generatedStream.Position = 0;
                        generatedStream.SetLength(0);
                        var codeGenOptions = new CodeGeneratorOptions {
                            VerbatimOrder = true, ElseOnClosing = false, BlankLinesBetweenMembers = false
                        };
                        provider.GenerateCodeFromCompileUnit(razorOut.GeneratedCode, generatedWriter, codeGenOptions);

                        // rewind
                        generatedWriter.Flush();
                        generatedStream.Position = 0;
                    }

            return(Task.FromResult((success: success, stream: (Stream)generatedStream)));
        }
Beispiel #12
0
        public void GenerateCodeWithConfigureClass()
        {
            // Arrange
            var filePath    = Path.Combine(TestProjectRoot, $"{FileName}.cshtml");
            var content     = File.ReadAllText(filePath);
            var projectItem = new TestRazorProjectItem($"{FileName}.cshtml", "")
            {
                Content = content,
            };
            var project     = new TestRazorProject(new[] { projectItem });
            var razorEngine = RazorEngine.Create(engine =>
            {
                engine.ConfigureClass((document, @class) =>
                {
                    @class.ClassName = "MyClass";

                    @class.Modifiers.Clear();
                    @class.Modifiers.Add("protected");
                    @class.Modifiers.Add("internal");
                });

                engine.ConfigureClass((document, @class) =>
                {
                    @class.Interfaces = new[] { "global::System.IDisposable" };
                    @class.BaseType   = "CustomBaseType";
                });
            });
            var templateEngine = new RazorTemplateEngine(razorEngine, project);

            // Act
            var cSharpDocument = templateEngine.GenerateCode(projectItem.FilePath);

            // Assert
            AssertCSharpDocumentMatchesBaseline(cSharpDocument);
        }
        public static ParsedTemplate parse(string sourceFilename, string cshtmlContent, string effectiveTemplateClassName, Type modelType)
        {
            var csCodeLanguage = new CSharpRazorCodeLanguage();
            var templateHost   = new RazorEngineHost(csCodeLanguage, () => new HtmlMarkupParser());

            var concreteBaseClassType = getBaseClassTypeFromModel(modelType);

            templateHost.DefaultBaseClass = concreteBaseClassType.FullName;

            var templateEngine = new RazorTemplateEngine(templateHost);

            var trimmedcshtmlContent = HeaderLines.trim(cshtmlContent);

            GeneratorResults res;

            using (var input = new StringReader(trimmedcshtmlContent))
            {
                res = templateEngine.GenerateCode(input, effectiveTemplateClassName, GeneratedTemplateNamespace, sourceFilename);
            }

            if (!res.Success)
            {
                throw new Exception("Failed to generate code");
            }

            var compileUnit             = res.GeneratedCode;
            var fullyQualifiedClassName = GeneratedTemplateNamespace + "." + effectiveTemplateClassName;

            return(new ParsedTemplate(fullyQualifiedClassName, compileUnit));
        }
        static void Main(string[] args)
        {
            // customize the default engine a little bit
            var engine = RazorEngine.Create(b =>
            {
                InheritsDirective.Register(b);     // make sure the engine understand the @inherits directive in the input templates
                b.SetNamespace("MyNamespace");     // define a namespace for the Template class
                b.Build();
            });
            // points to the local path
            var project = RazorProject.Create(".");
            var te      = new RazorTemplateEngine(engine, project);
            // get a razor-templated file. My "hello.txt" template file is defined like this:
            //
            // @inherits RazorTemplate.MyTemplate
            // Hello @Model.Name, welcome to Razor World!
            //
            var item = project.GetItem("hello.txt");
            // parse and generate C# code, outputs it on the console
            var cs = te.GenerateCode(item);

            Console.WriteLine(cs.GeneratedCode);
            // now, use roslyn, parse the C# code
            var tree = CSharpSyntaxTree.ParseText(cs.GeneratedCode);
            // define the dll
            const string dllName     = "hello";
            var          compilation = CSharpCompilation.Create(dllName, new[] { tree },
                                                                new[]
Beispiel #15
0
        /// <inheritdoc />
        public GeneratorResults GenerateCode(string rootRelativePath, Stream inputStream)
        {
            var className = ParserHelpers.SanitizeClassName(rootRelativePath);
            var engine    = new RazorTemplateEngine(this);

            return(engine.GenerateCode(inputStream, className, DefaultNamespace, rootRelativePath));
        }
Beispiel #16
0
        public PreprocessResult PreprocessRazorTemplate(string content, string className, string classNamespace)
        {
            var language  = new CSharpRazorCodeLanguage();
            var razorHost = new RazorEngineHost(language)
            {
                DefaultBaseClass      = typeof(TemplateBase).FullName,
                DefaultNamespace      = classNamespace,
                DefaultClassName      = className,
                GeneratedClassContext = new GeneratedClassContext(
                    nameof(TemplateBase.ExecuteAsync),
                    nameof(TemplateBase.Write),
                    nameof(TemplateBase.WriteLiteral),
                    new GeneratedTagHelperContext())
            };

            razorHost.NamespaceImports.Add(classNamespace);

            var razorEngine      = new RazorTemplateEngine(razorHost);
            var generatorResults = razorEngine.GenerateCode(new StringReader(content));

            if (!generatorResults.Success)
            {
                throw new Exception(string.Join(Environment.NewLine, generatorResults.ParserErrors.Select(x => x.Message)));
            }

            var preprocessResult = new PreprocessResult()
            {
                PreprocessedContent = generatorResults.GeneratedCode,
                References          = _host.StandardImports.ToList(),
            };

            return(preprocessResult);
        }
        public void GenerateCodeWithConfigureClass()
        {
            // Arrange
            var project     = new FileSystemRazorProject(TestProjectRoot);
            var razorEngine = RazorEngine.Create(engine =>
            {
                engine.Features.Add(new SuppressChecksumOptionsFeature());

                engine.ConfigureClass((document, @class) =>
                {
                    @class.ClassName = "MyClass";

                    @class.Modifiers.Clear();
                    @class.Modifiers.Add("protected");
                    @class.Modifiers.Add("internal");
                });

                engine.ConfigureClass((document, @class) =>
                {
                    @class.Interfaces = new[] { "global::System.IDisposable" };
                    @class.BaseType   = "CustomBaseType";
                });
            });
            var templateEngine = new RazorTemplateEngine(razorEngine, project);

            // Act
            var cSharpDocument = templateEngine.GenerateCode($"{FileName}.cshtml");

            // Assert
            AssertCSharpDocumentMatchesBaseline(cSharpDocument);
        }
Beispiel #18
0
        private static string GetTemplateSourceCode <T>(string templatePath, string content)
        {
            // customize the default engine a little bit
            var engine = RazorEngine.Create(engineBuilder =>
            {
                InheritsDirective.Register(engineBuilder);
                engineBuilder.SetNamespace("MyNamespace");
                engineBuilder.Build();
            });

            // points to the local path
            var project = RazorProject.Create(".");
            var te      = new RazorTemplateEngine(engine, project);

            // get a razor-templated file. My "hello.txt" template file is defined like this:
            //
            // @inherits RazorTemplate.MyTemplate
            // Hello @Model.Name, welcome to Razor World!
            //
            StringBuilder builder = new StringBuilder();

            builder.AppendLine(String.Format("@inherits Developpez.MagazineTool.TemplateManager.Template<{0}>", typeof(T).FullName));
            builder.Append(content);
            RazorSourceDocument sourceDocument = RazorSourceDocument.Create(builder.ToString(), templatePath);
            RazorCodeDocument   codeDocument   = RazorCodeDocument.Create(sourceDocument);

            // parse and generate C# code, outputs it on the console

            //var cs = te.GenerateCode(item);
            var cs = te.GenerateCode(codeDocument);

            return(cs.GeneratedCode);
        }
Beispiel #19
0
        public GeneratorResults Generate(Type modelType, string template)
        {
            //准备临时类名,读取模板文件和Razor代码生成器
            string templateType = "YOYO.AspNetCore.ViewEngine.Razor.RazorViewTemplate";

            string templateTypeName = modelType != null?string.Format(templateType + @"<{0}>", modelType.FullName) : templateType;

            var class_name = "c" + Guid.NewGuid().ToString("N");
            var host       = new RazorEngineHost(new CSharpRazorCodeLanguage(), () => new HtmlMarkupParser())
            {
                DefaultBaseClass      = templateTypeName,
                DefaultClassName      = class_name,
                DefaultNamespace      = "YOYO.AspNetCore.ViewEngine.Razor",
                GeneratedClassContext =
                    new GeneratedClassContext("Execute", "Write", "WriteLiteral", "WriteTo",
                                              "WriteLiteralTo",
                                              "RazorViewTemplate.Dynamic", new GeneratedTagHelperContext())
            };

            host.NamespaceImports.Add("System");
            host.NamespaceImports.Add("System.Dynamic");
            host.NamespaceImports.Add("System.Linq");
            host.NamespaceImports.Add("System.Collections.Generic");

            var engine = new RazorTemplateEngine(host);

            return(engine.GenerateCode(new StringReader(template)));;
        }
Beispiel #20
0
        private Assembly CreateAssembly(string resourceName, string rootNamespace, string className, string content, out string generatedSource)
        {
            using (var codeProvider = CreateCodeProvider())
            {
                using (var stringReader = new StringReader(content)) {
                    var generatorResult = _razorEngine.GenerateCode(
                        stringReader,
                        className,
                        rootNamespace,
                        "{0}{1}".FormatWith(_sourceFilenamePrefix, resourceName)
                        );
                    generatedSource = _razorContext.Config.Templates.IncludeGeneratedSourceCode ? GenerateSourceCode(generatorResult.GeneratedCode) : null;

                    if (!CheckParseResults(resourceName, generatorResult, content))
                    {
                        return(null);
                    }


                    var compilerParameter = new CompilerParameters(_razorContext.Config.References.ToArray())
                    {
                        GenerateInMemory = true, CompilerOptions = "/optimize"
                    };

                    var compilerResults = codeProvider.CompileAssemblyFromDom(compilerParameter, generatorResult.GeneratedCode);

                    return(!CheckCompileResults(generatorResult, compilerResults, content, generatedSource) ? null : compilerResults.CompiledAssembly);
                }
            }
        }
        private static string GenerateCodeFromRazorString(WebPageRazorHost host, string razorString, string virtualPath)
        {
            // Create Razor engine and use it to generate a CodeCompileUnit
            var engine = new RazorTemplateEngine(host);
            GeneratorResults results = null;

            using (StringReader reader = new StringReader(razorString))
            {
                results = engine.GenerateCode(reader, className: null, rootNamespace: null,
                                              sourceFileName: host.PhysicalPath);
            }

            if (!results.Success)
            {
                throw CreateExceptionFromParserError(results.ParserErrors.Last(), virtualPath);
            }

            // Use CodeDom to generate source code from the CodeCompileUnit
            using (var codeDomProvider = new CSharpCodeProvider())
            {
                using (var srcFileWriter = new StringWriter())
                {
                    codeDomProvider.GenerateCodeFromCompileUnit(results.GeneratedCode, srcFileWriter,
                                                                new CodeGeneratorOptions());

                    return(srcFileWriter.ToString());
                }
            }
        }
        private static object Compile(string code, string name)
        {
            var cacheKey           = (name ?? DynamicallyGeneratedClassName) + GetHash(code);
            var generatedClassName = name != null?name.Strip(c => !c.IsLetter() && !Char.IsDigit(c)) : DynamicallyGeneratedClassName;

            Assembly assembly;

            if (_cache.TryGetValue(cacheKey, out assembly))
            {
                return(assembly.CreateInstance(NamespaceForDynamicClasses + "." + generatedClassName));
            }

            var language = new CSharpRazorCodeLanguage();
            var host     = new RazorEngineHost(language)
            {
                DefaultBaseClass = "RazorTemplateBase<dynamic>",
                DefaultClassName = generatedClassName,
                DefaultNamespace = NamespaceForDynamicClasses
            };

            foreach (var n in DefaultNamespaces)
            {
                host.NamespaceImports.Add(n);
            }

            var engine        = new RazorTemplateEngine(host);
            var razorTemplate = engine.GenerateCode(new StringReader(code));

            assembly = CreateCompiledAssemblyFor(razorTemplate.GeneratedCode, name);
            _cache.TryAdd(cacheKey, assembly);

            return(assembly.CreateInstance(NamespaceForDynamicClasses + "." + generatedClassName));
        }
        public GeneratorResults Generate()
        {
            lock (this)
            {
                _codeTransformer.Initialize(this, _directives);

                // Create the engine
                var engine = new RazorTemplateEngine(this);

                // Generate code
                GeneratorResults results = null;
                try
                {
                    using (var stream = File.OpenRead())
                    {
                        var reader = new StreamReader(stream, Encoding.Default, detectEncodingFromByteOrderMarks: true);
                        results = engine.GenerateCode(reader, className: DefaultClassName, rootNamespace: DefaultNamespace, sourceFileName: this.File.RealPath);
                    }
                }
                catch (Exception e)
                {
                    throw new HttpParseException(e.Message, e, GetAbsoluteErrorPath(this.File.VirtualPath), null, 1);
                }

                //Throw the first parser message to generate the YSOD
                //TODO: Is there a way to output all errors at once?
                if (results.ParserErrors.Count > 0)
                {
                    var error = results.ParserErrors[0];
                    throw new HttpParseException(error.Message, null, GetAbsoluteErrorPath(this.File.VirtualPath), null, error.Location.LineIndex + 1);
                }

                return(results);
            }
        }
        private string GenerateCodeFromRazorTemplate(WebPageRazorHost host, string virtualPath)
        {
            // Create Razor engine and use it to generate a CodeCompileUnit
            var engine = new RazorTemplateEngine(host);
            GeneratorResults results = null;
            VirtualFile      file    = HostingEnvironment.VirtualPathProvider.GetFile(virtualPath);

            using (var stream = file.Open())
            {
                using (TextReader reader = new StreamReader(stream))
                {
                    results = engine.GenerateCode(reader, className: null, rootNamespace: null, sourceFileName: host.PhysicalPath);
                }
            }

            if (!results.Success)
            {
                throw CreateExceptionFromParserError(results.ParserErrors.Last(), virtualPath);
            }

            // Use CodeDom to generate source code from the CodeCompileUnit
            var codeDomProvider = new CSharpCodeProvider();
            var srcFileWriter   = new StringWriter();

            codeDomProvider.GenerateCodeFromCompileUnit(results.GeneratedCode, srcFileWriter, new CodeGeneratorOptions());

            return(srcFileWriter.ToString());
        }
Beispiel #25
0
        public void InjectVisitorWithModel_GeneratesCorrectLineMappings()
        {
            // Arrange
            var host = new MvcRazorHost("RazorView")
            {
                DesignTimeMode = true
            };

            host.NamespaceImports.Clear();
            var engine               = new RazorTemplateEngine(host);
            var source               = ReadResource("TestFiles/Input/InjectWithModel.cshtml");
            var expectedCode         = ReadResource("TestFiles/Output/InjectWithModel.cs");
            var expectedLineMappings = new List <LineMapping>
            {
                BuildLineMapping(7, 0, 7, 126, 6, 7, 7),
                BuildLineMapping(24, 1, 8, 562, 26, 8, 20),
                BuildLineMapping(54, 2, 8, 732, 34, 8, 22)
            };

            // Act
            GeneratorResults results;

            using (var buffer = new StringTextBuffer(source))
            {
                results = engine.GenerateCode(buffer);
            }

            // Assert
            Assert.True(results.Success);
            Assert.Equal(expectedCode, results.GeneratedCode);
            Assert.Empty(results.ParserErrors);
            Assert.Equal(expectedLineMappings, results.DesignTimeLineMappings);
        }
        private CodeCompileUnit GetGeneratedCode()
        {
            try
            {
                if (this.generatedCode == null)
                {
                    var engine = new RazorTemplateEngine(this.host);
                    GeneratorResults results;
                    using (var reader = this.OpenReader())
                    {
                        results = engine.GenerateCode(reader);
                    }

                    if (!results.Success)
                    {
                        throw new InvalidOperationException(results.ToString());
                    }

                    this.generatedCode = results.GeneratedCode;
                }

                return(this.generatedCode);
            }
            catch (Exception ex)
            {
                Log.Error("GetGeneratedCode(): ", ex);
                return(null);
            }
        }
        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();
        }
Beispiel #28
0
        public GeneratorResults Generate()
        {
            lock (this)
            {
                _codeTransformer.Initialize(this, _directives);

                // Create the engine
                var engine = new RazorTemplateEngine(this);

                // Generate code
                GeneratorResults results = null;
                try
                {
                    using (var stream = File.OpenRead())
                        using (var reader = new StreamReader(stream, Encoding.Default, detectEncodingFromByteOrderMarks: true))
                        {
                            results = engine.GenerateCode(reader, className: DefaultClassName, rootNamespace: DefaultNamespace, sourceFileName: this.File.RealPath);
                        }
                }
                catch (Exception e)
                {
                    OnGenerateError(4, e.Message, 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);
                }

                return(results);
            }
        }
Beispiel #29
0
        public virtual async Task <TemplateResult> RunTemplateAsync([NotNull] string content,
                                                                    [NotNull] dynamic templateModel, CancellationToken cancellationToken = default(CancellationToken))
        {
            Check.NotNull(content, nameof(content));
            Check.NotNull(templateModel, nameof(templateModel));

            cancellationToken.ThrowIfCancellationRequested();

            var host   = new RazorTemplatingHost(typeof(RazorReverseEngineeringBase));
            var engine = new RazorTemplateEngine(host);

            using (var reader = new StringReader(content))
            {
                var generatorResults = engine.GenerateCode(reader);

                if (!generatorResults.Success)
                {
                    var messages = generatorResults.ParserErrors.Select(e => e.Message);
                    return(new TemplateResult
                    {
                        GeneratedText = string.Empty,
                        ProcessingException = new TemplateProcessingException(messages)
                    });
                }

                var references     = _metadataReferencesProvider.GetApplicationReferences();
                var templateResult = _compilationService.Compile(
                    new List <string> {
                    generatorResults.GeneratedCode
                }, references);
                if (templateResult.Messages.Any())
                {
                    return(new TemplateResult
                    {
                        GeneratedText = string.Empty,
                        ProcessingException = new TemplateProcessingException(templateResult.Messages)
                    });
                }

                var compiledObject = Activator.CreateInstance(templateResult.CompiledType);
                var razorTemplate  = compiledObject as RazorReverseEngineeringBase;

                var result = String.Empty;
                if (razorTemplate != null)
                {
                    razorTemplate.Model           = templateModel;
                    razorTemplate.ModelUtilities  = _modelUtilities;
                    razorTemplate.CSharpUtilities = _csharpUtiliies;
                    //ToDo: If there are errors executing the code, they are missed here.
                    result = await razorTemplate.ExecuteTemplateAsync(cancellationToken);
                }

                return(new TemplateResult
                {
                    GeneratedText = result,
                    ProcessingException = null
                });
            }
        }
Beispiel #30
0
        /// <inheritdoc />
        public GeneratorResults GenerateCode(string rootRelativePath, Stream inputStream)
        {
            // Adding a prefix so that the main view class can be easily identified.
            var className = MainClassNamePrefix + ParserHelpers.SanitizeClassName(rootRelativePath);
            var engine    = new RazorTemplateEngine(this);

            return(engine.GenerateCode(inputStream, className, DefaultNamespace, rootRelativePath));
        }
        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();
        }
        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);
        }
Beispiel #33
0
            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;
                }
            }
        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);
        }
        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);
        }
 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);
 }