Esempio n. 1
0
        public EmitResult EmitAssembly(
            CSharpCompilation compilation,
            EmitOptions emitOptions,
            string assemblyPath,
            ResourceDescription[] resources)
        {
            EmitResult emitResult;

            using (var assemblyStream = new MemoryStream())
            {
                using (var pdbStream = new MemoryStream())
                {
                    emitResult = compilation.Emit(
                        assemblyStream,
                        pdbStream,
                        manifestResources: resources,
                        options: emitOptions);

                    if (emitResult.Success)
                    {
                        Directory.CreateDirectory(Path.GetDirectoryName(assemblyPath));
                        var pdbPath = Path.ChangeExtension(assemblyPath, ".pdb");
                        assemblyStream.Position = 0;
                        pdbStream.Position      = 0;

                        // Avoid writing to disk unless the compilation is successful.
                        using (var assemblyFileStream = File.OpenWrite(assemblyPath))
                        {
                            assemblyStream.CopyTo(assemblyFileStream);
                        }

                        using (var pdbFileStream = File.OpenWrite(pdbPath))
                        {
                            pdbStream.CopyTo(pdbFileStream);
                        }
                    }
                }
            }

            return(emitResult);
        }
Esempio n. 2
0
        public static void Create()
        {
            SyntaxTree        syntaxTree   = CSharpSyntaxTree.ParseText(@"
    using System;
    namespace RoslynCompileSample1
    {
        public class Writer
        {
            public void Write(string message)
            {
                Console.WriteLine(message);
            }
        }

public class Writer1
        {
            public void Write(string message)
            {
                Console.WriteLine(message);
            }
        }

    }");
            string            assemblyName = Path.GetRandomFileName();
            var               references   = AppDomain.CurrentDomain.GetAssemblies().Where(x => x.Location != "").Select(x => MetadataReference.CreateFromFile(x.Location));
            CSharpCompilation compilation  = CSharpCompilation.Create(
                assemblyName,
                syntaxTrees: new[] { syntaxTree },
                references: references,
                options: new CSharpCompilationOptions(OutputKind.DynamicallyLinkedLibrary));

            using (var ms = new MemoryStream())
            {
                EmitResult result = compilation.Emit(ms);
                if (result.Success)
                {
                    ms.Seek(0, SeekOrigin.Begin);
                    assembly = Assembly.Load(ms.ToArray());
                }
            }
        }
        /// <summary>
        /// Compile internal source code into memory array
        /// </summary>
        /// <param name="sourceCodes">Source codes of library</param>
        /// <returns>Byte array from compiled binary dll assembly</returns>
        private static byte[] BuildAssemblyFromSources(string[] sourceCodes)
        {
            string            assemblyName = Path.GetRandomFileName();
            CSharpCompilation compilation  = CSharpCompilation.Create(
                assemblyName,
                syntaxTrees: sourceCodes.Select(code => CSharpSyntaxTree.ParseText(text: code)),
                references: new MetadataReference[] { CorlibReference,
                                                      SystemCoreReference,
                                                      CSharpSymbolsReference,
                                                      CodeAnalysisReference,
                                                      DapperReference },
                options: new CSharpCompilationOptions(OutputKind.DynamicallyLinkedLibrary));

            // Emit the image of this assembly
            byte[] image = null;

            using (var ms = new MemoryStream())
            {
                var emitResult = compilation.Emit(ms);

                if (!emitResult.Success)
                {
                    StringBuilder diagnosticMessages = new StringBuilder(BuildFailMessage + "\r\n");

                    IEnumerable <Diagnostic> failures = emitResult.Diagnostics.Where(diagnostic =>
                                                                                     diagnostic.IsWarningAsError ||
                                                                                     diagnostic.Severity == DiagnosticSeverity.Error);

                    foreach (Diagnostic diagnostic in failures)
                    {
                        diagnosticMessages.Append(string.Format("{0}: {1} \r\n", diagnostic.Id, diagnostic.GetMessage()));
                    }

                    throw new ArgumentException(diagnosticMessages.ToString());
                }

                image = ms.ToArray();
            }

            return(image);
        }
Esempio n. 4
0
        /// <summary>
        /// Compile the roslyn AST
        /// </summary>
        /// <returns>Either the compiled bytes of the program, or a list of error messages</returns>
        private static Stream CreateAssembly(CSharpCompilation compilation)
        {
            var        ms       = new MemoryStream();
            EmitResult emmitted = compilation.Emit(ms);

            if (!emmitted.Success)
            {
                // create error messages
                var errors = emmitted.Diagnostics
                             .Where(diagnostic =>
                                    diagnostic.IsWarningAsError ||
                                    diagnostic.Severity == DiagnosticSeverity.Error)
                             .Select(diagnostic => $"{diagnostic.Id}: {diagnostic.GetMessage()}");

                throw new Exception(string.Join(Environment.NewLine, errors));
            }

            // load the program and run it
            ms.Seek(0, SeekOrigin.Begin);
            return(ms);
        }
Esempio n. 5
0
        /// <summary>
        /// Compiles code into a binary.
        /// </summary>
        /// <param name="outputPath">Output path for the compilation.</param>
        /// <param name="assemblyPaths">Paths to assemblies to reference.</param>
        /// <param name="sources">Source code to compile.</param>
        /// <param name="generateExecutable">Whether to generate an executable or a dynamically linked library.</param>
        /// <returns>Results for the compilation.</returns>
        public CodeCompileResults CompileSources(string outputPath, IEnumerable <string> assemblyPaths,
                                                 IEnumerable <string> sources, bool generateExecutable)
        {
            var parseOptions = CSharpParseOptions.Default.WithPreprocessorSymbols(PreprocessorSymbol);
            IEnumerable <SyntaxTree>        syntaxTrees = sources.Select(source => SyntaxFactory.ParseSyntaxTree(source, parseOptions));
            IEnumerable <MetadataReference> references  = assemblyPaths.Select(path => MetadataReference.CreateFromFile(path));
            var compilationOptions = new CSharpCompilationOptions(generateExecutable ? OutputKind.ConsoleApplication : OutputKind.DynamicallyLinkedLibrary);

            CSharpCompilation compilation = CSharpCompilation.Create("NetPrintsOutput")
                                            .WithOptions(compilationOptions)
                                            .AddReferences(references)
                                            .AddSyntaxTrees(syntaxTrees);

            EmitResult emitResult = compilation.Emit(outputPath);

            IEnumerable <string> errors = emitResult.Diagnostics
                                          .Where(d => d.Severity == DiagnosticSeverity.Error)
                                          .Select(d => d.GetMessage());

            return(new CodeCompileResults(emitResult.Success, errors, emitResult.Success ? outputPath : null));
        }
Esempio n. 6
0
        private static Stream GetInMemoryAssemblyStreamForCode([NotNull] string code,
                                                               [NotNull][ItemNotNull] params MetadataReference[] references)
        {
            SyntaxTree        tree        = CSharpSyntaxTree.ParseText(code);
            CSharpCompilation compilation = CSharpCompilation
                                            .Create("TempAssembly", new[] { tree })
                                            .WithOptions(new CSharpCompilationOptions(OutputKind.DynamicallyLinkedLibrary));

            PortableExecutableReference msCorLib = MetadataReference.CreateFromFile(typeof(object).Assembly.Location);

            compilation = compilation.AddReferences(msCorLib);
            compilation = compilation.AddReferences(references);

            var stream = new MemoryStream();

            EmitResult emitResult = compilation.Emit(stream);

            ValidateCompileErrors(emitResult);

            return(stream);
        }
        private static Assembly StreamAssemblyInMemory(CSharpCompilation cSharpCompilation)
        {
            Assembly dynamicAssembly;

            using (var memoryStream = new MemoryStream())
            {
                var result = cSharpCompilation.Emit(memoryStream);
                if (!result.Success)
                {
                    string errorMessage = (string.Join(Environment.NewLine, result.Diagnostics));
                    throw new Exception(errorMessage);
                }
                else
                {
                    memoryStream.Seek(0, SeekOrigin.Begin);
                    dynamicAssembly = Assembly.Load(memoryStream.ToArray());
                }
            }

            return(dynamicAssembly);
        }
Esempio n. 8
0
        /// <summary>
        /// 使用内存流进行脚本编译
        /// </summary>
        /// <param name="sourceContent">脚本内容</param>
        /// <param name="errorAction">发生错误执行委托</param>
        /// <returns></returns>
        public (Assembly Assembly, ImmutableArray <Diagnostic> Errors, CSharpCompilation Compilation) StreamComplier()
        {
            lock (Domain)
            {
                //创建语言编译
                CSharpCompilation compilation = CSharpCompilation.Create(
                    AssemblyName,
                    options: new CSharpCompilationOptions(
                        outputKind: OutputKind.DynamicallyLinkedLibrary,
                        optimizationLevel: OptimizationLevel.Release,
                        allowUnsafe: true),
                    syntaxTrees: SyntaxInfos.Trees,
                    references: References);


                //编译并生成程序集
                MemoryStream stream        = new MemoryStream();
                var          complieResult = compilation.Emit(stream);
                if (complieResult.Success)
                {
                    return(_domain.Handler(stream), default, compilation);
Esempio n. 9
0
        private CSharpCompilation CompileManagedClasses(CSharpCompilation compilation)
        {
            var syntaxTrees = new List <SyntaxTree>();

            NativeCefApiTypes.AddFilesToSyntaxTrees(syntaxTrees, Path.Combine(_basePath, "Managed", "Types"));
            AddPrivateInterfaceFilesToSyntaxTrees(syntaxTrees, Path.Combine(_basePath, "Managed", "Internal"));
            syntaxTrees.Add(SyntaxFactory.ParseSyntaxTree(SourceText.From(File.ReadAllText(Path.Combine(_basePath, "..", "CefTypes", "CefBaseRefCounted.cs")))));
            syntaxTrees.Add(SyntaxFactory.ParseSyntaxTree(SourceText.From(File.ReadAllText(Path.Combine(_basePath, "..", "CefTypes", "CefBaseScoped.cs")))));
            syntaxTrees.Add(SyntaxFactory.ParseSyntaxTree(SourceText.From(File.ReadAllText(Path.Combine(_basePath, "..", "CefTypes", "CefColor.cs")))));
            syntaxTrees.Add(SyntaxFactory.ParseSyntaxTree(SourceText.From(File.ReadAllText(Path.Combine(_basePath, "..", "CefTypes", "CefStringList.cs")))));
            syntaxTrees.Add(SyntaxFactory.ParseSyntaxTree(SourceText.From(File.ReadAllText(Path.Combine(_basePath, "..", "CefTypes", "CefStringMap.cs")))));
            syntaxTrees.Add(SyntaxFactory.ParseSyntaxTree(SourceText.From(File.ReadAllText(Path.Combine(_basePath, "..", "CefString.cs")))));
            syntaxTrees.Add(SyntaxFactory.ParseSyntaxTree(SourceText.From(File.ReadAllText(Path.Combine(_basePath, "..", "CefStructure.cs")))));
            syntaxTrees.Add(SyntaxFactory.ParseSyntaxTree(SourceText.From(File.ReadAllText(Path.Combine(_basePath, "..", "CefTypes", "CApi", "cef_string_t.cs")))));
            syntaxTrees.Add(SyntaxFactory.ParseSyntaxTree(SourceText.From(File.ReadAllText(Path.Combine(_basePath, "..", "Unsafe", "RefCountedWrapperStruct.cs")))));
            syntaxTrees.Add(SyntaxFactory.ParseSyntaxTree(SourceText.From(File.ReadAllText(Path.Combine(_basePath, "..", "Unsafe", "CefWrapperType.cs")))));
            syntaxTrees.Add(SyntaxFactory.ParseSyntaxTree(SourceText.From("namespace System { static class Ext111 { public static void InitBlock(this IntPtr startAddress, byte value, int size) { } } }")));
            syntaxTrees.Add(SyntaxFactory.ParseSyntaxTree(SourceText.From("using CefNet.CApi; namespace CefNet { public unsafe class CefWindowInfo { public cef_window_info_t* GetNativeInstance() { return null; } public static CefWindowInfo Wrap(cef_window_info_t* p) { return null; } } }")));
            syntaxTrees.Add(SyntaxFactory.ParseSyntaxTree(SourceText.From("namespace CefNet { public class InvalidCefObjectException : System.Exception { } }")));
            syntaxTrees.Add(SyntaxFactory.ParseSyntaxTree(SourceText.From("namespace CefNet { public class CefApi { public static bool UseUnsafeImplementation; } }")));
            syntaxTrees.Add(SyntaxFactory.ParseSyntaxTree(SourceText.From("using CefNet.CApi; namespace CefNet { public class CefStringMultimap { cef_string_multimap_t a; public static implicit operator cef_string_multimap_t(CefStringMultimap a) { return a.a; } } }")));

            compilation = compilation.AddSyntaxTrees(syntaxTrees);

            using (var ms = new MemoryStream())
            {
                EmitResult emitResult = compilation.Emit(ms);
                if (!emitResult.Success)
                {
                    foreach (var diag in emitResult.Diagnostics)
                    {
                        Console.WriteLine(diag);
                    }
                    Debugger.Break();
                    Environment.Exit(-1);
                }
            }

            return(compilation);
        }
Esempio n. 10
0
        private (RollbackProcessResult, EmitResult, int) TryCompilation(
            Stream ms,
            Stream symbolStream,
            CSharpCompilation compilation,
            EmitResult previousEmitResult,
            bool lastAttempt,
            bool devMode,
            int retryCount)
        {
            RollbackProcessResult rollbackProcessResult = null;

            if (previousEmitResult != null)
            {
                // remove broken mutations
                rollbackProcessResult = _rollbackProcess.Start(compilation, previousEmitResult.Diagnostics, lastAttempt, devMode);
                compilation           = rollbackProcessResult.Compilation;
            }

            // reset the memoryStream
            ms.SetLength(0);
            symbolStream?.SetLength(0);

            _logger.LogDebug($"Trying compilation for the {ReadableNumber(retryCount)} time.");

            var emitOptions = symbolStream == null ? null : new EmitOptions(false, DebugInformationFormat.PortablePdb, $"{AssemblyName}.pdb");
            var emitResult  = compilation.Emit(
                ms,
                symbolStream,
                manifestResources: _input.ProjectInfo.ProjectUnderTestAnalyzerResult.Resources,
                win32Resources: compilation.CreateDefaultWin32Resources(
                    true, // Important!
                    false,
                    null,
                    null),
                options: emitOptions);

            LogEmitResult(emitResult);

            return(rollbackProcessResult, emitResult, ++retryCount);
        }
        private static bool CreateTestApplication(string fileName)
        {
            SyntaxTree syntaxTree = CSharpSyntaxTree.ParseText(@"
                using System;
                using Microsoft.ApplicationInsights;
                using Microsoft.ApplicationInsights.DataContracts;
                using Microsoft.ApplicationInsights.Extensibility;

                class ActivityTest
                {
                    static void Main(string[] args)
                    {
                        var config = new TelemetryConfiguration();
                        config.TelemetryInitializers.Add(new OperationCorrelationTelemetryInitializer());
                        var tc = new TelemetryClient(config);
                        using (var requestOperation = tc.StartOperation<RequestTelemetry>(""request"", args[0]))
                        {
                            using (var dependencyOperation = tc.StartOperation<DependencyTelemetry>(""dependency"", args[0]))
                            {
                                Console.Write(dependencyOperation.Telemetry.Id);
                                tc.TrackTrace(""Hello World!"");
                            }
                        }
                    }
                }");

            MetadataReference[] references = new[]
            {
                MetadataReference.CreateFromFile(typeof(object).Assembly.Location),
                MetadataReference.CreateFromFile(typeof(TelemetryClient).Assembly.Location)
            };

            CSharpCompilation compilation = CSharpCompilation.Create(
                "ActivityTest",
                syntaxTrees: new[] { syntaxTree },
                references: references,
                options: new CSharpCompilationOptions(OutputKind.ConsoleApplication));

            return(compilation.Emit(fileName).Success);
        }
Esempio n. 12
0
        public static Assembly BuildAssembly(this CSharpCompilation compilation)
        {
            //Emit to stream
            var ms         = new MemoryStream();
            var emitResult = compilation.Emit(ms);

            if (!emitResult.Success)
            {
                IEnumerable <Diagnostic> failures = emitResult.Diagnostics.Where(diagnostic =>
                                                                                 diagnostic.IsWarningAsError ||
                                                                                 diagnostic.Severity == DiagnosticSeverity.Error);

                foreach (Diagnostic diagnostic in failures)
                {
                    Console.Error.WriteLine("{0}: {1}", diagnostic.Id, diagnostic.GetMessage());
                }

                throw new NotSupportedException($"Compilation did not succeed : {failures.Count()} errors.");
            }

            return(Assembly.Load(ms.ToArray()));
        }
Esempio n. 13
0
        private static Assembly CompileRoslyn(String codeToCompile)
        {
            string assemblyFileName = "gen" + Guid.NewGuid().ToString().Replace("-", "") + ".dll";

            SyntaxTree syntaxTree = CSharpSyntaxTree.ParseText(codeToCompile);

            MetadataReference[] references = new MetadataReference[]
            {
                MetadataReference.CreateFromFile(typeof(object).Assembly.Location),
                //MetadataReference.CreateFromFile(Path.Combine(Path.GetDirectoryName(typeof(object).Assembly.Location), "System.dll")),
            };

            CSharpCompilation compilation = CSharpCompilation.Create(assemblyFileName,
                                                                     syntaxTrees: new[] { syntaxTree },
                                                                     references: references,
                                                                     options: new CSharpCompilationOptions(OutputKind.DynamicallyLinkedLibrary)
                                                                     );

            using (var ms = new MemoryStream())
            {
                EmitResult result = compilation.Emit(ms);
                if (!result.Success)
                {
                    IEnumerable <Diagnostic> failures = result.Diagnostics.Where(diagnostic =>
                                                                                 diagnostic.IsWarningAsError ||
                                                                                 diagnostic.Severity == DiagnosticSeverity.Error);
                    foreach (Diagnostic diagnostic in failures)
                    {
                        Console.Error.WriteLine("{0}: {1}", diagnostic.Id, diagnostic.GetMessage());
                    }
                    return(null);
                }
                else
                {
                    ms.Seek(0, SeekOrigin.Begin);
                    return(Assembly.Load(ms.ToArray()));
                }
            }
        }
Esempio n. 14
0
        /// <summary>
        /// Generates an assembly from a <see cref="SyntaxTree"/> list and a
        /// list of <see cref="MetadataReference"/> required reference assemblies.
        /// <para>
        /// Caution: this method is not protected by the <see cref="WeakAssemblyNameResolver"/>.
        /// It should be done, if necessary, by the caller.
        /// </para>
        /// </summary>
        /// <param name="compileOptions">Compilation options.</param>
        /// <param name="trees">The syntax trees.</param>
        /// <param name="assemblyPath">The full final assembly path (including the .dll extension).</param>
        /// <param name="allReferences">Optional list of assemblies' references.</param>
        /// <param name="loader">Optional loader function to load the final emitted assembly.</param>
        /// <returns>Encapsulation of the result.</returns>
        static public GenerateResult Generate(
            CSharpCompilationOptions?compileOptions,
            IReadOnlyList <SyntaxTree> trees,
            string assemblyPath,
            IEnumerable <MetadataReference>?allReferences = null,
            Func <string, Assembly>?loader = null)
        {
            if (assemblyPath == null)
            {
                throw new ArgumentNullException(nameof(assemblyPath));
            }
            try
            {
                var option = (compileOptions ?? DefaultCompilationOptions).WithAssemblyIdentityComparer(DesktopAssemblyIdentityComparer.Default);
                CSharpCompilation compilation = CSharpCompilation.Create(
                    Path.GetFileNameWithoutExtension(assemblyPath),
                    trees,
                    allReferences,
                    option);

                var r = compilation.Emit(assemblyPath);
                if (r.Success && loader != null)
                {
                    try
                    {
                        return(new GenerateResult(null, trees, r, loader(assemblyPath), null, null));
                    }
                    catch (Exception ex)
                    {
                        return(new GenerateResult(null, trees, r, null, ex, null));
                    }
                }
                return(new GenerateResult(null, trees, r, null, null, null));
            }
            catch (Exception ex)
            {
                return(new GenerateResult(ex, Array.Empty <SyntaxTree>(), null, null, null, null));
            }
        }
Esempio n. 15
0
        protected override EmitResult _Compile(string name, List <MetadataReference> references, string[] imports, string code, ref MemoryStream ms)
        {
            Info("Generating C# Code for script compilation for script element {0}", new object[] { id });
            StringBuilder sbUsing = new StringBuilder();

            foreach (string str in imports)
            {
                sbUsing.AppendFormat("using {0};\n", str);
            }
            string ccode = string.Format((_IsCondition ? _CODE_BASE_CONDITION_TEMPLATE : (_IsTimerEvent ? _CODE_BASE_TIMER_EVENT_TEMPLATE : _CODE_BASE_SCRIPT_TEMPLATE)), new object[] {
                sbUsing.ToString(),
                _ClassName,
                _FunctionName,
                code
            });
            List <SyntaxTree> tress = new List <SyntaxTree>();

            tress.Add(SyntaxFactory.SyntaxTree(CSharpSyntaxTree.ParseText(ccode).GetRoot()));
            CSharpCompilation comp = CSharpCompilation.Create(name, tress, references, new CSharpCompilationOptions(OutputKind.DynamicallyLinkedLibrary));

            return(comp.Emit(ms));
        }
Esempio n. 16
0
        private void PrepareAssemblyCompileIfNecessary()
        {
            if (null != _codeAssembly)
            {
                return;
            }

            SyntaxTree syntaxTree = CSharpSyntaxTree.ParseText(CustomTypeDecoder);

            string assemblyName = Path.GetRandomFileName();
            var    refPaths     = new[] { typeof(object).GetTypeInfo().Assembly.Location, typeof(Console).GetTypeInfo().Assembly.Location, Path.Combine(Path.GetDirectoryName(typeof(GCSettings).GetTypeInfo().Assembly.Location), "System.Runtime.dll") };

            MetadataReference[] references = refPaths.Select(r => MetadataReference.CreateFromFile(r)).ToArray();

            CSharpCompilation compilation = CSharpCompilation.Create(
                assemblyName,
                new[] { syntaxTree },
                references,
                new CSharpCompilationOptions(outputKind: OutputKind.DynamicallyLinkedLibrary, allowUnsafe: true));

            _compiledCode = new MemoryStream();

            EmitResult result = compilation.Emit(_compiledCode);

            if (!result.Success)
            {
                foreach (var d in result.Diagnostics)
                {
                    TraceLine(TraceType.Err, "Compiling customer trace renderer failed");
                    TraceLine(TraceType.Err, d.ToString());
                    TraceLine(TraceType.Err, "--------------------------------------------");
                    TraceLine(TraceType.Err, CustomTypeDecoder);
                }

                throw new Exception("Unable to compile type converters");
            }

            _codeAssembly = Assembly.Load(_compiledCode.GetBuffer());
        }
Esempio n. 17
0
        internal static CodeGenerationResult BuildGeneratedCode(CodeGenerationResult result, string assemblyName, MetadataReference[] references)
        {
            var st = CSharpSyntaxTree.ParseText(result.Code);

            var fileName = assemblyName;
            var options  = new CSharpCompilationOptions(OutputKind.DynamicallyLinkedLibrary);
            CSharpCompilation compilation = CSharpCompilation.Create(
                fileName,
                syntaxTrees: new[] { st },
                references: references,
                options: options);

            result.AssemblyBytes = new MemoryStream();
            EmitResult emitted = compilation.Emit(result.AssemblyBytes);

            if (!emitted.Success)
            {
                result.Errors = new List <string>();

                IEnumerable <Diagnostic> failures = emitted.Diagnostics.Where(diagnostic =>
                                                                              diagnostic.IsWarningAsError ||
                                                                              diagnostic.Severity == DiagnosticSeverity.Error);

                foreach (Diagnostic diagnostic in failures)
                {
                    result.Errors.Add(string.Format("{0}: {1}", diagnostic.Id, diagnostic.GetMessage()));
                }
            }
            else
            {
                result.AssemblyBytes.Seek(0, SeekOrigin.Begin);
                result.Assembly = Assembly.Load(result.AssemblyBytes.ToArray());
                result.AssemblyBytes.Seek(0, SeekOrigin.Begin);
            }


            result.AssemblyName = fileName + ".dll";
            return(result);
        }
Esempio n. 18
0
        public Type[] GeneraterProxyService()
        {
            var assemblys = AppDomain.CurrentDomain.GetAssemblies().Where(o => o.IsDynamic == false);
            List <SyntaxTree> syntaxTrees = new List <SyntaxTree>();
            var interfaces = GeneraterProxyInterface().ToList();

            foreach (var interfacetype in interfaces)
            {
                syntaxTrees.AddIfNotContains(GetProxyClassSyntaxTree(interfacetype.Item1, interfacetype.Item2));
            }
            var references = new List <PortableExecutableReference>();

            foreach (var item in assemblys)
            {
                if (item.Location != "")
                {
                    var reference = MetadataReference.CreateFromFile(item.Location);
                    references.Add(reference);
                }
            }
            //stream.Seek(0, SeekOrigin.Begin);
            references.Add(MetadataReference.CreateFromFile(typeof(IService <>).GetTypeInfo().Assembly.Location));
            references.Add(MetadataReference.CreateFromFile(typeof(ServiceBase <>).GetTypeInfo().Assembly.Location));
            references.Add(MetadataReference.CreateFromFile(interfaces.First().Item2.GetTypeInfo().Assembly.Location));
            references.Add(MetadataReference.CreateFromFile(Path.Combine(dynamicProxysPath, "InterfaceProxys.dll")));
            CSharpCompilation compilation = CSharpCompilation.Create("Capgemini.Caf.ClassProxys", syntaxTrees, references, new CSharpCompilationOptions(OutputKind.DynamicallyLinkedLibrary));

            using (var ms = new MemoryStream())
            {
                EmitResult result = compilation.Emit(Path.Combine(dynamicProxysPath, "ClassProxys.dll"));
                if (result.Success)
                {
                    ms.Seek(0, SeekOrigin.Begin);
                    _dynamicAssembly = assemblyLoadContext.LoadFromAssemblyPath(Path.Combine(dynamicProxysPath, "ClassProxys.dll"));
                    return(_dynamicAssembly.GetTypes());//.ExportedTypes.ToArray();
                }
            }
            return(new Type[] {});
        }
Esempio n. 19
0
        public static Assembly BuildAssembly(this CSharpCompilation compilation, string filename = null)
        {
            Console.WriteLine("Compilation starting for tree");
            Console.Error.WriteLine(compilation.SyntaxTrees[0].ToString());

            //Emit to stream
            Stream stream = new MemoryStream();

            if (filename != null)
            {
                stream = File.Create(filename);
            }
            var emitResult = compilation.Emit(stream);

            if (!emitResult.Success)
            {
                IEnumerable <Diagnostic> failures = emitResult.Diagnostics.Where(diagnostic =>
                                                                                 diagnostic.IsWarningAsError ||
                                                                                 diagnostic.Severity == DiagnosticSeverity.Error);

                foreach (Diagnostic diagnostic in failures)
                {
                    Console.Error.WriteLine("{0}: {1}", diagnostic.Id, diagnostic.GetMessage());
                }


                throw new NotSupportedException($"Compilation did not succeed : {failures.Count()} errors.");
            }
            Console.WriteLine("Compilation succeeded");

            if (filename != null)
            {
                filename = (stream as FileStream).Name;
                stream.Close();
                return(Assembly.LoadFile(filename));
            }

            return(Assembly.Load((stream as MemoryStream).ToArray()));
        }
Esempio n. 20
0
        public DiagnosticAssembly(DiagnosticEngine engine, string assemblyName, CSharpCompilation compilation)
        {
            this.engine       = engine;
            this.assemblyName = assemblyName;
            this.engine.UpdateLog($"Script compilation into assembly {assemblyName}.");
            this.dllStream = new MemoryStream();
            this.pdbStream = new MemoryStream();
            var emitResult = compilation.Emit(this.dllStream, this.pdbStream);

            if (!emitResult.Success)
            {
                var x = emitResult.Diagnostics;
                this.engine.UpdateLog($"Script compilation failed: {string.Join(Environment.NewLine, x.Select(d => d.ToString()))}.");
            }
            else
            {
                this.engine.UpdateLog("Script compilation succeeded.");
                this.dllStream.Seek(0, SeekOrigin.Begin);
                this.assembly = Assembly.Load(this.dllStream.ToArray());
                this.engine.UpdateLog("Dynamic assembly loaded.");
            }
        }
Esempio n. 21
0
        private static Microsoft.CodeAnalysis.Emit.EmitResult Compile(string code, string fileName)
        {
            var roslynTree          = CSharpSyntaxTree.ParseText(code);
            var dotnetCoreDirectory = System.Runtime.InteropServices.RuntimeEnvironment.GetRuntimeDirectory(); // Path.GetDirectoryName(typeof(System.Object).GetTypeInfo().Assembly.Location);
            var references          = Assembly.GetExecutingAssembly().GetAllReferencesPaths().ToList();

            references.Add(Path.Combine(dotnetCoreDirectory, "mscorlib.dll"));
            references.Add(Path.Combine(dotnetCoreDirectory, "netstandard.dll"));
            references.Add(Path.Combine(dotnetCoreDirectory, "System.Collections.Immutable.dll"));
            references.Add(Path.Combine(dotnetCoreDirectory, "System.Linq.dll"));
            references.Add(Path.Combine(dotnetCoreDirectory, "System.Private.Uri.dll"));
            references.Add(Path.Combine(dotnetCoreDirectory, "System.Private.CoreLib.dll"));
            references.Add(Path.Combine(dotnetCoreDirectory, "System.Runtime.dll"));
            references.Add(Path.Combine(dotnetCoreDirectory, "System.Runtime.Extensions.dll"));
            references.Add(Path.Combine(dotnetCoreDirectory, "System.Runtime.InteropServices.dll"));
            references.Add(Path.Combine(dotnetCoreDirectory, "System.Reflection.Metadata.dll"));
            var metadataReferences        = references.Select(x => MetadataReference.CreateFromFile(x)).ToArray();
            var options                   = new CSharpCompilationOptions(OutputKind.DynamicallyLinkedLibrary);
            CSharpCompilation compilation = CSharpCompilation.Create("assemblyName", new[] { roslynTree }, metadataReferences, options);

            return(compilation.Emit(fileName));
        }
Esempio n. 22
0
        private static Assembly Compile(string migration)
        {
            string dotnetDir = Path.GetDirectoryName(typeof(object).Assembly.Location);

            Assert.IsNotNull(dotnetDir, "Cannot find base directory of the .NET runtime.");
            MetadataReference[] references =
            {
                MetadataReference.CreateFromFile(typeof(object).Assembly.Location),                      // System
                MetadataReference.CreateFromFile(typeof(Enumerable).Assembly.Location),                  // System.Linq
                MetadataReference.CreateFromFile(typeof(GeneratedCodeAttribute).Assembly.Location),
                MetadataReference.CreateFromFile(typeof(DbType).Assembly.Location),                      // System.Data
                MetadataReference.CreateFromFile(typeof(ExportAttribute).Assembly.Location),             // System.Composition
                MetadataReference.CreateFromFile(typeof(IDatabase).Assembly.Location),                   // MigSharp
                MetadataReference.CreateFromFile(Path.Combine(dotnetDir,                           "System.Runtime.dll")),
                MetadataReference.CreateFromFile(Assembly.Load("netstandard, Version=2.0.0.0").Location) // see: https://stackoverflow.com/questions/46421686/how-to-write-a-roslyn-analyzer-that-references-a-dotnet-standard-2-0-project
            };

            string            assemblyName = Path.GetRandomFileName();
            SyntaxTree        syntaxTree   = CSharpSyntaxTree.ParseText(migration);
            CSharpCompilation compilation  = CSharpCompilation.Create(assemblyName, new[] { syntaxTree }, references, new CSharpCompilationOptions(OutputKind.DynamicallyLinkedLibrary));

            using (var ms = new MemoryStream())
            {
                EmitResult result = compilation.Emit(ms);

                List <string> compilationErrors = new List <string>();
                foreach (Diagnostic diagnostic in result.Diagnostics.Where(diagnostic =>
                                                                           diagnostic.IsWarningAsError ||
                                                                           diagnostic.Severity == DiagnosticSeverity.Error))
                {
                    compilationErrors.Add(diagnostic.Id + ": " + diagnostic.GetMessage());
                }
                CollectionAssert.IsEmpty(compilationErrors, "Could not compile migration."); // this nicely outputs the compilation errors at the top of the output
                Assert.IsTrue(result.Success, "Could not compile migration.");
                ms.Seek(0, SeekOrigin.Begin);
                return(Assembly.Load(ms.ToArray()));
            }
        }
Esempio n. 23
0
        private void Compile(MemoryStream ms, SyntaxTree syntaxTree, Script script)
        {
            string assemblyName = Path.GetRandomFileName();

            MetadataReference[] references = new MetadataReference[]
            {
                MetadataReference.CreateFromFile(typeof(object).Assembly.Location),
                MetadataReference.CreateFromFile(typeof(Enumerable).Assembly.Location)
            };

            CSharpCompilation compilation = CSharpCompilation.Create(
                assemblyName,
                syntaxTrees: new[] { syntaxTree },
                references: references,
                options: new CSharpCompilationOptions(OutputKind.DynamicallyLinkedLibrary));

            Console.WriteLine("Compiling...");
            Stopwatch stopWatch = new Stopwatch();

            stopWatch.Start();
            EmitResult result = compilation.Emit(ms);

            stopWatch.Stop();
            Console.WriteLine("Compile complete. (" + stopWatch.ElapsedMilliseconds + "ms)");
            script.LastCompilationTime = DateTime.UtcNow;
            if (!result.Success)
            {
                script.AbortProcessing = true;
                IEnumerable <Diagnostic> failures = result.Diagnostics.Where(diagnostic =>
                                                                             diagnostic.IsWarningAsError ||
                                                                             diagnostic.Severity == DiagnosticSeverity.Error);

                foreach (Diagnostic diagnostic in failures)
                {
                    Console.Error.WriteLine("{0}: {1}", diagnostic.Id, diagnostic.GetMessage());
                }
            }
        }
 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);
     }
 }
        private static ContractCompilationResult Compile(IEnumerable <SyntaxTree> syntaxTrees)
        {
            // @TODO - Use OptimizationLevel.Release once we switch to injecting compiler options
            CSharpCompilation compilation = CSharpCompilation.Create(
                AssemblyName,
                syntaxTrees,
                GetReferences(),
                new CSharpCompilationOptions(
                    OutputKind.DynamicallyLinkedLibrary,
                    checkOverflow: true));


            using (var dllStream = new MemoryStream())
            {
                EmitResult emitResult = compilation.Emit(dllStream);
                if (!emitResult.Success)
                {
                    return(ContractCompilationResult.Failed(emitResult.Diagnostics));
                }

                return(ContractCompilationResult.Succeeded(dllStream.ToArray()));
            }
        }
Esempio n. 26
0
        private void CompileSourceCode()
        {
            SyntaxTree tree = CSharpSyntaxTree.ParseText(sourceCode, new CSharpParseOptions(LanguageVersion.CSharp5));
            IEnumerable <MetadataReference> assemblyReferences =
                references.Select(x => MetadataReference.CreateFromFile(x.Location));

            CSharpCompilation compilation = CSharpCompilation.Create(outputAssemblyFileName,
                                                                     options: new CSharpCompilationOptions(OutputKind.DynamicallyLinkedLibrary), syntaxTrees: new[] { tree },
                                                                     references: assemblyReferences);

            ImmutableArray <Diagnostic> compilerDiagnostics = compilation.GetDiagnostics(CancellationToken.None);

            ValidateCompilerDiagnostics(compilerDiagnostics);

            using (FileStream assemblyStream = File.Create(outputAssemblyFileName))
            {
                EmitResult compileResult = compilation.Emit(assemblyStream);

                Assert.True(compileResult.Success,
                            string.Format("Test Assembly Generation failed due to: {0}\r\n\r\nin:\r\n{1}",
                                          string.Join("\r\n", compileResult.Diagnostics), sourceCode));
            }
        }
Esempio n. 27
0
        public static void Compile()
        {
            string source   = "";
            string assembly = "test.exe";

            var syntaxTree = CSharpSyntaxTree.ParseText(source);

            CSharpCompilation compilation = CSharpCompilation.Create(
                assembly,
                new[] { syntaxTree },
                new[] { MetadataReference.CreateFromFile(typeof(object).Assembly.Location) },
                new CSharpCompilationOptions(OutputKind.DynamicallyLinkedLibrary));

            using (var dllStream = new MemoryStream())
                using (var pdbStream = new MemoryStream())
                {
                    var emitResult = compilation.Emit(dllStream, pdbStream);
                    if (!emitResult.Success)
                    {
                        // emitResult.Diagnostics
                    }
                }
        }
Esempio n. 28
0
        private static byte[] CompileAssembly(CSharpCompilation compiler)
        {
            byte[]       instrumentedAssembly;
            MemoryStream stream = new MemoryStream();

            EmitResult result = compiler.Emit(stream);

            if (IsMarginalSuccess(result))
            {
                instrumentedAssembly = stream.ToArray();
            }
            else
            {
                string errors = "";
                foreach (var resultDiagnostic in result.Diagnostics)
                {
                    errors += resultDiagnostic.ToString();
                    errors += "\r\n";
                }
                throw new Exception("Failed to instrument " + compiler.AssemblyName + ": " + errors);
            }
            return(instrumentedAssembly);
        }
        private EmitResult EmitAssembly(
            CSharpCompilation compilation,
            string assemblyPath,
            ResourceDescription[] resources)
        {
            Directory.CreateDirectory(Path.GetDirectoryName(assemblyPath));

            EmitResult emitResult;

            using (var assemblyStream = File.OpenWrite(assemblyPath))
            {
                using (var pdbStream = File.OpenWrite(Path.ChangeExtension(assemblyPath, ".pdb")))
                {
                    emitResult = compilation.Emit(
                        assemblyStream,
                        pdbStream,
                        manifestResources: resources,
                        options: MvcServiceProvider.Compiler.EmitOptions);
                }
            }

            return(emitResult);
        }
Esempio n. 30
0
        private static Assembly Compile(SyntaxTree syntaxTree)
        {
            string assemblyName = "HotChocolate.Resolvers.CodeGeneration" +
                                  $"._{Guid.NewGuid().ToString("N")}.dll";

            CSharpCompilation compilation = CSharpCompilation.Create(
                assemblyName, new SyntaxTree[] { syntaxTree },
                ResolveReferences(), _options);

            using (MemoryStream stream = new MemoryStream())
            {
                EmitResult result = compilation.Emit(stream);
                if (result.Success)
                {
                    stream.Position = 0;
                    return(Assembly.Load(stream.ToArray()));
                }

                // TODO : EXCEPTION
                throw new Exception(string.Join(Environment.NewLine,
                                                result.Diagnostics.Select(t => t.ToString())));
            }
        }
Esempio n. 31
0
        internal void VerifyAssemblyTable(
            CSharpCompilation compilation,
            Action<AssemblyDefinition> verifier,
            string strData = null,
            byte[] blobData = null,
            Guid guidData = default(Guid),
            string uddData = null)
        {
            var stream = new MemoryStream();
            Assert.True(compilation.Emit(stream).Success);
            stream.Position = 0;

            using (var metadata = ModuleMetadata.CreateFromImageStream(stream))
            {
                var peReader = metadata.MetadataReader;
                AssemblyDefinition row = peReader.GetAssemblyDefinition();

                if (verifier != null)
                    verifier(row);

                // Locale
                // temp
                if (strData != null)
                {
                    Assert.Equal(strData, peReader.GetString(row.Culture));
                }

                // PublicKey
                //Assert.Equal((uint)0, row.PublicKey);
            }
        }
Esempio n. 32
0
        // In VB use AssertTheseErrors format for expected diagnostics!
        private static void VerifyEmitDiagnostics(
            CSharpCompilation compilation,
            bool metadataOnlyShouldSucceed,
            DiagnosticDescription[] expectedFullBuildDiagnostics,
            DiagnosticDescription[] expectedMetadataOnlyDiagnostics = null)
        {
            using (var executableStream = new MemoryStream())
            {
                var result = compilation.Emit(executableStream);
                Assert.False(result.Success);
                result.Diagnostics.Verify(expectedFullBuildDiagnostics);
            }

            using (var executableStream = new MemoryStream())
            {
                var result = compilation.Emit(executableStream, options: new EmitOptions(metadataOnly: true));

                if (metadataOnlyShouldSucceed)
                {
                    Assert.True(result.Success);
                    result.Diagnostics.Verify();
                }
                else
                {
                    Assert.False(result.Success);
                    result.Diagnostics.Verify(expectedMetadataOnlyDiagnostics ?? expectedFullBuildDiagnostics);
                }
            }
        }