Exemplo n.º 1
0
        /// <summary>
        /// Generate one GrainReference class for each Grain Type in the inputLib file
        /// and output one GrainClient.dll under outputLib directory
        /// </summary>
        private bool CreateGrainClient(CodeGenOptions options)
        {
            // Load input assembly
            // special case Orleans.dll because there is a circular dependency.
            var assemblyName  = AssemblyName.GetAssemblyName(options.InputAssembly.FullName);
            var grainAssembly = (Path.GetFileName(options.InputAssembly.FullName) != "Orleans.dll")
                                    ? Assembly.LoadFrom(options.InputAssembly.FullName)
                                    : Assembly.Load(assemblyName);

            // Create directory for output file if it does not exist
            var outputFileDirectory = Path.GetDirectoryName(options.OutputFileName);

            if (!String.IsNullOrEmpty(outputFileDirectory) && !Directory.Exists(outputFileDirectory))
            {
                Directory.CreateDirectory(outputFileDirectory);
            }

            var codeGenerator = new RoslynCodeGenerator(new SerializationManager(null, new GlobalConfiguration()));

            // Generate source
            ConsoleText.WriteStatus("Orleans-CodeGen - Generating file {0}", options.OutputFileName);

            using (var sourceWriter = new StreamWriter(options.OutputFileName))
            {
                sourceWriter.WriteLine("#if !EXCLUDE_CODEGEN");
                DisableWarnings(sourceWriter, suppressCompilerWarnings);
                sourceWriter.WriteLine(codeGenerator.GenerateSourceForAssembly(grainAssembly));
                RestoreWarnings(sourceWriter, suppressCompilerWarnings);
                sourceWriter.WriteLine("#endif");
            }

            ConsoleText.WriteStatus("Orleans-CodeGen - Generated file written {0}", options.OutputFileName);

            return(true);
        }
Exemplo n.º 2
0
 private static string GenerateSourceForAssembly(Assembly grainAssembly, LogLevel logLevel)
 {
     using (var loggerFactory = new LoggerFactory())
     {
         var config = new ClusterConfiguration();
         loggerFactory.AddConsole(logLevel);
         var serializationProviderOptions = Options.Create(
             new SerializationProviderOptions
         {
             SerializationProviders        = config.Globals.SerializationProviders,
             FallbackSerializationProvider = config.Globals.FallbackSerializationProvider
         });
         var applicationPartManager = new ApplicationPartManager();
         applicationPartManager.AddFeatureProvider(new BuiltInTypesSerializationFeaturePopulator());
         applicationPartManager.AddFeatureProvider(new AssemblyAttributeFeatureProvider <GrainInterfaceFeature>());
         applicationPartManager.AddFeatureProvider(new AssemblyAttributeFeatureProvider <GrainClassFeature>());
         applicationPartManager.AddFeatureProvider(new AssemblyAttributeFeatureProvider <SerializerFeature>());
         applicationPartManager.AddApplicationPart(grainAssembly);
         applicationPartManager.AddApplicationPart(typeof(RuntimeVersion).Assembly);
         applicationPartManager.AddApplicationPartsFromReferences(grainAssembly);
         applicationPartManager.AddApplicationPartsFromReferences(typeof(RuntimeVersion).Assembly);
         var serializationManager = new SerializationManager(null, serializationProviderOptions, loggerFactory, new CachedTypeResolver());
         serializationManager.RegisterSerializers(applicationPartManager);
         var codeGenerator = new RoslynCodeGenerator(serializationManager, applicationPartManager, loggerFactory);
         return(codeGenerator.GenerateSourceForAssembly(grainAssembly));
     }
 }
Exemplo n.º 3
0
        /// <summary>
        /// Generate one GrainReference class for each Grain Type in the inputLib file
        /// and output a string with the code
        /// </summary>
        private string CreateGrainClient(CodeGenOptions options)
        {
            // Load input assembly
            // special case Orleans.dll because there is a circular dependency.
            var assemblyName  = AssemblyName.GetAssemblyName(options.InputAssembly.FullName);
            var grainAssembly = (Path.GetFileName(options.InputAssembly.FullName) != "Orleans.dll")
                                    ? Assembly.LoadFrom(options.InputAssembly.FullName)
                                    : Assembly.Load(assemblyName);

            // Create directory for output file if it does not exist
            var outputFileDirectory = Path.GetDirectoryName(options.OutputFileName);

            if (!String.IsNullOrEmpty(outputFileDirectory) && !Directory.Exists(outputFileDirectory))
            {
                Directory.CreateDirectory(outputFileDirectory);
            }

            var config        = new ClusterConfiguration();
            var codeGenerator = new RoslynCodeGenerator(new SerializationManager(null, config.Globals, config.Defaults));

            // Generate source
            ConsoleText.WriteStatus("Orleans-CodeGen - Generating file {0}", options.OutputFileName);

            return(codeGenerator.GenerateSourceForAssembly(grainAssembly));
        }
Exemplo n.º 4
0
        /// <summary>
        /// Generates support code for the provided assembly and adds it to the builder.
        /// </summary>
        /// <param name="manager">The builder.</param>
        /// <param name="loggerFactory">The optional logger factory, for outputting code generation diagnostics.</param>
        /// <returns>A builder with support parts added.</returns>
        public static IApplicationPartManagerWithAssemblies WithCodeGeneration(this IApplicationPartManagerWithAssemblies manager, ILoggerFactory loggerFactory = null)
        {
            var stopWatch = Stopwatch.StartNew();

            loggerFactory = loggerFactory ?? new NullLoggerFactory();
            var tempPartManager = new ApplicationPartManager();

            foreach (var provider in manager.FeatureProviders)
            {
                tempPartManager.AddFeatureProvider(provider);
            }

            foreach (var part in manager.ApplicationParts)
            {
                tempPartManager.AddApplicationPart(part);
            }

            tempPartManager.AddApplicationPart(new AssemblyPart(typeof(RuntimeVersion).Assembly));
            tempPartManager.AddFeatureProvider(new AssemblyAttributeFeatureProvider <GrainInterfaceFeature>());
            tempPartManager.AddFeatureProvider(new AssemblyAttributeFeatureProvider <GrainClassFeature>());
            tempPartManager.AddFeatureProvider(new AssemblyAttributeFeatureProvider <SerializerFeature>());
            tempPartManager.AddFeatureProvider(new BuiltInTypesSerializationFeaturePopulator());

            var codeGenerator     = new RoslynCodeGenerator(tempPartManager, loggerFactory);
            var generatedAssembly = codeGenerator.GenerateAndLoadForAssemblies(manager.Assemblies);

            stopWatch.Stop();
            var logger = loggerFactory.CreateLogger("Orleans.CodeGenerator.RuntimeCodeGen");

            logger?.LogInformation(0, $"Runtime code generation for assemblies {String.Join(",", manager.Assemblies.ToStrings())} took {stopWatch.ElapsedMilliseconds} milliseconds");
            return(manager.AddApplicationPart(generatedAssembly));
        }
        /// <summary>
        /// Generates support code for the the provided assembly and adds it to the builder.
        /// </summary>
        /// <param name="manager">The builder.</param>
        /// <returns>A builder with support parts added.</returns>
        public static IApplicationPartManagerWithAssemblies WithCodeGeneration(this IApplicationPartManagerWithAssemblies manager)
        {
            var tempPartManager = new ApplicationPartManager();

            foreach (var provider in manager.FeatureProviders)
            {
                tempPartManager.AddFeatureProvider(provider);
            }

            foreach (var part in manager.ApplicationParts)
            {
                tempPartManager.AddApplicationPart(part);
            }

            tempPartManager.AddApplicationPart(new AssemblyPart(typeof(RuntimeVersion).Assembly));
            tempPartManager.AddFeatureProvider(new AssemblyAttributeFeatureProvider <GrainInterfaceFeature>());
            tempPartManager.AddFeatureProvider(new AssemblyAttributeFeatureProvider <GrainClassFeature>());
            tempPartManager.AddFeatureProvider(new AssemblyAttributeFeatureProvider <SerializerFeature>());
            tempPartManager.AddFeatureProvider(new BuiltInTypesSerializationFeaturePopulator());

            var codeGenerator     = new RoslynCodeGenerator(tempPartManager, new NullLoggerFactory());
            var generatedAssembly = codeGenerator.GenerateAndLoadForAssemblies(manager.Assemblies);

            return(manager.AddApplicationPart(generatedAssembly));
        }
Exemplo n.º 6
0
        public override void Execute(Script script)
        {
            // Generate the script code.
            var generator = new RoslynCodeGenerator();
            var code      = generator.Generate(script);

            _log.Verbose("Compiling build script...");
            RoslynSession.Execute(code);
        }
Exemplo n.º 7
0
        public void Execute(Script script)
        {
            // Generate the script code.
            var generator = new RoslynCodeGenerator();
            var code      = generator.Generate(script);

            _log.Debug("Compiling build script...");
            _roslynSession.Execute(code);
        }
Exemplo n.º 8
0
        public override void Execute(Script script)
        {
            // Generate the script code.
            var generator = new RoslynCodeGenerator();
            var code      = generator.Generate(script);

            // Create the script options dynamically.
            var options = Microsoft.CodeAnalysis.Scripting.ScriptOptions.Default
                          .AddNamespaces(Namespaces)
                          .AddReferences(References)
                          .AddReferences(ReferencePaths.Select(r => r.FullPath));

            _log.Verbose("Compiling build script for debugging...");

            var roslynScript = Microsoft.CodeAnalysis.Scripting.CSharp.CSharpScript.Create(code, options)
                               .WithGlobalsType(_host.GetType());

            var compilation = roslynScript.GetCompilation();

            compilation = compilation.WithOptions(compilation.Options
                                                  .WithOptimizationLevel(Microsoft.CodeAnalysis.OptimizationLevel.Debug)
                                                  .WithOutputKind(Microsoft.CodeAnalysis.OutputKind.DynamicallyLinkedLibrary));

            using (var exeStream = new MemoryStream())
                using (var pdbStream = new MemoryStream())
                {
                    var result = compilation.Emit(exeStream, pdbStream: pdbStream);

                    if (result.Success)
                    {
                        _log.Verbose("Compilation successful");

                        var assembly = AppDomain.CurrentDomain.Load(exeStream.ToArray(), pdbStream.ToArray());

                        var type   = assembly.GetType(CompiledType);
                        var method = type.GetMethod(CompiledMethod, BindingFlags.Static | BindingFlags.Public);

                        var submissionStates = new object[2];
                        submissionStates[0] = _host;

                        method.Invoke(null, new[] { submissionStates });
                    }
                    else
                    {
                        _log.Verbose("Compilation failed");

                        var errors  = string.Join(Environment.NewLine, result.Diagnostics.Select(x => x.ToString()));
                        var message = string.Format(System.Globalization.CultureInfo.InvariantCulture, "Error occurred when compiling: {0}", errors);

                        throw new CakeException(message);
                    }
                }
        }
        public override void Execute(Script script)
        {
            // Generate the script code.
            var generator = new RoslynCodeGenerator();
            var code      = generator.Generate(script);

            // Create the script options dynamically.
            var options = Microsoft.CodeAnalysis.Scripting.ScriptOptions.Default
                          .AddNamespaces(Namespaces)
                          .AddReferences(References)
                          .AddReferences(ReferencePaths.Select(r => r.FullPath));

            _log.Verbose("Compiling build script...");
            Microsoft.CodeAnalysis.Scripting.CSharp.CSharpScript.Eval(code, options, _host);
        }
Exemplo n.º 10
0
        public override void Execute(Script script)
        {
            // Generate the script code.
            var generator = new RoslynCodeGenerator();
            var code      = generator.Generate(script);

            // Create the script options dynamically.
            var options = Microsoft.CodeAnalysis.Scripting.ScriptOptions.Default
                          .AddImports(Namespaces)
                          .AddReferences(References)
                          .AddReferences(ReferencePaths.Select(r => r.FullPath));

            var roslynScript = CSharpScript.Create(code, options, _host.GetType());
            var compilation  = roslynScript.GetCompilation();

            compilation = compilation.WithOptions(compilation.Options
                                                  .WithOptimizationLevel(OptimizationLevel.Debug)
                                                  .WithOutputKind(OutputKind.DynamicallyLinkedLibrary));

            using (var assemblyStream = new MemoryStream())
                using (var symbolStream = new MemoryStream())
                {
                    _log.Verbose("Compiling build script for debugging...");
                    var emitOptions = new EmitOptions(false, DebugInformationFormat.PortablePdb);
                    var result      = compilation.Emit(assemblyStream, symbolStream, options: emitOptions);
                    if (result.Success)
                    {
                        // Rewind the streams.
                        assemblyStream.Seek(0, SeekOrigin.Begin);
                        symbolStream.Seek(0, SeekOrigin.Begin);

                        var assembly = AssemblyLoadContext.Default.LoadFromStream(assemblyStream, symbolStream);
                        var type     = assembly.GetType(CompiledType);
                        var method   = type.GetMethod(CompiledMethod, BindingFlags.Static | BindingFlags.Public);

                        var submissionStates = new object[2];
                        submissionStates[0] = _host;

                        method.Invoke(null, new object[] { submissionStates });
                    }
                    else
                    {
                        var errors  = string.Join(Environment.NewLine, result.Diagnostics.Select(x => x.ToString()));
                        var message = string.Format(CultureInfo.InvariantCulture, "Error occurred when compiling: {0}", errors);
                        throw new CakeException(message);
                    }
                }
        }
Exemplo n.º 11
0
 private static string GenerateSourceForAssembly(Assembly grainAssembly, LogLevel logLevel)
 {
     using (var loggerFactory = new LoggerFactory())
     {
         loggerFactory.AddConsole(logLevel);
         var parts = new ApplicationPartManager()
                     .AddFeatureProvider(new BuiltInTypesSerializationFeaturePopulator())
                     .AddFeatureProvider(new AssemblyAttributeFeatureProvider <GrainInterfaceFeature>())
                     .AddFeatureProvider(new AssemblyAttributeFeatureProvider <GrainClassFeature>())
                     .AddFeatureProvider(new AssemblyAttributeFeatureProvider <SerializerFeature>());
         parts.AddApplicationPart(grainAssembly).WithReferences();
         parts.AddApplicationPart(typeof(RuntimeVersion).Assembly).WithReferences();
         var codeGenerator = new RoslynCodeGenerator(parts, loggerFactory);
         return(codeGenerator.GenerateSourceForAssembly(grainAssembly));
     }
 }
Exemplo n.º 12
0
 internal static string GenerateSourceForAssembly(Assembly grainAssembly)
 {
     using (var loggerFactory = new LoggerFactory())
     {
         var config = new ClusterConfiguration();
         loggerFactory.AddProvider(new ConsoleLoggerProvider(new ConsoleLoggerSettings()));
         var serializationProviderOptions = Options.Create(
             new SerializationProviderOptions
         {
             SerializationProviders        = config.Globals.SerializationProviders,
             FallbackSerializationProvider = config.Globals.FallbackSerializationProvider
         });
         var codeGenerator = new RoslynCodeGenerator(new SerializationManager(null, serializationProviderOptions, null, loggerFactory), loggerFactory);
         return(codeGenerator.GenerateSourceForAssembly(grainAssembly));
     }
 }
Exemplo n.º 13
0
        public override void Execute(Script script)
        {
            // Generate the script code.
            var generator = new RoslynCodeGenerator();
            var code      = generator.Generate(script);

            _log.Verbose("Compiling build script for debugging...");

            var submission = RoslynSession.CompileSubmission <CakeReport>(code);

            var compilation = (global::Roslyn.Compilers.CSharp.Compilation)submission.Compilation;

            compilation = compilation.WithOptions(compilation.Options
                                                  .WithOptimizations(false)
                                                  .WithDebugInformationKind(global::Roslyn.Compilers.Common.DebugInformationKind.Full));

            using (var outputStream = new MemoryStream())
                using (var pdbStream = new MemoryStream())
                {
                    var result = compilation.Emit(outputStream, null, null, pdbStream);

                    if (result.Success)
                    {
                        _log.Verbose("Compilation successful");

                        var assembly = AppDomain.CurrentDomain.Load(outputStream.ToArray(), pdbStream.ToArray());
                        var type     = assembly.GetType(CompiledType);
                        var method   = type.GetMethod(CompiledMethod, BindingFlags.Static | BindingFlags.Public);

                        method.Invoke(null, new[] { RoslynSession });
                    }
                    else
                    {
                        _log.Verbose("Compilation failed");

                        var errors  = string.Join(Environment.NewLine, result.Diagnostics.Select(x => x.ToString()));
                        var message = string.Format(System.Globalization.CultureInfo.InvariantCulture, "Error occurred when compiling: {0}", errors);

                        throw new CakeException(message);
                    }
                }
        }
Exemplo n.º 14
0
        private static string GenerateSourceForAssembly(Assembly grainAssembly, LogLevel logLevel)
        {
            var serviceCollection = new ServiceCollection()
                                    .AddLogging(logging =>
            {
                logging
                .AddConsole()
                .SetMinimumLevel(logLevel);
            });

            using (var services = serviceCollection.BuildServiceProvider())
            {
                var loggerFactory = services.GetRequiredService <ILoggerFactory>();
                var parts         = new ApplicationPartManager()
                                    .AddFeatureProvider(new BuiltInTypesSerializationFeaturePopulator())
                                    .AddFeatureProvider(new AssemblyAttributeFeatureProvider <GrainInterfaceFeature>())
                                    .AddFeatureProvider(new AssemblyAttributeFeatureProvider <GrainClassFeature>())
                                    .AddFeatureProvider(new AssemblyAttributeFeatureProvider <SerializerFeature>());
                parts.AddApplicationPart(grainAssembly).WithReferences();
                parts.AddApplicationPart(typeof(RuntimeVersion).Assembly).WithReferences();
                var codeGenerator = new RoslynCodeGenerator(parts, loggerFactory);
                return(codeGenerator.GenerateSourceForAssembly(grainAssembly));
            }
        }