コード例 #1
0
        private ScriptServices CreateScriptServices()
        {
            var console     = new ScriptConsole();
            var logProvider = new ColoredConsoleLogProvider(LogLevel.Info, console);

            var initializationServices = new InitializationServices(logProvider);

            initializationServices.GetAppDomainAssemblyResolver().Initialize();

            var scriptServicesBuilder = new ScriptServicesBuilder(console, logProvider, null, null, initializationServices);

            scriptServicesBuilder.Overrides[typeof(IFileSystem)] = _options.FileSystem;
            scriptServicesBuilder.LoadScriptPacks();
            scriptServicesBuilder.LoadModules(".csx", _options.Modules);

            var scriptServices = scriptServicesBuilder.Build();

            var assemblies = scriptServices.AssemblyResolver.GetAssemblyPaths(_options.FileSystem.CurrentDirectory, true);
            var packs      = scriptServices.ScriptPackResolver.GetPacks();

            scriptServices.Executor.Initialize(assemblies, packs, _options.ScriptArgs);
            scriptServices.Executor.AddReferences(typeof(Attribute), typeof(ExportAttribute));
            scriptServices.Executor.ImportNamespaces("System.ComponentModel.Composition");

            if (_options.References != null)
            {
                scriptServices.Executor.AddReferenceAndImportNamespaces(_options.References);
            }

            return(scriptServices);
        }
コード例 #2
0
        private void StartScriptCs()
        {
            var name    = "WPFScript.csx";
            var console = new WPFConsoleRelay();

            var configurator = new LoggerConfigurator(LogLevel.Info);

            configurator.Configure(console);
            var logger = configurator.GetLogger();

            var init = new InitializationServices(logger);

            init.GetAppDomainAssemblyResolver().Initialize();

            var builder = new ScriptServicesBuilder(console, logger, null, null, init)
                          .Cache()
                          .Debug(false)
                          .LogLevel(LogLevel.Info)
                          .ScriptName(name)
                          .Repl();

            var modules   = new string[0];
            var extension = Path.GetExtension(name);

            //OVERRIDES
            builder.ScriptHostFactory <WPFScriptHostFactory>();
            builder.ScriptEngine <RoslynScriptEngine>();
            builder.LoadModules(extension, modules);

            //BUILD SERVICE
            _service = builder.Build();
            _service.Executor.Initialize(Enumerable.Empty <string>(), _service.ScriptPackResolver.GetPacks(), new string[0]);
            var types = new Type[] {
                typeof(IConsole),
                typeof(ScriptContext),
                typeof(Newtonsoft.Json.Converters.BinaryConverter)
            };


            _service.Executor.AddReferenceAndImportNamespaces(types);



            EventAggr.Instance.GetEvent <WriteLineEvent>().Subscribe((text) =>
            {
                string[] lines = text.Split(new string[] { Environment.NewLine }, StringSplitOptions.None);
                foreach (var line in lines.Where(l => !string.IsNullOrEmpty(l)))
                {
                    _area.Document.Text += line;
                    NewLine();
                    _area.Document.Text += ">";
                }
            });

            EventAggr.Instance.GetEvent <WriteEvent>().Subscribe((text) =>
            {
                _area.Document.Text += text;
            }
                                                                 );
        }
コード例 #3
0
    private IScriptExecutor GetExecutor(List <string> references, string rootPath)
    {
        var console      = new ScriptConsole();
        var loggerConfig = new LoggerConfigurator(ScriptCs.Contracts.LogLevel.Error);

        loggerConfig.Configure(console);
        var logger = loggerConfig.GetLogger();

        var builder = new ScriptServicesBuilder(console, logger).
                      InMemory(true).
                      ScriptName("");

        var services = builder.Build();
        var executor = services.Executor;
        var paths    = services.AssemblyResolver.GetAssemblyPaths(rootPath, null).Where(p => !p.Contains("Contracts"));

        var packs = services.ScriptPackResolver.GetPacks();

        executor.Initialize(paths, packs);

        executor.AddReferences(references.ToArray());
        var reference = Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location) + @"\ScriptCs.Contracts.dll";

        executor.AddReferences(reference);
        executor.ImportNamespaces("ScriptCs.Contracts");
        return(executor);
    }
コード例 #4
0
            public void ShouldReturnTheBuilder(ScriptServicesBuilder builder)
            {
                var someValue       = new SomeOverride();
                var returnedBuilder = builder.SetOverride <ISomeOverride, SomeOverride>(someValue);

                returnedBuilder.ShouldBeSameAs(builder);
            }
コード例 #5
0
        public void Main(string[] args)
        {
            var assemblyReslover = new AspNet5AssemblyResolver(_libraryManager);
            var scriptServicesBuilder =
                new ScriptServicesBuilder(Console, new DefaultLogProvider()).Cache(false).Repl(true);

            scriptServicesBuilder = IsMono ? scriptServicesBuilder.ScriptEngine<MonoScriptEngine>() : scriptServicesBuilder.ScriptEngine<RoslynScriptEngine>();

            ((ScriptServicesBuilder)scriptServicesBuilder).Overrides[typeof (IAssemblyResolver)] = assemblyReslover;

            var scriptcs = scriptServicesBuilder.Build();

            scriptcs.Repl.Initialize(assemblyReslover.GetAssemblyPaths(string.Empty), Enumerable.Empty<IScriptPack>());

            try
            {
                while (ExecuteLine(scriptcs.Repl))
                {
                }

                Console.WriteLine();
            }
            catch (Exception ex)
            {
                var oldColor = Console.ForegroundColor;
                Console.ForegroundColor = ConsoleColor.Red;
                Console.WriteLine(ex.Message);
                Console.ForegroundColor = oldColor;
            }

        }
コード例 #6
0
ファイル: Program.cs プロジェクト: johnduhart/scriptcs
        private static int Main(string[] args)
        {
            string[] scriptArgs;
            ScriptCsArgs.SplitScriptArgs(ref args, out scriptArgs);

            var commandArgs = ParseArguments(args);
            var configurator = new LoggerConfigurator(commandArgs.LogLevel);
            var console = new ScriptConsole();
            configurator.Configure(console);
            var logger = configurator.GetLogger();

            var scriptServicesBuilder = new ScriptServicesBuilder(console, logger)   .
                Debug(commandArgs.Debug).
                LogLevel(commandArgs.LogLevel).
                ScriptName(commandArgs.ScriptName).
                Repl(commandArgs.Repl);

            var modules = GetModuleList(commandArgs.Modules);
            var extension = Path.GetExtension(commandArgs.ScriptName);
            if (extension != null)
                extension = extension.Substring(1);

            scriptServicesBuilder.LoadModules(extension, modules);
            var scriptServiceRoot = scriptServicesBuilder.Build();

            var commandFactory = new CommandFactory(scriptServiceRoot);
            var command = commandFactory.CreateCommand(commandArgs, scriptArgs);

            var result = command.Execute();

            return result == CommandResult.Success ? 0 : -1;
        }
コード例 #7
0
        public static IScriptServicesBuilder Create(Config config, string[] scriptArgs)
        {
            Guard.AgainstNullArgument("commandArgs", config);
            Guard.AgainstNullArgument("scriptArgs", scriptArgs);

            IConsole console = new ScriptConsole();
            if (!string.IsNullOrWhiteSpace(config.OutputFile))
            {
                console = new FileConsole(config.OutputFile, console);
            }

            var logProvider = new ColoredConsoleLogProvider(config.LogLevel, console);
            var initializationServices = new InitializationServices(logProvider);
            initializationServices.GetAppDomainAssemblyResolver().Initialize();

            // NOTE (adamralph): this is a hideous assumption about what happens inside the CommandFactory.
            // It is a result of the ScriptServicesBuilderFactory also having to know what is going to happen inside the
            // Command Factory so that it builds the builder(:-p) correctly in advance.
            // This demonstrates the technical debt that exists with the ScriptServicesBuilderFactory and CommandFactory
            // in their current form. We have a separate refactoring task raised to address this.
            var repl = config.Repl ||
                (!config.Clean && config.PackageName == null && !config.Save && config.ScriptName == null);

            var scriptServicesBuilder = new ScriptServicesBuilder(console, logProvider, null, null, initializationServices)
                .Cache(config.Cache)
                .Debug(config.Debug)
                .LogLevel(config.LogLevel)
                .ScriptName(config.ScriptName)
                .Repl(repl);

            return scriptServicesBuilder.LoadModules(Path.GetExtension(config.ScriptName) ?? ".csx", config.Modules);
        }
コード例 #8
0
        public void Main(string[] args)
        {
            var assemblyReslover      = new AspNet5AssemblyResolver(_libraryManager);
            var scriptServicesBuilder =
                new ScriptServicesBuilder(Console, new DefaultLogProvider()).Cache(false).Repl(true);

            scriptServicesBuilder = IsMono ? scriptServicesBuilder.ScriptEngine <MonoScriptEngine>() : scriptServicesBuilder.ScriptEngine <RoslynScriptEngine>();

            ((ScriptServicesBuilder)scriptServicesBuilder).Overrides[typeof(IAssemblyResolver)] = assemblyReslover;

            var scriptcs = scriptServicesBuilder.Build();

            scriptcs.Repl.Initialize(assemblyReslover.GetAssemblyPaths(string.Empty), Enumerable.Empty <IScriptPack>());

            try
            {
                while (ExecuteLine(scriptcs.Repl))
                {
                }

                Console.WriteLine();
            }
            catch (Exception ex)
            {
                var oldColor = Console.ForegroundColor;
                Console.ForegroundColor = ConsoleColor.Red;
                Console.WriteLine(ex.Message);
                Console.ForegroundColor = oldColor;
            }
        }
コード例 #9
0
        public ScriptCsService()
        {
            var logger = LogManager.GetLogger(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType);

            var scriptServicesBuilder = new ScriptServicesBuilder(new ScriptConsole(), logger).
                LogLevel(LogLevel.Info).Cache(false).Repl(false).ScriptEngine<RoslynScriptEngine>();

            Root = scriptServicesBuilder.Build();
        }
コード例 #10
0
 public void ShouldLoadScriptPacksIfScriptNameIsSet(IConsole console, TestLogProvider logProvider, IScriptEngine engine)
 {
     var builder = new ScriptServicesBuilder(console, logProvider);
     builder.Overrides[typeof(IScriptEngine)] = engine.GetType();
     builder.ScriptName("");
     builder.Build();
     var runtimeServices = (RuntimeServices)builder.RuntimeServices;
     runtimeServices.InitDirectoryCatalog.ShouldBeTrue();
 }
コード例 #11
0
 public void ShouldNotLoadScriptPacksIfLoadScriptPacksIsFalse(IConsole console, TestLogProvider logProvider, IScriptEngine engine)
 {
     var builder = new ScriptServicesBuilder(console, logProvider);
     builder.Overrides[typeof(IScriptEngine)] = engine.GetType();
     builder.LoadScriptPacks(false);
     builder.Build();
     var runtimeServices = (RuntimeServices)builder.RuntimeServices;
     runtimeServices.InitDirectoryCatalog.ShouldBeFalse();
 }
コード例 #12
0
ファイル: Program.cs プロジェクト: Jaydeep7/scriptcs
        private static int Main(string[] args)
        {
            ProfileOptimization.SetProfileRoot(typeof(Program).Assembly.Location);
            ProfileOptimization.StartProfile(typeof(Program).Assembly.GetName().Name + ".profile");

            var console = new ScriptConsole();

            var parser = new ArgumentHandler(new ArgumentParser(console), new ConfigFileParser(console), new FileSystem());
            var arguments = parser.Parse(args);
            var commandArgs = arguments.CommandArguments;
            var scriptArgs = arguments.ScriptArguments;

            var configurator = new LoggerConfigurator(commandArgs.LogLevel);
            configurator.Configure(console);
            var logger = configurator.GetLogger();

            var scriptServicesBuilder = new ScriptServicesBuilder(console, logger)
                .Cache(commandArgs.Cache)
                .Debug(commandArgs.Debug)
                .LogLevel(commandArgs.LogLevel)
                .ScriptName(commandArgs.ScriptName)
                .Repl(commandArgs.Repl);

            var modules = GetModuleList(commandArgs.Modules);
            var extension = Path.GetExtension(commandArgs.ScriptName);

            if (string.IsNullOrWhiteSpace(extension) && !commandArgs.Repl)
            {
                // No extension was given, i.e we might have something like
                // "scriptcs foo" to deal with. We activate the default extension,
                // to make sure it's given to the LoadModules below.
                extension = ".csx";

                if (!string.IsNullOrWhiteSpace(commandArgs.ScriptName))
                {
                    // If the was in fact a script specified, we'll extend it
                    // with the default extension, assuming the user giving
                    // "scriptcs foo" actually meant "scriptcs foo.csx". We
                    // perform no validation here thought; let it be done by
                    // the activated command. If the file don't exist, it's
                    // up to the command to detect and report.

                    commandArgs.ScriptName += extension;
                }
            }

            scriptServicesBuilder.LoadModules(extension, modules);
            var scriptServiceRoot = scriptServicesBuilder.Build();

            var commandFactory = new CommandFactory(scriptServiceRoot);
            var command = commandFactory.CreateCommand(commandArgs, scriptArgs);

            var result = command.Execute();

            return result == CommandResult.Success ? 0 : -1;
        }
コード例 #13
0
 static void SetEngine(ScriptServicesBuilder builder)
 {
     var useMono = Type.GetType ("Mono.Runtime") != null;
     if (useMono) {
         builder.ScriptEngine<MonoScriptEngine> ();
     }
     else {
         builder.ScriptEngine<RoslynScriptEngine> ();
     }
 }
コード例 #14
0
 public void ShouldLoadTheMonoModuleWhenTheMonoModuleIsPassedInTheListOfModules([Frozen] Mock<ITypeResolver> typeResolver, [Frozen] Mock<IModuleLoader> moduleLoader, ScriptServicesBuilder builder)
 {
     typeResolver.Setup(r => r.ResolveType("Mono.Runtime")).Returns((Type)null);
     moduleLoader.Setup(
         m =>
             m.Load(It.IsAny<IModuleConfiguration>(), It.IsAny<string[]>(), It.IsAny<string>(),
                 It.IsAny<string>(), It.IsAny<string[]>()))
         .Callback<IModuleConfiguration, string[], string, string, string[]>(
             (config, paths, hostBin, extension, module) => module.Single().ShouldEqual("mono"));
     builder.LoadModules(null, "mono");
 }
コード例 #15
0
            public void ShoulLoadScriptPacksIfLoadScriptPacksIsTrue(IConsole console, TestLogProvider logProvider)
            {
                var builder = new ScriptServicesBuilder(console, logProvider);

                builder.Overrides[typeof(IScriptEngine)] = typeof(MockScriptEngine);
                builder.LoadScriptPacks();
                builder.Build();
                var runtimeServices = (RuntimeServices)builder.RuntimeServices;

                runtimeServices.InitDirectoryCatalog.ShouldBeTrue();
            }
コード例 #16
0
            public void ShouldUseTheValueTypeWhenNoInstanceIsProvided(ScriptServicesBuilder builder)
            {
                var key = typeof(ISomeOverride);

                builder.SetOverride <ISomeOverride, SomeOverride>();

                var overrides = builder.Overrides;

                overrides.ContainsKey(key).ShouldBeTrue();
                overrides[key].ShouldBeSameAs(typeof(SomeOverride));
            }
コード例 #17
0
            public void ShouldLoadScriptPacksIfScriptNameIsSet(IConsole console, TestLogProvider logProvider, IScriptEngine engine)
            {
                var builder = new ScriptServicesBuilder(console, logProvider);

                builder.Overrides[typeof(IScriptEngine)] = engine.GetType();
                builder.ScriptName("");
                builder.Build();
                var runtimeServices = (RuntimeServices)builder.RuntimeServices;

                runtimeServices.InitDirectoryCatalog.ShouldBeTrue();
            }
コード例 #18
0
            public void ShouldNotLoadScriptPacksIfLoadScriptPacksIsFalse(IConsole console, TestLogProvider logProvider, IScriptEngine engine)
            {
                var builder = new ScriptServicesBuilder(console, logProvider);

                builder.Overrides[typeof(IScriptEngine)] = engine.GetType();
                builder.LoadScriptPacks(false);
                builder.Build();
                var runtimeServices = (RuntimeServices)builder.RuntimeServices;

                runtimeServices.InitDirectoryCatalog.ShouldBeFalse();
            }
コード例 #19
0
        public ScriptCsHost()
        {
            var logger = new ConsoleOutLogger("default", Common.Logging.LogLevel.Info, true, true, false, "dd MMM yyy hh:mm:ss");

            var scriptCsBuilder = new ScriptServicesBuilder(new ScriptConsole(), logger)
                                  .LogLevel(LogLevel.Debug)
                                  .Cache(true)
                                  .Repl(false)
                                  .ScriptEngine <RoslynScriptEngine>();

            _exec = scriptCsBuilder.Build().Executor;
        }
コード例 #20
0
        private ScriptServices CreateScriptServices()
        {
            var          console = new PersonalTrainerConsole();
            ILogProvider logger  = new DefaultLogProvider();

            var builder = new ScriptServicesBuilder(console, logger);

            builder.ScriptEngine <RoslynScriptEngine>();

            builder.FileSystem <ScriptFileSystem>();
            return(builder.Build());
        }
コード例 #21
0
            public void ShouldSetTheValueUsingTheKey(ScriptServicesBuilder builder)
            {
                var someValue = new SomeOverride();
                var key       = typeof(ISomeOverride);

                builder.SetOverride <ISomeOverride, SomeOverride>(someValue);

                var overrides = builder.Overrides;

                overrides.ContainsKey(key).ShouldBeTrue();
                overrides[key].ShouldBeSameAs(someValue);
            }
コード例 #22
0
        private ScriptServices CreateScriptServices()
        {
            var console = new PersonalTrainerConsole();
            ILogProvider logger = new DefaultLogProvider();

            var builder = new ScriptServicesBuilder(console, logger);

            builder.ScriptEngine<RoslynScriptEngine>();

            builder.FileSystem<ScriptFileSystem>();
            return builder.Build();
        }
コード例 #23
0
ファイル: ScriptCsHost.cs プロジェクト: joeriks/NapkinSyntax
        public ScriptCsHost()
        {
            var logger = LogManager.GetLogger(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType);

            var scriptServicesBuilder =
                new ScriptServicesBuilder(new ScriptConsole(), logger).LogLevel(LogLevel.Info)
                .Cache(false)
                .Repl(false)
                .ScriptEngine <RoslynScriptEngine>();

            Root = scriptServicesBuilder.Build();
        }
コード例 #24
0
ファイル: ScriptCsHost.cs プロジェクト: RejectKid/MakeSharp
        public ScriptCsHost()
        {
            var logger = new ConsoleOutLogger("default", Common.Logging.LogLevel.Info, true, true, false, "dd MMM yyy hh:mm:ss");

            var scriptCsBuilder = new ScriptServicesBuilder(new ScriptConsole(), logger)
                .LogLevel(LogLevel.Debug)
                .Cache(true)
                .Repl(false)
                .ScriptEngine<RoslynScriptEngine>();

            _exec = scriptCsBuilder.Build().Executor;
        }
コード例 #25
0
        public static IScriptServicesBuilder Create(ScriptCsArgs commandArgs, string[] scriptArgs)
        {
            Guard.AgainstNullArgument("commandArgs", commandArgs);
            Guard.AgainstNullArgument("scriptArgs", scriptArgs);

            IConsole console = new ScriptConsole();
            if (!string.IsNullOrWhiteSpace(commandArgs.Output))
            {
                console = new FileConsole(commandArgs.Output, console);
            }

            var configurator = new LoggerConfigurator(commandArgs.LogLevel);
            configurator.Configure(console);
            var logger = configurator.GetLogger();
            var initializationServices = new InitializationServices(logger);
            initializationServices.GetAppDomainAssemblyResolver().Initialize();

            var scriptServicesBuilder = new ScriptServicesBuilder(console, logger, null, null, initializationServices)
                .Cache(commandArgs.Cache)
                .Debug(commandArgs.Debug)
                .LogLevel(commandArgs.LogLevel)
                .ScriptName(commandArgs.ScriptName)
                .Repl(commandArgs.Repl);

            var modules = commandArgs.Modules == null
                ? new string[0]
                : commandArgs.Modules.Split(new[] { "," }, StringSplitOptions.RemoveEmptyEntries);

            var extension = Path.GetExtension(commandArgs.ScriptName);

            if (string.IsNullOrWhiteSpace(extension) && !commandArgs.Repl)
            {
                // No extension was given, i.e we might have something like
                // "scriptcs foo" to deal with. We activate the default extension,
                // to make sure it's given to the LoadModules below.
                extension = ".csx";

                if (!string.IsNullOrWhiteSpace(commandArgs.ScriptName))
                {
                    // If the was in fact a script specified, we'll extend it
                    // with the default extension, assuming the user giving
                    // "scriptcs foo" actually meant "scriptcs foo.csx". We
                    // perform no validation here thought; let it be done by
                    // the activated command. If the file don't exist, it's
                    // up to the command to detect and report.

                    commandArgs.ScriptName += extension;
                }
            }

            return scriptServicesBuilder.LoadModules(extension, modules);
        }
コード例 #26
0
        public void Initialize()
        {
            var console     = (IConsole) new ScriptConsole();
            var logProvider = new ColoredConsoleLogProvider(LogLevel.Info, console);

            var builder = new ScriptServicesBuilder(console, logProvider);

            builder.ScriptEngine <CSharpScriptEngine>();
            var services = builder.Build();

            Executor = (ScriptExecutor)services.Executor;
            Executor.Initialize(Enumerable.Empty <string>(), Enumerable.Empty <IScriptPack>());
        }
コード例 #27
0
        static void SetEngine(ScriptServicesBuilder builder)
        {
            var useMono = Type.GetType("Mono.Runtime") != null;

            if (useMono)
            {
                builder.ScriptEngine <MonoScriptEngine> ();
            }
            else
            {
                builder.ScriptEngine <RoslynScriptEngine> ();
            }
        }
コード例 #28
0
ファイル: ScriptHost.cs プロジェクト: ryanrousseau/chuck
        private ScriptServices CreateScriptServices(bool useLogging)
        {
            var console = new ScriptConsole();
            var configurator = new LoggerConfigurator(useLogging ? LogLevel.Debug : LogLevel.Info);

            configurator.Configure(console);
            var logger = configurator.GetLogger();
            var builder = new ScriptServicesBuilder(console, logger);

            builder.ScriptEngine<RoslynScriptEngine>();

            return builder.Build();
        }
コード例 #29
0
            public void ShouldReplaceTheValueWhenKeyAlreadyExists(ScriptServicesBuilder builder)
            {
                var key         = typeof(ISomeOverride);
                var firstValue  = new SomeOverride();
                var secondValue = new SomeOverride();

                builder.SetOverride <ISomeOverride, SomeOverride>(firstValue);
                builder.SetOverride <ISomeOverride, SomeOverride>(secondValue);

                var overrides = builder.Overrides;

                overrides[key].ShouldNotBeSameAs(firstValue);
                overrides[key].ShouldBeSameAs(secondValue);
            }
コード例 #30
0
        public static void Main(string[] args)
        {
            var console = (IConsole) new ScriptConsole();
            var logProvider = new ColoredConsoleLogProvider (LogLevel.Info, console);

            var builder = new ScriptServicesBuilder (console, logProvider);

            SetEngine (builder);
            var services = builder.Build ();

            var executor = (ScriptExecutor) services.Executor;
            executor.Initialize (Enumerable.Empty<string>(), Enumerable.Empty<IScriptPack>());
            ExecuteLooseScript (executor);
            ExecuteFile (executor);
        }
コード例 #31
0
        public static void Main(string[] args)
        {
            var console     = (IConsole) new ScriptConsole();
            var logProvider = new ColoredConsoleLogProvider(LogLevel.Info, console);

            var builder = new ScriptServicesBuilder(console, logProvider);

            SetEngine(builder);
            var services = builder.Build();

            var executor = (ScriptExecutor)services.Executor;

            executor.Initialize(Enumerable.Empty <string>(), Enumerable.Empty <IScriptPack>());
            ExecuteLooseScript(executor);
            ExecuteFile(executor);
        }
コード例 #32
0
        public HttpConfiguration Build()
        {
            var logger       = LogManager.GetLogger(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType);
            var commonLogger = new CodeConfigurableLog4NetLogger(logger);

            IList <Func <string, ScriptClass> > typeStrategies = new List <Func <string, ScriptClass> >(_typeStrategies);
            var services = new ScriptServicesBuilder(new ScriptConsole(), commonLogger).
                           FilePreProcessor <WebApiFilePreProcessor>().Build();

            var preProcessor = (WebApiFilePreProcessor)services.FilePreProcessor;

            typeStrategies.Add(ControllerStategy);
            preProcessor.SetClassStrategies(typeStrategies);
            preProcessor.LoadSharedCode(Path.Combine(_scriptsPath, "Shared"));
            ProcessScripts(services);
            return(_configuration);
        }
コード例 #33
0
            public void ShouldFindAllModulesInTheFileSystem([Frozen] Mock<ITypeResolver> typeResolver, [Frozen] Mock<IModuleLoader> moduleLoader, [Frozen] Mock<IFileSystem> fileSystem, [Frozen] Mock<IInitializationServices> initializationServices, ScriptServicesBuilder builder)
            {
                typeResolver.Setup(r => r.ResolveType("Mono.Runtime")).Returns((Type)null);
                fileSystem.SetupGet(fs => fs.ModulesFolder).Returns(@"c:\modules");
                fileSystem.SetupGet(fs => fs.ModulesFolder).Returns(@"c:\current");
                fileSystem.SetupGet(fs => fs.HostBin).Returns(@"c:\hostbin");
                initializationServices.Setup(i => i.GetFileSystem()).Returns(fileSystem.Object);
                moduleLoader.Setup(
                   m =>
                       m.Load(It.IsAny<IModuleConfiguration>(), It.IsAny<string[]>(), It.IsAny<string>(),
                           It.IsAny<string>(), It.IsAny<string[]>()))
                   .Callback<IModuleConfiguration, string[], string, string, string[]>(
                       (config, paths, hostBin, extension, module) =>
                       {
                           paths.ShouldContain(@"c:\modules");
                           paths.ShouldContain(@"c:\current");
                           paths.ShouldContain(@"c:\hostbin");
                       });

            }
コード例 #34
0
ファイル: Program.cs プロジェクト: jden/scriptcs
        private static int Main(string[] args)
        {
            var console = new ScriptConsole();

            var parser = new ArgumentHandler(new ArgumentParser(console), new ConfigFileParser(console), new FileSystem());
            var arguments = parser.Parse(args);
            var commandArgs = arguments.CommandArguments;
            var scriptArgs = arguments.ScriptArguments;

            var configurator = new LoggerConfigurator(commandArgs.LogLevel);
            configurator.Configure(console);
            var logger = configurator.GetLogger();

            var scriptServicesBuilder = new ScriptServicesBuilder(console, logger)
                .InMemory(commandArgs.InMemory)
                .LogLevel(commandArgs.LogLevel)
                .ScriptName(commandArgs.ScriptName)
                .Repl(commandArgs.Repl);

            var modules = GetModuleList(commandArgs.Modules);
            var extension = Path.GetExtension(commandArgs.ScriptName);
            if (!string.IsNullOrWhiteSpace(extension))
            {
                extension = extension.Substring(1);
            }
            else if (extension == string.Empty)
            {
                console.WriteLine(string.Format("{0} is not a valid script name.", commandArgs.ScriptName));
                return 1;
            }

            scriptServicesBuilder.LoadModules(extension, modules);
            var scriptServiceRoot = scriptServicesBuilder.Build();

            var commandFactory = new CommandFactory(scriptServiceRoot);
            var command = commandFactory.CreateCommand(commandArgs, scriptArgs);

            var result = command.Execute();

            return result == CommandResult.Success ? 0 : -1;
        }
コード例 #35
0
        static void Main(string[] args)
        {
            var console     = (IConsole) new ScriptConsole();
            var logProvider = new ColoredConsoleLogProvider(LogLevel.Info, console);
            var builder     = new ScriptServicesBuilder(console, logProvider);

            builder.ScriptHostFactory <DictionaryScriptHostFactory>();
            SetEngine(builder);
            var services = builder.Build();

            var executor = (ScriptExecutor)services.Executor;

            //add the Message reference and using so we can use the Message type.
            executor.AddReferences(typeof(Message).Assembly);
            executor.ImportNamespaces("DynamicHostExample");

            executor.Initialize(Enumerable.Empty <string>(), Enumerable.Empty <IScriptPack>());

            ExecuteLooseScript(executor);
            Console.ReadLine();
        }
コード例 #36
0
ファイル: ScriptRunner.cs プロジェクト: holytshirt/mmbot
        public void Initialize()
        {
            var console = new ScriptConsole();

            var scriptServicesBuilder = new ScriptServicesBuilder(console, _logger);

            scriptServicesBuilder.LoadModules("csx", new string[0]);
            _scriptServiceRoot = scriptServicesBuilder.Build();

            _scriptServiceRoot.Executor.AddReferences(ScriptExecutor.DefaultReferences.ToArray());
            _scriptServiceRoot.Executor.ImportNamespaces(ScriptExecutor.DefaultNamespaces.Concat(new[] { "MMBot", "Newtonsoft.Json", "Newtonsoft.Json.Linq" }).ToArray());
            _scriptServiceRoot.Executor.AddReference<Robot>();
            _scriptServiceRoot.Executor.AddReference<JArray>();
            _scriptServiceRoot.Executor.AddReference<HttpResponseMessage>();
            _scriptServiceRoot.Executor.AddReference<IScriptPackContext>();

            _scriptServiceRoot.Executor.Initialize(new string[0], new IScriptPack[]
            {
                new MMBot2ScriptPackInternal(_robot),
            });
        }
コード例 #37
0
ファイル: Program.cs プロジェクト: FengZiLi/RemoteCSharpShell
        private static ScriptServices BuildScriptServices(InOutConsole console)
        {
            var logConfiguration = new LoggerConfigurator(LogLevel.Info);
            logConfiguration.Configure(console);
            var logger = logConfiguration.GetLogger();

            var initializationServices = new InitializationServices(logger);

            initializationServices.GetAppDomainAssemblyResolver().Initialize();

            var scriptServicesBuilder = new ScriptServicesBuilder(console, logger, null, null, initializationServices)
                .Repl(true);

            scriptServicesBuilder.LoadModules("");

            var scriptServices = scriptServicesBuilder.Build();

            initializationServices.GetInstallationProvider().Initialize();

            scriptServices.Repl.Initialize(Enumerable.Empty<string>(), Enumerable.Empty<IScriptPack>());
            return scriptServices;
        }
コード例 #38
0
ファイル: ScriptRunner.cs プロジェクト: nardin/mmbot
        public bool RunScriptFile(string path)
        {
            var console = new ScriptConsole();

            var scriptServicesBuilder = new ScriptServicesBuilder(console, _logger);

            scriptServicesBuilder.InMemory(true);

            scriptServicesBuilder.LoadModules("csx", new string[0]);
            var scriptServiceRoot = scriptServicesBuilder.Build();

            scriptServiceRoot.Executor.AddReferences(ScriptExecutor.DefaultReferences.ToArray());
            scriptServiceRoot.Executor.ImportNamespaces(ScriptExecutor.DefaultNamespaces.Concat(new[] { "MMBot", "Newtonsoft.Json", "Newtonsoft.Json.Linq", "System.Xml", "System.Net", "System.Net.Http" }).ToArray());
            scriptServiceRoot.Executor.AddReference<Robot>();
            scriptServiceRoot.Executor.AddReference<ILog>();
            scriptServiceRoot.Executor.AddReference<JArray>();
            scriptServiceRoot.Executor.AddReference<HttpResponseMessage>();
            scriptServiceRoot.Executor.AddReference<IScriptPackContext>();

            scriptServiceRoot.Executor.Initialize(new string[0], new IScriptPack[]
            {
                new MMBot2ScriptPackInternal(_robot),
            });

            var result = scriptServiceRoot.Executor.Execute(path);
            if (result.CompileExceptionInfo != null)
            {
                _logger.Error(result.CompileExceptionInfo.SourceException.Message);
                _logger.Debug(result.CompileExceptionInfo.SourceException);
            }

            if (result.ExecuteExceptionInfo != null)
            {
                _logger.Error(result.ExecuteExceptionInfo.SourceException);
            }

            return result.CompileExceptionInfo == null && result.ExecuteExceptionInfo == null;
        }
        public ScriptCsExtension(ScriptCsOptions options)
        {
            this.options = options;

            var console     = (IConsole) new ScriptConsole();
            var logProvider = new ColoredConsoleLogProvider(LogLevel.Info, console);

            var builder = new ScriptServicesBuilder(console, logProvider);

            //var useMono = Type.GetType("Mono.Runtime") != null;
            //if (useMono)
            //{
            //    builder.ScriptEngine<MonoScriptEngine>();
            //}
            //else {
            builder.ScriptEngine <CSharpScriptEngine>();
            //}

            scriptServices = builder.Build();

            scriptExecutor = (ScriptExecutor)scriptServices.Executor;
            scriptExecutor.Initialize(Enumerable.Empty <string>(), Enumerable.Empty <IScriptPack>());
        }
コード例 #40
0
        public static IScriptServicesBuilder Create(Config config, string[] scriptArgs)
        {
            if (scriptArgs == null)
            {
                throw new ArgumentNullException(nameof(scriptArgs));
            }

            IConsole console = new ScriptConsole();

            if (!string.IsNullOrWhiteSpace(config.OutputFile))
            {
                console = new FileConsole(config.OutputFile, console);
            }

            var logProvider            = new ColoredConsoleLogProvider(config.LogLevel, console);
            var initializationServices = new InitializationServices(logProvider);

            //todo: maybe not needed at all?
            //initializationServices.GetAppDomainAssemblyResolver().Initialize();

            // NOTE (adamralph): this is a hideous assumption about what happens inside the CommandFactory.
            // It is a result of the ScriptServicesBuilderFactory also having to know what is going to happen inside the
            // Command Factory so that it builds the builder(:-p) correctly in advance.
            // This demonstrates the technical debt that exists with the ScriptServicesBuilderFactory and CommandFactory
            // in their current form. We have a separate refactoring task raised to address this.
            var repl = config.Repl ||
                       (!config.Clean && config.PackageName == null && !config.Save && config.ScriptName == null);

            var scriptServicesBuilder = new ScriptServicesBuilder(console, logProvider, null, null, initializationServices)
                                        .Cache(config.Cache)
                                        .Debug(config.Debug)
                                        .LogLevel(config.LogLevel)
                                        .ScriptName(config.ScriptName)
                                        .Repl(repl);

            return(scriptServicesBuilder.LoadModules(Path.GetExtension(config.ScriptName) ?? ".csx", config.Modules));
        }
コード例 #41
0
        public void Configuration(IAppBuilder app)
        {
            try
            {
                OwinScriptHost.App = app;

                var services =
                    new ScriptServicesBuilder(new ScriptConsole(), LogManager.GetCurrentClassLogger()).
                        Repl(false)
                        .ScriptHostFactory<OwinScriptHostFactory>()
                        .FileSystem<HackedFileSystem>()
                        .ScriptName(ScriptFullPath).Build();

                var packs = services.ScriptPackResolver.GetPacks();
                var assemblyPaths = services.AssemblyResolver.GetAssemblyPaths(services.FileSystem.CurrentDirectory);

                services.Executor.Initialize(assemblyPaths, packs);
                services.Executor.ImportNamespaces("Owin");

                var result = services.Executor.Execute(ScriptFullPath);

                if (result.CompileExceptionInfo != null)
                    throw result.CompileExceptionInfo.SourceException;

                if (result.ExecuteExceptionInfo != null)
                    throw result.ExecuteExceptionInfo.SourceException;
            }
            catch (Exception e)
            {
                app.Run(async context =>
                {
                    await context.Response.WriteAsync(e.Message);
                    await context.Response.WriteAsync(Environment.NewLine);
                    await context.Response.WriteAsync(e.StackTrace);
                });
            }
        }
コード例 #42
0
            public void ShouldReturnTheBuilder(ScriptServicesBuilder builder)
            {
                var someValue = new SomeOverride();
                var returnedBuilder = builder.SetOverride<ISomeOverride, SomeOverride>(someValue);

                returnedBuilder.ShouldBeSameAs(builder);
            }
コード例 #43
0
ファイル: ScriptRunner.cs プロジェクト: micro-chen/mmbot
        private bool RunScriptFile(string path)
        {
            using (StartScriptProcessingSession(new ScriptSource(Path.GetFileNameWithoutExtension(path), path)))
            {
                try
                {
                    ParseScriptComments(path);
                }
                catch (Exception ex)
                {
                    _logger.Warn(string.Format("Could not parse comments: {0}", ex.Message));
                }

                var console = new ScriptConsole();

                var scriptServicesBuilder = new ScriptServicesBuilder(console, _logger);

                scriptServicesBuilder.Cache(false);

                scriptServicesBuilder.LoadModules("csx", new string[0]);
                var scriptServiceRoot = scriptServicesBuilder.Build();

                var defaultReferences = ScriptExecutor.DefaultReferences.ToArray();

                var packageReferences =
                    scriptServiceRoot.PackageAssemblyResolver.GetAssemblyNames(Environment.CurrentDirectory);

                scriptServiceRoot.Executor.AddReferences(defaultReferences.Concat(NuGetPackageAssemblyResolver.FilterAssembliesToMostRecent(packageReferences)).ToArray());
                scriptServiceRoot.Executor.ImportNamespaces(
                    ScriptExecutor.DefaultNamespaces.Concat(new[]
                {
                    "MMBot", "Newtonsoft.Json", "Newtonsoft.Json.Linq", "HtmlAgilityPack", "System.Xml", "System.Net",
                    "System.Net.Http"
                }).ToArray());
                scriptServiceRoot.Executor.AddReference <Robot>();
                scriptServiceRoot.Executor.AddReference <ILog>();
                scriptServiceRoot.Executor.AddReference <JArray>();
                scriptServiceRoot.Executor.AddReference <HtmlDocument>();
                scriptServiceRoot.Executor.AddReference <HttpResponseMessage>();
                scriptServiceRoot.Executor.AddReference <IScriptPackContext>();
                scriptServiceRoot.Executor.AddReference <OwinContext>();

                scriptServiceRoot.Executor.Initialize(new string[0], new IScriptPack[]
                {
                    new MMBot2ScriptPackInternal(_robot),
                });

                var result = scriptServiceRoot.Executor.Execute(path);
                if (result.CompileExceptionInfo != null)
                {
                    _logger.Error(result.CompileExceptionInfo.SourceException.Message);
                    _logger.Debug(result.CompileExceptionInfo.SourceException);
                }

                if (result.ExecuteExceptionInfo != null)
                {
                    _logger.Error(result.ExecuteExceptionInfo.SourceException);
                }

                return(result.CompileExceptionInfo == null && result.ExecuteExceptionInfo == null);
            }
        }
コード例 #44
0
 public TheBuildMethod()
 {
     _mockFactory.Setup(f => f.GetScriptServices()).Returns(_scriptServices);
     _builder = new ScriptServicesBuilder(_mockConsole.Object, _mockLogger.Object, _mockFactory.Object);
 }
コード例 #45
0
            public void ShouldReplaceTheValueWhenKeyAlreadyExists(ScriptServicesBuilder builder)
            {
                var key = typeof(ISomeOverride);
                var firstValue = new SomeOverride();
                var secondValue = new SomeOverride();

                builder.SetOverride<ISomeOverride, SomeOverride>(firstValue);
                builder.SetOverride<ISomeOverride, SomeOverride>(secondValue);

                var overrides = builder.Overrides;
                overrides[key].ShouldNotBeSameAs(firstValue);
                overrides[key].ShouldBeSameAs(secondValue);
            }
コード例 #46
0
            public void ShouldSetTheValueUsingTheKey(ScriptServicesBuilder builder)
            {
                var someValue = new SomeOverride();
                var key = typeof(ISomeOverride);
                builder.SetOverride<ISomeOverride, SomeOverride>(someValue);

                var overrides = builder.Overrides;
                overrides.ContainsKey(key).ShouldBeTrue();
                overrides[key].ShouldBeSameAs(someValue);
            }
コード例 #47
0
        public void Initalize(IConfiguration configuration)
        {
            _logger.LogInformation($"Detecting CSX files in '{_env.Path}'.");

            var allCsxFiles = Directory.GetFiles(_env.Path, "*.csx", SearchOption.TopDirectoryOnly);

            if (allCsxFiles.Length == 0)
            {
                _logger.LogInformation("Could not find any CSX files");
                return;
            }

            _scriptCsContext.Path = _env.Path;
            _logger.LogInformation($"Found {allCsxFiles.Length} CSX files.");

            //script name is added here as a fake one (dir path not even a real file); this is OK though -> it forces MEF initialization
            var scriptServicesBuilder = new ScriptServicesBuilder(new ScriptConsole(), LogManager.GetCurrentClassLogger()).
                                        LogLevel(LogLevel.Info).Cache(false).Repl(false).ScriptName(_env.Path).ScriptEngine <NullScriptEngine>();

            _scriptServices = scriptServicesBuilder.Build();

            var mscorlib          = MetadataReference.CreateFromAssembly(typeof(object).GetTypeInfo().Assembly);
            var systemCore        = MetadataReference.CreateFromAssembly(typeof(Enumerable).GetTypeInfo().Assembly);
            var scriptcsContracts = MetadataReference.CreateFromAssembly(typeof(IScriptHost).Assembly);

            var parseOptions = new CSharpParseOptions(LanguageVersion.CSharp6, DocumentationMode.Parse, SourceCodeKind.Script);

            var scriptPacks   = _scriptServices.ScriptPackResolver.GetPacks().ToList();
            var assemblyPaths = _scriptServices.AssemblyResolver.GetAssemblyPaths(_env.Path);

            foreach (var csxPath in allCsxFiles)
            {
                try
                {
                    _scriptCsContext.CsxFiles.Add(csxPath);
                    var processResult = _scriptServices.FilePreProcessor.ProcessFile(csxPath);

                    var references = new List <MetadataReference> {
                        mscorlib, systemCore, scriptcsContracts
                    };
                    var usings = new List <string>(ScriptExecutor.DefaultNamespaces);

                    //default references
                    ImportReferences(references, ScriptExecutor.DefaultReferences);

                    //file usings
                    usings.AddRange(processResult.Namespaces);

                    //#r references
                    ImportReferences(references, processResult.References);

                    //nuget references
                    ImportReferences(references, assemblyPaths);

                    //script packs
                    if (scriptPacks != null && scriptPacks.Any())
                    {
                        var scriptPackSession = new ScriptPackSession(scriptPacks, new string[0]);
                        scriptPackSession.InitializePacks();

                        //script pack references
                        ImportReferences(references, scriptPackSession.References);

                        //script pack usings
                        usings.AddRange(scriptPackSession.Namespaces);

                        _scriptCsContext.ScriptPacks.UnionWith(scriptPackSession.Contexts.Select(pack => pack.GetType().ToString()));
                    }

                    _scriptCsContext.References.UnionWith(references.Select(x => x.Display));
                    _scriptCsContext.Usings.UnionWith(usings);

                    var compilationOptions = new CSharpCompilationOptions(OutputKind.DynamicallyLinkedLibrary, usings: usings.Distinct());

                    var fileName = Path.GetFileName(csxPath);

                    var projectId = ProjectId.CreateNewId(Guid.NewGuid().ToString());
                    var project   = ProjectInfo.Create(projectId, VersionStamp.Create(), fileName, $"{fileName}.dll", LanguageNames.CSharp, null, null,
                                                       compilationOptions, parseOptions, null, null, references, null, null, true, typeof(IScriptHost));

                    _workspace.AddProject(project);
                    AddFile(csxPath, projectId);

                    foreach (var filePath in processResult.LoadedScripts.Distinct().Except(new[] { csxPath }))
                    {
                        _scriptCsContext.CsxFiles.Add(filePath);
                        var loadedFileName = Path.GetFileName(filePath);

                        var loadedFileProjectId         = ProjectId.CreateNewId(Guid.NewGuid().ToString());
                        var loadedFileSubmissionProject = ProjectInfo.Create(loadedFileProjectId, VersionStamp.Create(),
                                                                             $"{loadedFileName}-LoadedFrom-{fileName}", $"{loadedFileName}-LoadedFrom-{fileName}.dll", LanguageNames.CSharp, null, null,
                                                                             compilationOptions, parseOptions, null, null, references, null, null, true, typeof(IScriptHost));

                        _workspace.AddProject(loadedFileSubmissionProject);
                        AddFile(filePath, loadedFileProjectId);
                        _workspace.AddProjectReference(projectId, new ProjectReference(loadedFileProjectId));
                    }
                }
                catch (Exception ex)
                {
                    _logger.LogError($"{csxPath} will be ignored due to the following error:", ex);
                }
            }
        }
コード例 #48
0
 public void ShouldLoadTheMonoModuleWhenTheMonoModuleIsPassedInTheListOfModules([Frozen] Mock <ITypeResolver> typeResolver, [Frozen] Mock <IModuleLoader> moduleLoader, ScriptServicesBuilder builder)
 {
     typeResolver.Setup(r => r.ResolveType("Mono.Runtime")).Returns((Type)null);
     moduleLoader.Setup(
         m =>
         m.Load(It.IsAny <IModuleConfiguration>(), It.IsAny <string[]>(), It.IsAny <string>(),
                It.IsAny <string>(), It.IsAny <string[]>()))
     .Callback <IModuleConfiguration, string[], string, string, string[]>(
         (config, paths, hostBin, extension, module) => module.Single().ShouldEqual("mono"));
     builder.LoadModules(null, "mono");
 }
コード例 #49
0
ファイル: ScriptRunner.cs プロジェクト: jamessantiago/mmbot
        public bool RunScriptFile(string path)
        {
            try
            {
                ParseScriptComments(path);
            }
            catch (Exception ex)
            {
                _logger.Warn(string.Format("Could not parse comments: {0}", ex.Message));
            }

            var console = new ScriptConsole();

            var scriptServicesBuilder = new ScriptServicesBuilder(console, _logger);

            scriptServicesBuilder.InMemory(true);

            scriptServicesBuilder.LoadModules("csx", new string[0]);
            var scriptServiceRoot = scriptServicesBuilder.Build();

            var defaultReferences = ScriptExecutor.DefaultReferences.ToArray();

            var packageReferences = scriptServiceRoot.PackageAssemblyResolver.GetAssemblyNames(Environment.CurrentDirectory);

            scriptServiceRoot.Executor.AddReferences(defaultReferences.Concat(packageReferences).ToArray());
            scriptServiceRoot.Executor.ImportNamespaces(ScriptExecutor.DefaultNamespaces.Concat(new[] { "MMBot", "Newtonsoft.Json", "Newtonsoft.Json.Linq", "System.Xml", "System.Net", "System.Net.Http" }).ToArray());
            scriptServiceRoot.Executor.AddReference<Robot>();
            scriptServiceRoot.Executor.AddReference<ILog>();
            scriptServiceRoot.Executor.AddReference<JArray>();
            scriptServiceRoot.Executor.AddReference<HttpResponseMessage>();
            scriptServiceRoot.Executor.AddReference<IScriptPackContext>();
            scriptServiceRoot.Executor.AddReference<OwinContext>();

            scriptServiceRoot.Executor.Initialize(new string[0], new IScriptPack[]
            {
                new MMBot2ScriptPackInternal(_robot),
            });

            var result = scriptServiceRoot.Executor.Execute(path);
            if (result.CompileExceptionInfo != null)
            {
                _logger.Error(result.CompileExceptionInfo.SourceException.Message);
                _logger.Debug(result.CompileExceptionInfo.SourceException);
            }

            if (result.ExecuteExceptionInfo != null)
            {
                _logger.Error(result.ExecuteExceptionInfo.SourceException);
            }

            return result.CompileExceptionInfo == null && result.ExecuteExceptionInfo == null;
        }
コード例 #50
0
            public void ShouldUseTheValueTypeWhenNoInstanceIsProvided(ScriptServicesBuilder builder)
            {
                var key = typeof(ISomeOverride);
                builder.SetOverride<ISomeOverride, SomeOverride>();

                var overrides = builder.Overrides;
                overrides.ContainsKey(key).ShouldBeTrue();
                overrides[key].ShouldBeSameAs(typeof(SomeOverride));
            }
コード例 #51
0
        public void Initalize(IConfiguration configuration)
        {
            Logger.LogInformation($"Detecting CSX files in '{Env.Path}'.");

            // Nothing to do if there are no CSX files
            var allCsxFiles = Directory.GetFiles(Env.Path, "*.csx", SearchOption.AllDirectories);

            if (allCsxFiles.Length == 0)
            {
                Logger.LogInformation("Could not find any CSX files");
                return;
            }

            Context.RootPath = Env.Path;
            Logger.LogInformation($"Found {allCsxFiles.Length} CSX files.");

            // TODO: write and adapter to implement the new ScriptCs ILogProvider interface
            #pragma warning disable 0618
            //script name is added here as a fake one (dir path not even a real file); this is OK though -> it forces MEF initialization
            var baseScriptServicesBuilder = new ScriptServicesBuilder(new ScriptConsole(), LogManager.GetCurrentClassLogger())
                                            .LogLevel(LogLevel.Debug)
                                            .Cache(false)
                                            .Repl(false)
                                            .ScriptName(Env.Path)
                                            .ScriptEngine <NullScriptEngine>();

            var scriptServices = baseScriptServicesBuilder.Build();

            var scriptPacks   = scriptServices.ScriptPackResolver.GetPacks().ToList();
            var assemblyPaths = scriptServices.AssemblyResolver.GetAssemblyPaths(Env.Path);

            // Common usings and references
            Context.CommonUsings.UnionWith(ScriptExecutor.DefaultNamespaces);

            Context.CommonReferences.UnionWith(DotNetBaseReferences);
            Context.CommonReferences.UnionWith(scriptServices.MakeMetadataReferences(ScriptExecutor.DefaultReferences));     // ScriptCs defaults
            Context.CommonReferences.UnionWith(scriptServices.MakeMetadataReferences(assemblyPaths));                        // nuget references

            if (scriptPacks != null && scriptPacks.Any())
            {
                var scriptPackSession = new ScriptPackSession(scriptPacks, new string[0]);
                scriptPackSession.InitializePacks();

                //script pack references
                Context.CommonReferences.UnionWith(scriptServices.MakeMetadataReferences(scriptPackSession.References));

                //script pack usings
                Context.CommonUsings.UnionWith(scriptPackSession.Namespaces);

                Context.ScriptPacks.UnionWith(scriptPackSession.Contexts.Select(pack => pack.GetType().ToString()));
            }

            // Process each .CSX file
            foreach (var csxPath in allCsxFiles)
            {
                try
                {
                    CreateCsxProject(csxPath, baseScriptServicesBuilder);
                }
                catch (Exception ex)
                {
                    Logger.LogError($"{csxPath} will be ignored due to the following error:", ex.ToString());
                    Logger.LogError(ex.ToString());
                    Logger.LogError(ex.InnerException?.ToString() ?? "No inner exception.");
                }
            }
        }
コード例 #52
0
 public void ShouldResolveScriptServices(ScriptServices scriptServices, [Frozen] Mock <IRuntimeServices> runtimeServicesMock, ScriptServicesBuilder builder)
 {
     runtimeServicesMock.Setup(r => r.GetScriptServices()).Returns(scriptServices);
     builder.Overrides[typeof(IScriptEngine)] = null;
     builder.Build().ShouldEqual(scriptServices);
 }
コード例 #53
0
        private bool RunScriptFile(string path)
        {
            string hash;

            using (var stream = File.OpenRead(path))
            {
                hash = Encoding.UTF8.GetString(System.Security.Cryptography.MD5.Create().ComputeHash(stream));
            }

            var scriptName = Path.GetFileNameWithoutExtension(path);

            if (scriptName != null && scriptHashes.ContainsKey(scriptName) && scriptHashes[scriptName] == hash)
            {
                return(false);
            }

            using (StartScriptProcessingSession(new ScriptSource(scriptName, path)))
            {
                try
                {
                    ParseScriptComments(path);
                }
                catch (Exception ex)
                {
                    _logger.Warn(string.Format("Could not parse comments: {0}", ex.Message));
                }

                var console = new ScriptConsole();

                var scriptServicesBuilder = new ScriptServicesBuilder(console, _logger);

                scriptServicesBuilder.Cache(false);

                scriptServicesBuilder.LoadModules("csx", new string[0]);
                var scriptServiceRoot = scriptServicesBuilder.Build();

                var defaultReferences = ScriptExecutor.DefaultReferences.ToArray();

                var packageReferences =
                    scriptServiceRoot.PackageAssemblyResolver.GetAssemblyNames(Environment.CurrentDirectory);

                scriptServiceRoot.Executor.AddReferences(defaultReferences.Concat(NuGetPackageAssemblyResolver.FilterAssembliesToMostRecent(packageReferences)).ToArray());
                scriptServiceRoot.Executor.ImportNamespaces(
                    ScriptExecutor.DefaultNamespaces.Concat(new[]
                {
                    "MMBot", "Newtonsoft.Json", "Newtonsoft.Json.Linq", "HtmlAgilityPack", "System.Xml", "System.Net",
                    "System.Net.Http"
                }).ToArray());
                scriptServiceRoot.Executor.AddReference <Robot>();
                scriptServiceRoot.Executor.AddReference <ILog>();
                scriptServiceRoot.Executor.AddReference <JArray>();
                scriptServiceRoot.Executor.AddReference <HtmlDocument>();
                scriptServiceRoot.Executor.AddReference <HttpResponseMessage>();
                scriptServiceRoot.Executor.AddReference <IScriptPackContext>();
                scriptServiceRoot.Executor.AddReference <OwinContext>();

                scriptServiceRoot.Executor.Initialize(new string[0], new IScriptPack[]
                {
                    new MMBot2ScriptPackInternal(_robot),
                });

                var result = scriptServiceRoot.Executor.Execute(path);

                if (result.ExpectingClosingChar.HasValue)
                {
                    _logger.Error(string.Format("{0}: closing {1} expected", path, result.ExpectingClosingChar.Value));
                }

                if (result.CompileExceptionInfo != null)
                {
                    _logger.Error(result.CompileExceptionInfo.SourceException.Message);
                    _logger.Debug(result.CompileExceptionInfo.SourceException);
                }

                if (result.ExecuteExceptionInfo != null)
                {
                    _logger.Error(result.ExecuteExceptionInfo.SourceException);
                }

                scriptHashes[CurrentScriptSource.Name] = hash;

                return(!result.ExpectingClosingChar.HasValue && result.CompileExceptionInfo == null && result.ExecuteExceptionInfo == null);
            }
        }
コード例 #54
0
 public TheBuildMethod()
 {
     _mockFactory.Setup(f => f.GetScriptServices()).Returns(_scriptServices);
     _builder = new ScriptServicesBuilder(_mockConsole.Object, _mockLogger.Object, _mockFactory.Object);
 }
コード例 #55
0
 public void ShouldFindAllModulesInTheFileSystem([Frozen] Mock <ITypeResolver> typeResolver, [Frozen] Mock <IModuleLoader> moduleLoader, [Frozen] Mock <IFileSystem> fileSystem, [Frozen] Mock <IInitializationServices> initializationServices, ScriptServicesBuilder builder)
 {
     typeResolver.Setup(r => r.ResolveType("Mono.Runtime")).Returns((Type)null);
     fileSystem.SetupGet(fs => fs.GlobalFolder).Returns(@"c:\modules");
     fileSystem.SetupGet(fs => fs.GlobalFolder).Returns(@"c:\current");
     fileSystem.SetupGet(fs => fs.HostBin).Returns(@"c:\hostbin");
     initializationServices.Setup(i => i.GetFileSystem()).Returns(fileSystem.Object);
     moduleLoader.Setup(
         m =>
         m.Load(It.IsAny <IModuleConfiguration>(), It.IsAny <string[]>(), It.IsAny <string>(),
                It.IsAny <string>(), It.IsAny <string[]>()))
     .Callback <IModuleConfiguration, string[], string, string, string[]>(
         (config, paths, hostBin, extension, module) =>
     {
         paths.ShouldContain(@"c:\modules");
         paths.ShouldContain(@"c:\current");
         paths.ShouldContain(@"c:\hostbin");
     });
 }
コード例 #56
0
ファイル: ScriptRunner.cs プロジェクト: troygizzi/mmbot
        private bool RunScriptFile(string path)
        {
            string hash;

            using (var stream = File.OpenRead(path))
            {
                hash = Encoding.UTF8.GetString(System.Security.Cryptography.MD5.Create().ComputeHash(stream));
            }

            var scriptName = Path.GetFileNameWithoutExtension(path);

            string value;

            if (scriptName != null && scriptHashes.TryGetValue(scriptName, out value) && value == hash)
            {
                return(false);
            }

            using (StartScriptProcessingSession(new ScriptSource(scriptName, path)))
            {
                try
                {
                    ParseScriptComments(path);
                }
                catch (Exception ex)
                {
                    _logger.Warn(string.Format("Could not parse comments: {0}", ex.Message));
                }

                var console = new ScriptConsole();

                var scriptServicesBuilder = new ScriptServicesBuilder(console, _logger);

                scriptServicesBuilder.Cache(false);

                scriptServicesBuilder.LoadModules("csx");
                var scriptServiceRoot = scriptServicesBuilder.Build();

                var defaultReferences = ScriptExecutor.DefaultReferences.ToArray();

                var fileSystem = new FileSystem();
                //where clause hack using the exact same code that the hack in scriptCS sues to filter their list of assemblies in ShouldLoadAssembly in RuntimeServices.cs
                var packageReferences = scriptServiceRoot.PackageAssemblyResolver.GetAssemblyNames(Environment.CurrentDirectory).Where(fileSystem.IsPathRooted);

                scriptServiceRoot.Executor.AddReferences(defaultReferences.Concat(NuGetPackageAssemblyResolver.FilterAssembliesToMostRecent(packageReferences)).ToArray());
                scriptServiceRoot.Executor.ImportNamespaces(
                    ScriptExecutor.DefaultNamespaces.Concat(new[]
                {
                    "MMBot", "Newtonsoft.Json", "Newtonsoft.Json.Linq", "HtmlAgilityPack", "System.Xml", "System.Net",
                    "System.Net.Http"
                }).ToArray());
                scriptServiceRoot.Executor.AddReference <Robot>();
                scriptServiceRoot.Executor.AddReference <ILog>();
                scriptServiceRoot.Executor.AddReference <JArray>();
                scriptServiceRoot.Executor.AddReference <HtmlDocument>();
                scriptServiceRoot.Executor.AddReference <HttpResponseMessage>();
                scriptServiceRoot.Executor.AddReference <IScriptPackContext>();
                scriptServiceRoot.Executor.AddReference <OwinContext>();

                scriptServiceRoot.Executor.Initialize(new string[0], new IScriptPack[]
                {
                    new MMBot2ScriptPackInternal(_robot),
                });

                var result = scriptServiceRoot.Executor.Execute(path);

                if (!result.IsCompleteSubmission)
                {
                    _logger.Error(string.Format("{0}: error compiling script - {1}", path, result.CompileExceptionInfo.SourceException.Message));
                }

                if (result.CompileExceptionInfo != null)
                {
                    _logger.Error(result.CompileExceptionInfo.SourceException.Message);
                    _logger.Debug(result.CompileExceptionInfo.SourceException);
                }

                if (result.ExecuteExceptionInfo != null)
                {
                    _logger.Error(result.ExecuteExceptionInfo.SourceException);
                }

                scriptHashes[CurrentScriptSource.Name] = hash;

                return(result.IsCompleteSubmission && result.CompileExceptionInfo == null && result.ExecuteExceptionInfo == null);
            }
        }
コード例 #57
0
 public void ShouldResolveScriptServices(ScriptServices scriptServices, [Frozen] Mock<IRuntimeServices> runtimeServicesMock, ScriptServicesBuilder builder)
 {
     runtimeServicesMock.Setup(r => r.GetScriptServices()).Returns(scriptServices);
     builder.Overrides[typeof(IScriptEngine)] = null;
     builder.Build().ShouldEqual(scriptServices);
 }
コード例 #58
0
        public void Initalize(IConfiguration configuration)
        {
            _logger.LogInformation($"Detecting CSX files in '{_env.Path}'.");

            var allCsxFiles = Directory.GetFiles(_env.Path, "*.csx", SearchOption.TopDirectoryOnly);

            if (allCsxFiles.Length == 0)
            {
                _logger.LogInformation("Could not find any CSX files");
                return;
            }

            _scriptCsContext.Path = _env.Path;
            _logger.LogInformation($"Found {allCsxFiles.Length} CSX files.");

            //script name is added here as a fake one (dir path not even a real file); this is OK though -> it forces MEF initialization
            var scriptServicesBuilder = new ScriptServicesBuilder(new ScriptConsole(), LogManager.GetCurrentClassLogger()).
                LogLevel(LogLevel.Info).Cache(false).Repl(false).ScriptName(_env.Path).ScriptEngine<NullScriptEngine>();

            _scriptServices = scriptServicesBuilder.Build();

            var mscorlib = MetadataReference.CreateFromFile(typeof(object).GetTypeInfo().Assembly.Location);
            var systemCore = MetadataReference.CreateFromFile(typeof(Enumerable).GetTypeInfo().Assembly.Location);
            var scriptcsContracts = MetadataReference.CreateFromFile(typeof(IScriptHost).Assembly.Location);

            var parseOptions = new CSharpParseOptions(LanguageVersion.CSharp6, DocumentationMode.Parse, SourceCodeKind.Script);

            var scriptPacks = _scriptServices.ScriptPackResolver.GetPacks().ToList();
            var assemblyPaths = _scriptServices.AssemblyResolver.GetAssemblyPaths(_env.Path);

            foreach (var csxPath in allCsxFiles)
            {
                try
                {
                    _scriptCsContext.CsxFiles.Add(csxPath);
                    var processResult = _scriptServices.FilePreProcessor.ProcessFile(csxPath);

                    var references = new List<MetadataReference> { mscorlib, systemCore, scriptcsContracts };
                    var usings = new List<string>(ScriptExecutor.DefaultNamespaces);

                    //default references
                    ImportReferences(references, ScriptExecutor.DefaultReferences);

                    //file usings
                    usings.AddRange(processResult.Namespaces);

                    //#r references
                    ImportReferences(references, processResult.References);

                    //nuget references
                    ImportReferences(references, assemblyPaths);

                    //script packs
                    if (scriptPacks != null && scriptPacks.Any())
                    {
                        var scriptPackSession = new ScriptPackSession(scriptPacks, new string[0]);
                        scriptPackSession.InitializePacks();

                        //script pack references
                        ImportReferences(references, scriptPackSession.References);

                        //script pack usings
                        usings.AddRange(scriptPackSession.Namespaces);

                        _scriptCsContext.ScriptPacks.UnionWith(scriptPackSession.Contexts.Select(pack => pack.GetType().ToString()));
                    }

                    _scriptCsContext.References.UnionWith(references.Select(x => x.Display));
                    _scriptCsContext.Usings.UnionWith(usings);

                    var compilationOptions = new CSharpCompilationOptions(OutputKind.DynamicallyLinkedLibrary, usings: usings.Distinct());

                    var fileName = Path.GetFileName(csxPath);

                    var projectId = ProjectId.CreateNewId(Guid.NewGuid().ToString());
                    var project = ProjectInfo.Create(projectId, VersionStamp.Create(), fileName, $"{fileName}.dll", LanguageNames.CSharp, null, null,
                                                            compilationOptions, parseOptions, null, null, references, null, null, true, typeof(IScriptHost));

                    _workspace.AddProject(project);
                    AddFile(csxPath, projectId);

                    foreach (var filePath in processResult.LoadedScripts.Distinct().Except(new[] { csxPath }))
                    {
                        _scriptCsContext.CsxFiles.Add(filePath);
                        var loadedFileName = Path.GetFileName(filePath);

                        var loadedFileProjectId = ProjectId.CreateNewId(Guid.NewGuid().ToString());
                        var loadedFileSubmissionProject = ProjectInfo.Create(loadedFileProjectId, VersionStamp.Create(),
                            $"{loadedFileName}-LoadedFrom-{fileName}", $"{loadedFileName}-LoadedFrom-{fileName}.dll", LanguageNames.CSharp, null, null,
                                            compilationOptions, parseOptions, null, null, references, null, null, true, typeof(IScriptHost));

                        _workspace.AddProject(loadedFileSubmissionProject);
                        AddFile(filePath, loadedFileProjectId);
                        _workspace.AddProjectReference(projectId, new ProjectReference(loadedFileProjectId));
                    }

                }
                catch (Exception ex)
                {
                    _logger.LogError($"{csxPath} will be ignored due to the following error:", ex);
                }
            }
        }
コード例 #59
0
ファイル: ScriptRunner.cs プロジェクト: dcr25568/mmbot
        private bool RunScriptFile(string path)
        {
            string hash;
            using (var stream = File.OpenRead(path))
            {
                hash = Encoding.UTF8.GetString(System.Security.Cryptography.MD5.Create().ComputeHash(stream));
            }

            var scriptName = Path.GetFileNameWithoutExtension(path);

            string value;
            if (scriptName != null && scriptHashes.TryGetValue(scriptName, out value) && value == hash)
            {
                return false;
            }
            
            using (StartScriptProcessingSession(new ScriptSource(scriptName, path)))
            {
                try
                {
                    ParseScriptComments(path);
                }
                catch (Exception ex)
                {
                    _logger.Warn(string.Format("Could not parse comments: {0}", ex.Message));
                }

                var console = new ScriptConsole();

                var scriptServicesBuilder = new ScriptServicesBuilder(console, _logger);

                scriptServicesBuilder.Cache(false);

                scriptServicesBuilder.LoadModules("csx");
                var scriptServiceRoot = scriptServicesBuilder.Build();

                var defaultReferences = ScriptExecutor.DefaultReferences.ToArray();

                var fileSystem = new FileSystem();
                //where clause hack using the exact same code that the hack in scriptCS sues to filter their list of assemblies in ShouldLoadAssembly in RuntimeServices.cs
                var packageReferences = scriptServiceRoot.PackageAssemblyResolver.GetAssemblyNames(Environment.CurrentDirectory).Where(fileSystem.IsPathRooted);

                scriptServiceRoot.Executor.AddReferences(defaultReferences.Concat(NuGetPackageAssemblyResolver.FilterAssembliesToMostRecent(packageReferences)).ToArray());
                scriptServiceRoot.Executor.ImportNamespaces(
                    ScriptExecutor.DefaultNamespaces.Concat(new[]
                    {
                        "MMBot", "Newtonsoft.Json", "Newtonsoft.Json.Linq", "HtmlAgilityPack", "System.Xml", "System.Net",
                        "System.Net.Http"
                    }).ToArray());
                scriptServiceRoot.Executor.AddReference<Robot>();
                scriptServiceRoot.Executor.AddReference<ILog>();
                scriptServiceRoot.Executor.AddReference<JArray>();
                scriptServiceRoot.Executor.AddReference<HtmlDocument>();
                scriptServiceRoot.Executor.AddReference<HttpResponseMessage>();
                scriptServiceRoot.Executor.AddReference<IScriptPackContext>();
                scriptServiceRoot.Executor.AddReference<OwinContext>();
                
                scriptServiceRoot.Executor.Initialize(new string[0], new IScriptPack[]
                {
                    new MMBot2ScriptPackInternal(_robot),
                });

                var result = scriptServiceRoot.Executor.Execute(path);

                if (!result.IsCompleteSubmission) 
                {
                    _logger.Error(string.Format("{0}: error compiling script - {1}", path, result.CompileExceptionInfo.SourceException.Message));
                }

                if (result.CompileExceptionInfo != null)
                {
                    _logger.Error(result.CompileExceptionInfo.SourceException.Message);
                    _logger.Debug(result.CompileExceptionInfo.SourceException);
                }

                if (result.ExecuteExceptionInfo != null)
                {
                    _logger.Error(result.ExecuteExceptionInfo.SourceException);
                }

                scriptHashes[CurrentScriptSource.Name] = hash;

                return result.IsCompleteSubmission && result.CompileExceptionInfo == null && result.ExecuteExceptionInfo == null;
            }
            
        }