Ejemplo n.º 1
0
 /// <summary>Saves the generated code.</summary>
 /// <param name="razorTemplate">The razor template.</param>
 /// <param name="path">The path.</param>
 private void SaveGeneratedCode(GeneratorResults razorTemplate, string path)
 {
     using (var writer = new StreamWriter(path, false, Encoding.UTF8))
     {
         provider.GenerateCodeFromCompileUnit(razorTemplate.GeneratedCode, writer, new CodeGeneratorOptions());
     }
 }
Ejemplo n.º 2
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);
            }
        }
Ejemplo n.º 3
0
 public CompiledRazorTemplate(
     GeneratorResults generatorResults,
     CompilerResults compilerResults)
 {
     this.generatorResults = generatorResults;
     this.compilerResults  = compilerResults;
 }
Ejemplo n.º 4
0
        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());
                }
            }
        }
        public void Compile_ReturnsFailedResultIfParseFails()
        {
            // Arrange
            var generatorResult = new GeneratorResults(
                new Block(new BlockBuilder {
                Type = BlockType.Comment
            }),
                Enumerable.Empty <TagHelperDescriptor>(),
                new RazorError[] { new RazorError("some message", 1, 1, 1, 1) },
                new CodeBuilderResult("", new LineMapping[0]),
                new CodeTree());
            var host = new Mock <IMvcRazorHost>();

            host.Setup(h => h.GenerateCode(It.IsAny <string>(), It.IsAny <Stream>()))
            .Returns(generatorResult)
            .Verifiable();

            var fileInfo = new Mock <IFileInfo>();

            fileInfo.Setup(f => f.CreateReadStream())
            .Returns(Stream.Null);

            var compiler         = new Mock <ICompilationService>(MockBehavior.Strict);
            var relativeFileInfo = new RelativeFileInfo(fileInfo.Object, @"Views\index\home.cshtml");
            var razorService     = new RazorCompilationService(compiler.Object, host.Object);

            // Act
            var result = razorService.Compile(relativeFileInfo);

            // Assert
            var ex = Assert.Throws <CompilationFailedException>(() => result.CompiledType);

            Assert.Equal("some message", Assert.Single(ex.Messages).Message);
            host.Verify();
        }
Ejemplo n.º 6
0
        public override string InspectSource(GeneratorResults results, TypeContext context)
        {
            foreach (var codeNamespace in results.GeneratedCode.Namespaces.Cast <CodeNamespace>().ToList())
            {
                foreach (var codeTypeDeclaration in codeNamespace.Types.Cast <CodeTypeDeclaration>().ToList())
                {
                    foreach (var codeTypeMember in codeTypeDeclaration.Members.Cast <CodeTypeMember>().ToList())
                    {
                        var snippetTypeMember = codeTypeMember as CodeSnippetTypeMember;
                        if (snippetTypeMember != null && snippetTypeMember.Text.Contains("#line hidden"))
                        {
                            snippetTypeMember.Text = snippetTypeMember.Text.Replace("#line hidden", "");
                        }
                    }
                }
            }
            var codeType = results.GeneratedCode.Namespaces[0].Types[0];

            //if (context.ModelType != null && CompilerServicesUtility.IsDynamicType(context.ModelType))
            //    codeType.CustomAttributes.Add(
            //        new CodeAttributeDeclaration(new CodeTypeReference(typeof (HasDynamicModelAttribute))));
            GenerateConstructors(CompilerServicesUtility.GetConstructors(context.TemplateType).ToArray(), codeType);
            //this.Inspect(results.GeneratedCode);
            var sb = new StringBuilder();

            using (var stringWriter = new StringWriter(sb, CultureInfo.InvariantCulture))
            {
                this.CodeDomProvider.GenerateCodeFromCompileUnit(
                    results.GeneratedCode,
                    stringWriter,
                    new CodeGeneratorOptions());
                return(sb.ToString());
            }
        }
Ejemplo n.º 7
0
 public ViewCompilationInfo(
     RelativeFileInfo relativeFileInfo,
     GeneratorResults generatorResults)
 {
     RelativeFileInfo = relativeFileInfo;
     GeneratorResults = generatorResults;
 }
Ejemplo n.º 8
0
        private GeneratorResults GenerateCode(Type modelType, string viewPath)
        {
            var host = new RazorEngineHost(new CSharpRazorCodeLanguage())
            {
                DefaultBaseClass = string.Format("Easy.Web.RazorEngineTemplate.RazorTemplateBase<{0}>", modelType.FullName),
                DefaultNamespace = "Easy.Web.RazorEngineTemplate",
                DefaultClassName = "RazorTemplate"
            };

            host.NamespaceImports.Add("System");
            if (NamespaceImports != null)
            {
                foreach (string item in NamespaceImports)
                {
                    host.NamespaceImports.Add(item);
                }
            }
            GeneratorResults razorResult = null;

            using (TextReader reader = new StringReader(new StreamReader(viewPath).ReadToEnd()))
            {
                razorResult = new RazorTemplateEngine(host).GenerateCode(reader);
            }
            return(razorResult);
        }
        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());
        }
        internal virtual void Run(CancellationToken cancelToken)
        {
            if (!cancelToken.IsCancellationRequested)
            {
                // Seek the buffer to the beginning
                Change.NewBuffer.Position = 0;

                try
                {
                    _results = Engine.GenerateCode(Change.NewBuffer, className: null, rootNamespace: null, sourceFileName: SourceFileName, cancelToken: cancelToken);
                }
                catch (OperationCanceledException ex)
                {
                    if (ex.CancellationToken == cancelToken)
                    {
                        // We've been cancelled, so just return.
                        return;
                    }
                    else
                    {
                        // Exception was thrown for some other reason...
                        throw;
                    }
                }
            }
        }
Ejemplo n.º 11
0
        private static Type CompileView(GeneratorResults razorResult, CompilerParameters compilerParameters)
        {
            var codeProvider = new CSharpCodeProvider(CompilerProperties);
            var result       = codeProvider.CompileAssemblyFromDom(compilerParameters, razorResult.GeneratedCode);

            if (result.Errors != null && result.Errors.HasErrors)
            {
                throw new RazorCompilerException(result.Errors.OfType <CompilerError>().Where(x => !x.IsWarning));
            }

            var assembly = Assembly.LoadFrom(compilerParameters.OutputAssembly);

            if (assembly == null)
            {
                throw new RazorCompilerException("Unable to load view assembly.");
            }

            var type = assembly.GetType(SimpleRazorConfiguration.Namespace + "." + compilerParameters.MainClass);

            if (type == null)
            {
                throw new RazorCompilerException("Unable to load view assembly.");
            }

            return(type);
        }
Ejemplo n.º 12
0
        public RazorException(GeneratorResults generatorResults, CompilerResults compilerResults)
        {
            Contract.Requires(generatorResults != null);

            this.generatorResults = generatorResults;
            this.compilerResults  = compilerResults;
        }
Ejemplo n.º 13
0
        private RazorViewBase GenerateRazorView(CodeDomProvider codeProvider, GeneratorResults razorResult)
        {
            // Compile the generated code into an assembly
            string outputAssemblyName = String.Format("Temp_{0}.dll", Guid.NewGuid().ToString("N"));

            CompilerResults results = codeProvider.CompileAssemblyFromDom(

                new CompilerParameters(new string[] {
                GetAssemblyPath(typeof(Microsoft.CSharp.RuntimeBinder.Binder)),
                GetAssemblyPath(typeof(System.Runtime.CompilerServices.CallSite)),
                GetAssemblyPath(Assembly.GetExecutingAssembly())
            }, outputAssemblyName),
                razorResult.GeneratedCode);

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

                return(new ErrorView(error));
            }
            else
            {
                // Load the assembly
                Assembly assembly = Assembly.LoadFrom(outputAssemblyName);
                if (assembly == null)
                {
                    string error = "Error loading template assembly";

                    return(new ErrorView(error));
                }
                else
                {
                    // Get the template type
                    Type type = assembly.GetType("RazorOutput.RazorView");
                    if (type == null)
                    {
                        string error = String.Format("Could not find type RazorOutput.Template in assembly {0}", assembly.FullName);
                        return(new ErrorView(error));
                    }
                    else
                    {
                        RazorViewBase view = Activator.CreateInstance(type) as RazorViewBase;
                        if (view == null)
                        {
                            string error = "Could not construct RazorOutput.Template or it does not inherit from RazorViewBase";
                            return(new ErrorView(error));
                        }
                        else
                        {
                            return(view);
                        }
                    }
                }
            }
        }
        internal virtual void Run(CancellationToken cancelToken)
        {
            if (!cancelToken.IsCancellationRequested)
            {
                // Seek the buffer to the beginning
                Change.NewBuffer.Position = 0;

                try
                {
                    _results = Engine.GenerateCode(Change.NewBuffer, className: null, rootNamespace: null, sourceFileName: SourceFileName, cancelToken: cancelToken);
                }
                catch (OperationCanceledException ex)
                {
                    if (ex.CancellationToken == cancelToken)
                    {
                        // We've been cancelled, so just return.
                        return;
                    }
                    else
                    {
                        // Exception was thrown for some other reason...
                        throw;
                    }
                }
            }
        }
        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);
            }
        }
Ejemplo n.º 16
0
        /// <summary>
        /// 创建指定路径的模板解析后的模板类型。
        /// </summary>
        /// <param name="templateReader">用于获取模板内容的 <see cref="TextReader"/> 对象。</param>
        /// <param name="className">模板编译后的类名。默认为根据 <paramref name="sourceFileName"/> 动态生成。</param>
        /// <param name="rootNamespace">模板编译后的名字空间。默认为 RazorCompiledTemplates 。</param>
        /// <param name="sourceFileName">模板的文件名或模板的别名,用于在模板互相引用时使用。模板的名字作为模板的唯一标识符,应该保证其唯一性。默认为模板文件的路径或模板字符串本身的哈希值。</param>
        /// <param name="baseClassName">模板编译后的默认基类。如果值为 null,则使用 <see cref="TemplateBase&lt;T&gt;"/> 作为模板基类。在模板中可以通过 @inherits 关键字来覆盖这里的设置。</param>
        /// <param name="modelType">模板编译后的模型类型。如果值为 null,则表示不使用模板对象。未来版本中,在模板中可以通过 @model 关键字来覆盖这里的设置。</param>
        public Type AddTemplateType(TextReader templateReader, string className, string rootNamespace, string sourceFileName, string baseClassName, Type modelType)
        {
            // 1. 编译为 DOM 语法树。
            GeneratorResults generatorResult = GenerateCode(templateReader, className, rootNamespace, sourceFileName, baseClassName, modelType);

            if (!generatorResult.Success)
            {
                throw new RazorParseException(generatorResult.ParserErrors);
            }

            // 2. 编译为动态的类型。
            CompilerResults compilerResults = CodeDomProvider.CompileAssemblyFromDom(CompilerParameters, generatorResult.GeneratedCode);

#if PARSER_DEBUG
            StringBuilder sb     = new StringBuilder();
            TextWriter    writer = new StringWriter(sb);
            CodeDomProvider.GenerateCodeFromCompileUnit(generatorResult.GeneratedCode, writer, new CodeGeneratorOptions());
            Console.Write(sb.ToString());
            File.WriteAllText("D:\\aa.cs", sb.ToString());
#endif

            if (compilerResults.Errors.Count > 0)
            {
                throw new RazorComplieException(compilerResults.Errors);
            }

            // 3. 获取刚创建的类型。
            Type type = compilerResults.CompiledAssembly.GetType(String.IsNullOrEmpty(rootNamespace) ? className : String.Concat(rootNamespace, ".", className));

            // 4. 加入缓存列表。
            _templateTypeCache[sourceFileName] = new Tuple <Type, Type>(type, modelType);

            return(type);
        }
Ejemplo n.º 17
0
        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);
        }
Ejemplo n.º 18
0
        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);
            }
        }
Ejemplo n.º 19
0
 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());
     }
 }
        public override string InspectSource(GeneratorResults results, TypeContext context)
        {
#if RAZOR4
            string generatedCode = results.GeneratedCode;
            if (context.TemplateContent.TemplateFile == null)
            {
                generatedCode = generatedCode.Replace("#line hidden", "");
            }

            // TODO: add attributes and constructor to the source code.

            return(generatedCode);
#else
            if (context.TemplateContent.TemplateFile == null)
            {
                // Allow to step into the template code by removing the "#line hidden" pragmas
                foreach (CodeNamespace @namespace in results.GeneratedCode.Namespaces.Cast <CodeNamespace>().ToList())
                {
                    foreach (CodeTypeDeclaration @type in @namespace.Types.Cast <CodeTypeDeclaration>().ToList())
                    {
                        foreach (CodeTypeMember member in @type.Members.Cast <CodeTypeMember>().ToList())
                        {
                            var snippet = member as CodeSnippetTypeMember;
                            if (snippet != null && snippet.Text.Contains("#line hidden"))
                            {
                                snippet.Text = snippet.Text.Replace("#line hidden", "");
                            }
                        }
                    }
                }
            }


            // Add the dynamic model attribute if the type is an anonymous type.
            var generatedType = results.GeneratedCode.Namespaces[0].Types[0];
            if (context.ModelType != null && CompilerServicesUtility.IsDynamicType(context.ModelType))
            {
                generatedType.CustomAttributes.Add(new CodeAttributeDeclaration(new CodeTypeReference(typeof(HasDynamicModelAttribute))));
            }

            // Generate any constructors required by the base template type.
            GenerateConstructors(CompilerServicesUtility.GetConstructors(context.TemplateType), generatedType);

#pragma warning disable 0618 // Backwards Compat.
            // Despatch any inspectors
            Inspect(results.GeneratedCode);
#pragma warning restore 0618 // Backwards Compat.

            string generatedCode;
            var    builder = new StringBuilder();
            using (var writer = new StringWriter(builder, CultureInfo.InvariantCulture))
            {
                CodeDomProvider.GenerateCodeFromCompileUnit(results.GeneratedCode, writer, new CodeGeneratorOptions());
                generatedCode = builder.ToString();
            }
            return(generatedCode);
#endif
        }
Ejemplo n.º 21
0
 public CompiledClass(string classFullName, string template, string[] additionalNamespaceImports = null, string[] additionalReferencedAssemblies = null)
 {
     ClassFullName     = classFullName;
     _compiledAssembly = new Lazy <Assembly>(() =>
     {
         GeneratorResults razorTemplate = GenerateCode <TModel>(classFullName, template, additionalNamespaceImports);
         return(CreateCompiledAssemblyFor <TModel>(razorTemplate.GeneratedCode, additionalReferencedAssemblies));
     });
 }
Ejemplo n.º 22
0
        private static void AddModelNamespace(GeneratorResults razorResult, Type modelType)
        {
            if (razorResult.GeneratedCode.Namespaces[0].Imports.OfType <CodeNamespaceImport>().Any(x => x.Namespace == modelType.Namespace))
            {
                return;
            }

            razorResult.GeneratedCode.Namespaces[0].Imports.Add(new CodeNamespaceImport(modelType.Namespace));
        }
Ejemplo n.º 23
0
        /// <summary>
        /// Load a new engine instance and setup it up, parse template and generate code
        /// on a GeneratorResults form (this allows to execute it after)
        /// </summary>
        /// <param name="template"></param>
        /// <returns></returns>
        private static GeneratorResults GenerateSourceCodeResult(string template)
        {
            RazorTemplateEngine engine      = RazorEngineHelper.SetupRazorEngine();
            GeneratorResults    razorResult = null;

            using (TextReader rdr = new StringReader(template))
            {
                razorResult = engine.GenerateCode(rdr);
            }
            return(razorResult);
        }
        public override string InspectSource(GeneratorResults results, TypeContext context)
        {
            string generatedCode;
            var    builder = new StringBuilder();

            using (var writer = new StringWriter(builder, CultureInfo.InvariantCulture))
            {
                _codeDomProvider.GenerateCodeFromCompileUnit(results.GeneratedCode, writer, new CodeGeneratorOptions());
                generatedCode = builder.ToString();
            }
            return(generatedCode);
        }
Ejemplo n.º 25
0
        internal static string RenderRazorString <T>(T model, string templateString, dynamic viewBag = null)
        {
            DynamicContentGeneratorBase templateInstance;

            if (_assemblyCache.TryGetValue(templateString, out templateInstance))
            {
                templateInstance.Model = model;

                if (viewBag != null)
                {
                    templateInstance.ViewBag    = viewBag;
                    templateInstance.ViewBag.xt = model;
                }
                return(_assemblyCache[templateString].GetContent());
            }

            const string dynamicallyGeneratedClassName = "DynamicContentTemplate";
            const string namespaceForDynamicClasses    = "runnerDotNet";
            const string dynamicClassFullName          = "runnerDotNet.DynamicContentTemplate";

            var host = new RazorEngineHost(new CSharpRazorCodeLanguage())
            {
                DefaultBaseClass = typeof(DynamicContentGeneratorBase).Name,
                DefaultClassName = dynamicallyGeneratedClassName,
                DefaultNamespace = namespaceForDynamicClasses,
            };

            host.NamespaceImports.Add("System");
            host.NamespaceImports.Add("System.Dynamic");
            host.NamespaceImports.Add("System.Text");
            host.NamespaceImports.Add("System.Web");
            host.NamespaceImports.Add("System.Web.Mvc");
            host.NamespaceImports.Add("System.Web.Mvc.Html");
            var engine = new RazorTemplateEngine(host);

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

            var compiledAssembly = CreateCompiledAssemblyFor(razorTemplate.GeneratedCode);

            templateInstance = (DynamicContentGeneratorBase)compiledAssembly.CreateInstance(dynamicClassFullName);
            _assemblyCache[templateString] = templateInstance;

            templateInstance.Model = model;

            if (viewBag != null)
            {
                templateInstance.ViewBag    = viewBag;
                templateInstance.ViewBag.xt = model;
            }

            return(templateInstance.GetContent());
        }
Ejemplo n.º 26
0
        private void DocumentParseCompleteMainThread()
        {
            if (_parseData == null)
            {
                return;
            }
            ParseData parseData = _parseData;

            lock (parseData)
            {
                _parseData.NotificationPending = false;
                if (_pendingShimTextChange.HasValue && (_parseData.SourceChange.NewBuffer as IShimTextBuffer).Snapshot == (_pendingShimTextChange.Value.NewBuffer as IShimTextBuffer).Snapshot)
                {
                    _pendingShimTextChange = null;
                    if (_viewBuffer != null)
                    {
                        ITextSnapshot snapshot = (_parseData.SourceChange.NewBuffer as IShimTextBuffer).Snapshot;
                        if (snapshot != snapshot.TextBuffer.CurrentSnapshot)
                        {
                            ReparseFile();
                        }
                        else
                        {
                            _result = _parseData.GeneratorResults;
                            if (!_parseData.TreeStructureChanged)
                            {
                                NotifyOnCodeGenerationComplete(null);
                            }
                            else
                            {
                                _parseData.TreeStructureChanged = false;
                                IEnumerable <System.Web.Razor.Parser.SyntaxTree.Span> spans = _result.Document.Flatten();
                                List <RazorRange> newCodeRanges = GetNewCodeRanges(spans);
                                NotifyOnCodeGenerationComplete(newCodeRanges);
                                NotifySpansChanged(spans, newCodeRanges);
                                if (_spanContextChanged)
                                {
                                    RepairCompletionSession();
                                    _spanContextChanged = false;
                                }
                                if (_parseData != null)
                                {
                                    NotifyPossibleTrigger(_parseData.SourceChange);
                                }
                            }
                        }
                    }
                }
            }
        }
Ejemplo n.º 27
0
        public void GenerateOutputsResultsOfParsingAndGeneration()
        {
            // Arrange
            RazorTemplateEngine engine = new RazorTemplateEngine(CreateHost());

            // Act
            GeneratorResults results = engine.GenerateCode(new StringTextBuffer("foo @bar("));

            // Assert
            Assert.False(results.Success);
            Assert.Single(results.ParserErrors);
            Assert.NotNull(results.Document);
            Assert.NotNull(results.GeneratedCode);
        }
Ejemplo n.º 28
0
        private static CompilerResults CompileCode(GeneratorResults razorResult)
        {
            var referencedAssemblies = new List <string>
            {
                Assembly.GetExecutingAssembly().Location,
                typeof(Microsoft.CSharp.RuntimeBinder.Binder).Assembly.Location,
                typeof(System.Runtime.CompilerServices.CallSite).Assembly.Location
            };

            var compilerParameters = new CompilerParameters(referencedAssemblies.Distinct().ToArray());
            var codeProvider       = new CSharpCodeProvider();

            return(codeProvider.CompileAssemblyFromSource(compilerParameters, razorResult.GeneratedCode));
        }
Ejemplo n.º 29
0
        /// <summary>
        /// Load a new engine instance and setup it up, parse template and generate code
        /// on a string form (only to get the source)
        /// </summary>
        /// <param name="template"></param>
        /// <returns></returns>
        public static string GenerateSourceCode(string template)
        {
            GeneratorResults razorResult = GenerateSourceCodeResult(template);

            CSharpCodeProvider codeProvider = new CSharpCodeProvider();
            string             result       = string.Empty;

            using (StringWriter sw = new StringWriter())
            {
                codeProvider.GenerateCodeFromCompileUnit(razorResult.GeneratedCode, sw, new CodeGeneratorOptions());
                result = sw.GetStringBuilder().ToString();
            }
            return(result);
        }
        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.True(results.Success);
            Assert.Empty(results.ParserErrors);
            Assert.NotNull(results.Document);
            Assert.NotNull(results.GeneratedCode);
            Assert.NotNull(results.DesignTimeLineMappings);
        }
Ejemplo n.º 31
0
        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 Compile_ReturnsFailedResultIfParseFails()
        {
            // Arrange
            var errorSink = new ErrorSink();
            errorSink.OnError(new RazorError("some message", 1, 1, 1, 1));
            var generatorResult = new GeneratorResults(
                    new Block(new BlockBuilder { Type = BlockType.Comment }),
                    Enumerable.Empty<TagHelperDescriptor>(),
                    errorSink,
                    new CodeGeneratorResult("", new LineMapping[0]),
                    new ChunkTree());
            var host = new Mock<IMvcRazorHost>();
            host.Setup(h => h.GenerateCode(It.IsAny<string>(), It.IsAny<Stream>()))
                .Returns(generatorResult)
                .Verifiable();

            var fileInfo = new Mock<IFileInfo>();
            fileInfo.Setup(f => f.CreateReadStream())
                    .Returns(Stream.Null);

            var compiler = new Mock<ICompilationService>(MockBehavior.Strict);
            var relativeFileInfo = new RelativeFileInfo(fileInfo.Object, @"Views\index\home.cshtml");
            var razorService = new RazorCompilationService(compiler.Object, host.Object, GetOptions());

            // Act
            var result = razorService.Compile(relativeFileInfo);

            // Assert
            Assert.NotNull(result.CompilationFailures);
            Assert.Collection(result.CompilationFailures,
                failure =>
                {
                    var message = Assert.Single(failure.Messages);
                    Assert.Equal("some message", message.Message);
                });
            host.Verify();
        }
Ejemplo n.º 33
0
 public abstract string InspectSource(GeneratorResults results, TypeContext context);
Ejemplo n.º 34
0
 public virtual string InspectSource(GeneratorResults results, TypeContext context)
 {
     return results.GeneratedCode;
 }
        public override string InspectSource(GeneratorResults results, TypeContext context)
        {
            #if RAZOR4
            string generatedCode = results.GeneratedCode;
            if (context.TemplateContent.TemplateFile == null)
            {
                generatedCode = generatedCode.Replace("#line hidden", "");
            }

            // TODO: add attributes and constructor to the source code.

            return generatedCode;
            #else
            if (context.TemplateContent.TemplateFile == null)
            {
                // Allow to step into the template code by removing the "#line hidden" pragmas
                foreach (CodeNamespace @namespace in results.GeneratedCode.Namespaces.Cast<CodeNamespace>().ToList())
                {
                    foreach (CodeTypeDeclaration @type in @namespace.Types.Cast<CodeTypeDeclaration>().ToList())
                    {
                        foreach (CodeTypeMember member in @type.Members.Cast<CodeTypeMember>().ToList())
                        {
                            var snippet = member as CodeSnippetTypeMember;
                            if (snippet != null && snippet.Text.Contains("#line hidden"))
                            {
                                snippet.Text = snippet.Text.Replace("#line hidden", "");
                            }
                        }
                    }
                }
            }

            // Add the dynamic model attribute if the type is an anonymous type.
            var generatedType = results.GeneratedCode.Namespaces[0].Types[0];
            if (context.ModelType != null && CompilerServicesUtility.IsDynamicType(context.ModelType))
                generatedType.CustomAttributes.Add(new CodeAttributeDeclaration(new CodeTypeReference(typeof(HasDynamicModelAttribute))));

            // Generate any constructors required by the base template type.
            GenerateConstructors(CompilerServicesUtility.GetConstructors(context.TemplateType), generatedType);

            #pragma warning disable 0618 // Backwards Compat.
            // Despatch any inspectors
            Inspect(results.GeneratedCode);
            #pragma warning restore 0618 // Backwards Compat.

            string generatedCode;
            var builder = new StringBuilder();
            using (var writer = new StringWriter(builder, CultureInfo.InvariantCulture))
            {
                CodeDomProvider.GenerateCodeFromCompileUnit(results.GeneratedCode, writer, new CodeGeneratorOptions());
                generatedCode = builder.ToString();
            }
            return generatedCode;
            #endif
        }
        public void Compile_ReturnsResultFromCompilationServiceIfParseSucceeds()
        {
            // Arrange
            var code = "compiled-content";
            var generatorResult = new GeneratorResults(
                    new Block(new BlockBuilder { Type = BlockType.Comment }),
                    Enumerable.Empty<TagHelperDescriptor>(),
                    new ErrorSink(),
                    new CodeGeneratorResult(code, new LineMapping[0]),
                    new ChunkTree());
            var host = new Mock<IMvcRazorHost>();
            host.Setup(h => h.GenerateCode(It.IsAny<string>(), It.IsAny<Stream>()))
                .Returns(generatorResult);

            var fileInfo = new Mock<IFileInfo>();
            fileInfo.Setup(f => f.CreateReadStream())
                    .Returns(Stream.Null);
            var relativeFileInfo = new RelativeFileInfo(fileInfo.Object, @"Views\index\home.cshtml");

            var compilationResult = CompilationResult.Successful(typeof(object));
            var compiler = new Mock<ICompilationService>();
            compiler.Setup(c => c.Compile(relativeFileInfo, code))
                    .Returns(compilationResult)
                    .Verifiable();
            var razorService = new RazorCompilationService(compiler.Object, host.Object, GetOptions());

            // Act
            var result = razorService.Compile(relativeFileInfo);

            // Assert
            Assert.Same(compilationResult, result);
            compiler.Verify();
        }