public void GlobalSetup() { var loader = new RazorCompiledItemLoader(); var viewsDll = Path.ChangeExtension(typeof(ViewAssemblyMarker).Assembly.Location, "Views.dll"); var viewsAssembly = Assembly.Load(File.ReadAllBytes(viewsDll)); var services = new ServiceCollection(); var listener = new DiagnosticListener(GetType().Assembly.FullName); var partManager = new ApplicationPartManager(); partManager.ApplicationParts.Add(CompiledRazorAssemblyApplicationPartFactory.GetDefaultApplicationParts(viewsAssembly).Single()); var builder = services .AddSingleton <ILoggerFactory, NullLoggerFactory>() .AddSingleton <ObjectPoolProvider, DefaultObjectPoolProvider>() .AddSingleton <DiagnosticSource>(listener) .AddSingleton(listener) .AddSingleton <IWebHostEnvironment, BenchmarkHostingEnvironment>() .AddSingleton <ApplicationPartManager>(partManager) .AddScoped <BenchmarkViewExecutor>() .AddMvc(); _serviceProvider = services.BuildServiceProvider(); _routeData = new RouteData(); _actionDescriptor = new ActionDescriptor(); _tempDataDictionaryFactory = _serviceProvider.GetRequiredService <ITempDataDictionaryFactory>(); _viewEngine = _serviceProvider.GetRequiredService <ICompositeViewEngine>(); }
private CompilationResult GetCompilation(RazorProjectItem projectItem, RazorProjectFileSystem projectFileSystem) { using (IServiceScope scope = _serviceScopeFactory.CreateScope()) { IServiceProvider serviceProvider = scope.ServiceProvider; // See RazorViewCompiler.CompileAndEmit() RazorProjectEngine projectEngine = serviceProvider.GetRequiredService <RazorProjectEngine>(); RazorCodeDocument codeDocument = projectEngine.Process(projectItem); RazorCSharpDocument cSharpDocument = codeDocument.GetCSharpDocument(); if (cSharpDocument.Diagnostics.Count > 0) { throw (Exception)CreateCompilationFailedException.Invoke( null, new object[] { codeDocument, cSharpDocument.Diagnostics }); } // Use the RazorViewCompiler to finish compiling the view for consistency with layouts IViewCompilerProvider viewCompilerProvider = serviceProvider.GetRequiredService <IViewCompilerProvider>(); IViewCompiler viewCompiler = viewCompilerProvider.GetCompiler(); Assembly assembly = (Assembly)CompileAndEmitMethod.Invoke( viewCompiler, new object[] { codeDocument, cSharpDocument.GeneratedCode }); // Get the runtime item RazorCompiledItemLoader compiledItemLoader = new RazorCompiledItemLoader(); RazorCompiledItem compiledItem = compiledItemLoader.LoadItems(assembly).SingleOrDefault(); return(new CompilationResult(compiledItem)); } }
public virtual void PopulateFeature(IEnumerable <ApplicationPart> parts, ViewsFeature feature) { if (ActiveWidgetTemplates == null) { ActiveWidgetTemplates = new HashSet <string>(); foreach (var item in feature.ViewDescriptors) { string name = Path.GetFileName(item.RelativePath); if (name.StartsWith("Widget.") && !ActiveWidgetTemplates.Contains(name)) { ActiveWidgetTemplates.Add(name); } } } var knownIdentifiers = new HashSet <string>(StringComparer.OrdinalIgnoreCase); var attributes = new RazorCompiledItemLoader().LoadItems(Assembly); foreach (var item in attributes) { var descriptor = new CompiledViewDescriptor(item); if (knownIdentifiers.Add(descriptor.RelativePath)) { string name = Path.GetFileName(descriptor.RelativePath); if (name.StartsWith("Widget.") && !ActiveWidgetTemplates.Contains(name)) { ActiveWidgetTemplates.Add(name); } feature.ViewDescriptors.Add(descriptor); } } }
protected virtual CompiledTemplateDescriptor CompileAndEmit(RazorLightProjectItem projectItem) { Assembly assembly = default(Assembly); if (_razorLightOptions.BinaryCache.TryGetValue($"{projectItem.Key}-Assembly", out var assemblyBinary) && _razorLightOptions.BinaryCache.TryGetValue($"{projectItem.Key}-Assembly", out var pdbBinary)) { assembly = _compiler.Emit(assemblyBinary, pdbBinary); } else { IGeneratedRazorTemplate generatedTemplate = _razorSourceGenerator.GenerateCodeAsync(projectItem).GetAwaiter().GetResult(); var compileResult = _compiler.Compile(generatedTemplate); _razorLightOptions.BinaryCache.CreateEntry($"{projectItem.Key}-Assembly", compileResult.AssemblyStream); _razorLightOptions.BinaryCache.CreateEntry($"{projectItem.Key}-Pdb", compileResult.PdbStream); assembly = _compiler.Emit(compileResult.AssemblyStream, compileResult.PdbStream); } // Anything we compile from source will use Razor 2.1 and so should have the new metadata. var loader = new RazorCompiledItemLoader(); var item = loader.LoadItems(assembly).SingleOrDefault(); var attribute = assembly.GetCustomAttribute <RazorLightTemplateAttribute>(); return(new CompiledTemplateDescriptor() { Item = item, TemplateKey = projectItem.Key, TemplateAttribute = attribute }); }
public RazorTemplateEngineV2() { var thisAssembly = Assembly.GetExecutingAssembly(); var viewAssembly = RelatedAssemblyAttribute.GetRelatedAssemblies(thisAssembly, false).Single(); var razorCompiledItems = new RazorCompiledItemLoader().LoadItems(viewAssembly); foreach (var item in razorCompiledItems) { _razorCompiledItems.Add(item.Identifier, item); } }
public async Task <string> RenderAsync <TModel>(string key, TModel model) { var razorCompiledItem = new RazorCompiledItemLoader().LoadItems(_viewAssembly) .FirstOrDefault(item => item.Identifier == key); if (razorCompiledItem == null) { throw new Exception("Compilation failed"); } return(await GetOutput(_viewAssembly, razorCompiledItem, model)); }
private HashSet <string> GetAvailableTemplates() { HashSet <string> templates = new HashSet <string>(); var attributes = new RazorCompiledItemLoader().LoadItems(this.GetType().Assembly); foreach (var item in attributes) { var descriptor = new CompiledViewDescriptor(item); string name = Path.GetFileName(descriptor.RelativePath); templates.Add(name); } return(templates); }
protected virtual CompiledTemplateDescriptor CompileAndEmit(RazorLightProjectItem projectItem) { IGeneratedRazorTemplate generatedTemplate = _razorSourceGenerator.GenerateCodeAsync(projectItem).GetAwaiter().GetResult(); Assembly assembly = _compiler.CompileAndEmit(generatedTemplate); // Anything we compile from source will use Razor 2.1 and so should have the new metadata. var loader = new RazorCompiledItemLoader(); var item = loader.LoadItems(assembly).SingleOrDefault(); var attribute = assembly.GetCustomAttribute <RazorLightTemplateAttribute>(); return(new CompiledTemplateDescriptor() { Item = item, TemplateKey = projectItem.Key, TemplateAttribute = attribute }); }
internal virtual IReadOnlyList <RazorCompiledItem> LoadItems(AssemblyPart assemblyPart) { if (assemblyPart == null) { throw new ArgumentNullException(nameof(assemblyPart)); } var viewAssembly = assemblyPart.Assembly; if (viewAssembly != null) { var loader = new RazorCompiledItemLoader(); return(loader.LoadItems(viewAssembly)); } return(Array.Empty <RazorCompiledItem>()); }
// Token: 0x06000181 RID: 385 RVA: 0x00007290 File Offset: 0x00005490 protected virtual CompiledViewDescriptor CompileAndEmit(string relativePath) { RazorProjectItem item = this._projectEngine.FileSystem.GetItem(relativePath); RazorCodeDocument razorCodeDocument = this._projectEngine.Process(item); RazorCSharpDocument csharpDocument = RazorCodeDocumentExtensions.GetCSharpDocument(razorCodeDocument); if (csharpDocument.Diagnostics.Count > 0) { //throw CompilationFailedExceptionFactory.Create(razorCodeDocument, csharpDocument.Diagnostics); throw new ApplicationException("csharpDocument.Diagnostics.Count > 0"); } Assembly assembly = this.CompileAndEmit(razorCodeDocument, csharpDocument.GeneratedCode); RazorCompiledItem item2 = new RazorCompiledItemLoader().LoadItems(assembly).SingleOrDefault <RazorCompiledItem>(); RazorViewAttribute customAttribute = assembly.GetCustomAttribute <RazorViewAttribute>(); return(new CompiledViewDescriptor(item2, customAttribute)); }
public Type PageType <TModel>(string view) { var viewAssembly = AssemblyFor <TModel>(); var items = _assemblyItems.GetOrAdd(viewAssembly, a => { var itemLoader = new RazorCompiledItemLoader(); var assemblyItems = itemLoader.LoadItems(viewAssembly); return(assemblyItems); }); var item = items.Where(i => i.Identifier == view).SingleOrDefault(); if (item == null) { throw new Exception($"Could not find view '{view}' in assembly {viewAssembly.Location}. Valid views:\n{string.Join("\n", items.Select(i => i.Identifier))}"); } return(item.Type); }
protected virtual CompiledViewDescriptor CompileAndEmit(string relativePath) { var projectItem = _projectEngine.FileSystem.GetItem(relativePath, fileKind: null); var codeDocument = _projectEngine.Process(projectItem); var cSharpDocument = codeDocument.GetCSharpDocument(); if (cSharpDocument.Diagnostics.Count > 0) { throw CompilationFailedExceptionFactory.Create( codeDocument, cSharpDocument.Diagnostics); } var assembly = CompileAndEmit(codeDocument, cSharpDocument.GeneratedCode); // Anything we compile from source will use Razor 2.1 and so should have the new metadata. var loader = new RazorCompiledItemLoader(); var item = loader.LoadItems(assembly).Single(); return(new CompiledViewDescriptor(item)); }
protected virtual CompiledViewDescriptor CompileAndEmit(string relativePath) { var projectItem = _projectEngine.FileSystem.GetItem(relativePath); var codeDocument = _projectEngine.Process(projectItem); var cSharpDocument = codeDocument.GetCSharpDocument(); if (cSharpDocument.Diagnostics.Count > 0) { throw CompilationFailedExceptionFactory.Create( codeDocument, cSharpDocument.Diagnostics); } var assembly = CompileAndEmit(codeDocument, cSharpDocument.GeneratedCode); var loader = new RazorCompiledItemLoader(); var item = loader.LoadItems(assembly).SingleOrDefault(); var attribute = assembly.GetCustomAttribute <RazorViewAttribute>(); return(new CompiledViewDescriptor(item, attribute)); }
protected virtual CompiledViewDescriptor CompileAndEmit(string relativePath) { var codeDocument = _templateEngine.CreateCodeDocument(relativePath); var cSharpDocument = _templateEngine.GenerateCode(codeDocument); if (cSharpDocument.Diagnostics.Count > 0) { throw CompilationFailedExceptionFactory.Create( codeDocument, cSharpDocument.Diagnostics); } var assembly = CompileAndEmit(codeDocument, cSharpDocument.GeneratedCode); // Anything we compile from source will use Razor 2.1 and so should have the new metadata. var loader = new RazorCompiledItemLoader(); var item = loader.LoadItems(assembly).SingleOrDefault(); var attribute = assembly.GetCustomAttribute <RazorViewAttribute>(); return(new CompiledViewDescriptor(item, attribute)); }
public async Task RunAsync(Assembly assembly, HttpContext httpContext, string viewName, object model) { try { RazorCompiledItemLoader loader = new RazorCompiledItemLoader(); RazorCompiledItem item = loader.LoadItems(assembly).SingleOrDefault(); EmbeddedViewModel view = (EmbeddedViewModel)Activator.CreateInstance(item.Type); view.HttpContext = httpContext; view.ViewName = viewName; view.Html = new Html(httpContext); view.Url = new Url(); if (model != null) { item.Type.GetProperty("Model").SetValue(view, model); } var result = await view.Execute(); if (httpContext.Response.StatusCode == 200 && result is EmbededViewViewResult) { await view.ExecuteAsync(); } if (httpContext.Response.StatusCode == 200 && result is EmbededViewJsonResult) { httpContext.Response.ContentType = "application/json"; await httpContext.Response.WriteAsync(((EmbededViewJsonResult)result).Json); } if (httpContext.Response.StatusCode == 200 && result is EmbededViewRedirectResult) { httpContext.Response.Redirect(((EmbededViewRedirectResult)result).Url); } } finally { BufferedStream bufferedStream = httpContext.Response.Body as BufferedStream; if (bufferedStream != null) { await bufferedStream.FlushAsync(); } } }
public void GlobalSetup() { var current = new DirectoryInfo(AppContext.BaseDirectory); while (current != null && !File.Exists(Path.Combine(current.FullName, Document))) { current = current.Parent; } var root = current; var fileSystem = RazorProjectFileSystem.Create(root.FullName); var className = GetClassName(Document); var viewBaseType = typeof(MockBaseView); var engine = RazorProjectEngine.Create(RazorConfiguration.Default, fileSystem, builder => { builder.AddTargetExtension(new TemplateTargetExtension() { TemplateTypeName = typeof(MockHelperResult).FullName, }); builder .SetNamespace(GetType().Namespace) .SetBaseType(viewBaseType.FullName) .ConfigureClass((document, @class) => { @class.ClassName = GetClassName(document.Source.FilePath); @class.Modifiers.Clear(); @class.Modifiers.Add("public"); }); }); var directiveFeature = engine.EngineFeatures.OfType <IRazorDirectiveFeature>().FirstOrDefault(); var directives = directiveFeature?.Directives.ToArray() ?? Array.Empty <DirectiveDescriptor>(); var compilation = Microsoft.CodeAnalysis.CSharp.CSharpCompilation.Create(GetType().Name + "_" + className); compilation = compilation.WithReferences( MetadataReference.CreateFromFile(Assembly.Load("netstandard").Location), MetadataReference.CreateFromFile(Assembly.Load("System.Runtime").Location), MetadataReference.CreateFromFile(Assembly.Load("System.Runtime.Extensions").Location), // required for TextWriter MetadataReference.CreateFromFile(Assembly.Load("Microsoft.CSharp").Location), // required for dynamic MetadataReference.CreateFromFile(Assembly.Load("System.Linq.Expressions").Location), // https://github.com/dotnet/roslyn/issues/23573#issuecomment-417801552 MetadataReference.CreateFromFile(typeof(Task).Assembly.Location), MetadataReference.CreateFromFile(typeof(IHtmlContent).Assembly.Location), MetadataReference.CreateFromFile(typeof(Hosting.RazorCompiledItem).Assembly.Location), MetadataReference.CreateFromFile(viewBaseType.Assembly.Location) ); compilation = compilation.WithOptions( compilation.Options .WithOutputKind(OutputKind.DynamicallyLinkedLibrary) .WithAssemblyIdentityComparer( DesktopAssemblyIdentityComparer.Default)); var filePath = Path.Combine(root.FullName, Document); var projectItem = fileSystem.GetItem(filePath); var codeDocument = engine.Process(projectItem); var csDocument = codeDocument.GetCSharpDocument(); foreach (var diagnostic in csDocument.Diagnostics) { Console.WriteLine($"{Document}: RAZOR {diagnostic.Id}: {diagnostic.GetMessage()}"); if (diagnostic.Severity == RazorDiagnosticSeverity.Error) { throw new Exception($"{Document} contains invalid cshtml"); } } var csSyntaxTree = CSharpSyntaxTree.ParseText( csDocument.GeneratedCode, path: filePath + ".cs", encoding: Encoding.UTF8); compilation = compilation.AddSyntaxTrees(csSyntaxTree); using (var pe = new MemoryStream()) using (var pdb = new MemoryStream()) { var result = compilation.Emit(pe, pdb); foreach (var diagnostic in result.Diagnostics) { Console.WriteLine(diagnostic.ToString()); } if (!result.Success) { throw new Exception("Compilation failed"); } pe.Position = pdb.Position = 0; var assembly = Assembly.Load(pe.GetBuffer(), pdb.GetBuffer()); var loader = new RazorCompiledItemLoader(); var razorItems = loader.LoadItems(assembly); var item = razorItems.First(x => x.Type.Name == className); _view = (MockBaseView)Activator.CreateInstance(item.Type); } }