Example #1
0
 public PageActionDescriptorProvider(
     RazorProject project,
     IOptions <MvcOptions> options)
 {
     _project = project;
     _options = options.Value;
 }
Example #2
0
 public PageActionInvokerProvider(
     IPageLoader loader,
     IPageFactoryProvider pageFactoryProvider,
     IPageModelFactoryProvider modelFactoryProvider,
     IRazorPageFactoryProvider razorPageFactoryProvider,
     IActionDescriptorCollectionProvider collectionProvider,
     IEnumerable <IFilterProvider> filterProviders,
     ParameterBinder parameterBinder,
     IModelMetadataProvider modelMetadataProvider,
     ITempDataDictionaryFactory tempDataFactory,
     IOptions <MvcOptions> mvcOptions,
     IOptions <HtmlHelperOptions> htmlHelperOptions,
     IPageHandlerMethodSelector selector,
     RazorProject razorProject,
     DiagnosticSource diagnosticSource,
     ILoggerFactory loggerFactory)
 {
     _loader = loader;
     _pageFactoryProvider      = pageFactoryProvider;
     _modelFactoryProvider     = modelFactoryProvider;
     _razorPageFactoryProvider = razorPageFactoryProvider;
     _collectionProvider       = collectionProvider;
     _filterProviders          = filterProviders.ToArray();
     _valueProviderFactories   = mvcOptions.Value.ValueProviderFactories.ToArray();
     _parameterBinder          = parameterBinder;
     _modelMetadataProvider    = modelMetadataProvider;
     _tempDataFactory          = tempDataFactory;
     _htmlHelperOptions        = htmlHelperOptions.Value;
     _selector         = selector;
     _razorProject     = razorProject;
     _diagnosticSource = diagnosticSource;
     _logger           = loggerFactory.CreateLogger <PageActionInvoker>();
 }
        public DefaultPageLoader(
            IOptions <RazorPagesOptions> options,
            RazorProject project,
            CSharpCompilationFactory compilationFactory,
            PageRazorEngineHost host,
            ITagHelperDescriptorResolver tagHelperDescriptorResolver)
        {
            _options            = options.Value;
            _project            = project;
            _compilationFactory = compilationFactory;
            _host = host;

            _tagHelperDescriptorResolver = tagHelperDescriptorResolver;

            _engine = RazorEngineBuilder.Build(builder =>
            {
                builder.Features.Add(new TagHelperFeature(_host.TagHelperDescriptorResolver));
                builder.Features.Add(new VirtualDocumentSyntaxTreePass());
                builder.Features.Add(new TagHelperBinderSyntaxTreePass());
                builder.Features.Add(new DefaultChunkTreeLoweringFeature(_host));

                builder.Features.Add(new PageDirectiveFeature()); // RazorPages-specific feature

                builder.Phases.Add(new DefaultSyntaxTreePhase());
                builder.Phases.Add(new DefaultChunkTreePhase());
                builder.Phases.Add(new DefaultCSharpSourceLoweringPhase(_host));
            });
        }
        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[]
Example #5
0
        private void PrintProjectData(RazorProject project)
        {
            NuGetVersion version = typeof(Jcst).Assembly.GetNuGetPackageVersion();

            this.PrintMessage("Jerrycurl Build Engine");
            if (version == null)
            {
                this.PrintMessage("\tVersion: <unknown>");
            }
            else if (version.CommitHash != null)
            {
                this.PrintMessage($"\tVersion: {version.PublicVersion} ({version.CommitHash})");
            }
            else
            {
                this.PrintMessage($"\tVersion: {version.PublicVersion}");
            }
            this.PrintMessage($"\tProjectName: {this.ProjectName}");
            this.PrintMessage($"\tProjectDirectory: {project.ProjectDirectory}");
            this.PrintMessage($"\tRootNamespace: {this.RootNamespace}");
            this.PrintMessage($"\tSkeletonPath: {this.SkeletonPath}");
            this.PrintMessage($"\tIntermediatePath: {this.IntermediatePath}");

            if (project.Items.Any())
            {
                this.PrintMessage("\tTranspiling:");
            }
        }
Example #6
0
 public void Apply(RazorProject project, IList <RazorPage> result)
 {
     foreach (RazorPage razorFile in result)
     {
         this.ApplyConventions(project, razorFile);
     }
 }
        /// <summary>
        /// Initializes a new instance of the <see cref="RazorViewEngine" />.
        /// </summary>
        public RazorViewEngine(
            IRazorPageFactoryProvider pageFactory,
            IRazorPageActivator pageActivator,
            HtmlEncoder htmlEncoder,
            IOptions <RazorViewEngineOptions> optionsAccessor,
            RazorProject razorProject,
            ILoggerFactory loggerFactory,
            DiagnosticSource diagnosticSource)
        {
            _options = optionsAccessor.Value;

            if (_options.ViewLocationFormats.Count == 0)
            {
                throw new ArgumentException(
                          Resources.FormatViewLocationFormatsIsRequired(nameof(RazorViewEngineOptions.ViewLocationFormats)),
                          nameof(optionsAccessor));
            }

            if (_options.AreaViewLocationFormats.Count == 0)
            {
                throw new ArgumentException(
                          Resources.FormatViewLocationFormatsIsRequired(nameof(RazorViewEngineOptions.AreaViewLocationFormats)),
                          nameof(optionsAccessor));
            }

            _pageFactory      = pageFactory;
            _pageActivator    = pageActivator;
            _htmlEncoder      = htmlEncoder;
            _logger           = loggerFactory.CreateLogger <RazorViewEngine>();
            _razorProject     = razorProject;
            _diagnosticSource = diagnosticSource;
            ViewLookupCache   = new MemoryCache(new MemoryCacheOptions());
        }
Example #8
0
        public override bool Execute()
        {
            RazorProject project = this.CreateRazorProject();
            RazorParser  parser  = new RazorParser();

            this.PrintProjectData(project);

            List <string> filesToCompile = new List <string>();

            Stopwatch watch = Stopwatch.StartNew();

            foreach (RazorPage razorPage in parser.Parse(project))
            {
                RazorGenerator   generator = new RazorGenerator(this.CreateGeneratorOptions());
                ProjectionResult result    = generator.Generate(razorPage.Data);

                Directory.CreateDirectory(Path.GetDirectoryName(razorPage.IntermediatePath));
                File.WriteAllText(razorPage.IntermediatePath, result.Content, Encoding.UTF8);

                this.PrintPageData(razorPage, razorPage.IntermediatePath);

                filesToCompile.Add(razorPage.IntermediatePath);
            }

            this.Compile = filesToCompile.ToArray();

            this.PrintResultData(filesToCompile.Count, watch.ElapsedMilliseconds);

            return(true);
        }
Example #9
0
        private static void RegisterServices(IServiceCollection services)
        {
            services.TryAddEnumerable(ServiceDescriptor.Singleton <IActionDescriptorProvider, PageActionDescriptorProvider>());
            services.TryAddEnumerable(ServiceDescriptor.Singleton <IActionInvokerProvider, PageActionInvokerProvider>());

            services.TryAddSingleton <IPageFactory, DefaultPageFactory>();
            services.TryAddSingleton <IPageActivator, DefaultPageActivator>();
            services.TryAddSingleton <IPageHandlerMethodSelector, DefaultPageHandlerMethodSelector>();

            services.TryAddSingleton <RazorProject>((s) =>
            {
                var options = s.GetRequiredService <IOptions <RazorPagesOptions> >();
                return(RazorProject.Create(new CompositeFileProvider(options.Value.FileProviders)));
            });

            services.TryAddSingleton <IPageLoader, DefaultPageLoader>();
            services.TryAddSingleton <PageRazorEngineHost>();
            services.TryAddSingleton <ReferenceManager, ApplicationPartManagerReferenceManager>();
            services.TryAddSingleton <CSharpCompilationFactory, DefaultCSharpCompilationFactory>();

            services.Replace(ServiceDescriptor.Singleton <IRazorPageActivator, HackedRazorPageActivator>()); // Awful Hack

            services.TryAddSingleton <PageArgumentBinder, DefaultPageArgumentBinder>();

            services.TryAddSingleton <PageResultExecutor>();

            services.TryAddEnumerable(ServiceDescriptor.Transient <IConfigureOptions <RazorPagesOptions>, DefaultRazorPagesOptionsSetup>());

            services.TryAddSingleton <TempDataPropertyProvider>();
        }
Example #10
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);
        }
 /// <summary>
 /// Initializes a new instance of <see cref="MvcRazorTemplateEngine"/>.
 /// </summary>
 /// <param name="engine">The <see cref="RazorEngine"/>.</param>
 /// <param name="project">The <see cref="RazorProject"/>.</param>
 public MvcRazorTemplateEngine(
     RazorEngine engine,
     RazorProject project)
     : base(engine, project)
 {
     Options.ImportsFileName = "_ViewImports.cshtml";
     Options.DefaultImports  = GetDefaultImports();
 }
Example #12
0
        public DefaultPageLoader(
            IOptions <RazorPagesOptions> options,
            RazorProject project,
            CSharpCompilationFactory compilationFactory,
            PageRazorEngineHost host,
            ITagHelperDescriptorResolver tagHelperDescriptorResolver)
        {
            _options            = options.Value;
            _project            = project;
            _compilationFactory = compilationFactory;
            _host = host;

            _tagHelperDescriptorResolver = tagHelperDescriptorResolver;

            // TODO: Code smell, this is newed up in several locations. We should find a unified location for this.
            var attributeContext = new GeneratedTagHelperAttributeContext()
            {
                CreateModelExpressionMethodName     = "CreateModelExpression",
                ModelExpressionProviderPropertyName = "ModelExpressionProvider",
                ModelExpressionTypeName             = "Microsoft.AspNetCore.Mvc.ViewFeatures.ModelExpression",
                ViewDataPropertyName = "ViewData",
            };

            _engine = RazorEngineBuilder.Build(builder =>
            {
                builder.Features.Add(new TagHelperFeature(_host.TagHelperDescriptorResolver));
                builder.Features.Add(new VirtualDocumentSyntaxTreePass());
                builder.Features.Add(new TagHelperBinderSyntaxTreePass());

                builder.Features.Add(new InstrumentationPass(_host));
                builder.Features.Add(new PreallocatedTagHelperAttributePass());

                // MVC specific features
                builder.Features.Add(new ModelExpressionAttributePass(attributeContext));
                builder.Features.Add(new InjectDirectiveRenderer(typeof(RazorInjectAttribute).FullName));

                builder.Features.Add(new DefaultChunkTreeLoweringFeature(_host));
                builder.Features.Add(new DefaultCSharpSourceLoweringFeature(_host));

                // Renderers
                builder.Features.Add(new RuntimeCSharpRenderer());
                builder.Features.Add(new PageStructureCSharpRenderer());

                builder.Features.Add(new PageDirectiveFeature()); // RazorPages-specific feature
                builder.Features.Add(new PagesPropertyInjectionPass());
                builder.Features.Add(new RazorDirectiveDiscoveryPass());

                builder.Phases.Add(new DefaultSyntaxTreePhase());
                builder.Phases.Add(new DefaultChunkTreePhase());

                // New Razor generation phases.
                builder.Phases.Add(new DefaultCSharpSourceLoweringPhase());
                builder.Phases.Add(new DefaultCSharpDocumentGenerationPhase(_host));

                // Uncomment the below line to force old-style view rendering.
                // builder.Phases.Add(new Razevolution.DefaultCSharpSourceLoweringPhase(_host));
            });
        }
Example #13
0
 public TestPageLoader(
     IOptions <RazorPagesOptions> options,
     RazorProject project,
     CSharpCompilationFactory compilationFactory,
     PageRazorEngineHost host,
     ITagHelperDescriptorResolver tagHelperDescriptorResolver)
     : base(options, project, compilationFactory, host, tagHelperDescriptorResolver)
 {
 }
Example #14
0
 public RazorProjectPageRouteModelProvider(
     RazorProject razorProject,
     IOptions <RazorPagesOptions> pagesOptionsAccessor,
     ILoggerFactory loggerFactory)
 {
     _project      = razorProject;
     _pagesOptions = pagesOptionsAccessor.Value;
     _logger       = loggerFactory.CreateLogger <RazorProjectPageRouteModelProvider>();
 }
Example #15
0
        internal RazorCompilerResult ToCSharpByContent(string content)
        {
            var razorEngine    = GetRazorEngine();
            var razorProject   = RazorProject.Create(BasePath);
            var projectItem    = new ContentRazorProjectItem(content);
            var templateEngine = GetTemplateEngine(razorEngine, razorProject);

            return(GetCompilerResult(templateEngine, projectItem));
        }
Example #16
0
        private RazorTemplateEngine GetTemplateEngine(RazorEngine razorEngine, RazorProject razorProject)
        {
            var templateEngine = new RazorTemplateEngine(razorEngine, razorProject);

            templateEngine.Options.DefaultImports = RazorSourceDocument.Create(@"
        @using System
        @using System.Threading.Tasks
        ", fileName: null);
            return(templateEngine);
        }
        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 file. My 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[]
            {
                MetadataReference.CreateFromFile(typeof(object).Assembly.Location),         // include corlib
                MetadataReference.CreateFromFile(Assembly.GetExecutingAssembly().Location), // this file (that contains the MyTemplate base class)
                // for some reason on .NET core, I need to add this... this is not needed with .NET framework
                MetadataReference.CreateFromFile(Path.Combine(Path.GetDirectoryName(typeof(object).Assembly.Location), "System.Runtime.dll")),
            },
                                                                new CSharpCompilationOptions(OutputKind.DynamicallyLinkedLibrary)); // we want a dll
            // compile the dll
            string path   = Path.Combine(Path.GetFullPath("."), dllName + ".dll");
            var    result = compilation.Emit(path);

            if (!result.Success)
            {
                Console.WriteLine(string.Join(Environment.NewLine, result.Diagnostics));
                return;
            }
            // load the built DLL
            Console.WriteLine(path);
            var asm = Assembly.LoadFile(path);
            // the generated type is defined in our custom namespace, as we asked. "Template" is the type name that razor uses by default.
            var template = (MyTemplate)Activator.CreateInstance(asm.GetType("MyNamespace.Template"));

            // run the code.
            // should display "Hello Killroy, welcome to Razor World!"
            template.ExecuteAsync().Wait();
        }
Example #18
0
        public static IList <RazorPageGeneratorResult> MainCore(string rootNamespace, string targetProjectDirectory)
        {
            var razorEngine = RazorEngine.Create(builder =>
            {
                builder
                .SetNamespace(rootNamespace)
                .SetBaseType("Microsoft.Extensions.RazorViews.BaseView")
                .ConfigureClass((document, @class) =>
                {
                    @class.ClassName = Path.GetFileNameWithoutExtension(document.Source.FilePath);
                    @class.Modifiers.Clear();
                    @class.Modifiers.Add("internal");
                });

                builder.Features.Add(new SuppressChecksumOptionsFeature());
            });

            var viewDirectories = Directory.EnumerateDirectories(targetProjectDirectory, "Views", SearchOption.AllDirectories);
            var razorProject    = RazorProject.Create(targetProjectDirectory);
            var templateEngine  = new RazorTemplateEngine(razorEngine, razorProject);

            templateEngine.Options.DefaultImports = RazorSourceDocument.Create(@"
@using System
@using System.Threading.Tasks
", fileName: null);

            var fileCount = 0;

            var results = new List <RazorPageGeneratorResult>();

            foreach (var viewDir in viewDirectories)
            {
                Console.WriteLine();
                Console.WriteLine("  Generating code files for views in {0}", viewDir);
                var viewDirPath = viewDir.Substring(targetProjectDirectory.Length).Replace('\\', '/');
                var cshtmlFiles = razorProject.EnumerateItems(viewDirPath);

                if (!cshtmlFiles.Any())
                {
                    Console.WriteLine("  No .cshtml files were found.");
                    continue;
                }

                foreach (var item in cshtmlFiles)
                {
                    Console.WriteLine("    Generating code file for view {0}...", item.FileName);
                    results.Add(GenerateCodeFile(templateEngine, item));
                    Console.WriteLine("      Done!");
                    fileCount++;
                }
            }

            return(results);
        }
Example #19
0
        public RazorPagesSitemapMiddleware(IActionDescriptorCollectionProvider actionDescriptors, RazorProject razorProject, IOptions <RazorPagesSitemapOptions> options)
        {
            _actionDescriptorCollectionProvider = actionDescriptors;
            _razorProject = razorProject;
            _options      = options.Value;

            if (!string.IsNullOrEmpty(_options.IgnoreExpression))
            {
                _ignoreExpression = new Regex(_options.IgnoreExpression, RegexOptions.Compiled);
            }
        }
Example #20
0
        private void ApplyConventions(RazorProject project, RazorPage razorPage)
        {
            if (razorPage.Data.Class == null)
            {
                razorPage.Data.Class = this.GetClassDirectiveFromFileName(razorPage);
            }

            if (razorPage.ProjectPath != null && razorPage.Data.Namespace == null)
            {
                razorPage.Data.Namespace = this.GetNamespaceDirectiveFromFileName(project, razorPage);
            }
        }
Example #21
0
        private RazorFragment GetNamespaceDirectiveFromFileName(RazorProject project, RazorPage razorPage)
        {
            Namespace ns = Namespace.FromPath(Path.GetDirectoryName(razorPage.ProjectPath));

            if (!string.IsNullOrEmpty(project.RootNamespace))
            {
                ns = new Namespace(project.RootNamespace).Add(ns);
            }

            return(new RazorFragment()
            {
                Text = ns.ToString(),
            });
        }
Example #22
0
        private void PrintProjectData(RazorProject project)
        {
            this.PrintMessage("Jerrycurl Build Engine");
            this.PrintMessage($"\tVersion: " + typeof(Jcst).Assembly.GetNuGetPackageVersion() ?? "<unknown>");
            this.PrintMessage($"\tProjectName: {this.ProjectName}");
            this.PrintMessage($"\tProjectDirectory: {project.ProjectDirectory}");
            this.PrintMessage($"\tRootNamespace: {this.RootNamespace}");
            this.PrintMessage($"\tSkeletonPath: {this.SkeletonPath}");
            this.PrintMessage($"\tIntermediatePath: {this.IntermediatePath}");

            if (project.Items.Any())
            {
                this.PrintMessage("\tTranspiling:");
            }
        }
 /// <summary>
 /// Initializes a new instance of the <see cref="RazorViewEngine" />.
 /// </summary>
 public MultiTemplateEngine(
     IRazorPageFactoryProvider pageFactory,
     IRazorPageActivator pageActivator,
     HtmlEncoder htmlEncoder,
     IOptions <RazorViewEngineOptions> optionsAccessor,
     ILoggerFactory loggerFactory,
     RazorProject razorProject)
 {
     _options        = optionsAccessor.Value;
     _pageFactory    = pageFactory;
     _pageActivator  = pageActivator;
     _htmlEncoder    = htmlEncoder;
     _logger         = loggerFactory.CreateLogger <RazorViewEngine>();
     _razorProject   = razorProject;
     ViewLookupCache = new MemoryCache(new MemoryCacheOptions());
 }
Example #24
0
        public static void Transpile(RunnerArgs args)
        {
            string projectDirectory = args.Options["-p", "--project"]?.Value ?? Environment.CurrentDirectory;
            string rootNamespace    = args.Options["-ns", "--namespace"]?.Value;
            string sourcePath       = Path.GetDirectoryName(typeof(DotNetJerryHost).Assembly.Location);
            string skeletonPath     = Path.Combine(sourcePath, "skeleton.jerry");
            string outputDirectory  = args.Options["-o", "--output"]?.Value;

            if (!Directory.Exists(projectDirectory))
            {
                throw new RunnerException($"Project directory '{projectDirectory}' does not exist.");
            }

            if (!File.Exists(skeletonPath))
            {
                throw new RunnerException("Skeleton file not found.");
            }

            projectDirectory = PathHelper.MakeAbsolutePath(Environment.CurrentDirectory, projectDirectory);
            outputDirectory  = PathHelper.MakeAbsolutePath(projectDirectory, outputDirectory ?? RazorProjectConventions.DefaultIntermediateDirectory);

            RazorProject project = new RazorProject()
            {
                ProjectDirectory      = projectDirectory,
                RootNamespace         = rootNamespace,
                Items                 = new List <RazorProjectItem>(),
                IntermediateDirectory = outputDirectory,
            };

            if (args.Options["-f", "--file"] != null)
            {
                foreach (string file in args.Options["-f", "--file"].Values)
                {
                    foreach (string expandedFile in ResponseFile.ExpandStrings(file, project.ProjectDirectory))
                    {
                        if (!HasPipeFormat(expandedFile, out var fullPath, out var projectPath))
                        {
                            project.AddItem(expandedFile);
                        }
                        else if (!string.IsNullOrEmpty(fullPath))
                        {
                            project.Items.Add(new RazorProjectItem()
                            {
                                FullPath = MakeAbsolutePath(fullPath), ProjectPath = projectPath
                            });
                        }
                    }
Example #25
0
        private void _Init(string templateNamespace, string typeName, string basePath)
        {
            if (string.IsNullOrWhiteSpace(templateNamespace))
            {
                throw new ArgumentNullException(nameof(templateNamespace), "Cannot be null or empty.");
            }

            if (string.IsNullOrWhiteSpace(typeName))
            {
                throw new ArgumentNullException(nameof(typeName), "Cannot be null or empty.");
            }

            // 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
                FunctionsDirective.Register(b);    // make sure the engine understand the @function directive in the input templates
                SectionDirective.Register(b);      // make sure the engine understand the @section directive in the input templates
                b.SetNamespace(templateNamespace); // define a namespace for the Template class
                b.Build();
            });

            var project        = RazorProject.Create(HostingEnvironment.ContentRootPath);
            var templateEngine = 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 fileInfo = _FindView(typeName, basePath, out var filepath);

            // ... parse and generate C# code ...
            var codeDoc = RazorCSharpDocument.Create();
            var cs      = templateEngine.GenerateCode(codeDoc);

            // ... use roslyn to parse the C# code ...
            //
            var tree = CSharpSyntaxTree.ParseText(cs.GeneratedCode);

            // ... name the assembly ...
            //
            string dllName = templateNamespace + "." + typeName;

            var compilation = CSharpCompilation.Create(dllName, new[] { tree },
                                                       new[]
        public override RazorTemplateEngine Create(string projectPath, Action <IRazorEngineBuilder> configure)
        {
            if (projectPath == null)
            {
                throw new ArgumentNullException(nameof(projectPath));
            }

            // In 15.5 we expect projectPath to be a directory, NOT the path to the csproj.
            var project              = FindProject(projectPath);
            var configuration        = (project?.Configuration as MvcExtensibilityConfiguration) ?? DefaultConfiguration;
            var razorLanguageVersion = configuration.LanguageVersion;
            var razorConfiguration   = new RazorConfiguration(razorLanguageVersion, "unnamed", Array.Empty <RazorExtension>(), designTime: true);

            RazorEngine engine;

            if (razorLanguageVersion.Major == 1)
            {
                engine = RazorEngine.CreateCore(razorConfiguration, b =>
                {
                    configure?.Invoke(b);

                    Mvc1_X.RazorExtensions.Register(b);

                    if (configuration.MvcAssembly.Identity.Version.Minor >= 1)
                    {
                        Mvc1_X.RazorExtensions.RegisterViewComponentTagHelpers(b);
                    }
                });

                var templateEngine = new Mvc1_X.MvcRazorTemplateEngine(engine, RazorProject.Create(projectPath));
                templateEngine.Options.ImportsFileName = "_ViewImports.cshtml";
                return(templateEngine);
            }
            else
            {
                engine = RazorEngine.CreateCore(razorConfiguration, b =>
                {
                    configure?.Invoke(b);

                    MvcLatest.RazorExtensions.Register(b);
                });

                var templateEngine = new MvcLatest.MvcRazorTemplateEngine(engine, RazorProject.Create(projectPath));
                templateEngine.Options.ImportsFileName = "_ViewImports.cshtml";
                return(templateEngine);
            }
        }
Example #27
0
        public void Setup()
        {
            var razorProject = RazorProject.Create(AppDomain.CurrentDomain.BaseDirectory);
            var razorEngine = RazorEngine.Create(b =>
            {
                b.SetNamespace("Some.Namespace");
                b.SetBaseType(typeof(MinimalistRazorTemplate).FullName);
            });
            var razorTemplateEngine = new RazorTemplateEngine(razorEngine, razorProject);

            var references = AppDomain.CurrentDomain.GetAssemblies()
                .Where(a => !a.IsDynamic)
                .Select(a => MetadataReference.CreateFromFile(a.Location))
                .ToList();
            var emitOptions = new EmitOptions(debugInformationFormat: We.SupportFullPdb() ? DebugInformationFormat.Pdb : DebugInformationFormat.PortablePdb);
            _renderer = new RazorViewCompiler(razorTemplateEngine, references, emitOptions);
        }
Example #28
0
        private static PageActionInvokerProvider CreateInvokerProvider(
            IPageLoader loader,
            IActionDescriptorCollectionProvider actionDescriptorProvider,
            IPageFactoryProvider pageProvider                  = null,
            IPageModelFactoryProvider modelProvider            = null,
            IRazorPageFactoryProvider razorPageFactoryProvider = null,
            RazorProject razorProject = null)
        {
            var tempDataFactory = new Mock <ITempDataDictionaryFactory>();

            tempDataFactory
            .Setup(t => t.GetTempData(It.IsAny <HttpContext>()))
            .Returns((HttpContext context) => new TempDataDictionary(context, Mock.Of <ITempDataProvider>()));

            if (razorProject == null)
            {
                razorProject = Mock.Of <RazorProject>();
            }

            var modelMetadataProvider = TestModelMetadataProvider.CreateDefaultProvider();
            var modelBinderFactory    = TestModelBinderFactory.CreateDefault();
            var parameterBinder       = new ParameterBinder(
                modelMetadataProvider,
                TestModelBinderFactory.CreateDefault(),
                Mock.Of <IModelValidatorProvider>(),
                NullLoggerFactory.Instance);

            return(new PageActionInvokerProvider(
                       loader,
                       pageProvider ?? Mock.Of <IPageFactoryProvider>(),
                       modelProvider ?? Mock.Of <IPageModelFactoryProvider>(),
                       razorPageFactoryProvider ?? Mock.Of <IRazorPageFactoryProvider>(),
                       actionDescriptorProvider,
                       new IFilterProvider[0],
                       parameterBinder,
                       modelMetadataProvider,
                       modelBinderFactory,
                       tempDataFactory.Object,
                       Options.Create(new MvcOptions()),
                       Options.Create(new HtmlHelperOptions()),
                       Mock.Of <IPageHandlerMethodSelector>(),
                       razorProject,
                       new DiagnosticListener("Microsoft.AspNetCore"),
                       NullLoggerFactory.Instance));
        }
Example #29
0
        /// <summary>
        /// Initializes a new instance of <see cref="RazorTemplateEngine"/>.
        /// </summary>
        /// <param name="engine">The <see cref="RazorEngine"/>.</param>
        /// <param name="project">The <see cref="RazorProject"/>.</param>
        public RazorTemplateEngine(
            RazorEngine engine,
            RazorProject project)
        {
            if (engine == null)
            {
                throw new ArgumentNullException(nameof(engine));
            }

            if (project == null)
            {
                throw new ArgumentNullException(nameof(project));
            }

            Engine   = engine;
            Project  = project;
            _options = new RazorTemplateEngineOptions();
        }
        protected override RazorPageGeneratorResult Generate(string rootNamespace, string targetPath, Type modelType)
        {
            var baseTypeName = "KiraNet.GutsMvc.View.RazorPageViewBase";

            if (modelType != null)
            {
                baseTypeName = $"{baseTypeName}<{TypeHelper.GetCSharpTypeName(modelType)}>";
            }

            var className   = String.Empty;
            var razorEngine = RazorEngine.Create(builder =>
            {
                builder
                .SetNamespace(rootNamespace)
                .SetBaseType(baseTypeName)
                .ConfigureClass((document, @class) =>
                {
                    @class.ClassName = className = Path.GetFileNameWithoutExtension(document.Source.FilePath) + DateTime.Now.Ticks;
                    @class.Modifiers.Clear();
                    @class.Modifiers.Add("internal");
                });

                builder.Features.Add(new SuppressChecksumOptionsFeature());
            });

            var razorProject   = RazorProject.Create(ViewPath.Path);
            var templateEngine = new RazorTemplateEngine(razorEngine, razorProject);

            templateEngine.Options.DefaultImports = RazorSourceDocument.Create(@"
                @using System
                @using System.Threading.Tasks
                @using System.Collections.Generic
                @using System.Collections
                ", fileName: null);


            //templateEngine.Options.DefaultImports = RazorSourceDocument.Create("", null);
            var cshtmlFile  = razorProject.GetItem(targetPath);
            var razorResult = GenerateCodeFile(templateEngine, cshtmlFile);

            razorResult.ClassName = className;
            return(razorResult);
        }