Example #1
0
 public ActionResult logout()
 {
     AppCore.GetUserContextManager().DestroyUserContext(AppCore.GetUserContextManager().GetCurrentUserContext());
     AppCore.Get <Binding.Providers.SessionBinder>().ClearUserContextFromRequest();
     AppCore.GetUserContextManager().ClearCurrentUserContext();
     return(Redirect("/"));
 }
Example #2
0
        /// <summary>
        /// Возвращает список схем, зарегистрированных для модуля <typeparamref name="TModule"/>.
        /// </summary>
        public Dictionary <uint, string> GetSchemeList <TModule>()
            where TModule : ModuleCore <TModule>
        {
            var module = AppCore.Get <TModule>();

            return(module != null?GetSchemeList(module.IdModule) : new Dictionary <uint, string>());
        }
Example #3
0
        /// <summary>
        /// </summary>
        protected override void OnModuleStarting()
        {
            _thisModule = this;

            var taskSchedulingManager = AppCore.Get <TaskSchedulingManager>();
            var task = taskSchedulingManager.RegisterTask(new TaskRequest()
            {
                Name            = "Обслуживание индексов",
                Description     = "",
                IsEnabled       = true,
                TaskOptions     = TaskOptions.AllowDisabling | TaskOptions.AllowManualSchedule | TaskOptions.PreventParallelExecution,
                UniqueKey       = $"{typeof(DbMaintenanceModule).FullName}_{nameof(MaintenanceIndexes)}",
                ExecutionLambda = () => MaintenanceIndexesStatic()
            });

            if (task.ManualSchedules.Count == 0)
            {
                taskSchedulingManager.SetTaskManualScheduleList(task, new List <TaskSchedule>()
                {
                    new TaskCronSchedule(Cron.Daily())
                    {
                        IsEnabled = true
                    }
                });
            }
        }
Example #4
0
        protected override void OnAfterApplicationStart()
        {
            try
            {
                var physicalApplicationPath = AppCore.ApplicationWorkingFolder;

#if DEBUG
                var paths = new List <string>();

                if (AppDomain.CurrentDomain.GetAssemblies().Where(x => x.FullName.StartsWith("OnWeb.Binding.AspNetMvc,")).Count() > 0)
                {
                    paths.Add(Path.GetFullPath(Path.Combine(physicalApplicationPath, "../../Binding/AspNetMvc/Library")));
                }

                if (AppDomain.CurrentDomain.GetAssemblies().Where(x => x.FullName.StartsWith("OnWeb.Standard.AspNetMvc,")).Count() > 0)
                {
                    paths.Add(Path.GetFullPath(Path.Combine(physicalApplicationPath, "../../Standard/AspNetMvc/Library")));
                }

                AppCore.Get <Core.Storage.ResourceProvider>().SourceDevelopmentPathList.AddRange(paths);
#endif
            }
            catch (Exception ex)
            {
                Debug.WriteLine("OnAfterApplicationStart.Development: {0}", ex.Message);
                throw;
            }
        }
Example #5
0
        /// <summary>
        /// </summary>
        protected sealed override void OnStarted()
        {
            _taskDescriptionClear = AppCore.Get <TaskSchedulingManager>().RegisterTask(new TaskRequest()
            {
                Name      = "Менеджер сообщений: очистка старых записей",
                IsEnabled = true,
                UniqueKey = typeof(MessagingManager).FullName + "_ClearLastNDays",
                Schedules = new List <TaskSchedule>()
                {
                    new TaskCronSchedule(Cron.Hourly())
                    {
                        IsEnabled = true
                    }
                },
                ExecutionLambda = () => ClearLastNDays(),
                TaskOptions     = TaskOptions.AllowDisabling | TaskOptions.AllowManualSchedule | TaskOptions.PreventParallelExecution
            });

            // Попытка инициализировать все сервисы обработки сообщений, наследующиеся от IMessagingService.
            var types = AppCore.GetQueryTypes().Where(x => x.GetInterfaces().Contains(typeof(IMessagingServiceInternal))).ToList();

            foreach (var type in types)
            {
                try
                {
                    var instance = AppCore.Get <IMessagingServiceInternal>(type);
                    if (instance != null && !_services.Contains(instance))
                    {
                        _services.Add(instance);
                    }
                }
                catch { }
            }
        }
Example #6
0
        public virtual ActionResult Journals()
        {
            using (var db = new JournalingDB.DataContext())
            {
                var dbAccessor = AppCore.Get <JournalingDB.JournalingManagerDatabaseAccessor <WebApplication> >();

                var queryDataBase    = dbAccessor.CreateQueryJournalData(db);
                var queryDataGrouped = from row in queryDataBase
                                       group row.JournalData by row.JournalName.IdJournal into gr
                                       select new { Count = gr.Count(), IdJournalDataLast = gr.Max(x => x.IdJournalData) };

                var query = from row in queryDataBase
                            join sq2 in queryDataGrouped on row.JournalData.IdJournalData equals sq2.IdJournalDataLast
                            select new Model.JournalQueries.QueryJournalData
                {
                    JournalData = row.JournalData,
                    JournalName = row.JournalName,
                    User        = row.User,
                    Count       = sq2.Count
                };

                var data = dbAccessor.
                           FetchQueryJournalData <Model.JournalQueries.QueryJournalData, Model.JournalQueries.JournalData>(query, (row, instance) => instance.Count = row.Count).
                           Select(x => new Design.Model.JournalsList()
                {
                    JournalName   = x.JournalInfo,
                    EventsCount   = x.Count,
                    EventLastDate = x.DateEvent,
                    EventLastType = x.EventType
                }).ToList();

                return(View("Journals.cshtml", data));
            }
        }
Example #7
0
        public virtual ActionResult JournalClear(int?IdJournal = null)
        {
            var answer = JsonAnswer();

            try
            {
                if (!IdJournal.HasValue)
                {
                    throw new Exception("Не указан идентификатор журнала.");
                }

                var result = AppCore.Get <JournalingManager>().GetJournal(IdJournal.Value);
                if (!result.IsSuccess)
                {
                    throw new Exception(result.Message);
                }

                using (var db = new JournalingDB.DataContext())
                    using (var scope = db.CreateScope())
                    {
                        db.DataContext.ExecuteQuery("DELETE FROM Journal WHERE IdJournal=@IdJournal", new { IdJournal = result.Result.IdJournal });
                        scope.Commit();
                    }
                answer.FromSuccess(null);
            }
            catch (Exception ex)
            {
                this.RegisterEventWithCode(System.Net.HttpStatusCode.InternalServerError, "Ошибка во время удаления журнала", $"Журнал №{IdJournal}", ex);
                answer.FromFail("Ошибка во время удаления журнала.");
            }
            return(ReturnJson(answer));
        }
Example #8
0
        void SetTask(string name, string cronExpression, Expression <Action> taskDelegate)
        {
            lock (_jobsSyncRoot)
            {
                if (_jobsList.Any(x => x.JobName == name))
                {
                    _jobsList.RemoveAll(x => x.JobName == name);
                }

                var schedule          = CrontabSchedule.Parse(cronExpression);
                var executionDelegate = taskDelegate.Compile();
                var baseTime          = DateTime.UtcNow;

                if (_delayedTaskRegistration != null)
                {
                    _delayedTaskRegistration.Add(() => _jobsList.Add(new JobInternal()
                    {
                        CronSchedule      = schedule,
                        JobName           = name,
                        ExecutionDelegate = executionDelegate,
                        ClosestOccurrence = schedule.GetNextOccurrence(baseTime.Add(AppCore.Get <Modules.CoreModule.CoreModule>().ApplicationTimeZoneInfo.BaseUtcOffset))
                    }));
                }
                else
                {
                    _jobsList.Add(new JobInternal()
                    {
                        CronSchedule      = schedule,
                        JobName           = name,
                        ExecutionDelegate = executionDelegate,
                        ClosestOccurrence = schedule.GetNextOccurrence(baseTime.Add(AppCore.Get <Modules.CoreModule.CoreModule>().ApplicationTimeZoneInfo.BaseUtcOffset))
                    });
                }
            }
        }
Example #9
0
        public virtual ActionResult MainSettings()
        {
            var handler = AppCore.Get <ModuleControllerTypesManager>();
            var model   = new Model.AdminMainModelInfoPage(AppCore.AppConfig, AppCore.WebConfig)
            {
                ModulesList = (from p in AppCore.GetModulesManager().GetModules()
                               where handler.GetModuleControllerTypes(p.QueryType) != null
                               orderby p.Caption
                               select new SelectListItem()
                {
                    Value = p.ID.ToString(),
                    Text = p.Caption,
                    Selected = AppCore.WebConfig.IdModuleDefault == p.ID
                }).ToList()
            };

            using (var db = Module.CreateUnitOfWork())
            {
                model.Roles = (from p in db.Role orderby p.NameRole ascending select p).ToList();
                model.Roles.Insert(0, new Role()
                {
                    IdRole = 0, NameRole = "Не выбрано"
                });
            }

            return(View("CoreSettings.tpl", model));
        }
Example #10
0
        protected override ModuleConfiguration <EMailModule> ConfigurationSaveCustom(Configuration formData, out string outputMessage)
        {
            var handlers = AppCore.AppConfig.MessageServicesComponentsSettings.ToDictionary(x => x.TypeFullName, x => x);

            handlers.Remove(typeof(Components.SmtpServer).FullName);
            if (formData.IsUseSmtp)
            {
                handlers[typeof(Components.SmtpServer).FullName] = new ComponentSettings()
                {
                    TypeFullName       = typeof(Components.SmtpServer).FullName,
                    SettingsSerialized = JsonConvert.SerializeObject(new Components.SmtpServerSettings()
                    {
                        Server   = formData?.Smtp?.Server,
                        IsSecure = formData?.Smtp?.IsSecure ?? false,
                        Port     = formData?.Smtp?.Port,
                        Login    = formData?.Smtp?.Login,
                        Password = formData?.Smtp?.Password
                    })
                };
            }

            var cfg = AppCore.Get <CoreModule <WebApplication> >().GetConfigurationManipulator().GetEditable <CoreConfiguration <WebApplication> >();

            cfg.MessageServicesComponentsSettings = handlers.Values.ToList();

            AppCore.Get <CoreModule <WebApplication> >().GetConfigurationManipulator().ApplyConfiguration(cfg);
            AppCore.Get <MessagingManager <WebApplication> >().UpdateComponentsFromSettings();

            return(base.ConfigurationSaveCustom(formData, out outputMessage));
        }
Example #11
0
 private void RegisterLogHistoryEvent(int idUser, EventType eventType, int eventCode, string eventInfo, string Comment = null)
 {
     try
     {
         var idJournal = GetAuthJournalId();
         if (idJournal.HasValue)
         {
             AppCore.Get <JournalingManager>().RegisterEventForItem(
                 idJournal.Value,
                 new ItemKey(ItemTypeFactory.GetItemType <CoreDB.User>().IdItemType, idUser, ""),
                 eventType,
                 eventCode,
                 eventInfo,
                 Comment);
         }
     }
     catch (Exception ex)
     {
         var idJournal = GetAuthJournalId();
         if (idJournal.HasValue)
         {
             AppCore.Get <JournalingManager>().RegisterEvent(idJournal.Value, EventType.CriticalError, 0, "Ошибка регистрации события в журнал", null, null, ex);
         }
     }
 }
        public virtual ActionResult UserEdit(int IdUser = 0)
        {
            using (var db = new CoreContext())
            {
                var data = IdUser != 0 ? db.Users.Where(x => x.IdUser == IdUser).FirstOrDefault() : new User();
                if (data == null)
                {
                    throw new KeyNotFoundException("Неправильно указан пользователь!");
                }
                var history = AppCore.Get <JournalingManager>().GetJournalForItem(data);

                var model = new Design.Model.AdminUserEditForm()
                {
                    history = history.Result,
                    IsNeedToChangePassword = false,
                    User      = data,
                    UserRoles = db.RoleUser
                                .Where(x => x.IdUser == data.IdUser)
                                .Select(x => x.IdRole)
                                .ToList(),
                    Roles = db.Role
                            .OrderBy(x => x.NameRole)
                            .Select(x => new SelectListItem()
                    {
                        Value = x.IdRole.ToString(),
                        Text  = x.NameRole
                    })
                            .ToList(),
                };

                return(View("admin/AdminUserEditForm.cshtml", model));
            }
        }
Example #13
0
        protected override void OnModuleStarting()
        {
            _thisModule = this;

            var taskSchedulingManager = AppCore.Get <TaskSchedulingManager>();
            var task = taskSchedulingManager.RegisterTask(new TaskRequest()
            {
                Name            = "Проверка новых необработанных слов",
                Description     = "",
                IsEnabled       = true,
                TaskOptions     = TaskOptions.AllowDisabling | TaskOptions.AllowManualSchedule | TaskOptions.PreventParallelExecution,
                UniqueKey       = $"{typeof(LexiconManager).FullName}_{nameof(LexiconManager.PrepareNewWords)}",
                ExecutionLambda = () => LexiconNewWordsStatic()
            });

            if (task.ManualSchedules.Count == 0)
            {
                taskSchedulingManager.SetTaskManualScheduleList(task, new List <TaskSchedule>()
                {
                    new TaskCronSchedule(Cron.MinuteInterval(2))
                    {
                        IsEnabled = true
                    }
                });
            }
        }
Example #14
0
        public virtual ActionResult UserEdit(int IdUser = 0)
        {
            using (var db = this.CreateUnitOfWork())
            {
                var data = IdUser != 0 ? db.Users.Where(x => x.IdUser == IdUser).FirstOrDefault() : new User();
                if (data == null)
                {
                    throw new KeyNotFoundException("Неправильно указан пользователь!");
                }
                var history = AppCore.Get <JournalingManager>().GetJournalForItem(data);

                var model = new Model.AdminUserEdit()
                {
                    history   = history.Result,
                    User      = data,
                    UserRoles = db.RoleUser
                                .Where(x => x.IdUser == data.IdUser)
                                .Select(x => x.IdRole)
                                .ToList(),
                    Roles = db.Role
                            .OrderBy(x => x.NameRole)
                            .Select(x => new SelectListItem()
                    {
                        Value = x.IdRole.ToString(),
                        Text  = x.NameRole
                    })
                            .ToList(),
                };

                return(View("admin/admin_customer_users_ae.cshtml", model));
            }
        }
Example #15
0
        List <SitemapItem> ISitemapProvider.GetItems()
        {
            var moduleMaterials = AppCore.Get <ModuleMaterials>();

            using (var db = new DB.DataLayerContext())
            {
                var news = (from p in db.News
                            orderby p.name ascending
                            where p.status
                            select p).ToList();

                var pages = (from p in db.Pages
                             orderby p.name ascending
                             where p.status > 0
                             select p).ToList();

                var items = news.OfType <ItemBase>().Union(pages.OfType <ItemBase>()).OfType <IItemRouted>();

                //items.ForEach(item => item.OwnerModule = moduleMaterials);

                return(items.Select(x => new SitemapItem()
                {
                    Location = x.Url,
                    LastModificationTime = (x as ItemBase).DateChangeBase >= DateTime.MinValue ? (DateTime?)((x as ItemBase).DateChangeBase) : null
                }).ToList());
            }
        }
Example #16
0
        protected void SetServiceStatus(ServiceStatus status, string statusDetailed = null)
        {
            this.ServiceStatus         = status;
            this.ServiceStatusDetailed = statusDetailed;

            AppCore.Get <Monitor>().RegisterServiceStateWithoutJournal(this, status, statusDetailed);
        }
Example #17
0
        public JsonResult SchemeAdd(int?idModule = null, string schemeName = null)
        {
            var result = JsonAnswer <uint>();

            try
            {
                if (!idModule.HasValue)
                {
                    throw new Exception("Не указан идентификатор модуля.");
                }

                var module = AppCore.GetModulesManager().GetModule(idModule.Value) as IModuleCore;
                if (module == null)
                {
                    throw new Exception("Модуль не найден.");
                }

                if (Request.Form.HasKey(nameof(schemeName)))
                {
                    schemeName = Request.Form[nameof(schemeName)];
                }

                if (string.IsNullOrEmpty(schemeName))
                {
                    result.Message = "Не указано название схемы!";
                }
                else if (!schemeName.isOneStringTextOnly())
                {
                    result.Message = "Некорректно указано название схемы!";
                }
                else
                {
                    using (var db = this.CreateUnitOfWork())
                    {
                        var data = new CustomFieldsScheme()
                        {
                            IdModule   = idModule.Value,
                            NameScheme = schemeName
                        };
                        db.CustomFieldsSchemes.Add(data);

                        if (db.SaveChanges() > 0)
                        {
                            result.Message = "Схема добавлена.";
                            result.Success = true;
                            result.Data    = (uint)data.IdScheme;
                            AppCore.Get <ModuleItemsCustomize <WebApplication> >().UpdateCache();
                        }
                        else
                        {
                            result.Message = "По неизвестной причине схему не получилось добавить.";
                        }
                    }
                }
            }
            catch (Exception ex) { result.Message = ex.Message; }

            return(ReturnJson(result));
        }
Example #18
0
 /// <summary>
 /// Инициирует немедленный запуск сервиса генерации карты сайта.
 /// </summary>
 public void MarkSitemapGenerationToRun()
 {
     if (_sitemapTask == null)
     {
         throw new InvalidOperationException("Сервис генерации карты сайта недоступен. Возможно, модуль был некорректно инициализирован.");
     }
     AppCore.Get <TaskSchedulingManager>().ExecuteTask(_sitemapTask);
 }
Example #19
0
        /// <summary>
        /// Связывает тип объекта <typeparamref name="TItemBase"/> с модулем типа <typeparamref name="TModule"/>.
        /// </summary>
        /// <seealso cref="ModuleCore{TSelfReference}.QueryType"/>
        /// <seealso cref="ItemTypeAliasAttribute"/>
        public void RegisterModuleItemType <TItemBase, TModule>()
            where TItemBase : ItemBase
            where TModule : ModuleCore
        {
            var module = AppCore.Get <TModule>();

            RegisterModuleItemType <TItemBase, TModule>(module);
        }
Example #20
0
        /// <summary>
        /// См. <see cref="ModuleCore.OnModuleStarting"/>.
        /// </summary>
        protected sealed override void OnModuleStarting()
        {
            RegisterPermission(PERM_MANAGEUSERS, "Управление пользователями");
            RegisterPermission(PERM_MANAGEROLES, "Управление ролями");
            RegisterPermission(PERM_VIEWHISTORY, "Просмотр истории");

            AppCore.Get <ItemsManager>().RegisterModuleItemType <User, ModuleCustomer>(this);
        }
Example #21
0
        /// <summary>
        /// Записывает в журнал сервиса событие, связанное с сервисом.
        /// </summary>
        /// <param name="service">Сервис, для которого производится регистрация состояния.</param>
        /// <param name="eventType">См. <see cref="JournalData.EventType"/>.</param>
        /// <param name="eventInfo">См. <see cref="JournalData.EventInfo"/>.</param>
        /// <param name="eventInfoDetailed">См. <see cref="JournalData.EventInfoDetailed"/>.</param>
        /// <param name="exception">См. <see cref="JournalData.ExceptionDetailed"/>.</param>
        public void RegisterServiceEvent(IMonitoredService service, EventType eventType, string eventInfo, string eventInfoDetailed = null, Exception exception = null)
        {
            var serviceJournal = GetJournalName(service);

            if (serviceJournal != null)
            {
                AppCore.Get <JournalingManager>().RegisterEvent(serviceJournal.IdJournal, eventType, eventInfo, eventInfoDetailed, null, exception);
            }
        }
Example #22
0
        bool IService.SendToAdmin(string message)
        {
            var adminUserName = AppCore.Get <ModuleCommunication>().GetConfiguration <ModuleConfiguration>().AdminUserName;

            if (string.IsNullOrEmpty(adminUserName))
            {
                throw new Exception("Не задано имя администратора в Telegram.");
            }
            return(Send(adminUserName, message));
        }
Example #23
0
        /// <summary>
        /// Возвращает пользовательский контекст на основании данных в текущем запросе.
        /// </summary>
        /// <returns>Возвращает пользовательский контекст или null.</returns>
        /// <exception cref="InvalidOperationException">Возникает, если метод выполняется не в рамках входящего запроса.</exception>
        /// <seealso cref="BindUserContextToRequest(IUserContext)"/>
        /// <seealso cref="ClearUserContextFromRequest"/>
        /// <seealso cref="TryGetUserCredentialsFromRequest(out int?)"/>
        public IUserContext RestoreUserContextFromRequest()
        {
            if (TryGetUserCredentialsFromRequest(out int?idUser))
            {
                var userContextResult = AppCore.Get <Core.Users.WebUserContextManager>().CreateUserContext(idUser.Value, out var userContext);
                return(userContextResult == Core.Users.eAuthResult.Success ? userContext : null);
            }

            return(null);
        }
Example #24
0
        public virtual ActionResult TaskSheduling()
        {
            var taskList = AppCore.Get <TaskSchedulingManager>().GetTaskList(false);
            var model    = new ViewModels.TaskSheduling()
            {
                TaskList = taskList.Select(x => new Model.TaskShedulingTask(x)).ToList()
            };

            return(View("TaskSheduling.cshtml", model));
        }
Example #25
0
        /// <summary>
        /// Ищет и запускает все модули, для которых зарегистрированы привязки типов.
        /// </summary>
        internal protected void StartModules()
        {
            if (AppCore.AppDebugLevel >= DebugLevel.Common)
            {
                Debug.WriteLine($"{nameof(ModulesManager)}.{nameof(StartModules)}");
            }

            lock (_syncRoot)
            {
                var moduleCoreType = typeof(ModuleCore);

                // Сначала ищем список модулей.
                var typesList         = AppCore.GetQueryTypes().ToList();
                var filteredTypesList = typesList.Where(FilterModuleTypes).ToList();
                if (!filteredTypesList.IsNullOrEmpty() && filteredTypesList.Any(type => !typeof(ModuleCore).IsAssignableFrom(type)))
                {
                    throw new ApplicationStartException(ApplicationStartStep.BindingsAutoStartCritical, typeof(ModulesManager), new ArgumentException());
                }

                if (AppCore.AppDebugLevel >= DebugLevel.Detailed)
                {
                    Debug.WriteLine($"{nameof(ModulesManager)}.{nameof(StartModules)}: список всех query-типов (всего {typesList.Count}):");
                    typesList.OrderBy(x => x.FullName).ForEach(x => Debug.WriteLine($"{nameof(ModulesManager)}.{nameof(StartModules)}: {x}"));
                    Debug.WriteLine($"{nameof(ModulesManager)}.{nameof(StartModules)}: список отфильтрованных query-типов (всего {filteredTypesList.Count}):");
                    filteredTypesList.OrderBy(x => x.FullName).ForEach(x => Debug.WriteLine($"{nameof(ModulesManager)}.{nameof(StartModules)}: {x}"));
                }

                foreach (var moduleType in filteredTypesList)
                {
                    try
                    {
                        if (AppCore.AppDebugLevel >= DebugLevel.Detailed)
                        {
                            Debug.WriteLine($"{nameof(ModulesManager)}.{nameof(StartModules)}: запуск модуля '{moduleType}'");
                        }

                        var moduleInstance = AppCore.Get <ModuleCore>(moduleType);
                    }
                    catch (Exception ex)
                    {
                        if (AppCore.AppDebugLevel >= DebugLevel.Detailed)
                        {
                            Debug.WriteLine($"{nameof(ModulesManager)}.{nameof(StartModules)}: ошибка запуска модуля");
                            Debug.WriteLine($"{nameof(ModulesManager)}.{nameof(StartModules)}: {ex}");
                        }

                        if (typeof(ICritical).IsAssignableFrom(moduleType))
                        {
                            throw new ApplicationStartException(ApplicationStartStep.BindingsAutoStartCritical, moduleType, ex);
                        }
                    }
                }
            }
        }
Example #26
0
        /// <summary>
        /// </summary>
        protected internal override void OnModuleStarted()
        {
            var subscriptionManager = AppCore.Get <SubscriptionsManager>();

            _subscriptionEventCritical = subscriptionManager.RegisterSubscription(
                "Журнал: уведомление о критических событиях",
                subscriptionManager.SubscriptionGroupSystem,
                new Journaling.CriticalJournalEventSubscription());

            OnConfigurationApplied();
        }
Example #27
0
 private JournalInfo GetJournalName(IMonitoredService service)
 {
     return(_servicesJournalsList.GetOrAddWithExpiration(service.ServiceID, (key) =>
     {
         var result = AppCore.Get <JournalingManager>().RegisterJournal(1, service.ServiceName, "ServiceMonitor_" + key.ToString());
         if (!result.IsSuccess)
         {
             this.RegisterEvent(EventType.Error, "Не удалось зарегистрировать журнал мониторинга", $"Журнал для типа '{service.GetType().FullName}'");
         }
         return result.Result;
     }, TimeSpan.FromMinutes(15)));
 }
Example #28
0
 public ActionResult TestGeo(string address)
 {
     System.Net.IPAddress ip = null;
     if (System.Net.IPAddress.TryParse(address, out ip))
     {
         var result = AppCore.Get <Core.Addresses.IManager>().GetAddressByIP(ip);
         return(Content(result.Result?.KodAddress));
     }
     else
     {
         return(Content("not"));
     }
 }
Example #29
0
        protected sealed override void OnRunService()
        {
            var moduleRouting = AppCore.Get <Modules.Routing.ModuleRouting>();

            try
            {
                moduleRouting?.ClearCurrentThreadCache();
                OnRunServiceWeb();
            }
            finally
            {
                moduleRouting?.ClearCurrentThreadCache();
            }
        }
Example #30
0
        /// <summary>
        /// </summary>
        protected sealed internal override void OnConfigurationApplied()
        {
            var cfg = GetConfiguration <ModuleConfiguration>();

            if (_component == null && cfg.IsUseSmtp)
            {
                _component = new Components.SmtpServer();
                AppCore.Get <Messaging.MessagingManager>().RegisterComponent(_component);
            }
            if (_component != null)
            {
                _component.InitClient();
            }
        }