コード例 #1
0
        public void Parse_ParsesDocumentAndInvokesVisitor()
        {
            // Arrange
            var factory = SpanFactory.CreateCsHtml();
            var visitor = new Mock<ParserVisitor> { CallBase = true };
            var parser = new RazorParser(new CSharpCodeParser(), new HtmlMarkupParser());

            // Act
            parser.Parse(new StringReader("foo @bar baz"), visitor.Object);

            // Assert
            visitor.Verify(v => v.VisitSpan(It.Is<Span>(s => s.Kind == SpanKind.Markup && s.Content == "foo ")));
            visitor.Verify(v => v.VisitSpan(It.Is<Span>(s => s.Kind == SpanKind.Transition && s.Content == "@")));
            visitor.Verify(v => v.VisitSpan(It.Is<Span>(s => s.Kind == SpanKind.Code && s.Content == "bar")));
            visitor.Verify(v => v.VisitSpan(It.Is<Span>(s => s.Kind == SpanKind.Markup && s.Content == " baz")));
        }
コード例 #2
0
        public void ParseMethodCallsParseDocumentOnMarkupParserAndReturnsResults() {
            // Arrange
            RazorParser parser = new RazorParser(new CSharpCodeParser(), new HtmlMarkupParser());

            // Act/Assert
            ParserTestBase.EvaluateResults(TestContext,
                                           parser.Parse(new StringReader("foo @bar baz")),
                                           new MarkupBlock(
                                            new MarkupSpan("foo "),
                                            new ExpressionBlock(
                                                new TransitionSpan(RazorParser.TransitionString, hidden: false, acceptedCharacters: AcceptedCharacters.None),
                                                new ImplicitExpressionSpan("bar", CSharpCodeParser.DefaultKeywords, acceptTrailingDot: false, acceptedCharacters: AcceptedCharacters.NonWhiteSpace)
                                            ),
                                            new MarkupSpan(" baz")
                                           ));
        }
コード例 #3
0
        public void ParseMethodCallsParseDocumentOnMarkupParserAndReturnsResults()
        {
            var factory = SpanFactory.CreateCsHtml();

            // Arrange
            RazorParser parser = new RazorParser(new CSharpCodeParser(), new HtmlMarkupParser());

            // Act/Assert
            ParserTestBase.EvaluateResults(parser.Parse(new StringReader("foo @bar baz")),
                new MarkupBlock(
                    factory.Markup("foo "),
                    new ExpressionBlock(
                        factory.CodeTransition(),
                        factory.Code("bar")
                               .AsImplicitExpression(CSharpCodeParser.DefaultKeywords)
                               .Accepts(AcceptedCharacters.NonWhiteSpace)),
                    factory.Markup(" baz")));
        }
コード例 #4
0
        public void ParseMethodUsesProvidedParserListenerIfSpecified() {
            // Arrange
            RazorParser parser = new RazorParser(new CSharpCodeParser(), new HtmlMarkupParser());
            SyntaxTreeBuilderVisitor builder = new SyntaxTreeBuilderVisitor();

            // Act
            parser.Parse(new StringReader("foo @bar baz"), builder);

            // Assert
            ParserTestBase.EvaluateResults(TestContext,
                                           builder.Results,
                                           new MarkupBlock(
                                            new MarkupSpan("foo "),
                                            new ExpressionBlock(
                                                new TransitionSpan(RazorParser.TransitionString, hidden: false, acceptedCharacters: AcceptedCharacters.None),
                                                new ImplicitExpressionSpan("bar", CSharpCodeParser.DefaultKeywords, acceptTrailingDot: false, acceptedCharacters: AcceptedCharacters.NonWhiteSpace)
                                            ),
                                            new MarkupSpan(" baz")
                                           ));
        }
コード例 #5
0
        public void ParseMethodUsesProvidedParserListenerIfSpecified()
        {
            var factory = SpanFactory.CreateCsHtml();

            // Arrange
            RazorParser parser = new RazorParser(new CSharpCodeParser(), new HtmlMarkupParser());

            // Act
            ParserResults results = parser.Parse(new StringReader("foo @bar baz"));

            // Assert
            ParserTestBase.EvaluateResults(results,
                new MarkupBlock(
                    factory.Markup("foo "),
                    new ExpressionBlock(
                        factory.CodeTransition(),
                        factory.Code("bar")
                               .AsImplicitExpression(CSharpCodeParser.DefaultKeywords)
                               .Accepts(AcceptedCharacters.NonWhiteSpace)),
                    factory.Markup(" baz")));
        }
コード例 #6
0
ファイル: RazorCompiler.cs プロジェクト: cmenge/RazorTex
        private CompilerResults Compile(string className, string template, IEnumerable<string> additionalNamespaces, Type modelType = null)
        {
            var languageService = provider.CreateLanguageService();
            var codeDom = provider.CreateCodeDomProvider();
            var host = new RazorEngineHost(languageService);
            host.NamespaceImports.Add("System");
            host.NamespaceImports.Add("System.Collections.Generic");
            host.NamespaceImports.Add("System.IO");
            host.NamespaceImports.Add("System.Linq");
            host.NamespaceImports.Add("RazorTex");

            if (additionalNamespaces != null)
            {
                additionalNamespaces.ToList().ForEach(p => host.NamespaceImports.Add(p));
            }
            //Razor.importedNamespaces.ForEach(p => host.NamespaceImports.Add(p));

            var generator = languageService.CreateCodeGenerator(className, "Razor.Dynamic", null, host);
            var parser = new RazorParser(languageService.CreateCodeParser(), new HtmlMarkupParser()); //FIXME!

            // TODO: Make this association file-type dependent!
            Type baseType = (modelType == null)
                ? typeof(LatexTemplate)
                : typeof(LatexTemplate<>).MakeGenericType(modelType);

            generator.GeneratedClass.BaseTypes.Add(baseType);

            using(StreamReader reader = new StreamReader(new MemoryStream(Encoding.ASCII.GetBytes(template))))
            {
                parser.Parse(reader, generator);
            }

            var statement = new CodeMethodInvokeExpression(new CodeThisReferenceExpression(), "Clear");
            generator.GeneratedExecuteMethod.Statements.Insert(0, new CodeExpressionStatement(statement));

            var builder = new StringBuilder();
            using (var writer = new StringWriter(builder))
            {
                codeDom.GenerateCodeFromCompileUnit(generator.GeneratedCode, writer, new CodeGeneratorOptions());
            }

            var @params = new CompilerParameters();
            foreach (var assembly in AppDomain.CurrentDomain.GetAssemblies())
            {
                if (assembly.IsDynamic)
                    continue;

                try
                {
                    @params.ReferencedAssemblies.Add(assembly.Location);
                }
                catch (Exception ex)
                {
                }
            }

            @params.GenerateInMemory = true;
            @params.IncludeDebugInformation = false;
            @params.GenerateExecutable = false;
            @params.CompilerOptions = "/target:library /optimize";
            string source = builder.ToString();

            var result = codeDom.CompileAssemblyFromSource(@params, new[] { source });
            return result;
        }
コード例 #7
0
ファイル: RazorCompiler.cs プロジェクト: tqc/RazorEngine
 /// <summary>
 /// Parses the specified template.
 /// </summary>
 /// <param name="template">The string template to parse.</param>
 /// <param name="parser">The parser.</param>
 /// <param name="visitor">The parser visitor.</param>
 private static void ParseTemplate(string template, RazorParser parser, ParserVisitor visitor)
 {
     using (var reader = new StreamReader(new MemoryStream(Encoding.UTF8.GetBytes(template))))
     {
         parser.Parse(reader, visitor);
     }
 }
コード例 #8
0
        /// <summary>
        /// Compiles the template.
        /// </summary>
        /// <param name="className">The class name of the dynamic type.</param>
        /// <param name="template">The template to compile.</param>
        /// <param name="modelType">[Optional] The mode type.</param>
        private CompilerResults Compile(string className, string template, Type modelType = null)
        {
            var languageService = provider.CreateLanguageService();
            var codeDom = provider.CreateCodeDomProvider();
            var host = new RazorEngineHost(languageService);

            var generator = languageService.CreateCodeGenerator(className, "Razor.Dynamic", null, host);
            var parser = new RazorParser(languageService.CreateCodeParser(), new HtmlMarkupParser());

            Type baseType = (modelType == null)
                ? typeof(TemplateBase)
                : typeof(TemplateBase<>).MakeGenericType(modelType);

            generator.GeneratedClass.BaseTypes.Add(baseType);

            using (var reader = new StreamReader(new MemoryStream(Encoding.ASCII.GetBytes(template))))
            {
                parser.Parse(reader, generator);
            }

            var statement = new CodeMethodInvokeExpression(new CodeThisReferenceExpression(), "Clear");
            generator.GeneratedExecuteMethod.Statements.Insert(0, new CodeExpressionStatement(statement));

            var builder = new StringBuilder();
            using (var writer = new StringWriter(builder))
            {
                codeDom.GenerateCodeFromCompileUnit(generator.GeneratedCode, writer, new CodeGeneratorOptions());
            }

            var @params = new CompilerParameters();
            foreach (var assembly in AppDomain.CurrentDomain.GetAssemblies())
            {
                if (!assembly.IsDynamic)
                    @params.ReferencedAssemblies.Add(assembly.Location);
            }

            @params.GenerateInMemory = true;
            @params.IncludeDebugInformation = false;
            @params.GenerateExecutable = false;
            @params.CompilerOptions = "/target:library /optimize";
            @params.TempFiles.KeepFiles = KeepFiles;

            var result = codeDom.CompileAssemblyFromSource(@params, new[] { builder.ToString() });
            return result;
        }
コード例 #9
0
        private static Span[] GenerateSpans(string text, SpanKind spanKind, int spanIndex, string spanText)
        {
            Assert.True(spanIndex > 0);

            RazorParser parser = new RazorParser(new CSharpCodeParser(), new HtmlMarkupParser());

            Span[] spans;

            using (var reader = new StringReader(text))
            {
                ParserResults results = parser.Parse(reader);
                spans = results.Document.Flatten().ToArray();
            }

            Assert.True(spans.Length > spanIndex);
            Assert.Equal(spanKind, spans[spanIndex].Kind);
            Assert.Equal(spanText, spans[spanIndex].Content);

            return spans;
        }
コード例 #10
0
ファイル: RazorHtmlSpans.cs プロジェクト: RazorPad/RazorPad
 void ParseTemplate(string html)
 {
     var parser = new RazorParser(codeLanguage.CreateCodeParser(), new HtmlMarkupParser());
     parserResults = parser.Parse(new StringReader(html));
 }