Exemplo n.º 1
0
        public void Compile(TestAssembly testAssembly, string assemblyFileName, TargetDotNetFrameworkVersion dotNetFrameworkVersion)
        {
            var architecture = DotNetFrameworkArchitecture.Current;

            switch (testAssembly.Platform)
            {
            case Platform.X86:
                architecture = DotNetFrameworkArchitecture.Bitness32;
                break;

            case Platform.X64:
                architecture = DotNetFrameworkArchitecture.Bitness32;
                break;
            }

            var assemblyInfoSyntaxTree = CSharpSyntaxTree.ParseText(ResourceManager.GetContentFromResource(AssemblyInfoResourceName) + Environment.NewLine + string.Join(Environment.NewLine, testAssembly.Attributes));
            var compilation            =
                CSharpCompilation.Create(Path.GetFileName(assemblyFileName))
                .WithOptions(new CSharpCompilationOptions(OutputKind.DynamicallyLinkedLibrary)
                             .WithPlatform(testAssembly.Platform)
                             .WithOptimizationLevel(OptimizationLevel.Debug))
                .AddReferences(GetDotNetFrameworkReferences(dotNetFrameworkVersion, architecture))
                .AddReferences(testAssembly.References.Select(assembly => MetadataReference.CreateFromFile(assembly)))
                .AddSyntaxTrees(assemblyInfoSyntaxTree)
                .AddSyntaxTrees(UtilsSyntaxTree)
                .AddSyntaxTrees(testAssembly.Classes.Select(CreateClassSyntaxTree));

            using (var file = new FileStream(assemblyFileName, FileMode.Create))
            {
                var result = compilation.Emit(file);
                if (!result.Success)
                {
                    var code = string.Join(Environment.NewLine + Environment.NewLine, compilation.SyntaxTrees.Select(i => i.ToString()));
                    throw new Exception($"Errors:\n{string.Join(Environment.NewLine, result.Diagnostics.Select(i => i.GetMessage(CultureInfo.InvariantCulture)))}\n\nCode:\n{code}");
                }

                file.Flush(true);
            }
        }