protected override void OnInitialized(EventArgs e)
        {
            base.OnInitialized(e);

            BtnAddPlayer.Click += BtnAddPlayer_Click;
            LstItems.ItemInvoked += LstItems_ItemInvoked;

            var items = new RangeObservableCollection<MediaPlayerViewModel>();
            var view = (ListCollectionView)CollectionViewSource.GetDefaultView(items);
            LstItems.ItemsSource = view;

            items.AddRange(_config.Configuration.MediaPlayers.Select(i => new MediaPlayerViewModel(i)));
        }
示例#2
0
        public SideMenuViewModel(ITheaterApplicationHost appHost, ISessionManager sessionManager, IImageManager imageManager, IApiClient apiClient)
        {
            _sessionManager = sessionManager;
            Users = new SideMenuUsersViewModel(sessionManager, imageManager, apiClient);
            CommandGroups = new RangeObservableCollection<SideMenuGroupViewModel>();
            UserCommandGroups = new RangeObservableCollection<SideMenuGroupViewModel>();

            IEnumerable<IMenuCommand> commands = appHost.GetExports<IMenuCommand>().ToList();
            
            IEnumerable<IGrouping<MenuCommandGroup, IMenuCommand>> commandGroups = commands.Where(c => c.Group != MenuCommandGroup.User).Where(c => !(c is IGlobalMenuCommand)).GroupBy(c => c.Group);
            CommandGroups.AddRange(commandGroups.OrderBy(g => g.Key.SortOrder).Select(g => new SideMenuGroupViewModel(g)));

            IEnumerable<IGrouping<MenuCommandGroup, IMenuCommand>> userCommandGroups = commands.Where(c => c.Group == MenuCommandGroup.User).Where(c => !(c is IGlobalMenuCommand)).GroupBy(c => c.Group);
            UserCommandGroups.AddRange(userCommandGroups.OrderBy(g => g.Key.SortOrder).Select(g => new SideMenuGroupViewModel(g)));

            sessionManager.UserLoggedIn += UserChanged;
            sessionManager.UserLoggedOut += UserChanged;
        }
        private void ReloadList(BaseItemDto item)
        {
            if (item == null)
            {
                _listItems.Clear();
                return;
            }

            // Record the current item
            var currentItem = _listCollectionView.CurrentItem as ItemPersonViewModel;

            var people = item.People ?? new BaseItemPerson[] { };

            int?selectedIndex = null;

            if (currentItem != null)
            {
                var index = Array.FindIndex(people, i => string.Equals(i.Name, currentItem.Name, StringComparison.OrdinalIgnoreCase));

                if (index != -1)
                {
                    selectedIndex = index;
                }
            }

            _listItems.Clear();

            _listItems.AddRange(people.Select(i => new ItemPersonViewModel(_apiClient, _imageManager)
            {
                ImageWidth  = ImageWidth,
                Person      = i,
                ImageHeight = ImageHeight
            }));

            if (selectedIndex.HasValue)
            {
                ListCollectionView.MoveCurrentToPosition(selectedIndex.Value);
            }
        }
        WhenCollectionIsCreatedWithRangeAndSingleItemAndSourceIsUpdatedWithRemoveRange_ThenSingleNotificationIsRaisedWithAllWrappers
            ()
        {
            var source        = new RangeObservableCollection <object>();
            var items         = new[] { new object() };
            var numberOfTimes = 0;

            var collection = new WrappingCollection(isBulk: true)
            {
                FactoryMethod = o => o
            };

            collection.AddSource(source);
            source.AddRange(items);
            collection.CollectionChanged += (sender, args) =>
            {
                args.OldItems.Should().BeEquivalentTo(items);
                numberOfTimes++;
                numberOfTimes.Should().Be(1);
            };
            source.RemoveRange(items);
        }
        public CompetitionRoundViewModel()
        {
            communicator = new Communicator();
            scores = new Scores();
            TestResults = new ObservableCollection<TestResultViewModel>
            {
                new TestResultViewModel { Name = "FirstTest" },
                new TestResultViewModel { Name = "SecondTest" },
                new TestResultViewModel { Name = "ThirdTest" },
                new TestResultViewModel { Name = "FourthTest" },
                new TestResultViewModel { Name = "FifthTest" }
            };

            uiUpdateTimer = new DispatcherTimer();
            uiUpdateTimer.Tick += UpdateResults;
            uiUpdateTimer.Interval = TimeSpan.FromMilliseconds(300);

            RoundAdminViewModel = new RoundAdminViewModel(this);
            ResetTests();

            Scores = new RangeObservableCollection<Score>();
            Scores.AddRange(scores.TheScores);
        }
示例#6
0
        public void ReloadChapters(BaseItemDto item)
        {
            if (item == null)
            {
                _listItems.Clear();
                return;
            }

            var chapters = item.Chapters ?? new List <ChapterInfoDto>();

            _listItems.Clear();

            _listItems.AddRange(chapters.Select(i => new ChapterInfoViewModel(_apiClient, _imageManager, _playback)
            {
                Chapter    = i,
                Item       = item,
                ImageWidth = ImageWidth
            }));

            if (StartPositionTicks.HasValue)
            {
                //SetPositionTicks(StartPositionTicks.Value);
            }
        }
示例#7
0
        private void ShowCategoriesVisibilityWindow()
        {
            var categoriesWindow = new CategoriesVisibility {
                DataContext = this
            };
            var allCategories = GetAllCategories(Categories);

            var currentCategoriesState =
                allCategories.Select(c => new CategoryVM(c.Model)
            {
                IsProductsHide = c.IsProductsHide
            }).ToList();

            if (categoriesWindow.ShowDialog() == true)
            {
                _nonVisibleCategories =
                    GetAllCategories(Categories).Where(c => c.IsProductsHide).Select(c => c.Model).ToList();
                if (!_isCategoriesVisibilitySetted)
                {
                    _tempSearchColl = new List <ProductVM>();
                    _tempSearchColl.AddRange(_searchColl);
                }
                var visibleProducts = GetVisibleProducts(_tempSearchColl);
                _searchColl.Clear();
                _searchColl.AddRange(visibleProducts);
                _isCategoriesVisibilitySetted = true;
            }
            else
            {
                allCategories.ForEach(
                    changedCategory =>
                    changedCategory.IsProductsHide =
                        currentCategoriesState.Find(c => c.Model.Id == changedCategory.Model.Id)
                        .IsProductsHide);
            }
        }
        public CompetitionRoundViewModel()
        {
            communicator = new Communicator();
            scores       = new Scores();
            TestResults  = new ObservableCollection <TestResultViewModel>
            {
                new TestResultViewModel {
                    Name = "FirstTest"
                },
                new TestResultViewModel {
                    Name = "SecondTest"
                },
                new TestResultViewModel {
                    Name = "ThirdTest"
                },
                new TestResultViewModel {
                    Name = "FourthTest"
                },
                new TestResultViewModel {
                    Name = "FifthTest"
                }
            };

            uiUpdateTimer          = new DispatcherTimer();
            uiUpdateTimer.Tick    += UpdateResults;
            uiUpdateTimer.Interval = TimeSpan.FromMilliseconds(300);

            RoundAdminViewModel = new RoundAdminViewModel(this);
            ResetTests();

            Scores = new RangeObservableCollection <Score>();
            Scores.AddRange(scores.TheScores);

            OpenLeaderboardCommand = new DelegateCommand(o => OpenLeaderboard());
            DrawWinnerCommand      = new DelegateCommand(o => DrawWinner());
        }
        public ColumnPickerViewModel(string identifier, IColumnsService columnsService, ISchedulerService schedulerService)
        {
            _identifier       = identifier;
            _columnsService   = columnsService;
            _schedulerService = schedulerService;

            _left  = new RangeObservableCollection <ColumnPickerItemViewModel>();
            _right = new RangeObservableCollection <ColumnPickerItemViewModel>();

            _columnsService.Initialised
            .ObserveOn(schedulerService.TaskPool)
            .StartWith(new [] { identifier })
            .Where(x => x == identifier)
            .Select(x =>
            {
                var visible = columnsService.VisibleColumns(identifier)
                              .Select(y => new ColumnPickerItemViewModel(y, ColumnHelper.DisplayName(y)))
                              .ToArray();

                var hidden = columnsService.HiddenColumns(identifier)
                             .Select(y => new ColumnPickerItemViewModel(y, ColumnHelper.DisplayName(y)))
                             .ToArray();

                return(new VisibleColumns(visible, hidden));
            })
            .ObserveOn(schedulerService.Dispatcher)
            .Subscribe(x =>
            {
                _left.Clear();
                _right.Clear();

                _left.AddRange(x.Hidden);
                _right.AddRange(x.Visible);
            })
            .DisposeWith(this);

            AddCommand = ReactiveCommand.Create(CanAddObservable())
                         .DisposeWith(this);

            RemoveCommand = ReactiveCommand.Create(CanRemoveObservable())
                            .DisposeWith(this);

            MoveupCommand = ReactiveCommand.Create(CanMoveupObservable())
                            .DisposeWith(this);

            MovedownCommand = ReactiveCommand.Create(CanMovedownObservable())
                              .DisposeWith(this);

            AddCommand.ActivateGestures()
            .Subscribe(x => Add())
            .DisposeWith(this);

            RemoveCommand.ActivateGestures()
            .Subscribe(x => Remove())
            .DisposeWith(this);

            MoveupCommand.ActivateGestures()
            .Subscribe(x => Moveup())
            .DisposeWith(this);

            MovedownCommand.ActivateGestures()
            .Subscribe(x => Movedown())
            .DisposeWith(this);
        }
        public void AddIndexOptions(IEnumerable <TabItem> options)
        {
            _indexOptions.AddRange(options);

            OnPropertyChanged("HasIndexOptions");
        }
示例#11
0
 public SideMenuGroupViewModel(IEnumerable<IMenuCommand> commands)
 {
     Buttons = new RangeObservableCollection<SideMenuButtonViewModel>();
     Buttons.AddRange(commands.OrderBy(c => c.SortOrder).Select(c => new SideMenuButtonViewModel(c)));
 }
示例#12
0
 void PasteItemDatas(List<ItemData> copys, ItemData selectedItem, RangeObservableCollection<ItemData> itemsSource, Point clickPoint)
 {
     var list = new List<ItemData>();
     var item = selectedItem;
     if (selectedItem != null)
     {
         var roots = copys.Where(x => x.ItemParentId == item.ItemId);
         foreach (var itemData in roots)
         {
             if (itemData.ItemParentId.IsNullOrEmpty())
             {
                 itemData.Left = clickPoint.X;
                 itemData.Top = clickPoint.Y;
             }
             list.Add(itemData);
             list.AddRange(AddChild(copys, itemData));
         }
         itemsSource.AddRange(list);
     }
     else
     {
         var roots = copys.Where(x => copys.All(y => y.ItemId != x.ItemParentId));
         foreach (var r in roots)
         {
             if (r.ItemParentId.IsNullOrEmpty())
             {
                 r.Left = clickPoint.X;
                 r.Top = clickPoint.Y;
             }
             r.ItemParentId = string.Empty;
             list.Add(r);
             list.AddRange(AddChild(copys, r));
         }
         itemsSource.AddRange(list);
     }
 }
示例#13
0
 private void _load()
 {
     _items.AddRange(BackupEngine.Instance.GetBackups().Select(p => new BackupView(p)));
 }
        private void LoadPluginSettingsList(IEnumerable<ISettingsPage> allSettingsPages)
        {
            var items = new RangeObservableCollection<ISettingsPage>();
            var view = (ListCollectionView)CollectionViewSource.GetDefaultView(items);

            PluginMenuList.ItemsSource = view;

            var pages = allSettingsPages
                .Where(i => i.Category == SettingsPageCategory.Plugin);

            items.AddRange(pages);

            TxtPluginSettings.Visibility =
                GridPluginSettings.Visibility = items.Count == 0 ? Visibility.Collapsed : Visibility.Visible;
        }
示例#15
0
        private void GetAnalyse()
        {
            _grid.DetailConfigurations.Clear();
            _viewSource.DisposeChildren();
            _viewSource.Clear();

            if (!dateStart.SelectedDate.HasValue || !dateEnd.SelectedDate.HasValue)
            {
                Manager.UI.ShowMessage("Необходимо корректно задать начальную и конечную даты!");
                progress.Abort();
                return;
            }

            #region проверяем входящие параметры

            HashSet <int> uspds;
            HashSet <int> tis;
            var           filterObjectsList = GetSelectedObjects(true, out uspds, out tis);
            if (filterObjectsList != null && filterObjectsList.Count == 0 && tis != null && tis.Count == 0)
            {
                Manager.UI.ShowMessage("Необходимо выбрать хотя бы один объект или ТИ для мониторинга!");
                progress.Abort();
                return;
            }

            switch (
                ValidHelper.Valid(enumTimeDiscreteType.DBHours, 1000, dateEnd.SelectedDate.Value - dateStart.SelectedDate.Value,
                                  new Tuple <Xceed.Wpf.Controls.DatePicker, Xceed.Wpf.Controls.DatePicker>(dateStart, dateEnd), GetAnalyse)
                )
            {
            case enumRestartAfterValid.Abort:
                //Ошибка входящих параметров
                progress.Abort();
                return;

            case enumRestartAfterValid.Restart:
                return;
            }

            #endregion

            DateTime    dtStart;
            DateTime    dtEnd;
            double?     maxValue;
            bool        isConcentratorsEnabled;
            bool        isMetersEnabled;
            List <int>  selectedEvents;
            List <byte> selectedСhannels;

            GetParamsFromForm(out dtStart, out dtEnd, out maxValue, out isConcentratorsEnabled, out isMetersEnabled, out selectedEvents, out selectedСhannels);

            this.RunAsync(() => GetObjectsForAnalys(filterObjectsList, uspds, tis, dtStart, dtEnd, maxValue, isConcentratorsEnabled, isMetersEnabled, selectedEvents, selectedСhannels),
                          monitoringFactory =>
            {
                if (monitoringFactory == null || _grid == null)
                {
                    progress.Abort();
                    return;
                }

                ConfigureGrid(monitoringFactory.DtStart, monitoringFactory.DtEnd, monitoringFactory.IsConcentratorsEnabled, monitoringFactory.IsMetersEnabled);
                _viewSource.AddRange(monitoringFactory.MonitoringAnalyseDict.Values);

                var settings = VisualEx.GetModuleSettings(this);
                if (settings != null)
                {
                    Manager.Config.SaveModulesSettingsCompressed(this.GetType().Name, settings);
                }

                progress.Value   = 0;
                progress.Maximum = monitoringFactory.MonitoringAnalyseDict.Count;
                //Собрали в таблицу информацию по шлюзам и концентраторам
                //Теперь собираем информацию по ПУ для этих объектов
                worker = new BackgroundWorker {
                    WorkerSupportsCancellation = true
                };
                worker.DoWork             += WorkerDoWork;
                worker.RunWorkerCompleted += WorkerCompleted;
                worker.RunWorkerAsync(monitoringFactory);
            });
        }
        public IFreeHierarchyObject UpdateSource(List <Info_Balance_FreeHierarchy_Description> descriptions, Dispatcher dispatcher,
                                                 Action onFieldChanged, out bool isAdded)
        {
            isAdded = false;

            //List<Info_Balance_FreeHierarchy_Description> descriptions = null;

            if (_balance != null && descriptions == null)
            {
                descriptions = ARM_Service.BL_GetFreeHierarchyBalanceDescritions(_balance.BalanceFreeHierarchy_UN);
            }

            var sections = ARM_Service.BL_GetFreeHierarchyBalanceSections(BalanceFreeHierarchyTypeID);

            if (sections == null || sections.Count == 0)
            {
                Manager.UI.ShowMessage("Не описаны разделы для данного типа баланса!");
                return(null);
            }

            var source = new List <BalanceFreeHierarchySectionRow>();
            var isExistsDescription = descriptions != null && descriptions.Count > 0;
            var tps        = EnumClientServiceDictionary.GetTps();
            var isFirst    = true;
            var isFirstRow = true;

            IFreeHierarchyObject result = null;

            foreach (var section in sections.Where(s => s.UseInTotalResult))
            {
                var row = new BalanceFreeHierarchySectionRow(section, dispatcher);
                if (isFirst)
                {
                    row.IsSelected = true;
                    isFirst        = false;
                }

                if (isExistsDescription)
                {
                    //Если есть описание данного баланса
                    foreach (var description in descriptions.Where(d => string.Equals(d.BalanceFreeHierarchySection_UN, section.BalanceFreeHierarchySection_UN)).OrderBy(d => d.SortNumber))
                    {
                        var isIntegral = false;
                        IFreeHierarchyObject hierarchyObject = null;
                        if (description.TI_ID.HasValue)
                        {
                            TInfo_TI ti;
                            if (!EnumClientServiceDictionary.TIHierarchyList.TryGetValue(description.TI_ID.Value, out ti) || ti == null)
                            {
                                continue;
                            }
                            hierarchyObject = ti;
                        }
                        if (description.IntegralTI_ID.HasValue)
                        {
                            isIntegral = true;
                            TInfo_TI ti;
                            if (!EnumClientServiceDictionary.TIHierarchyList.TryGetValue(description.IntegralTI_ID.Value, out ti) || ti == null)
                            {
                                continue;
                            }
                            hierarchyObject = ti;
                        }
                        else if (description.TP_ID.HasValue && tps != null)
                        {
                            TPoint tp;
                            if (!tps.TryGetValue(description.TP_ID.Value, out tp) || tp == null)
                            {
                                continue;
                            }
                            hierarchyObject = tp;
                        }
                        else if (!string.IsNullOrEmpty(description.Formula_UN) && EnumClientServiceDictionary.FormulasList != null)
                        {
                            var formula = EnumClientServiceDictionary.FormulasList[description.Formula_UN];
                            hierarchyObject = formula;
                        }
                        else if (!string.IsNullOrEmpty(description.OurFormula_UN))
                        {
                            TFormulaForSection formula;
                            if (!EnumClientServiceDictionary.FormulaFsk.TryGetValue(description.OurFormula_UN, out formula) || formula == null)
                            {
                                continue;
                            }
                            hierarchyObject = formula;
                        }
                        else if (!string.IsNullOrEmpty(description.ContrFormula_UN))
                        {
                            TFormulaForSection formula;
                            if (!EnumClientServiceDictionary.FormulaCA.TryGetValue(description.ContrFormula_UN, out formula) || formula == null)
                            {
                                continue;
                            }
                            hierarchyObject = formula;
                        }
                        else if (description.PTransformator_ID.HasValue)
                        {
                            var transformator = EnumClientServiceDictionary.GetOrAddTransformator(description.PTransformator_ID.Value, null);
                            hierarchyObject = transformator;
                        }
                        else if (description.PReactor_ID.HasValue)
                        {
                            var reactor = EnumClientServiceDictionary.GetOrAddReactor(description.PReactor_ID.Value, null);
                            hierarchyObject = reactor;
                        }
                        else if (description.Section_ID.HasValue)
                        {
                            var      hierarhicalSections = EnumClientServiceDictionary.GetSections();
                            TSection hierarhicalSection;
                            if (hierarhicalSections != null && hierarhicalSections.TryGetValue(description.Section_ID.Value, out hierarhicalSection))
                            {
                                hierarchyObject = hierarhicalSection;
                            }
                        }
                        else if (!string.IsNullOrEmpty(description.FormulaConstant_UN))
                        {
                            var formulaConstant = EnumClientServiceDictionary.FormulaConstantDictionary[description.FormulaConstant_UN];
                            hierarchyObject = formulaConstant;
                        }

                        if (hierarchyObject == null)
                        {
                            continue;
                        }

                        var itemRows = FindDescriptions(description, row, dispatcher);
                        if (itemRows != null)
                        {
                            itemRows.Add(new BalanceFreeHierarchyItemRow(hierarchyObject, description.ChannelType, description.Coef ?? 1, onFieldChanged,
                                                                         description.SortNumber, itemRows, isIntegral, (EnumDataSourceType?)description.DataSource_ID));
                        }

                        //Раскрываем дерево на первом объекте баланса
                        if (isFirstRow)
                        {
                            //fhTree.Dispatcher.BeginInvoke((Action)(() =>
                            //{
                            //    var freeHierTreeId = FormulaEditor_Frame.FindTreeByObjectType(hierarchyObject);
                            //    fhTree.ReloadTree(freeHierTreeId, hierarchyObject: hierarchyObject);
                            //}), DispatcherPriority.Background);

                            result = hierarchyObject;

                            isAdded    = true;
                            isFirstRow = false;
                        }
                    }
                }

                source.Add(row);
            }

            dispatcher.BeginInvoke((Action)(() => Source.AddRange(source)));

            //if (!isAdded)
            //{
            //    Task.Factory.StartNew(() =>
            //    {
            //        Thread.Sleep(100);
            //        //Раскрываем дерево на родителе баланса
            //        fhTree.Dispatcher.BeginInvoke((Action)(() =>
            //           fhTree.ExpandAndSelect(_hierarchyObject, true)), DispatcherPriority.ContextIdle);
            //    });
            //}

            return(result);
        }
        private void ProcessMetadata(IEnumerable <IMetadataViewModel> viewModels)
        {
            DisposeOfMetadata();

            _metadata.AddRange(viewModels);
        }
        private async Task ReloadItems(bool isInitialLoad)
        {
            if (HasIndexOptions && CurrentIndexOption == null)
            {
                return;
            }

            if (ShowLoadingAnimation)
            {
                _presentationManager.ShowLoadingAnimation();
            }

            try
            {
                var result = await _getItemsDelegate(this);

                var items = result.Items;

                int?selectedIndex = null;

                if (isInitialLoad && AutoSelectFirstItem)
                {
                    selectedIndex = 0;
                }

                MedianPrimaryImageAspectRatio = result.Items.MedianPrimaryImageAspectRatio();

                _listItems.Clear();

                var imageTypes = GetPreferredImageTypes();

                var childWidth         = Convert.ToInt32(ImageDisplayWidth);
                var imageDisplayHeight = Convert.ToInt32(GetImageDisplayHeight());

                var viewModels = items.Select(
                    i =>
                {
                    var vm = new ItemViewModel(_apiClient, _imageManager, _playbackManager,
                                               _presentationManager, _logger, _serverEvents)
                    {
                        DownloadPrimaryImageAtExactSize = DownloadImageAtExactSize ?? IsCloseToMedianPrimaryImageAspectRatio(i),
                        ImageHeight = imageDisplayHeight,
                        ImageWidth  = childWidth,
                        Item        = i,
                        ViewType    = ViewType,
                        DisplayName = DisplayNameGenerator == null ? i.Name : DisplayNameGenerator(i),
                        DownloadImagesAtExactSize = DownloadImageAtExactSize ?? true,
                        PreferredImageTypes       = imageTypes,
                        ListType  = ListType,
                        ShowTitle = ShowTitle
                    };

                    var stretch = ImageStretch;

                    if (!stretch.HasValue && imageTypes.Length > 0)
                    {
                        var exact = imageTypes[0] == ImageType.Primary ? vm.DownloadPrimaryImageAtExactSize : vm.DownloadImagesAtExactSize;
                        stretch   = exact ? Stretch.UniformToFill : Stretch.Uniform;
                    }

                    if (stretch.HasValue)
                    {
                        vm.ImageStretch = stretch.Value;
                    }

                    return(vm);
                }
                    ).ToList();

                _listItems.AddRange(viewModels);

                ItemCount = items.Length;

                UpdateContainerSizes();

                if (selectedIndex.HasValue)
                {
                    ListCollectionView.MoveCurrentToPosition(selectedIndex.Value);
                }
            }
            catch (Exception)
            {
                _presentationManager.ShowDefaultErrorMessage();
            }
            finally
            {
                if (ShowLoadingAnimation)
                {
                    _presentationManager.HideLoadingAnimation();
                }
            }
        }
示例#19
0
        private void InitializeFilterCommands()
        {
            SearchCommand = new ActionCommand(async() =>
            {
                await Task.Run(() =>
                {
                    Busy();
                    RangeObservableCollection <PatientModel> patients = null;
                    if (String.IsNullOrWhiteSpace(SearchText))
                    {
                        patients =
                            new RangeObservableCollection <PatientModel>(
                                Context.Patients.Local.Select(PatientSelector));
                    }
                    else if (StepNameFilter != null)
                    {
                        patients =
                            new RangeObservableCollection <PatientModel>(
                                Context.Patients.Local.Where(
                                    e => (e.FirstName.ToLower() + " " + e.LastName.ToLower())
                                    .Contains(SearchText.ToLower()) && e.CurrentStep.StepName == StepNameFilter)
                                .Select(PatientSelector));
                    }

                    else
                    {
                        patients =
                            new RangeObservableCollection <PatientModel>(
                                Context.Patients.Local.Where(
                                    e => (e.FirstName.ToLower() + " " + e.LastName.ToLower())
                                    .Contains(SearchText.ToLower()))
                                .Select(PatientSelector));
                    }
                    ShowCanceled  = true;
                    ShowCompleted = true;
                    ShowOngoing   = true;
                    ShowOverDue   = true;
                    Patients      = patients;
                    Free();
                });
            });
            ReverseSortCommand = new ActionCommand(async() =>
            {
                await Task.Run(() =>
                {
                    Busy();
                    Patients = new RangeObservableCollection <PatientModel>(Patients.Reverse());
                    Free();
                });
            });
            FilterStepCommand = new ActionCommand(async() =>
            {
                await Task.Run(() =>
                {
                    RangeObservableCollection <PatientModel> patients = null;
                    Busy();
                    if (StepNameFilter != null)
                    {
                        patients =
                            new RangeObservableCollection <PatientModel>(
                                Context.Patients.OrderByDescending(e => e.Id)
                                .Where(e => e.CurrentStep.StepName == StepNameFilter).Select(PatientSelector));
                    }
                    else
                    {
                        patients =
                            new RangeObservableCollection <PatientModel>(
                                Context.Patients.OrderByDescending(e => e.Id).Select(PatientSelector));
                    }
                    Patients      = patients;
                    ShowCanceled  = true;
                    ShowCompleted = true;
                    ShowOngoing   = true;
                    ShowOverDue   = true;
                    Free();
                });
            });
            FilterPatientsCommand = new ActionCommand(async obj =>
            {
                ShowWindowCommand.Execute(null);
                await Task.Run(() =>
                {
                    var patients = new RangeObservableCollection <PatientModel>();

                    Busy();

                    if (obj is int)
                    {
                        BusyMessage = "Loading Patient";
                        Locator.SinglePatientViewModel.Patient = Patients.First(e => e.Id == (int)obj);
                    }
                    else
                    {
                        BusyMessage   = "Loading Patients";
                        ShowOngoing   = false;
                        ShowCanceled  = false;
                        ShowCompleted = false;
                        patients.AddRange(OverDuePatients.OrderBy(e => e.Id));
                        Patients = patients;
                    }

                    Free();
                });
            });
            FilterCnacled = new ActionCommand(async() =>
            {
                var patients = new RangeObservableCollection <PatientModel>();

                await Task.Run(() =>
                {
                    Busy();
                    BusyMessage = "Applying Filter";
                    if (ShowCanceled)
                    {
                        patients.AddRange(Patients);
                        patients.AddRange(
                            Context.Patients.Local.Where(e => e.CurrentStep.IsCancled).Select(PatientSelector));
                        patients =
                            new RangeObservableCollection <PatientModel>(
                                patients.OrderByDescending(e => e.Id));
                    }
                    else
                    {
                        for (int i = 0; i < Patients.Count; i++)
                        {
                            PatientModel patient = Patients[i];
                            if (!patient.CurrentStep.IsCancled)
                            {
                                patients.Add(patient);
                            }
                        }
                    }
                    Patients = patients;
                    Free();
                });
            });
            FilterCompleted = new ActionCommand(async() =>
            {
                var patients = new RangeObservableCollection <PatientModel>();

                await Task.Run(() =>
                {
                    Busy();
                    BusyMessage = "Applying Filter";
                    if (ShowCompleted)
                    {
                        patients.AddRange(Patients);
                        patients.AddRange(
                            Context.Patients.Local.Where(e => e.CurrentStep.IsCompleted).Select(PatientSelector));
                        patients =
                            new RangeObservableCollection <PatientModel>(
                                patients.OrderByDescending(e => e.Id));
                    }
                    else
                    {
                        for (int i = 0; i < Patients.Count; i++)
                        {
                            PatientModel patient = Patients[i];
                            if (!patient.CurrentStep.IsCompleted)
                            {
                                patients.Add(patient);
                            }
                        }
                    }
                    Patients = patients;
                    Free();
                });
            });
            FilterOngoing = new ActionCommand(async() =>
            {
                var patients = new RangeObservableCollection <PatientModel>();

                await Task.Run(() =>
                {
                    Busy();
                    BusyMessage = "Applying Filter";
                    if (ShowOngoing)
                    {
                        patients.AddRange(Patients);
                        patients.AddRange(
                            Context.Patients.Local.Where(e => e.CurrentStep.Status == Status.Ongoing)
                            .Select(PatientSelector));
                        patients =
                            new RangeObservableCollection <PatientModel>(
                                patients.OrderByDescending(e => e.Id));
                    }
                    else
                    {
                        for (int i = 0; i < Patients.Count; i++)
                        {
                            PatientModel patient = Patients[i];
                            if (patient.CurrentStep.Status != Status.Ongoing)
                            {
                                patients.Add(patient);
                            }
                        }
                    }
                    Patients = patients;
                    Free();
                });
            });

            FilterOverdue = new ActionCommand(async() =>
            {
                var patients = new RangeObservableCollection <PatientModel>();
                await Task.Run(() =>
                {
                    Busy();
                    BusyMessage = "Applying Filter";
                    if (ShowOverDue)
                    {
                        patients.AddRange(Patients);
                        patients.AddRange(
                            Context.Patients.Local.Where(e => e.CurrentStep.Status == Status.Overdue)
                            .Select(PatientSelector));
                        patients =
                            new RangeObservableCollection <PatientModel>(
                                patients.OrderByDescending(e => e.Id));
                    }
                    else
                    {
                        for (int i = 0; i < Patients.Count; i++)
                        {
                            PatientModel patient = Patients[i];
                            if (patient.CurrentStep.Status != Status.Overdue)
                            {
                                patients.Add(patient);
                            }
                        }
                    }
                    Patients = patients;
                    Free();
                });
            });
        }
示例#20
0
        private async Task PopulateUserList()
        {
            fullUserList.Clear();
            var server = LocatorService.DiscordSocketClient.GetGuild(selectedGuildId);

            await Task.Run(() => {
                List <UserListSectionModel> tmpOffline = new List <UserListSectionModel>();
                List <UserListSectionModel> tmpOnline  = new List <UserListSectionModel>();

                SortedDictionary <IRole, List <UserListSectionModel> > tmpUserSort = new SortedDictionary <IRole, List <UserListSectionModel> >();

                foreach (var user in server.Users)
                {
                    Color roleColor = Color.Default;

                    // todo: figure out how to pick 'highest' role and take that color
                    // this seems to work for the time being though
                    IRole foundRole = null;
                    foreach (var role in user.Roles)
                    {
                        roleColor = role.Color;
                        if (role.IsHoisted)
                        {
                            foundRole = role;
                        }
                    }
                    if (user.Status == UserStatus.Offline || user.Status == UserStatus.Unknown)
                    {
                        tmpOffline.Add(new UserListSectionModel {
                            AvatarUrl        = user.GetAvatarUrlOrDefault(),
                            CurrentlyPlaying = user.Game.HasValue ? user.Game.Value.Name : "",
                            StatusColor      = user.Status.ToWinColor(),
                            Username         = String.IsNullOrEmpty(user.Nickname) ? user.Username : user.Nickname,
                            UserRoleColor    = roleColor.ToWinColor(),
                            Id       = user.Id,
                            IsBot    = user.IsBot,
                            Nickname = user.Nickname
                        });
                        continue;
                    }
                    if (foundRole == null)
                    {
                        tmpOnline.Add(new UserListSectionModel {
                            AvatarUrl        = user.GetAvatarUrlOrDefault(),
                            CurrentlyPlaying = user.Game.HasValue ? user.Game.Value.Name : "",
                            StatusColor      = user.Status.ToWinColor(),
                            Username         = String.IsNullOrEmpty(user.Nickname) ? user.Username : user.Nickname,
                            UserRoleColor    = roleColor.ToWinColor(),
                            Id       = user.Id,
                            IsBot    = user.IsBot,
                            Nickname = user.Nickname
                        });
                    }
                    else
                    {
                        if (!tmpUserSort.ContainsKey(foundRole))
                        {
                            tmpUserSort[foundRole] = new List <UserListSectionModel>();
                        }
                        tmpUserSort[foundRole].Add(new UserListSectionModel {
                            AvatarUrl        = user.GetAvatarUrlOrDefault(),
                            CurrentlyPlaying = user.Game.HasValue ? user.Game.Value.Name : "",
                            StatusColor      = user.Status.ToWinColor(),
                            Username         = user.Username,
                            UserRoleColor    = roleColor.ToWinColor(),
                            Id       = user.Id,
                            IsBot    = user.IsBot,
                            Nickname = user.Nickname
                        });
                    }
                }
                // todo: can we use DeferRefresh here instead of this other range thing?
                // or is that advancedcollectionview specific?
                DispatcherHelper.CheckBeginInvokeOnUI(() => {
                    foreach (var key in tmpUserSort.Keys)
                    {
                        fullUserList.Add(new UserListSectionModel {
                            RoleSectionName = key.Name,
                            NumUsers        = (uint)tmpUserSort[key].Count,
                        });

                        fullUserList.AddRange(tmpUserSort[key]);
                    }
                    if (tmpOnline.Count > 0)
                    {
                        fullUserList.Add(new UserListSectionModel {
                            RoleSectionName = "Online",
                            NumUsers        = (uint)tmpOnline.Count
                        });
                        fullUserList.AddRange(tmpOnline.OrderBy(x => x.Username));
                    }
                    if (tmpOffline.Count > 0)
                    {
                        fullUserList.Add(new UserListSectionModel {
                            RoleSectionName = "Offline",
                            NumUsers        = (uint)tmpOffline.Count
                        });
                        fullUserList.AddRange(tmpOffline.OrderBy(x => x.Username));
                    }
                });
            });
        }
        private void LoadSystemSettingsList(IEnumerable<ISettingsPage> allSettingsPages)
        {
            var items = new RangeObservableCollection<ISettingsPage>();
            var view = (ListCollectionView)CollectionViewSource.GetDefaultView(items);

            MenuList.ItemsSource = view;

            var pages = allSettingsPages
                .Where(i => i.Category == SettingsPageCategory.System);

            items.AddRange(pages);
        }