Exemple #1
0
        public IEnumerable <Span> Parse(string viewFile)
        {
            RazorCodeLanguage language;

            switch (viewFile.FileExtension())
            {
            case ".cshtml":
                language = new CSharpRazorCodeLanguage(true);
                break;

            case ".vbhtml":
                language = new VBRazorCodeLanguage(true);
                break;

            default:
                throw new ArgumentException("Invalid extension for Razor engine.");
            }

            using (var fileStream = new FileStream(viewFile, FileMode.Open, FileAccess.Read))
                using (var reader = new StreamReader(fileStream))
                {
                    var engine       = new RazorTemplateEngine(new RazorEngine.Compilation.RazorEngineHost(language, () => new HtmlMarkupParser()));
                    var parseResults = engine.ParseTemplate(reader);
                    return(parseResults.Document.Flatten());
                }
        }
        ParserResults ParseTemplate(ITextBuffer textBuffer)
        {
            var host   = new RazorEngineHost(new CSharpRazorCodeLanguage());
            var engine = new RazorTemplateEngine(host);

            return(engine.ParseTemplate(textBuffer.CreateReader()));
        }
        private static ChunkTree ParseViewFile(
            RazorTemplateEngine engine,
            IFileInfo fileInfo,
            string viewImportsPath)
        {
            using (var stream = fileInfo.CreateReadStream())
            {
                using (var streamReader = new StreamReader(stream))
                {
                    var parseResults   = engine.ParseTemplate(streamReader, viewImportsPath);
                    var className      = ParserHelpers.SanitizeClassName(fileInfo.Name);
                    var language       = engine.Host.CodeLanguage;
                    var chunkGenerator = language.CreateChunkGenerator(
                        className,
                        engine.Host.DefaultNamespace,
                        viewImportsPath,
                        engine.Host);
                    chunkGenerator.Visit(parseResults);

                    // Rewrite the location of inherited chunks so they point to the global import file.
                    var chunkTree = chunkGenerator.Context.ChunkTreeBuilder.Root;
                    foreach (var chunk in chunkTree.Children)
                    {
                        chunk.Start = new SourceLocation(
                            viewImportsPath,
                            chunk.Start.AbsoluteIndex,
                            chunk.Start.LineIndex,
                            chunk.Start.CharacterIndex);
                    }

                    return(chunkTree);
                }
            }
        }
        public void Load(string content)
        {
            var host = new RazorEngineHost(new CSharpRazorCodeLanguage());

            var engine = new RazorTemplateEngine(host);

            parseResults = engine.ParseTemplate(new StringReader(content));
        }
Exemple #5
0
        void ReadHtmlSpans(string html)
        {
            RazorEngineHost     razorEngineHost = new RazorEngineHost(codeLanguage);
            RazorTemplateEngine engine          = new RazorTemplateEngine(razorEngineHost);
            ParserResults       results         = engine.ParseTemplate(new StringReader(html));

            spans = new List <Span>(results.Document.Flatten());
            spans.RemoveAll(span => span.Kind != SpanKind.Markup);
        }
Exemple #6
0
        void ReadBlockSpans(string markup)
        {
            var razorEngineHost = new RazorEngineHost(codeLanguage);
            var engine          = new RazorTemplateEngine(razorEngineHost);
            var results         = engine.ParseTemplate(new StringReader(markup));

            spans = new List <Span>(results.Document.Flatten());
            spans.RemoveAll(span => !span.IsBlock);
        }
        public ParserResults ParseTemplate(string template)
        {
            RazorEngineHost     host   = new RazorEngineHost(new CSharpRazorCodeLanguage());
            RazorTemplateEngine engine = new RazorTemplateEngine(host);

            using (StringReader sr = new StringReader(template))
            {
                return(engine.ParseTemplate(sr));
            }
        }
Exemple #8
0
        public IEnumerable<Span> Parse(string viewFile)
        {
            var codeLanguage = RazorCodeLanguageFactory.Create(viewFile.FileExtension());

            using (var fileStream = new FileStream(viewFile, FileMode.Open, FileAccess.Read))
            using (var reader = new StreamReader(fileStream))
            {
                var templateEngine = new RazorTemplateEngine(new RazorEngineHost(codeLanguage));
                var parseResults = templateEngine.ParseTemplate(reader);
                return parseResults.Document.Flatten();
            }
        }
        public void ParseTemplateOutputsResultsOfParsingProvidedTemplateSource()
        {
            // Arrange
            RazorTemplateEngine engine = new RazorTemplateEngine(CreateHost());

            // Act
            ParserResults results = engine.ParseTemplate(new StringTextBuffer("foo @bar("));

            // Assert
            Assert.IsFalse(results.Success);
            Assert.AreEqual(1, results.ParserErrors.Count);
            Assert.IsNotNull(results.Document);
        }
        public void ParseTemplateOutputsResultsOfParsingProvidedTemplateSource()
        {
            // Arrange
            var engine = new RazorTemplateEngine(CreateHost());

            // Act
            var results = engine.ParseTemplate(new StringTextBuffer("foo @bar("));

            // Assert
            Assert.False(results.Success);
            Assert.Single(results.ParserErrors);
            Assert.NotNull(results.Document);
        }
Exemple #11
0
        public static bool IsValidRazor(string razor)
        {
            var host   = new RazorEngineHost(new CSharpRazorCodeLanguage());
            var engine = new RazorTemplateEngine(host);

            using (var stream = new MemoryStream(Encoding.UTF8.GetBytes(razor)))
            {
                using (var reader = new StreamReader(stream))
                {
                    var parserResults = engine.ParseTemplate(reader);
                    return(!parserResults.ParserErrors.Any());
                }
            }
        }
Exemple #12
0
        public virtual void RenderClientTemplate(TextReader razorTemplate, TextWriter output)
        {
            var host   = new RazorEngineHost(new CSharpRazorCodeLanguage());
            var engine = new RazorTemplateEngine(host);

            var parserResults = engine.ParseTemplate(razorTemplate);

            if (parserResults.Success == false)
            {
                // TODO: Less suck
                throw new RazorClientTemplateException("Template parse exception");
            }

            RenderClientTemplate(parserResults.Document, output);
        }
Exemple #13
0
        public LoveSyntaxTree Parse(TextReader source)
        {
            var language = new CSharpRazorCodeLanguage();
            var host     = new RazorEngineHost(language)
            {
            };
            var parser  = new RazorTemplateEngine(host);
            var results = parser.ParseTemplate(source);

            //var debugText = RazorDebugView.ToDebug(results);

            var tree     = VisitTree(results);
            var treeText = tree.ToString();

            return(tree);
        }
        public string Process(Stream stream)
        {
            using (var reader = new StreamReader(stream))
            {
                var parserResults = engine.ParseTemplate(reader);

                var walkContext = new WalkContext();
                WalkTree(walkContext, parserResults.Document);

                StringBuilder result = new StringBuilder();
                foreach (var span in walkContext.FlattenedTree)
                {
                    result.Append(span.Content);
                }

                return(result.ToString());
            }
        }
 // TODO: This needs to be cached (#1016)
 private CodeTree ParseViewFile(RazorTemplateEngine engine,
                                IFileInfo fileInfo)
 {
     using (var stream = fileInfo.CreateReadStream())
     {
         using (var streamReader = new StreamReader(stream))
         {
             var parseResults  = engine.ParseTemplate(streamReader);
             var className     = ParserHelpers.SanitizeClassName(fileInfo.Name);
             var language      = engine.Host.CodeLanguage;
             var codeGenerator = language.CreateCodeGenerator(className,
                                                              engine.Host.DefaultNamespace,
                                                              fileInfo.PhysicalPath,
                                                              engine.Host);
             codeGenerator.Visit(parseResults);
             return(codeGenerator.Context.CodeTreeBuilder.CodeTree);
         }
     }
 }
Exemple #16
0
        public View(string viewRelativePath, ViewProject viewProject)
        {
            var viewFile      = Path.Combine(viewProject.ViewsPath, viewRelativePath.BackSlashes()) + ".cshtml";
            var viewName      = Path.GetFileNameWithoutExtension(viewFile);
            var viewReader    = System.IO.File.OpenText(Path.Combine(viewFile));
            var host          = new RazorEngineHost(new CSharpRazorCodeLanguage());
            var engine        = new RazorTemplateEngine(host);
            var parserResults = engine.ParseTemplate(viewReader);
            var document      = parserResults.Document;
            var visitor       = new RazorParserVisitor(viewReader, viewRelativePath, viewProject);

            this.Name               = viewName;
            this.viewProject        = viewProject;
            this.File               = viewFile;
            this.ViewDataDictionary = new Dictionary <string, object>();

            visitor.OnPartialView += Visitor_OnPartialView;

            document.Accept(visitor);

            this.SemanticTree = visitor.RootNode;
        }
        public void ParseTemplateOutputsResultsOfParsingProvidedTemplateSource() {
            // Arrange
            RazorTemplateEngine engine = new RazorTemplateEngine(CreateHost());

            // Act
            ParserResults results = engine.ParseTemplate(new StringTextBuffer("foo @bar("));

            // Assert
            Assert.IsFalse(results.Success);
            Assert.AreEqual(1, results.ParserErrors.Count);
            Assert.IsNotNull(results.Document);
        }
Exemple #18
0
        public static void BuilderTemplate(ITemplateInfo templateinfo, ITemplateHost host)
        {
            Type type = host.BaseType;

            string typename            = "_" + Guid.NewGuid().ToString("N");
            RazorTemplateEngine engine = CreateHost(type, "_" + type.Name, typename);

            AddNamespace(type.Namespace);
            GeneratorResults razorResults = null;

            using (System.IO.StreamReader reader = templateinfo.GetCode())
            {
                razorResults = engine.GenerateCode(reader);
                CSharpCodeProvider   codeProvider = new CSharpCodeProvider();
                CodeGeneratorOptions options      = new CodeGeneratorOptions();
                string LastGeneratedCode          = null;
                using (StringWriter writer = new StringWriter())
                {
                    codeProvider.GenerateCodeFromCompileUnit(razorResults.GeneratedCode, writer, options);
                    templateinfo.Host.LastCompileSource = writer.ToString();
                }
                CompilerParameters compilerParameters = new CompilerParameters(new string[0]);
                compilerParameters.OutputAssembly   = "tmp_assembly" + typename;
                compilerParameters.GenerateInMemory = false;
                AddDomainAssemblies();
                foreach (string item in ReferencedAssemblies)
                {
                    compilerParameters.ReferencedAssemblies.Add(item);
                }
                compilerParameters.GenerateInMemory = true;
                CompilerResults compilerResults = codeProvider.CompileAssemblyFromDom(compilerParameters, razorResults.GeneratedCode);
                if (compilerResults.Errors.Count > 0)
                {
                    string errormessage = null;

                    int throwindex = 1;
                    System.Text.StringBuilder sb = new System.Text.StringBuilder();
                    reader.BaseStream.Seek(0, SeekOrigin.Begin);
                    using (System.IO.StreamReader line = new StreamReader(reader.BaseStream, reader.CurrentEncoding))
                    {
                        ParserResults presult = engine.ParseTemplate(line);

                        if (presult.ParserErrors.Count > 0)
                        {
                            throwindex   = presult.ParserErrors[0].Location.LineIndex + 1;
                            errormessage = presult.ParserErrors[0].Message;
                            reader.BaseStream.Seek(0, SeekOrigin.Begin);
                            using (System.IO.StreamReader readcode = new StreamReader(reader.BaseStream, reader.CurrentEncoding))
                            {
                                string code = readcode.ReadLine();
                                while (code != null)
                                {
                                    sb.AppendLine(code);
                                    code = readcode.ReadLine();
                                }
                            }
                        }
                        else
                        {
                            throwindex   = compilerResults.Errors[0].Line;
                            errormessage = compilerResults.Errors[0].ErrorText;
                            sb.Append(LastGeneratedCode);
                        }
                    }

                    templateinfo.CompileError = errormessage;
                    throw new RazorException(templateinfo.CompileError);
                }
                templateinfo.Assembly     = compilerResults.CompiledAssembly;
                templateinfo.TemplateType = compilerResults.CompiledAssembly.GetType("_" + type.Name + "." + typename);
            }
        }
        public void ParseTemplateOutputsResultsOfParsingProvidedTemplateSource()
        {
            // Arrange
            var engine = new RazorTemplateEngine(CreateHost());

            // Act
            var results = engine.ParseTemplate(new StringTextBuffer("foo @bar("));

            // Assert
            Assert.False(results.Success);
            Assert.Single(results.ParserErrors);
            Assert.NotNull(results.Document);
        }