/// <summary>
        /// Performs validation based on provided rules and populates <see cref="Errors"/> if any errors occured
        /// </summary>
        /// <returns><c>true</c> if validation successful, <c>false</c> otherwise.</returns>
        public bool Validate()
        {
            _errors.Clear();

            var errors = _validations.Where(v => !v.Validate(Value))
                         .Select(v => v.ValidationMessage);

            _errors.AddRange(errors);

            IsValid = !Errors.Any();

            return(IsValid);
        }
Esempio n. 2
0
        public async Task LoadItemsAsync(string presenterId)
        {
            try
            {
                await Task.Delay(500);//These are needed or the list is blank, investigate further and/or report bug

                Presentations.Clear();
                var items = await DataStore.GetItemsAsync(true);

                await Task.Delay(500);

                presenterId = string.IsNullOrWhiteSpace(presenterId) ? PresenterId : presenterId;

                if (presenterId != null)
                {
                    items = items.Where(x => x.PresenterId == presenterId);
                }


                Presentations.AddRange(items);
                OnPropertyChanged(nameof(Presentations));
            }
            catch (Exception ex)
            {
                Debug.WriteLine(ex);
            }
            finally
            {
                IsBusy = false;
            }
        }
        public void ReplaceRange()
        {
            var collection = new ObservableRangeCollection <int>();
            var toAdd      = new[] { 3, 1, 4, 1, 5, 9, 2, 6, 5, 3, 5, 8, 9, 7, 9, 3, 2, 3 };
            var toRemove   = new[] { 1, 1, 2, 2, 3, 3, 4, 4, 5, 5, 6, 6, 7, 7, 8, 8, 9, 9, 0, 0 };

            collection.AddRange(toRemove);
            collection.CollectionChanged += (s, e) =>
            {
                Assert.AreEqual(NotifyCollectionChangedAction.Reset, e.Action);

                Assert.Null(e.OldItems);
                Assert.Null(e.NewItems);

                Assert.AreEqual(collection.Count, toAdd.Length);

                for (var i = 0; i < toAdd.Length; i++)
                {
                    if (collection[i] != (int)toAdd[i])
                    {
                        throw new NUnitException("Expected and actual items don't match.");
                    }
                }
            };
            collection.ReplaceRange(toAdd);
        }
        public async Task InitializeComponents()
        {
            try
            {
                Components = new ObservableRangeCollection <Component>();
                ComponentKeeper componentKeeper = new ComponentKeeper();
                await componentKeeper.Reload($"PlaceId={_thisProcess.PlaceId}");

                Device.BeginInvokeOnMainThread(() => {
                    Components = new ObservableRangeCollection <Component>();
                    Components.AddRange(componentKeeper.Items);
                    if (Components.Any())
                    {
                        if (_thisProcess.ComponentId != null)
                        {
                            Component = Components.Where(c => c.ComponentId == _thisProcess.ComponentId).FirstOrDefault();
                        }
                        HasComponents = true;
                    }
                    else
                    {
                        HasComponents = false;
                    }
                });
            }
            catch (Exception ex)
            {
                throw;
            }
        }
        public void AddRange()
        {
            var collection = new ObservableRangeCollection <int>();
            var toAdd      = new[] { 3, 1, 4, 1, 5, 9, 2, 6, 5, 3, 5, 8, 9, 7, 9, 3, 2, 3 };

            collection.CollectionChanged += (s, e) =>
            {
                Assert.AreEqual(e.Action,
                                NotifyCollectionChangedAction.Add,
                                "AddRange didn't use Add like requested.");

                Assert.IsNull(e.OldItems, "OldItems should be null.");

                Assert.AreEqual(toAdd.Length,
                                e.NewItems.Count,
                                "Expected and actual OldItems don't match.");

                for (var i = 0; i < toAdd.Length; i++)
                {
                    Assert.AreEqual(toAdd[i], (int)e.NewItems[i],
                                    "Expected and actual NewItems don't match.");
                }
            };
            collection.AddRange(toAdd);
        }
Esempio n. 6
0
        private async Task LoadTagsAsync()
        {
            TagCollection = new ObservableRangeCollection <TagData> ();
            var store = ServiceContainer.Resolve <IDataStore> ();

            var workspaceTags = await store.Table <TagData> ()
                                .Where(r => r.DeletedAt == null && r.WorkspaceId == workspaceId)
                                .ToListAsync();

            var currentSelectedTags = await store.Table <TagData> ()
                                      .Where(r => r.DeletedAt == null && previousSelectedIds.Contains(r.Id))
                                      .ToListAsync();

            // TODO:
            // There is an strange case, tags are created again across
            // workspaces. To avoid display similar names
            // on the list the diff and corrupt data, the filter is done by
            // names. The bad point is that tags will appears unselected.
            var diff = currentSelectedTags.Where(sTag => workspaceTags.All(wTag => sTag.Name != wTag.Name));

            workspaceTags.AddRange(diff);

            workspaceTags.Sort((a, b) => {
                var aName = a != null ? (a.Name ?? String.Empty) : String.Empty;
                var bName = b != null ? (b.Name ?? String.Empty) : String.Empty;
                return(String.Compare(aName, bName, StringComparison.Ordinal));
            });

            TagCollection.AddRange(workspaceTags);
        }
Esempio n. 7
0
        private async Task GetVoteDetails()
        {
            var questions = await MultiChainVm.Model.GetQuestions();

            var questionVMs = questions.Select(q => new QuestionViewModel(this)
            {
                QuestionNumber = q.Number,
                Question       = q.Question,
                Answers        = q.Answers.Select(a => new AnswerViewModel
                {
                    Answer = a.Answer,
                    Info   = a.Info
                }).ToList()
            }).ToList();

            Ui(() =>
            {
                Loading = false;

                Questions.Clear();
                Questions.AddRange(questionVMs);

                TotalQuestions  = questionVMs.Count;
                CurrentQuestion = 1;
                TransitionView.ShowPage(Questions.First());
            });
        }
Esempio n. 8
0
        private async Task LoadIncidents()
        {
            var dialog = Mvx.Resolve <IUserDialogs>();

            dialog.ShowLoading(Messages.Loading);

            var disasterService = Mvx.Resolve <ITap2GiveService>();

            try
            {
                var disasters = await disasterService.GetDisasters(true);

                if (disasters != null)
                {
                    DisasterIncidents.AddRange(disasters.Where(d => !string.IsNullOrEmpty(d.GiveUrl))
                                               .Select(d => new DisasterListItemViewModel(d)));
                }
            }
            catch (Exception ex)
            {
                dialog.HideLoading();
                Mvx.Trace("Unable to load Disasters list, exception: {0}", ex);
                await dialog.AlertAsync("Unable to load Disasters list. Please try again");
            }
            finally
            {
                dialog.HideLoading();
            }
        }
Esempio n. 9
0
 public MorePageViewModel(INavigation navigation, IUserDialogs userDialogs) : base(navigation, userDialogs)
 {
     StorageFeatures.AddRange(new[]
     {
         new MenuItem {
             Name = "Files", Icon = "tab_feed.png", Parameter = "files"
         },
         new MenuItem {
             Name = "Subscriptions", Icon = "tab_feed.png", Parameter = "subscriptions"
         },
     });
     SettingsItems.AddRange(new[]
     {
         new MenuItem {
             Name = "About", Icon = "tab_feed.png", Parameter = "about"
         },
         new MenuItem {
             Name = "Log Out", Icon = "tab_feed.png", Parameter = "logout"
         },
         new MenuItem {
             Name = "Delete Local Blobs", Icon = "tab_feed.png", Parameter = "deletelocalblobs"
         },
     });
     signOnClient = DependencyService.Get <ISignOnClient>();
 }
Esempio n. 10
0
        public ItemsViewModel()
        {
            UserID           = -1;
            Title            = "Browse";
            Jokes            = new ObservableRangeCollection <Joke>();
            LoadItemsCommand = new Command(async() => await ExecuteLoadItemsCommand());

            MessagingCenter.Subscribe <NewItemPage, Joke>(this, "AddJoke", async(obj, item) =>
            {
                var _item    = item as Joke;
                var newJokes = new List <Joke>();
                newJokes.Add(item);
                Jokes.AddRange(newJokes);
                await JokeInitializer.AddItemAsync(_item);
            });

            MessagingCenter.Subscribe <ItemDetailPage, Joke>(this, "DeleteJoke", async(obj, item) =>
            {
                var _item = item as Joke;
                //Jokes.Add(_item);
                var jokeToDelete = new List <Joke>();
                foreach (var el in Jokes)
                {
                    if (el.JokeID == _item.JokeID)
                    {
                        jokeToDelete.Add(el);
                        break;
                    }
                }
                Jokes.RemoveRange(jokeToDelete);
                await JokeInitializer.DeleteItemAsync(_item);
            });
        }
        public void TestAddRange_Reset()
        {
            var collection_01 = new List <int>()
            {
                1, 2, 3
            };
            var collection_02 = new List <int>()
            {
                4, 5
            };
            var collection_marged = new List <int>();

            collection_marged.AddRange(collection_01);
            collection_marged.AddRange(collection_02);

            var orc             = new ObservableRangeCollection <int>(collection_01);
            var isEventOccurred = false;

            orc.CollectionChanged += (sender, e) =>
            {
                isEventOccurred = true;
                Assert.That(e.Action, Is.EqualTo(NotifyCollectionChangedAction.Reset));
            };

            orc.AddRange(collection_02, NotifyCollectionChangedAction.Reset);
            Assert.That(orc, Is.EqualTo(collection_marged));
            Assert.That(isEventOccurred);
        }
        public void TestAddRange()
        {
            var collection_01 = new List <int>()
            {
                1, 2, 3
            };
            var collection_02 = new List <int>()
            {
                4, 5
            };
            var collection_marged = new List <int>();

            collection_marged.AddRange(collection_01);
            collection_marged.AddRange(collection_02);

            var orc             = new ObservableRangeCollection <int>(collection_01);
            var orcCount        = orc.Count;
            var isEventOccurred = false;

            orc.CollectionChanged += (sender, e) =>
            {
                isEventOccurred = true;
                Assert.That(e.Action, Is.EqualTo(NotifyCollectionChangedAction.Add));
                Assert.That(e.NewItems, Is.EqualTo(collection_02));
                Assert.That(e.NewStartingIndex, Is.EqualTo(orcCount));
                Assert.That(e.OldItems, Is.EqualTo(null));
                Assert.That(e.OldStartingIndex, Is.EqualTo(-1));
            };

            orc.AddRange(collection_02);
            Assert.That(orc, Is.EqualTo(collection_marged));
            Assert.That(isEventOccurred);
        }
Esempio n. 13
0
        public void GetClubs()
        {
            ClubsList = new ObservableRangeCollection <Club>();
            var clubs = _documentClient.CreateDocumentQuery <Club>(DOCUMENT_COLLETCTION_URI).Where(x => x.Name != string.Empty).ToList();

            ClubsList.AddRange(clubs);
        }
 private void SetupPages()
 {
     _pages.AddRange(new List <MenuItem>
     {
         new MenuItem
         {
             Name     = "Conference Feed",
             Icon     = "menu_feed.png",
             Pagename = nameof(FeedPage)
         },
         new MenuItem
         {
             Name     = "Sessions",
             Icon     = "menu_sessions.png",
             Pagename = nameof(SessionsPage)
         },
         new MenuItem
         {
             Name     = "Workshops",
             Icon     = "menu_sessions.png",
             Pagename = nameof(WorkshopsPage)
         },
         new MenuItem
         {
             Name     = "Events",
             Icon     = "menu_events.png",
             Pagename = nameof(EventsPage)
         },
         new MenuItem
         {
             Name     = "Sponsors",
             Icon     = "menu_sponsors.png",
             Pagename = nameof(SponsorsPage)
         },
         new MenuItem
         {
             Name     = "Venue",
             Icon     = "menu_venue.png",
             Pagename = nameof(VenuePage)
         },
         new MenuItem
         {
             Name     = "Floor Maps",
             Icon     = "menu_plan.png",
             Pagename = nameof(FloorMapsPage)
         },
         new MenuItem
         {
             Name     = "Conference Info",
             Icon     = "menu_info.png",
             Pagename = nameof(ConferenceInformationPage)
         },
         new MenuItem
         {
             Name     = "Settings",
             Icon     = "menu_settings.png",
             Pagename = nameof(SettingsPage)
         }
     });
 }
Esempio n. 15
0
        public async Task SearchForProduct()
        {
            if (IsBusy)
            {
                return;
            }

            IsBusy = true;

            try
            {
                var result = await ProductsService.SerchForProductByName(SearchedText);

                AllProducts.Clear();
                AllProducts.AddRange(result);
                await Application.Current.MainPage.Navigation.PushAsync(new ShowAllProductsPage(AllProducts));
            }
            catch (Exception e)
            {
                await Application.Current.MainPage.DisplayAlert("Fejl", e.ToString(), "OK");
            }
            finally
            {
                IsBusy = false;
            }
        }
Esempio n. 16
0
        protected async Task Load()
        {
            var dialog = Resolve <IUserDialogs>();

            dialog.ShowLoading(Messages.General.Loading);

            var context = Resolve <AttributedListContext>();

            try
            {
                Title = $"{context.ItemType}s";
                var rawItems = await context.Load();

                if (rawItems != null)
                {
                    Items.AddRange(rawItems.Select(s => new AttributedListItemViewModel(s)));
                }
            }
            catch (Exception ex)
            {
                dialog.HideLoading();
                Mvx.Trace($"Unable to load {context.ItemType} list, exception: {ex}");
                await dialog.AlertAsync($"Unable to load {context.ItemType} list. Please try again");
            }
            finally
            {
                dialog.HideLoading();
            }
        }
        public void RemoveRangeRemoveFact()
        {
            var collection = new ObservableRangeCollection <int>();
            var toAdd      = new[] { 3, 1, 4, 1, 5, 9, 2, 6, 5, 3, 5, 8, 9, 7, 9, 3, 2, 3 };
            var toRemove   = new[] { 1, 1, 2, 2, 3, 3, 4, 4, 5, 5, 6, 6, 7, 7, 8, 8, 9, 9, 0, 0 };

            collection.AddRange(toAdd);
            collection.CollectionChanged += (s, e) =>
            {
                if (e.Action != NotifyCollectionChangedAction.Remove)
                {
                    throw new NUnitException("RemoveRange didn't use Remove like requested.");
                }

                if (e.OldItems == null)
                {
                    throw new NUnitException("OldItems should not be null.");
                }

                var expected = new int[] { 1, 1, 2, 2, 3, 3, 4, 5, 5, 6, 7, 8, 9, 9 };
                if (expected.Length != e.OldItems.Count)
                {
                    throw new NUnitException("Expected and actual OldItems don't match.");
                }

                for (var i = 0; i < expected.Length; i++)
                {
                    if (expected[i] != (int?)e.OldItems[i])
                    {
                        throw new NUnitException("Expected and actual OldItems don't match.");
                    }
                }
            };
            collection.RemoveRange(toRemove, NotifyCollectionChangedAction.Remove);
        }
Esempio n. 18
0
        public void ArkLightCollectionTest()
        {
            var doubleList = new List <List <double> >()
            {
                new List <double> {
                    1, 2, 3
                },
                new List <double> {
                    4, 5, 6, 23, 4, 5
                },
                new List <double> {
                    7, 8, 9
                },
            };
            var list = new double[] { 1, 1, 2, 3, 4, 5, 6, 44 };
            var x    = from score in list where score > 8 select score;
            var dic  = new Dictionary <string, int>()
            {
                { "sss", 1 },
                { "sa", 1 },
                { "s1", 1 },
            };

            Assert.AreEqual("{\"sss\" : 1, \"sa\" : 1, \"s1\" : 1}", dic.ToKeyValuePairString());
            var items = new ObservableRangeCollection <int>();

            items.AddRange(new int[] { 1, 2, 3 });
            Assert.AreEqual(1, items[0]);
        }
Esempio n. 19
0
        private void OnSearchCommand()
        {
            SearchResultListChanged();
            _searchResultsInternal.Clear();
            if (!string.IsNullOrWhiteSpace(_searchValue))
            {
                var searchValue = _searchValue.ToLower();

                Task.Run(async() =>
                {
                    var events = await _repository.FindAll(EventModelExtensions.GetSearchCondition(searchValue));
                    if (events != null)
                    {
                        Device.BeginInvokeOnMainThread(() =>
                        {
                            if (events.Any())
                            {
                                var tempList = new List <SearchResult>();
                                events.OrderByDescending(e => e.Start).ToList().ForEach(_ => tempList.Add(SearchResult.FromEvent(_, searchValue)));
                                _searchResultsInternal.AddRange(tempList);
                            }
                        });
                    }
                });
            }
        }
Esempio n. 20
0
 public bool CreateAccount(List <IAccountInterface> oAccountData)
 {
     m_oAccounts.AddRange(oAccountData);
     m_oAccounts.CollectionChanged -= M_oAccounts_CollectionChanged;
     m_oAccounts.CollectionChanged += M_oAccounts_CollectionChanged;
     return(true);
 }
        public void AddRange_WhenCalledWithNullRange_ThrowsCorrectException(
            NotifyCollectionChangedAction notificationMode)
        {
            var collection = new ObservableRangeCollection <int>();

            Assert.Throws <ArgumentNullException>(() => collection.AddRange(null, notificationMode));
        }
Esempio n. 22
0
        public void ReplaceRange()
        {
            var collection = new ObservableRangeCollection <int>();
            var toAdd      = new[] { 3, 1, 4, 1, 5, 9, 2, 6, 5, 3, 5, 8, 9, 7, 9, 3, 2, 3 };
            var toRemove   = new[] { 1, 1, 2, 2, 3, 3, 4, 4, 5, 5, 6, 6, 7, 7, 8, 8, 9, 9, 0, 0 };

            collection.AddRange(toRemove);
            collection.CollectionChanged += (s, e) =>
            {
                Assert.Equal(NotifyCollectionChangedAction.Reset,
                             e.Action);                       //,
                                                              //"ReplaceRange didn't use Remove like requested.");

                Assert.Null(e.OldItems);                      //, "OldItems should be null.");
                Assert.Null(e.NewItems);                      //, "NewItems should be null.");

                Assert.Equal(collection.Count, toAdd.Length); //, "Lengths are not the same");

                for (var i = 0; i < toAdd.Length; i++)
                {
                    if (collection[i] != (int)toAdd[i])
                    {
                        Assert.True(false);//Fail("Expected and actual items don't match.");
                    }
                }
            };
            collection.ReplaceRange(toAdd);
        }
        private void RefreshViewModel()
        {
            ObservableRangeCollection <ViewModel_DiaryPage> entries = new ObservableRangeCollection <ViewModel_DiaryPage>();

            entries.AddRange(UserDiaryFileController.Load());
            DiaryEntries = entries;
        }
        public void RemoveRange_RemoveTest()
        {
            ObservableRangeCollection <int> collection = new ObservableRangeCollection <int>();

            int[] toAdd    = new[] { 3, 1, 4, 1, 5, 9, 2, 6, 5, 3, 5, 8, 9, 7, 9, 3, 2, 3 };
            int[] toRemove = new[] { 1, 1, 2, 2, 3, 3, 4, 4, 5, 5, 6, 6, 7, 7, 8, 8, 9, 9, 0, 0 };
            collection.AddRange(toAdd);
            collection.CollectionChanged += (s, e) =>
            {
                if (e.Action != System.Collections.Specialized.NotifyCollectionChangedAction.Remove)
                {
                    Assert.Fail("RemoveRange didn't use Remove like requested.");
                }
                if (e.OldItems == null)
                {
                    Assert.Fail("OldItems should not be null.");
                }
                int[] expected = new int[] { 1, 1, 2, 2, 3, 3, 4, 5, 5, 6, 7, 8, 9, 9 };
                if (expected.Length != e.OldItems.Count)
                {
                    Assert.Fail("Expected and actual OldItems don't match.");
                }
                for (int i = 0; i < expected.Length; i++)
                {
                    if (expected[i] != (int)e.OldItems[i])
                    {
                        Assert.Fail("Expected and actual OldItems don't match.");
                    }
                }
            };
            collection.RemoveRange(toRemove, System.Collections.Specialized.NotifyCollectionChangedAction.Remove);
        }
Esempio n. 25
0
        private async Task Load()
        {
            var dialog = Resolve <IUserDialogs>();

            dialog.ShowLoading(Messages.General.Loading);
            try
            {
                var disasterService = Resolve <ITap2HelpService>();

                var disasters = await disasterService.GetDisasters();

                if (disasters != null)
                {
                    Items.AddRange(disasters.Select(d => new DisasterListItemViewModel(d)));
                }
            }
            catch (Exception ex)
            {
                dialog.HideLoading();
                Mvx.Trace("Unable to load Disasters list, exception: {0}", ex);
                await dialog.AlertAsync("Unable to load Disasters list. Please try again");
            }
            finally
            {
                dialog.HideLoading();
            }
        }
Esempio n. 26
0
        public void GroupingSubKey()
        {
            var grouped = new ObservableRangeCollection <Grouping <string, string, Person> >();
            var people  = new[]
            {
                new Person {
                    FirstName = "Joseph", LastName = "Hill"
                },
                new Person {
                    FirstName = "James", LastName = "Montemagno"
                },
                new Person {
                    FirstName = "Pierce", LastName = "Boggan"
                },
            };

            var sorted = from person in people
                         orderby person.FirstName
                         group person by person.SortName into personGroup
                         select new Grouping <string, string, Person>(personGroup.Key, personGroup.Key, personGroup);

            grouped.AddRange(sorted);

            Assert.AreEqual(2, grouped.Count, "There should be 2 groups");
            Assert.AreEqual("J", grouped[0].SubKey, "Key for group 0 should be J");
            Assert.AreEqual("J", grouped[0].Key, "Key for group 0 should be J");
            Assert.AreEqual(2, grouped[0].Count, "There should be 2 items in group 0");
            Assert.AreEqual(1, grouped[1].Count, "There should be 1 items in group 1");
            Assert.AreEqual(2, grouped[0].Items.Count, "There should be 2 items in group 0");
            Assert.AreEqual(1, grouped[1].Items.Count, "There should be 1 items in group 1");
        }
        public async Task InitializeAsync()
        {
            using (new ProcessingScope(this))
            {
                _settings = await _findTextureManagementSettingsQuery.FindAsync();

                _textures.Clear();

                TexturePreview.ShowEmpty();
                if (_settings.SourceDirectory.IsNullOrEmpty())
                {
                    return;
                }

                IEnumerable <TextureFile> files = null;
                await _actionBuilder.Dispatch(new LoadTextureFilesCommand(_settings.SourceDirectory))
                .CompleteFor <TextureFilesLoadedNotification>((context, @event) => files = @event.Files)
                .CompleteFor <ErrorOccuredNotification>(async(context, @event) => await PublishUnknownErrorEventAsync())
                .OnTimeout(async() => await PublishTimeoutEventAsync())
                .Execute();

                _textures.AddRange(files
                                   .OrderBy(file => file.Length)
                                   .ThenBy(file => file.FilePath)
                                   .Select(file => new TextureNodeViewModel(file, this, _filePicker, TexturePreview)));
            }

            Rebind();
        }
Esempio n. 28
0
        private async Task LoadTagsAsync ()
        {
            TagCollection = new ObservableRangeCollection<TagData> ();
            var store = ServiceContainer.Resolve<IDataStore> ();

            var workspaceTags = await store.Table<TagData> ()
                                .Where (r => r.DeletedAt == null && r.WorkspaceId == workspaceId)
                                .ToListAsync();
            var currentSelectedTags = await store.Table<TagData> ()
                                      .Where (r => r.DeletedAt == null && previousSelectedIds.Contains (r.Id))
                                      .ToListAsync();

            // TODO:
            // There is an strange case, tags are created again across
            // workspaces. To avoid display similar names
            // on the list the diff and corrupt data, the filter is done by
            // names. The bad point is that tags will appears unselected.
            var diff = currentSelectedTags.Where (sTag => workspaceTags.All (wTag => sTag.Name != wTag.Name));

            workspaceTags.AddRange (diff);

            workspaceTags.Sort ((a, b) => {
                var aName = a != null ? (a.Name ?? String.Empty) : String.Empty;
                var bName = b != null ? (b.Name ?? String.Empty) : String.Empty;
                return String.Compare (aName, bName, StringComparison.Ordinal);
            });

            TagCollection.AddRange (workspaceTags);
        }
Esempio n. 29
0
        public WatchVM()
        {
            WatchProjects = new ObservableRangeCollection <Project>();

            var range = new List <Project>(App.DBWatch.GetItems());

            WatchProjects.AddRange(range);

            //fixes indicators when page loads 1st time
            foreach (var p in WatchProjects)
            {
                p.IsBusy = false;
            }

            MessagingCenter.Subscribe <Project>(this, "MsgAddWatchProject", (project) =>
            {
                App.DBWatch.SaveItem(project);
                WatchProjects.Add(project);

                Fetch(project);
            });

            FetchCommand = new Command(Fetch);

            WatchAddCommand = new Command(async() => {
                await Navigation.PushAsync(new WatchAddPage(new Project()));
            });

            WatchDeleteCommand = new Command(Delete);
        }
Esempio n. 30
0
        /// <summary>
        /// Temp colour code. As stated above should be driven from service.
        /// </summary>
        /// <param name="backingStore">Value to update</param>
        /// <param name="value">The new value</param>
        /// <param name="colour">Which colour is this</param>
        private void ToggleColour(ref bool backingStore, bool value, ColourEnum colour)
        {
            // Update the property on this VM
            SetProperty(ref backingStore, value);

            // Copy the existing colours to a new object so we can force an update (and trigger the binding to update)
            var colours = new ObservableRangeCollection <Colour>();

            colours.AddRange(this.Person.Colours);

            // Also ensure the colours in the person's colour collection is correct
            if (value)
            {
                // The colour must be present
                if (!colours.Where(c => c.Id == (int)colour).Any())
                {
                    colours.Add(new Colour()
                    {
                        Id = (int)colour, Name = colour.ToString()
                    });
                }
            }
            else
            {
                // Make sure the colour is not there
                var existingColour = colours.FirstOrDefault(c => c.Id == (int)colour);
                if (existingColour != null)
                {
                    colours.Remove(existingColour);
                }
            }

            // Update the colour collection and trigger the refresh
            this.Person.Colours = colours;
        }
Esempio n. 31
0
        public MenuPageViewModel()
        {
            menuItems = new ObservableRangeCollection <MenuItem>();

            menuItems.AddRange(new List <MenuItem> {
                new MenuItem {
                    Label = "Sync",
                    Icon  = "\uE895",
                    Page  = new SyncPage()
                },
                new MenuItem {
                    Label = "New Transaction",
                    Icon  = "\uE710",
                    Page  = new AddOrEditTransactionPage(null)
                },
                new MenuItem {
                    Label = "All Transactions",
                    Icon  = "\uE8AB",
                    Page  = new TransactionsPage()
                },
                new MenuItem {
                    Label = "My Items",
                    Icon  = "\uE8BC",
                    Page  = new ItemsPage()
                },
                new MenuItem {
                    Label = "About",
                    Icon  = "\uE716",
                    Page  = new AboutPage()
                }
            });
        }
        public MenuItemViewModel(string rpText, ICommand rpCommand)
        {
            Title = rpText;
            Command = rpCommand;

            r_Items = new ObservableRangeCollection<object>();

            var rItems = CreateMenuItems();
            if (rItems != null)
                r_Items.AddRange(rItems);
        }
        public void GroupingTestCase()
        {

            var grouped = new ObservableRangeCollection<Grouping<string, Person>>();
            var people = new[]
            { 
                new Person { FirstName = "Joseph", LastName = "Hill" },
                new Person { FirstName = "James", LastName = "Montemagno" },
                new Person { FirstName = "Pierce", LastName = "Boggan" },
            };

            var sorted = from person in people
                                  orderby person.LastName
                                  group person by person.SortName into personGroup
                                  select new Grouping<string, Person>(personGroup.Key, personGroup);

            grouped.AddRange(sorted);
           
        }
Esempio n. 34
0
        /// <summary>
        /// Установка видимости для кнопок, сответствующим местам в вагоне
        /// Видимая - если место занято,
        /// </summary>
        /// <param name="seats"></param>
        /// <param name="visibility"></param>
        private void SetWagonSeatsButtonsVisibility(WagonSeatsSet seats, ObservableRangeCollection<String> visibility)
        {
            visibility.Clear();

            visibility.AddRange(seats.Seats.Select(seatIsFree => 
            {
                return seatIsFree ? freeSeatOpacity : occupiedSeatOpacity;
            }));
        }
 private void InitializeCategories()
 {
     List<Entry> entries = DataHandler.Instance.GetAllEntries().OrderBy(entry => entry.Category).ToList();
     EntriesObservableCollection = new ObservableCollection<Entry>();
     foreach (Entry entry in entries)
     {
         EntriesObservableCollection.Add(entry);
     }
     List<string> distinctCategories = EntriesObservableCollection.Select(k => k.Category).Distinct().ToList();
     CategoriesListObservableCollection = new ObservableRangeCollection<string>();
     CategoriesListObservableCollection.AddRange(distinctCategories);
     CategoriesList.ItemsSource = CategoriesListObservableCollection;
 }
        void StartTwitterErase(object nbParallelConnectionsObj)
        {
            int nbParallelConnections = (int)nbParallelConnectionsObj;

            TwitterContext ctx = (TwitterContext)Application.Current.Properties["context"];

            //No need to synchronize here, all tasks are (supposed?) not started yet.
            nbTweetsToErase = tweets.Where(t => t.ToErase == true || !String.IsNullOrEmpty(t.Status)).Count();

            #if !DEBUG
            if (ctx == null)
            {
                MessageBox.Show("Error loading twitter authentication info; please try again", "Twitter Archive Eraser", MessageBoxButton.OK, MessageBoxImage.Error);
                isErasing = false;
                EnableControls();
                return;
            }
            #endif

            #if DEBUG
            sleepFakeWaitMilliseconds = 5000 / nbParallelConnections;
            #endif

            Task[] tasks = new Task[nbParallelConnections];

            for (int i = 0; i < nbParallelConnections; i++)
            {
                tasks[i] = Task.Factory.StartNew(() => EraseTweetsAction(ctx, cancellationSource.Token));
            }

            try
            {
                Task.WaitAll(tasks);
                EnableControls();
            }
            catch (Exception e)
            {
                nextTweetID = 0;
            }

            isErasing = false;  // Done erasing

            if (nbTweetsDeleted >= (nbTweetsToErase - nbParallelConnections))
            {
                progressBar.Dispatcher.BeginInvoke(new Action(delegate()
                {
                    progressBar.Value = 100;
                    txtPrcnt.Text = "100%";

                    EnableControls();
                    nextTweetID = 0;
                    nbTweetsDeleted = 0;
                    nbTweetsToErase = 0;

                    if (notDeletedTweets.Count == 0)
                    {
                        MessageBox.Show("Done! Everything is clean ;).\n", "Twitter Archive Eraser", MessageBoxButton.OK, MessageBoxImage.Information);
                    }
                    else
                    {
                        string jsonTweets = JsonConvert.SerializeObject(notDeletedTweets);
                        File.WriteAllText(notDeletedTweetsFilename, jsonTweets);

                        if(MessageBox.Show(notDeletedTweets.Count + " tweets were not deleted!\n" +
                                                                 "Do you want to retry deleting these tweets again?\n\n" +
                                                                 "You can try deleting these tweets later by loading them in Twitter Archive Eraser from the following file:\n\n" +
                                                                 notDeletedTweetsFilename + "\n\n" +
                                                                 "Select 'Yes' to retry now, or 'No' to retry later",
                                        "Twitter Archive Eraser",
                                        MessageBoxButton.YesNo,
                                        MessageBoxImage.Exclamation) == MessageBoxResult.Yes)
                        {
                            WebUtils.ReportStats((string)Application.Current.Properties["userName"],
                                                  (string)Application.Current.Properties["sessionGUID"],
                                                  tweets.Count,
                                                  tweets.Where(t => String.Equals(t.Status, STATUS_DELETED)).Count(),
                                                  tweets.Where(t => String.Equals(t.Status, STATUS_NOT_FOUND)).Count(),
                                                  tweets.Where(t => String.Equals(t.Status, STATUS_ERROR)).Count(),
                                                  tweets.Where(t => String.Equals(t.Status, STATUS_NOT_ALLOWED)).Count(),
                                                  true,
                                                  nbParallelConnections,
                                                  filters,
                                                  (DateTime.Now - startTime).TotalSeconds);

                            tweets = new ObservableRangeCollection<Tweet>();
                            tweets.AddRange(notDeletedTweets.Select(t => new Tweet(){
                                                                Text = t.text,
                                                                ID = t.id_str,
                                                                IsRetweet = t.retweeted_status != null ? "    ✔" : "",
                                                                Status = "",
                                                                ToErase = true,
                                                                Date = ParseDateTime(t.created_at)
                                        }));

                            // We pass an empty list of jsFiles to reuse code from DeleteTweets_Loaded
                            // Nothing of clean code I know!
                            // Sometimes I have hard times sleeping because I know such things is released to the wild
                            Application.Current.Properties["jsFiles"] = new List<JsFile>();
                            DeleteTweets_Loaded(null, null);
                        }
                    }
                }));
            }
        }
        void StartTwitterErase(int nbParallelConnections)
        {
            TwitterContext ctx = appSettings.Context;

            //No need to synchronize here, no tasks were started yet.
            nbTweetsToErase = mTweetsCollection.Where(t => t.ToErase == true && string.IsNullOrEmpty(t.Status) /* did not get deleted previously */).Count();
            nbOutstandingOperations = nbTweetsToErase;
            nextTweetID = 0;

            #if !DEBUG_TEST
            if (ctx == null)
            {
                MessageBox.Show("Error loading twitter authentication info; please try again", "Twitter Archive Eraser", MessageBoxButton.OK, MessageBoxImage.Error);
                isCurrentlyErasing = false;
                SetStoppedDeletionState();
                return;
            }
            #endif

            #if DEBUG_TEST
            sleepFakeWaitMilliseconds = 1000;
            #endif

            Task[] tasks = new Task[nbParallelConnections];

            for (int i = 0; i < nbParallelConnections; i++)
            {
                tasks[i] = Task.Factory.StartNew(() => EraseTweetsAction(ctx, globalCancellationSource.Token));
            }

            try
            {
                Task.WaitAll(tasks);
            }
            catch (Exception e)
            {
                nextTweetID = 0;
                RunOnUIThread(delegate ()
                {
                    MessageBox.Show("Error: " + e.Message);
                });
            }
            finally
            {

                SetStoppedDeletionState();

                // This is called after all tasks are canceled, should renew cacelation token
                globalCancellationSource = new CancellationTokenSource();
            }

            isCurrentlyErasing = false;  // Done erasing

            //termination condition
            if (nbOutstandingOperations == 0) // nbTweetsDeleted >= (nbTweetsToErase - nbParallelConnections))
            {
                RunOnUIThread(delegate()
                {
                    progressBar.Value = 100;
                    txtPrcnt.Text = "100%";

                    SetStoppedDeletionState();
                    nextTweetID = 0;
                    nbTweetsToErase = 0;

                    var lastTweet = mTweetsCollection.Where(t => !string.IsNullOrEmpty(t.Status)).LastOrDefault();
                    if(lastTweet != null)
                    {
                        gridTweets.BringItemIntoView(lastTweet);
                    }

                    appSettings.TotalRunningMillisec += runningTime.ElapsedMilliseconds;

                    if (notDeletedTweets.Count == 0)
                    {
                        ShowShareTweetDialog(mTweetsCollection.Where(t => String.Equals(t.Status, STATUS_DELETED)).Count());
                    }
                    else
                    {
                        string jsonTweets = JsonConvert.SerializeObject(notDeletedTweets);
                        File.WriteAllText(notDeletedTweetsFilename, jsonTweets);

                        if (MessageBox.Show(notDeletedTweets.Count + " tweets were not deleted!\n" +
                                                                 "Do you want to retry deleting these tweets again?\n\n" +
                                                                 "You can try deleting these tweets later by loading them in Twitter Archive Eraser from the following file:\n\n" +
                                                                 notDeletedTweetsFilename + "\n\n" +
                                                                 "Select 'Yes' to retry now, or 'No' to retry later",
                                        "Twitter Archive Eraser",
                                        MessageBoxButton.YesNo,
                                        MessageBoxImage.Exclamation) == MessageBoxResult.Yes)
                        {
                            WebUtils.ReportStats(appSettings.Username,
                                                  appSettings.SessionId.ToString(),
                                                  appSettings.EraseType.ToString(),
                                                  mTweetsCollection.Count,
                                                  mTweetsCollection.Where(t => String.Equals(t.Status, STATUS_DELETED)).Count(),
                                                  mTweetsCollection.Where(t => String.Equals(t.Status, STATUS_NOT_FOUND)).Count(),
                                                  mTweetsCollection.Where(t => String.Equals(t.Status, STATUS_ERROR)).Count(),
                                                  mTweetsCollection.Where(t => String.Equals(t.Status, STATUS_NOT_ALLOWED)).Count(),
                                                  true,
                                                  nbParallelConnections,
                                                  filters,
                                                  (DateTime.Now - startTime).TotalSeconds);

                            gridTweets.ItemsSource = null;
                            gridTweets.Items.Refresh();

                            tweetsCollectionView = null;

                            mTweetsCollection = new ObservableRangeCollection<Tweet>();

                            mTweetsCollection.AddRange(notDeletedTweets.Select(t => new Tweet()
                            {
                                Text = t.text,
                                ID = t.id_str,
                                Type = t.retweeted_status != null ? TweetType.Retweet : TweetType.Tweet,
                                Status = "",
                                ToErase = true,
                                Date = Helpers.ParseDateTime(t.created_at)
                            }));

                            areTweetsFetchedThroughAPI = true;

                            notDeletedTweets.Clear();

                            // We pass an empty list of jsFiles to reuse code from DeleteTweets_Loaded
                            // Nothing of clean code I know!
                            // Sometimes I have hard times sleeping because I know such things are released in the wild
                            appSettings.JsFiles = new List<JsFile>();
                            DeleteTweets_Loaded(null, null);
                        }
                        else
                        {
                            ShowShareTweetDialog(mTweetsCollection.Where(t => String.Equals(t.Status, STATUS_DELETED)).Count());
                        }
                    }
                });
            }
        }