Example #1
0
        public void Start()
        {
            var builder = new ContainerBuilder();

            _core = AppCoreBuilder.Create(builder)
                .AddModule<NCoreFileStorageModule>()
                .AddModule(new NHibernatePostgreModule()
                {
                    AssemblyMapper = Assembly.GetExecutingAssembly(),
                    ConnectionStringKey = "ncore-test-base",
                    AfterConfigure = e => {

                        FileStorageCore.Configure(e);
                        SecurityCore.Configure(e);

                    }
                })
                .AddModule(new NCoreSecurityNHibernateModule())
                .Configure(c => {
                    c.RegisterType<TestService>().As<ITestService>();
                    c.RegisterType<TestRepository>().As<ITestRepository>();
                })
                .Build();

            var service = _core.Resolve<ITestService>();
            service.AddTestRecord();
        }
Example #2
0
 public AppHost(AppCore core)
 {
     _core = core;
     _appScopeList = new List<IAppScope>();
     _factory = new TaskFactory(_cancellationToken);
     _tokenSource = new CancellationTokenSource();
     _cancellationToken = _tokenSource.Token;
     Apps=new List<IHostedApp>();
 }
    public BaseMediaItem(string filePath, int index, DataModel.MediaItem data) {
      ACore = ACore = (AppCore) Application.Current.Properties[nameof(AppProps.AppCore)];
      FilePath = filePath;
      Index = index;

      if (data == null) return;
      Id = data.Id;
      DirId = data.DirectoryId;
      Comment = data.Comment;
      Rating = data.Rating;
      Orientation = data.Orientation;
      Data = data;
    }
Example #4
0
        private async void LoadPage()
        {
            _ProgressBar.IsIndeterminate = true;
            var res = await AppCore.InstaApi.GetUserTimelineFeedAsync(InstaSharper.Classes.PaginationParameters.MaxPagesToLoad(1));

            if (res.Info.Message == "login_required")
            {
                //AppCore.InstaApi = null;
                AppCore.SaveUserInfo(null, null, false);
                MainPage.MainFrame.GoBack();
                return;
            }
            var strs = await AppCore.InstaApi.GetStoryFeedAsync();

            StoriesList.ItemsSource = strs.Value.Items.OrderBy(x => x.Seen != 0);

            if (HomePageItemssource != null)
            {
                HomePageItemssource.CollectionChanged -= HomePageItemssource_CollectionChanged;
            }

            HomePageItemssource = new GenerateHomePage <InstaMedia>(100000, (count) =>
            {
                //return tres[count];
                return(new InstaMedia());
            });

            HomePageItemssource.CollectionChanged += HomePageItemssource_CollectionChanged;
            //MediasCVS.Source = HomePageItemssource;
            mylist.ItemsSource = HomePageItemssource;

            //await HomePageItemssource.LoadMoreItemsAsync(20);

            //mylist.ItemsSource = res.Value.Medias;

            //mylist.ItemsSource = res.Value.Medias;

            _ProgressBar.IsIndeterminate = false;
            var sv = FindChildOfType <ScrollViewer>(mylist);

            sv.ViewChanged += Sv_ViewChanged;
            //await Task.Delay(2000);
            //DirectFr.Navigate(typeof(DirectsListView));
            //MainPage.MainFrame.Navigate(typeof(DirectsListView));
        }
        public MediaItemsVM(Core core, AppCore coreVM, MediaItemsM model)
        {
            _core   = core;
            _coreVM = coreVM;
            Model   = model;

            #region Commands
            RotateCommand = new(
                Rotate,
                () => _core.ThumbnailsGridsM.Current?.FilteredItems.Count(
                    x => x.IsSelected && x.MediaType == MediaType.Image) > 0);

            RenameCommand = new(
                Rename,
                () => Model.Current != null);

            DeleteCommand = new(
                Delete,
                () => _core.ThumbnailsGridsM.Current?.SelectedItems.Count > 0 || _coreVM.AppInfo.AppMode == AppMode.Viewer);

            EditCommand = new(
                () => Model.IsEditModeOn = true,
                () => _core.ThumbnailsGridsM.Current?.FilteredItems.Count > 0);

            SaveEditCommand = new(
                SaveEdit,
                () => Model.IsEditModeOn && Model.ModifiedItems.Count > 0);

            CancelEditCommand = new(
                CancelEdit,
                () => Model.IsEditModeOn);

            CommentCommand = new(
                Comment,
                () => Model.Current != null);

            ReloadMetadataCommand = new(
                () => ReloadMetadata(_core.ThumbnailsGridsM.Current.GetSelectedOrAll()),
                () => _core.ThumbnailsGridsM.Current?.FilteredItems.Count > 0);

            ReloadMetadataInFolderCommand = new(
                ReloadMetadataInFolder,
                x => x != null);
            #endregion
        }
Example #6
0
        /// <summary>
        /// </summary>
        protected override void OnConfigurationApplied()
        {
            var hasSmsService = AppCore.Get <MessagingSMS.SMSService>() != null;

            if (!hasSmsService)
            {
                var cfg = GetConfigurationManipulator().GetEditable <WebCoreConfiguration>();
                switch (cfg.userAuthorizeAllowed)
                {
                case Core.Users.eUserAuthorizeAllowed.EmailAndPhone:
                case Core.Users.eUserAuthorizeAllowed.OnlyPhone:
                    cfg.userAuthorizeAllowed = Core.Users.eUserAuthorizeAllowed.OnlyEmail;
                    this.RegisterEvent(EventType.CriticalError, "Сервис рассылки СМС не найден - режим авторизации сброшен", "Не найден сервис рассылки СМС-сообщений. В связи с этим режим авторизации пользователей изменен на 'Только Email'.");
                    GetConfigurationManipulator().ApplyConfiguration(cfg);
                    break;
                }
            }
        }
Example #7
0
        /// <summary>
        /// </summary>
        protected override void OnModuleStarting()
        {
            RegisterPermission(PERM_SITEMAP, "Управление картой сайта");

            _sitemapTask = AppCore.Get <TaskSchedulingManager>().RegisterTask(new TaskRequest()
            {
                Name            = $"Карта сайта: генерация",
                Description     = "",
                IsEnabled       = true,
                TaskOptions     = TaskOptions.PreventParallelExecution | TaskOptions.AllowDisabling | TaskOptions.AllowManualSchedule,
                UniqueKey       = GetType().FullName + "_Execute",
                ExecutionLambda = () => Execute(),
                Schedules       = new List <TaskSchedule>()
                {
                    new TaskCronSchedule(Cron.Daily(5))
                }
            });
        }
Example #8
0
        /// <summary>
        /// Возвращает обратный адрес по-умолчанию для писем, для которых отправитель не задан явно.
        /// </summary>
        /// <returns></returns>
        public MailAddress GetDefaultOutgoingAddress()
        {
            var address = "no-reply@localhost";

            if (AppCore.ServerUrl != null)
            {
                address = "no-reply@" + AppCore.ServerUrl.Host;
            }

            var cfg = AppCore.Get <Module>().GetConfiguration <ModuleConfiguration>();

            if (!string.IsNullOrEmpty(cfg.OutgoingAddress))
            {
                address = cfg.OutgoingAddress;
            }

            return(new MailAddress(address, cfg.OutgoingName));
        }
Example #9
0
        /// <summary>
        /// Creates a new ChangeWorklocationViewModel
        /// </summary>
        /// <param name="page"> ChangeWorklocation</param>
        public ChangeWorklocationViewModel(ContentPage page)
        {
            this.page    = page;
            this.appcore = AppCore.Instance;

            MessagingCenter.Subscribe <AppCore, List <Model.Entity.Location> >(this, "ChooseWorkLocation", (sender, buildingList) =>
            {
                Debug.WriteLine("Empfangene Liste Größe " + buildingList.Count);
                this.buildings.Clear();
                foreach (Model.Entity.Location t in buildingList)
                {
                    this.buildings.Add(t);
                }
            });


            MessagingCenter.Send <ChangeWorklocationViewModel>(this, "ChangeWorklocationReady");
        }
Example #10
0
        protected override void OnNavigatedTo(NavigationEventArgs e)
        {
            base.OnNavigatedTo(e);
            if (e.NavigationMode != NavigationMode.Back)
            {
                AppCore.ModerateBack(Frame.GoBack);
            }
            if (StoryViewersItemssource != null)
            {
                StoryViewersItemssource.CollectionChanged -= StoryViewersItemssource_CollectionChanged;
            }

            StoryViewersItemssource = new GenerateStoryMediaViewers <User1>(100000, (count) => new User1(), e.Parameter.ToString());

            StoryViewersItemssource.CollectionChanged += StoryViewersItemssource_CollectionChanged;
            // MediasCVS.Source = HomePageItemssource;
            myList.ItemsSource = StoryViewersItemssource;
        }
Example #11
0
        public virtual ActionResult MonitorJournal(Guid?serviceGuid = null)
        {
            try
            {
                if (!serviceGuid.HasValue)
                {
                    throw new Exception("Не указан идентификатор сервиса.");
                }

                var serviceJournal = AppCore.Get <ServiceMonitor.Monitor>().GetServiceJournal(serviceGuid.Value);
                return(View("MonitorJournal.cshtml", serviceJournal.ToList()));
            }
            catch (Exception ex)
            {
                var answer = JsonAnswer();
                answer.FromException(ex);
                return(ReturnJson(answer));
            }
        }
Example #12
0
 protected override void OnNavigatedTo(NavigationEventArgs e)
 {
     base.OnNavigatedTo(e);
     if (e.NavigationMode != NavigationMode.Back)
     {
         AppCore.ModerateBack(Frame.GoBack);
     }
     if (PageItemssource != null)
     {
         PageItemssource.CollectionChanged -= PageItemssource_CollectionChanged;
     }
     PageItemssource = new GenerateUserFollowings <InstaUserShort>(100000, (count) =>
     {
         //return tres[count];
         return(new InstaUserShort());
     }, e.Parameter.ToString());
     PageItemssource.CollectionChanged += PageItemssource_CollectionChanged;
     myList.ItemsSource = PageItemssource;
 }
        public virtual ActionResult RolesManage()
        {
            var model = new Model.AdminRolesManage();

            using (var db = new CoreContext())
            {
                var permsQuery = (from p in db.RolePermission
                                  select new { p.IdRole, p.IdModule, p.Permission }
                                  ).Distinct();

                var perms = permsQuery.
                            ToList().
                            GroupBy(x => x.IdRole).
                            ToDictionary(x => x.Key,
                                         x => x.Select(p => string.Format("{0};{1}", p.IdModule, p.Permission)).ToList());


                model.Roles = db.Role
                              .OrderBy(x => x.NameRole)
                              .ToDictionary(x => x.IdRole,
                                            x => new Model.AdminRoleEdit(x)
                {
                    Permissions = perms.ContainsKey(x.IdRole) ? perms[x.IdRole] : new List <string>()
                });

                var mperms = new List <SelectListItem>();
                foreach (var module in AppCore.GetModulesManager().GetModules().OrderBy(x => x.Caption))
                {
                    var gr = new SelectListGroup()
                    {
                        Name = module.Caption
                    };
                    mperms.AddRange(module.GetPermissions().OrderBy(x => x.Caption).Select(x => new SelectListItem()
                    {
                        Group = gr,
                        Value = string.Format("{0};{1}", module.ID, x.Key),
                        Text  = x.Caption
                    }));
                }
                model.ModulesPermissions = mperms;
            }
            return(View("admin/admin_customer_rolesManage.cshtml", model));
        }
 public void Start()
 {
     if (_scope == null)
     {
         _core1 = AppCoreBuilder
             .Create()
             .AddModule(new RavenEmbeededDataStoreModule("Data") {RunInMemory = true})
             .AddModule<RavenRepositoriesModule>()
             .Configure(b =>
                 {
                     // Необходимо для работы AutofacCreationConverter
                     b.RegisterType<TestObject>().PropertiesAutowired();
                     //b.RegisterType<TestObject1>();
                 })
             .Build();
         _scope = _core1.BeginScope();
         //AutofacCreationConverter.Container = _core.Scope;
     }
 }
Example #15
0
        /// <summary>
        /// Initializes a new instance of the <see cref="T:HealthcareApp.View.ScanPage"/> class.
        /// When a Qr Code is scanned the result is handled in different methods.
        /// </summary>
        public ScanPage() : base()
        {
            appcore = AppCore.Instance;
            setRole();
            Title         = "QR Code scannen";
            OnScanResult += (result) =>
            {
                IsScanning = false;
                HandleResult(result.ToString());

                Device.BeginInvokeOnMainThread(() =>
                {
                    //Navigation.PopAsync();
                    DisplayAlert("Scanned QR Code", result.ToString(), "Close");
                    appcore.changeQRTasks(stringId);
                    Navigation.PushAsync(new TasksPage().CurrentPage = new QRTaskPage());
                });
            };
        }
Example #16
0
        /// <summary>
        /// Возвращает список контейнеров схем, зарегистрированных для текущего модуля.
        /// </summary>
        public Dictionary <ItemType, Dictionary <SchemeItem, string> > GetSchemeItemsList(int idModule)
        {
            var itemsGroups = new Dictionary <ItemType, Dictionary <SchemeItem, string> >();
            var module      = AppCore.GetModulesManager().GetModule(idModule) as IModuleCore;

            if (module == null)
            {
                return(null);
            }

            foreach (var itemType in module.GetItemTypes())
            {
                var items = new Dictionary <SchemeItem, string>();

                var _itemsPre = module.GetItems(itemType.IdItemType);
                var _items    = _itemsPre != null?_itemsPre.GetSimplifiedHierarchy() : new NestedCollectionSimplified();

                if (_items != null && _items.Count() > 0)
                {
                    foreach (var res in _items)
                    {
                        items[new SchemeItem(res.Key.ID, itemType.IdItemType)] = res.Value;
                    }
                }
                else
                {
                    items[new SchemeItem(0, itemType.IdItemType)] = "По-умолчанию";
                }

                if (!items.Any(x => x.Key.IdItem == 0 && x.Key.IdItemType == itemType.IdItemType))
                {
                    var items2 = new Dictionary <SchemeItem, string>();
                    items2[new SchemeItem(0, itemType.IdItemType)] = "По-умолчанию";
                    items.ForEach(x => items2.Add(x.Key, x.Value));
                    items = items2;
                }

                itemsGroups[itemType] = items;
            }

            return(itemsGroups);
        }
Example #17
0
        public JsonResult SchemeDelete(int IdScheme)
        {
            var result = JsonAnswer <int>();

            try
            {
                if (IdScheme == 0)
                {
                    result.Message = "Схема \"По-умолчанию\" не удаляется.";
                }
                else
                {
                    using (var db = this.CreateUnitOfWork())
                        using (var scope = db.CreateScope())
                        {
                            var data = db.CustomFieldsSchemes.Where(x => x.IdScheme == IdScheme).FirstOrDefault();
                            if (data == null)
                            {
                                throw new Exception(string.Format("Схема с номером '{0}' не найдена.", IdScheme));
                            }

                            db.CustomFieldsSchemeDatas.Where(x => x.IdScheme == IdScheme).Delete();
                            db.CustomFieldsSchemes.Where(x => x.IdScheme == IdScheme).Delete();

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

            return(ReturnJson(result));
        }
Example #18
0
        /// <summary>
        /// Регистрирует событие в журнал HTTP-кодов.
        /// </summary>
        /// <param name="code">Код HTTP ошибки</param>
        /// <param name="message">См. <see cref="JournalingManager.RegisterEvent(int, EventType, string, string, DateTime?, Exception)"/>.</param>
        /// <param name="messageDetailed">См. <see cref="JournalingManager.RegisterEvent(int, EventType, string, string, DateTime?, Exception)"/>.</param>
        /// <param name="ex">См. <see cref="JournalingManager.RegisterEvent(int, EventType, string, string, DateTime?, Exception)"/>.</param>
        internal protected void RegisterEventWithCode(HttpStatusCode code, string message, string messageDetailed = null, Exception ex = null)
        {
            var idJournal = _journalsForErrors.GetOrAddWithExpiration((int)code, GetJournalForErrors, TimeSpan.FromMinutes(5));

            var msg = $"URL запроса: {Request.Url}\r\n";

            if (Request.UrlReferrer != null)
            {
                msg += $"URL-referer: {Request.UrlReferrer}\r\n";
            }

            var context = AppCore.GetUserContextManager().GetCurrentUserContext();

            if (context.IsGuest)
            {
                msg += $"Пользователь: Гость\r\n";
            }
            else
            {
                msg += $"Пользователь: {context.GetData().ToString()} (id: {context.IdUser})\r\n";
            }

            if (!string.IsNullOrEmpty(Request.UserAgent))
            {
                msg += $"User-agent: {Request.UserAgent}\r\n";
            }
            var ipdns = new Dictionary <string, string>()
            {
                { "IP", Request.UserHostAddress }, { "DNS", Request.UserHostName }
            }.Where(x => !string.IsNullOrEmpty(x.Value)).ToList();

            if (ipdns.Count > 0)
            {
                msg += $"User {string.Join(" / ", ipdns.Select(x => x.Key))}: {string.Join("/", ipdns.Select(x => x.Value))}\r\n";
            }

            msg += messageDetailed;

            var errorType = (int)code == 500 ? EventType.CriticalError : EventType.Error;

            AppCore.Get <JournalingManager>().RegisterEvent(idJournal, errorType, message, msg, null, ex);
        }
Example #19
0
        protected override async void OnNavigatedTo(NavigationEventArgs e)
        {
            base.OnNavigatedTo(e);
            if (e.NavigationMode != NavigationMode.Back)
            {
                AppCore.ModerateBack(BackFunc);
            }
            DataContext = ((InstaDirectInboxThread)e.Parameter);
            var source = ((InstaDirectInboxThread)e.Parameter);

            ItemsList = new GenerateDirectThreadList <InstaDirectInboxItem>(100000, (count) => new InstaDirectInboxItem()
                                                                            , source.ThreadId);
            var message = await AppCore.InstaApi.GetDirectInboxThreadAsync(source.ThreadId, PaginationParameters.MaxPagesToLoad(1));

            VieweIds  = message.Value.VieweId;
            ThreadIds = message.Value.ThreadId;
            DataUser  = message.Value.Users[0];
            try
            {
                UserId = message.Value.Users[0].Pk;
            }
            catch
            {
                UserId = (await AppCore.InstaApi.GetCurrentUserAsync()).Value.Pk;
            }

            // MessageList.ItemsSource = Message.Value.Items;
            message.Value.Items.Reverse();
            // for (int a = 0; a < Message.Value.Items.Count; a++)
            // {
            //    MessageList.Items.Add(Message.Value.Items[a]);
            // }

            // foreach (InstaDirectInboxItem item in ItemsList)
            // {
            //    MessageList.Items.Insert(0, item);
            // }

            MessageList.ItemsSource = ItemsList;

            // var test = await AppCore.InstaApi.GetRecentRecipientsAsync();
        }
Example #20
0
        protected override void OnStarted()
        {
            try
            {
                using (var ctx = AppCore.Create <context>())
                {
                    var dd = ctx.Test.
                             WithMetadataObjectProperties().
                             AsNoTracking().
                             Take(2).
                             ToList();

                    var ddd = new Realty();
                    ctx.Test.Attach(ddd);
                }
            }
            catch (Exception ex)
            {
            }
        }
        /// <summary>
        /// Creates a new LoginViewModel
        /// </summary>
        /// <param name="page"> LoginPage</param>
        /// <param name="model">Model</param>
        public LoginViewModel(ContentPage page)
        {
            this.page         = page;
            this.LoginCommand = new Command(() => HandleLoginAsync());
            MessagingCenter.Subscribe <AppCore, bool>(this, "ServerConnectionChange", (sender, hasConnection) =>
            {
                if (hasConnection)
                {
                    this.Wlan = Color.Green; this.WlanCon = true;
                }
                else
                {
                    this.Wlan = Color.Red; this.WlanCon = false;
                }
            });

            MessagingCenter.Send <LoginViewModel>(this, "LoginReady");

            appcore = AppCore.Instance;
        }
Example #22
0
        private void OnModuleInitialized <TModuleType>(TModuleType module) where TModuleType : ModuleCore <TModuleType>
        {
            var controllerTypes = AppCore.GetBindedTypes <IModuleController <TModuleType> >();

            if (controllerTypes != null)
            {
                var controllerTypesSplitIntoTypes = controllerTypes.
                                                    Select(x => new { Type = x, Attribute = x.GetCustomAttribute <ModuleControllerAttribute>() }).
                                                    Where(x => x.Attribute != null).
                                                    GroupBy(x => x.Attribute.ControllerTypeID, x => x.Type).
                                                    Select(x => new { ControllerTypeID = x.Key, ControllerType = x.Last() }).
                                                    ToList();

                _moduleControllerTypesList[module.QueryType] = controllerTypesSplitIntoTypes.ToDictionary(x => x.ControllerTypeID, x => x.ControllerType);
            }
            else
            {
                _moduleControllerTypesList[module.QueryType] = new Dictionary <int, Type>();
            }
        }
Example #23
0
        /// <summary>
        /// Возвращает журнал для указанного идентификатора сервиса.
        /// </summary>
        public List <JournalData> GetServiceJournal(Guid serviceID)
        {
            if (_servicesJournalsList.TryGetValue(serviceID, out var serviceJournal))
            {
                var journalingManager = AppCore.Get <JournalingManager>();
                using (var db = new Journaling.DB.DataContext())
                {
                    var query = journalingManager.DatabaseAccessor.CreateQueryJournalData(db).
                                Where(x => x.JournalData.IdJournal == serviceJournal.IdJournal).
                                OrderByDescending(x => x.JournalData.DateEvent);

                    var data = journalingManager.DatabaseAccessor.FetchQueryJournalData(query);
                    return(data);
                }
            }
            else
            {
                return(new List <JournalData>());
            }
        }
Example #24
0
        public virtual ActionResult JournalDetails(int?IdJournal = null)
        {
            try
            {
                if (!IdJournal.HasValue)
                {
                    throw new Exception("Не указан идентификатор журнала.");
                }

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

                    var dbAccessor = AppCore.Get <JournalingDB.JournalingManagerDatabaseAccessor <WebApplication> >();

                    using (var db = new JournalingDB.DataContext())
                    {
                        int skip  = 0;
                        int limit = 100;

                        var query = dbAccessor.CreateQueryJournalData(db).Where(x => x.JournalData.IdJournal == result.Result.IdJournal).OrderByDescending(x => x.JournalData.DateEvent).Skip(skip).Take(limit);
                        var data  = dbAccessor.FetchQueryJournalData(query);
                        return(View("JournalDetails.cshtml", new Design.Model.JournalDetails()
                        {
                            JournalName = result.Result,
                            JournalData = data
                        }));
                    }
                }
            }
            catch (Exception ex)
            {
                var answer = JsonAnswer();
                answer.FromException(ex);
                return(ReturnJson(answer));
            }
        }
Example #25
0
        /// <summary>
        /// См. <see cref="ModuleAdmin.GetAdminMenuList(IUserContext)"/>.
        /// </summary>
        public override Dictionary <IModuleCore, NestedLinkCollection> GetAdminMenuList(IUserContext userContext)
        {
            var modulesList = AppCore.GetModulesManager().GetModules().OfType <IModuleCore>();
            var mods        = new Dictionary <IModuleCore, NestedLinkCollection>();
            var mods_errors = new Dictionary <IModuleCore, string>();

            foreach (var module in modulesList)
            {
                if (module.CheckPermission(userContext, ModulesConstants.PermissionManage) != CheckPermissionVariant.Allowed)
                {
                    mods_errors[module] = "Недостаточно прав";
                }
                else
                {
                    var links = module.GetAdminMenuItems();
                    if (links == null)
                    {
                        links = new NestedLinkCollection();
                    }

                    if (links.Count > 0)
                    {
                        if (module.CheckPermission(userContext, ModulesConstants.PermissionManage) == CheckPermissionVariant.Allowed)
                        {
                            mods[module] = links;
                        }
                        else
                        {
                            mods_errors[module] = "Недостаточно прав";
                        }
                    }
                }
            }

            var model = new Dictionary <IModuleCore, NestedLinkCollection>();

            mods.Where(x => x.Value.Count > 0).OrderBy(x => x.Key.Caption).ForEach(x => model[x.Key] = x.Value);
            mods_errors.OrderBy(x => x.Key.Caption).ForEach(x => model[x.Key].Add(new NestedLinkSimple(x.Value)));

            return(model);
        }
Example #26
0
        protected bool RegisterOutcomingMessage(TMessage message, out MessageInfo <TMessage> messageInfo)
        {
            try
            {
                var resolver = new Newtonsoft.Json.Serialization.DefaultContractResolver();
                resolver.DefaultMembersSearchFlags = resolver.DefaultMembersSearchFlags | System.Reflection.BindingFlags.NonPublic;

                using (var db = new DB.DataContext())
                {
                    var mess = new DB.MessageQueue()
                    {
                        IdMessageType = IdMessageType,
                        StateType     = DB.MessageStateType.NotProcessed,
                        Direction     = false,
                        DateCreate    = DateTime.Now,
                        MessageInfo   = Newtonsoft.Json.JsonConvert.SerializeObject(message, new Newtonsoft.Json.JsonSerializerSettings()
                        {
                            ContractResolver = resolver
                        }),
                    };

                    db.MessageQueue.Add(mess);
                    db.SaveChanges();

                    var taskOutcomingMessages = _taskOutcomingMessages;
                    if (taskOutcomingMessages != null)
                    {
                        AppCore.Get <TaskSchedulingManager>()?.ExecuteTask(taskOutcomingMessages);
                    }

                    messageInfo = new MessageInfo <TMessage>(new IntermediateStateMessage <TMessage>(message, mess));
                    return(true);
                }
            }
            catch (Exception ex)
            {
                this.RegisterEvent(Journaling.EventType.Error, "Ошибка регистрации исходящего сообщения", null, ex);
                messageInfo = null;
                return(false);
            }
        }
Example #27
0
        /// <summary>
        /// Возвращает список пользователей, облаюающих ролями с разрешением <paramref name="permissionKey"/> в модуле <typeparamref name="TModule"/>.
        /// </summary>
        /// <param name="permissionKey">См. <see cref="Permission.Key"/>.</param>
        /// <exception cref="ArgumentNullException">Возникает, если <paramref name="permissionKey"/> является пустой строкой или null.</exception>
        /// <exception cref="InvalidOperationException">Возникает, если в модуле <typeparamref name="TModule"/> не зарегистрировано разрешение <paramref name="permissionKey"/>.</exception>
        public List <User> GetUsersByRolePermission <TModule>(string permissionKey)
            where TModule : ModuleCore <TModule>
        {
            if (string.IsNullOrEmpty(permissionKey))
            {
                throw new ArgumentNullException(nameof(permissionKey));
            }

            var module = AppCore.Get <TModule>();

            if (module == null)
            {
                throw new InvalidOperationException("Указанный модуль не найден.");
            }

            if (!module.GetPermissions().Any(x => x.Key == permissionKey.GenerateGuid()))
            {
                throw new InvalidOperationException($"Модуль '{module.Caption}' не содержит разрешение '{permissionKey}'.");
            }

            try
            {
                using (var db = new CoreContext())
                {
                    var query = from permission in db.RolePermission
                                join role in db.Role on permission.IdRole equals role.IdRole
                                join userRole in db.RoleUser on role.IdRole equals userRole.IdRole
                                join user in db.Users on userRole.IdUser equals user.IdUser
                                where permission.Permission == permissionKey && permission.IdModule == module.IdModule
                                select user;

                    var data = query.ToList();
                    return(data);
                }
            }
            catch (Exception ex)
            {
                this.RegisterEvent(EventType.Error, "Ошибка получения списка пользователей", $"Список пользователей для разрешения '{permissionKey}'.", ex);
                throw;
            }
        }
Example #28
0
        private void BtnImgBrowser_Click(object sender, RoutedEventArgs e)
        {
            var dlg = new Microsoft.Win32.OpenFileDialog
            {
                Title           = "Select an Image",
                Filter          = "Images |*.jpg; *.png",
                CheckFileExists = true
            };

            if (dlg.ShowDialog() == true)
            {
                AsScanned  scan       = AppCore.CheckImage(dlg.FileName);
                AsListItem asListItem = new AsListItem
                {
                    Title = scan.Title,
                    Image = scan.Image,
                    Score = scan.Score
                };
                ImageList.Children.Add(asListItem);
            }
        }
Example #29
0
        public ActionResult logoutJson()
        {
            var success = false;
            var message = "";

            try
            {
                AppCore.GetUserContextManager().DestroyUserContext(AppCore.GetUserContextManager().GetCurrentUserContext());
                AppCore.Get <Binding.Providers.SessionBinder>().ClearUserContextFromRequest();
                AppCore.GetUserContextManager().ClearCurrentUserContext();
                success = true;
                message = "Выход прошел успешно.";
            }
            catch (Exception ex)
            {
                success = false;
                message = ex.Message;
            }

            return(this.ReturnJson(success, message, Module.GetRememberedUserContextRequestedAddressWhenRedirectedToAuthorization()));
        }
Example #30
0
        //  private List<DataPoint> _data_graf2;
        public void RunGraphsResultStrategy2(int min, int max, int pracovnikov1, int replikacii, int dlzka)
        {
            //_data_graf2 = new List<DataPoint>(max-min+1);
            // var a = new AppCore(new AutoserviceGenerators());
            for (int i = min; i <= max; i++)
            {
                if (!Graph2Break)
                {
                    var a = new AppCore(new AutoserviceGenerators());

                    a.NastavKonfiguraciu(pracovnikov1, i);
                    a.Gen = new AutoserviceGenerators();
                    a.SuperExtraUltraMode = true;
                    a.Refresh             = false;
                    a.Simulate(replikacii, dlzka);
                    RefreshWindowDispatcher();
                    UpdateGraph2(i, a.Results.Sg5PriemernySysteme);
                    RefreshWindowDispatcher();
                }
            }
        }
Example #31
0
        private static async Task Main(string[] args)
        {
            Ultralight.SetLogger(new Logger {
                LogMessage = Log
            });
            AppCore.EnablePlatformFontLoader();
            AppCore.EnablePlatformFileSystem("assets");

            var settings = new Settings();

            var config = new Config();

            config.SetEnableJavaScript(true);
            config.SetEnableImages(true);
            config.SetResourcePath("resources");
            config.SetCachePath("cache");
            config.SetUseGpuRenderer(true);

            var app     = new App(settings, config);
            var monitor = app.GetMainMonitor();

            uint windowWidth  = app.GetMainMonitor().GetWidth() - 100;
            uint windowHeight = app.GetMainMonitor().GetHeight() - 100;
            var  window       = new Window(monitor, windowWidth, windowHeight, false, WindowFlags.Titled);

            window.SetTitle("Super browser");
            app.SetWindow(window);

            var renderer = app.GetRenderer();
            var session  = new Session(renderer, false, "Session1");

            var mainView = new View(renderer, windowWidth, windowHeight, true, session);

            mainView.SetAddConsoleMessageCallback(JsConsoleMessage, default);
            mainView.LoadUrl("file:///index.html");
            var mainOverlay = new Overlay(window, mainView, 0, 0);

            mainOverlay.Show();
            app.Run();
        }
Example #32
0
        protected sealed override void OnStarting()
        {
            if (!AppCore.Get <DbSchemaManagerConfigure>().IsSchemaControlEnabled)
            {
                return;
            }

            try
            {
                using (var ctx = new Db.CoreContextBase())
                {
                    var isNeedToRun     = false;
                    var serviceProvider = new ServiceCollection().
                                          AddFluentMigratorCore().
                                          ConfigureRunner(rb =>
                    {
                        isNeedToRun = AppCore.DbConfigurationBuilder.OnConfigureFluentMigrator(rb);
                    }).
                                          Configure <RunnerOptions>(cfg => cfg.Profile = DbSchemaDefaultProfile.ProfileName).
                                          AddSingleton <IMigrationSource>(sp => this).
                                          AddSingleton <IMigrationRunnerConventions>(sp => new d()).
                                          AddSingleton <IProfileSource, DbSchemaProfileSource>().
                                          BuildServiceProvider(false);

                    using (var scope = serviceProvider.CreateScope())
                    {
                        var runner = serviceProvider.GetRequiredService <IMigrationRunner>();
                        if (isNeedToRun)
                        {
                            runner.MigrateUp();
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                _startErrors = new Exception[] { ex };
                Debug.WriteLine($"DbSchemaManager.OnStart: {ex}");
            }
        }
Example #33
0
        protected override void OnAfterApplicationStart()
        {
            try
            {
                var resourceManager         = AppCore.Get <Core.Storage.ResourceProvider>();
                var physicalApplicationPath = AppCore.ApplicationWorkingFolder;
                var paths = new List <string>();

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

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

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

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

                resourceManager.SourceDevelopmentPathList.AddRange(paths);

                //AppCore.Get<Journaling.JournalingManager>().SetJournalOptionsDefault(new Journaling.JournalOptions() { LimitByLastNDays = 30 });
                //  AppCore.Get<OnXap.Modules.MessagingEmail.EmailService>().SendMailFromSite(null, "*****@*****.**", "123", "23123123", OnXap.Modules.MessagingEmail.ContentType.Text);
            }
            catch (Exception ex)
            {
                Debug.WriteLine("OnAfterApplicationStart.Development: {0}", ex.Message);
                throw;
            }
        }
Example #34
0
        private IController CreateController(ControllerType controllerType, IModuleCore module, RouteValueDictionary routeValues)
        {
            var controllerTypes = AppCore.Get <ModuleControllerTypesManager>().GetModuleControllerTypes(module.QueryType);
            var targetType      = controllerTypes.GetValueOrDefault(controllerType.ControllerTypeID);

            if (targetType == null)
            {
                throw new NotSupportedException(controllerType.ErrorCannotFindControllerTypeSpecified(module, routeValues));
            }

            if (!controllerType.CheckPermissions(module, routeValues))
            {
                throw new ErrorCodeException(HttpStatusCode.Forbidden, "Отсутствует доступ.");
            }

            if (targetType != null)
            {
                return(CreateController(module, targetType, routeValues));
            }

            return(null);
        }
 public BaseTreeViewItem() {
   Items = new ObservableCollection<BaseTreeViewItem>();
   ACore = (AppCore) Application.Current.Properties[nameof(AppProps.AppCore)];
 }
Example #36
0
 public MediaItems() {
   ACore = (AppCore) Application.Current.Properties[nameof(AppProps.AppCore)];
   Items = new ObservableCollection<BaseMediaItem>();
 }
 public void Initialize(AppCore core, PlayerSettings player)
 {
     this.Life.Value = this.LifeMax;
     this.Player = player;
     this.Core = core;
 }