public static CompiledAssemblyResult GetAssemblyFromCompilation(
            CSharpCompilation compilation)
        {
            EmitResult result;
            using (var ms = new MemoryStream())
            {
                using (var pdb = new MemoryStream())
                {
                    if (_isMono.Value)
                    {
                        result = compilation.Emit(ms, pdbStream: null);
                    }
                    else
                    {
                        result = compilation.Emit(ms, pdbStream: pdb);
                    }

                    if (!result.Success)
                    {
                        var formatter = new DiagnosticFormatter();
                        var errorMessages = result.Diagnostics
                            .Where(IsError)
                            .Select(d => formatter.Format(d));

                        return CompiledAssemblyResult.FromErrorMessages(errorMessages);
                    }

                    Assembly assembly;
                    if (_isMono.Value)
                    {
                        var assemblyLoadMethod = typeof(Assembly).GetTypeInfo().GetDeclaredMethods("Load")
                            .First(
                                m =>
                                    {
                                        var parameters = m.GetParameters();
                                        return parameters.Length == 1 && parameters[0].ParameterType == typeof(byte[]);
                                    });
                        assembly = (Assembly)assemblyLoadMethod.Invoke(null, new[] { ms.ToArray() });
                    }
                    else
                    {
                        var assemblyLoadMethod = typeof(Assembly).GetTypeInfo().GetDeclaredMethods("Load")
                            .First(
                                m =>
                                    {
                                        var parameters = m.GetParameters();
                                        return parameters.Length == 2
                                               && parameters[0].ParameterType == typeof(byte[])
                                               && parameters[1].ParameterType == typeof(byte[]);
                                    });
                        assembly = (Assembly)assemblyLoadMethod.Invoke(null, new[] { ms.ToArray(), pdb.ToArray() });
                    }

                    return CompiledAssemblyResult.FromAssembly(assembly);
                }
            }
        }
Ejemplo n.º 2
0
        public static bool CompileCSharp(
            IEnumerable <string> sourceFiles,
            string outputPath,
            IEnumerable <string> references,
            IEnumerable <string> defines,
            out List <string> messages
            )
        {
            CS.CSharpCompilation compilation =
                CreateCSharpCompilation(
                    sourceFiles,
                    Path.GetFileName(outputPath),
                    references,
                    defines,
                    out messages
                    );

            // compile and write results
            var result = compilation.Emit(outputPath);

            foreach (var diag in result.Diagnostics)
            {
                messages.Add(diag.ToString());
            }

            return(result.Success);
        }
Ejemplo n.º 3
0
        public static bool CompileCSharp(
            IEnumerable <string> sourceFiles,
            string outputPath,
            IEnumerable <string> references,
            IEnumerable <string> defines,
            bool debug,
            out List <string> messages
            )
        {
            CS.CSharpCompilation compilation =
                CreateCSharpCompilation(
                    sourceFiles,
                    Path.GetFileName(outputPath),
                    references,
                    defines,
                    debug,
                    out messages
                    );

            // compile and write results
            EmitResult result;

            if (debug)
            {
                string pdbName = Path.Combine(
                    Path.GetDirectoryName(outputPath),
                    Path.GetFileNameWithoutExtension(outputPath) + ".pdb"
                    );
                result = compilation.Emit(outputPath, pdbName);
            }
            else
            {
                result = compilation.Emit(outputPath);
            }

            foreach (var diag in result.Diagnostics)
            {
                messages.Add(diag.ToString());
            }

            return(result.Success);
        }
Ejemplo n.º 4
0
        private Assembly CreateAssembly(CSharpCompilation compilation)
        {
            using (var outputStream = new MemoryStream())
            using (var pdbStream = new MemoryStream())
            {
                // Emit assembly to streams
                var result = compilation.Emit(outputStream, pdbStream);
                if (!result.Success)
                {
                    throw new CompilationException(result);
                }

                // Load the compiled assembly;
                var assembly = Assembly.Load(outputStream.ToArray(), pdbStream.ToArray());
                return assembly;
            }
        }
Ejemplo n.º 5
0
        /// <summary>
        /// Compile source files to assembly<br/>
        /// 编译源代码到程序集<br/>
        /// </summary>
        public void Compile(IList <string> sourceFiles,
                            string assemblyName, string assemblyPath)
        {
            // Parse source files into syntax trees
            // Also define NETCORE for .Net Core
            var parseOptions = CSharpParseOptions.Default;

            parseOptions = parseOptions.WithPreprocessorSymbols("NETCORE");
            var syntaxTrees = sourceFiles
                              .Select(path => CSharpSyntaxTree.ParseText(
                                          File.ReadAllText(path), parseOptions, path, Encoding.UTF8))
                              .ToList();

            LoadAssembliesFromUsings(syntaxTrees);
            // Add loaded assemblies to compile references
            var assemblyLoader = new NetAssemblyLoader();
            var references     = assemblyLoader.GetLoadedAssemblies()
                                 .Select(assembly => assembly.Location)
                                 .Select(path => MetadataReference.CreateFromFile(path))
                                 .ToList();

            var optimizationLevel  = OptimizationLevel.Release;
            var compilationOptions = new CSharpCompilationOptions(
                OutputKind.DynamicallyLinkedLibrary,
                optimizationLevel: optimizationLevel);

            // Compile to assembly, throw exception if error occurred
            Microsoft.CodeAnalysis.CSharp.CSharpCompilation compilation = CSharpCompilation.Create(assemblyName)
                                                                          .WithOptions(compilationOptions)
                                                                          .AddReferences(references)
                                                                          .AddSyntaxTrees(syntaxTrees);
            Microsoft.CodeAnalysis.Emit.EmitResult emitResult = compilation.Emit(assemblyPath);
            if (!emitResult.Success)
            {
                throw new Exception(string.Join("\r\n",
                                                emitResult.Diagnostics.Where(d => d.WarningLevel == 0)));
            }
        }
Ejemplo n.º 6
0
 /// <summary>
 /// Builds the assembly.
 /// </summary>
 protected virtual Assembly BuildAssembly(CSharpCompilation compilation)
 {
     using (var ms = new MemoryStream())
     {
         var result = compilation.Emit(ms);
         if (result.Success)
         {
             var assembly = Assembly.Load(ms.ToArray());
             assemblyCache.AddAssembly(assembly, compilation.ToMetadataReference());
             return assembly;
         }
         else
         {
             throw new Exception("The compilation failed! This is most probably bug in the DotVVM framework.\r\n\r\n"
                 + string.Join("\r\n", result.Diagnostics)
                 + "\r\n\r\n" + compilation.SyntaxTrees[0].GetRoot().NormalizeWhitespace() + "\r\n\r\n"
                 + "References: " + string.Join("\r\n", compilation.ReferencedAssemblyNames.Select(n => n.Name)));
         }
     }
 }
Ejemplo n.º 7
0
 private void Save()
 {
     if (Options.FullCompile)
     {
         var bindingsAssemblyPath = bindingCompiler.OutputFileName;
         bindingCompiler.SaveAssembly();
         Program.WriteInfo("bindings saved to " + bindingsAssemblyPath);
         compilation = compilation.AddReferences(MetadataReference.CreateFromFile(Path.GetFullPath(bindingsAssemblyPath)));
         var compiledViewsFileName = Path.Combine(Options.OutputPath, Options.AssemblyName + ".dll");
         //Directory.CreateDirectory("outputCS");
         //int i = 0;
         //foreach (var tree in compilation.SyntaxTrees)
         //{
         //    File.WriteAllText($"outputCS/file{i++}.cs", tree.GetRoot().NormalizeWhitespace().ToString());
         //}
         var result = compilation.Emit(compiledViewsFileName);
         if (!result.Success)
         {
             throw new Exception("compilation failed");
         }
         Program.WriteInfo("views saved to " + compiledViewsFileName);
     }
 }