Beispiel #1
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);
        }
        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);
        }
Beispiel #3
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);
        }
Beispiel #4
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);
        }
Beispiel #5
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);
        }
Beispiel #6
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);
        }
Beispiel #7
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);
        }
Beispiel #8
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;
                }
            }
        }
Beispiel #9
0
        private LoadedModule LoadByteCode(string filePath)
        {
            var code     = _hostedScript.EngineInstance.Loader.FromFile(filePath);
            var compiler = _hostedScript.GetCompilerService();
            var byteCode = compiler.Compile(code);
            var module   = _hostedScript.EngineInstance.LoadModuleImage(byteCode);

            return(module);
        }
Beispiel #10
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);
            }
        }
Beispiel #11
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);
        }
Beispiel #12
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);
                    }
                }
        }
Beispiel #13
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);
        }
        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);
        }
Beispiel #16
0
        private int RunTestScript(ICodeSource source, string resourceName)
        {
            var module = engine.GetCompilerService().CreateModule(source);

            engine.LoadUserScript(new ScriptEngine.UserAddedScript()
            {
                Type   = ScriptEngine.UserAddedScriptType.Class,
                Module = module,
                Symbol = resourceName
            });

            var process = engine.CreateProcess(this, source);

            return(process.Start());
        }
Beispiel #17
0
 public void AddDataProcessorManagers(System.Collections.Hashtable managerFiles)
 {
     ScriptEngine.HostedScript.Library.StructureImpl dataProcessors = new ScriptEngine.HostedScript.Library.StructureImpl();
     // Добавляем обработки, написанные на OneScript
     foreach (System.Collections.DictionaryEntry cm in managerFiles)
     {
         ICodeSource src             = _hostedScript.Loader.FromString(InsertMandatoryMethods((string)cm.Value, (string)cm.Key));
         var         compilerService = _hostedScript.GetCompilerService();
         var         module          = compilerService.CreateModule(src);
         var         _loaded         = _hostedScript.EngineInstance.LoadModuleImage(module);
         dataProcessors.Insert((string)cm.Key, (IValue)_hostedScript.EngineInstance.NewObject(_loaded));
     }
     // Добавляем библиотеки как обработки
     AddLibrariesAsDataProcessors(dataProcessors);
     _hostedScript.EngineInstance.Environment.SetGlobalProperty("Обработки", new ScriptEngine.HostedScript.Library.FixedStructureImpl(dataProcessors));
 }
Beispiel #18
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);
        }
Beispiel #19
0
        System.Collections.Hashtable _dataProcessorObjectModules; // Список модулей объекта обработок

        public DataProcessorsManagerImpl(HostedScriptEngine hostedScript, System.Collections.Hashtable managerFiles, System.Collections.Hashtable objectFiles)
        {
            _hostedScript = hostedScript;
            _dataProcessorObjectModules = new System.Collections.Hashtable();

            foreach (System.Collections.DictionaryEntry co in objectFiles)
            {
                ICodeSource src = _hostedScript.Loader.FromString((string)co.Value);

                var compilerService = _hostedScript.GetCompilerService();
                var module          = compilerService.CreateModule(src);

                var _loaded = _hostedScript.EngineInstance.LoadModuleImage(module);
                _dataProcessorObjectModules.Add(co.Key, _loaded);
            }

            AddDataProcessorManagers(managerFiles);
        }
Beispiel #20
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;
                }
            }
        }
        public void RunTestScript(string resourceName)
        {
            var source        = LoadFromAssemblyResource(resourceName);
            var bytecodeImage = engine.GetCompilerService().Compile(source);

            engine.LoadUserScript(new ScriptEngine.UserAddedScript()
            {
                Type   = ScriptEngine.UserAddedScriptType.Class,
                Image  = bytecodeImage,
                Symbol = resourceName
            });

            var       test = AttachedScriptsFactory.ScriptFactory(resourceName, new IValue[] { });
            ArrayImpl testArray;

            {
                int methodIndex = test.FindMethod("ПолучитьСписокТестов");

                {
                    IValue ivTests;
                    test.CallAsFunction(methodIndex, new IValue[] { TestRunner }, out ivTests);
                    testArray = ivTests as ArrayImpl;
                }
            }

            foreach (var ivTestName in testArray)
            {
                string testName    = ivTestName.AsString();
                int    methodIndex = test.FindMethod(testName);
                if (methodIndex == -1)
                {
                    // Тест указан, но процедуры нет или она не экспортирована
                    continue;
                }

                test.CallAsProcedure(methodIndex, new IValue[] { });
            }
        }
Beispiel #22
0
        public void RunTestScript(string resourceName)
        {
            var source   = LoadFromAssemblyResource(resourceName);
            var byteCode = engine.GetCompilerService().Compile(source);
            var module   = engine.EngineInstance.LoadModuleImage(byteCode);

            var test = new UserScriptContextInstance(module);

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

            ArrayImpl testArray;

            {
                int methodIndex = test.FindMethod("ПолучитьСписокТестов");

                {
                    IValue ivTests;
                    test.CallAsFunction(methodIndex, new IValue [] { TestRunner }, out ivTests);
                    testArray = ivTests as ArrayImpl;
                }
            }

            foreach (var ivTestName in testArray)
            {
                string testName    = ivTestName.AsString();
                int    methodIndex = test.FindMethod(testName);
                if (methodIndex == -1)
                {
                    // Тест указан, но процедуры нет или она не экспортирована
                    continue;
                }

                test.CallAsProcedure(methodIndex, new IValue [] { });
            }
        }
        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);
        }
Beispiel #24
0
        private static ScriptableCounter CreateCounter()
        {
            var         curDir = Directory.GetCurrentDirectory();
            var         module = Path.Combine(curDir, "counter.os");
            ICodeSource src;

            if (File.Exists(module))
            {
                src = _world.Loader.FromFile(module);
            }
            else
            {
                src = _world.Loader.FromString("");
            }

            var compiler     = _world.GetCompilerService();
            var image        = compiler.CreateModule(src);
            var loadedModule = _world.EngineInstance.LoadModuleImage(image);

            var counter = new ScriptableCounter(loadedModule);

            _world.EngineInstance.InitializeSDO(counter);
            return(counter);
        }
Beispiel #25
0
        public AspNetHostEngine()
        {
            System.Collections.Specialized.NameValueCollection appSettings = System.Web.Configuration.WebConfigurationManager.AppSettings;

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

            AspNetLog.Write(logWriter, "Start loading. " + DateTime.Now.Ticks.ToString());

            if (appSettings == null)
            {
                AspNetLog.Write(logWriter, "appSettings is null");
            }

            try
            {
                _hostedScript = new HostedScriptEngine();
                // метод настраивает внутренние переменные у SystemGlobalContext
                _hostedScript.SetGlobalEnvironment(new NullApplicationHost(), new NullEntryScriptSrc());
                _hostedScript.Initialize();
                // Размещаем oscript.cfg вместе с web.config. Так наверное привычнее
                _hostedScript.CustomConfig = appSettings["configFilePath"] ?? System.IO.Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "oscript.cfg");
                //_hostedScript.AttachAssembly(System.Reflection.Assembly.GetExecutingAssembly());
                // Аттачим доп сборки. По идее должны лежать в Bin
                foreach (System.Reflection.Assembly assembly in _assembliesForAttaching)
                {
                    try
                    {
                        _hostedScript.AttachAssembly(assembly);
                    }
                    catch (Exception ex)
                    {
                        // Возникла проблема при аттаче сборки
                        AspNetLog.Write(logWriter, "Assembly attaching error: " + ex.Message);
                        if (appSettings["handlerLoadingPolicy"] == "strict")
                        {
                            throw;
                        }
                    }
                }

                //Загружаем библиотечные скрипты aka общие модули
                string libPath = ConvertRelativePathToPhysical(appSettings["commonModulesPath"]);
                if (libPath != null)
                {
                    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.CreateModule(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, логгируем, если логгирование включено
                            AspNetLog.Write(logWriter, "Error loading " + System.IO.Path.GetFileNameWithoutExtension(filePathName) + " : " + ex.Message);
                            if (appSettings["handlerLoadingPolicy"] == "strict")
                            {
                                throw;
                            }
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                // Возникла проблема при инициализации
                AspNetLog.Write(logWriter, ex.ToString());

                if (appSettings["handlerLoadingPolicy"] == "strict")
                {
                    throw; // Must fail!
                }
            }
            finally
            {
                AspNetLog.Write(logWriter, "End loading.");
                AspNetLog.Close(logWriter);
            }
        }
        public AspNetHostEngine(
            List <System.Reflection.Assembly> assembliesForAttaching,
            List <PropertiesInjectorInfo> propertiesInjectorsInfo,
            System.Collections.Hashtable commonModulesForLoading
            )
        {
            System.Collections.Specialized.NameValueCollection appSettings = System.Web.Configuration.WebConfigurationManager.AppSettings;

            _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"] ?? System.IO.Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "oscript.cfg");

            // Аттачим доп сборки. По идее должны лежать в Bin
            foreach (System.Reflection.Assembly assembly in assembliesForAttaching)
            {
                _hostedScript.AttachAssembly(assembly);
            }

            // Добавляем свойства для общих модулей
            foreach (System.Collections.DictionaryEntry cm in commonModulesForLoading)
            {
                _hostedScript.InjectGlobalProperty((string)cm.Key, ValueFactory.Create(), true);
            }

            // Загружаем классы инжекторов свойств
            List <PropertiesInjector> propertiesInjectors = new List <PropertiesInjector>();

            foreach (PropertiesInjectorInfo ci in propertiesInjectorsInfo)
            {
                ILibraryAsPropertiesLoader instance = (ILibraryAsPropertiesLoader)(Activator.CreateInstance(ci.AssemblyName, ci.ClassName).Unwrap());
                propertiesInjectors.Add(new PropertiesInjector(instance, ci.Info));
            }

            // Получаем и вставляем списки свойств. Класс инжектора должен иметь метод GetPropertyNamesForInjecting
            foreach (PropertiesInjector injector in propertiesInjectors)
            {
                List <string> propertiesNames = injector.Loader.GetPropertiesNamesForInjecting(injector.Info);
                foreach (string cp in propertiesNames)
                {
                    _hostedScript.InjectGlobalProperty(cp, ValueFactory.Create(), true);
                }
            }

            // Подключаем общие модули
            foreach (System.Collections.DictionaryEntry cm in commonModulesForLoading)
            {
                ICodeSource src = _hostedScript.Loader.FromString((string)cm.Value);

                var compilerService = _hostedScript.GetCompilerService();
                var module          = compilerService.CreateModule(src);
                var loaded          = _hostedScript.EngineInstance.LoadModuleImage(module);
                var instance        = (IValue)_hostedScript.EngineInstance.NewObject(loaded);
                _hostedScript.EngineInstance.Environment.SetGlobalProperty((string)cm.Key, instance);
            }

            // Присваиваем значения свойств
            foreach (PropertiesInjector injector in propertiesInjectors)
            {
                injector.Loader.AssignPropertiesValues(_hostedScript);
            }

            _hostedScript.EngineInstance.Environment.LoadMemory(MachineInstance.Current);
        }
Beispiel #27
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);
            }
        }