private void InitializeData()
        {
            if (DesignMode.DesignModeEnabled)
                return;

            //when instantiating the collection, you pass it the task that gets more item, in this case it's "GetMoreData"
            //NOTE: This is for infinite items. if you have a max or total count, use the overload and pass the total as the 2nd parameter
            InfiniteItems = new IncrementalLoadingCollection<IncrementedItem>((cancellationToken, count) => Task.Run(GetMoreData, cancellationToken));
        }
 public void Initialize()
 {
     var repository = new DemoItemWebServiceRepository();
     var source = new DemoItemRepositorySource(repository);
     _items = new IncrementalLoadingCollection<DemoItem>(source);
     _items.Loading += (s, e) =>
     {
         SystemTray.Message = "読み込み中";
         SystemTray.IsBusy = true;
     };
     _items.Loaded += (s, e) =>
     {
         SystemTray.IsBusy = false;
     };
 }
Пример #3
0
        private async Task LoadWall()
        {
            TaskStarted("wall");

            try
            {
                var result = await _tracksService.GetWallPosts(ownerId : -Society.Id);

                _wallPostsTotalCount            = result.TotalCount;
                WallPosts                       = new IncrementalLoadingCollection <AudioPost>(result.Posts ?? new List <AudioPost>());
                WallPosts.HasMoreItemsRequested = () => WallPosts.Count > _wallPostsTotalCount;
                WallPosts.OnMoreItemsRequested  = LoadMoreWallPosts;
            }
            catch (Exception ex)
            {
                Logger.Error(ex, "Unable to load society wall");
            }

            TaskFinished("wall");
        }
Пример #4
0
        private async Task LoadPlaylists()
        {
            TaskStarted("playlists");

            try
            {
                var result = await _tracksService.GetPlaylists(userId : -Society.Id, tracks : _tracks);

                _totalPlaylistsCount            = result.TotalCount;
                Playlists                       = new IncrementalLoadingCollection <IPlaylist>(result.Playlists ?? new List <IPlaylist>());
                Playlists.HasMoreItemsRequested = () => _totalPlaylistsCount > Playlists?.Count;
                Playlists.OnMoreItemsRequested  = LoadMorePlaylists;
            }
            catch (Exception ex)
            {
                Logger.Error(ex, "Unable to load society playlists");
            }

            TaskFinished("playlists");
        }
Пример #5
0
        public async Task FirstRequestFails()
        {
            var source     = new DataSource <int>(AllData, DataSource <int> .ThrowException);
            var collection = new IncrementalLoadingCollection <DataSource <int>, int>(source, PageSize);

            await Assert.ThrowsExceptionAsync <AggregateException>(collection.LoadMoreItemsAsync(0).AsTask);

            Assert.IsTrue(!collection.Any());

            var requests = new List <Task>();

            for (int pageNum = 1; pageNum <= Pages; pageNum++)
            {
                requests.Add(collection.LoadMoreItemsAsync(0).AsTask()
                             .ContinueWith(t => Assert.IsTrue(t.IsCompletedSuccessfully)));
            }

            await Task.WhenAll(requests);

            CollectionAssert.AreEqual(AllData, collection);
        }
Пример #6
0
        private void GetEmails()
        {
            var collection = new IncrementalLoadingCollection <MicrosoftGraphSource <Microsoft.Graph.Message>, Microsoft.Graph.Message>(
                10,
                async() =>
            {
                await Dispatcher.RunAsync(CoreDispatcherPriority.Normal, () =>
                {
                    Loader.Visibility = Visibility.Visible;
                });
            },
                async() =>
            {
                await Dispatcher.RunAsync(CoreDispatcherPriority.Normal, () =>
                {
                    Loader.Visibility = Visibility.Collapsed;
                });
            },
                async ex =>
            {
                if (!Dispatcher.HasThreadAccess)
                {
                    if (ex is ServiceException)
                    {
                        await Dispatcher.RunAsync(CoreDispatcherPriority.Normal, () =>
                        {
                            NotConnectedMessage.Visibility = Visibility.Visible;
                            Loader.Visibility = Visibility.Collapsed;
                            //await DisplayAuthorizationErrorMessageAsync(ex as ServiceException, "Read user mail");
                        });
                    }
                    else
                    {
                        throw ex;
                    }
                }
            });

            Mails.ItemsSource = collection;
        }
Пример #7
0
        public async Task GetUserDetail()
        {
            try
            {
                Loading = true;

                var api = userCenterAPI.UserCenterDetail(mid);

                var results = await api.Request();

                if (results.status)
                {
                    var data = await results.GetData <UserCenterDetailModel>();

                    if (data.success)
                    {
                        UserCenterDetail = data.data;
                        GetTopImage();
                        SubmitVideos = new IncrementalLoadingCollection <UserSubmitVideoSource, SubmitVideoItemModel>(new UserSubmitVideoSource(mid), 30);
                    }
                    else
                    {
                        Utils.ShowMessageToast(data.message);
                    }
                }
                else
                {
                    Utils.ShowMessageToast(results.message);
                }
            }
            catch (Exception ex)
            {
                var handel = HandelError(ex);
                Utils.ShowMessageToast(handel.message);
            }
            finally
            {
                Loading = false;
            }
        }
Пример #8
0
 public ForumViewModel(Forum forum, ApiConfig config)
 {
     Name  = forum.Name;
     ID    = forum.Id;
     Posts = new IncrementalLoadingCollection <PostLoader, PostViewModel>(
         new PostLoader(this, config),
         () => { _onError = false; FooterText = Bible.OnLoading; RefreshCommand.RaiseCanExecuteChanged(); }
         , () => { if (!_onError)
                   {
                       FooterText = Bible.OnFinished;
                   }
                   RefreshCommand.RaiseCanExecuteChanged(); },
         (ex) => { FooterText = Bible.OnError; _onError = true; RefreshCommand.RaiseCanExecuteChanged(); });
     RefreshCommand = new RelayCommand(() => { if (_onError)
                                               {
                                                   Posts.RetryFailed();
                                               }
                                               else
                                               {
                                                   Posts.RefreshAsync();
                                               } }, () => !Posts.IsLoading, true);
 }
Пример #9
0
        public override Task OnNavigatedToAsync(object parameter, NavigationMode mode, IDictionary <string, object> state)
        {
            if ((parameter as string) != _query)
            {
                _query = parameter as string;
                var loading = Window.Current.Content as LoadingView;

                _searchSource = new SearchSource(_query, () =>
                {
                    loading.IsLoading = true;
                },
                                                 () =>
                {
                    loading.IsLoading = false;
                });
                SearchList = new IncrementalLoadingCollection <SearchSource, SearchResult>(_searchSource,
                                                                                           onError: (ex) =>
                {
                    loading.IsLoading = false;
                });
            }
            return(Task.CompletedTask);
        }
Пример #10
0
        public UsersViewModel(IScreen screen) : base(screen)
        {
            Add = ReactiveCommand.Create(AddAction);

            this.WhenActivated(d =>
            {
                Users = new IncrementalLoadingCollection <UserSource, User>();

                ReactiveFactory.UserChanged += ReactiveFactory_UserChanged;
                this.WhenAnyValue(x => x.SelectedUser)
                .WhereNotNull().Subscribe(s =>
                {
                    HostScreen.Router.Navigate.Execute(new TestListViewModel(HostScreen, SelectedUser));
                    SelectedUser = null;
                });
                Disposable
                .Create(() =>
                {
                    ReactiveFactory.UserChanged -= ReactiveFactory_UserChanged;
                })
                .DisposeWith(d);
            });
        }
Пример #11
0
        public async Task EveryOtherRequestFails()
        {
            var source     = new DataSource <int>(AllData, FailPassSequence);
            var collection = new IncrementalLoadingCollection <DataSource <int>, int>(source, PageSize);

            var willFail = true;

            for (int submitedRequests = 0; submitedRequests < Pages * 2; submitedRequests++)
            {
                if (willFail)
                {
                    await Assert.ThrowsExceptionAsync <AggregateException>(collection.LoadMoreItemsAsync(0).AsTask);
                }
                else
                {
                    await collection.LoadMoreItemsAsync(0);
                }

                willFail = !willFail;
            }

            CollectionAssert.AreEqual(AllData, collection);
        }
        public MoviePageViewModel()
        {
            MovieListCollection = new IncrementalLoadingCollection <MovieListModel>(CommonDataLoader.GetMovieListModel);
#if DEBUG
            if (DesignMode.DesignModeEnabled)
            {
                MovieListCollection.Add(new MovieListModel
                {
                    Cover = "ms-appx:///Resources/Test/cover.png",
                    Id    = "34",
                    Title = "卧虎藏龙2:青冥宝剑",
                    Score = "39"
                });
                MovieListCollection.Add(new MovieListModel
                {
                    Cover = "ms-appx:///Resources/Test/cover.png",
                    Id    = "34",
                    Title = "卧虎藏龙2:青冥宝剑",
                    Score = "39"
                });
            }
#endif
        }
        /// <summary>
        /// Initializes a new instance of the <see cref="ProfileViewModel" /> class.
        /// </summary>
        /// <param name="navigationFacade">The navigation facade.</param>
        /// <param name="photoService">The photo service.</param>
        /// <param name="dialogService">The dialog service.</param>
        public ProfileViewModel(INavigationFacade navigationFacade, IPhotoService photoService,
            IDialogService dialogService)
        {
            _navigationFacade = navigationFacade;
            _photoService = photoService;
            _dialogService = dialogService;

            Photos = new IncrementalLoadingCollection<Photo>(s =>
            {
                Func<Task<PagedResponse<Photo>>> f = async () =>
                {
                    if (IsShowingCurrentUser)
                    {
                        var stream = await photoService.GetPhotosForCurrentUser(s);
                        return stream;
                    }

                    return await photoService.GetPhotosForUser(User, s);
                };
                return f();
            }, async () => await _dialogService.ShowGenericServiceErrorNotification(),
                OnPhotosLoadingFinished);

            // Photos collection is being loaded asynchronously, so we need to
            // watch it to see if the user has any pictures uploaded already.
            Photos.CollectionChanged += PhotosCollectionChanged;

            // Initialize commands
            PhotoSelectedCommand = new RelayCommand<Photo>(OnPhotoSelected);
            DeletePhotoCommand = new RelayCommand<Photo>(OnDeletePhoto);
            SetProfilePhotoCommand = new RelayCommand<Photo>(OnSetProfilePhoto);

            // Before pictures are retrieved from the service,
            // we want to prevent an initial notification showing up
            // that the user has no pictures.
            ArePhotosEmpty = false;
        }
        /// <summary>
        /// Initializes a new instance of the <see cref="ProfileViewModel" /> class.
        /// </summary>
        /// <param name="navigationFacade">The navigation facade.</param>
        /// <param name="photoService">The photo service.</param>
        /// <param name="dialogService">The dialog service.</param>
        public ProfileViewModel(INavigationFacade navigationFacade, IPhotoService photoService,
                                IDialogService dialogService)
        {
            _navigationFacade = navigationFacade;
            _photoService     = photoService;
            _dialogService    = dialogService;

            Photos = new IncrementalLoadingCollection <Photo>(s =>
            {
                Func <Task <PagedResponse <Photo> > > f = async() =>
                {
                    if (IsShowingCurrentUser)
                    {
                        var stream = await photoService.GetPhotosForCurrentUser(s);
                        return(stream);
                    }

                    return(await photoService.GetPhotosForUser(User, s));
                };
                return(f());
            }, async() => await _dialogService.ShowGenericServiceErrorNotification(),
                                                              OnPhotosLoadingFinished);

            // Photos collection is being loaded asynchronously, so we need to
            // watch it to see if the user has any pictures uploaded already.
            Photos.CollectionChanged += PhotosCollectionChanged;

            // Initialize commands
            PhotoSelectedCommand   = new RelayCommand <Photo>(OnPhotoSelected);
            DeletePhotoCommand     = new RelayCommand <Photo>(OnDeletePhoto);
            SetProfilePhotoCommand = new RelayCommand <Photo>(OnSetProfilePhoto);

            // Before pictures are retrieved from the service,
            // we want to prevent an initial notification showing up
            // that the user has no pictures.
            ArePhotosEmpty = false;
        }
Пример #15
0
        private void SearchQueryCommandExecute(object args)
        {
            try
            {
                if (args is AutoSuggestBoxQuerySubmittedEventArgs)
                {
                    var queryText = (args as AutoSuggestBoxQuerySubmittedEventArgs).QueryText;

                    var flickrConfig = new FlickrDataConfig()
                    {
                        QueryType = FlickrQueryType.Search, Query = queryText
                    };

                    Reset();

                    PhotoCollection = new IncrementalLoadingCollection <Photo>((cancellationToken, count)
                                                                               => Task.Run(() => GetFlickrPhotos(flickrConfig), cancellationToken));
                }
            }
            catch (Exception ex)
            {
                AppLogs.WriteError("[SearchQueryCommandExecute]", ex.ToString());
            }
        }
Пример #16
0
        private async void AvailabilityChanged(ConnectionTypes connectionTypes)
        {
            try
            {
                var networkAvailabilityStatus = await _networkAvailableService.IsInternetAvailable();

                if (IsNetworkAvailable != networkAvailabilityStatus)
                {
                    IsNetworkAvailable = networkAvailabilityStatus;

                    if (IsNetworkAvailable)
                    {
                        _pageIndex = 0;

                        PhotoCollection = new IncrementalLoadingCollection <Photo>((cancellationToken, count)
                                                                                   => Task.Run(() => GetFlickrPhotos(new FlickrDataConfig()), cancellationToken));
                    }
                }
            }
            catch (Exception ex)
            {
                AppLogs.WriteError("[AvailabilityChanged]", ex.ToString());
            }
        }
        private async void GetEventsButton_Click(object sender, RoutedEventArgs e)
        {
            if (!await Tools.CheckInternetConnectionAsync())
            {
                return;
            }

            int top = 10;

            var collection = new IncrementalLoadingCollection <MicrosoftGraphSource <Event>, Event>(
                top,
                async() =>
            {
                await Dispatcher.RunAsync(CoreDispatcherPriority.Normal, () => { Shell.Current.DisplayWaitRing = true; });
            },
                async() =>
            {
                await Dispatcher.RunAsync(CoreDispatcherPriority.Normal, () => { Shell.Current.DisplayWaitRing = false; });
            },
                async ex =>
            {
                if (!Dispatcher.HasThreadAccess)
                {
                    if (ex is ServiceException)
                    {
                        await Dispatcher.RunAsync(CoreDispatcherPriority.Normal, async() => { await DisplayAuthorizationErrorMessageAsync(ex as ServiceException, "Read user event"); });
                    }
                    else
                    {
                        throw ex;
                    }
                }
            });

            EventsList.ItemsSource = collection;
        }
Пример #18
0
        public async Task <bool> RefreshAsync()
        {
            try
            {
                if (DataList.IsBusy)
                {
                    return(false);
                }

                PageIndex = DEFAULT_PAGE_INDEX;

                if (DataList == null)
                {
                    DataList = new IncrementalLoadingCollection <T>(count =>
                    {
                        return(GetIncrementalListData(PageIndex++));
                    });
                }
                else
                {
                    //DataList.DataFetchDelegate = (c =>
                    //  {
                    //      return GetIncrementalListData(PageIndex++);
                    //  });
                }

                await DataList.LoadMoreItemsAsync(20u);

                return(true);
            }
            catch (Exception e)
            {
                var task = Logger.LogAsync(e);
                return(false);
            }
        }
Пример #19
0
        private void LoadJokeInfoCollection(JokeAPI jokeAPI)
        {
            JokeInfoCollection = new IncrementalLoadingCollection<JokeInfo>(
               async (pageIndex, requestCount) =>
               {
                   IsBusy = !IsDisConnected;
                   PageIndex = pageIndex;
                   JokeResponse<JokeInfo> tempJokeResponse = await JokeAPIUtils.GetJokeInfoList<JokeInfo>(new RequestParam
                   {
                       jokeAPI = jokeAPI,
                       page = pageIndex,
                       count = requestCount,
                       token = JokeAPIUtils.UserLoginInfo.token,
                       args = UserInfo == null ? null : new string[] { UserInfo.id }
                   });
                   IsBusy = false;

                   return tempJokeResponse;
               },
               (jokeInfo) =>
               {
                   return JokeInfoCollection.FirstOrDefault(joke => joke.id == jokeInfo.id) != null;
               });

            _JokeInfoCollection.OnLoadStatusChanged += _JokeInfoCollection_OnLoadStatusChanged;
            _JokeInfoCollection.OnNetworkStatusChanged += _JokeInfoCollection_OnNetworkStatusChanged;
        }
        /// <summary>
        /// Stößt den Abonnementvorgang an. Der lokale Nutzer abonniert den Kanal, der aktuell
        /// in der Detailansicht angezeigt wird.
        /// </summary>
        private async Task executeSubscribeChannel()
        {
            try
            {
                displayIndeterminateProgressIndicator();
                await channelController.SubscribeChannelAsync(Channel.Id);

                //Setze Kanal als abonniert.
                ChannelSubscribedStatus = true;

                if (ChannelSubscribedStatus && !Channel.Deleted)
                {
                    CanUnsubscribeChannel = true;
                }
                else
                {
                    CanUnsubscribeChannel = false;
                }

                // Lade Moderatoren-Info.
                await LoadModeratorsOfChannelAsync();

                // Bleibe auf der Seite, aber lade die Nachrichten nach.
                List<Announcement> announcements = await Task.Run(() => channelController.GetAllAnnouncementsOfChannel(Channel.Id));
                     
                // Setze PageSize auf 0, d.h. lade keine Elemente nach.
                Announcements = new IncrementalLoadingCollection<IncrementalAnnouncementLoaderController, Announcement>(Channel.Id, 0);
                await Announcements.LoadExistingCollectionAsync(announcements);
            }
            catch(ClientException ex)
            {
                // Markiere Kanal in lokaler Liste als gelöscht, wenn er nicht auf dem Server gefunden wurde.
                if(ex.ErrorCode == ErrorCodes.ChannelNotFound)
                {
                    // Passe View an.
                    Channel.Deleted = true;
                    checkCommandExecution();
                }

                displayError(ex.ErrorCode);
            }
            finally
            {
                hideIndeterminateProgressIndicator();
            }
        }
Пример #21
0
        private async Task Reset()
        {
            if (Mylist.Value == null)
            {
                return;
            }

            CanEditMylist = false;

            var mylistOrigin = Mylist.Value?.ToMylistOrigin();

            IsLoginUserDeflist      = false;
            IsWatchAfterLocalMylist = Mylist.Value is Interfaces.ILocalMylist &&
                                      Mylist.Value?.Id == HohoemaPlaylist.WatchAfterPlaylistId;
            IsUserOwnerdMylist = Mylist.Value is Interfaces.IUserOwnedMylist;
            IsLocalMylist      = Mylist.Value is Interfaces.ILocalMylist;

            IsLoginUserMylistWithoutDeflist = false;

            MaxItemsCount = Mylist.Value.ItemCount;
            RaisePropertyChanged(nameof(MaxItemsCount));

            switch (mylistOrigin)
            {
            case PlaylistOrigin.LoginUser:
            {
                var mylistGroup = UserMylistManager.GetMylistGroup(Mylist.Value.Id);
                MylistItems = mylistGroup.ToReadOnlyReactiveCollection(x => new MylistVideItemViewModel(x, mylistGroup))
                              .AddTo(_NavigatingCompositeDisposable);

                MylistTitle        = mylistGroup.Label;
                MylistDescription  = mylistGroup.Description;
                ThemeColor         = mylistGroup.IconType.ToColor();
                IsPublic           = mylistGroup.IsPublic;
                IsLoginUserDeflist = mylistGroup.IsDeflist;

                OwnerUserId = mylistGroup.UserId;
                UserName    = NiconicoSession.UserName;

                CanEditMylist = !IsLoginUserDeflist;

                if (IsLoginUserDeflist)
                {
                    MylistState = "とりあえずマイリスト";
                    DeflistRegistrationCapacity = UserMylistManager.DeflistRegistrationCapacity;
                    DeflistRegistrationCount    = UserMylistManager.DeflistRegistrationCount;
                }
                else
                {
                    IsLoginUserMylistWithoutDeflist = true;
                    MylistState = IsPublic ? "公開マイリスト" : "非公開マイリスト";
                    MylistRegistrationCapacity = UserMylistManager.MylistRegistrationCapacity;
                    MylistRegistrationCount    = UserMylistManager.MylistRegistrationCount;
                }
            }
            break;


            case PlaylistOrigin.OtherUser:
                var otherOwnedMylist = Mylist.Value as OtherOwneredMylist;

                MylistItems = new IncrementalLoadingCollection <OtherOwnedMylistIncrementalSource, MylistVideItemViewModel>(new OtherOwnedMylistIncrementalSource(otherOwnedMylist, MylistProvider, NgSettings));

                var response = await MylistProvider.GetMylistGroupDetail(Mylist.Value.Id);

                var mylistGroupDetail = response.MylistGroup;
                MylistTitle       = otherOwnedMylist.Label;
                MylistDescription = otherOwnedMylist.Description;
                IsPublic          = true;
                //ThemeColor = mylistGroupDetail.GetIconType().ToColor();

                OwnerUserId = mylistGroupDetail.UserId;

                MylistState = IsPublic ? "公開マイリスト" : "非公開マイリスト";
                var user = Database.NicoVideoOwnerDb.Get(OwnerUserId);
                if (user != null)
                {
                    UserName = user.ScreenName;
                }
                else
                {
                    var userDetail = await UserProvider.GetUser(OwnerUserId);

                    UserName = userDetail.ScreenName;
                }

                CanEditMylist = false;

                break;



            case PlaylistOrigin.Local:
            {
                var localMylist = Mylist.Value as LocalMylistGroup;
                MylistItems = localMylist.ToReadOnlyReactiveCollection(x => new MylistVideItemViewModel(x, localMylist))
                              .AddTo(_NavigatingCompositeDisposable);

                MylistTitle = Mylist.Value.Label;
                OwnerUserId = NiconicoSession.UserId.ToString();
                UserName    = NiconicoSession.UserName;

                MylistState = "ローカル";

                CanEditMylist = !IsWatchAfterLocalMylist;
            }

            break;

            default:
                break;
            }

            RaisePropertyChanged(nameof(MylistItems));

            EditMylistGroupCommand.RaiseCanExecuteChanged();
            DeleteMylistCommand.RaiseCanExecuteChanged();
        }
Пример #22
0
 async void LoadCommands()
 {
     await StopCommandsSubscription();
     bool loaded = false;
     CommandFilter filter = new CommandFilter() 
     {
         End = filterCommandsEnd,
         Start = filterCommandsStart,
         SortOrder = SortOrder.DESC
     };
     var list = new IncrementalLoadingCollection<Command>(async (take, skip) =>
     {
         filter.Skip = (int)skip;
         filter.Take = (int)take;
         try
         {
             Debug.WriteLine("CMD LOAD START");
             var commands = await ClientService.Current.GetCommandsAsync(deviceId, filter);
             Debug.WriteLine("CMD LOAD END");
             return commands;
         }
         catch (Exception ex)
         {
             Dispatcher.RunAsync(CoreDispatcherPriority.Normal, () =>
             {
                 new MessageDialog(ex.Message, "Error").ShowAsync();
             });
             throw ex;
         }
     }, 20);
     list.IsLoadingChanged += (s, isLoading) =>
     {
         LoadingItems += isLoading ? 1 : -1;
         if (!isLoading && !loaded)
         {
             StartCommandsSubscription();
             if (s.Count > 0)
             {
                 // makes server response faster
                 filter.End = s.First().Timestamp;
             }
             loaded = true;
         }
     };
     CommandsObservable = list;
 }
Пример #23
0
 public Album()
 {
     photos = new IncrementalLoadingCollection <PhotosSource, Photo>(10);
     this.InitializeComponent();
 }
Пример #24
0
        // If you have install the code sniplets, use "propvm + [tab] +[tab]" create a property。
        // 如果您已经安装了 MVVMSidekick 代码片段,请用 propvm +tab +tab 输入属性



        public AuthorListPage_Model()
        {
            AuthorListAuthor = new IncrementalLoadingCollection <AuthorSource, Author>("", AppStrings.PageSize);
            Title            = "zhuanlan";
        }
Пример #25
0
 public ViewModel()
 {
     Items = new IncrementalLoadingCollection();
 }
 public void Initialize()
 {
     var repository = new DemoItemStaticRepository();
     var source = new DemoItemRepositorySource(repository);
     _items = new IncrementalLoadingCollection<DemoItem>(source);
 }
Пример #27
0
        private void LoadAllUserPerformedEvents(string login)
        {
            UserPerformedActivitySource source = new UserPerformedActivitySource(login);

            allUserPerformedEvents = new IncrementalLoadingCollection <UserPerformedActivitySource, Activity>(source);
        }
Пример #28
0
 public void LoadAllCurrentUserFollowings()
 {
     allCurrentUserFollowings = new IncrementalLoadingCollection <CurrentUserFollowings, Octokit.User>();
 }
Пример #29
0
 public void LoadAllCurrentUserPerformedEvents()
 {
     allCurrentUserPerformedEvents = new IncrementalLoadingCollection <CurrentUserPerformedActivitySource, Activity>();
 }
 public void Initialize()
 {
     System.Diagnostics.Debug.WriteLine("GridViewAndNavigationMainViewModel.Initialize");
     var repository = new DemoItemStaticRepository();
     var source = new DemoItemRepositorySource(repository);
     _items = new IncrementalLoadingCollection<DemoItem>(source);
 }
Пример #31
0
 //----------------------------------------------------------------------
 public void Init()
 {
     Games = new IncrementalLoadingCollection<Game>( GetGames, TimeSpan.FromSeconds( 30 ) );
     RaisePropertyChanged( () => Games );
 }
Пример #32
0
 protected override void OnNavigatedTo(NavigationEventArgs e)
 {
     base.OnNavigatedTo(e);
     selectedSubreddit = e.Parameter as Subreddit;
     Posts             = new IncrementalLoadingCollection <SubredditPostSource, Post>(selectedSubreddit);
 }
Пример #33
0
 public NukiLockStatusPartViewModel()
 {
     LockHistory = null;
 }
Пример #34
0
 public MainViewModel(IGithubService service)
 {
     _repositoriesSource = new GithubIncrementalItemSource(service);
     Repositories = new IncrementalLoadingCollection<Repository, GithubIncrementalItemSource>(_repositoriesSource);
 }
Пример #35
0
 public ScriptGalleryViewModel(ScriptApi api)
 {
     Api       = api;
     _loadFunc = page => Api.Home(page);
     Source    = new IncrementalLoadingCollection <IIncrementalSource <IGallery>, IGallery>(this, onError: OnLoadError, onStartLoading: OnStartLoading, onEndLoading: OnEndLoading);
 }
        /// <summary>
        /// Lädt die Daten des Kanals mit der übergebenen Id in das ViewModel
        /// und macht die Daten über die Properties verfügbar.
        /// </summary>
        /// <param name="selectedChannelId">Die Id des Kanals, der geladen werden soll.</param>
        public void LoadSelectedChannel(int selectedChannelId)
        {
            try
            {
                Channel = channelController.GetChannel(selectedChannelId);
            }
            catch (ClientException ex)
            {
                // Zeige Fehlernachricht an.
                displayError(ex.ErrorCode);
            }

            if (Channel != null)
            {
                switch (Channel.Type)
                {
                    case ChannelType.LECTURE:
                        Debug.WriteLine("Selected channel is of type Lecture.");
                        Lecture = Channel as Lecture;
                        break;
                    case ChannelType.EVENT:
                        Debug.WriteLine("Selected channel is of type Event.");
                        EventObj = Channel as Event;
                        break;
                    case ChannelType.SPORTS:
                        Debug.WriteLine("Selected channel is of type Sports.");
                        Sports = Channel as Sports;
                        break;
                    default:
                        Debug.WriteLine("Selected channel is of type Student_Group or Other with no special properties.");
                        break;
                }
            }

            // Initialisiere asynchrones Announcement Laden.
            Announcements = new IncrementalLoadingCollection<IncrementalAnnouncementLoaderController, Announcement>(selectedChannelId, 20);

            checkCommandExecution();
        }
        protected async Task ResetList()
        {
            using (var releaser = await _ItemsUpdateLock.LockAsync())
            {
                HasItem.Value          = true;
                LoadedItemsCount.Value = 0;

                IsSelectionModeEnable.Value = false;

                SelectedItems.Clear();

                if (IncrementalLoadingItems != null)
                {
                    if (IncrementalLoadingItems.Source is HohoemaIncrementalSourceBase <ITEM_VM> )
                    {
                        (IncrementalLoadingItems.Source as HohoemaIncrementalSourceBase <ITEM_VM>).Error -= HohoemaIncrementalSource_Error;
                    }
                    IncrementalLoadingItems.BeginLoading -= BeginLoadingItems;
                    IncrementalLoadingItems.DoneLoading  -= CompleteLoadingItems;
                    IncrementalLoadingItems.Dispose();
                    IncrementalLoadingItems = null;
                    RaisePropertyChanged(nameof(IncrementalLoadingItems));
                }

                try
                {
                    var source = GenerateIncrementalSource();

                    if (source == null)
                    {
                        HasItem.Value = false;
                        return;
                    }

                    MaxItemsCount.Value = await source.ResetSource();

                    IncrementalLoadingItems = new IncrementalLoadingCollection <IIncrementalSource <ITEM_VM>, ITEM_VM>(source);
                    RaisePropertyChanged(nameof(IncrementalLoadingItems));

                    IncrementalLoadingItems.BeginLoading += BeginLoadingItems;
                    IncrementalLoadingItems.DoneLoading  += CompleteLoadingItems;

                    if (IncrementalLoadingItems.Source is HohoemaIncrementalSourceBase <ITEM_VM> )
                    {
                        (IncrementalLoadingItems.Source as HohoemaIncrementalSourceBase <ITEM_VM>).Error += HohoemaIncrementalSource_Error;
                    }

                    ItemsView.Source = IncrementalLoadingItems;
                    RaisePropertyChanged(nameof(ItemsView));

                    PostResetList();
                }
                catch
                {
                    IncrementalLoadingItems = null;
                    NowLoading.Value        = false;
                    HasItem.Value           = true;
                    HasError.Value          = true;
                    Debug.WriteLine("failed GenerateIncrementalSource.");
                }
            }
        }
Пример #38
0
 public MainViewModel(IGithubService service)
 {
     _repositoriesSource = new GithubIncrementalItemSource(service);
     Repositories        = new IncrementalLoadingCollection <Repository, GithubIncrementalItemSource>(_repositoriesSource);
 }
Пример #39
0
        private async Task ListFilesFolders(string path)
        {
            await Dispatcher.RunAsync(CoreDispatcherPriority.Normal, () =>
            {
                // update the title path
                if (path == "/")
                {
                    pathText.Text = "CloudStreamer";
                }
                else
                {
                    pathText.Text = path;
                }
                fileScrollViewer.Visibility = Visibility.Collapsed;
                progressRing.Visibility     = Visibility.Visible;
                progressRing.IsActive       = true;
            });

            // handle login
            try
            {
                await UpdateOrInitOneDriveAuthIfNecessary();
            }
            catch (Exception e)
            {
                System.Diagnostics.Debug.WriteLine(e, "error");
                try
                {
                    await ExitOrRetryWithMessage("Failed to authenticate with OneDrive. Error: " + e.ToString());
                }
                catch (Exception ex)
                {
                    Crashes.TrackError(ex, new Dictionary <string, string>
                    {
                        { "On", "Call Error Dialog" },
                        { "Where", "MainPage.xaml:InitOneDrive" },
                        { "DueTo", e.Message }
                    });
                }
                return;
            }


            if (oneDriveClient == null)
            {
                return;
            }

            try
            {
                IItemChildrenCollectionRequest request;
                if (path == "/")
                {
                    request = oneDriveClient.Drive.Root.Children.Request();
                }
                else
                {
                    request = oneDriveClient.Drive.Root.ItemWithPath(path).Children.Request();
                }
                IItemChildrenCollectionRequest sortedRequest = request.OrderBy(currentSortBy + " " + currentSortByDir);
                sortedRequest = sortedRequest.Expand("thumbnails");
                files         = (ItemChildrenCollectionPage)await sortedRequest.GetAsync();
            }
            catch (Exception e)
            {
                System.Diagnostics.Debug.WriteLine(e, "error");
                try
                {
                    await ExitOrRetryWithMessage("Failed to load Files from OneDrive. Error: " + e.ToString());
                }
                catch (Exception ex)
                {
                    Crashes.TrackError(ex, new Dictionary <string, string>
                    {
                        { "On", "Call Error Dialog" },
                        { "Where", "MainPage.xaml:ListFilesFolders" },
                        { "DueTo", e.Message }
                    });
                }
            }
            await Dispatcher.RunAsync(CoreDispatcherPriority.Normal, () =>
            {
                fileItems = new IncrementalLoadingCollection(files);
                fileScrollViewer.ItemsSource = fileItems;
                loading = false;
                progressRing.IsActive       = false;
                progressRing.Visibility     = Visibility.Collapsed;
                fileScrollViewer.Visibility = Visibility.Visible;
            });

            System.Diagnostics.Debug.WriteLine("Got " + fileItems.Count() + " files");
        }
        /// <summary>
        /// Initializes a new instance of the <see cref="StreamViewModel" /> class.
        /// </summary>
        /// <param name="navigationFacade">The navigation facade.</param>
        /// <param name="photoService">The photo service.</param>
        /// <param name="authEnforcementHandler">the authentication enforcement handler</param>
        /// <param name="dialogService">The dialog service.</param>
        public StreamViewModel(INavigationFacade navigationFacade, IPhotoService photoService,
            IAuthEnforcementHandler authEnforcementHandler, IDialogService dialogService)
        {
            _navigationFacade = navigationFacade;
            _authEnforcementHandler = authEnforcementHandler;
            _dialogService = dialogService;

            Photos = new IncrementalLoadingCollection<Photo>(s =>
            {
                Func<Task<PagedResponse<Photo>>> f = async () =>
                {
                    var stream = await photoService.GetPhotosForCategoryId(Category.Id, s);

                    if (SelectedPhotoThumbnail != null
                        && SelectedPhoto == null)
                    {
                        SelectedPhoto = stream.Items.FindPhotoForThumbnail(SelectedPhotoThumbnail);
                    }

                    return stream;
                };

                return f();
            }, async () => await _dialogService.ShowGenericServiceErrorNotification());

            // Initialize commands
            RefreshCommand = new RelayCommand(OnRefresh);
            GotoCameraCommand = new RelayCommand(OnGotoCamera);
            GiveGoldCommand = new RelayCommand<Photo>(OnGiveGold);
            PhotoSelectedCommand = new RelayCommand<Photo>(OnPhotoSelected);
            ContributeCommand = new RelayCommand(OnGotoCamera);
            UserSelectedCommand = new RelayCommand<User>(OnUserSelected);
        }
Пример #41
0
        public void HasMoreItems_IsTrueByDefault()
        {
            var collection = new IncrementalLoadingCollection <object>(Mock.Create <IVirtualisedDataSource <object> >());

            Assert.Equal(true, collection.HasMoreItems);
        }
Пример #42
0
        private void LoadAllUserFollowers(string login)
        {
            UserFollowersSource source = new UserFollowersSource(login);

            allUserFollowers = new IncrementalLoadingCollection <UserFollowersSource, Octokit.User>(source);
        }
        /// <summary>
        /// Lädt die Daten des Kanals mit der übergebenen Id in das ViewModel
        /// und macht die Daten über die Properties verfügbar.
        /// </summary>
        /// <param name="selectedChannelId">Die Id des Kanals, der geladen werden soll.</param>
        public void LoadSelectedChannel(int selectedChannelId)
        {
            try
            {
                Channel = channelController.GetChannel(selectedChannelId);
            }
            catch(ClientException ex)
            {
                // Zeige Fehlernachricht an.
                displayError(ex.ErrorCode);
            }
                        
            if(Channel != null)
            {
                switch (Channel.Type)
                {
                    case ChannelType.LECTURE:
                        Debug.WriteLine("Selected channel is of type Lecture.");
                        Lecture = Channel as Lecture;
                        break;
                    case ChannelType.EVENT:
                        Debug.WriteLine("Selected channel is of type Event.");
                        EventObj = Channel as Event;
                        break;
                    case ChannelType.SPORTS:
                        Debug.WriteLine("Selected channel is of type Sports.");
                        Sports = Channel as Sports;
                        break;
                    default:
                        Debug.WriteLine("Selected channel is of type Student_Group or Other with no special properties.");
                        break;
                }

                // Prüfe, ob Kanal bereits abonniert wurde.
                ChannelSubscribedStatus = channelController.IsChannelSubscribed(Channel.Id);

                if (ChannelSubscribedStatus && !Channel.Deleted)
                {
                    CanUnsubscribeChannel = true;
                }
                else
                {
                    CanUnsubscribeChannel = false;
                }

                if(ChannelSubscribedStatus == true)
                {
                    // Aktiviere dynamisches Laden der Announcements.
                    // Es sollen mindestens immer alle noch nicht gelesenen Nachrichten geladen werden, immer aber mindestens 20.
                    int numberOfItems = Channel.NumberOfUnreadAnnouncements;
                    if(numberOfItems < 20)
                    {
                        numberOfItems = 20;
                    }

                    Debug.WriteLine("Call constructor of IncrementalLoadingCollection. Selected channel id is {0}.", selectedChannelId);
                    Announcements = new IncrementalLoadingCollection<IncrementalAnnouncementLoaderController, Announcement>(selectedChannelId, numberOfItems);
                }

                checkCommandExecution();
            }
        }