Пример #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;
            }
                                                                 );
        }
        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);
        }
Пример #4
0
        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;
        }
Пример #5
0
        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;
        }
 public void ShouldLoadTheMonoModuleWhenTheMonoRuntimeIsPresent([Frozen] Mock<ITypeResolver> typeResolver, [Frozen] Mock<IModuleLoader> moduleLoader, ScriptServicesBuilder builder)
 {
     typeResolver.Setup(r => r.ResolveType("Mono.Runtime")).Returns(typeof(string));
     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);
 }
Пример #7
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");
 }
        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);
        }
Пример #9
0
        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;
        }
Пример #10
0
        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),
            });
        }
Пример #11
0
        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;
        }
Пример #12
0
        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;
        }
Пример #13
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));
        }
Пример #14
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);

            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);
            }
        }
Пример #15
0
        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);
            }
        }
Пример #16
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);

            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;
            }
            
        }
Пример #17
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);
            }
        }
Пример #18
0
        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;
        }