Пример #1
0
        public SearchClientsViewModel(List<ClientEntity> clientEntities, bool reservationMode = false)
        {
            _pcs = new PropertyChangeSupport(this);
            _title = "Resotel - Recherche de client";

            if(reservationMode)
            {
                _title = "Resotel - Recherche de réservation";
            }

            _searchClientVMs = new ObservableCollection<SearchClientViewModel>();
            _searchClientVMsSource = CollectionViewProvider.Provider(_searchClientVMs);
            _searchClientVMsView = _searchClientVMsSource.View;
            _searchClientVMsView.Filter = _filterClientNameOrFirstName;
            _searchClientVMsView.CurrentChanged += _client_selected;

            HashSet<string> clientKeys = new HashSet<string>();

            foreach(ClientEntity clientEntity in clientEntities)
            {
                if (clientKeys.Add($"{clientEntity.FirstName}{clientEntity.LastName}"))
                {
                    SearchClientViewModel clientSearchVM = new SearchClientViewModel(clientEntity, clientEntities);
                    _searchClientVMs.Add(clientSearchVM);
                    clientSearchVM.ClientSelected += _subClient_selected;
                }
            }
        }
Пример #2
0
 public WhatsNewViewModel()
 {
     _tabs = new ObservableCollection<ITab<object>>();
     _tabs.Add(ServiceLocator.Current.TryResolve<WhatsNewTabItemView>());
     _tabs.Add(ServiceLocator.Current.TryResolve<TopListsTabItemView>());
     _tabsIcv = new ListCollectionView(_tabs);
 }
 public MultiChoiceFeature(IProjectService projectService, IEnumerable<IFeatureItem> items)
 {
     this.projectService = projectService;
     this.items = new ObservableCollection<IFeatureItem>(items);
     this.itemsView = CollectionViewSource.GetDefaultView(this.items);
     this.itemsView.SortDescriptions.Add(new SortDescription(nameof(IFeatureItem.Order), ListSortDirection.Ascending));
 }
        public WorldViewModel()
        {
            _undoManager = new UndoManager(this);
            _clipboard = new ClipboardManager(this);
            World.ProgressChanged += OnProgressChanged;
            Brush.BrushChanged += OnPreviewChanged;
            UpdateTitle();

            _spriteFilter = string.Empty;
            _spritesView = CollectionViewSource.GetDefaultView(World.Sprites);
            _spritesView.Filter = o =>
            {
                var sprite = o as Sprite;
                if (sprite == null || string.IsNullOrWhiteSpace(sprite.TileName))
                    return false;

                return sprite.TileName.IndexOf(_spriteFilter, StringComparison.InvariantCultureIgnoreCase) >= 0 ||
                       sprite.Name.IndexOf(_spriteFilter, StringComparison.InvariantCultureIgnoreCase) >= 0;
            };

            _saveTimer.AutoReset = true;
            _saveTimer.Elapsed += SaveTimerTick;
            // 3 minute save timer
            _saveTimer.Interval = 3 * 60 * 1000;

            // Test File Association and command line
            if (Application.Current.Properties["OpenFile"] != null)
            {
                string filename = Application.Current.Properties["OpenFile"].ToString();
                LoadWorld(filename);
            }
        }
		public void SelectAllItems(ICollectionView availableItemsCollectionView)
		{
			if (availableItemsCollectionView.SourceCollection is ICollection<Store>)
			{
				availableItemsCollectionView.Cast<Store>().ToList().ForEach(x => SelectItem(x));
			}
		}
Пример #6
0
        public GridViewModel()
        {
            ResultData = new ObservableCollection<TestPointDataObject>();

            //get the unique test points
            var definedTestPoints = _resultValueTags.Where(dt => dt.Name.ToLower().Contains("testpoint")).GroupBy(dt => dt.Name.Split('.').First()).Select(grp => grp.First().Name.Split('.').First());
            //var q2 = _resultValueTags.Where(dt => Regex.Match(dt.Name.Split('.').Single((s) => s.Contains("test")), @"(testpoint)[\d+]", RegexOptions.IgnoreCase).Success);

            //Add the test point with a header value of it's number.
            foreach (string tp in definedTestPoints)
                ResultData.Add(new TestPointDataObject(Regex.Match(tp,@"[\d+]").Value));

            foreach (DataTag tag in _resultValueTags.Where(dt => dt.Name.ToLower().Contains("testpoint")))
                ResultData.ElementAt(Convert.ToInt32(Regex.Match(tag.Name, @"[\d+]").Value) - 1).Results.Add(new ResultDataObject(tag.Name,tag.Double));

            foreach (DataTag tag in _results)
            {
                tag.ValueChanged += Tag_ValueChanged;
                tag.ValueSet += Tag_ValueSet;
            }

            foreach (var v in ResultData)
            {

                _view = CollectionViewSource.GetDefaultView(v.Results);
                _view.GroupDescriptions.Add(new PropertyGroupDescription("Name", new ResultNameGrouper()));
            }
        }
        public TextFilterService(ICollectionView collectionView, TextBox textBox)
            : this()
        {
            string filterText = String.Empty;

            _collectionView = collectionView;

            collectionView.Filter = delegate(object obj)
                                        {
                                            if ( (obj is ServiceCategory)
                                                || string.IsNullOrEmpty(filterText))
                                            {
                                                return true;
                                            }

                                            Service service = obj as Service;

                                            if (service == null || string.IsNullOrEmpty(service.Name))
                                            {
                                                return false;
                                            }

                                            return
                                                service.Name.IndexOf(filterText, 0, StringComparison.CurrentCultureIgnoreCase) >=
                                                0;
                                        };

            textBox.TextChanged += delegate
                                       {
                                           filterText = textBox.Text;
                                           _keyTime.Start();
                                       };
        }
Пример #8
0
        public SortViewModel(ICollectionView source, SortData[] columns, IEnumerable<SortDescription> existing = null,
            SortData[] requiredColumns = null) {
            View = source;
            Columns = columns;
            _requiredColumns = requiredColumns ?? new SortData[0];
            if (existing != null) {
                var d = View.DeferRefresh();
                SortDescriptions.Clear();
                foreach (var c in _requiredColumns)
                    SortDescriptions.Add(c.ToSortDescription());
                var item = existing
                    .FirstOrDefault(x => Columns.Select(y => y.Value).Contains(x.PropertyName));
                if (item != default(SortDescription)) {
                    SelectedSort = Columns.First(x => x.Value == item.PropertyName);
                    SelectedSort.SortDirection = item.Direction;
                    SortDescriptions.Add(item);
                }

                d.Dispose();
            } else {
                var item = SortDescriptions.FirstOrDefault(x => Columns.Select(y => y.Value).Contains(x.PropertyName));
                if (item != default(SortDescription)) {
                    SelectedSort = Columns.First(x => x.Value == item.PropertyName);
                    SelectedSort.SortDirection = item.Direction;
                }
            }

            OldSelectedSort = SelectedSort;

            this.WhenAnyValue(x => x.SelectedSort)
                .Skip(1)
                .Subscribe(x => SortColumn());
            this.SetCommand(x => x.SortCommand).Subscribe(x => SortColumn());
            this.SetCommand(x => x.ToggleVisibilityCommand).Subscribe(x => ToggleVisibility());
        }
Пример #9
0
        public static void RestoreSorting(DataGridSortDescription sortDescription, DataGrid grid, ICollectionView view)
        {
            if (sortDescription.SortDescription != null && sortDescription.SortDescription.Count == 0)
            {
                if (Core.Settings.Default.CacheListEnableAutomaticSorting)
                {
                    if (Core.Settings.Default.CacheListSortOnColumnIndex >= 0 && Core.Settings.Default.CacheListSortOnColumnIndex < grid.Columns.Count)
                    {
                        SortDescription sd = new SortDescription(grid.Columns[Core.Settings.Default.CacheListSortOnColumnIndex].SortMemberPath, Core.Settings.Default.CacheListSortDirection == 0 ? ListSortDirection.Ascending : ListSortDirection.Descending);
                        sortDescription.SortDescription.Add(sd);
                    }
                }
            }
            //restore the column sort order
            if (sortDescription.SortDescription != null && sortDescription.SortDescription.Count > 0)
            {
                sortDescription.SortDescription.ToList().ForEach(x => view.SortDescriptions.Add(x));
                view.Refresh();
            }

            //restore the sort directions. Arrows are nice :)
            foreach (DataGridColumn c in grid.Columns)
            {
                if (sortDescription.SortDirection.ContainsKey(c))
                {
                    c.SortDirection = sortDescription.SortDirection[c];
                }
            }
        }
        public CustomerInfoSearch(ICollectionView filteredList, TextBox textEdit)
        {
            string filterText = string.Empty;

            filteredList.Filter = delegate(object obj)
            {
                if (String.IsNullOrEmpty(filterText))
                {
                    return true;
                }
                ModelCustomer str = obj as ModelCustomer;
                if (str.UserName==null)
                {
                    return true;
                }
                if (str.UserName.ToUpper().Contains(filterText.ToUpper()))
                {
                    return true;
                }
                else
                {
                    return false;
                }
            };
            textEdit.TextChanged += delegate
            {
                filterText = textEdit.Text;
                filteredList.Refresh();
            };
        }
Пример #11
0
 public void DataBind(DataSet lDataSet)
 {
     this.mDataSet = lDataSet;
     this.mDataView = mDataSet.Tables["i9Attachment"].DefaultView;
     this.mCollectionView = CollectionViewSource.GetDefaultView(mDataSet.Tables["i9Attachment"]);
     this.DataContext = mDataView;
 }
        // <summary>
        // Basic ctor
        // </summary>
        public SubPropertyEditor() 
        {
            _quickTypeCollection = new ObservableCollection<NewItemFactoryTypeModel>();

            _quickTypeView = CollectionViewSource.GetDefaultView(_quickTypeCollection);
            _quickTypeView.CurrentChanged += new EventHandler(OnCurrentQuickTypeChanged);
        }
Пример #13
0
        /// <summary>
        /// コンストラクタ
        /// </summary>
        public MainWindow()
        {
            InitializeComponent();

            DataContext = _vm;

            // データのフィルータリング、ソートを設定する。
            // ただし、CollecionView を使用すると、
            // StaffList をバインドしたすべてのコレクションに影響を与える。
            _staffCollectionView = CollectionViewSource.GetDefaultView(_vm.StaffList);

            // フィルター条件の設定
            _staffCollectionView.Filter = x =>
            {
                var staff = x as Staff;
                if (staff != null)
                {
                    if (SelectedFilterRole == Role.All)
                    {
                        // "All" 選択時は全スタッフ表示
                        return true;
                    }

                    //該当する役割のスタッフだけ表示する。
                    return staff.Role == SelectedFilterRole;
                }

                return true;
            };

            // ソート条件の設定
            // 年功序列とする。
            // 新たにデータが追加されてもこのソート条件は有効
            _staffCollectionView.SortDescriptions.Add(new SortDescription("Age", ListSortDirection.Descending));
        }
Пример #14
0
        public TextFilter(ICollectionView filteredView, TextBox box)
        {
            string filterText = "";

            filteredView.Filter = delegate(object obj)
            {
                if (string.IsNullOrEmpty(filterText))
                    return true;

                string str = obj as string;

                if (obj is IFilterable)
                    str = ((IFilterable)obj).FilterString;

                if (string.IsNullOrEmpty(str))
                    return false;

                return str.IndexOf(filterText, 0, StringComparison.InvariantCultureIgnoreCase) >= 0;
            };

            box.TextChanged += delegate {
                filterText = box.Text;
                filteredView.Refresh();
            };
        }
Пример #15
0
        public TextSearchFilter(
            ICollectionView filterView,
            TextBox textbox)
        {
            string filterText = "";

            filterView.Filter = delegate(object obj)
            {
                if (String.IsNullOrEmpty(filterText))
                    return true;

                Stream stream = obj as Stream;
                if (stream == null)
                    return false;

                String streamText = stream.Title + stream.Genre + stream.Description;

                int index = streamText.IndexOf(filterText, 0, StringComparison.InvariantCultureIgnoreCase);

                return index > -1;
            };

            textbox.TextChanged += delegate
            {
                filterText = textbox.Text;
                filterView.Refresh();
            };
        }
        protected LibraryGroupViewModel(string header, string addHeader = null, string icon = null) {
            Header = header;
            AddHeader = addHeader;
            Icon = icon;
            if (!Execute.InDesignMode)
                this.SetCommand(x => x.AddCommand);

            Children = new ReactiveList<IHierarchicalLibraryItem>();
            IsExpanded = true;

            this.WhenAnyValue(x => x.SelectedItemsInternal)
                .Select(x => x == null ? null : x.CreateDerivedCollection(i => (IHierarchicalLibraryItem) i))
                .BindTo(this, x => x.SelectedItems);


            UiHelper.TryOnUiThread(() => {
                Children.EnableCollectionSynchronization(_childrenLock);
                _childrenView =
                    Children.CreateCollectionView(
                        new[] {
                            new SortDescription("SortOrder", ListSortDirection.Ascending),
                            new SortDescription("Model.IsFavorite", ListSortDirection.Descending),
                            new SortDescription("Model.Name", ListSortDirection.Ascending)
                        }, null,
                        null, null, true);
                _itemsView = _childrenView;
            });
        }
Пример #17
0
        private async void ButtonLogin_Click(object sender, RoutedEventArgs e)
        {
            if (string.IsNullOrWhiteSpace(TextBoxUserName.Text) || string.IsNullOrWhiteSpace(TextBoxPassword.Password) || string.IsNullOrWhiteSpace(TextBoxBlogName.Text))
            {
                GridHost.RenderTransform.BeginAnimation(ScaleTransform.ScaleXProperty, new DoubleAnimation(1, 1.1, TimeSpan.FromMilliseconds(200)) { AutoReverse = true });
                return;
            }

            GridLoading.Visibility = Visibility.Visible;
            t = new Tumblr(TextBoxUserName.Text, TextBoxPassword.Password, TextBoxBlogName.Text);

            if (!await t.Login())
            {
                GridLoading.Visibility = Visibility.Collapsed;
                GridHost.RenderTransform.BeginAnimation(ScaleTransform.ScaleXProperty, new DoubleAnimation(1, 1.1, TimeSpan.FromMilliseconds(200)) { AutoReverse = true });
                return;
            }

            await t.GetThemes().ContinueWith(c => { ListBoxThemeFilter = CollectionViewSource.GetDefaultView(c.Result); });
            ListBoxTheme.ItemsSource = ListBoxThemeFilter;
            ListBoxTheme.SelectedIndex = 0;

            GridLoading.Visibility = Visibility.Collapsed;
            BeginAnimation(HeightProperty, new DoubleAnimation(Height, 550, TimeSpan.FromSeconds(1)));

            GridLogin.Visibility = Visibility.Collapsed;
            GridThemes.Visibility = Visibility.Visible;
        }
        /// <summary>
        /// Remove a handler for the given source's event.
        /// </summary>
        public static void RemoveHandler(ICollectionView source, EventHandler<CurrentChangingEventArgs> handler)
        {
            if (handler == null)
                throw new ArgumentNullException("handler");

            CurrentManager.ProtectedRemoveHandler(source, handler);
        }
        public void Start()
        {
            // Setup the event stream subscription
            MyPushEventProvider eventProvider = new MyPushEventProvider();

            collectionView = CollectionViewSource.GetDefaultView(processes);
            collectionView.SortDescriptions.Add(new SortDescription("Name", ListSortDirection.Ascending));

            subscription = (from processInfo in eventProvider.ProcessInformation
                            select processInfo)
                            .AsObservable()
                            .OnErrorResumeNext(eventProvider.ProcessInformation.AsObservable())
                            .ObserveOnDispatcher()
                            .Subscribe(message => {
                                // Update the process if it exists
                                if (processes.Any(p => p.ProcessId == message.ProcessId)) {
                                    processes.Where(p => p.ProcessId == message.ProcessId).ToList().ForEach(
                                        x => x.Update(message));
                                }
                                else {
                                    // Otherwise add it
                                    processes.Add(message);
                                }
                            },
                            () => processes.Clear()); // Clear the table when complete
        }
Пример #20
0
        private void btn_serarch_Click(object sender, RoutedEventArgs e)
        {
            string selectedPartner ="";
            string selectedDeal = "";
            if(cb_partner.SelectedItem!=null)
                selectedPartner= ((string)cb_partner.SelectedItem);
            if(cb_deal.SelectedItem!=null)
                selectedDeal = ((string)cb_deal.SelectedItem);

            var q = from x in Databases.localModel.OrderSet
                    where x.Deal!=null &&
                          x.Deleted == false &&
                          x.Billing_data.Name.Contains(tb_billingName.Text) &&
                          x.Shipping_data.Name.Contains(tb_shippingName.Text) &&
                          x.External_Id.Contains(tb_externalId.Text) &&
                          x.Id.Contains(tb_innerId.Text) &&
                          ((x.Billing_data.City+x.Billing_data.Address).Contains(tb_address.Text) || (x.Shipping_data.City+x.Shipping_data.Address).Contains(tb_address.Text)) &&
                          (x.Partner_site.Name.Contains(selectedPartner) || selectedPartner=="Összes") &&
                          (x.Deal.Name.Contains(selectedDeal) || selectedDeal =="Összes")
                    select x;

            _orders = q.ToList();
            cvOrders = CollectionViewSource.GetDefaultView(_orders);

            dataGrid.ItemsSource = cvOrders;
            cvOrders = CollectionViewSource.GetDefaultView(dataGrid.ItemsSource);
        }
 protected override void OnSourceChanged(object oldSource, object newSource)
 {
     base.OnSourceChanged(oldSource, newSource);
     _defaultView = GetDefaultView(newSource);
     _count = _defaultView.SourceCollection.Count();
     LoadHashset();
 }
Пример #22
0
 /// <summary>
 /// Constructor</summary>
 /// <param name="service">Palette service</param>
 public PaletteContent(IPaletteService service)
 {
     m_paletteService = service;
     m_dataView = CollectionViewSource.GetDefaultView(m_items);
     m_dataView.GroupDescriptions.Add(new PropertyGroupDescription("Category"));
     // Add sort?
 }
Пример #23
0
        public VMInnerRooms(Network Server)
        {
            _Server = Server;

            VMRooms rooms = new VMRooms(_Server);
            VMCreateRoom cr_room = new VMCreateRoom(_Server);
            VMRoom room = new VMRoom(_Server);

            rooms.moveTo += new EventHandler<MoveToEventArgs>(Inner_moveTo);
            cr_room.moveTo += new EventHandler<MoveToEventArgs>(Inner_moveTo);
            room.moveTo  += new EventHandler<MoveToEventArgs>(Inner_moveTo);

            cr_room.roomCreation += new EventHandler<RoomEventArgs>(room.roomAssociation);
            rooms.roomJoin += new EventHandler<RoomEventArgs>(room.roomAssociation);

            ViewModels = new ObservableCollection<ViewModelBase>()
            {
                rooms,
                cr_room,
                room
            };

            
            ViewModelView = CollectionViewSource.GetDefaultView(ViewModels);
        }
Пример #24
0
        public LibraryWindowViewModel() 
        {
            view = CollectionViewSource.GetDefaultView(LibraryItems);

            LibraryItems = new System.Collections.ObjectModel.ObservableCollection<string>(iservice.Files);
            iservice.Start();
            iservice.FilesUpdated += new EventHandler<EventArgs<IList<string>>>(iservice_FilesUpdated);

            this.PropertyChanged += (s, ea) => 
                System.Diagnostics.Debug.WriteLine(ea.PropertyName + " changed to " + 
                    this.GetType().GetProperty(ea.PropertyName).GetValue(this,null));

            Observable.FromEventPattern<System.ComponentModel.PropertyChangedEventArgs>(this, "PropertyChanged")
                .Where(et => et.EventArgs.PropertyName == "SearchString")
                .Throttle(TimeSpan.FromMilliseconds(250))
                .Subscribe(_ => {
                    System.Diagnostics.Debug.WriteLine("search string changed");
                    
                    if (SearchString.Trim() == string.Empty)
                        view.Filter = null;
                    else
                        view.Filter = o => Regex.IsMatch(o as string, SearchString, RegexOptions.IgnoreCase);
                        
                    view.Refresh();
                    FilteredLibraryItemsCount = LibraryItems.Where(o => Regex.IsMatch(o as string, SearchString, RegexOptions.IgnoreCase)).Count();
                });

            //Observable.FromEventPattern<System.ComponentModel.PropertyChangedEventArgs>(this, "PropertyChanged")
            //    .Where(et => et.EventArgs.PropertyName == "LibraryItems")
            //    .Do(et => view = CollectionViewSource.GetDefaultView(LibraryItems));
            
            

        }
        public TextFilterMucAffs(ICollectionView[] collectionViews, TextBox textBox)
            : this()
        {
            string filterText = String.Empty;

            _collectionViews = collectionViews;

            foreach (ICollectionView collectionView in _collectionViews)
            {
                collectionView.Filter = delegate(object obj)
                                            {
                                                MucAffContact mucAffContact = obj as MucAffContact;

                                                if (mucAffContact == null || string.IsNullOrEmpty(mucAffContact.Jid))
                                                {
                                                    return false;
                                                }

                                                return
                                                    mucAffContact.Jid.IndexOf(filterText, 0, StringComparison.CurrentCultureIgnoreCase) >= 0;
                                            };

                textBox.TextChanged += delegate
                                           {
                                               filterText = textBox.Text;
                                               _keyTime.Start();
                                           };
            }
        }
        private void BuildMultiMaterialMeshesCollectionView()
        {
            _multiMaterialMeshesCollectionView = CollectionViewSource.GetDefaultView(MeshFile.MultiMaterialMeshFiles);
            _multiMaterialMeshesCollectionView.Filter = FilterMultiMaterialMeshes;

            OnPropertyChanged(() => MultiMaterialMeshesCollectionView);
        }
Пример #27
0
    internal async Task LoadImages()
    {
      if (_ == null || _.Length == 0)
        return;
      if (_initialized)
        return;
      _initialized = true;
      IsBusying = true;

      await Task.WhenAll(_.Select(DescribeImage)).ConfigureAwait(false);
      IsBusying = false;

      await DispatcherHelper.UIDispatcher.BeginInvoke((Action)(() =>
      {
        _coll_images = new FeedImages();
      }), System.Windows.Threading.DispatcherPriority.ContextIdle);
      foreach (var i in _)
      {
        var c = i;
        if (c.duration != 0)
          continue;
        await DispatcherHelper.UIDispatcher.BeginInvoke((Action)(() => _coll_images.Add(new ImageUnitViewModel(c))), System.Windows.Threading.DispatcherPriority.ContextIdle);
      }
      await DispatcherHelper.UIDispatcher.BeginInvoke((Action)(() =>
      {
        Images = CollectionViewSource.GetDefaultView(_coll_images);
      }), System.Windows.Threading.DispatcherPriority.ContextIdle);

      IsReady = true;
    }
Пример #28
0
 // Methods
 internal CollectionViewGroupRoot(ICollectionView view, bool isDataInGroupOrder)
     : base("Root", null)
 {
     this._groupBy = new ObservableCollection<GroupDescription>();
     this._view = view;
     this._isDataInGroupOrder = isDataInGroupOrder;
 }
Пример #29
0
        public TextSearchFilter(ICollectionView filteredView, TextBox textBox)
        {
            string filterText = "";

           /* filteredView.Filter = delegate(object obj)
            {

                if (string.IsNullOrEmpty(filterText))
                    return true;

                string str = obj as string;

                if (string.IsNullOrEmpty(str))
                    return false;

                int index = str.IndexOf(filterText, 0, StringComparison.CurrentCultureIgnoreCase);

                return index > -1;

            };
            textBox.TextChanged += delegate
            {
                filterText = textBox.Text;
                filteredView.Refresh();
            };**/
        }
Пример #30
0
        public FilterRoster(ICollectionView collectionView, TextBox searchBox)
        {
            _collectionView = collectionView;
            _refreshTimer.IsEnabled = false;
            _refreshTimer.Interval = new TimeSpan(0, 0, 0, 0, 500);

            Settings.Default.PropertyChanged += delegate(object sender, PropertyChangedEventArgs e)
                                                    {
                                                        switch (e.PropertyName)
                                                        {
                                                            case "UI_DisplayOfflineContacts":
                                                            case "UI_DisplayServices":
                                                                {
                                                                    _displayOffline =
                                                                        Settings.Default.UI_DisplayOfflineContacts;

                                                                    _displayServices =
                                                                        Settings.Default.UI_DisplayServices;

                                                                    Refresh();
                                                                    break;
                                                                }
                                                        }
                                                    };

            searchBox.TextChanged += delegate
                                         {
                                             _refreshTimer.Stop();
                                             _refreshTimer.Start();
                                         };

            collectionView.Filter = delegate(object obj)
                                        {
                                            IContact contact = obj as IContact;

                                            if (contact == null)
                                            {
                                                return false;
                                            }

                                            if (!_displayServices && contact.IsService)
                                            {
                                                return false;
                                            }

                                            bool contains =
                                                contact.SearchLowerText.Contains(searchBox.Text.ToLower());

                                            if (contact.IsAvailable)
                                            {
                                                return contains;
                                            }
                                            else
                                            {
                                                return _displayOffline && contains;
                                            }
                                        };

            _refreshTimer.Tick += _refreshTimer_Tick;
        }
Пример #31
0
        private void PopulateData()
        {
            SelectedBuilding    = _settlementPage.SelectedBuildingName.Name;
            InvoiceSum          = Math.Ceiling(_settlementPage.SettledInvoices.Select(x => x.CostAmount).DefaultIfEmpty(0).Sum() * 100) / 100;
            ApartmentsAmount    = _settlementPage.ApartmentCollection.Where(x => !x.IsDeleted && x.SoldDate == null && x.BuildingId.Equals(_settlementPage.SelectedBuildingName.BuildingId)).Count();
            SettlementCattegory = _settlementPage.SettlementCategoryName.CategoryName;

            if (_settlementPage.SettlementMethod == SettlementMethodsEnum.PER_APARTMENT)
            {
                var notRounded = InvoiceSum / ApartmentsAmount;
                SettlePerApartment     = (Math.Ceiling(notRounded * 100)) / 100;
                PerApartmentCollection = new ObservableCollection <ApartamentMeterDataGrid>();
                foreach (var a in Apartments.Where(x => !x.IsDeleted && x.SoldDate == null && x.BuildingId.Equals(_settlementPage.SelectedBuildingName.BuildingId)))
                {
                    decimal chargeAmount = 0;
                    var     c            = Charges.Where(x => x.ApartmentId.Equals(a.ApartmentId) && x.ChargeDate >= _settlementPage.SettlementFrom && x.ChargeDate <= _settlementPage.SettlementTo);
                    foreach (var cc in c)
                    {
                        chargeAmount += cc.Components.Where(y => _settlementPage.SettleChargeCategories.Any(x => x.BuildingChargeBasisCategoryId.Equals(y.CostCategoryId))).Select(x => x.Sum).DefaultIfEmpty(0).Sum();
                    }

                    PerApartmentCollection.Add(new ApartamentMeterDataGrid()
                    {
                        ApartmentO  = a,
                        Charge      = chargeAmount,
                        OwnerO      = Owners.FirstOrDefault(x => x.OwnerId.Equals(a.OwnerId)),
                        CostSettled = SettlePerApartment,
                        Saldo       = chargeAmount - SettlePerApartment,
                    });
                }

                ICollectionView cv = (CollectionView)CollectionViewSource.GetDefaultView(PerApartmentCollection);
                cv.SortDescriptions.Clear();
                cv.SortDescriptions.Add(new SortDescription("ApartmentO.ApartmentNumber", ListSortDirection.Ascending));
                cv.GroupDescriptions.Clear();
                cv.GroupDescriptions.Add(new PropertyGroupDescription(""));
            }

            if (_settlementPage.SettlementMethod == SettlementMethodsEnum.PER_AREA)
            {
                BuildingAreaSum      = Math.Ceiling((Apartments.Where(x => x.BuildingId.Equals(_settlementPage.SelectedBuildingName.BuildingId)).Select(x => new { totalArea = x.AdditionalArea + x.ApartmentArea }).Sum(x => x.totalArea) * 100)) / 100;
                SettlePerSquareMeter = Math.Ceiling((InvoiceSum / Convert.ToDecimal(BuildingAreaSum)) * 100) / 100;
                PerAreaCollection    = new ObservableCollection <ApartamentMeterDataGrid>();

                foreach (var a in Apartments.Where(x => !x.IsDeleted && x.SoldDate == null && x.BuildingId.Equals(_settlementPage.SelectedBuildingName.BuildingId)))
                {
                    decimal chargeAmount = 0;
                    var     c            = Charges.Where(x => x.ApartmentId.Equals(a.ApartmentId) && x.ChargeDate >= _settlementPage.SettlementFrom && x.ChargeDate <= _settlementPage.SettlementTo);
                    foreach (var cc in c)
                    {
                        chargeAmount += cc.Components.Where(y => _settlementPage.SettleChargeCategories.Any(x => x.BuildingChargeBasisCategoryId.Equals(y.CostCategoryId))).Select(x => x.Sum).DefaultIfEmpty(0).Sum();
                    }

                    PerAreaCollection.Add(new ApartamentMeterDataGrid()
                    {
                        SettleArea  = (a.AdditionalArea + a.ApartmentArea),
                        ApartmentO  = a,
                        Charge      = chargeAmount,
                        OwnerO      = Owners.FirstOrDefault(x => x.OwnerId.Equals(a.OwnerId)),
                        CostSettled = SettlePerSquareMeter * Convert.ToDecimal((a.AdditionalArea + a.ApartmentArea)),
                        Saldo       = chargeAmount - SettlePerSquareMeter * Convert.ToDecimal((a.AdditionalArea + a.ApartmentArea)),
                    });
                }

                ICollectionView cv = (CollectionView)CollectionViewSource.GetDefaultView(PerAreaCollection);
                cv.SortDescriptions.Clear();
                cv.SortDescriptions.Add(new SortDescription("ApartmentO.ApartmentNumber", ListSortDirection.Ascending));
                cv.GroupDescriptions.Clear();
                cv.GroupDescriptions.Add(new PropertyGroupDescription(""));
            }

            if (_settlementPage.SettlementMethod == SettlementMethodsEnum.PER_METERS)
            {
                var ap = Apartments.Where(x => !x.IsDeleted && x.SoldDate == null && x.SoldDate == null && x.BuildingId.Equals(_settlementPage.SelectedBuildingName.BuildingId) && x.MeterCollection != null && x.MeterCollection.Count > 0);
                int notValidMetersCount = ap.Where(x => x.MeterCollection.FirstOrDefault(y => !y.IsDeleted && y.MeterTypeParent.MeterId.Equals(_settlementPage.SelectedMeterName.MeterId)).LegalizationDate <= DateTime.Now).Count();

                MainMeterDiff    = _settlementPage.MainMeterDiff;
                ApartmentDiffSum = Convert.ToDecimal(_settlementPage.ApartmentMetersCollection.Where(x => x.IsMeterLegalized).Select(x => x.MeterDifference).DefaultIfEmpty(0).Sum()) + _settlementPage.NoMeterConstantAdjustment * notValidMetersCount;
                ApartmentsAmount = _settlementPage.ApartmentCollection.Where(x => !x.IsDeleted && x.SoldDate == null && x.BuildingId.Equals(_settlementPage.SelectedBuildingName.BuildingId)).Count();
                BuildingAreaSum  = Math.Ceiling((Apartments.Where(x => x.BuildingId.Equals(_settlementPage.SelectedBuildingName.BuildingId)).Select(x => new { totalArea = x.AdditionalArea + x.ApartmentArea }).Sum(x => x.totalArea) * 100)) / 100;


                decimal measureToDivide     = Convert.ToDecimal(MainMeterDiff);
                decimal deficitPerApartment = 0;
                if (!_settlementPage.ChargeDeficit)
                {
                    if (MainMeterDiff > 0)
                    {
                        measureToDivide = Math.Min(Convert.ToDecimal(MainMeterDiff), ApartmentDiffSum);
                    }
                    else
                    {
                        measureToDivide = ApartmentDiffSum;
                    }
                }
                else
                {
                    if (Convert.ToDecimal(MainMeterDiff) > ApartmentDiffSum)
                    {
                        deficitPerApartment = (Convert.ToDecimal(MainMeterDiff) - ApartmentDiffSum) / notValidMetersCount;
                    }
                }

                var adjustedInvoiceSum = InvoiceSum - (notValidMetersCount * _settlementPage.NoMeterConstantCharge);

                if (_settlementPage.ConstantSettlementMethod == SettlementMethodsEnum.PER_AREA)
                {
                    SettlePerSquareMeter = Math.Ceiling((((Convert.ToDecimal(_settlementPage.ConstantPeriod) / 100) * adjustedInvoiceSum) / Convert.ToDecimal(BuildingAreaSum)) * 100) / 100;
                }
                else
                {
                    SettlePerSquareMeter = Math.Ceiling((((Convert.ToDecimal(_settlementPage.ConstantPeriod) / 100) * adjustedInvoiceSum) / ApartmentsAmount) * 100) / 100;
                }
                SettlePerMeter      = Math.Ceiling((((Convert.ToDecimal(_settlementPage.VariablePeriod) / 100) * adjustedInvoiceSum) / measureToDivide) * 100) / 100;
                PerMetersCollection = new ObservableCollection <ApartamentMeterDataGrid>();

                foreach (var a in ap)
                {
                    var selectedAmdg = _settlementPage.ApartmentMetersCollection.FirstOrDefault(x => x.ApartmentO.ApartmentId.Equals(a.ApartmentId));

                    decimal chargeAmount = 0;
                    var     c            = Charges.Where(x => x.ApartmentId.Equals(a.ApartmentId) && x.ChargeDate >= _settlementPage.SettlementFrom && x.ChargeDate <= _settlementPage.SettlementTo);
                    foreach (var cc in c)
                    {
                        chargeAmount += cc.Components.Where(y => _settlementPage.SettleChargeCategories.Any(x => x.BuildingChargeBasisCategoryId.Equals(y.CostCategoryId))).Select(x => x.Sum).DefaultIfEmpty(0).Sum();
                    }
                    //var meterDiff = selectedAmdg.MeterDifference;
                    //var costSett = Math.Ceiling((meterDiff * SettlePerMeter) * 100) / 100;

                    /*if (!selectedAmdg.IsMeterLegalized)
                     * {
                     *  selectedAmdg.LastMeasure = 0;
                     *  selectedAmdg.CurrentMeasure = (_settlementPage.NoMeterConstantAdjustment + deficitPerApartment);
                     *  costSett += _settlementPage.NoMeterConstantCharge;
                     * }*/

                    var amd = new ApartamentMeterDataGrid()
                    {
                        LastMeasure      = selectedAmdg.LastMeasure,
                        CurrentMeasure   = selectedAmdg.CurrentMeasure,
                        IsMeterLegalized = selectedAmdg.IsMeterLegalized,
                        ApartmentO       = a,
                        Charge           = chargeAmount,
                        OwnerO           = Owners.FirstOrDefault(x => x.OwnerId.Equals(a.OwnerId)),
                        SettleArea       = a.ApartmentArea + a.AdditionalArea,
                    };

                    var costSett = Math.Ceiling((Convert.ToDecimal(amd.MeterDifference) * SettlePerMeter) * 100) / 100;
                    if (!amd.IsMeterLegalized)
                    {
                        amd.LastMeasure    = 0;
                        amd.CurrentMeasure = Convert.ToDouble(Convert.ToDecimal(_settlementPage.NoMeterConstantAdjustment) + deficitPerApartment);
                        costSett           = Math.Ceiling((Convert.ToDecimal(amd.MeterDifference) * SettlePerMeter) * 100) / 100;
                        costSett          += _settlementPage.NoMeterConstantCharge;
                    }
                    amd.VariableCost = costSett;
                    amd.Saldo        = chargeAmount - costSett;

                    if (_settlementPage.ConstantSettlementMethod == SettlementMethodsEnum.PER_AREA)
                    {
                        amd.ConstantCost = SettlePerSquareMeter * Convert.ToDecimal((amd.ApartmentO.AdditionalArea + amd.ApartmentO.ApartmentArea));
                    }
                    else
                    {
                        amd.ConstantCost = SettlePerSquareMeter;
                    }
                    amd.CostSettled = amd.VariableCost + amd.ConstantCost;
                    PerMetersCollection.Add(amd);
                }
                TotalSum = PerMetersCollection.Select(x => x.CostSettled).DefaultIfEmpty(0).Sum();
                ICollectionView cv = (CollectionView)CollectionViewSource.GetDefaultView(PerMetersCollection);
                cv.SortDescriptions.Clear();
                cv.SortDescriptions.Add(new SortDescription("ApartmentO.ApartmentNumber", ListSortDirection.Ascending));
                cv.GroupDescriptions.Clear();
                cv.GroupDescriptions.Add(new PropertyGroupDescription(""));
            }

            if (_settlementPage.SettlementMethod == SettlementMethodsEnum.GAS)
            {
                var ap = Apartments.Where(x => !x.IsDeleted && x.SoldDate == null && x.BuildingId.Equals(_settlementPage.SelectedBuildingName.BuildingId));
                ApartmentsAmount = _settlementPage.ApartmentCollection.Where(x => !x.IsDeleted && x.SoldDate == null && x.BuildingId.Equals(_settlementPage.SelectedBuildingName.BuildingId)).Count();
                BuildingAreaSum  = Math.Ceiling((Apartments.Where(x => x.BuildingId.Equals(_settlementPage.SelectedBuildingName.BuildingId)).Select(x => new { totalArea = x.AdditionalArea + x.ApartmentArea }).Sum(x => x.totalArea) * 100)) / 100;

                var GJsum = _settlementPage.ApartmentGasMetersCollection.Where(x => x.IsMeterLegalized && x.Meter.MeterId.Equals(_settlementPage.HeatMeterName.MeterId)).Select(x => x.MeterDifference).DefaultIfEmpty(0).Sum();
                var warmWaterCubicMeterSum = _settlementPage.ApartmentGasMetersCollection.Where(x => x.IsMeterLegalized && x.Meter.MeterId.Equals(_settlementPage.WarmWaterMeterName.MeterId)).Select(x => x.MeterDifference).DefaultIfEmpty(0).Sum();

                ApartmentGJMeterDiffSum        = GJsum;
                ApartmentHeatWaterMeterDiffSum = warmWaterCubicMeterSum;

                var notValidHeatMetersCount      = _settlementPage.ApartmentGasMetersCollection.Where(x => !x.IsMeterLegalized && x.Meter.MeterId.Equals(_settlementPage.HeatMeterName.MeterId)).Count();
                var notValidWarmWaterMetersCount = _settlementPage.ApartmentGasMetersCollection.Where(x => !x.IsMeterLegalized && x.Meter.MeterId.Equals(_settlementPage.WarmWaterMeterName.MeterId)).Count();

                GJConstantCharge     = _settlementPage.NoHeatMeterConstantCharge;
                GJConstantAdjustment = _settlementPage.NoHeatMeterConstantAdjustment;
                IsGJDeficitShared    = _settlementPage.ChargeHeatDeficit;

                WarmWaterConstantCharge     = _settlementPage.HeatWaterConstantCharge;
                WarmWaterConstantAdjustment = _settlementPage.HeatWaterConstantAdjustment;
                IsWarmWaterDeficitShared    = _settlementPage.ChargeHeatMeterDeficit;

                var adjustedInvoiceSum             = InvoiceSum - (notValidHeatMetersCount * _settlementPage.NoHeatMeterConstantCharge + notValidWarmWaterMetersCount * _settlementPage.HeatWaterConstantCharge);
                var adjustedGJsum                  = Convert.ToDecimal(GJsum) + (notValidHeatMetersCount * _settlementPage.NoHeatMeterConstantAdjustment);
                var adjustedWarmMeterCubicMeterSum = Convert.ToDecimal(warmWaterCubicMeterSum) + (notValidWarmWaterMetersCount * _settlementPage.HeatWaterConstantAdjustment);
                if (warmWaterCubicMeterSum == 0)
                {
                    warmWaterCubicMeterSum = Convert.ToDouble(adjustedWarmMeterCubicMeterSum);
                }

                if (_settlementPage.GasUnitCostAuto && _settlementPage.GasMeterDiff != 0)
                {
                    GasUnitCost = adjustedInvoiceSum / Convert.ToDecimal(_settlementPage.GasMeterDiff);
                }
                else
                {
                    double gasUnitC;
                    double.TryParse(_settlementPage.GasUnitCost, out gasUnitC);
                    GasUnitCost = GasUnitCost;
                }

                var valueToDivideGJ = _settlementPage.HeatMeterDiff == 0 ? adjustedGJsum : Math.Min(Convert.ToDecimal(_settlementPage.HeatMeterDiff), adjustedGJsum);

                var waterHeatCost      = GasUnitCost * Convert.ToDecimal(_settlementPage.GasNeededToHeatWater);
                var waterHeatTotalCost = waterHeatCost * Convert.ToDecimal(_settlementPage.HeatWaterMeterDiff);
                WarmWaterCost = waterHeatTotalCost;
                var heatTotalCost = InvoiceSum - waterHeatTotalCost;
                COCost = heatTotalCost;

                // Do adjusted dodać deficity jezeli rozlicane i min z głownego i adjusted)
                var valueToDivideWarmWater = Convert.ToDecimal(_settlementPage.HeatWaterMeterDiff);
                if (!IsWarmWaterDeficitShared)
                {
                    valueToDivideWarmWater = Math.Min(Convert.ToDecimal(_settlementPage.HeatWaterMeterDiff), adjustedWarmMeterCubicMeterSum);
                }

                var     heatTotalCostAdjusted       = heatTotalCost - (notValidHeatMetersCount * _settlementPage.NoHeatMeterConstantCharge);
                decimal GJunitCost                  = Math.Ceiling(100 * ((Convert.ToDecimal(_settlementPage.VariablePeriod / 100)) * heatTotalCostAdjusted) / valueToDivideGJ) / 100;
                var     waterHeatTotalCostAdjusted  = waterHeatTotalCost - (notValidWarmWaterMetersCount * _settlementPage.HeatWaterConstantCharge);
                decimal warmWaterCubicMeterUnitCost = Math.Ceiling(100 * ((Convert.ToDecimal(_settlementPage.VariablePeriod) / 100) * waterHeatTotalCostAdjusted) / valueToDivideWarmWater) / 100;

                GJSettlePerMeter        = GJunitCost;
                WarmWaterSettlePerMeter = warmWaterCubicMeterUnitCost;

                decimal GJconstantCost;
                decimal warmWaterConstantCost;
                if (_settlementPage.ConstantSettlementMethod == SettlementMethodsEnum.PER_APARTMENT)
                {
                    GJconstantCost        = Math.Ceiling(100 * ((Convert.ToDecimal(_settlementPage.ConstantPeriod) / 100) * heatTotalCost) / ApartmentsAmount) / 100;
                    warmWaterConstantCost = Math.Ceiling(100 * ((Convert.ToDecimal(_settlementPage.ConstantPeriod) / 100) * waterHeatTotalCost) / ApartmentsAmount) / 100;
                }
                else
                {
                    GJconstantCost        = Math.Ceiling(100 * ((Convert.ToDecimal(_settlementPage.ConstantPeriod) / 100) * heatTotalCost) / Convert.ToDecimal(BuildingAreaSum)) / 100;
                    warmWaterConstantCost = Math.Ceiling(100 * ((Convert.ToDecimal(_settlementPage.ConstantPeriod) / 100) * waterHeatTotalCost) / Convert.ToDecimal(BuildingAreaSum)) / 100;
                }
                GJSettlePerSquareMeter        = GJconstantCost;
                WarmWaterSettlePerSquareMeter = warmWaterConstantCost;

                decimal warmWaterDeficitPerApartment = 0;
                if (_settlementPage.ChargeHeatMeterDeficit)
                {
                    if (_settlementPage.HeatWaterMeterDiff > ApartmentHeatWaterMeterDiffSum)
                    {
                        warmWaterDeficitPerApartment = (Convert.ToDecimal(_settlementPage.HeatWaterMeterDiff) - adjustedWarmMeterCubicMeterSum) / notValidWarmWaterMetersCount;
                    }
                }

                decimal GJDeficitPerApartment = 0;
                if (_settlementPage.ChargeHeatDeficit)
                {
                    if (_settlementPage.HeatMeterDiff > ApartmentGJMeterDiffSum)
                    {
                        GJDeficitPerApartment = (Convert.ToDecimal(_settlementPage.HeatMeterDiff) - adjustedGJsum) / notValidHeatMetersCount;
                    }
                }

                PerGasCollection = new ObservableCollection <ApartamentMeterDataGrid>();

                foreach (var a in ap)
                {
                    var selectedAmdgs = _settlementPage.ApartmentGasMetersCollection.Where(x => x.ApartmentO.ApartmentId.Equals(a.ApartmentId));

                    //Warm water

                    var amdg = selectedAmdgs.FirstOrDefault(x => x.Meter.MeterId.Equals(_settlementPage.WarmWaterMeterName.MeterId));

                    decimal chargeAmount = 0;
                    var     c            = Charges.Where(x => x.ApartmentId.Equals(a.ApartmentId) && x.ChargeDate >= _settlementPage.SettlementFrom && x.ChargeDate <= _settlementPage.SettlementTo);
                    foreach (var cc in c)
                    {
                        chargeAmount += cc.Components.Where(y => _settlementPage.WarmWaterChargeCategoryName.Equals(y.CostCategoryId)).Select(x => x.Sum).DefaultIfEmpty(0).Sum();
                    }

                    var amd = new ApartamentMeterDataGrid()
                    {
                        Meter            = amdg.Meter,
                        LastMeasure      = amdg.LastMeasure,
                        CurrentMeasure   = amdg.CurrentMeasure,
                        IsMeterLegalized = amdg.IsMeterLegalized,
                        ApartmentO       = a,
                        Charge           = chargeAmount,
                        OwnerO           = Owners.FirstOrDefault(x => x.OwnerId.Equals(a.OwnerId)),
                        SettleArea       = a.ApartmentArea + a.AdditionalArea,
                    };

                    var costSett = Math.Ceiling((Convert.ToDecimal(amd.MeterDifference) * WarmWaterSettlePerMeter) * 100) / 100;
                    if (!amd.IsMeterLegalized)
                    {
                        amd.LastMeasure    = 0;
                        amd.CurrentMeasure = Convert.ToDouble(WarmWaterConstantAdjustment + warmWaterDeficitPerApartment);
                        costSett           = Math.Ceiling((Convert.ToDecimal(amd.MeterDifference) * WarmWaterSettlePerMeter) * 100) / 100;
                        costSett          += WarmWaterConstantCharge;
                    }
                    amd.VariableCost = costSett;
                    amd.Saldo        = chargeAmount - costSett;

                    if (_settlementPage.ConstantSettlementMethod == SettlementMethodsEnum.PER_AREA)
                    {
                        amd.ConstantCost = WarmWaterSettlePerSquareMeter * Convert.ToDecimal(amd.ApartmentO.AdditionalArea + amd.ApartmentO.ApartmentArea);
                    }
                    else
                    {
                        amd.ConstantCost = WarmWaterSettlePerSquareMeter;
                    }
                    amd.CostSettled              = amd.VariableCost + amd.ConstantCost;
                    TotalWarmWaterCubicMeterSum += Convert.ToDouble(amd.CostSettled);
                    PerGasCollection.Add(amd);

                    // GJ
                    amdg = selectedAmdgs.FirstOrDefault(x => x.Meter.MeterId.Equals(_settlementPage.HeatMeterName.MeterId));

                    chargeAmount = 0;
                    c            = Charges.Where(x => x.ApartmentId.Equals(a.ApartmentId) && x.ChargeDate >= _settlementPage.SettlementFrom && x.ChargeDate <= _settlementPage.SettlementTo);
                    foreach (var cc in c)
                    {
                        chargeAmount += cc.Components.Where(y => _settlementPage.HeatChargeCategoryName.Equals(y.CostCategoryId)).Select(x => x.Sum).DefaultIfEmpty(0).Sum();
                    }

                    amd = new ApartamentMeterDataGrid()
                    {
                        Meter            = amdg.Meter,
                        LastMeasure      = amdg.LastMeasure,
                        CurrentMeasure   = amdg.CurrentMeasure,
                        IsMeterLegalized = amdg.IsMeterLegalized,
                        ApartmentO       = a,
                        Charge           = chargeAmount,
                        OwnerO           = Owners.FirstOrDefault(x => x.OwnerId.Equals(a.OwnerId)),
                        SettleArea       = a.ApartmentArea + a.AdditionalArea,
                    };

                    costSett = Math.Ceiling((Convert.ToDecimal(amd.MeterDifference) * GJSettlePerMeter) * 100) / 100;
                    if (!amd.IsMeterLegalized)
                    {
                        amd.LastMeasure    = 0;
                        amd.CurrentMeasure = Convert.ToDouble(GJConstantAdjustment + GJDeficitPerApartment);
                        costSett           = Math.Ceiling((Convert.ToDecimal(amd.MeterDifference) * GJSettlePerMeter) * 100) / 100;
                        costSett          += GJConstantCharge;
                    }
                    amd.VariableCost = costSett;
                    amd.Saldo        = chargeAmount - costSett;

                    if (_settlementPage.ConstantSettlementMethod == SettlementMethodsEnum.PER_AREA)
                    {
                        amd.ConstantCost = GJSettlePerSquareMeter * Convert.ToDecimal(amd.ApartmentO.AdditionalArea + amd.ApartmentO.ApartmentArea);
                    }
                    else
                    {
                        amd.ConstantCost = GJSettlePerSquareMeter;
                    }
                    amd.CostSettled = amd.VariableCost + amd.ConstantCost;
                    TotalGJSum     += Convert.ToDouble(amd.CostSettled);
                    PerGasCollection.Add(amd);
                    //  dodać footer z podsumowaniem
                }
                TotalSum = Convert.ToDecimal(TotalGJSum + TotalWarmWaterCubicMeterSum);

                ICollectionView cv = (CollectionView)CollectionViewSource.GetDefaultView(PerGasCollection);
                cv.SortDescriptions.Clear();
                cv.SortDescriptions.Add(new SortDescription("ApartmentO.ApartmentNumber", ListSortDirection.Ascending));
                cv.GroupDescriptions.Clear();
                cv.GroupDescriptions.Add(new PropertyGroupDescription("ApartmentO.ApartmentId"));
            }
        }
Пример #32
0
 public PersonsViewModel()
 {
     Items        = CollectionViewSource.GetDefaultView(Person.GetPersons());
     Items.Filter = FilterPerson;
 }
        private void OnListDataContextChanged(object sender, DependencyPropertyChangedEventArgs e)
        {
            ICollectionView view = CollectionViewSource.GetDefaultView(Controller.Tasks);

            view.SortDescriptions.Add(new SortDescription("SystemGenerated", ListSortDirection.Descending));
        }
 public static int Count(this ICollectionView collectionView)
 {
     return(collectionView.Cast <object>().Count());
 }
Пример #35
0
        // reset the collections of properties to observe, and their
        // corresponding DPs
        internal void SetLiveShapingProperties(LiveShapingFlags flags)
        {
            int    k, n;
            string path;

            _dpFromPath.BeginReset();

            // Sorting //

            // get the properties used for comparison
            SortDescriptionCollection sdc = ((ICollectionView)View).SortDescriptions;

            n          = sdc.Count;
            _compInfos = new LivePropertyInfo[n];
            for (k = 0; k < n; ++k)
            {
                path          = NormalizePath(sdc[k].PropertyName);
                _compInfos[k] = new LivePropertyInfo(path, _dpFromPath.GetDP(path));
            }


            if (TestLiveShapingFlag(flags, LiveShapingFlags.Sorting))
            {
                // get the list of property paths to observe
                Collection <string> sortProperties = View.LiveSortingProperties;

                if (sortProperties.Count == 0)
                {
                    // use the sort description properties
                    _sortInfos = _compInfos;
                }
                else
                {
                    // use the explicit list of properties
                    n          = sortProperties.Count;
                    _sortInfos = new LivePropertyInfo[n];
                    for (k = 0; k < n; ++k)
                    {
                        path          = NormalizePath(sortProperties[k]);
                        _sortInfos[k] = new LivePropertyInfo(path, _dpFromPath.GetDP(path));
                    }
                }
            }
            else
            {
                _sortInfos = new LivePropertyInfo[0];
            }


            // Filtering //

            if (TestLiveShapingFlag(flags, LiveShapingFlags.Filtering))
            {
                // get the list of property paths to observe
                Collection <string> filterProperties = View.LiveFilteringProperties;
                n            = filterProperties.Count;
                _filterInfos = new LivePropertyInfo[n];
                for (k = 0; k < n; ++k)
                {
                    path            = NormalizePath(filterProperties[k]);
                    _filterInfos[k] = new LivePropertyInfo(path, _dpFromPath.GetDP(path));
                }

                _filterRoot = new LiveShapingTree(this);
            }
            else
            {
                _filterInfos = new LivePropertyInfo[0];
                _filterRoot  = null;
            }


            // Grouping //

            if (TestLiveShapingFlag(flags, LiveShapingFlags.Grouping))
            {
                // get the list of property paths to observe
                Collection <string> groupingProperties = View.LiveGroupingProperties;

                if (groupingProperties.Count == 0)
                {
                    // if no explicit list, use the group description properties
                    groupingProperties = new Collection <string>();
                    ICollectionView icv = View as ICollectionView;
                    ObservableCollection <GroupDescription> groupDescriptions = (icv != null) ? icv.GroupDescriptions : null;

                    if (groupDescriptions != null)
                    {
                        foreach (GroupDescription gd in groupDescriptions)
                        {
                            PropertyGroupDescription pgd = gd as PropertyGroupDescription;
                            if (pgd != null)
                            {
                                groupingProperties.Add(pgd.PropertyName);
                            }
                        }
                    }
                }

                n           = groupingProperties.Count;
                _groupInfos = new LivePropertyInfo[n];
                for (k = 0; k < n; ++k)
                {
                    path           = NormalizePath(groupingProperties[k]);
                    _groupInfos[k] = new LivePropertyInfo(path, _dpFromPath.GetDP(path));
                }
            }
            else
            {
                _groupInfos = new LivePropertyInfo[0];
            }

            _dpFromPath.EndReset();
        }
 private static void RemoveHandlers(GridView gridView, ICollectionView view)
 {
     view.CollectionChanged -= ColumnsSource_CollectionChanged;
     GetGridViewsForColumnSource(view).Remove(gridView);
 }
 private static void AddHandlers(GridView gridView, ICollectionView view)
 {
     GetGridViewsForColumnSource(view).Add(gridView);
     view.CollectionChanged += ColumnsSource_CollectionChanged;
 }
 private void OnGraphVisibilityChanged(object sender, EventArgs e)
 {
     // AddRange produces tons of notifications -> too expensive
     myPreviewNodes = null;
     RaisePropertyChanged(nameof(PreviewNodes));
 }
Пример #39
0
 public TLKTextViewArgs(ListBox lstbox)
 {
     _collection = (ICollectionView)lstbox.ItemsSource;
 }
Пример #40
0
        private void Window_Loaded(object sender, RoutedEventArgs e)
        {
            ConWrLi("---- -84- Zahlungen Window_Loaded");
            int    anz  = 0;
            double wert = 0;

            //string[] sArr = new string[] { "nix", "ZINSEN/DIVIDENDE", "WERTPAPIERZAHLUNG", "STORNO" };
            foreach (Model.Wertpapier wp in DgBanken._wertpapiere)
            {
                if (wp.ISIN.Length != 12)
                {
                    continue;
                }
                if (wp.ISIN.Contains("7483612"))
                {
                    Console.WriteLine("wp: {0} DE0007483612", wp.Name);
                }
                foreach (Model.Kontoumsatz ku in _kontoumsätze)
                {
                    if (!ku.PaymtPurpose.Contains(wp.ISIN))
                    {
                        continue;
                    }
                    if (ku.PaymtPurpose.Contains("7483612"))
                    {
                        Console.WriteLine("\tku: {0} DE0007483612 knr: {1} name1: {2} name2: {3}", ku.BankCode, ku.Kontonummer, ku.Name1, ku.Name2);
                    }
                    //Debug.WriteLine("---- -85-1- Zahlungen ISIN: " + wp.ISIN + " EntryText: " + ku.EntryText + " PaymtPurpose: " + ku.PaymtPurpose);
                    if ((!ku.EntryText.Contains("ZINSEN/DIVIDENDE")) &&
                        (!ku.EntryText.Contains("WERTPAPIERZAHLUNG")) &&
                        (!ku.EntryText.Contains("STORNO")) &&
                        (!ku.EntryText.Contains("WERTP. ABRECHN.")) &&
                        (!ku.EntryText.Contains("WERTPAPIERE")) &&
                        (!ku.PaymtPurpose.Contains("Wertpapierertrag")) &&
                        (!ku.PaymtPurpose.Contains("STEUERAUSGLEICH")) &&
                        (!ku.PaymtPurpose.Contains("WERTP. ABRECHN.")) &&
                        (!ku.PaymtPurpose.Contains("Wertp.Abrechn.")))
                    {
                        // DEPOT     700617681|WERTP. ABRECHN.   25.03.15|000006030110100  WKN A0YJMG|GESCH.ART  KV|WHC - GLOBAL DISCOVERY|DE000A0YJMG1
                        // Depot 0700617681|Wertp.Abrechn. 22.09.2016|000001067448600 WKN A1JRQD|Gesch.Art KV|4Q-SPECIAL INCOME EUR(R)|ISIN DE000A1JRQD1
                        continue;
                    }
                    //Console.WriteLine("++++ -85-2- Zahlungen ISIN: " + wp.ISIN + " EntryText: " + ku.EntryText + " PaymtPurpose: " + ku.PaymtPurpose);
                    ++anz;
                    wert = Convert.ToDouble(ku.Value);
                    _zahlungen.Add(new Model.Zahlung {
                        Anzahl               = wp.Anzahl.ToString(),
                        Isin                 = wp.ISIN,
                        Name                 = wp.Name,
                        EntryDate            = ku.EntryDate,
                        ValueDate            = ku.ValueDate,
                        Value                = ku.Value,
                        AcctNo               = ku.AcctNo,
                        BankCode             = ku.BankCode,
                        Name1                = ku.Name1,
                        Name2                = ku.Name2,
                        PaymtPurpose         = ku.PaymtPurpose,
                        EntryText            = ku.EntryText,
                        PrimaNotaNo          = ku.PrimaNotaNo,
                        TranTypeIdCode       = ku.TranTypeIdCode,
                        ZkaTranCode          = ku.ZkaTranCode,
                        TextKeyExt           = ku.TextKeyExt,
                        BankRef              = ku.BankRef,
                        OwnerRef             = ku.OwnerRef,
                        SupplementaryDetails = ku.SupplementaryDetails
                    });
                    DateTime dat     = Convert.ToDateTime(ku.ValueDate);
                    string   strDate = dat.ToString("dd.MM.yy");
                    isins.Add(new ISIN {
                        Isin = wp.ISIN, Name = wp.Name, eingefügt = false, Datum = strDate, Anzahl = anz, Wert = wert, EntryText = ku.EntryText, PaymtPurpose = ku.PaymtPurpose
                    });
                    if (wp.ISIN.Contains("DE0007483612"))
                    {
                        Console.WriteLine("B-DE0007483612: " + wert + " " + strDate + " " + wp.Name);
                    }
                }
                if (anz > 0)
                {
                    isins.Add(new ISIN {
                        Isin = "", Name = "------", Anzahl = 0, Wert = 0
                    });
                }
                anz  = 0;
                wert = 0;
            }
            ICollectionView cvZahlungen = CollectionViewSource.GetDefaultView(gridZahlungen.ItemsSource);

            cvZahlungen.GroupDescriptions.Clear();
            gridZahlungen.ItemsSource = _zahlungen;
            gridWP.ItemsSource        = isins;
            foreach (ISIN isi in isins)
            {
                if (isi.Name == "------")
                {
                    continue;
                }
                bool einfügen = true;
                foreach (DataRow dr in DataSetAdmin.dtPortFolBew.Rows)
                {
                    if (System.DBNull.Value.Equals(dr["isin"]))
                    {
                        continue;
                    }
                    if ((string)dr["isin"] != isi.Isin)
                    {
                        continue;
                    }
                    foreach (DataRow dr2 in DataSetAdmin.dtPortFolBew.Rows)
                    {
                        if (dr2["ISIN"].ToString() == isi.Isin)
                        {
                            if (dr2["Datum"].ToString() == isi.Datum)
                            {
                                einfügen = false;
                                break;
                            }
                        }
                    }
                }
                if (einfügen)
                {
                    DataRow newRow = DataSetAdmin.dtPortFolBew.NewRow();
                    newRow["ID"]           = rand.Next();
                    newRow["ISIN"]         = isi.Isin;
                    newRow["Name"]         = isi.Name;
                    newRow["Datum"]        = isi.Datum;
                    newRow["Betrag"]       = isi.Wert;
                    newRow["IDvomGiroKto"] = 0;
                    newRow["Feld1"]        = isi.EntryText;
                    newRow["IDvomWP"]      = 0;
                    newRow["Text1"]        = isi.PaymtPurpose;
                    try {
                        DataSetAdmin.dtPortFolBew.Rows.Add(newRow);
                        isi.eingefügt = true;
                    }
                    catch (Exception ex) {
                        // Die Spalte 'ISIN, Datum, Text1' hat die Einschränkung, dass sie eindeutig sein muss.
                        // Der Wert 'DE000A0YJMG1, 15.02.2017 00:00:00, Depot 0700617681|Wertpapierertrag 14.02.2017|000054528021880
                        // WKN A0YJMG|WHC - GLOBAL DISCOVERY|ISIN DE000A0YJMG1' ist bereits vorhanden.
                        Console.WriteLine("Fehler in .Rows.Add:" + ex);
                        Console.WriteLine("{0} {1} {2} {3} {4}", isi.Isin, isi.Name, isi.eingefügt, isi.Datum, isi.Wert);
                        break;
                    }
                }
            }
            DataSetAdmin.DatasetSichernInXml(Helpers.GlobalRef.g_Ein.MyDataPfad);
            this.Close();
        }
        /// <summary>
        /// Filter the current GamesList with textbox from filter controls
        /// </summary>
        /// <param name="obj"></param>
        private void FilterGamesByText(GameFilter gameFilter)
        {
            if (GamesList != null)
            {
                ICollectionView cv = this.GamesList;

                var filter        = gameFilter.FilterText;
                var showClones    = gameFilter.ShowClones;
                var favesOnly     = gameFilter.ShowFavoritesOnly;
                var enabledFilter = gameFilter.ShowEnabledOnly;

                int enabled = 0;

                if (enabledFilter)
                {
                    enabled = 1;
                }

                cv.Filter = o =>
                {
                    var g            = o as GameItemViewModel;
                    var textFiltered = false;

                    try
                    {
                        if (string.IsNullOrEmpty(filter))
                        {
                            if (favesOnly && showClones && enabledFilter)
                            {
                                textFiltered =
                                    g.GameEnabled.Equals(enabled) &&
                                    g.IsFavorite.Equals(favesOnly) &&
                                    g.CloneOf.Length >= 0;
                            }
                            else if (favesOnly && showClones)
                            {
                                textFiltered =
                                    g.IsFavorite.Equals(favesOnly) &&
                                    g.CloneOf.Length >= 0;
                            }
                            else if (favesOnly && !showClones && enabledFilter)
                            {
                                textFiltered =
                                    g.GameEnabled.Equals(enabled) &&
                                    g.IsFavorite.Equals(favesOnly) &&
                                    g.CloneOf.Equals(string.Empty);
                            }
                            else if (favesOnly && !showClones)
                            {
                                textFiltered =
                                    g.IsFavorite.Equals(favesOnly) &&
                                    g.CloneOf.Equals(string.Empty);
                            }
                            else if (!favesOnly && !showClones && enabledFilter)
                            {
                                textFiltered = g.CloneOf.Equals(string.Empty) &&
                                               g.GameEnabled.Equals(enabled);
                            }
                            else if (!favesOnly && showClones && enabledFilter)
                            {
                                textFiltered = g.CloneOf.Length >= 0 &&
                                               g.GameEnabled.Equals(enabled);
                            }
                            else if (!favesOnly && !showClones)
                            {
                                textFiltered = g.CloneOf.Equals(string.Empty);
                            }
                            else if (!favesOnly && showClones)
                            {
                                textFiltered = g.CloneOf.Length >= 0;
                            }
                        }
                        else // Text is used as filter
                        {
                            if (showClones && favesOnly && enabledFilter)
                            {
                                textFiltered = g.Description.ToUpper().Contains(filter.ToUpper()) &&
                                               g.GameEnabled.Equals(enabled) &&
                                               g.IsFavorite.Equals(favesOnly) &&
                                               g.CloneOf.Length >= 0;
                            }
                            else if (showClones && favesOnly)
                            {
                                textFiltered = g.Description.ToUpper().Contains(filter.ToUpper()) &&
                                               g.IsFavorite.Equals(favesOnly) &&
                                               g.CloneOf.Length >= 0;
                            }
                            else if (showClones && !favesOnly && enabledFilter)
                            {
                                textFiltered = g.Description.ToUpper().Contains(filter.ToUpper()) &&
                                               g.GameEnabled.Equals(enabled) &&
                                               g.CloneOf.Length >= 0;
                            }
                            else if (showClones && !favesOnly)
                            {
                                textFiltered = g.Description.ToUpper().Contains(filter.ToUpper()) &&
                                               g.CloneOf.Length >= 0;
                            }
                            else if (!showClones && favesOnly && enabledFilter)
                            {
                                textFiltered = g.Description.ToUpper().Contains(filter.ToUpper()) &&
                                               g.GameEnabled.Equals(enabled) &&
                                               g.IsFavorite.Equals(favesOnly) && g.CloneOf.Equals(string.Empty);
                            }
                            else if (!showClones && favesOnly)
                            {
                                textFiltered = g.Description.ToUpper().Contains(filter.ToUpper()) &&
                                               g.IsFavorite.Equals(favesOnly) && g.CloneOf.Equals(string.Empty);
                            }
                            else if (!showClones && !favesOnly && enabledFilter)
                            {
                                textFiltered = g.Description.ToUpper().Contains(filter.ToUpper()) &&
                                               g.GameEnabled.Equals(enabled) &&
                                               g.CloneOf.Equals(string.Empty);
                            }
                            else if (!showClones && !favesOnly)
                            {
                                textFiltered = g.Description.ToUpper().Contains(filter.ToUpper()) &&
                                               g.CloneOf.Equals(string.Empty);
                            }
                        }
                    }
                    catch { }

                    return(textFiltered);
                };
            }
        }
Пример #42
0
        /// <summary>
        /// Stop listening to the given source for the event.
        /// </summary>
        protected override void StopListening(object source)
        {
            ICollectionView typedSource = (ICollectionView)source;

            typedSource.CurrentChanging -= new CurrentChangingEventHandler(OnCurrentChanging);
        }
Пример #43
0
        void EnsureView(object source, Type collectionViewType)
        {
            if (_isInitializing || _deferLevel > 0)
            {
                return;
            }

            DataSourceProvider dataProvider = source as DataSourceProvider;

            // listen for DataChanged events from an DataSourceProvider
            if (dataProvider != _dataProvider)
            {
                if (_dataProvider != null)
                {
                    DataChangedEventManager.RemoveHandler(_dataProvider, OnDataChanged);
                }

                _dataProvider = dataProvider;

                if (_dataProvider != null)
                {
                    DataChangedEventManager.AddHandler(_dataProvider, OnDataChanged);
                    _dataProvider.InitialLoad();
                }
            }

            // if the source is DataSourceProvider, use its Data instead
            if (dataProvider != null)
            {
                source = dataProvider.Data;
            }

            // get the view
            ICollectionView view = null;

            if (source != null)
            {
                DataBindEngine engine     = DataBindEngine.CurrentDataBindEngine;
                ViewRecord     viewRecord = engine.GetViewRecord(source, this, collectionViewType, true,
                                                                 (object x) =>
                {
                    BindingExpressionBase beb = BindingOperations.GetBindingExpressionBase(this, SourceProperty);
                    return((beb != null) ? beb.GetSourceItem(x) : null);
                });

                if (viewRecord != null)
                {
                    view = viewRecord.View;
                    _isViewInitialized = viewRecord.IsInitialized;

                    // bring view up to date with the CollectionViewSource
                    if (_version != viewRecord.Version)
                    {
                        ApplyPropertiesToView(view);
                        viewRecord.Version = _version;
                    }
                }
            }

            // update the View property
            SetValue(ViewPropertyKey, view);
        }
Пример #44
0
        // Forward properties from the CollectionViewSource to the CollectionView
        void ApplyPropertiesToView(ICollectionView view)
        {
            if (view == null || _deferLevel > 0)
            {
                return;
            }

            ICollectionViewLiveShaping liveView = view as ICollectionViewLiveShaping;

            using (view.DeferRefresh())
            {
                int i, n;

                // Culture
                if (Culture != null)
                {
                    view.Culture = Culture;
                }

                // Sort
                if (view.CanSort)
                {
                    view.SortDescriptions.Clear();
                    for (i = 0, n = SortDescriptions.Count; i < n; ++i)
                    {
                        view.SortDescriptions.Add(SortDescriptions[i]);
                    }
                }
                else if (SortDescriptions.Count > 0)
                {
                    throw new InvalidOperationException(SR.Get(SRID.CannotSortView, view));
                }

                // Filter
                Predicate <object> filter;
                if (FilterHandlersField.GetValue(this) != null)
                {
                    filter = FilterWrapper;
                }
                else
                {
                    filter = null;
                }

                if (view.CanFilter)
                {
                    view.Filter = filter;
                }
                else if (filter != null)
                {
                    throw new InvalidOperationException(SR.Get(SRID.CannotFilterView, view));
                }

                // GroupBy
                if (view.CanGroup)
                {
                    view.GroupDescriptions.Clear();
                    for (i = 0, n = GroupDescriptions.Count; i < n; ++i)
                    {
                        view.GroupDescriptions.Add(GroupDescriptions[i]);
                    }
                }
                else if (GroupDescriptions.Count > 0)
                {
                    throw new InvalidOperationException(SR.Get(SRID.CannotGroupView, view));
                }

                // Live shaping
                if (liveView != null)
                {
                    ObservableCollection <string> properties;

                    // sorting
                    if (liveView.CanChangeLiveSorting)
                    {
                        liveView.IsLiveSorting = IsLiveSortingRequested;
                        properties             = liveView.LiveSortingProperties;
                        properties.Clear();

                        if (IsLiveSortingRequested)
                        {
                            foreach (string s in LiveSortingProperties)
                            {
                                properties.Add(s);
                            }
                        }
                    }

                    CanChangeLiveSorting = liveView.CanChangeLiveSorting;
                    IsLiveSorting        = liveView.IsLiveSorting;

                    // filtering
                    if (liveView.CanChangeLiveFiltering)
                    {
                        liveView.IsLiveFiltering = IsLiveFilteringRequested;
                        properties = liveView.LiveFilteringProperties;
                        properties.Clear();

                        if (IsLiveFilteringRequested)
                        {
                            foreach (string s in LiveFilteringProperties)
                            {
                                properties.Add(s);
                            }
                        }
                    }

                    CanChangeLiveFiltering = liveView.CanChangeLiveFiltering;
                    IsLiveFiltering        = liveView.IsLiveFiltering;

                    // grouping
                    if (liveView.CanChangeLiveGrouping)
                    {
                        liveView.IsLiveGrouping = IsLiveGroupingRequested;
                        properties = liveView.LiveGroupingProperties;
                        properties.Clear();

                        if (IsLiveGroupingRequested)
                        {
                            foreach (string s in LiveGroupingProperties)
                            {
                                properties.Add(s);
                            }
                        }
                    }

                    CanChangeLiveGrouping = liveView.CanChangeLiveGrouping;
                    IsLiveGrouping        = liveView.IsLiveGrouping;
                }
                else
                {
                    CanChangeLiveSorting   = false;
                    IsLiveSorting          = null;
                    CanChangeLiveFiltering = false;
                    IsLiveFiltering        = null;
                    CanChangeLiveGrouping  = false;
                    IsLiveGrouping         = null;
                }
            }
        }
Пример #45
0
 public CollectionView(List <T> items)
 {
     _collectionView = new ListCollectionView(items);
 }
Пример #46
0
 public FlowDocViewModel(params FlowDocDataItem [] items)
 {
     _items = new ObservableCollection <FlowDocDataItem>(items);
     _cv    = CollectionViewSource.GetDefaultView(_items);
 }
Пример #47
0
 public void populate(List <VaRResult> results)
 {
     data       = results;
     Securities = CollectionViewSource.GetDefaultView(data);
     Securities.Refresh();
 }
 public ImageViewerViewModel()
 {
     _fileInfoCollections = new CollectionView(_fileInfos);
     //OpenCommand=new DelegateCommand<string>(OpenCommandHandler);
     GetImages();
 }
Пример #49
0
        public static Task FuncFilterAllInFieldsAsync <T>(this IEnumerable <T> source, ICollectionView view, object objSearch, Func <object, object, bool> comp, IEnumerable <string> fieldsSearch) where T : class
        {
            return(Task.Run(() =>
            {
                var filterOK = source.WhereAllForFuncInFields(objSearch, comp, fieldsSearch).ToList();

                //view.Filter += a => filterOK.Any(b => b == a);

                Application.Current.Dispatcher.Invoke(() =>
                {
                    view.Filter += a => filterOK.Any(b => b == a);
                });
            }));
        }
Пример #50
0
 public void InitList(ICollectionView collectionView)
 {
     _collectionView = collectionView;
 }
Пример #51
0
        public static void SaveViewState(MainViewModel model)
        {
            XmlDocument doc  = XmlHelper.CreateDocument();
            XmlElement  conf = doc.CreateElement("Configuration");

            doc.AppendChild(conf);

            XmlHelper.SetAttributes(doc, conf, "Location", model.UserInfo, (m, x) =>
            {
                XmlHelper.SetAttribute(doc, x, "UserName", m.UserName);
                XmlHelper.SetAttribute(doc, x, "File", m.File);
                XmlHelper.SetAttribute(doc, x, "SavePassword", m.SavePassword);
                XmlHelper.SetAttribute(doc, x, "AutoLogin", m.AutoLogin);

                if (m.SavePassword)
                {
                    XmlHelper.SetAttribute(doc, x, "Password", m.Password);
                }
            });

            XmlHelper.SetAttributes(doc, conf, "Tasks", model.Configuration, (m, x) =>
            {
                XmlHelper.SetAttribute(doc, x, "ShowTaskInNewWindow", m.ShowTaskInNewWindow);
                XmlHelper.SetAttribute(doc, x, "MinimumPriority", m.MinimumPriority);
            });

            XmlHelper.SetAttributes(doc, conf, "Group", model.Configuration, (m, x) =>
            {
                XmlHelper.SetAttribute(doc, x, "ShowGroupAll", m.ShowGroupAll);
            });

            XmlHelper.SetAttributes(doc, conf, "Windows", model.Configuration, (m, x) =>
            {
                XmlHelper.SetAttribute(doc, x, "ShowInWindowList", m.ShowInWindowList);
                XmlHelper.SetAttribute(doc, x, "ShowInTaskbar", m.ShowInTaskbar);
                XmlHelper.SetAttribute(doc, x, "ShowInTray", m.ShowInTray);
                XmlHelper.SetAttribute(doc, x, "ShowButtonsText", m.ShowButtonsText);
            });

            XmlHelper.SetAttributes(doc, conf, "MainWindow", model.Configuration, (m, x) =>
            {
                XmlHelper.SetAttribute(doc, x, "Left", m.MainLeft);
                XmlHelper.SetAttribute(doc, x, "Top", m.MainTop);
                XmlHelper.SetAttribute(doc, x, "Width", m.MainWidth);
                XmlHelper.SetAttribute(doc, x, "Height", m.MainHeight);
            });

            XmlHelper.SetAttributes(doc, conf, "Groups", model.Configuration, (m, x) =>
            {
                XmlHelper.SetAttribute(doc, x, "Sorted", m.GroupsSort);
                XmlHelper.SetAttribute(doc, x, "SortedDirection", m.GroupsSortDirection);
            });

            XmlHelper.SetAttributes(doc, conf, "Locale", model.Configuration.Locale, (m, x) =>
            {
                XmlHelper.SetAttribute(doc, x, "Value", m.Name);
            });

            XmlHelper.SetAttributes(doc, conf, "DetailWindow", model.Configuration, (m, x) =>
            {
                XmlHelper.SetAttribute(doc, x, "Width", m.DetailWidth);
                XmlHelper.SetAttribute(doc, x, "Height", m.DetailHeight);
            });

            XmlHelper.SetAttributes(doc, conf, "CheckedTaskStates", "TaskState", model.CheckableTaskStates.Where(s => s.IsChecked), (m, x) =>
            {
                XmlHelper.SetAttribute(doc, x, "ID", m.Data.ID);
            });

            if (model.SelectedGroup != null)
            {
                XmlHelper.SetAttributes(doc, conf, "SelectedGroup", model.SelectedGroup, (m, x) =>
                {
                    XmlHelper.SetAttribute(doc, x, "ID", m.ID);
                });
            }

            ICollectionView view = CollectionViewSource.GetDefaultView(model.Tasks);

            if (view != null)
            {
                XmlHelper.SetAttributes(doc, conf, "TasksSort", "SortDescription", view.SortDescriptions, (sd, x) =>
                {
                    XmlHelper.SetAttribute(doc, x, "Property", sd.PropertyName);
                    XmlHelper.SetAttribute(doc, x, "Direction", sd.Direction.ToString());
                });
            }

            IsolatedStorageFile f = IsolatedStorageFile.GetUserStoreForAssembly();

            using (IsolatedStorageFileStream stream = new IsolatedStorageFileStream(ConfigurationFileName, FileMode.Create, f))
                doc.Save(stream);
        }
Пример #52
0
        private void ImportBtn_Click(object sender, RoutedEventArgs e)
        {
            ICollectionView cards = CollectionViewSource.GetDefaultView(DG1.ItemsSource);

            Card card = cards
                        .Cast <Card>()
                        .Where(e => e.ToImport)
                        .FirstOrDefault();

            if (card.IsNull())
            {
                MessageBox.Show("Failed to import card because card was null");
                return;
            }

            TemplateRenderOptions opts = new TemplateRenderOptions();

            opts.Refs
            .WithAuthor(AuthorTextbox.Text)
            .WithTitle(TitleTextbox.Text)
            .WithAuthor(SourceTextbox.Text);

            if (ImageExtractionCheckbox.IsChecked == true)
            {
                opts.AddImageComponents = true;
            }
            else
            {
                opts.AddImageComponents = false;
            }

            ElementBuilder builder = null;

            if (IgnoreDuplicateFieldsCheckbox.IsChecked == true)
            {
                var question = new Renderer(card).Render(TemplateType.Question, out var fieldDict);
                var answer   = new Renderer(card).RenderAnswerIgnoreDuplicates(fieldDict, out _);
                builder = new AnkiCardBuilder(card, question, answer).CreateElementBuilder();
            }
            else
            {
                builder = new AnkiCardBuilder(card).CreateElementBuilder();
            }

            IElement parent = null;

            double priority = PrioritySlider.Value;

            if (priority < 0 || priority > 100)
            {
                priority = 30;
            }

            if (ImportChildRadio.IsChecked == true)
            {
                parent = Svc.SM.UI.ElementWdw.CurrentElement;
            }

            Svc.SM.Registry.Element.Add(
                out _,
                Interop.SuperMemo.Elements.Models.ElemCreationFlags.ForceCreate,
                builder
                .WithParent(parent)
                .WithPriority(priority)
                );
        }
Пример #53
0
 private async Task FilterBy(ICollectionView <object> collectionView, string query)
 {
     await(collectionView as ISupportFiltering).FilterAsync(collectionView.CreateFilterFromString(query, TreatSpacesAsAndOperator, MatchNumbers));
 }
Пример #54
0
        public static void LoadViewState(MainViewModel model)
        {
            IsolatedStorageFile f = IsolatedStorageFile.GetUserStoreForAssembly();

            if (f.FileExists(ConfigurationFileName))
            {
                XmlDocument doc = null;
                using (IsolatedStorageFileStream stream = new IsolatedStorageFileStream(ConfigurationFileName, FileMode.OpenOrCreate, f))
                {
                    try
                    {
                        doc = new XmlDocument();
                        doc.Load(stream);
                    }
                    catch (Exception)
                    {
                        doc = null;
                    }
                }

                if (doc == null)
                {
                    return;
                }

                XmlHelper.ElementByName(doc.DocumentElement, "Location", model.UserInfo, (m, x) =>
                {
                    m.AutoLogin    = XmlHelper.GetAttributeBool(x, "AutoLogin", false);
                    m.SavePassword = XmlHelper.GetAttributeBool(x, "SavePassword", false);

                    m.UserName = XmlHelper.GetAttributeValue(x, "UserName");
                    m.File     = XmlHelper.GetAttributeValue(x, "File");

                    if (m.SavePassword)
                    {
                        m.Password = XmlHelper.GetAttributeValue(x, "Password");
                    }
                });

                XmlHelper.ElementByName(doc.DocumentElement, "Tasks", model.Configuration, (m, x) =>
                {
                    m.ShowTaskInNewWindow = XmlHelper.GetAttributeBool(x, "ShowTaskInNewWindow", false);
                    m.MinimumPriority     = XmlHelper.GetAttributeDecimal(x, "MinimumPriority", 1);
                });

                XmlHelper.ElementByName(doc.DocumentElement, "Group", model.Configuration, (m, x) =>
                {
                    m.ShowGroupAll = XmlHelper.GetAttributeBool(x, "ShowGroupAll", true);
                });

                XmlHelper.ElementByName(doc.DocumentElement, "Windows", model.Configuration, (m, x) =>
                {
                    m.ShowInWindowList = XmlHelper.GetAttributeBool(x, "ShowInWindowList", true);
                    m.ShowInTaskbar    = XmlHelper.GetAttributeBool(x, "ShowInTaskbar", true);
                    m.ShowInTray       = XmlHelper.GetAttributeBool(x, "ShowInTray", false);
                    m.ShowButtonsText  = XmlHelper.GetAttributeBool(x, "ShowButtonsText", true);
                });

                XmlHelper.ElementByName(doc.DocumentElement, "Groups", model.Configuration, (m, x) =>
                {
                    m.GroupsSort          = XmlHelper.GetAttributeValue(x, "Sorted", model.Configuration.GroupsSort);
                    m.GroupsSortDirection = XmlHelper.GetAttributeEnum <ListSortDirection>(x, "SortedDirection", ListSortDirection.Descending);
                });

                XmlHelper.ElementByName(doc.DocumentElement, "MainWindow", model.Configuration, (m, x) =>
                {
                    m.MainLeft   = XmlHelper.GetAttributeDouble(x, "Left", model.Window.Left);
                    m.MainTop    = XmlHelper.GetAttributeDouble(x, "Top", model.Window.Top);
                    m.MainWidth  = XmlHelper.GetAttributeDouble(x, "Width", model.Window.Width);
                    m.MainHeight = XmlHelper.GetAttributeDouble(x, "Height", model.Window.Height);
                });

                XmlHelper.ElementByName(doc.DocumentElement, "Locale", model.Configuration, (m, x) =>
                {
                    m.Locale = XmlHelper.GetAttributeCulture(x, "Value", Thread.CurrentThread.CurrentCulture);
                });

                XmlHelper.ElementByName(doc.DocumentElement, "DetailWindow", model.Configuration, (m, x) =>
                {
                    m.DetailWidth  = XmlHelper.GetAttributeDouble(x, "Width", model.Window.Width);
                    m.DetailHeight = XmlHelper.GetAttributeDouble(x, "Height", model.Window.Height);
                });

                ICollectionView view = CollectionViewSource.GetDefaultView(model.Tasks);
                if (view != null)
                {
                    XmlNodeList xsort = doc.GetElementsByTagName("TasksSort");
                    if (xsort.Count == 1)
                    {
                        view.SortDescriptions.Clear();
                        foreach (XmlElement item in ((XmlElement)xsort[0]).GetElementsByTagName("SortDescription"))
                        {
                            string            propertyName = XmlHelper.GetAttributeValue(item, "Property", "Priority");
                            ListSortDirection direction    = XmlHelper.GetAttributeEnum <ListSortDirection>(item, "Direction", ListSortDirection.Descending);
                            model.Window.SortTasks(model.Sorts.First(i => i.Property == propertyName), direction == ListSortDirection.Descending);
                        }
                    }
                }
            }
        }
Пример #55
0
        public static async Task <ObservableCollection <ISemanticZoomSelector> > UpdateSemanticZoomSelectors(ICollectionView semanticZoomables)
        {
            // Get all the possible semantic zoom selectors
            var zoomSelectors = new ObservableCollection <ISemanticZoomSelector>();

            await Task.Run(() =>
            {
                foreach (string item in Defaults.SemanticZoomItems)
                {
                    zoomSelectors.Add(new SemanticZoomSelectorViewModel
                    {
                        Header  = item,
                        CanZoom = false
                    });
                }
            });

            // Set the availability of the semantic zoom selectors
            await Task.Run(() =>
            {
                try
                {
                    foreach (ISemanticZoomable zoomable in semanticZoomables)
                    {
                        dynamic selector = zoomSelectors.Select((s) => s).Where((s) => s.Header.ToLower() == zoomable.Header.ToLower()).FirstOrDefault();
                        if (selector != null)
                        {
                            selector.CanZoom = true;
                        }
                    }
                }
                catch (Exception ex)
                {
                    LogClient.Error("Error while setting the availability of the semantic zoom selectors.", ex.Message);
                }
            });

            return(zoomSelectors);
        }
Пример #56
0
 public pgPays()
 {
     InitializeComponent();
     _listePays          = CollectionViewSource.GetDefaultView(_bdd.Pays);
     grpPays.DataContext = _listePays;
 }
Пример #57
0
 private void switchLogin_Checked(object sender, RoutedEventArgs e)
 {
     if (this.switchPrivacy.IsChecked.HasValue && this.switchPrivacy.IsChecked.Value)
     {
         bool cont = false;
         this.txtEmail.Background    = (Brush)Application.Current.MainWindow.FindResource("FilledBackground");
         this.txtPassword.Background = (Brush)Application.Current.MainWindow.FindResource("FilledBackground");
         if ((Global.PRIVACY_MANAGER != null) && Global.PRIVACY_MANAGER.IsLoggedIn)
         {
             this.txtEmail.IsEnabled          = false;
             this.txtEmail.Opacity            = 0.6;
             this.txtPassword.IsEnabled       = false;
             this.txtPassword.Opacity         = 0.6;
             this.cmbCaptchaService.IsEnabled = false;
             this.cmbCaptchaService.Opacity   = 0.6;
             this.brGrid.IsEnabled            = true;
             this.brGrid.Opacity             = 1.0;
             this.brNewPrivacyCard.IsEnabled = true;
             this.brNewPrivacyCard.Opacity   = 1.0;
             ICollectionView defaultView = CollectionViewSource.GetDefaultView(Global.PRIVACY_MANAGER.Cards);
             this.gvCards.ItemsSource = defaultView;
         }
         else
         {
             TaskScheduler current;
             if (SynchronizationContext.Current != null)
             {
                 current = TaskScheduler.FromCurrentSynchronizationContext();
             }
             else
             {
                 current = TaskScheduler.Current;
             }
             this.lblName.Visibility           = Visibility.Hidden;
             this.lblPassword.Visibility       = Visibility.Hidden;
             this.lblCaptcha.Visibility        = Visibility.Hidden;
             this.txtEmail.Visibility          = Visibility.Hidden;
             this.txtPassword.Visibility       = Visibility.Hidden;
             this.cmbCaptchaService.Visibility = Visibility.Hidden;
             this.switchPrivacy.IsEnabled      = false;
             this.lblLoadingText.Visibility    = Visibility.Visible;
             this.progBarPrivacy.Visibility    = Visibility.Visible;
             this.progBarPrivacy.IsEnabled     = true;
             Task.Factory.StartNew(delegate {
                 Global.PRIVACY_MANAGER = new PrivacyManager();
                 Global.PRIVACY_MANAGER.Login();
                 if (Global.PRIVACY_MANAGER.IsLoggedIn)
                 {
                     cont = true;
                     Global.PRIVACY_MANAGER.LoadCards();
                 }
             }).ContinueWith(delegate(Task t) {
                 this.switchPrivacy.IsEnabled   = true;
                 this.lblLoadingText.Visibility = Visibility.Collapsed;
                 this.progBarPrivacy.Visibility = Visibility.Collapsed;
                 this.progBarPrivacy.IsEnabled  = false;
                 if (!cont)
                 {
                     this.switchPrivacy.IsChecked = false;
                 }
                 else
                 {
                     this.txtEmail.IsEnabled          = false;
                     this.txtEmail.Opacity            = 0.6;
                     this.txtPassword.IsEnabled       = false;
                     this.txtPassword.Opacity         = 0.6;
                     this.cmbCaptchaService.IsEnabled = false;
                     this.cmbCaptchaService.Opacity   = 0.6;
                     this.brGrid.IsEnabled            = true;
                     this.brGrid.Opacity             = 1.0;
                     this.brNewPrivacyCard.IsEnabled = true;
                     this.brNewPrivacyCard.Opacity   = 1.0;
                     ICollectionView defaultView     = CollectionViewSource.GetDefaultView(Global.PRIVACY_MANAGER.Cards);
                     this.gvCards.ItemsSource        = defaultView;
                 }
                 this.lblName.Visibility           = Visibility.Visible;
                 this.lblPassword.Visibility       = Visibility.Visible;
                 this.lblCaptcha.Visibility        = Visibility.Visible;
                 this.txtEmail.Visibility          = Visibility.Visible;
                 this.txtPassword.Visibility       = Visibility.Visible;
                 this.cmbCaptchaService.Visibility = Visibility.Visible;
             }, current);
         }
     }
     else
     {
         this.txtEmail.IsEnabled          = true;
         this.txtEmail.Opacity            = 1.0;
         this.txtPassword.IsEnabled       = true;
         this.txtPassword.Opacity         = 1.0;
         this.cmbCaptchaService.IsEnabled = true;
         this.cmbCaptchaService.Opacity   = 1.0;
         this.brGrid.IsEnabled            = false;
         this.brGrid.Opacity             = 0.6;
         this.brNewPrivacyCard.IsEnabled = false;
         this.brNewPrivacyCard.Opacity   = 0.6;
     }
 }
Пример #58
0
        //lab1part32
        private void btnNext_Click(object sender, RoutedEventArgs e)
        {
            ICollectionView navigationView = CollectionViewSource.GetDefaultView(phoneNumbersDataSet.PhoneNumbers);

            navigationView.MoveCurrentToNext();
        }
    private static void ColumnsSource_CollectionChanged(object sender, NotifyCollectionChangedEventArgs e)
    {
        ICollectionView view      = sender as ICollectionView;
        var             gridViews = GetGridViewsForColumnSource(view);

        if (gridViews == null || gridViews.Count == 0)
        {
            return;
        }
        switch (e.Action)
        {
        case NotifyCollectionChangedAction.Add:
            foreach (var gridView in gridViews)
            {
                for (int i = 0; i < e.NewItems.Count; i++)
                {
                    GridViewColumn column = CreateColumn(gridView, e.NewItems[i]);
                    gridView.Columns.Insert(e.NewStartingIndex + i, column);
                }
            }
            break;

        case NotifyCollectionChangedAction.Move:
            foreach (var gridView in gridViews)
            {
                List <GridViewColumn> columns = new List <GridViewColumn>();
                for (int i = 0; i < e.OldItems.Count; i++)
                {
                    GridViewColumn column = gridView.Columns[e.OldStartingIndex + i];
                    columns.Add(column);
                }
                for (int i = 0; i < e.NewItems.Count; i++)
                {
                    GridViewColumn column = columns[i];
                    gridView.Columns.Insert(e.NewStartingIndex + i, column);
                }
            }
            break;

        case NotifyCollectionChangedAction.Remove:
            foreach (var gridView in gridViews)
            {
                for (int i = 0; i < e.OldItems.Count; i++)
                {
                    gridView.Columns.RemoveAt(e.OldStartingIndex);
                }
            }
            break;

        case NotifyCollectionChangedAction.Replace:
            foreach (var gridView in gridViews)
            {
                for (int i = 0; i < e.NewItems.Count; i++)
                {
                    GridViewColumn column = CreateColumn(gridView, e.NewItems[i]);
                    gridView.Columns[e.NewStartingIndex + i] = column;
                }
            }
            break;

        case NotifyCollectionChangedAction.Reset:
            foreach (var gridView in gridViews)
            {
                gridView.Columns.Clear();
                CreateColumns(gridView, sender as ICollectionView);
            }
            break;

        default:
            break;
        }
    }
 public static List <T> GetFilteredData <T>(this ICollectionView collectionView)
 {
     return(collectionView.Cast <T>().ToList());
 }