private static Type CompileView(GeneratorResults razorResult, CompilerParameters compilerParameters) { var codeProvider = new CSharpCodeProvider(CompilerProperties); var result = codeProvider.CompileAssemblyFromDom(compilerParameters, razorResult.GeneratedCode); if (result.Errors != null && result.Errors.HasErrors) { throw new RazorCompilerException(result.Errors.OfType<CompilerError>().Where(x => !x.IsWarning)); } var assembly = Assembly.LoadFrom(compilerParameters.OutputAssembly); if (assembly == null) { throw new RazorCompilerException("Unable to load view assembly."); } var type = assembly.GetType(SimpleRazorConfiguration.Namespace + "." + compilerParameters.MainClass); if (type == null) { throw new RazorCompilerException("Unable to load view assembly."); } return type; }
public CompilerResults Compile(GeneratorResults generatorResults) { var parameters = CompilationParameters.CompilerParameters; var codeProvider = CompilationParameters.CodeProvider; var generatedCode = generatorResults.GeneratedCode; var compiledCode = codeProvider.CompileAssemblyFromDom(parameters, generatedCode); return compiledCode; }
/// <summary> /// Inspects the GeneratorResults and returns the source code. /// </summary> /// <param name="results"></param> /// <param name="context"></param> /// <returns></returns> public override string InspectSource(GeneratorResults results, TypeContext context) { string generatedCode; var builder = new StringBuilder(); using (var writer = new StringWriter(builder, CultureInfo.InvariantCulture)) { _codeDomProvider.GenerateCodeFromCompileUnit(results.GeneratedCode, writer, new CodeGeneratorOptions()); generatedCode = builder.ToString(); } return generatedCode; }
protected internal virtual void ProcessChange(CancellationToken cancelToken, TextChange change, Block parseTree) { try { if (!cancelToken.IsCancellationRequested) { GeneratorResults results = null; RazorTemplateEngine engine = new RazorTemplateEngine(_host); // Seek the buffer to the beginning change.NewBuffer.Position = 0; try { results = engine.GenerateCode(change.NewBuffer, className: null, rootNamespace: null, sourceFileName: _sourceFileName, cancelToken: cancelToken); } catch (OperationCanceledException) { // We've been cancelled, so just return. return; } // Parsing complete! Check if we're still active: bool lockTaken = false; _syncLock.Enter(ref lockTaken); if (lockTaken && !cancelToken.IsCancellationRequested) { // We're still active, check for tree changes, then update the parse tree bool treeStructureChanged = parseTree == null || TreesAreDifferent(parseTree, results.Document, change); Interlocked.Exchange(ref _currentParseTree, results.Document); Interlocked.Exchange(ref _lastChangeOwner, null); #if DEBUG Interlocked.Exchange(ref _currentCodeCompileUnit, results.GeneratedCode); #endif _parseUnderway = false; // Done, now exit the lock and fire the event _syncLock.Exit(); OnDocumentParseComplete(new DocumentParseCompleteEventArgs() { GeneratorResults = results, SourceChange = change, TreeStructureChanged = treeStructureChanged }); } } } finally { // Make sure we release the lock if we're holding it if (_syncLock.IsHeldByCurrentThread) { _syncLock.Exit(); } } }
private RazorViewBase GenerateRazorView(CodeDomProvider codeProvider, GeneratorResults razorResult) { // Compile the generated code into an assembly string outputAssemblyName = String.Format("Temp_{0}.dll", Guid.NewGuid().ToString("N")); CompilerResults results = codeProvider.CompileAssemblyFromDom( new CompilerParameters(new string[] { GetAssemblyPath(typeof(Microsoft.CSharp.RuntimeBinder.Binder)), GetAssemblyPath(typeof(System.Runtime.CompilerServices.CallSite)), GetAssemblyPath(Assembly.GetExecutingAssembly()) }, outputAssemblyName), razorResult.GeneratedCode); if (results.Errors.HasErrors) { CompilerError err = results.Errors .OfType<CompilerError>() .Where(ce => !ce.IsWarning) .First(); var error = String.Format("Error Compiling Template: ({0}, {1}) {2})", err.Line, err.Column, err.ErrorText); return new ErrorView(error); } else { // Load the assembly Assembly assembly = Assembly.LoadFrom(outputAssemblyName); if (assembly == null) { string error = "Error loading template assembly"; return new ErrorView(error); } else { // Get the template type Type type = assembly.GetType("RazorOutput.RazorView"); if (type == null) { string error = String.Format("Could not find type RazorOutput.Template in assembly {0}", assembly.FullName); return new ErrorView(error); } else { RazorViewBase view = Activator.CreateInstance(type) as RazorViewBase; if (view == null) { string error = "Could not construct RazorOutput.Template or it does not inherit from RazorViewBase"; return new ErrorView(error); } else { return view; } } } } }
private string CompileCode(GeneratorResults razorResult) { var codeProvider = new CSharpCodeProvider(); string outputAssemblyName = String.Format("Temp_{0}.dll", Guid.NewGuid().ToString("N")); codeProvider.CompileAssemblyFromDom( new CompilerParameters(new[] { typeof (Form1).Assembly.CodeBase.Replace("file:///", "").Replace("/", "\\"), "System.Core.dll", "Microsoft.CSharp.dll" }, outputAssemblyName), razorResult.GeneratedCode); return outputAssemblyName; }
public void SetGeneratorResults(GeneratorResults generatorResults) { if (generatorResults == null) return; Success = generatorResults.Success; ParsedDocument = ParseNode(generatorResults.Document); Messages = from error in generatorResults.ParserErrors select new TemplateMessage { Kind = TemplateMessageKind.Error, Text = error.ToString(), }; }
private void OnParseCompleted(GeneratorResults results, BackgroundParseTask parseTask) { try { // Lock the state objects bool treeStructureChanged = true; TextChange lastChange; lock (_lock) { // Are we still active? if (_outstandingParserTasks.Count == 0 || !ReferenceEquals(parseTask, _outstandingParserTasks.Peek())) { // We aren't, just abort return; } // Ok, we're active. Flush out the changes from all the parser tasks and clear the stack of outstanding parse tasks TextChange[] changes = _outstandingParserTasks.Select(t => t.Change).Reverse().ToArray(); lastChange = changes.Last(); _outstandingParserTasks.Clear(); // Take the current tree and check for differences treeStructureChanged = CurrentParseTree == null || TreesAreDifferent(CurrentParseTree, results.Document, changes); CurrentParseTree = results.Document; #if DEBUG _currentCompileUnit = results.GeneratedCode; #endif _lastChangeOwner = null; } // Done, now exit the lock and fire the event OnDocumentParseComplete(new DocumentParseCompleteEventArgs() { GeneratorResults = results, SourceChange = lastChange, TreeStructureChanged = treeStructureChanged }); } finally { parseTask.Dispose(); } }
private string ExecuteInternal(GeneratorResults razorResults, string defaultnamespace, string defaultclassname, IDictionary<string, object> bulaqData) { using (var provider = new CSharpCodeProvider()) { var compiler = new CompilerParameters(); compiler.ReferencedAssemblies.Add("System.dll"); compiler.ReferencedAssemblies.Add("System.Core.dll"); compiler.ReferencedAssemblies.Add("Microsoft.CSharp.dll"); compiler.ReferencedAssemblies.Add(AppDomain.CurrentDomain.BaseDirectory + "\\bin\\BulaqCMS.Models.dll"); compiler.ReferencedAssemblies.Add(Assembly.GetExecutingAssembly().Location); compiler.GenerateInMemory = true; var result = provider.CompileAssemblyFromDom(compiler, razorResults.GeneratedCode); if (result.Errors.HasErrors) { var error = result.Errors.OfType<CompilerError>().Where(i => !i.IsWarning).FirstOrDefault(); if (error != null) throw new Exception(error.ErrorText); //抛出错误 } BulaqTemplateForRazorBase temp = (BulaqTemplateForRazorBase)result.CompiledAssembly.CreateInstance(defaultnamespace + "." + defaultclassname); //temp.Model = new { Title = "Abduwaris" };//Model; temp.SetProperty(bulaqData); //if (temp.Layout != null) //{ // //有布局页 //} try { temp.Execute(); } catch (Exception ex) { throw new Exception("执行错误", ex); } return temp.Output.ToString(); } }
private static void AddModelNamespace(GeneratorResults razorResult, Type modelType) { if (string.IsNullOrWhiteSpace(modelType.Namespace)) { return; } if (razorResult.GeneratedCode.Namespaces[0].Imports.OfType<CodeNamespaceImport>().Any(x => x.Namespace == modelType.Namespace)) { return; } razorResult.GeneratedCode.Namespaces[0].Imports.Add(new CodeNamespaceImport(modelType.Namespace)); }
public CompilationResults(GeneratorResults generatorResults, TemplateBase compiled) : base(true, generatorResults.Document, generatorResults.ParserErrors, generatorResults.GeneratedCode, generatorResults.DesignTimeLineMappings) { Compiled = compiled; }
public CompilationResults(GeneratorResults generatorResults, IList<CompilerError> errors) : base(false, generatorResults.Document, generatorResults.ParserErrors, generatorResults.GeneratedCode, generatorResults.DesignTimeLineMappings) { Errors = errors; }
private Func<NancyRazorViewBase> GenerateRazorViewFactory(CodeDomProvider codeProvider, GeneratorResults razorResult, Assembly referencingAssembly, IEnumerable<string> rendererSpecificAssemblies, Type passedModelType) { var outputAssemblyName = Path.Combine(Path.GetTempPath(), String.Format("Temp_{0}.dll", Guid.NewGuid().ToString("N"))); var modelType = FindModelType(razorResult.Document, passedModelType); var assemblies = new List<string> { GetAssemblyPath(typeof(System.Runtime.CompilerServices.CallSite)), GetAssemblyPath(typeof(IHtmlString)), GetAssemblyPath(Assembly.GetExecutingAssembly()), GetAssemblyPath(modelType) }; if (referencingAssembly != null) assemblies.Add(GetAssemblyPath(referencingAssembly)); assemblies = assemblies .Union(rendererSpecificAssemblies) .ToList(); if (this.razorConfiguration != null) { var assemblyNames = this.razorConfiguration.GetAssemblyNames(); if (assemblyNames != null) { assemblies.AddRange(assemblyNames.Select(Assembly.Load).Select(GetAssemblyPath)); } if (this.razorConfiguration.AutoIncludeModelNamespace) { AddModelNamespace(razorResult, modelType); } } var compilerParameters = new CompilerParameters(assemblies.ToArray(), outputAssemblyName); var results = codeProvider.CompileAssemblyFromDom(compilerParameters, razorResult.GeneratedCode); if (results.Errors.HasErrors) { var err = results.Errors .OfType<CompilerError>() .Where(ce => !ce.IsWarning) .Select(error => String.Format("Error Compiling Template: ({0}, {1}) {2})", error.Line, error.Column, error.ErrorText)) .Aggregate((s1, s2) => s1 + "<br/>" + s2); return () => new NancyRazorErrorView(err); } var assembly = Assembly.LoadFrom(outputAssemblyName); if (assembly == null) { const string error = "Error loading template assembly"; return () => new NancyRazorErrorView(error); } var type = assembly.GetType("RazorOutput.RazorView"); if (type == null) { var error = String.Format("Could not find type RazorOutput.Template in assembly {0}", assembly.FullName); return () => new NancyRazorErrorView(error); } if (Activator.CreateInstance(type) as NancyRazorViewBase == null) { const string error = "Could not construct RazorOutput.Template or it does not inherit from RazorViewBase"; return () => new NancyRazorErrorView(error); } return () => (NancyRazorViewBase)Activator.CreateInstance(type); }
private Func<INancyRazorView> GenerateRazorViewFactory(IRazorViewRenderer renderer, GeneratorResults generatorResults, Type passedModelType, ViewLocationResult viewLocationResult) { var modelType = GetModelTypeFromGeneratedCode(generatorResults, passedModelType); var sourceCode = string.Empty; if (this.razorConfiguration != null) { if (this.razorConfiguration.AutoIncludeModelNamespace) { AddModelNamespace(generatorResults, modelType); } } using (var writer = new StringWriter()) { renderer.Provider.GenerateCodeFromCompileUnit(generatorResults.GeneratedCode, writer, new CodeGeneratorOptions()); sourceCode = writer.ToString(); } var compilation = CSharpCompilation.Create( assemblyName: string.Format("Temp_{0}.dll", Guid.NewGuid().ToString("N")), syntaxTrees: new[] { CSharpSyntaxTree.ParseText(sourceCode) }, references: this.GetMetadataReferences().Value, options: new CSharpCompilationOptions(OutputKind.DynamicallyLinkedLibrary)); using (var ms = new MemoryStream()) { var result = compilation.Emit(ms); if (!result.Success) { return () => new NancyRazorErrorView(BuildErrorMessage(result, viewLocationResult, sourceCode), this.traceConfiguration); } ms.Seek(0, SeekOrigin.Begin); var viewAssembly = Assembly.Load(ms.ToArray()); return () => (INancyRazorView) Activator.CreateInstance(viewAssembly.GetType("RazorOutput.RazorView")); } }
private static Type GetModelTypeFromGeneratedCode(GeneratorResults generatorResults, Type passedModelType) { return (Type)generatorResults.GeneratedCode.Namespaces[0].Types[0].UserData["ModelType"] ?? passedModelType ?? typeof(object); }
private static SyntaxTree GetSyntaxTree(WebPageRazorHost host, GeneratorResults razorResult) { // Use CodeDom to generate source code from the CodeCompileUnit // Use roslyn to parse it back using (var codeDomProvider = CodeDomProvider.CreateProvider(host.CodeLanguage.LanguageName)) using (var viewCodeStream = new MemoryStream()) using (var viewCodeWriter = new StreamWriter(viewCodeStream)) { codeDomProvider.GenerateCodeFromCompileUnit(razorResult.GeneratedCode, viewCodeWriter, new CodeGeneratorOptions()); viewCodeWriter.Flush(); viewCodeStream.Position = 0; var sourceText = SourceText.From(viewCodeStream); // We need a different file path for the generated file, otherwise breakpoints won't get // hit due to #line directives pointing at the original .cshtml. If we'd want breakpoint // in the generated .cs code, we'd have to dump them somewhere on disk, and specify the path here. var sourcePath = string.IsNullOrEmpty(host.PhysicalPath) ? host.VirtualPath // yay virtual paths, won't point at the original file : Path.ChangeExtension(host.PhysicalPath, ".roslynviewengine"); return SyntaxFactory.ParseSyntaxTree(sourceText, path: sourcePath); } }
private static CompilerResults CompileView(GeneratorResults razorResult, CompilerParameters compilerParameters) { var codeProvider = new CSharpCodeProvider(CompilerProperties); return codeProvider.CompileAssemblyFromDom(compilerParameters, razorResult.GeneratedCode); }
protected static void ThrowExceptionIfErrors(GeneratorResults results) { if (results.Success) { return; } throw new AggregateException(results .ParserErrors .Select(e => new Exception(string.Format(LineX0TColX1TErrorX2Rn, e.Location.LineIndex, e.Location.CharacterIndex, e.Message)))); }
private static bool CheckParseResults(string resourceName, GeneratorResults generatorResults, string templateContent) { if (!generatorResults.ParserErrors.Any()) return true; var contentlines = templateContent .Split('\n') .Select(line => line.Trim()) .ToList(); string parseExceptionMessage; try { parseExceptionMessage = string.Join( Environment.NewLine, generatorResults .ParserErrors .Select(error => "parse error at template: {0}{1}line {2}: {3}{1}parse error: {4}".FormatWith(resourceName, Environment.NewLine, error.Location.LineIndex + 1, contentlines[error.Location.LineIndex], error.Message)) .ToArray() ); } catch { // on any error create a raw error message parseExceptionMessage = string.Join( Environment.NewLine, generatorResults .ParserErrors .Select(error => error.ToString()) .ToArray()); } throw new TemplateParseException(parseExceptionMessage); }
public CodeGenerationException(GeneratorResults generatorResults) : base("The template could not be parsed") { GeneratorResults = generatorResults; }
private Func<INancyRazorView> GenerateRazorViewFactory(IRazorViewRenderer viewRenderer, GeneratorResults razorResult, Assembly referencingAssembly, Type passedModelType, ViewLocationResult viewLocationResult) { var outputAssemblyName = Path.Combine(Path.GetTempPath(), String.Format("Temp_{0}.dll", Guid.NewGuid().ToString("N"))); var modelType = FindModelType(razorResult.Document, passedModelType, viewRenderer.ModelCodeGenerator); var assemblies = new List<string> { GetAssemblyPath(typeof(System.Runtime.CompilerServices.CallSite)), GetAssemblyPath(typeof(IHtmlString)), GetAssemblyPath(Assembly.GetExecutingAssembly()), GetAssemblyPath(modelType) }; assemblies.AddRange(AppDomainAssemblyTypeScanner.Assemblies.Select(GetAssemblyPath)); if (referencingAssembly != null) { assemblies.Add(GetAssemblyPath(referencingAssembly)); } if (this.razorConfiguration != null) { var assemblyNames = this.razorConfiguration.GetAssemblyNames(); if (assemblyNames != null) { assemblies.AddRange(assemblyNames.Select(Assembly.Load).Select(GetAssemblyPath)); } if (this.razorConfiguration.AutoIncludeModelNamespace) { AddModelNamespace(razorResult, modelType); } } assemblies = assemblies .Union(viewRenderer.Assemblies) .ToList(); var compilerParameters = new CompilerParameters(assemblies.ToArray(), outputAssemblyName); CompilerResults results; lock (this.compileLock) { results = viewRenderer.Provider.CompileAssemblyFromDom(compilerParameters, razorResult.GeneratedCode); } if (results.Errors.HasErrors) { var output = new string[results.Output.Count]; results.Output.CopyTo(output, 0); var fullTemplateName = viewLocationResult.Location + "/" + viewLocationResult.Name + "." + viewLocationResult.Extension; var templateLines = GetViewBodyLines(viewLocationResult); var errors = results.Errors.OfType<CompilerError>().Where(ce => !ce.IsWarning).ToArray(); var errorMessages = BuildErrorMessages(errors); var compilationSource = this.GetCompilationSource(viewRenderer.Provider, razorResult.GeneratedCode); MarkErrorLines(errors, templateLines); var lineNumber = 1; var errorDetails = string.Format( "Error compiling template: <strong>{0}</strong><br/><br/>Errors:<br/>{1}<br/><br/>Details:<br/>{2}<br/><br/>Compilation Source:<br/><pre><code>{3}</code></pre>", fullTemplateName, errorMessages, templateLines.Aggregate((s1, s2) => s1 + "<br/>" + s2), compilationSource.Aggregate((s1, s2) => s1 + "<br/>Line " + lineNumber++ + ":\t" + s2)); return () => new NancyRazorErrorView(errorDetails); } var assembly = Assembly.LoadFrom(outputAssemblyName); if (assembly == null) { const string error = "Error loading template assembly"; return () => new NancyRazorErrorView(error); } var type = assembly.GetType("RazorOutput.RazorView"); if (type == null) { var error = String.Format("Could not find type RazorOutput.Template in assembly {0}", assembly.FullName); return () => new NancyRazorErrorView(error); } if (Activator.CreateInstance(type) as INancyRazorView == null) { const string error = "Could not construct RazorOutput.Template or it does not inherit from INancyRazorView"; return () => new NancyRazorErrorView(error); } return () => (INancyRazorView)Activator.CreateInstance(type); }
private void DocumentParseCompleteMainThread() { if (_parseData == null) { return; } ParseData parseData = _parseData; lock (parseData) { _parseData.NotificationPending = false; if (_pendingShimTextChange.HasValue && (_parseData.SourceChange.NewBuffer as IShimTextBuffer).Snapshot == (_pendingShimTextChange.Value.NewBuffer as IShimTextBuffer).Snapshot) { _pendingShimTextChange = null; if (_viewBuffer != null) { ITextSnapshot snapshot = (_parseData.SourceChange.NewBuffer as IShimTextBuffer).Snapshot; if (snapshot != snapshot.TextBuffer.CurrentSnapshot) { ReparseFile(); } else { _result = _parseData.GeneratorResults; if (!_parseData.TreeStructureChanged) { NotifyOnCodeGenerationComplete(null); } else { _parseData.TreeStructureChanged = false; IEnumerable<System.Web.Razor.Parser.SyntaxTree.Span> spans = _result.Document.Flatten(); List<RazorRange> newCodeRanges = GetNewCodeRanges(spans); NotifyOnCodeGenerationComplete(newCodeRanges); NotifySpansChanged(spans, newCodeRanges); if (_spanContextChanged) { RepairCompletionSession(); _spanContextChanged = false; } if (_parseData != null) { NotifyPossibleTrigger(_parseData.SourceChange); } } } } } } }
private bool CheckCompileResults(GeneratorResults generatorResults, CompilerResults compilerResults, string templateContent, string generatedSource) { if (!compilerResults.Errors.HasErrors) return true; List<string> sourceLines = null; Func<List<string>> generatedSourceLines = () => sourceLines ?? (sourceLines = (generatedSource ?? GenerateSourceCode(generatorResults.GeneratedCode)).Split('\n').Select(line => line.Trim()).ToList()); var contentlines = templateContent .Split('\n') .Select(line => line.Trim()) .ToList(); string compileExceptionMessage; try { compileExceptionMessage = string.Join( "{0}{0}".FormatWith(Environment.NewLine), compilerResults .Errors .OfType<CompilerError>() .Where(error => !error.IsWarning) .Select(error => "compile error at {0}{1}line {2}: {3}{1}compile error: {4}: {5}".FormatWith(error.FileName, Environment.NewLine, error.Line, (error.FileName ?? "").StartsWith(_sourceFilenamePrefix) ? contentlines[error.Line - 1] : generatedSourceLines()[error.Line - 1], error.ErrorNumber, error.ErrorText)) .ToArray() ); } catch { // on any error create a raw error message compileExceptionMessage = string.Join( "{0}{0}".FormatWith(Environment.NewLine), compilerResults .Errors .OfType<CompilerError>() .Where(error => !error.IsWarning) .Select(error => error.ToString()) .ToArray()); } throw new TemplateCompileException(compileExceptionMessage); }
public static SyntaxTreeParserResults Parse(GeneratorResults results) { Node[] nodes = Traverse(results.Document).ToArray(); return new SyntaxTreeParserResults(new ReadOnlyCollection<Node>(nodes)); }