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); }
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); }
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); }
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 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 { /*что-то не так, ничего не делаем*/ } } }
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); }
public static HostedScriptEngine StartEngine() { var engine = new HostedScriptEngine(); engine.Initialize(); engine.AttachAssembly(System.Reflection.Assembly.GetAssembly(typeof(Bracker.BrackerWriterImpl))); return(engine); }
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); }
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(); }
private int RunCGIMode(string scriptFile) { var engine = new HostedScriptEngine { CustomConfig = ScriptFileHelper.CustomConfigPath(scriptFile) }; engine.AttachAssembly(Assembly.GetExecutingAssembly()); var request = new WebRequestContext(); engine.InjectGlobalProperty("ВебЗапрос", request, true); engine.InjectGlobalProperty("WebRequest", request, true); engine.InjectObject(this, false); ScriptFileHelper.OnBeforeScriptRead(engine); var source = engine.Loader.FromFile(scriptFile); Process process; try { process = engine.CreateProcess(this, source); } catch (Exception e) { ShowExceptionInfo(e); return(1); } var exitCode = process.Start(); if (!_isContentEchoed) { Echo(""); } return(exitCode); }
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); } }
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); }
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); } }