예제 #1
0
        static AspNetHostEngine()
        {
            _assembliesForAttaching = new List <System.Reflection.Assembly>();

            System.Collections.Specialized.NameValueCollection appSettings = System.Web.Configuration.WebConfigurationManager.AppSettings;

            TextWriter logWriter = AspNetLog.Open(appSettings);

            _cachingEnabled = (appSettings["cachingEnabled"] == "true");
            AspNetLog.Write(logWriter, "Start assemblies loading.");

            foreach (string assemblyName in appSettings.AllKeys)
            {
                if (appSettings[assemblyName] == "attachAssembly")
                {
                    try
                    {
                        _assembliesForAttaching.Add(System.Reflection.Assembly.Load(assemblyName));
                    }
                    // TODO: Исправить - должно падать. Если конфиг сайта неработоспособен - сайт не должен быть работоспособен.
                    catch (Exception ex)
                    {
                        AspNetLog.Write(logWriter, "Error loading assembly: " + assemblyName + " " + ex.ToString());
                        if (appSettings["handlerLoadingPolicy"] == "strict")
                        {
                            throw; // Must fail!
                        }
                    }
                }
            }

            // Загружаем ASPNetHandler.dll
            try
            {
                _assembliesForAttaching.Add(System.Reflection.Assembly.Load("ASPNETHandler"));
            }
            // TODO: Исправить - должно падать. Если конфиг сайта неработоспособен - сайт не должен быть работоспособен.
            catch (Exception ex)
            {
                AspNetLog.Write(logWriter, "Error loading assembly: ASPNetHandler" + " " + ex.ToString());
                if (appSettings["handlerLoadingPolicy"] == "strict")
                {
                    throw; // Must fail!
                }
            }

            AspNetLog.Write(logWriter, "Stop assemblies loading.");

            // ToDo: Загружаем и компилируем общие модули

            AspNetLog.Close(logWriter);
        }
예제 #2
0
        public static void ExecuteJob(object stateInfo)
        {
            WebBackgroundJob job = (WebBackgroundJob)stateInfo;

            System.Collections.Hashtable syncJobsKeys;
            syncJobsKeys = System.Collections.Hashtable.Synchronized(jobsKeys);

            if (job.Key != "" && job.Key != null)
            {
                // Пробуем вставить в таблицу ключей
                //, если вставка неудачна, значит фоновое задание уже выполняется

                try
                {
                    syncJobsKeys.Add(job.Key, job.Key);
                }
                catch (ArgumentException)
                {
                    // Такое значение уже есть в списке, не запускаем задание
                    return;
                }
            }

            // Заполняем значения работы и вставляем ее в список
            System.Collections.Hashtable syncJobs = System.Collections.Hashtable.Synchronized(jobs);
            syncJobs.Add(job.UUID, job);
            job.Begin = DateTime.Now;

            try
            {
                AspNetHostEngine engine = new AspNetHostEngine();
                engine.CallCommonModuleProcedure(job.MethodName, job.ExecutionParameters);
                job.State = BackgroundJobState.Completed;
                job.ExecutionParameters = null;
            }
            catch (ScriptEngine.ScriptException ex)
            {
                job.ErrorInfo = new ExceptionInfoContext(ex);
                job.State     = BackgroundJobState.Failed;

                System.IO.TextWriter logWriter = AspNetLog.Open();
                AspNetLog.Write(logWriter, "Error executing background job ");
                AspNetLog.Write(logWriter, ex.ToString());
                AspNetLog.Close(logWriter);
            }
            catch (Exception ex)
            {
                job.State = BackgroundJobState.Failed;

                System.IO.TextWriter logWriter = AspNetLog.Open();
                AspNetLog.Write(logWriter, "Error executing background job ");
                AspNetLog.Write(logWriter, ex.ToString());
                AspNetLog.Close(logWriter);
            }
            finally
            {
                job.End = DateTime.Now;

                try
                {
                    syncJobs.Remove(job.UUID);
                }
                catch { /* Ничего не делаем*/ }

                try
                {
                    if (job.Key != null)
                    {
                        syncJobsKeys.Remove(job.Key);
                    }
                }
                catch { /* Ничего не делаем*/ }
            }
        }
        public void WaitForCompletion(int?timeout = null)
        {
            int  delta     = WebBackgroundJobsManager.CheckInterval;
            long timeoutMs = 1000;

            if (timeout == null)
            {
                delta = 0;
            }
            else
            {
                timeoutMs = (long)(timeout * 1000);
            }

            long current = 0;

            do
            {
                System.Threading.Thread.Sleep(WebBackgroundJobsManager.CheckInterval);
                current += delta;
            } while (current < timeoutMs && State == WebBackgroundJobStateImpl.Active);

            System.IO.TextWriter logWriter;

            if (State == WebBackgroundJobStateImpl.Failed)
            {
                logWriter = AspNetLog.Open();
                string logStr = ErrorInfo.ModuleName + "`n"
                                + ErrorInfo.LineNumber + "`n"
                                + ErrorInfo.Description + "`n"
                                + ErrorInfo.DetailedDescription;
                AspNetLog.Write(logWriter, logStr);
                AspNetLog.Close(logWriter);

                throw (new Exception("Фоновое задание завершились с ошибкой."));
            }

            if (State == WebBackgroundJobStateImpl.Completed)
            {
                return;
            }

            string exceptionString = "Timeout expires for job: ";

            exceptionString += "start date: " + Begin.ToString() + " ";
            exceptionString += "method: " + MethodName + " ";

            if (Description != null)
            {
                exceptionString += "description: " + Description + " ";
            }
            if (Key != null)
            {
                exceptionString += "key: " + Description + " ";
            }

            logWriter = AspNetLog.Open();
            AspNetLog.Write(logWriter, exceptionString);
            AspNetLog.Close(logWriter);

            throw (new Exception(exceptionString));
        }
예제 #4
0
        public void WaitForCompletion(ArrayImpl backgroundJobs, int?timeout = null)
        {
            int  delta     = WebBackgroundJobsManager.CheckInterval;
            long timeoutMs = 1000;

            if (timeout == null)
            {
                delta = 0;
            }
            else
            {
                timeoutMs = (long)(timeout * 1000);
            }

            long current = 0;
            WebBackgroundJobImpl failedJob       = null;
            WebBackgroundJobImpl notCompletedJob = null;

            do
            {
                System.Threading.Thread.Sleep(WebBackgroundJobsManager.CheckInterval);
                current += delta;

                notCompletedJob = null;

                foreach (IValue cj in backgroundJobs)
                {
                    if (((WebBackgroundJobImpl)cj).State == WebBackgroundJobStateImpl.Active)
                    {
                        notCompletedJob = (WebBackgroundJobImpl)cj;
                    }
                    if (((WebBackgroundJobImpl)cj).State == WebBackgroundJobStateImpl.Failed)
                    {
                        failedJob = (WebBackgroundJobImpl)cj;
                        break;
                    }
                }
            } while (current < timeoutMs && notCompletedJob != null && failedJob == null);

            System.IO.TextWriter logWriter;

            if (failedJob != null)
            {
                logWriter = AspNetLog.Open();
                string logStr = failedJob.ErrorInfo.ModuleName + "`n"
                                + failedJob.ErrorInfo.LineNumber + "`n"
                                + failedJob.ErrorInfo.Description + "`n"
                                + failedJob.ErrorInfo.DetailedDescription;
                AspNetLog.Write(logWriter, logStr);
                AspNetLog.Close(logWriter);

                throw (new Exception("Одно или несколько фоновых заданий завершились с ошибкой."));
            }

            if (notCompletedJob == null)
            {
                return;
            }

            string exceptionString = "Timeout expires for job: ";

            exceptionString += "start date: " + notCompletedJob.Begin.ToString() + " ";
            exceptionString += "method: " + notCompletedJob.MethodName + " ";

            if (notCompletedJob.Description != null)
            {
                exceptionString += "description: " + notCompletedJob.Description + " ";
            }
            if (notCompletedJob.Key != null)
            {
                exceptionString += "key: " + notCompletedJob.Description + " ";
            }

            logWriter = AspNetLog.Open();
            AspNetLog.Write(logWriter, exceptionString);
            AspNetLog.Close(logWriter);

            throw (new Exception(exceptionString));
        }
        public static void ExecuteJob(object stateInfo)
        {
            WebBackgroundJob job = (WebBackgroundJob)stateInfo;

            if (job.Key != "" && job.Key != null)
            {
                // Пробуем вставить в таблицу ключей
                //, если вставка неудачна, значит фоновое задание уже выполняется
                if (!jobsKeys.TryAdd(job.Key, job.Key))
                {
                    // Такое значение уже есть в списке, не запускаем задание?
                    throw new RuntimeException("Фоновое задание с таким значением ключа уже выполняется");
                }
            }

            // Заполняем значения работы и вставляем ее в список
            jobs.TryAdd(job.UUID, job);
            job.Begin = DateTime.Now;
            AspNetHostEngine engine = null;

            try
            {
                if (!engines.TryDequeue(out engine))
                {
                    throw new RuntimeException("cannot deque engine");
                }

                engine.CallCommonModuleProcedure(job.MethodName, job.ExecutionParameters);
                job.State = BackgroundJobState.Completed;
                job.ExecutionParameters = null;
            }
            catch (ScriptEngine.ScriptException ex)
            {
                job.ErrorInfo = new ExceptionInfoContext(ex);
                job.State     = BackgroundJobState.Failed;

                System.IO.TextWriter logWriter = AspNetLog.Open();
                AspNetLog.Write(logWriter, "Error executing background job ");
                AspNetLog.Write(logWriter, ex.ToString());
                AspNetLog.Close(logWriter);
            }
            catch (Exception ex)
            {
                job.State = BackgroundJobState.Failed;

                System.IO.TextWriter logWriter = AspNetLog.Open();
                AspNetLog.Write(logWriter, "Error executing background job ");
                AspNetLog.Write(logWriter, ex.ToString());
                AspNetLog.Close(logWriter);
            }
            finally
            {
                job.End = DateTime.Now;
                if (engine != null)
                {
                    engines.Enqueue(engine);
                }

                try
                {
                    WebBackgroundJob outjob;
                    jobs.TryRemove(job.UUID, out outjob);
                }
                catch { /* Ничего не делаем*/ }

                try
                {
                    string outStr;
                    if (job.Key != null && job.Key != "")
                    {
                        jobsKeys.TryRemove(job.Key, out outStr);
                    }
                }
                catch { /* Ничего не делаем*/ }
            }
        }
예제 #6
0
        public AspNetHostEngine()
        {
            System.Collections.Specialized.NameValueCollection appSettings = System.Web.Configuration.WebConfigurationManager.AppSettings;

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

            AspNetLog.Write(logWriter, "Start loading.");

            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.Message);

                if (appSettings["handlerLoadingPolicy"] == "strict")
                {
                    throw; // Must fail!
                }
            }
            finally
            {
                AspNetLog.Write(logWriter, "End loading.");
                AspNetLog.Close(logWriter);
            }
        }