Beispiel #1
0
        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 CustomCompilationFailedExceptionFactory.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();

            return(new CompiledViewDescriptor(item));
        }
Beispiel #2
0
        internal Assembly CompileAndEmit(RazorCodeDocument codeDocument, string generatedCode)
        {
            _logger.GeneratedCodeToAssemblyCompilationStart(codeDocument.Source.FilePath);

            var startTimestamp = _logger.IsEnabled(LogLevel.Debug) ? Stopwatch.GetTimestamp() : 0;

            var assemblyName = Path.GetRandomFileName();
            var compilation  = CreateCompilation(generatedCode, assemblyName);

            var emitOptions = _csharpCompiler.EmitOptions;
            var emitPdbFile = _csharpCompiler.EmitPdb && emitOptions.DebugInformationFormat != DebugInformationFormat.Embedded;

            using (var assemblyStream = new MemoryStream())
                using (var pdbStream = emitPdbFile ? new MemoryStream() : null)
                {
                    var result = compilation.Emit(
                        assemblyStream,
                        pdbStream,
                        options: emitOptions);

                    if (!result.Success)
                    {
                        throw CustomCompilationFailedExceptionFactory.Create(
                                  codeDocument,
                                  generatedCode,
                                  assemblyName,
                                  result.Diagnostics);
                    }

                    assemblyStream.Seek(0, SeekOrigin.Begin);
                    pdbStream?.Seek(0, SeekOrigin.Begin);

                    var assembly = Assembly.Load(assemblyStream.ToArray(), pdbStream?.ToArray());
                    _logger.GeneratedCodeToAssemblyCompilationEnd(codeDocument.Source.FilePath, startTimestamp);

                    return(assembly);
                }
        }