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); }
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 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); }
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 static void InjectSettings(HostedScriptEngine engine) { string server = ConfigurationManager.AppSettings["server"]; string userName = ConfigurationManager.AppSettings["userName"]; string password = ConfigurationManager.AppSettings["password"]; string replyTo = ConfigurationManager.AppSettings["replyTo"] ?? String.Format("{0}@{1}", userName, server); string pop3server = ConfigurationManager.AppSettings["pop3server"] ?? server; string imapserver = ConfigurationManager.AppSettings["imapserver"] ?? server; int portSmtp; bool useSsl; int timeout; if (!Int32.TryParse(ConfigurationManager.AppSettings["portSmtp"], out portSmtp)) { portSmtp = 25; } if (!Boolean.TryParse(ConfigurationManager.AppSettings["useSsl"], out useSsl)) { useSsl = true; } if (!Int32.TryParse(ConfigurationManager.AppSettings["timeout"], out timeout)) { timeout = 30; } engine.InjectGlobalProperty("Сервер", ValueFactory.Create(server), true); engine.InjectGlobalProperty("СерверPOP3", ValueFactory.Create(pop3server), true); engine.InjectGlobalProperty("СерверIMAP", ValueFactory.Create(imapserver), true); engine.InjectGlobalProperty("Пользователь", ValueFactory.Create(userName), true); engine.InjectGlobalProperty("Пароль", ValueFactory.Create(password), true); engine.InjectGlobalProperty("ПортSMTP", ValueFactory.Create(portSmtp), true); engine.InjectGlobalProperty("Отправитель", ValueFactory.Create(replyTo), true); engine.InjectGlobalProperty("ИспользоватьSSLSMTP", ValueFactory.Create(useSsl), true); engine.InjectGlobalProperty("ИспользоватьSSLPOP3", ValueFactory.Create(useSsl), true); engine.InjectGlobalProperty("ИспользоватьSSLIMAP", ValueFactory.Create(useSsl), true); engine.InjectGlobalProperty("Таймаут", ValueFactory.Create(timeout), true); }
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); } }