示例#1
0
        private void Button_Click_1(object sender, RoutedEventArgs e)
        {
            result.Text = "";
            var sw   = new System.Diagnostics.Stopwatch();
            var host = new Host(result);

            var hostedScript = new HostedScriptEngine();

            hostedScript.Initialize();
            var src = hostedScript.Loader.FromString(txtCode.Text);

            Process process = null;

            try
            {
                process = hostedScript.CreateProcess(host, src);
            }
            catch (Exception exc)
            {
                result.Text = exc.Message;
                return;
            }

            result.AppendText("Script started: " + DateTime.Now.ToString() + "\n");
            sw.Start();
            var returnCode = process.Start();

            sw.Stop();
            if (returnCode != 0)
            {
                result.AppendText("\nError detected. Exit code = " + returnCode.ToString());
            }
            result.AppendText("\nScript completed: " + DateTime.Now.ToString());
            result.AppendText("\nDuration: " + sw.Elapsed.ToString());
        }
示例#2
0
        public HostedScriptEngine StartEngine()
        {
            engine = new HostedScriptEngine();
            engine.Initialize();


            engine.AttachAssembly(System.Reflection.Assembly.GetAssembly(typeof(OMyGodEco)));

            // Подключаем тестовую оболочку
            engine.AttachAssembly(System.Reflection.Assembly.GetAssembly(typeof(EngineHelpWrapper)));

            var testrunnerSource = LoadFromAssemblyResource("NUnitTests.Tests.testrunner.os");
            var testrunnerModule = engine.GetCompilerService()
                                   .Compile(testrunnerSource);

            {
                var mi = engine.GetType().GetMethod("SetGlobalEnvironment",
                                                    BindingFlags.NonPublic | BindingFlags.Public | BindingFlags.InvokeMethod | BindingFlags.Instance);
                mi.Invoke(engine, new object[] { this, testrunnerSource });
            }

            engine.LoadUserScript(new ScriptEngine.UserAddedScript()
            {
                Type   = ScriptEngine.UserAddedScriptType.Class,
                Image  = testrunnerModule,
                Symbol = "TestRunner"
            });

            var testRunner = AttachedScriptsFactory.ScriptFactory("TestRunner", new IValue[] { });

            TestRunner = ValueFactory.Create(testRunner);

            return(engine);
        }
        public override int Execute()
        {
            var hostedScript = new HostedScriptEngine
            {
                CustomConfig = ScriptFileHelper.CustomConfigPath(_path)
            };

            hostedScript.Initialize();
            ScriptFileHelper.OnBeforeScriptRead(hostedScript);
            var source   = hostedScript.Loader.FromFile(_path);
            var compiler = hostedScript.GetCompilerService();

            hostedScript.SetGlobalEnvironment(new DoNothingHost(), source);
            var writer = new ModuleWriter(compiler);

            try
            {
                writer.Write(Console.Out, source);
            }
            catch (ScriptException e)
            {
                Output.WriteLine(e.Message);
                return(1);
            }

            return(0);
        }
示例#4
0
        public override int Execute()
        {
            var hostedScript = new HostedScriptEngine();

            hostedScript.CustomConfig = ScriptFileHelper.CustomConfigPath(_path);
            hostedScript.Initialize();
            ScriptFileHelper.OnBeforeScriptRead(hostedScript);
            var source = hostedScript.Loader.FromFile(_path);

            try
            {
                if (_envFile != null)
                {
                    var envCompiler = hostedScript.GetCompilerService();
                    var envSrc      = hostedScript.Loader.FromFile(_envFile);
                    envCompiler.CreateModule(envSrc);
                }
                var compiler = hostedScript.GetCompilerService();
                compiler.CreateModule(source);
            }
            catch (ScriptException e)
            {
                Output.WriteLine(e.Message);
                return(1);
            }

            Output.WriteLine("No errors.");

            return(0);
        }
示例#5
0
        public override int Execute()
        {
            Console.WriteLine("Make started...");
            using (var exeStream = Assembly.GetExecutingAssembly().GetManifestResourceStream("oscript.StandaloneRunner.exe"))
                using (var output = new FileStream(_exePath, FileMode.Create))
                {
                    exeStream.CopyTo(output);

                    int offset = (int)output.Length;

                    var engine = new HostedScriptEngine();
                    engine.Initialize();
                    var source    = engine.Loader.FromFile(_codePath);
                    var formatter = new System.Runtime.Serialization.Formatters.Binary.BinaryFormatter();
                    var persistor = new ScriptEngine.Compiler.ModulePersistor(formatter);
                    var compiler  = engine.GetCompilerService();
                    persistor.Save(compiler.CreateModule(source), output);

                    byte[] signature = new byte[4]
                    {
                        0x4f, 0x53, 0x4d, 0x44
                    };
                    output.Write(signature, 0, signature.Length);
                    using (var bw = new BinaryWriter(output))
                    {
                        bw.Write(offset);
                    }
                }
            Console.WriteLine("Make completed");
            return(0);
        }
示例#6
0
        private int RunCGIMode(string scriptFile)
        {
            var engine = new HostedScriptEngine();

            engine.AttachAssembly(System.Reflection.Assembly.GetExecutingAssembly());

            var request = new WebRequestContext();

            engine.InjectGlobalProperty("ВебЗапрос", request, true);
            engine.InjectObject(this, false);
            engine.Initialize();

            var source = engine.Loader.FromFile(scriptFile);

            Process process;

            try
            {
                process = engine.CreateProcess(this, source);
            }
            catch (Exception e)
            {
                ShowExceptionInfo(e);
                return(1);
            }

            int exitCode = process.Start();

            if (!_isContentEchoed)
            {
                Echo("");
            }

            return(exitCode);
        }
示例#7
0
        public HostedScriptEngine StartEngine()
        {
            engine = new HostedScriptEngine();
            engine.Initialize();

            engine.AttachAssembly(System.Reflection.Assembly.GetAssembly(typeof(TinyXdto.XdtoFactory)));
            engine.AttachAssembly(System.Reflection.Assembly.GetAssembly(typeof(OneScript.Soap.Definitions)));

            // Подключаем тестовую оболочку
            engine.AttachAssembly(System.Reflection.Assembly.GetAssembly(typeof(EngineHelpWrapper)));

            var testrunnerSource = LoadFromAssemblyResource("NUnitTests.Tests.testrunner.os");
            var moduleByteCode   = engine.GetCompilerService().Compile(testrunnerSource);
            var testrunnerModule = engine.EngineInstance.LoadModuleImage(moduleByteCode);

            var testRunner = new UserScriptContextInstance(testrunnerModule);

            testRunner.AddProperty("ЭтотОбъект", "ThisObject", testRunner);
            testRunner.InitOwnData();
            testRunner.Initialize();

            TestRunner = ValueFactory.Create(testRunner);

            var testRootDir = ValueFactory.Create(TestContext.CurrentContext.TestDirectory);

            engine.InjectGlobalProperty("TestDataDirectory", testRootDir, readOnly: true);
            engine.InjectGlobalProperty("КаталогТестовыхДанных", testRootDir, readOnly: true);

            return(engine);
        }
示例#8
0
        public HostedScriptEngine StartEngine()
        {
            engine = new HostedScriptEngine();
            engine.Initialize();

            // Тут можно указать любой класс из компоненты
            engine.AttachAssembly(System.Reflection.Assembly.GetAssembly(typeof(oscriptFtp.FtpConnection)));

            // Подключаем тестовую оболочку
            engine.AttachAssembly(System.Reflection.Assembly.GetAssembly(typeof(EngineHelpWrapper)));

            var testrunnerSource = LoadFromAssemblyResource("NUnitTests.Tests.testrunner.os");
            var testrunnerModule = engine.GetCompilerService().CreateModule(testrunnerSource);

            engine.LoadUserScript(new ScriptEngine.UserAddedScript()
            {
                Type   = ScriptEngine.UserAddedScriptType.Class,
                Module = testrunnerModule,
                Symbol = "TestRunner"
            });

            var testRunner = AttachedScriptsFactory.ScriptFactory("TestRunner", new IValue[] { });

            TestRunner = ValueFactory.Create(testRunner);

            return(engine);
        }
示例#9
0
        public HostedScriptEngine StartEngine()
        {
            engine = new HostedScriptEngine();
            engine.Initialize();

            // Тут можно указать любой класс из компоненты
            engine.AttachAssembly(System.Reflection.Assembly.GetAssembly(typeof(Bracker.BrackerWriterImpl)));

            // Если проектов компонент несколько, то надо взять по классу из каждой из них
            // engine.AttachAssembly(System.Reflection.Assembly.GetAssembly(typeof(oscriptcomponent_2.MyClass_2)));
            // engine.AttachAssembly(System.Reflection.Assembly.GetAssembly(typeof(oscriptcomponent_3.MyClass_3)));

            // Подключаем тестовую оболочку
            engine.AttachAssembly(System.Reflection.Assembly.GetAssembly(typeof(EngineHelpWrapper)));

            var testrunnerSource = LoadFromAssemblyResource("NUnitTests.Tests.testrunner.os");
            var testrunnerModule = engine.GetCompilerService().CreateModule(testrunnerSource);

            engine.LoadUserScript(new ScriptEngine.UserAddedScript()
            {
                Type   = ScriptEngine.UserAddedScriptType.Class,
                Module = testrunnerModule,
                Symbol = "TestRunner"
            });

            var testRunner = AttachedScriptsFactory.ScriptFactory("TestRunner", new IValue[] { });

            TestRunner = ValueFactory.Create(testRunner);

            return(engine);
        }
示例#10
0
        private void Button_Click(object sender, RoutedEventArgs e)
        {
            var hostedScript = new HostedScriptEngine();

            hostedScript.CustomConfig = CustomConfigPath(_currentDocPath);
            hostedScript.Initialize();
            var src = hostedScript.Loader.FromString(txtCode.Text);

            using (var writer = new StringWriter())
            {
                try
                {
                    var cs = hostedScript.GetCompilerService();
                    if (GenerateExtraCode.IsChecked)
                    {
                        cs.ProduceExtraCode |= CodeGenerationFlags.CodeStatistics;
                    }
                    if (GenerateDebugCode.IsChecked)
                    {
                        cs.ProduceExtraCode |= CodeGenerationFlags.DebugCode;
                    }

                    var moduleWriter = new ScriptEngine.Compiler.ModuleWriter(cs);
                    moduleWriter.Write(writer, src);
                    result.Text = writer.GetStringBuilder().ToString();
                }
                catch (Exception exc)
                {
                    result.Text = exc.Message;
                }
            }
        }
示例#11
0
        public HostedScriptEngine StartEngine()
        {
            engine = new HostedScriptEngine();
            engine.Initialize();

            commandLineArgs = new string[] { };

            return(engine);
        }
示例#12
0
        public static HostedScriptEngine StartEngine()
        {
            var engine = new HostedScriptEngine();

            engine.Initialize();

            engine.AttachAssembly(System.Reflection.Assembly.GetAssembly(typeof(Bracker.BrackerWriterImpl)));

            return(engine);
        }
示例#13
0
        private void CreateDump(Stream output)
        {
            var offset = (int)output.Length;

            var engine = new HostedScriptEngine
            {
                CustomConfig = ScriptFileHelper.CustomConfigPath(_codePath)
            };

            engine.Initialize();
            ScriptFileHelper.OnBeforeScriptRead(engine);
            var source   = engine.Loader.FromFile(_codePath);
            var compiler = engine.GetCompilerService();

            engine.SetGlobalEnvironment(new DoNothingHost(), source);
            var entry = compiler.Compile(source);

            var embeddedContext = engine.GetUserAddedScripts();
            var templates       = GlobalsManager.GetGlobalContext <TemplateStorage>();

            var dump = new ApplicationDump();

            dump.Scripts = new UserAddedScript[]
            {
                new UserAddedScript()
                {
                    Image  = entry,
                    Symbol = "$entry",
                    Type   = UserAddedScriptType.Module
                }
            }.Concat(embeddedContext)
            .ToArray();
            dump.Resources = templates.GetTemplates()
                             .Select(SerializeTemplate)
                             .ToArray();

            using (var bw = new BinaryWriter(output))
            {
                var serializer = new BinaryFormatter();
                serializer.Serialize(output, dump);

                var signature = new byte[]
                {
                    0x4f,
                    0x53,
                    0x4d,
                    0x44
                };
                output.Write(signature, 0, signature.Length);

                bw.Write(offset);

                OutputToFile(output);
            }
        }
示例#14
0
        private void CreateExe()
        {
            using (var exeStream = Assembly.GetExecutingAssembly().GetManifestResourceStream("oscript.StandaloneRunner.exe"))
                using (var output = new MemoryStream())
                {
                    exeStream?.CopyTo(output);

                    var offset = (int)output.Length;

                    var engine = new HostedScriptEngine
                    {
                        CustomConfig = ScriptFileHelper.CustomConfigPath(_codePath)
                    };
                    engine.Initialize();
                    ScriptFileHelper.OnBeforeScriptRead(engine);
                    var source   = engine.Loader.FromFile(_codePath);
                    var compiler = engine.GetCompilerService();
                    engine.SetGlobalEnvironment(new DoNothingHost(), source);
                    var entry = compiler.CreateModule(source);

                    var embeddedContext = engine.GetUserAddedScripts();

                    using (var bw = new BinaryWriter(output))
                    {
                        var userAddedScripts = embeddedContext as IList <UserAddedScript> ?? embeddedContext.ToList();
                        bw.Write(userAddedScripts.Count + 1);

                        var persistor = new ModulePersistor();
                        persistor.Save(new UserAddedScript
                        {
                            Type   = UserAddedScriptType.Module,
                            Symbol = "$entry",
                            Module = entry
                        }, output);

                        foreach (var item in userAddedScripts)
                        {
                            persistor.Save(item, output);
                        }

                        var signature = new byte[]
                        {
                            0x4f,
                            0x53,
                            0x4d,
                            0x44
                        };
                        output.Write(signature, 0, signature.Length);

                        bw.Write(offset);
                        OutputToFile(output);
                    }
                }
        }
示例#15
0
        public override int Execute()
        {
            var hostedScript = new HostedScriptEngine();

            hostedScript.Initialize();
            var source   = hostedScript.Loader.FromFile(_path);
            var compiler = hostedScript.GetCompilerService();
            var writer   = new ScriptEngine.Compiler.ModuleWriter(compiler);

            writer.Write(Console.Out, source);
            return(0);
        }
示例#16
0
        static void Main(string[] args)
        {
            var host   = new ApplicationHost();
            var source = args[0];

            host.CommandLineArguments = args.Skip(1).ToArray();
            var Engine = new HostedScriptEngine();

            Engine.Initialize();
            //Engine.Loader.ReaderEncoding = Encoding.GetEncoding("utf-8");
            var process = Engine.CreateProcess(host, Engine.Loader.FromFile(source));

            process.Start();
        }
示例#17
0
        private void CreateDump(Stream output)
        {
            var offset = (int)output.Length;

            var engine = new HostedScriptEngine
            {
                CustomConfig = ScriptFileHelper.CustomConfigPath(_codePath)
            };

            engine.Initialize();
            ScriptFileHelper.OnBeforeScriptRead(engine);
            var source   = engine.Loader.FromFile(_codePath);
            var compiler = engine.GetCompilerService();

            engine.SetGlobalEnvironment(new DoNothingHost(), source);
            var entry = compiler.Compile(source);

            var embeddedContext = engine.GetUserAddedScripts();

            using (var bw = new BinaryWriter(output))
            {
                var userAddedScripts = embeddedContext as IList <UserAddedScript> ?? embeddedContext.ToList();
                bw.Write(userAddedScripts.Count + 1);

                var persistor = new ModulePersistor();
                persistor.Save(new UserAddedScript
                {
                    Type   = UserAddedScriptType.Module,
                    Symbol = "$entry",
                    Image  = entry
                }, output);

                foreach (var item in userAddedScripts)
                {
                    persistor.Save(item, output);
                }

                var signature = new byte[]
                {
                    0x4f,
                    0x53,
                    0x4d,
                    0x44
                };
                output.Write(signature, 0, signature.Length);

                bw.Write(offset);
                OutputToFile(output);
            }
        }
        public override int Execute()
        {
            Output.WriteLine("Make started...");
            using (var exeStream = Assembly.GetExecutingAssembly().GetManifestResourceStream("oscript.StandaloneRunner.exe"))
                using (var output = new FileStream(_exePath, FileMode.Create))
                {
                    exeStream.CopyTo(output);

                    int offset = (int)output.Length;

                    var engine = new HostedScriptEngine();
                    engine.CustomConfig = ScriptFileHelper.CustomConfigPath(_codePath);
                    engine.Initialize();
                    ScriptFileHelper.OnBeforeScriptRead(engine);
                    var source   = engine.Loader.FromFile(_codePath);
                    var compiler = engine.GetCompilerService();
                    var entry    = compiler.CreateModule(source);

                    var embeddedContext = engine.GetUserAddedScripts();

                    using (var bw = new BinaryWriter(output))
                    {
                        bw.Write(embeddedContext.Count() + 1);

                        var formatter = new System.Runtime.Serialization.Formatters.Binary.BinaryFormatter();
                        var persistor = new ScriptEngine.Compiler.ModulePersistor(formatter);
                        persistor.Save(new UserAddedScript()
                        {
                            Type   = UserAddedScriptType.Module,
                            Symbol = "$entry",
                            Module = entry
                        }, output);

                        foreach (var item in embeddedContext)
                        {
                            persistor.Save(item, output);
                        }

                        byte[] signature = new byte[4]
                        {
                            0x4f, 0x53, 0x4d, 0x44
                        };
                        output.Write(signature, 0, signature.Length);

                        bw.Write(offset);
                    }
                }
            Output.WriteLine("Make completed");
            return(0);
        }
示例#19
0
        public override int Execute()
        {
            if (!System.IO.File.Exists(_path))
            {
                throw new System.IO.FileNotFoundException("Script file is not found", _path);
            }

            var hostedScript = new HostedScriptEngine();

            hostedScript.Initialize();
            var source  = hostedScript.Loader.FromFile(_path);
            var process = hostedScript.CreateProcess(this, source);

            return(process.Start());
        }
示例#20
0
 public ASPNETHandler()
 {
     _hostedScript = new HostedScriptEngine();
     _hostedScript.Initialize();
     _hostedScript.AttachAssembly(System.Reflection.Assembly.GetExecutingAssembly());
     // Аттачим доп сборки. По идее должны лежать в Bin
     foreach (System.Reflection.Assembly assembly in _assembliesForAttaching)
     {
         try
         {
             _hostedScript.AttachAssembly(assembly);
         }
         catch { /*что-то не так, ничего не делаем*/ }
     }
 }
示例#21
0
        private static void CreateWorld()
        {
            _world = new HostedScriptEngine();
            var thisAsm = System.Reflection.Assembly.GetExecutingAssembly();
            var asmDir  = Path.GetDirectoryName(thisAsm.Location);
            var libDir  = Path.Combine(asmDir, "lib");

            if (Directory.Exists(libDir))
            {
                _world.InitExternalLibraries(libDir, new string[0]);
            }

            _world.SetGlobalEnvironment(new ConsoleHost(), null);
            _world.AttachAssembly(thisAsm);
            _world.Initialize();
        }
示例#22
0
        public override int Execute()
        {
            var engine = new HostedScriptEngine
            {
                CustomConfig = ScriptFileHelper.CustomConfigPath(_path)
            };

            engine.Initialize();
            ScriptFileHelper.OnBeforeScriptRead(engine);
            var source   = engine.Loader.FromFile(_path);
            var compiler = engine.GetCompilerService();

            engine.SetGlobalEnvironment(new DoNothingHost(), source);
            var entry           = compiler.Compile(source);
            var embeddedContext = engine.GetExternalLibraries();

            var serializer = new JsonSerializer();
            var sb         = new StringBuilder();

            using (var textWriter = new StringWriter(sb))
            {
                var writer = new JsonTextWriter(textWriter);
                writer.WriteStartArray();

                WriteImage(new UserAddedScript
                {
                    Type   = UserAddedScriptType.Module,
                    Symbol = "$entry",
                    Image  = entry
                }, writer, serializer);

                foreach (var item in embeddedContext)
                {
                    item.Classes.ForEach(x => WriteImage(x, writer, serializer));
                    item.Modules.ForEach(x => WriteImage(x, writer, serializer));
                }

                writer.WriteEndArray();
            }

            string result = sb.ToString();

            Output.WriteLine(result);

            return(0);
        }
示例#23
0
        public int Run()
        {
            try
            {
                ScriptModuleHandle module;
                var engine = new HostedScriptEngine();
                engine.Initialize();

                using (Stream codeStream = LocateCode())
                    using (var binReader = new BinaryReader(codeStream))
                    {
                        int modulesCount;
                        modulesCount = binReader.ReadInt32();


                        var formatter = new BinaryFormatter();
                        var reader    = new ScriptEngine.Compiler.ModulePersistor(formatter);

                        var entry = reader.Read(codeStream);
                        --modulesCount;

                        while (modulesCount-- > 0)
                        {
                            var userScript = reader.Read(codeStream);
                            engine.LoadUserScript(userScript);
                        }

                        module = entry.Module;
                    }

                var src     = new BinaryCodeSource(module);
                var process = engine.CreateProcess(this, module, src);

                return(process.Start());
            }
            catch (ScriptInterruptionException e)
            {
                return(e.ExitCode);
            }
            catch (Exception e)
            {
                this.ShowExceptionInfo(e);
                return(1);
            }
        }
示例#24
0
        public override int Execute()
        {
            var hostedScript = new HostedScriptEngine
            {
                CustomConfig = ScriptFileHelper.CustomConfigPath(_path)
            };

            hostedScript.Initialize();

            if (_isCgi)
            {
                var request = ValueFactory.Create();
                hostedScript.InjectGlobalProperty("ВебЗапрос", request, true);
                hostedScript.InjectGlobalProperty("WebRequest", request, true);
            }

            ScriptFileHelper.OnBeforeScriptRead(hostedScript);
            var source = hostedScript.Loader.FromFile(_path);

            hostedScript.SetGlobalEnvironment(new DoNothingHost(), source);

            try
            {
                if (_envFile != null)
                {
                    var envCompiler = hostedScript.GetCompilerService();
                    var envSrc      = hostedScript.Loader.FromFile(_envFile);
                    envCompiler.Compile(envSrc);
                }
                var compiler = hostedScript.GetCompilerService();
                compiler.Compile(source);
            }
            catch (ScriptException e)
            {
                Output.WriteLine(e.Message);
                return(1);
            }

            Output.WriteLine("No errors.");

            return(0);
        }
示例#25
0
        private void Button_Click(object sender, RoutedEventArgs e)
        {
            var hostedScript = new HostedScriptEngine();

            hostedScript.Initialize();
            var src = hostedScript.Loader.FromString(txtCode.Text);

            using (var writer = new StringWriter())
            {
                try
                {
                    var moduleWriter = new ScriptEngine.Compiler.ModuleWriter(hostedScript.GetCompilerService());
                    moduleWriter.Write(writer, src);
                    result.Text = writer.GetStringBuilder().ToString();
                }
                catch (Exception exc)
                {
                    result.Text = exc.Message;
                }
            }
        }
示例#26
0
        public Process CreateProcess(Stream sourceStream, IHostApplication host)
        {
            var appDump         = DeserializeAppDump(sourceStream);
            var engine          = new HostedScriptEngine();
            var src             = new BinaryCodeSource();
            var templateStorage = new TemplateStorage(new StandaloneTemplateFactory());

            engine.SetGlobalEnvironment(host, src);
            engine.InitializationCallback = (e, env) =>
            {
                e.Environment.InjectObject(templateStorage);
                GlobalsManager.RegisterInstance(templateStorage);
            };
            engine.Initialize();

            LoadResources(templateStorage, appDump.Resources);
            LoadScripts(engine, appDump.Scripts);

            var process = engine.CreateProcess(host, appDump.Scripts[0].Image, src);

            return(process);
        }
        public HostedScriptEngine StartEngine()
        {
            engine = new HostedScriptEngine();
            engine.Initialize();

            // Тут можно указать любой класс из компоненты
            engine.AttachAssembly(System.Reflection.Assembly.GetAssembly(typeof(oscriptcomponent.MyClass)));

            // Если проектов компонент несколько, то надо взять по классу из каждой из них
            // engine.AttachAssembly(System.Reflection.Assembly.GetAssembly(typeof(oscriptcomponent_2.MyClass_2)));
            // engine.AttachAssembly(System.Reflection.Assembly.GetAssembly(typeof(oscriptcomponent_3.MyClass_3)));

            // Подключаем тестовую оболочку
            engine.AttachAssembly(System.Reflection.Assembly.GetAssembly(typeof(EngineHelpWrapper)));

            var testrunnerSource = LoadFromAssemblyResource("NUnitTests.Tests.testrunner.os");
            var testrunnerModule = engine.GetCompilerService().Compile(testrunnerSource);

            {
                var mi = engine.GetType().GetMethod("SetGlobalEnvironment",
                                                    BindingFlags.NonPublic | BindingFlags.Public | BindingFlags.InvokeMethod | BindingFlags.Instance);
                mi.Invoke(engine, new object[] { this, testrunnerSource });
            }

            engine.LoadUserScript(new ScriptEngine.UserAddedScript()
            {
                Type   = ScriptEngine.UserAddedScriptType.Class,
                Image  = testrunnerModule,
                Symbol = "TestRunner"
            });

            var testRunner = AttachedScriptsFactory.ScriptFactory("TestRunner", new IValue[] { });

            TestRunner = ValueFactory.Create(testRunner);

            return(engine);
        }
示例#28
0
        public int Run()
        {
            if (_sourceStream == null && CommandLineArguments != null && CommandLineArguments.Length > 1)
            {
                var firstArg = CommandLineArguments[0];
                if (firstArg == "-loadDump")
                {
                    var path = CommandLineArguments[1];
                    CommandLineArguments = CommandLineArguments.Skip(2).ToArray();
                    using (var dumpStream = new FileStream(path, FileMode.Open))
                    {
                        _sourceStream = GetCodeStream(dumpStream);
                    }

                    return(Run()); //ну да, говнокод и лапша, время жмет
                }
            }

            if (_sourceStream == null)
            {
                _sourceStream = LocateCode();
            }

            var engine = new HostedScriptEngine();
            var src    = new BinaryCodeSource();

            engine.SetGlobalEnvironment(this, src);

            try
            {
                var templateStorage = new TemplateStorage(new StandaloneTemplateFactory());
                engine.InitializationCallback = (e, env) =>
                {
                    e.Environment.InjectObject(templateStorage);
                    GlobalsManager.RegisterInstance(templateStorage);
                };

                engine.Initialize();

                var serializer = new BinaryFormatter();
                var appDump    = (ApplicationDump)serializer.Deserialize(_sourceStream);
                foreach (var resource in appDump.Resources)
                {
                    templateStorage.RegisterTemplate(resource.ResourceName, DeserializeTemplate(resource.Data));
                }
                var module = appDump.Scripts[0].Image;
                for (int i = 1; i < appDump.Scripts.Length; i++)
                {
                    engine.LoadUserScript(appDump.Scripts[i]);
                }

                var process = engine.CreateProcess(this, module, src);

                return(process.Start());
            }
            catch (ScriptInterruptionException e)
            {
                return(e.ExitCode);
            }
            catch (Exception e)
            {
                ShowExceptionInfo(e);
                return(1);
            }
        }
示例#29
0
        public ASPNETHandler()
        {
            System.Collections.Specialized.NameValueCollection appSettings = System.Web.Configuration.WebConfigurationManager.AppSettings;

            // Инициализируем логгирование, если надо
            TextWriter logWriter = OpenLog(appSettings);

            WriteToLog(logWriter, "Start loading.");

            try
            {
                _hostedScript = new HostedScriptEngine();
                // метод настраивает внутренние переменные у SystemGlobalContext
                if (appSettings["enableEcho"] == "true")
                {
                    _hostedScript.SetGlobalEnvironment(new ASPNetApplicationHost(), new AspEntryScriptSrc(appSettings["startupScript"] ?? HttpContext.Current.Server.MapPath("~/web.config")));
                }
                else
                {
                    _hostedScript.SetGlobalEnvironment(new AspNetNullApplicationHost(), new AspNetNullEntryScriptSrc());
                }

                _hostedScript.Initialize();


                // Размещаем oscript.cfg вместе с web.config. Так наверное привычнее
                _hostedScript.CustomConfig = appSettings["configFilePath"] ?? HttpContext.Current.Server.MapPath("~/oscript.cfg");
                _hostedScript.AttachAssembly(System.Reflection.Assembly.GetExecutingAssembly());
                // Аттачим доп сборки. По идее должны лежать в Bin
                foreach (System.Reflection.Assembly assembly in _assembliesForAttaching)
                {
                    try
                    {
                        _hostedScript.AttachAssembly(assembly);
                    }
                    catch (Exception ex)
                    {
                        // Возникла проблема при аттаче сборки
                        WriteToLog(logWriter, "Assembly attaching error: " + ex.Message);
                        if (appSettings["handlerLoadingPolicy"] == "strict")
                        {
                            throw;
                        }
                    }
                }

                //Загружаем библиотечные скрипты aka общие модули
                string libPath = appSettings["commonModulesPath"];

                if (libPath != null)
                {
                    libPath = HttpContext.Current.Server.MapPath(libPath);

                    string[] files = System.IO.Directory.GetFiles(libPath, "*.os");


                    foreach (string filePathName in files)
                    {
                        _hostedScript.InjectGlobalProperty(System.IO.Path.GetFileNameWithoutExtension(filePathName), ValueFactory.Create(), true);
                    }

                    foreach (string filePathName in files)
                    {
                        try
                        {
                            ICodeSource src = _hostedScript.Loader.FromFile(filePathName);

                            var compilerService = _hostedScript.GetCompilerService();
                            var module          = compilerService.Compile(src);
                            var loaded          = _hostedScript.EngineInstance.LoadModuleImage(module);
                            var instance        = (IValue)_hostedScript.EngineInstance.NewObject(loaded);
                            _hostedScript.EngineInstance.Environment.SetGlobalProperty(System.IO.Path.GetFileNameWithoutExtension(filePathName), instance);
                        }
                        catch (Exception ex)
                        {
                            // Возникла проблема при загрузке файла os, логгируем, если логгирование включено
                            WriteToLog(logWriter, "Error loading " + System.IO.Path.GetFileNameWithoutExtension(filePathName) + " : " + ex.Message);
                            if (appSettings["handlerLoadingPolicy"] == "strict")
                            {
                                throw;
                            }
                        }
                    }
                }

                _hostedScript.EngineInstance.Environment.LoadMemory(MachineInstance.Current);
            }
            catch (Exception ex)
            {
                // Возникла проблема при инициализации хэндлера
                WriteToLog(logWriter, ex.Message);

                if (appSettings["handlerLoadingPolicy"] == "strict")
                {
                    throw; // Must fail!
                }
            }
            finally
            {
                WriteToLog(logWriter, "End loading.");
                CloseLog(logWriter);
            }
        }
示例#30
0
        public int Run()
        {
            if (_sourceStream == null && CommandLineArguments != null && CommandLineArguments.Length > 1)
            {
                var firstArg = CommandLineArguments[0];
                if (firstArg == "-loadDump")
                {
                    var path = CommandLineArguments[1];
                    CommandLineArguments = CommandLineArguments.Skip(2).ToArray();
                    using (var dumpStream = new FileStream(path, FileMode.Open))
                    {
                        _sourceStream = GetCodeStream(dumpStream);
                    }

                    Run(); //ну да, говнокод и лапша, время жмет
                }
            }

            if (_sourceStream == null)
            {
                _sourceStream = LocateCode();
            }

            var engine = new HostedScriptEngine();
            var src    = new BinaryCodeSource();

            engine.SetGlobalEnvironment(this, src);

            try
            {
                ModuleImage module;
                engine.Initialize();

                using (var binReader = new BinaryReader(_sourceStream))
                {
                    var modulesCount = binReader.ReadInt32();

                    var reader = new ModulePersistor();

                    var entry = reader.Read(_sourceStream);
                    --modulesCount;

                    while (modulesCount-- > 0)
                    {
                        var userScript = reader.Read(_sourceStream);
                        engine.LoadUserScript(userScript);
                    }

                    module = entry.Image;
                }

                var process = engine.CreateProcess(this, module, src);

                return(process.Start());
            }
            catch (ScriptInterruptionException e)
            {
                return(e.ExitCode);
            }
            catch (Exception e)
            {
                ShowExceptionInfo(e);
                return(1);
            }
        }