public void Should_raise_changed_event_when_adding_deleting_and_manual()
        {
            var changedEvents = new List <NotifyCollectionChangedEventArgs>();
            var collection    = new CustomObservableCollection <string>();

            collection.CollectionChanged += (s, e) => changedEvents.Add(e);

            collection.Add("one");
            collection.Add("two");
            collection.Remove("one");
            collection.RaiseCollectionChanged();

            Assert.AreEqual(4, changedEvents.Count);

            Assert.AreEqual(NotifyCollectionChangedAction.Add, changedEvents[0].Action);
            Assert.AreEqual("one", changedEvents[0].NewItems.OfType <string>().FirstOrDefault());

            Assert.AreEqual(NotifyCollectionChangedAction.Add, changedEvents[1].Action);
            Assert.AreEqual("two", changedEvents[1].NewItems.OfType <string>().FirstOrDefault());

            Assert.AreEqual(NotifyCollectionChangedAction.Remove, changedEvents[2].Action);
            Assert.AreEqual("one", changedEvents[2].OldItems.OfType <string>().FirstOrDefault());

            Assert.AreEqual(NotifyCollectionChangedAction.Reset, changedEvents[3].Action);
        }
Exemplo n.º 2
0
        /*
         * Refreshes the page information
         */
        private void refreshDetails()
        {
            bool allOrgansDonated = false;

            savedLives  = calculateSavedLives();
            helpedLives = calculateHelpedLives();

            savedPeopleGrid.Children.Clear();
            helpedPeopleGrid.Children.Clear();

            Random rnd = new Random();

            for (int i = 0; i < savedLives; i++)
            {
                int humanToChoose = rnd.Next(1, 35);
                var image         = new Image {
                    Source = $"human{humanToChoose}.png"
                };
                image.Scale = 0.5;

                savedPeopleGrid.Children.Add(image);
            }

            for (int i = 0; i < helpedLives; i++)
            {
                int humanToChoose = rnd.Next(1, 35);
                var image         = new Image {
                    Source = $"human{humanToChoose}.png"
                };
                image.Scale = 0.5;

                helpedPeopleGrid.Children.Add(image);
            }

            if (savedLives + helpedLives == 11)
            {
                allOrgansDonated = true;
            }

            recommendationsList.Clear();

            if (!allOrgansDonated)
            {
                recommendationsList.Add("Donate more organs");
            }

            if (UserController.Instance.photoObject == null)
            {
                recommendationsList.Add("Add a profile photo");
            }

            recommendationsList.Add("Add in more details about yourself");

            savedLivesText.Text  = String.Format("You could save {0} lives", calculateSavedLives());
            helpedLivesText.Text = String.Format("and you could also help {0} lives", calculateHelpedLives());
        }
Exemplo n.º 3
0
 /// <summary>
 /// Loads all XMPPClients from the DB and inserts them into the clients list.
 /// </summary>
 private void loadClients()
 {
     CLIENT_SEMA.Wait();
     CLIENTS.Clear();
     foreach (XMPPAccount acc in AccountDBManager.INSTANCE.loadAllAccounts())
     {
         CLIENTS.Add(loadAccount(acc));
     }
     CLIENT_SEMA.Release();
 }
Exemplo n.º 4
0
 /// <summary>
 /// Loads all XMPPClients from the DB and inserts them into the clients list.
 /// </summary>
 private void LoadClients()
 {
     CLIENT_SEMA.Wait();
     CLIENTS.Clear();
     foreach (XMPPAccount account in AccountDBManager.INSTANCE.loadAllAccounts())
     {
         ClientConnectionHandler client = new ClientConnectionHandler(account);
         client.ClientConnected += OnClientConnected;
         CLIENTS.Add(client);
     }
     CLIENT_SEMA.Release();
 }
Exemplo n.º 5
0
        //ALL BOOKS BY ALL USERS
        public async Task <CustomObservableCollection <Activity> > GetActiveBooksByAllUsers(int uid)
        {
            var retList = new CustomObservableCollection <Activity>();

            if (CrossConnectivity.Current.IsConnected)
            {
                db = new AzureDB($"Activity/{0}/all");
                var books = await db.GetAllItems <Activity>(true);

                //Order by User on top
                var soList = books.OrderBy(e => e.FullName).Where(e => e.IsReading == true);

                foreach (var item in soList)
                {
                    if (item.UserId != uid)
                    {
                        var n = item.FullName.ToFriendlyName();
                        item.B1Text   = $"{n} Books";
                        item.B2Text   = $"Read {item.Book.Title}";
                        item.LineItem = $"{item.FullName.ToLineItemName()} is reading {item.Book.Title}";
                        retList.Add(item);
                    }
                }
            }

            return(retList);
        }
        private void showResultDisco(DiscoResponseMessage disco)
        {
            rooms.Clear();
            messageResponseHelper?.Dispose();
            messageResponseHelper = null;

            if (disco == null || disco.ITEMS == null || disco.ITEMS.Count <= 0)
            {
                // Show non found in app notification:
                noneFound_notification.Show("None found. Please retry!");
            }
            else
            {
                foreach (DiscoItem i in disco.ITEMS)
                {
                    rooms.Add(new MUCRoomTemplate()
                    {
                        client   = Client,
                        roomInfo = new MUCRoomInfo()
                        {
                            jid  = i.JID ?? "",
                            name = i.NAME ?? (i.JID ?? "")
                        }
                    });
                }
            }

            loading_grid.Visibility = Visibility.Collapsed;
            main_grid.Visibility    = Visibility.Visible;
        }
Exemplo n.º 7
0
 public void Add(Uri feedUrl)
 {
     Feed.CreateFrom(feedUrl, f =>
     {
         feeds.Add(f);
         Save();
     });
 }
Exemplo n.º 8
0
        /// <summary>
        /// Loads the given account and adds it to the list of clients (<see cref="CLIENTS"/>).
        /// </summary>
        /// <param name="account">The <see cref="AccountModel"/> that should be added.</param>
        private ClientConnectionHandler LoadClient(AccountModel account)
        {
            ClientConnectionHandler client = new ClientConnectionHandler(account);

            client.ClientConnected += OnClientConnected;
            CLIENTS.Add(client);
            return(client);
        }
Exemplo n.º 9
0
        private void AddImage(BackgroundImageSelectionControlItemDataTemplate img, string curBackgroundImagePath)
        {
            IMAGES.Add(img);

            if (ChatBackgroundHelper.INSTANCE.BackgroundMode != ChatBackgroundMode.CUSTOM_IMAGE && string.Equals(curBackgroundImagePath, img.Path))
            {
                SelectedItem = img;
            }
        }
Exemplo n.º 10
0
 private void addDummyMessage(string msg, string fromUser, MessageState state, bool isImage)
 {
     chatMessages.Add(new ChatMessageDataTemplate()
     {
         chat    = Chat,
         message = new ChatMessageTable()
         {
             message        = msg,
             chatId         = Chat.id,
             fromUser       = fromUser,
             date           = DateTime.Now,
             state          = state,
             type           = MessageMessage.TYPE_CHAT,
             isImage        = isImage,
             isDummyMessage = true
         }
     });
 }
 /// <summary>
 /// When the Add Affected organ is clicked, the selected organ is added to affected organs
 /// </summary>
 /// <param name="sender"></param>
 /// <param name="e"></param>
 private void AddAffectedOrganClicked(object sender, EventArgs e)
 {
     if (NewAffectedOrganPicker.SelectedItem == null)
     {
         // List is empty
         return;
     }
     organsAffected.Add(NewAffectedOrganPicker.SelectedItem.ToString());
     organsAvailable.Remove(NewAffectedOrganPicker.SelectedItem.ToString());
 }
 private void AddClients(IList list)
 {
     foreach (object item in list)
     {
         if (item is XMPPClient client)
         {
             ACCOUNTS.Add(new AccountDataTemplate
             {
                 Client = client
             });
         }
     }
 }
Exemplo n.º 13
0
        //Get Entire Library
        public async Task <CustomObservableCollection <Book> > GetAllBooksAsync()
        {
            var retList = new CustomObservableCollection <Book>();

            //Check to see if this is persisted
            if (AppSettings.Contains(Constants.LibKey) && LocalArchive.Length > 2)
            {
                string json = LocalArchive;

                var books = await Task.Run(() => JsonConvert.DeserializeObject <IEnumerable <Book> >(json));

                foreach (var item in books)
                {
                    retList.Add(item);
                }
            }

            else if (CrossConnectivity.Current.IsConnected)
            {
                db = new AzureDB("Book");
                var books = await db.GetAllItems <Book>(true);

                foreach (var item in books)
                {
                    retList.Add(item);
                }

                //Serialize to string and Persist Library
                var serJson = JsonConvert.SerializeObject(books);
                LocalArchive = serJson;
                return(retList);
            }
            else
            {
                //TODO sqllite
            }

            return(retList);
        }
        public void Should_raise_changed_event_when_adding_deleting_and_manual()
        {
            var changedEvents = new List<NotifyCollectionChangedEventArgs>();
            var collection = new CustomObservableCollection<string>();
            collection.CollectionChanged += (s, e) => changedEvents.Add(e);

            collection.Add("one");
            collection.Add("two");
            collection.Remove("one");
            collection.RaiseCollectionChanged();

            Assert.AreEqual(4, changedEvents.Count);

            Assert.AreEqual(NotifyCollectionChangedAction.Add, changedEvents[0].Action);
            Assert.AreEqual("one", changedEvents[0].NewItems.OfType<string>().FirstOrDefault());

            Assert.AreEqual(NotifyCollectionChangedAction.Add, changedEvents[1].Action);
            Assert.AreEqual("two", changedEvents[1].NewItems.OfType<string>().FirstOrDefault());

            Assert.AreEqual(NotifyCollectionChangedAction.Remove, changedEvents[2].Action);
            Assert.AreEqual("one", changedEvents[2].OldItems.OfType<string>().FirstOrDefault());

            Assert.AreEqual(NotifyCollectionChangedAction.Reset, changedEvents[3].Action);
        }
Exemplo n.º 15
0
        //ALL READ BOOKS BY USER(either current user or another app user)
        public async Task <CustomObservableCollection <Activity> > GetAllBooksByUser(int id, bool refresh = false)
        {
            var retList = new CustomObservableCollection <Activity>();
            var act     = await GetBooksByUser(id, refresh, !refresh);

            //Sort active on top
            var soList = act.OrderBy(e => e.IsReading ? 0 : 1).ThenBy(e => e.Book.Title);

            foreach (var item in soList)
            {
                item.LineItem = $"{item.Book.Title} - {item.Book.Author}";

                retList.Add(item);
            }

            return(retList);
        }
Exemplo n.º 16
0
        private bool onNewMessage(IQMessage iq)
        {
            if (iq is RoomInfoMessage)
            {
                RoomInfoMessage responseMessage = iq as RoomInfoMessage;

                // Add controls and update viability:
                Dispatcher.RunAsync(CoreDispatcherPriority.Normal, () =>
                {
                    fields.Clear();
                    roomConfigType_tbx.Text = "Configuration level: " + Utils.mucAffiliationToString(responseMessage.CONFIG_LEVEL);
                    foreach (Field o in responseMessage.ROOM_CONFIG.FIELDS)
                    {
                        if (o.type != FieldType.HIDDEN)
                        {
                            fields.Add(new MUCInfoFieldTemplate()
                            {
                                field = o
                            });
                        }
                    }
                    reload_btn.IsEnabled = true;
                    notificationBanner_ian.Dismiss();
                    timeout_stckpnl.Visibility = Visibility.Collapsed;
                    loading_grid.Visibility    = Visibility.Collapsed;
                    info_grid.Visibility       = Visibility.Visible;
                }).AsTask();
                return(true);
            }
            else if (iq is IQErrorMessage errorMessage)
            {
                Dispatcher.RunAsync(CoreDispatcherPriority.Normal, () =>
                {
                    fields.Clear();
                    retry_btn.IsEnabled        = true;
                    info_grid.Visibility       = Visibility.Collapsed;
                    loading_grid.Visibility    = Visibility.Collapsed;
                    timeout_stckpnl.Visibility = Visibility.Visible;

                    notificationBanner_ian.Show("Failed to request configuration! Server responded:\nType: " + errorMessage.ERROR_OBJ.ERROR_NAME + "\nMessage: " + errorMessage.ERROR_OBJ.ERROR_MESSAGE);
                }).AsTask();
            }
            return(false);
        }
Exemplo n.º 17
0
 private void LoadRecentEmoji()
 {
     Task.Run(() =>
     {
         IsLoading = true;
         if (Settings.LOCAL_OBJECT_STORAGE_HELPER.KeyExists(SettingsConsts.CHAT_RECENT_EMOJI))
         {
             int[] result = Settings.LOCAL_OBJECT_STORAGE_HELPER.Read <int[]>(SettingsConsts.CHAT_RECENT_EMOJI);
             foreach (int i in result)
             {
                 if (TryGetEmoji(i, out SingleEmoji emoji))
                 {
                     EMOJI_RECENT.Add(emoji);
                 }
             }
         }
         IsLoading = false;
     });
 }
Exemplo n.º 18
0
        public void replaceOmemoPreKey(uint preKeyId, IOmemoStore omemoStore)
        {
            // Remove key:
            foreach (PreKeyRecord key in OMEMO_PRE_KEYS)
            {
                if (key.getId() == preKeyId)
                {
                    OMEMO_PRE_KEYS.Remove(key);
                    omemoStore.RemovePreKey(preKeyId);
                    break;
                }
            }

            // Generate new key:
            PreKeyRecord newKey = KeyHelper.generatePreKeys(preKeyId, 1)[0];

            OMEMO_PRE_KEYS.Add(newKey);
            omemoStore.StorePreKey(newKey.getId(), newKey);
            omemoBundleInfoAnnounced = false;
        }
Exemplo n.º 19
0
        //ALL BOOKS Activity by book id
        public async Task <CustomObservableCollection <Activity> > GetBookReviews(int id)
        {
            var retList = new CustomObservableCollection <Activity>();

            if (CrossConnectivity.Current.IsConnected)
            {
                db = new AzureDB($"Activity/book/all/{id}");
                var act = await db.GetAllItems <Activity>(true);

                //Order by User on top
                var soList = act.OrderBy(e => e.FullName);

                foreach (var item in soList)
                {
                    var n = item.FullName.ToFriendlyName();
                    item.LineItem = $"{item.FullName} Rated it {item.Rating}";
                    retList.Add(item);
                }
            }

            return(retList);
        }
Exemplo n.º 20
0
        private void showResultDisco(ExtendedDiscoResponseMessage disco)
        {
            FIELDS.Clear();
            messageResponseHelper?.Dispose();
            messageResponseHelper = null;

            if (disco != null && disco.roomConfig != null)
            {
                disco.roomConfig.FIELDS.Sort((a, b) => { return(a.type - b.type); });
                foreach (Field f in disco.roomConfig.FIELDS)
                {
                    if (f.type != FieldType.HIDDEN)
                    {
                        FIELDS.Add(new MUCInfoFieldTemplate()
                        {
                            field = f
                        });
                    }
                }
            }

            loading_grid.Visibility = Visibility.Collapsed;
            details_itmc.Visibility = Visibility.Visible;
        }
Exemplo n.º 21
0
            public void SupportsCustomCollections()
            {
                var source   = new CustomObservableCollection();
                var listener = new EventListener();

                var weakEventListener = listener.SubscribeToWeakCollectionChangedEvent(source, listener.OnCollectionChangedEvent);

                Assert.AreEqual(0, listener.CollectionChangedEventCount);

                source.Add(DateTime.Now);

                Assert.AreEqual(1, listener.CollectionChangedEventCount);

                // Some dummy code to make sure the previous listener is removed
                listener = new EventListener();
                GC.Collect();
                var type = listener.GetType();

                Assert.IsTrue(weakEventListener.IsSourceAlive);
                Assert.IsFalse(weakEventListener.IsTargetAlive);

                // Some dummy code to make sure the source stays in memory
                source.GetType();
            }
Exemplo n.º 22
0
        public EditFilmPageViewModel(Film film)
        {
            ResourceManager manager = new ResourceManager("BetterThanIMDB.Resources.locale", typeof(FilmsPageViewModel).GetTypeInfo().Assembly);

            _film       = film;
            ReleaseDate = film.ReleaseDate;
            Duration    = film.Duration;
            Title       = film.Title;
            Poster      = film.Poster;
            Description = film.Description;
            foreach (var a in _film.Actors)
            {
                _tempActors.Add(a);
            }
            foreach (var p in _film.Producers)
            {
                _tempProducers.Add(p);
            }
            foreach (var g in _film.GenresList)
            {
                _tempGenres.Add(g);
            }
            foreach (var g in Enum.GetValues(typeof(Genres)))
            {
                _allGenres.Add((Genres)g);
            }

            ApplyCommand = new Command(async() =>
            {
                var col1 = _film.Actors.Except(_tempActors).ToList();
                var col2 = _tempActors.Except(_film.Actors).ToList();

                for (int i = 0; i < col1.Count(); i++)
                {
                    col1.ElementAt(i).RemoveFilm(_film);
                }
                for (int i = 0; i < col2.Count(); i++)
                {
                    col2.ElementAt(i).AddFilm(_film);
                }

                var col3 = _film.Producers.Except(_tempProducers).ToList();
                var col4 = _tempProducers.Except(_film.Producers).ToList();

                for (int i = 0; i < col3.Count(); i++)
                {
                    col3.ElementAt(i).RemoveFilm(_film);
                }
                for (int i = 0; i < col4.Count(); i++)
                {
                    col4.ElementAt(i).AddFilm(_film);
                }

                _film.Title       = Title;
                _film.ReleaseDate = ReleaseDate;
                _film.Duration    = Duration;
                _film.GenresList  = _tempGenres;
                _film.Poster      = Poster;

                await App.NavigationService.GoBackAsync();
            });

            RemoveActorCommand = new Command(() =>
            {
                ActionSheetConfig config = new ActionSheetConfig();
                foreach (var actor in _tempActors)
                {
                    config.Add(actor.Name, () =>
                    {
                        _tempActors.Remove(actor);
                    });
                }
                config.SetCancel();
                config.Title = manager.GetString("removeActor", CustomSettings.Settings.Instance.Culture);
                UserDialogs.Instance.ActionSheet(config);
            });

            AddActorCommand = new Command(() =>
            {
                ActionSheetConfig config     = new ActionSheetConfig();
                var actorsExceptAlreadyAdded = _allActors.Except(_tempActors);
                foreach (var actor in actorsExceptAlreadyAdded)
                {
                    config.Add(actor.Name, () => _tempActors.Add(actor));
                }
                config.SetCancel();
                config.Title = manager.GetString("addActor", CustomSettings.Settings.Instance.Culture);
                UserDialogs.Instance.ActionSheet(config);
            });

            AddProducerCommand = new Command(() =>
            {
                ActionSheetConfig config        = new ActionSheetConfig();
                var producersExceptAlreadyAdded = _allProducers.Except(_tempProducers);
                foreach (var producer in producersExceptAlreadyAdded)
                {
                    config.Add(producer.Name, () => _tempProducers.Add(producer));
                }
                config.SetCancel();
                config.Title = manager.GetString("addProducer", CustomSettings.Settings.Instance.Culture);
                UserDialogs.Instance.ActionSheet(config);
            });

            RemoveProducerCommand = new Command(() =>
            {
                ActionSheetConfig config = new ActionSheetConfig();
                foreach (var producer in _tempProducers)
                {
                    config.Add(producer.Name, () => _tempProducers.Remove(producer));
                }
                config.SetCancel();
                config.Title = manager.GetString("removeProducer", CustomSettings.Settings.Instance.Culture);
                UserDialogs.Instance.ActionSheet(config);
            });

            AddGenreCommand = new Command(() =>
            {
                ActionSheetConfig config     = new ActionSheetConfig();
                var genresExceptAlreadyAdded = _allGenres.Except(_tempGenres);
                foreach (var genre in genresExceptAlreadyAdded)
                {
                    config.Add(genre.ToString(), () => _tempGenres.Add(genre));
                }
                config.SetCancel();
                config.Title = manager.GetString("addGenre", CustomSettings.Settings.Instance.Culture);
                UserDialogs.Instance.ActionSheet(config);
            });

            RemoveGenreCommand = new Command(() =>
            {
                ActionSheetConfig config = new ActionSheetConfig();
                foreach (var genre in _tempGenres)
                {
                    config.Add(genre.ToString(), () => _tempGenres.Remove(genre));
                }
                config.SetCancel();
                config.Title = manager.GetString("removeGenre", CustomSettings.Settings.Instance.Culture);
                UserDialogs.Instance.ActionSheet(config);
            });

            SelectDateCommand = new Command(async() =>
            {
                DateTime.TryParse(ReleaseDate, out DateTime currentDate);
                var result = await UserDialogs.Instance.DatePromptAsync(new DatePromptConfig()
                {
                    SelectedDate = currentDate
                });
                if (result.Ok)
                {
                    ReleaseDate = result.SelectedDate.ToString("dd.MM.yyyy");
                }
            });

            SelectImageCommand = new Command(async() =>
            {
                await CrossMedia.Current.Initialize();
                var selectedImageFile = await CrossMedia.Current.PickPhotoAsync(new Plugin.Media.Abstractions.PickMediaOptions()
                {
                    CompressionQuality = 92,
                    PhotoSize          = Plugin.Media.Abstractions.PhotoSize.Medium
                });

                /*string fileName = Title + "_poster.jpeg";
                 * string path = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData), fileName);
                 *
                 * using (var memoryStream = new MemoryStream())
                 * {
                 *  selectedImageFile.GetStream().CopyTo(memoryStream);
                 *  selectedImageFile.Dispose();
                 *
                 *  byte[] arr = memoryStream.ToArray();
                 *
                 *  using (FileStream file = File.Create(path))
                 *  {
                 *      await file.WriteAsync(arr, 0, arr.Length);
                 *  }
                 * }*/
                if (selectedImageFile != null)
                {
                    Poster = selectedImageFile.Path;
                }
            });
        }
Exemplo n.º 23
0
        public SearchFilmsPageViewModel(FilmsPageViewModel vm)
        {
            ResourceManager manager = new ResourceManager("BetterThanIMDB.Resources.locale", typeof(FilmsPageViewModel).GetTypeInfo().Assembly);

            PickMinDateCommand = new Command(async() =>
            {
                DateTime.TryParse(MinDate, out DateTime currentDate);
                var result = await UserDialogs.Instance.DatePromptAsync(new DatePromptConfig()
                {
                    SelectedDate = currentDate
                });
                if (result.Ok)
                {
                    MinDate = result.SelectedDate.ToString("dd.MM.yyyy");
                }
            });
            PickMaxDateCommand = new Command(async() =>
            {
                DateTime.TryParse(MaxDate, out DateTime currentDate);
                var result = await UserDialogs.Instance.DatePromptAsync(new DatePromptConfig()
                {
                    SelectedDate = currentDate
                });
                if (result.Ok)
                {
                    MaxDate = result.SelectedDate.ToString("dd.MM.yyyy");
                }
            });
            AddActorCommand = new Command(() =>
            {
                ActionSheetConfig config     = new ActionSheetConfig();
                var actorsExceptAlreadyAdded = _allActors.Except(_actors);
                foreach (var actor in actorsExceptAlreadyAdded)
                {
                    config.Add(actor.Name, () => _actors.Add(actor));
                }
                config.SetCancel();
                config.Title = manager.GetString("addActor", CustomSettings.Settings.Instance.Culture);
                UserDialogs.Instance.ActionSheet(config);
            });
            AddProducerCommand = new Command(() =>
            {
                ActionSheetConfig config        = new ActionSheetConfig();
                var producersExceptAlreadyAdded = _allProducers.Except(_producers);
                foreach (var producer in producersExceptAlreadyAdded)
                {
                    config.Add(producer.Name, () => _producers.Add(producer));
                }
                config.SetCancel();
                config.Title = manager.GetString("addProducer", CustomSettings.Settings.Instance.Culture);
                UserDialogs.Instance.ActionSheet(config);
            });
            AddGenreCommand = new Command(() =>
            {
                ActionSheetConfig config = new ActionSheetConfig();
                List <Genres> allGenres  = new List <Genres>();
                foreach (var g in Enum.GetValues(typeof(Genres)))
                {
                    allGenres.Add((Genres)g);
                }
                foreach (var genre in allGenres.Except(_genres))
                {
                    config.Add(genre.ToString(), () => _genres.Add(genre));
                }
                config.SetCancel();
                config.Title = manager.GetString("addGenre", CustomSettings.Settings.Instance.Culture);
                UserDialogs.Instance.ActionSheet(config);
            });
            RemoveActorCommand = new Command(() =>
            {
                ActionSheetConfig config = new ActionSheetConfig();
                foreach (var actor in _actors)
                {
                    config.Add(actor.Name, () => _actors.Remove(actor));
                }
                config.SetCancel();
                config.Title = manager.GetString("removeActor", CustomSettings.Settings.Instance.Culture);
                UserDialogs.Instance.ActionSheet(config);
            });
            RemoveProducerCommand = new Command(() =>
            {
                ActionSheetConfig config = new ActionSheetConfig();
                foreach (var producer in _producers)
                {
                    config.Add(producer.Name, () => _producers.Remove(producer));
                }
                config.SetCancel();
                config.Title = manager.GetString("removeProducer", CustomSettings.Settings.Instance.Culture);
                UserDialogs.Instance.ActionSheet(config);
            });
            RemoveGenreCommand = new Command(() =>
            {
                ActionSheetConfig config = new ActionSheetConfig();
                foreach (var genre in _genres)
                {
                    config.Add(genre.ToString(), () => _genres.Remove(genre));
                }
                config.SetCancel();
                config.Title = manager.GetString("removeGenre", CustomSettings.Settings.Instance.Culture);
                UserDialogs.Instance.ActionSheet(config);
            });

            ApplyCommand = new Command(async() =>
            {
                DateTime minDate = DateTime.Parse(MinDate);
                DateTime maxDate = DateTime.Parse(MaxDate);
                if (MinDuration > MaxDuration || MaxDuration == 0)
                {
                    UserDialogs.Instance.Toast("Check your duration preferences");
                }
                else if (minDate > maxDate)
                {
                    UserDialogs.Instance.Toast("Check your date preferences");
                }
                else
                {
                    vm.Films = new CustomObservableCollection <Film>(FilmCollection.Instance.Films.
                                                                     Where(f => f.Title.ToLower().Contains(Title.ToLower())).
                                                                     Where(f => f.Duration <= MaxDuration && f.Duration >= MinDuration).
                                                                     Where(f => DateTime.Parse(f.ReleaseDate) <= maxDate && DateTime.Parse(f.ReleaseDate) >= minDate).
                                                                     Where(f => f.Actors.Intersect(_actors).Count() == _actors.Count).
                                                                     Where(f => f.Producers.Intersect(_producers).Count() == _producers.Count).
                                                                     Where(f => f.GenresList.Intersect(_genres).Count() == _genres.Count));
                    await App.NavigationService.GoBackAsync();
                }
            });
        }
        public SearchActorsPageViewModel(ActorsPageViewModel vm)
        {
            ResourceManager manager = new ResourceManager("BetterThanIMDB.Resources.locale", typeof(FilmsPageViewModel).GetTypeInfo().Assembly);

            PickMinDateCommand = new Command(async() =>
            {
                DateTime.TryParse(MinDate, out DateTime currentDate);
                var result = await UserDialogs.Instance.DatePromptAsync(new DatePromptConfig()
                {
                    SelectedDate = currentDate
                });
                if (result.Ok)
                {
                    MinDate = result.SelectedDate.ToString("dd.MM.yyyy");
                }
            });
            PickMaxDateCommand = new Command(async() =>
            {
                DateTime.TryParse(MaxDate, out DateTime currentDate);
                var result = await UserDialogs.Instance.DatePromptAsync(new DatePromptConfig()
                {
                    SelectedDate = currentDate
                });
                if (result.Ok)
                {
                    MaxDate = result.SelectedDate.ToString("dd.MM.yyyy");
                }
            });
            AddFilmCommand = new Command(() =>
            {
                ActionSheetConfig config    = new ActionSheetConfig();
                var filmsExceptAlreadyAdded = _allFilms.Except(_films);
                foreach (var film in filmsExceptAlreadyAdded)
                {
                    config.Add(film.Title, () => _films.Add(film));
                }
                config.SetCancel();
                config.Title = manager.GetString("addFilm", CustomSettings.Settings.Instance.Culture);
                UserDialogs.Instance.ActionSheet(config);
            });
            RemoveFilmCommand = new Command(() =>
            {
                ActionSheetConfig config = new ActionSheetConfig();
                foreach (var film in _films)
                {
                    config.Add(film.Title, () => _films.Remove(film));
                }
                config.SetCancel();
                config.Title = manager.GetString("removeFilm", CustomSettings.Settings.Instance.Culture);
                UserDialogs.Instance.ActionSheet(config);
            });
            ApplyCommand = new Command(async() =>
            {
                DateTime minDate = DateTime.Parse(MinDate);
                DateTime maxDate = DateTime.Parse(MaxDate);
                if (minDate > maxDate)
                {
                    UserDialogs.Instance.Toast("Check your date preferences");
                }
                else
                {
                    vm.Actors = new CustomObservableCollection <Actor>(ActorCollection.Instance.Actors.Where(a => a.Name.ToLower().Contains(Name.ToLower())).
                                                                       Where(a => DateTime.Parse(a.DateOfBirth) <= maxDate && DateTime.Parse(a.DateOfBirth) >= minDate).
                                                                       Where(a => a.Films.Intersect(_films).Count() == _films.Count));
                    await App.NavigationService.GoBackAsync();
                }
            });
        }
Exemplo n.º 25
0
 private void NewUserCreated(User user)
 {
     _observableUsers.Add(user);
 }
Exemplo n.º 26
0
        public EditActorPageViewModel(Actor actor)
        {
            ResourceManager manager = new ResourceManager("BetterThanIMDB.Resources.locale", typeof(FilmsPageViewModel).GetTypeInfo().Assembly);

            _actor      = actor;
            Name        = actor.Name;
            DateOfBirth = actor.DateOfBirth;
            Photo       = actor.Photo;

            foreach (var film in actor.Films)
            {
                _tempFilms.Add(film);
            }

            ApplyCommand = new Command(async() =>
            {
                var col1 = _actor.Films.Except(_tempFilms).ToList();
                var col2 = _tempFilms.Except(_actor.Films).ToList();

                for (int i = 0; i < col1.Count(); i++)
                {
                    col1.ElementAt(i).RemoveActor(_actor);
                }
                for (int i = 0; i < col2.Count(); i++)
                {
                    col2.ElementAt(i).AddActor(_actor);
                }

                _actor.Name        = Name;
                _actor.DateOfBirth = DateOfBirth;
                _actor.Photo       = Photo;

                await App.NavigationService.GoBackAsync();
            });
            SelectDateCommand = new Command(async() =>
            {
                DateTime.TryParse(DateOfBirth, out DateTime currentDate);
                var result = await UserDialogs.Instance.DatePromptAsync(new DatePromptConfig()
                {
                    SelectedDate = currentDate
                });
                if (result.Ok)
                {
                    DateOfBirth = result.SelectedDate.ToString("dd.MM.yyyy");
                }
            });
            SelectImageCommand = new Command(async() =>
            {
                await CrossMedia.Current.Initialize();
                var selectedImageFile = await CrossMedia.Current.PickPhotoAsync(new Plugin.Media.Abstractions.PickMediaOptions()
                {
                    CompressionQuality = 92,
                    PhotoSize          = Plugin.Media.Abstractions.PhotoSize.Medium
                });

                if (selectedImageFile != null)
                {
                    Photo = selectedImageFile.Path;
                }
            });
            AddFilmCommand = new Command(() =>
            {
                ActionSheetConfig config = new ActionSheetConfig();
                foreach (var film in _allFilms.Except(_tempFilms))
                {
                    config.Add(film.Title, () => _tempFilms.Add(film));
                }
                config.SetCancel();
                config.Title = manager.GetString("addFilm", CustomSettings.Settings.Instance.Culture);
                UserDialogs.Instance.ActionSheet(config);
            });
            RemoveFilmCommand = new Command(() =>
            {
                ActionSheetConfig config = new ActionSheetConfig();
                foreach (var film in _tempFilms)
                {
                    config.Add(film.Title, () => _tempFilms.Remove(film));
                }
                config.SetCancel();
                config.Title = manager.GetString("removeFilm", CustomSettings.Settings.Instance.Culture);
                UserDialogs.Instance.ActionSheet(config);
            });
        }