public override RazorTemplateEngine Create(string projectPath, Action <IRazorEngineBuilder> configure)
        {
            if (projectPath == null)
            {
                throw new ArgumentNullException(nameof(projectPath));
            }

            var engine = RazorEngine.CreateDesignTime(b =>
            {
                configure?.Invoke(b);

                // For now we're hardcoded to use MVC's extensibility.
                RazorExtensions.Register(b);
            });

            var templateEngine = new MvcRazorTemplateEngine(engine, RazorProject.Create(projectPath));

            templateEngine.Options.ImportsFileName = "_ViewImports.cshtml";
            return(templateEngine);
        }
示例#2
0
        private int ExecuteCore(string projectDirectory, string outputDirectory, string tagHelperManifest, string[] sources)
        {
            var tagHelpers = GetTagHelpers(tagHelperManifest);

            var engine = RazorEngine.Create(b =>
            {
                RazorExtensions.Register(b);

                b.Features.Add(new StaticTagHelperFeature()
                {
                    TagHelpers = tagHelpers,
                });
            });

            var templateEngine = new MvcRazorTemplateEngine(engine, RazorProject.Create(projectDirectory));

            var sourceItems = GetRazorFiles(projectDirectory, sources);
            var results     = GenerateCode(templateEngine, sourceItems);

            var success = true;

            foreach (var result in results)
            {
                if (result.CSharpDocument.Diagnostics.Count > 0)
                {
                    success = false;
                    foreach (var error in result.CSharpDocument.Diagnostics)
                    {
                        Console.Error.WriteLine(error.ToString());
                    }
                }

                var outputFilePath = Path.Combine(outputDirectory, Path.ChangeExtension(result.ViewFileInfo.ViewEnginePath.Substring(1), ".cs"));
                File.WriteAllText(outputFilePath, result.CSharpDocument.GeneratedCode);
            }

            return(success ? 0 : -1);
        }
        public CodeGenerationBenchmark()
        {
            var current = new DirectoryInfo(AppContext.BaseDirectory);

            while (current != null && !File.Exists(Path.Combine(current.FullName, "MSN.cshtml")))
            {
                current = current.Parent;
            }

            var root = current;

            var engine = RazorEngine.Create(b => { RazorExtensions.Register(b); });

            var project = RazorProject.Create(root.FullName);

            DesignTimeTemplateEngine = new MvcRazorTemplateEngine(RazorEngine.CreateDesignTime(b => { RazorExtensions.Register(b); }), project);
            RuntimeTemplateEngine    = new MvcRazorTemplateEngine(RazorEngine.Create(b => { RazorExtensions.Register(b); }), project);

            var codeDocument = RuntimeTemplateEngine.CreateCodeDocument(Path.Combine(root.FullName, "MSN.cshtml"));

            Imports = codeDocument.Imports;
            MSN     = codeDocument.Source;
        }
示例#4
0
        public void GetCompilationFailedResult_UsesPhysicalPath()
        {
            // Arrange
            var viewPath     = "/Views/Home/Index.cshtml";
            var physicalPath = @"x:\myapp\views\home\index.cshtml";

            var fileSystem = new VirtualRazorProjectFileSystem();

            fileSystem.Add(new TestRazorProjectItem(viewPath, "<span name=\"@(User.Id\">", physicalPath: physicalPath));

            var razorEngine    = RazorEngine.Create();
            var templateEngine = new MvcRazorTemplateEngine(razorEngine, fileSystem);

            var codeDocument = templateEngine.CreateCodeDocument(viewPath);

            // Act
            var csharpDocument    = templateEngine.GenerateCode(codeDocument);
            var compilationResult = CompilationFailedExceptionFactory.Create(codeDocument, csharpDocument.Diagnostics);

            // Assert
            var failure = Assert.Single(compilationResult.CompilationFailures);

            Assert.Equal(physicalPath, failure.SourceFilePath);
        }
示例#5
0
        public MvcServiceProvider(
            string projectPath,
            string applicationName,
            string contentRoot,
            string configureCompilationType)
        {
            _projectPath     = projectPath;
            _contentRoot     = contentRoot;
            _applicationName = applicationName;

            var mvcBuilderConfiguration = GetConfigureCompilationAction(configureCompilationType);
            var serviceProvider         = GetProvider(mvcBuilderConfiguration);

            Engine         = serviceProvider.GetRequiredService <RazorEngine>();
            TemplateEngine = new MvcRazorTemplateEngine(Engine, serviceProvider.GetRequiredService <RazorProject>())
            {
                Options =
                {
                    ImportsFileName = "_ViewImports.cshtml",
                }
            };
            Compiler          = serviceProvider.GetRequiredService <CSharpCompiler>();
            ViewEngineOptions = serviceProvider.GetRequiredService <IOptions <RazorViewEngineOptions> >().Value;
        }
示例#6
0
        /// <summary>
        ///
        /// </summary>
        /// <param name="project"></param>
        /// <param name="key"></param>
        /// <param name="model"></param>
        /// <param name="isMainPage"></param>
        /// <returns></returns>
        public async Task <string> CompileRenderAsync(
            DynamicRazorProject project,
            string key,
            object model,
            bool isMainPage = true,
            ActionDescriptor actionDescriptor = null)
        {
            if (project == null)
            {
                throw new ArgumentNullException(nameof(project));
            }

            var templateEngine = new MvcRazorTemplateEngine(_engine, project);

            var httpContext = new CustomHttpContext(_httpContextAccessor?.HttpContext);

            httpContext.RequestServices = _serviceProvider;

            _razorEngineOptions.Value.ViewLocationFormats.Insert(0, "/{0}.cshtml");

            var projectID = project.GetHashCode().ToString();

            var viewCompilerProvider = new DynamicRazorViewCompilerProvider(
                _applicationPartManager,
                templateEngine,
                _razorViewEngineFileProviderAccessor,
                _cSharpCompiler,
                _projectCacheProvider.GetCache(projectID),
                _razorEngineOptions,
                _loggerFactory);

            var engine = new RazorViewEngine(
                new DefaultRazorPageFactoryProvider(viewCompilerProvider),
                _razorPageActivator,
                _htmlEncoder,
                _razorEngineOptions,
                project,
                _loggerFactory,
                _diagnosticSource);

            var viewResult = engine.GetView(null, ViewPath.NormalizePath(key), isMainPage);

            if (!viewResult.Success)
            {
                throw new InvalidOperationException("View Not Found");
            }

            var actionContext = new ActionContext(httpContext, new RouteData(), actionDescriptor ?? new ActionDescriptor());

            var viewContext = new ViewContext(
                actionContext,
                viewResult.View,
                new ViewDataDictionary(new EmptyModelMetadataProvider(), new ModelStateDictionary()),
                _tempDataDictionaryFactory.GetTempData(httpContext),
                TextWriter.Null,
                _mvcViewOptions.Value.HtmlHelperOptions);

            viewContext.ViewData.Model = model;

            var sb = new StringBuilder();

            using (var sw = new StringWriter(sb))
            {
                viewContext.Writer = sw;
                await viewContext.View.RenderAsync(viewContext);
            }

            return(sb.ToString());
        }