コード例 #1
0
        protected BaseRepositoriesViewModel(ISessionService applicationService)
        {
            ApplicationService = applicationService;
            ShowRepositoryOwner = true;
            Title = "Repositories";

            var gotoRepository = new Action<RepositoryItemViewModel>(x => {
                var vm = this.CreateViewModel<RepositoryViewModel>();
                vm.Init(x.Owner, x.Name);
                NavigateTo(vm);
            });

            var repositories = new ReactiveList<RepositoryItemViewModel>();
            Repositories = repositories.CreateDerivedCollection(
                x => x, 
                filter: x => x.Name.ContainsKeyword(SearchKeyword),
                signalReset: this.WhenAnyValue(x => x.SearchKeyword));

            //Filter = applicationService.Account.Filters.GetFilter<RepositoriesFilterModel>(filterKey);

            LoadCommand = ReactiveCommand.CreateAsyncTask(t =>
                repositories.SimpleCollectionLoad(CreateRequest(),
                    x => new RepositoryItemViewModel(x.Name, x.Owner.Login, x.Owner.AvatarUrl, 
                        ShowRepositoryDescription ? x.Description : string.Empty, x.StargazersCount, x.ForksCount, 
                        ShowRepositoryOwner, gotoRepository),
                    x => LoadMoreCommand = x == null ? null : ReactiveCommand.CreateAsyncTask(_ => x())));

//			_repositories.FilteringFunction = x => Repositories.Filter.Ascending ? x.OrderBy(y => y.Name) : x.OrderByDescending(y => y.Name);
//            _repositories.GroupingFunction = CreateGroupedItems;
        }
コード例 #2
0
 public MenuViewModel(IUserRepository userRepository)
 {
     if (userRepository == null) 
         throw new ArgumentNullException("userRepository");
     _userRepository = userRepository;
     Menu = new ReactiveList<MenuOptionViewModel>();
     // Use WhenAny to observe one or more values
     var canLoadMenu = this.WhenAny(m => m.User, user => user.Value != null);
     // hook function to command, shouldn't contain UI/complex logic
     LoadMenu = ReactiveCommand.CreateAsyncTask(canLoadMenu, _ => _userRepository.GetMenuByUser(User));
     // RxApp.MainThreadScheduler is our UI thread, you can go wild here
     LoadMenu.ObserveOn(RxApp.MainThreadScheduler).Subscribe(menu =>
     {
         Menu.Clear();
         foreach (var option in menu)
         {
             var menuOption = new MenuOptionViewModel(option);
             Menu.Add(menuOption);
         }
     });
     LoadMenu.ThrownExceptions.Subscribe(ex =>
     {
         Menu.Clear();
         MessageBox.Show(ex.Message);
     });
     // Use WhenAnyValue to check if a property was changed
     // If user was changed reload menu
     this.WhenAnyValue(m => m.User).InvokeCommand(this, vm => vm.LoadMenu);
 }
コード例 #3
0
        protected BaseCommitsViewModel()
	    {
            Title = "Commits";

            var gotoCommitCommand = ReactiveCommand.Create();
            gotoCommitCommand.OfType<CommitItemViewModel>().Subscribe(x =>
            {
                var vm = this.CreateViewModel<CommitViewModel>();
                vm.RepositoryOwner = RepositoryOwner;
                vm.RepositoryName = RepositoryName;
                vm.Node = x.Commit.Sha;
                NavigateTo(vm);
            });

            var commits = new ReactiveList<CommitItemViewModel>();
            Commits = commits.CreateDerivedCollection(
                x => x, 
                x => x.Description.ContainsKeyword(SearchKeyword) || x.Name.ContainsKeyword(SearchKeyword), 
                signalReset: this.WhenAnyValue(x => x.SearchKeyword));

            LoadCommand = ReactiveCommand.CreateAsyncTask(t =>
                commits.SimpleCollectionLoad(CreateRequest(), 
                    x => new CommitItemViewModel(x, gotoCommitCommand.ExecuteIfCan),
                    x => LoadMoreCommand = x == null ? null : ReactiveCommand.CreateAsyncTask(_ => x())));
	    }
コード例 #4
0
 public PersonListViewModel(IScreen hostScreen, IPersonRepository personRepository = null)
 {
     HostScreen = hostScreen;
     personRepository = personRepository ?? new PersonRepository();
     Persons = new ReactiveList<PersonItemViewModel>();
     NewPersonCommand = new ReactiveCommand(null);
     NewPersonCommand.RegisterAsyncAction(_ => { }).Subscribe(_ => HostScreen.Router.Navigate.Execute(new PersonAddViewModel(HostScreen)));
     RefreshCommand = new ReactiveCommand(null);
     var refresh = RefreshCommand.RegisterAsync<List<Person>>(_ => Observable.Start(() => personRepository.RetrievePersonsAsync().
                                                                                                           Result));
     refresh.Subscribe(list =>
     {
         using (Persons.SuppressChangeNotifications())
         {
             Persons.Clear();
             Persons.AddRange(personRepository.RetrievePersonsAsync().
                                               Result.Select(d => new PersonItemViewModel(d.FirstName,
                                                                      d.LastName,
                                                                      d.Age)));
         }
     });
     MessageBus.Current.Listen<Person>().
                Subscribe(p =>
                {
                    personRepository.AddPerson(p);
                    RefreshCommand.Execute(null);
                });
 }
コード例 #5
0
        public LanguagesViewModel(IJsonSerializationService jsonSerializationService, INetworkActivityService networkActivity)
        {
            var languages = new ReactiveList<LanguageModel>();

            Languages = languages.CreateDerivedCollection(
                x => new LanguageItemViewModel(x.Name, x.Slug), 
                x => x.Name.StartsWith(SearchKeyword ?? string.Empty, StringComparison.OrdinalIgnoreCase), 
                signalReset: this.WhenAnyValue(x => x.SearchKeyword));

            Languages
                .Changed.Select(_ => Unit.Default)
                .Merge(this.WhenAnyValue(x => x.SelectedLanguage).Select(_ => Unit.Default))
                .Select(_ => SelectedLanguage)
                .Where(x => x != null)
                .Subscribe(x =>
                {
                    foreach (var l in Languages)
                        l.Selected = l.Slug == x.Slug;
                });

            LoadCommand = ReactiveCommand.CreateAsyncTask(async t =>
            {
                var trendingData = await BlobCache.LocalMachine.DownloadUrl(LanguagesUrl, absoluteExpiration: DateTimeOffset.Now.AddDays(1));
                var langs = jsonSerializationService.Deserialize<List<LanguageModel>>(System.Text.Encoding.UTF8.GetString(trendingData));
                langs.Insert(0, DefaultLanguage);
                languages.Reset(langs);
            });

            LoadCommand.TriggerNetworkActivity(networkActivity);
            LoadCommand.ExecuteIfCan();
        }
コード例 #6
0
        public IssueLabelsViewModel(
            Func<Task<IReadOnlyList<Label>>> loadAllLabelsFunc,
            Func<Task<IReadOnlyList<Label>>> loadSelectedFunc,
            Func<IEnumerable<Label>, Task> saveLabelsFunc)
	    {
            var labels = new ReactiveList<Label>();
            var selected = new ReactiveList<Label>();
            Labels = labels.CreateDerivedCollection(x => 
            {
                var vm = new IssueLabelItemViewModel(x);
                vm.IsSelected = selected.Any(y => y.Url == x.Url);
                return vm;
            });

            SaveCommand = ReactiveCommand.CreateAsyncTask(_ =>
            {
                var currentlySelected = Labels.Where(x => x.IsSelected).ToList();
                var selectedLabelsUrl = currentlySelected.Select(x => x.Label.Url).ToArray();
                var prevSelectedLabelsUrl = selected.Select(x => x.Url).ToArray();
                var intersect = selectedLabelsUrl.Intersect(prevSelectedLabelsUrl).ToArray();
                var different = selectedLabelsUrl.Length != prevSelectedLabelsUrl.Length || intersect.Length != selectedLabelsUrl.Length;
                return different ? saveLabelsFunc(currentlySelected.Select(x => x.Label)) : Task.FromResult(0);
            });

            LoadCommand = ReactiveCommand.CreateAsyncTask(async _ => {
                selected.Clear();
                selected.AddRange((await loadSelectedFunc()) ?? Enumerable.Empty<Label>());
                labels.Reset(await loadAllLabelsFunc());
            });
	    }
コード例 #7
0
        public AccountsViewModel(IAccountsService accountsService)
        {
            _accountsService = accountsService;
            Accounts = new ReactiveList<IAccount>(accountsService);
            LoginCommand = ReactiveCommand.Create();
            GoToAddAccountCommand = ReactiveCommand.Create();
            DeleteAccountCommand = ReactiveCommand.Create();

            DeleteAccountCommand.OfType<IAccount>().Subscribe(x =>
            {
                if (Equals(accountsService.ActiveAccount, x))
                    ActiveAccount = null;
                accountsService.Remove(x);
                Accounts.Remove(x);
            });

            LoginCommand.OfType<IAccount>().Subscribe(x =>
            {
                if (Equals(accountsService.ActiveAccount, x))
                    DismissCommand.ExecuteIfCan();
                else
                {
                    ActiveAccount = x;
                    MessageBus.Current.SendMessage(new LogoutMessage());
                    DismissCommand.ExecuteIfCan();
                }
            });

            GoToAddAccountCommand.Subscribe(_ => ShowViewModel(CreateViewModel<IAddAccountViewModel>()));

            this.WhenActivated(d => Accounts.Reset(accountsService));
        }
コード例 #8
0
        public RepositoryCreationViewModelDesigner()
        {
            RepositoryName = "Hello-World";
            Description = "A description";
            KeepPrivate = true;
            CanKeepPrivate = true;
            Accounts = new ReactiveList<IAccount>
            {
                new AccountDesigner { Login = "******" },
                new AccountDesigner { Login = "******", IsUser = false }
            };
            SelectedAccount = Accounts[0];
            GitIgnoreTemplates = new ReactiveList<GitIgnoreItem>
            {
                GitIgnoreItem.Create("VisualStudio"),
                GitIgnoreItem.Create("Wap"),
                GitIgnoreItem.Create("WordPress")
            };
            SelectedGitIgnoreTemplate = GitIgnoreTemplates[0];
            Licenses = new ReactiveList<LicenseItem>
            {
                new LicenseItem("agpl-3.0", "GNU Affero GPL v3.0"),
                new LicenseItem("apache-2.0", "Apache License 2.0"),
                new LicenseItem("artistic-2.0", "Artistic License 2.0"),
                new LicenseItem("mit", "MIT License")
            };

            SelectedLicense = Licenses[0];
        }
コード例 #9
0
        protected LibraryGroupViewModel(string header, string addHeader = null, string icon = null) {
            Header = header;
            AddHeader = addHeader;
            Icon = icon;
            if (!Execute.InDesignMode)
                this.SetCommand(x => x.AddCommand);

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

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


            UiHelper.TryOnUiThread(() => {
                Children.EnableCollectionSynchronization(_childrenLock);
                _childrenView =
                    Children.CreateCollectionView(
                        new[] {
                            new SortDescription("SortOrder", ListSortDirection.Ascending),
                            new SortDescription("Model.IsFavorite", ListSortDirection.Descending),
                            new SortDescription("Model.Name", ListSortDirection.Ascending)
                        }, null,
                        null, null, true);
                _itemsView = _childrenView;
            });
        }
コード例 #10
0
        public AgentAnnotationViewModel(ISharedDataService sharedDataService, MeetingViewModel meeting)
            : base(sharedDataService, meeting)
        {
            _annotations = new ReactiveList<AnnotationViewModel>();

            var annotationsChangedObs = _annotations
                .WhenAnyObservable(p => p.Changed)
                .Select(p => AreThereAnnotationInTheCurrentPage());

            var activeToolObs = Meeting.WhenAnyValue(vm => vm.ActiveTool).Where(t => t != null);
            var pageChangedObs = activeToolObs
                             .Select(t => t.WhenAnyValue(v => v.CurrentPageNumber, p => AreThereAnnotationInTheCurrentPage()))
                             .Switch(); // Only listen to the most recent sequence of property changes (active tool)
            var toolChangedObs = activeToolObs.Select(t => AreThereAnnotationInTheCurrentPage());

            _containsAnnotationsForCurrentPage = toolChangedObs.Merge(pageChangedObs).Merge(annotationsChangedObs)
                .ToProperty(this, p => p.ContainsAnnotationsForCurrentPage); 

            AnnotationTools = new AnnotationToolViewModel(this);

            // when the IsEditing flag changes to false, it means an edit has just completed and we can send
            // the updates annotations to the client
            _isEditingSub = this.WhenAnyValue(p => p.IsEditing)
                .Where(p => !p)
                .Subscribe(_ => UpdateAnnotationModelAnnotations());
        }
コード例 #11
0
        public MainVM()
        {
            var bobbyJoe = new Person("Bobby Joe", new[] { new Pet("Fluffy") });
            var bob = new Person("Bob", new[] { bobbyJoe });
            var littleJoe = new Person("Little Joe");
            var joe = new Person("Joe", new[] { littleJoe });
            Family = new ReactiveList<TreeItem> { bob, joe };

            _addPerson = ReactiveCommand.Create();
            _addPerson.Subscribe(_ =>
            {
                if (SelectedItem == null) return;
                var p = new Person(NewName);
                SelectedItem.AddChild(p);
                p.IsSelected = true;
                p.ExpandPath();
            });
            _addPet = ReactiveCommand.Create();
            _addPet.Subscribe(_ =>
            {
                if (SelectedItem == null) return;
                var p = new Pet(PetName);
                SelectedItem.AddChild(p);
                p.IsSelected = true;
                p.ExpandPath();
            });
            _collapse = ReactiveCommand.Create();
            _collapse.Subscribe(_ =>
            {
                SelectedItem?.CollapsePath();
            });
        }
コード例 #12
0
        public PullRequestsViewModel(IApplicationService applicationService)
		{
            PullRequests = new ReactiveList<PullRequestModel>();

            GoToPullRequestCommand = ReactiveCommand.Create();
		    GoToPullRequestCommand.OfType<PullRequestModel>().Subscribe(pullRequest =>
		    {
		        var vm = CreateViewModel<PullRequestViewModel>();
		        vm.RepositoryOwner = RepositoryOwner;
		        vm.RepositoryName = RepositoryName;
		        vm.PullRequestId = pullRequest.Number;
		        vm.PullRequest = pullRequest;
		        vm.WhenAnyValue(x => x.PullRequest).Skip(1).Subscribe(x =>
		        {
                    var index = PullRequests.IndexOf(pullRequest);
                    if (index < 0) return;
                    PullRequests[index] = x;
                    PullRequests.Reset();
		        });
                ShowViewModel(vm);
		    });

		    this.WhenAnyValue(x => x.SelectedFilter).Skip(1).Subscribe(_ => LoadCommand.ExecuteIfCan());

            LoadCommand = ReactiveCommand.CreateAsyncTask(t =>
            {
                var state = SelectedFilter == 0 ? "open" : "closed";
			    var request = applicationService.Client.Users[RepositoryOwner].Repositories[RepositoryName].PullRequests.GetAll(state: state);
                return PullRequests.SimpleCollectionLoad(request, t as bool?);
            });
		}
コード例 #13
0
ファイル: BlogViewModel.cs プロジェクト: moswald/rxui-samples
        public BlogViewModel(string title, Uri feedAddress, IFeedService feedService = null, IBlobCache cache = null)
        {
            Title = title;
            FeedAddress = feedAddress;
            FeedService = feedService ?? Locator.Current.GetService<IFeedService>();
            Cache = cache ?? Locator.Current.GetService<IBlobCache>();

            Articles = new ReactiveList<ArticleViewModel>();

            Refresh = ReactiveCommand.CreateAsyncObservable(x => GetAndFetchLatestArticles());
            Refresh.Subscribe(articles =>
            {
                // this could be done cleaner, send a PR.
                // Refresh.ToPropertyEx(this, x => x.Articles);

                Articles.Clear();
                Articles.AddRange(articles);
            });

            
            Refresh.ThrownExceptions.Subscribe(thrownException => { this.Log().Error(thrownException); });
            _isLoading = Refresh.IsExecuting.ToProperty(this, x => x.IsLoading);

            // post-condition checks
            Condition.Ensures(FeedAddress).IsNotNull();
            Condition.Ensures(FeedService).IsNotNull();
            Condition.Ensures(Cache).IsNotNull();
        }
コード例 #14
0
        public AddInterestViewModel(IApplicationService applicationService)
        {
            DoneCommand = ReactiveCommand.CreateAsyncTask(async _ =>
            {
                if (SelectedLanguage == null)
                    throw new Exception("You must select a language for your interest!");
                if (string.IsNullOrEmpty(Keyword))
                    throw new Exception("Please specify a keyword to go with your interest!");

                applicationService.Account.Interests.Insert(new Interest
                {
                    Language = _selectedLanguage.Name,
                    LanguageId = _selectedLanguage.Slug,
                    Keyword = _keyword
                });

                await DismissCommand.ExecuteAsync();
            });

            GoToLanguagesCommand = ReactiveCommand.Create();
            GoToLanguagesCommand.Subscribe(_ =>
            {
                var vm = CreateViewModel<LanguagesViewModel>();
                vm.SelectedLanguage = SelectedLanguage;
                vm.WhenAnyValue(x => x.SelectedLanguage).Skip(1).Subscribe(x =>
                {
                    SelectedLanguage = x;
                    vm.DismissCommand.ExecuteIfCan();
                });
                ShowViewModel(vm);
            });

            var str = System.IO.File.ReadAllText(PopularInterestsPath, System.Text.Encoding.UTF8);
            PopularInterests = new ReactiveList<PopularInterest>(JsonConvert.DeserializeObject<List<PopularInterest>>(str));
        }
コード例 #15
0
        public ViewModel2()
        {
            SearchResults = new ReactiveList<FlickrPhoto>();
            var canSearch = this.WhenAny(x => x.SearchTerm, x => !String.IsNullOrWhiteSpace(x.Value));

            Search = ReactiveCommand.CreateAsyncTask(canSearch, async _ =>  {  return await GetSearchResultFromBing(this.SearchTerm); });
            LoadMoreItems = ReactiveCommand.CreateAsyncTask(canSearch, async x => { return await LoadMore((int)x);  });

            Search.Subscribe(results =>
            {
                SearchResults.Clear();
                foreach (var item in results)
                {
                    SearchResults.Add(item);
                }
            });

            LoadMoreItems.Subscribe(results =>
            {
                foreach (var item in results)
                {
                    SearchResults.Add(item);
                }
            });

            Search.ThrownExceptions.Subscribe(ex => { UserError.Throw("Potential network connectivity Error", ex); });
            LoadMoreItems.ThrownExceptions.Subscribe(ex => { UserError.Throw("Problem when downloading additional items", ex); });

            this.WhenAnyValue(x => x.SearchTerm)
                .Throttle(TimeSpan.FromSeconds(1), RxApp.MainThreadScheduler)
                .InvokeCommand(this, x => x.Search);

            //SearchTerm = "british cat";
        }
コード例 #16
0
        public PickCollectionViewModel(IMediator mediator) {
            _mediator = mediator;
            Items = new ReactiveList<PickCollectionDataModel>();
            UiHelper.TryOnUiThread(() => {
                Items.EnableCollectionSynchronization(_itemsLock);
                ItemsView =
                    Items.CreateCollectionView(new List<SortDescription> {
                        new SortDescription("Name", ListSortDirection.Ascending)
                    }, null, new List<string> {"Name"}, OnFilter, true);
            });
            SelectedItems = new ReactiveList<PickCollectionDataModel>();

            this.WhenAnyValue(x => x.FilterText)
                .Throttle(Common.AppCommon.DefaultFilterDelay)
                .ObserveOn(RxApp.MainThreadScheduler)
                .Subscribe(x => ItemsView.TryRefreshIfHasView());

            this.SetCommand(x => x.OkCommand,
                this.WhenAnyValue(x => x.SelectedItems.Count).Select(x => x > 0), false)
                .RegisterAsyncTask(Process)
                .Subscribe();

            OkCommand.IsExecuting.Subscribe(x => IsExecuting = x);

            DisplayName = "Add mod to Collections";
        }
コード例 #17
0
ファイル: ExploreViewModel.cs プロジェクト: zdd910/CodeHub
        public ExploreViewModel(ISessionService applicationService)
        {
            ShowRepositoryDescription = applicationService.Account.ShowRepositoryDescriptionInList;

            Title = "Explore";

            var gotoRepository = new Action<RepositoryItemViewModel>(x => {
                var vm = this.CreateViewModel<RepositoryViewModel>();
                vm.RepositoryOwner = x.Owner;
                vm.RepositoryName = x.Name;
                NavigateTo(vm);
            });

            var repositories = new ReactiveList<Octokit.Repository>();
            Repositories = repositories.CreateDerivedCollection(x => 
                new RepositoryItemViewModel(x, true, gotoRepository));

            var users = new ReactiveList<Octokit.User>();
            Users = users.CreateDerivedCollection(x => 
                new UserItemViewModel(x.Login, x.AvatarUrl, false, () => {
                    var vm = this.CreateViewModel<UserViewModel>();
                    vm.Init(x.Login);
                    NavigateTo(vm);
                }));

            this.WhenAnyValue(x => x.SearchFilter)
                .DistinctUntilChanged()
                .Subscribe(_ => {
                    SearchText = string.Empty;
                    users.Clear();
                    repositories.Clear();
                });

            var canSearch = this.WhenAnyValue(x => x.SearchText).Select(x => !string.IsNullOrEmpty(x));
            SearchCommand = ReactiveCommand.CreateAsyncTask(canSearch, async t => {
                try
                {
                    users.Clear();
                    repositories.Clear();

                    if (SearchFilter == SearchType.Repositories)
                    {
                        var request = new Octokit.SearchRepositoriesRequest(SearchText);
                        var response = await applicationService.GitHubClient.Search.SearchRepo(request);
                        repositories.Reset(response.Items);
                    }
                    else if (SearchFilter == SearchType.Users)
                    {
                        var request = new Octokit.SearchUsersRequest(SearchText);
                        var response = await applicationService.GitHubClient.Search.SearchUsers(request);
                        users.Reset(response.Items);
                    }
                }
                catch (Exception e)
                {
                    var msg = string.Format("Unable to search for {0}. Please try again.", SearchFilter.Humanize());
                    throw new Exception(msg, e);
                }
            });
        }
コード例 #18
0
        public FlickrSearchViewModel(IImageService imageService)
        {
            Images = new ReactiveList<SearchResultViewModel>();

            var canExecute = this.WhenAnyValue(x => x.SearchText)
                .Select(x => !String.IsNullOrWhiteSpace(x));

            Search = ReactiveCommand.CreateAsyncObservable(
                canExecute,
                _ =>
                {
                    Images.Clear();
                    ShowError = false;
                    return imageService.GetImages(SearchText);
                });

            Search.Subscribe(images => Images.Add(images));

            Search.ThrownExceptions.Subscribe(_ => ShowError = true);

            isLoading = Search.IsExecuting.ToProperty(this, vm => vm.IsLoading);

            canEnterSearchText = this.WhenAnyValue(x => x.IsLoading)
                .Select(x => !x)
                .ToProperty(this, vm => vm.CanEnterSearchText);
        }
コード例 #19
0
        public IssueMilestonesViewModel(
            Func<Task<IReadOnlyList<Milestone>>> loadMilestones,
            Func<Task<Milestone>> loadSelectedFunc,
            Func<Milestone, Task> saveFunc)
        {
            var milestones = new ReactiveList<Milestone>();
            Milestones = milestones.CreateDerivedCollection(x => CreateItemViewModel(x));

            this.WhenAnyValue(x => x.Selected)
                .Subscribe(x => {
                    foreach (var a in Milestones)
                        a.IsSelected = a.Number == x?.Number;
                });

            DismissCommand = ReactiveCommand.Create();

            SaveCommand = ReactiveCommand.CreateAsyncTask(_ => {
                DismissCommand.ExecuteIfCan();
                return _selected != _previouslySelected ? saveFunc(_selected) : Task.FromResult(0);
            });

            LoadCommand = ReactiveCommand.CreateAsyncTask(async _ => {
                _previouslySelected = Selected = await loadSelectedFunc();
                milestones.Reset(await loadMilestones());
            });
        }
コード例 #20
0
        public MetroiLinksViewModel()
        {
            OpenPageSelectorCommand = new ReactiveCommand();
            OpenPageSelectorCommand
                .Where(x => MetroiLink != null)
                .Select(x => new Dialog.PageSelector())
                .Subscribe(x =>
                {
                    x.Show();
                    MessageBus.Current.SendMessage(CommunityProfiles, "pagesToSelect");
                });

            this.ObservableForProperty(x => x.MetroiLink)
                .Subscribe(x =>
                {
                    ShowEditor = x.Value != null;
                    NotShowEditor = !ShowEditor;
                    var cpRepo = new CommunityProfilesRepo();
                    if (x.Value != null)
                        CommunityProfiles = new ReactiveList<Page>(cpRepo.GetCommunityProfiles(x.Value.Client_ID));
                });

            CommunityProfiles = new ReactiveList<Page>();
            NotShowEditor = !ShowEditor;
        }
コード例 #21
0
        public ObserveWindowViewModel( string filename, IActorRef tailCoordinator )
        {
            _tailCoordinator = tailCoordinator;
            Filename = filename;
            Title = filename;
            Items = new ReactiveList<String>();

            // start coordinator
            _tailCoordinator.Tell( new TailCoordinatorActor.StartTail( filename, this ) );

            // this is how we can update the viewmodel
            // from the actor.
            Lines = new Subject<String>();
            Lines.ObserveOnDispatcher().Subscribe( item =>
            {
                Items.Add( item );

                if ( Items.Count > 1500 )
                {
                    Items.RemoveAt( 0 );
                }

                SelectedLine = Items.Count - 1;

            } );
        }
コード例 #22
0
        public MainWindowModel()
        {
            _testDataSource = new TestDataSource();
            TestModels = new ReactiveList<TestModel>();

            TestViewModels = TestModels.CreateDerivedCollection(m =>
            {
                var vm = new TestViewModel
                {
                    Id = m.Id,
                    Name = m.Name,
                    OtherValue = "",
                    OriginalModel = m
                };
                vm.DoStuffWithThisCommand.Subscribe(x => DoStuff(x as TestViewModel));
                return vm;
            }, m => true, (m, vm) => 0);

            SetUpDataCommand = ReactiveCommand.CreateAsyncTask(_ => _testDataSource.GetTests());
            SetUpDataCommand.Subscribe(results =>
                {
                    using (SuppressChangeNotifications())
                    {
                        TestModels.Clear();
                        foreach (var model in results)
                            TestModels.Add(model);
                    }
                });
        }
コード例 #23
0
        public CacheViewModel(IScreen hostScreen, IAppState appState)
        {
            HostScreen = hostScreen;

            appState.WhenAny(x => x.CachePath, x => x.Value)
                .Where(x => !String.IsNullOrWhiteSpace(x))
                .Select(x => (new DirectoryInfo(x)).Name)
                .ToProperty(this, x => x.UrlPathSegment, out _UrlPathSegment);

            Keys = new ReactiveList<string>();
            appState.WhenAny(x => x.CurrentCache, x => x.Value)
                .SelectMany(x => Observable.Start(() => x.GetAllKeys(), RxApp.TaskpoolScheduler))
                .ObserveOn(RxApp.MainThreadScheduler)
                .Subscribe(newKeys => {
                    Keys.Clear();
                    newKeys.ForEach(x => Keys.Add(x));
                });

            FilteredKeys = Keys.CreateDerivedCollection(
                key => key,
                key => FilterText == null || key.IndexOf(FilterText, StringComparison.OrdinalIgnoreCase) > -1,
                signalReset: this.WhenAny(x => x.FilterText, x => x.Value));

            SelectedViewer = "Text";

            this.WhenAny(x => x.SelectedKey, x => x.SelectedViewer, (k, v) => k.Value)
                .Where(x => x != null && SelectedViewer != null)
                .SelectMany(x => appState.CurrentCache.GetAsync(x).Catch(Observable.Return(default(byte[]))))
                .Select(x => createValueViewModel(x, SelectedViewer))
                .LoggedCatch(this, Observable.Return<ICacheValueViewModel>(null))
                .ToProperty(this, x => x.SelectedValue, out _SelectedValue);
        }
コード例 #24
0
        public IssueMilestonesViewModel(IApplicationService applicationService)
        {
            Milestones = new ReactiveList<MilestoneModel>();

            SelectMilestoneCommand = ReactiveCommand.CreateAsyncTask(async t =>
            {
                var milestone = t as MilestoneModel;
                if (milestone != null)
                    SelectedMilestone = milestone;

                if (SaveOnSelect)
                {
                    try
                    {
                        int? milestoneNumber = null;
                        if (SelectedMilestone != null) milestoneNumber = SelectedMilestone.Number;
                        var updateReq = applicationService.Client.Users[RepositoryOwner].Repositories[RepositoryName].Issues[IssueId].UpdateMilestone(milestoneNumber);
                        await applicationService.Client.ExecuteAsync(updateReq);
                    }
                    catch (Exception e)
                    {
                        throw new Exception("Unable to to save milestone! Please try again.", e);
                    }
                }

                DismissCommand.ExecuteIfCan();
            });

            LoadCommand = ReactiveCommand.CreateAsyncTask(t =>
                Milestones.SimpleCollectionLoad(
                    applicationService.Client.Users[RepositoryOwner].Repositories[RepositoryName].Milestones.GetAll(),
                    t as bool?));
        }
コード例 #25
0
 private MultiSelectCollectionView<ShortcutViewModel> CreateCollectionView(ReactiveList<ShortcutViewModel> shortcuts)
 {
     var view = new MultiSelectCollectionView<ShortcutViewModel>(shortcuts);
     view.Filter = ApplyFilter;
     view.SortDescriptions.Add(new SortDescription(nameof(ShortcutViewModel.Name), ListSortDirection.Ascending));
     return view;
 }
コード例 #26
0
        public ChangesetViewModel(IApplicationService applicationService)
        {
            _applicationService = applicationService;

            Comments = new ReactiveList<CommentModel>();

            GoToHtmlUrlCommand = ReactiveCommand.Create(this.WhenAnyValue(x => x.Commit).Select(x => x != null));
            GoToHtmlUrlCommand.Select(x => Commit).Subscribe(GoToUrlCommand.ExecuteIfCan);

            GoToRepositoryCommand = ReactiveCommand.Create();
            GoToRepositoryCommand.Subscribe(_ =>
            {
                var vm = CreateViewModel<RepositoryViewModel>();
                vm.RepositoryOwner = RepositoryOwner;
                vm.RepositoryName = RepositoryName;
                ShowViewModel(vm);
            });

            GoToFileCommand = ReactiveCommand.Create();
            GoToFileCommand.OfType<CommitModel.CommitFileModel>().Subscribe(x =>
            {
                if (x.Patch == null)
                {
                    var vm = CreateViewModel<SourceViewModel>();
                    vm.Branch = Commit.Sha;
                    vm.Username = RepositoryOwner;
                    vm.Repository = RepositoryName;
                    vm.Items = new [] 
                    { 
                        new SourceViewModel.SourceItemModel 
                        {
                            ForceBinary = true,
                            GitUrl = x.BlobUrl,
                            Name = x.Filename,
                            Path = x.Filename,
                            HtmlUrl = x.BlobUrl
                        }
                    };
                    vm.CurrentItemIndex = 0;
                    ShowViewModel(vm);
                }
                else
                {
                    var vm = CreateViewModel<ChangesetDiffViewModel>();
                    vm.Username = RepositoryOwner;
                    vm.Repository = RepositoryName;
                    vm.Branch = Commit.Sha;
                    vm.Filename = x.Filename;
                    ShowViewModel(vm);
                }
            });

            LoadCommand = ReactiveCommand.CreateAsyncTask(t =>
            {
                var forceCacheInvalidation = t as bool?;
                var t1 = this.RequestModel(_applicationService.Client.Users[RepositoryOwner].Repositories[RepositoryName].Commits[Node].Get(), forceCacheInvalidation, response => Commit = response.Data);
                Comments.SimpleCollectionLoad(_applicationService.Client.Users[RepositoryOwner].Repositories[RepositoryName].Commits[Node].Comments.GetAll(), forceCacheInvalidation).FireAndForget();
                return t1;
            });
        }
コード例 #27
0
        public IssueLabelsViewModel(Func<Task<IReadOnlyList<Label>>> loadLabels)
	    {
            var labels = new ReactiveList<Label>();
            Selected = new ReactiveList<Label>();
            Labels = labels.CreateDerivedCollection(x => 
            {
                var vm = new IssueLabelItemViewModel(x);
                vm.IsSelected = Selected.Any(y => string.Equals(y.Name, x.Name));
//                vm.GoToCommand
//                    .Select(_ => x)
//                    .Where(y => vm.IsSelected)
//                    .Where(y => Selected.All(l => l.Url != y.Url))
//                    .Subscribe(Selected.Add);
//                vm.GoToCommand
//                    .Select(_ => x)
//                    .Where(y => !vm.IsSelected)
//                    .Select(y => Selected.Where(l => l.Url == y.Url).ToArray())
//                    .Subscribe(Selected.RemoveAll);
                return vm;
            });

            SelectLabelsCommand = ReactiveCommand.CreateAsyncTask(t => {
                var selectedLabelsUrl = Selected.Select(x => x.Url).ToArray();
                var prevSelectedLabelsUrl = _previouslySelectedLabels.Select(x => x.Url).ToArray();
                var intersect = selectedLabelsUrl.Intersect(prevSelectedLabelsUrl).ToArray();
                var different = selectedLabelsUrl.Length != prevSelectedLabelsUrl.Length || intersect.Length != selectedLabelsUrl.Length;
                return Task.FromResult(0); //different ? updateIssue(new ReadOnlyCollection<Label>(Selected)) : Task.FromResult(0);
	        });

            LoadCommand = ReactiveCommand.CreateAsyncTask(async _ => {
                labels.Reset(await loadLabels());
            });
	    }
コード例 #28
0
ファイル: BaseUsersViewModel.cs プロジェクト: zdd910/CodeHub
        protected BaseUsersViewModel()
        {
            var users = new ReactiveList<BasicUserModel>();
            Users = users.CreateDerivedCollection(x => {
                var isOrg = string.Equals(x.Type, "organization", StringComparison.OrdinalIgnoreCase);
                return new UserItemViewModel(x.Login, x.AvatarUrl, isOrg, () => {
                    if (isOrg)
                    {
                        var vm = this.CreateViewModel<OrganizationViewModel>();
                        vm.Init(x.Login);
                        NavigateTo(vm);
                    }
                    else
                    {
                        var vm = this.CreateViewModel<UserViewModel>();
                        vm.Init(x.Login);
                        NavigateTo(vm);
                    }
                });
            },
            x => x.Login.StartsWith(SearchKeyword ?? string.Empty, StringComparison.OrdinalIgnoreCase),
            signalReset: this.WhenAnyValue(x => x.SearchKeyword));

            LoadCommand = ReactiveCommand.CreateAsyncTask(t =>
                users.SimpleCollectionLoad(CreateRequest(), 
                x => LoadMoreCommand = x == null ? null : ReactiveCommand.CreateAsyncTask(_ => x())));
        }
コード例 #29
0
ファイル: AppState.cs プロジェクト: dbeattie71/HDP-Mobil
 public AppState()
 {
     Articles = new ReactiveList<Article> ();
     ElectionArticles = new ReactiveList<ElectionArticle> ();
     Events = new ReactiveList<Event> ();
     OrganizationMenuItems = new ReactiveList<OrganizationMenuItem> ();
 }
コード例 #30
0
        public IssueAssigneeViewModel(
            Func<Task<IReadOnlyList<User>>> loadAssignees,
            Func<Task<User>> loadSelectedFunc,
            Func<User, Task> saveFunc)
        {
            var assignees = new ReactiveList<IssueAssigneeItemViewModel>();
            Assignees = assignees.CreateDerivedCollection(
                x => x,
                filter: x => x.Name.ContainsKeyword(SearchKeyword),
                signalReset: this.WhenAnyValue(x => x.SearchKeyword));

            this.WhenAnyValue(x => x.Selected)
                .Subscribe(x => {
                    foreach (var a in Assignees)
                        a.IsSelected = string.Equals(a.User.Login, x?.Login);
                });

            DismissCommand = ReactiveCommand.Create();

            SaveCommand = ReactiveCommand.CreateAsyncTask(_ => {
                DismissCommand.ExecuteIfCan();
                return Selected != _previouslySelected ? saveFunc(_selected) : Task.FromResult(0);
            });

            LoadCommand = ReactiveCommand.CreateAsyncTask(async _ => {
                _previouslySelected = Selected = await loadSelectedFunc();
                assignees.Reset((await loadAssignees()).Select(CreateItemViewModel));
            });
        }
コード例 #31
0
        internal static void CloneReactiveList <T>(this ReactiveList <T> source, IChangeSet <T> changes)
        {
            if (source == null)
            {
                throw new ArgumentNullException(nameof(source));
            }
            if (changes == null)
            {
                throw new ArgumentNullException(nameof(changes));
            }

            changes.ForEach(item =>
            {
                switch (item.Reason)
                {
                case ListChangeReason.Add:
                    {
                        var change   = item.Item;
                        var hasIndex = change.CurrentIndex >= 0;
                        if (hasIndex)
                        {
                            source.Insert(change.CurrentIndex, change.Current);
                        }
                        else
                        {
                            source.Add(change.Current);
                        }
                        break;
                    }

                case ListChangeReason.AddRange:
                    {
                        var startingIndex = item.Range.Index;

                        if (RxApp.SupportsRangeNotifications)
                        {
                            if (startingIndex >= 0)
                            {
                                source.InsertRange(startingIndex, item.Range);
                            }
                            else
                            {
                                source.AddRange(item.Range);
                            }
                        }
                        else
                        {
                            if (startingIndex >= 0)
                            {
                                item.Range.Reverse().ForEach(t => source.Insert(startingIndex, t));
                            }
                            else
                            {
                                item.Range.ForEach(source.Add);
                            }
                        }

                        break;
                    }

                case ListChangeReason.Clear:
                    {
                        source.Clear();
                        break;
                    }

                case ListChangeReason.Replace:
                    {
                        var change    = item.Item;
                        bool hasIndex = change.CurrentIndex >= 0;
                        if (hasIndex && change.CurrentIndex == change.PreviousIndex)
                        {
                            source[change.CurrentIndex] = change.Current;
                        }
                        else
                        {
                            source.RemoveAt(change.PreviousIndex);
                            source.Insert(change.CurrentIndex, change.Current);
                        }
                    }
                    break;

                case ListChangeReason.Remove:
                    {
                        var change    = item.Item;
                        bool hasIndex = change.CurrentIndex >= 0;
                        if (hasIndex)
                        {
                            source.RemoveAt(change.CurrentIndex);
                        }
                        else
                        {
                            source.Remove(change.Current);
                        }
                        break;
                    }

                case ListChangeReason.RemoveRange:
                    {
                        if (RxApp.SupportsRangeNotifications && item.Range.Index >= 0)
                        {
                            source.RemoveRange(item.Range.Index, item.Range.Count);
                        }
                        else
                        {
                            source.RemoveMany(item.Range);
                        }
                    }
                    break;

                case ListChangeReason.Moved:
                    {
                        var change    = item.Item;
                        bool hasIndex = change.CurrentIndex >= 0;
                        if (!hasIndex)
                        {
                            throw new UnspecifiedIndexException("Cannot move as an index was not specified");
                        }

                        source.Move(change.PreviousIndex, change.CurrentIndex);
                        break;
                    }
                }
            });
        }
コード例 #32
0
 private void InitializeStages()
 {
     stages = new ReactiveList <StageObject>();
     ReloadStages();
 }
コード例 #33
0
 public Parent(int id)
 {
     Id               = id;
     Children         = new ReactiveList <Person>();
     ChildrenReadonly = Children;
 }
コード例 #34
0
 public Parent(int id, IEnumerable <Person> children)
 {
     Id               = id;
     Children         = new ReactiveList <Person>(children);
     ChildrenReadonly = Children;
 }
 public Parent()
 {
     Children         = new ReactiveList <Person>();
     ChildrenReadonly = Children;
 }
コード例 #36
0
        public SourceTreeViewModel(IApplicationService applicationService)
        {
            //Filter = applicationService.Account.Filters.GetFilter<SourceFilterModel>("SourceViewModel");
            var content = new ReactiveList <ContentModel>();

            Content = content.CreateDerivedCollection(x => x);

            GoToSubmoduleCommand = ReactiveCommand.Create();
            GoToSubmoduleCommand.OfType <ContentModel>().Subscribe(x =>
            {
                var nameAndSlug = x.GitUrl.Substring(x.GitUrl.IndexOf("/repos/", StringComparison.OrdinalIgnoreCase) + 7);
                var repoId      = new RepositoryIdentifier(nameAndSlug.Substring(0, nameAndSlug.IndexOf("/git", StringComparison.OrdinalIgnoreCase)));
                var vm          = CreateViewModel <SourceTreeViewModel>();
                vm.Username     = repoId.Owner;
                vm.Repository   = repoId.Name;
                vm.Branch       = x.Sha;
                ShowViewModel(vm);
            });

            GoToSourceCommand = ReactiveCommand.Create();
            GoToSourceCommand.OfType <ContentModel>().Subscribe(x =>
            {
                var otherFiles = Content
                                 .Where(y => string.Equals(y.Type, "file", StringComparison.OrdinalIgnoreCase))
                                 .Where(y => y.Size.HasValue && y.Size.Value > 0)
                                 .Select(y => new SourceViewModel.SourceItemModel
                {
                    Name    = y.Name,
                    Path    = y.Path,
                    HtmlUrl = y.HtmlUrl,
                    GitUrl  = y.GitUrl
                }).ToArray();

                var vm              = CreateViewModel <SourceViewModel>();
                vm.Branch           = Branch;
                vm.Username         = Username;
                vm.Repository       = Repository;
                vm.TrueBranch       = TrueBranch;
                vm.Items            = otherFiles;
                vm.CurrentItemIndex = Array.FindIndex(otherFiles, f => string.Equals(f.GitUrl, x.GitUrl, StringComparison.OrdinalIgnoreCase));
                ShowViewModel(vm);
            });

            GoToSourceTreeCommand = ReactiveCommand.Create();
            GoToSourceTreeCommand.OfType <ContentModel>().Subscribe(x =>
            {
                var vm        = CreateViewModel <SourceTreeViewModel>();
                vm.Username   = Username;
                vm.Branch     = Branch;
                vm.Repository = Repository;
                vm.TrueBranch = TrueBranch;
                vm.Path       = x.Path;
                ShowViewModel(vm);
            });

            this.WhenAnyValue(x => x.Filter).Subscribe(filter =>
            {
//                if (filter == null)
//                {
//                    Content.OrderFunc = null;
//                }
//                else
//                {
//                    Content.OrderFunc = x =>
//                    {
//                        switch (filter.OrderBy)
//                        {
//                            case SourceFilterModel.Order.FoldersThenFiles:
//                                x = x.OrderBy(y => y.Type).ThenBy(y => y.Name);
//                                break;
//                            default:
//                                x = x.OrderBy(y => y.Name);
//                                break;
//                        }
//
//                        return filter.Ascending ? x : x.Reverse();
//                    };
//                }
            });

            LoadCommand = ReactiveCommand.CreateAsyncTask(t =>
                                                          content.SimpleCollectionLoad(
                                                              applicationService.Client.Users[Username].Repositories[Repository].GetContent(
                                                                  Path ?? string.Empty, Branch ?? "master"), t as bool?));
        }
コード例 #37
0
        /// <summary>
        /// Convert an observable collection into a dynamic stream of change sets, using the hash code as the object's key
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="source">The source.</param>
        /// <returns></returns>
        /// <exception cref="System.ArgumentNullException">source</exception>
        public static IObservable <IChangeSet <T> > ToObservableChangeSet <T>(this  ReactiveList <T> source)
        {
            return(Observable.Create <IChangeSet <T> >
                   (
                       observer =>
            {
                Func <ChangeSet <T> > initialChangeSet = () =>
                {
                    var items = source.Select((t, index) => new Change <T>(ListChangeReason.Add, t, index));
                    return new ChangeSet <T>(items);
                };

                //populate local cache, otherwise there is no way to deal with a reset
                var cloneOfList = new SourceList <T>();

                var sourceUpdates = Observable
                                    .FromEventPattern <NotifyCollectionChangedEventHandler, NotifyCollectionChangedEventArgs>(
                    h => source.CollectionChanged += h,
                    h => source.CollectionChanged -= h)
                                    .Select
                                    (
                    args =>
                {
                    var changes = args.EventArgs;

                    switch (changes.Action)
                    {
                    case NotifyCollectionChangedAction.Add:
                        return changes.NewItems.OfType <T>()
                        .Select((t, index) => new Change <T>(ListChangeReason.Add, t, index + changes.NewStartingIndex));

                    case NotifyCollectionChangedAction.Remove:
                        return changes.OldItems.OfType <T>()
                        .Select((t, index) => new Change <T>(ListChangeReason.Remove, t, index + changes.OldStartingIndex));

                    case NotifyCollectionChangedAction.Replace:
                        {
                            return changes.NewItems.OfType <T>()
                            .Select((t, idx) =>
                            {
                                var old = changes.OldItems[idx];
                                return new Change <T>(ListChangeReason.Replace, t, (T)old, idx, idx);
                            });
                        }

                    case NotifyCollectionChangedAction.Reset:
                        {
                            //Clear all from the cache and reload
                            var removes = source.Select((t, index) => new Change <T>(ListChangeReason.Remove, t, index)).Reverse();
                            return removes.Concat(initialChangeSet());
                        }

                    case NotifyCollectionChangedAction.Move:
                        {
                            var item = changes.NewItems.OfType <T>().First();
                            var change = new Change <T>(item, changes.NewStartingIndex, changes.OldStartingIndex);
                            return new[] { change };
                        }

                    default:
                        return null;
                    }
                })
                                    .Where(updates => updates != null)
                                    .Select(updates => (IChangeSet <T>) new ChangeSet <T>(updates));

                var initialChanges = initialChangeSet();
                var cacheLoader = Observable.Return(initialChanges).Concat(sourceUpdates).PopulateInto(cloneOfList);
                var subscriber = cloneOfList.Connect().SubscribeSafe(observer);
                return new CompositeDisposable(cacheLoader, subscriber, cloneOfList);
            }));
        }
コード例 #38
0
 protected override void ApplyAction(ReactiveList <ChemicalIndicatorValue> editObject)
 {
     editObject.DoForEach(item => item.CertificateQuality = item.CertificateQuality ?? _certificateQuality);
 }
コード例 #39
0
        private void AddNote()
        {
            var addNoteViewModel = new AddEditNoteViewModel
            {
                IsGroupPossible = SelectedStage is StageObject
            };

            addNoteViewModel.OnSaveAction = () =>
            {
                ReactiveList <NoteObject> noteList = null;

                if (SelectedStage is StageObject)
                {
                    if (addNoteViewModel.IsGroup)
                    {
                        var group = new InnerGroupObject
                        {
                            Name       = addNoteViewModel.Name,
                            IsSelected = true
                        };

                        (SelectedStage as StageObject).InnerGroups.Add(group);
                        SaveNote();
                        return;
                    }

                    noteList = (SelectedStage as StageObject).Notes;
                }
                else if (SelectedStage is InnerGroupObject)
                {
                    noteList = (SelectedStage as InnerGroupObject).Notes;
                }
                else
                {
                    foreach (var stage in stages)
                    {
                        if (stage.Notes.Contains(SelectedStage))
                        {
                            noteList = stage.Notes;
                            break;
                        }

                        foreach (var group in stage.InnerGroups)
                        {
                            if (group.Notes.Contains(SelectedStage))
                            {
                                noteList = group.Notes;
                                break;
                            }
                        }
                    }
                }

                if (noteList == null)
                {
                    return;
                }

                var note = new NoteObject
                {
                    ID = ObjectsHelper.GetNextID(NoteService.CurrentNotesAppSettings.AllNotes),
                    ParentStageType = NoteStageType,
                    Name            = addNoteViewModel.Name,
                    DisplayedNote   = addNoteViewModel.Name,
                    IsSelected      = true
                };

                note.TrackChanges(true);

                noteList.Add(note);

                SaveNote();
            };

            var popupEventArgs = new RaisePopupEventArgs()
            {
                Title   = CommonResourceManager.Instance.GetResourceString("XRay_AddEditNoteView_AddTitle"),
                Content = new AddEditNoteView(addNoteViewModel)
            };

            eventAggregator.GetEvent <RaisePopupEvent>().Publish(popupEventArgs);
        }
コード例 #40
0
        /// <summary>
        /// Clones the ReactiveList from all changes
        /// </summary>
        /// <typeparam name="TObject">The type of the object.</typeparam>
        /// <typeparam name="TKey">The type of the key.</typeparam>
        /// <param name="source">The source.</param>
        /// <param name="keySelector">The key selector.</param>
        /// <returns></returns>
        /// <exception cref="System.ArgumentNullException">source
        /// or
        /// keySelector</exception>
        public static IObservable <IChangeSet <TObject, TKey> > ToObservableChangeSet <TObject, TKey>(this  ReactiveList <TObject> source, Func <TObject, TKey> keySelector)
        {
            if (source == null)
            {
                throw new ArgumentNullException(nameof(source));
            }
            if (keySelector == null)
            {
                throw new ArgumentNullException(nameof(keySelector));
            }

            return(Observable.Create <IChangeSet <TObject, TKey> >
                   (
                       observer =>
            {
                //populate local cache, otherwise there is no way to deal with a reset
                var resultCache = new SourceCache <TObject, TKey>(keySelector);

                Func <ChangeSet <TObject, TKey> > initialChangeSet = () =>
                {
                    var items = source.Select(t => new Change <TObject, TKey>(ChangeReason.Add, keySelector(t), t));
                    return new ChangeSet <TObject, TKey>(items);
                };

                var sourceUpdates = Observable
                                    .FromEventPattern <NotifyCollectionChangedEventHandler, NotifyCollectionChangedEventArgs>(
                    h => source.CollectionChanged += h,
                    h => source.CollectionChanged -= h)
                                    .Select
                                    (
                    args =>
                {
                    var changes = args.EventArgs;

                    switch (changes.Action)
                    {
                    case NotifyCollectionChangedAction.Add:
                        return changes.NewItems.OfType <TObject>()
                        .Select(t => new Change <TObject, TKey>(ChangeReason.Add, keySelector(t), t));

                    case NotifyCollectionChangedAction.Remove:
                        return changes.OldItems.OfType <TObject>()
                        .Select(t => new Change <TObject, TKey>(ChangeReason.Remove, keySelector(t), t));

                    case NotifyCollectionChangedAction.Replace:
                        {
                            return changes.NewItems.OfType <TObject>()
                            .Select((t, idx) =>
                            {
                                var old = changes.OldItems[idx];
                                return new Change <TObject, TKey>(ChangeReason.Update, keySelector(t), t, (TObject)old);
                            });
                        }

                    case NotifyCollectionChangedAction.Reset:
                        {
                            //Clear all from the cache and reload
                            var removes = resultCache.KeyValues.Select(t => new Change <TObject, TKey>(ChangeReason.Remove, t.Key, t.Value)).ToArray();
                            return removes.Concat(initialChangeSet());
                        }

                    default:
                        return null;
                    }
                })
                                    .Where(updates => updates != null)
                                    .Select(updates => (IChangeSet <TObject, TKey>) new ChangeSet <TObject, TKey>(updates));


                var initialChanges = initialChangeSet();
                var cacheLoader = Observable.Return(initialChanges).Concat(sourceUpdates).PopulateInto(resultCache);
                var subscriber = resultCache.Connect().SubscribeSafe(observer);

                return new CompositeDisposable(cacheLoader, subscriber, resultCache);
            }

                   ));
        }
コード例 #41
0
        /// <summary>
        /// Initializes a new instance of the <see cref="SearchSettingsViewModel"/> class.
        /// </summary>
        /// <param name="dialogService">Dialog service for opening dialogs from view model.</param>
        public SearchSettingsViewModel(IMainDialogService dialogService)
        {
            this.dialogService = dialogService;
            SearchModes        = new[] { InternalCleavageType.MultipleInternalCleavages, InternalCleavageType.SingleInternalCleavage, InternalCleavageType.NoInternalCleavage };
            ToleranceUnits     = new[] { ToleranceUnit.Ppm, ToleranceUnit.Mz };
            SelectedSequence   = string.Empty;
            FastaEntries       = new ReactiveList <FastaEntry>();
            SequenceProteins   = new FastaEntry[0];

            SearchRunning = false;

            FromFastaEntry = true;
            FromSequence   = false;

            // Browse Spectrum Files Command
            BrowseSpectrumFilesCommand = ReactiveCommand.Create(BrowseSpectrumFilesImplementation);

            // Browse Feature Files Command
            BrowseFeatureFilesCommand = ReactiveCommand.Create(BrowseFeatureFilesImplementation);

            // Browse Fasta DB Files Command
            BrowseFastaDbFilesCommand = ReactiveCommand.Create(BrowseFastaDbFilesImplementation);

            // Browse Output Directories Command
            BrowseOutputDirectoriesCommand = ReactiveCommand.Create(BrowseOutputDirectoriesImplementation);

            // Select All Proteins Command
            SelectAllProteinsCommand = ReactiveCommand.Create(() => SelectProteinsImplementation(true), FastaEntries.WhenAnyValue(x => x.Count).Select(count => count > 0));

            // Select No Proteins Command
            SelectNoProteinsCommand = ReactiveCommand.Create(() => SelectProteinsImplementation(false), FastaEntries.WhenAnyValue(x => x.Count).Select(count => count > 0));

            // Manage Modifications Command
            ManageModificationsCommand = ReactiveCommand.Create(ManageModificationsImplementation);

            // Add Modifications Command
            AddModificationCommand = ReactiveCommand.Create(AddModificationImplementation);

            // Run Command - Disabled when there is no SpectrumFilePath, FastaDbFilePath, or OutputFilePath selected
            RunCommand = ReactiveCommand.CreateFromTask(async _ => await RunImplementation(),
                                                        this.WhenAnyValue(
                                                            x => x.SpectrumFilePath,
                                                            x => x.FastaDbFilePath,
                                                            x => x.OutputFilePath)
                                                        .Select(x => !string.IsNullOrWhiteSpace(x.Item1) &&
                                                                !string.IsNullOrWhiteSpace(x.Item2) &&
                                                                !string.IsNullOrWhiteSpace(x.Item3))
                                                        );

            // Prev tab command
            PrevTabCommand = ReactiveCommand.Create(() => TabIndex--,
                                                    Observable.Merge(
                                                        new[]
            {
                this.WhenAnyValue(x => x.TabIndex).Select(tabIndex => tabIndex > 0),
                RunCommand.IsExecuting.Select(exec => !exec)
            }));

            // Next tab command
            NextTabCommand = ReactiveCommand.Create(() => TabIndex++,
                                                    Observable.Merge(
                                                        new[]
            {
                this.WhenAnyValue(x => x.TabIndex).Select(tabIndex => tabIndex < MaxTabIndex),
                RunCommand.IsExecuting.Select(exec => !exec)
            }));

            // Cancel Command
            CancelCommand = ReactiveCommand.Create(CancelImplementation);

            // Default values
            SelectedSearchMode         = InternalCleavageType.SingleInternalCleavage;
            MinSequenceLength          = 21;
            MaxSequenceLength          = 300;
            MinPrecursorIonCharge      = 2;
            MaxPrecursorIonCharge      = 30;
            MinProductIonCharge        = 1;
            MaxProductIonCharge        = 15;
            MinSequenceMass            = 3000.0;
            MaxSequenceMass            = 50000.0;
            PrecursorIonToleranceValue = 10;
            PrecursorIonToleranceUnit  = ToleranceUnit.Ppm;
            ProductIonToleranceValue   = 10;
            PrecursorIonToleranceUnit  = ToleranceUnit.Ppm;
            minScanNumber = 0;
            maxScanNumber = 0;
            maxDynamicModificationsPerSequence = 0;
            FixedNTerm            = true;
            FixedCTerm            = true;
            NumMatchesPerSpectrum = 1;

            // When search mode is selected, display correct search mode description
            this.WhenAnyValue(x => x.SelectedSearchMode)
            .Subscribe(searchMode => SearchModeDescription = searchModeDescriptions[(int)searchMode]);

            // When Spectrum file path is selected, use its directory for the output path by default if a output path
            // has not already been selected.
            this.WhenAnyValue(x => x.SpectrumFilePath)
            .Where(_ => string.IsNullOrWhiteSpace(OutputFilePath))
            .Select(Path.GetDirectoryName)
            .Subscribe(specDir => OutputFilePath = specDir);

            SearchModifications = new ReactiveList <SearchModificationViewModel> {
                ChangeTrackingEnabled = true
            };

            this.WhenAnyValue(x => x.FastaDbFilePath).Subscribe(_ => LoadFastaFile());

            this.WhenAnyValue(x => x.FastaEntries.Count, x => x.SelectedSequence)
            .Select(x => FastaEntries.Where(entry => entry.ProteinSequenceText.Contains(x.Item2)).ToArray())
            .Subscribe(entries => SequenceProteins = entries);

            // Remove search modification when its Remove property is set to true.
            SearchModifications.ItemChanged.Where(x => x.PropertyName == "Remove")
            .Select(x => x.Sender).Where(sender => sender.Remove)
            .Subscribe(searchMod => SearchModifications.Remove(searchMod));

            ModificationsUpdated = false;
        }
コード例 #42
0
        private void InitializeHoleCardsCollection()
        {
            HoleCardsCollection = new ReactiveList <HoleCardsViewModel>();

            var rankValues = HandHistories.Objects.Cards.Card.PossibleRanksHighCardFirst;

            for (int i = 0; i < rankValues.Length; i++)
            {
                var startS = false;

                for (int j = 0; j < rankValues.Length; j++)
                {
                    var card1 = i < j?rankValues.ElementAt(i) : rankValues.ElementAt(j);

                    var card2 = i < j?rankValues.ElementAt(j) : rankValues.ElementAt(i);

                    if (startS)
                    {
                        HoleCardsCollection.Add(new HoleCardsViewModel
                        {
                            Name      = $"{card1}{card2}s",
                            ItemType  = RangeSelectorItemType.Suited,
                            IsChecked = true
                        });
                    }
                    else
                    {
                        if (!card1.Equals(card2))
                        {
                            HoleCardsCollection.Add(new HoleCardsViewModel
                            {
                                Name      = $"{card1}{card2}o",
                                ItemType  = RangeSelectorItemType.OffSuited,
                                IsChecked = true
                            });
                        }
                        else
                        {
                            HoleCardsCollection.Add(new HoleCardsViewModel
                            {
                                Name      = $"{card1}{card2}",
                                ItemType  = RangeSelectorItemType.Pair,
                                IsChecked = true
                            });

                            startS = true;
                        }
                    }
                }
            }

            HoleCardsCollection.ChangeTrackingEnabled = true;
            HoleCardsCollection.ItemChanged
            .Where(x => x.PropertyName == nameof(HoleCardsViewModel.IsChecked))
            .Select(x => x.Sender)
            .Subscribe(x =>
            {
                if (SelectedNote != null && SelectedNote.Settings != null)
                {
                    var excludedCardsList = SelectedNote.Settings.ExcludedCardsList;

                    if (!x.IsChecked && !excludedCardsList.Contains(x.Name))
                    {
                        excludedCardsList.Add(x.Name);
                        SelectedNote.Settings.ExcludedCardsList = excludedCardsList;
                    }
                    else if (x.IsChecked && excludedCardsList.Contains(x.Name))
                    {
                        excludedCardsList.Remove(x.Name);
                        SelectedNote.Settings.ExcludedCardsList = excludedCardsList;
                    }
                }
            });
        }
コード例 #43
0
        partial void InitializeAutoCombat()
        {
            var game = Locator.Current.GetService <GameModel>();

            SearchBehavior = AutoCombatSearchBehavior.SearchAndDestroy;
            NearbyMonsters = new ReactiveList <string>();
            TargetList     = new ReactiveList <string>();
            TargetList.CountChanged.Subscribe(_ => TargetList.Sort());

            var canRefreshNearbyMonsters = game.WhenAnyValue(x => x.Status, x => x == GameStatus.LoggedIn);

            RefreshNearbyMonsters = ReactiveCommand.CreateAsyncTask(canRefreshNearbyMonsters, async _ =>
            {
                var names = await Task.Run(() =>
                {
                    return(new NpcContainer(game.Game).GetItems()
                           .Where(x => x.NpcType.Value == NpcType.Monster)
                           .Select(x => x.Name.Value.Value)
                           .Distinct());
                });

                return(names);
            });
            RefreshNearbyMonsters.Subscribe(results =>
            {
                NearbyMonsters.Clear();
                foreach (var item in results)
                {
                    NearbyMonsters.Add(item);
                }
            });

            AddTarget = ReactiveCommand.Create();
            AddTarget.Subscribe(x =>
            {
                var name = (string)x;

                if (!TargetList.Contains(name))
                {
                    TargetList.Add(name);
                }
            });

            var canClearTargetList = TargetList.CountChanged.Select(x => x != 0);

            ClearTargetList = ReactiveCommand.Create(canClearTargetList);
            ClearTargetList.Subscribe(_ => TargetList.Clear());

            RemoveTarget = ReactiveCommand.Create();
            RemoveTarget.Subscribe(name => TargetList.Remove((string)name));

#pragma warning disable CS1998 // Async method lacks 'await' operators and will run synchronously
            var dialogService       = Locator.Current.GetService <IDialogService>();
            var canExportTargetList = TargetList.CountChanged.Select(x => x != 0);
            ExportTargetList = ReactiveCommand.CreateAsyncTask(canExportTargetList, async _ =>
            {
                var dialog = new SaveFileDialog()
                {
                    Filter = TargetListFileFormat
                };
                if (dialog.ShowDialog() == false)
                {
                    return;
                }

                var serializer = new XmlSerializer(typeof(List <string>));
                using (var stream = dialog.OpenFile())
                    serializer.Serialize(stream, TargetList.ToList());
            });
            ExportTargetList.ThrownExceptions.Subscribe(async e => await dialogService.DisplayExceptionAsyncOn <SettingViewModel>(e));

            ImportTargetList = ReactiveCommand.CreateAsyncTask(async _ =>
            {
                var dialog = new OpenFileDialog()
                {
                    Filter = TargetListFileFormat
                };
                if (dialog.ShowDialog() == false)
                {
                    return;
                }

                if (TargetList.Any())
                {
                    var result = await dialogService.ShowMessageDialogAsyncOn <SettingViewModel>("Confirmation",
                                                                                                 "Do you wish to merge the current list with this list?",
                                                                                                 "Merge them",
                                                                                                 "Keep new list",
                                                                                                 "Cancel, keep current list");
                    switch (result)
                    {
                    case DialogResult.Affirmative:
                        break;

                    case DialogResult.Negative:
                        TargetList.Clear();
                        break;

                    case DialogResult.FirstAuxiliary:
                        return;
                    }
                }

                var serializer = new XmlSerializer(typeof(List <string>));
                using (var stream = dialog.OpenFile())
                {
                    var list = serializer.Deserialize(stream) as List <string>;
                    foreach (var item in list)
                    {
                        if (!TargetList.Contains(item))
                        {
                            TargetList.Add(item);
                        }
                    }
                }
            });
            ImportTargetList.ThrownExceptions.Subscribe(async e => await dialogService.DisplayExceptionAsyncOn <SettingViewModel>(e));
#pragma warning restore CS1998 // Async method lacks 'await' operators and will run synchronously
        }
コード例 #44
0
        public NotificationsViewModel(ISessionService applicationService)
        {
            _applicationService = applicationService;
            Title = "Notifications";

            ReadSelectedCommand = ReactiveCommand.Create().WithSubscription(_ =>
            {
                if (GroupedNotifications.SelectMany(x => x.Notifications).All(x => !x.IsSelected))
                {
                    var request = new Octokit.MarkAsReadRequest {
                        LastReadAt = DateTimeOffset.Now
                    };
                    applicationService.GitHubClient.Notification.MarkAsRead(request).ToBackground();
                    _notifications.Clear();
                }
                else
                {
                    var selected = GroupedNotifications.SelectMany(x => x.Notifications)
                                   .Where(x => x.IsSelected && x.Notification.Unread).ToList();

                    var tasks = selected
                                .Select(t => _applicationService.GitHubClient.Notification.MarkAsRead(int.Parse(t.Id)));

                    Task.WhenAll(tasks).ToBackground();

                    _notifications.RemoveAll(selected.Select(y => y.Notification));
                }
            });

            _notifications.Changed.Select(_ => Unit.Default)
            .Merge(_notifications.ItemChanged.Select(_ => Unit.Default))
            .Subscribe(_ =>
            {
                GroupedNotifications = _notifications.GroupBy(x => x.Repository.FullName).Select(x =>
                {
                    var items         = x.Select(y => new NotificationItemViewModel(y, GoToNotification));
                    var notifications = new ReactiveList <NotificationItemViewModel>(items);
                    return(new NotificationGroupViewModel(x.Key, notifications));
                }).ToList();
            });


            LoadCommand = ReactiveCommand.CreateAsyncTask(async _ => {
                var all           = ActiveFilter == AllFilter;
                var participating = ActiveFilter == ParticipatingFilter;
                var req           = new Octokit.NotificationsRequest {
                    All = all, Participating = participating, Since = DateTimeOffset.Now.Subtract(TimeSpan.FromDays(365))
                };
                var notifications = await applicationService.GitHubClient.Notification.GetAllForCurrent(req);
                _notifications.Reset(notifications);
            });

            _notifications.CountChanged
            .Where(_ => ActiveFilter == UnreadFilter)
            .Subscribe(_notificationCount.OnNext);

            this.WhenAnyValue(x => x.ActiveFilter).Skip(1).Subscribe(x =>
            {
                _notifications.Clear();
                LoadCommand.ExecuteIfCan();
            });
        }
コード例 #45
0
 public void Teardown()
 {
     _reactiveList = null;
 }
コード例 #46
0
 public AnnotationsModel()
 {
     Annotations = new ReactiveList <Annotation>();
 }
コード例 #47
0
 protected void SourceLinesChangedSubscriptionRegister(IScheduler scheduler, ReactiveList <SourceCodeLine> sourceLines)
 {
     _sourceLinesChangedSubscription = sourceLines.Changed.Subscribe(OnSourceLinesChanged, OnSourceLinesChangedError);
 }
コード例 #48
0
ファイル: LocalViewModel.cs プロジェクト: umfaruki/Espera
        public LocalViewModel(Library library, ViewSettings viewSettings, CoreSettings coreSettings, Guid accessToken)
            : base(library, coreSettings, accessToken)
        {
            if (viewSettings == null)
            {
                Throw.ArgumentNullException(() => viewSettings);
            }

            this.viewSettings = viewSettings;

            this.artistUpdateSignal = new Subject <Unit>();

            this.allArtistsViewModel = new ArtistViewModel("All Artists");
            this.allArtists          = new ReactiveList <ArtistViewModel> {
                this.allArtistsViewModel
            };

            this.Artists = this.allArtists.CreateDerivedCollection(x => x,
                                                                   x => x.IsAllArtists || this.filteredSongs.Contains(x.Name), (x, y) => x.CompareTo(y), this.artistUpdateSignal);

            // We need a default sorting order
            this.ApplyOrder(SortHelpers.GetOrderByArtist <LocalSongViewModel>, ref this.artistOrder);

            this.SelectedArtist = this.allArtistsViewModel;

            var gate = new object();

            this.Library.SongsUpdated
            .Buffer(TimeSpan.FromSeconds(1), RxApp.TaskpoolScheduler)
            .Where(x => x.Any())
            .Select(_ => Unit.Default)
            .Merge(this.WhenAny(x => x.SearchText, _ => Unit.Default)
                   .Do(_ => this.SelectedArtist = this.allArtistsViewModel))
            .Synchronize(gate)
            .ObserveOn(RxApp.MainThreadScheduler)
            .Subscribe(_ =>
            {
                this.UpdateSelectableSongs();
                this.UpdateArtists();
            });

            this.WhenAnyValue(x => x.SelectedArtist)
            .Skip(1)
            .Synchronize(gate)
            .Subscribe(_ => this.UpdateSelectableSongs());

            this.playNowCommand = ReactiveCommand.CreateAsyncTask(this.Library.LocalAccessControl.ObserveAccessPermission(accessToken)
                                                                  .Select(x => x == AccessPermission.Admin || !coreSettings.LockPlayPause), _ =>
            {
                int songIndex = this.SelectableSongs.TakeWhile(x => x.Model != this.SelectedSongs.First().Model).Count();

                return(this.Library.PlayInstantlyAsync(this.SelectableSongs.Skip(songIndex).Select(x => x.Model), accessToken));
            });

            this.showAddSongsHelperMessage = this.Library.SongsUpdated
                                             .StartWith(Unit.Default)
                                             .Select(_ => this.Library.Songs.Count == 0)
                                             .TakeWhile(x => x)
                                             .Concat(Observable.Return(false))
                                             .ToProperty(this, x => x.ShowAddSongsHelperMessage);

            this.isUpdating = this.Library.WhenAnyValue(x => x.IsUpdating)
                              .ToProperty(this, x => x.IsUpdating);

            this.OpenTagEditor = ReactiveCommand.Create(this.WhenAnyValue(x => x.SelectedSongs, x => x.Any()));
        }
コード例 #49
0
 protected LibrarySetup()
 {
     Items = new ReactiveList <IHierarchicalLibraryItem>();
 }
コード例 #50
0
 public void Setup()
 {
     _reactiveList = new ReactiveList<string>();
 }
コード例 #51
0
        public RepositoryPublishViewModel(
            IRepositoryHosts hosts,
            IRepositoryPublishService repositoryPublishService,
            IVSServices vsServices,
            IConnectionManager connectionManager)
        {
            this.vsServices = vsServices;
            this.hosts      = hosts;

            title = this.WhenAny(
                x => x.SelectedHost,
                x => x.Value != null ?
                string.Format(CultureInfo.CurrentCulture, Resources.PublishToTitle, x.Value.Title) :
                Resources.PublishTitle
                )
                    .ToProperty(this, x => x.Title);

            Connections = new ReactiveList <IConnection>(connectionManager.Connections);
            this.repositoryPublishService = repositoryPublishService;

            if (Connections.Any())
            {
                SelectedConnection = Connections.FirstOrDefault(x => x.HostAddress.IsGitHubDotCom()) ?? Connections[0];
            }

            accounts = this.WhenAny(x => x.SelectedConnection, x => x.Value != null ? hosts.LookupHost(x.Value.HostAddress) : RepositoryHosts.DisconnectedRepositoryHost)
                       .Where(x => !(x is DisconnectedRepositoryHost))
                       .SelectMany(host => host.ModelService.GetAccounts())
                       .ObserveOn(RxApp.MainThreadScheduler)
                       .ToProperty(this, x => x.Accounts, initialValue: new ReadOnlyCollection <IAccount>(new IAccount[] {}));

            this.WhenAny(x => x.Accounts, x => x.Value)
            .WhereNotNull()
            .Where(accts => accts.Any())
            .Subscribe(accts => {
                var selectedAccount = accts.FirstOrDefault();
                if (selectedAccount != null)
                {
                    SelectedAccount = accts.FirstOrDefault();
                }
            });

            isHostComboBoxVisible = this.WhenAny(x => x.Connections, x => x.Value)
                                    .WhereNotNull()
                                    .Select(h => h.Count > 1)
                                    .ToProperty(this, x => x.IsHostComboBoxVisible);

            InitializeValidation();

            PublishRepository = InitializePublishRepositoryCommand();

            canKeepPrivate = CanKeepPrivateObservable.CombineLatest(PublishRepository.IsExecuting,
                                                                    (canKeep, publishing) => canKeep && !publishing)
                             .ToProperty(this, x => x.CanKeepPrivate);

            isPublishing = PublishRepository.IsExecuting
                           .ToProperty(this, x => x.IsPublishing);

            var defaultRepositoryName = repositoryPublishService.LocalRepositoryName;

            if (!string.IsNullOrEmpty(defaultRepositoryName))
            {
                DefaultRepositoryName = defaultRepositoryName;
            }

            this.WhenAny(x => x.SelectedConnection, x => x.SelectedAccount,
                         (a, b) => true)
            .Where(x => RepositoryNameValidator.ValidationResult != null && SafeRepositoryNameWarningValidator.ValidationResult != null)
            .Subscribe(async _ =>
            {
                var name       = RepositoryName;
                RepositoryName = null;
                await RepositoryNameValidator.ResetAsync();
                await SafeRepositoryNameWarningValidator.ResetAsync();
                RepositoryName = name;
            });
        }
コード例 #52
0
 public AbstractLexer(IScheduler scheduler, IParser parser, IGrammarContainer grammarContainer, ReactiveList <SourceCodeLine> sourceLines, ILexerOptions lexerOptions)
 {
     _parser = parser;
     CheckNextTokenSubscriptionRegister(scheduler, parser);
     GrammarChangeIdentifiedSubscriptionRegister(scheduler, parser);
     _grammarContainer = grammarContainer;
     _sourceLines      = sourceLines;
     SourceLinesChangedSubscriptionRegister(scheduler, sourceLines);
     _lexerOptions = lexerOptions;
     OptionsChangedSubscriptionRegister(scheduler, lexerOptions);
     _parser.RegisterLexer(scheduler, this);
 }
コード例 #53
0
        public IssueViewModel(IApplicationService applicationService, IShareService shareService)
        {
            _applicationService = applicationService;
            Comments            = new ReactiveList <IssueCommentModel>();
            Events = new ReactiveList <IssueEventModel>();
            var issuePresenceObservable = this.WhenAnyValue(x => x.Issue).Select(x => x != null);

            ShareCommand = ReactiveCommand.Create(this.WhenAnyValue(x => x.Issue, x => x != null && !string.IsNullOrEmpty(x.HtmlUrl)));
            ShareCommand.Subscribe(_ => shareService.ShareUrl(Issue.HtmlUrl));

            AddCommentCommand = ReactiveCommand.Create();
            AddCommentCommand.Subscribe(_ =>
            {
                var vm = CreateViewModel <CommentViewModel>();
                ReactiveUI.Legacy.ReactiveCommandMixins.RegisterAsyncTask(vm.SaveCommand, async t =>
                {
                    var issue   = _applicationService.Client.Users[RepositoryOwner].Repositories[RepositoryName].Issues[IssueId];
                    var comment = await _applicationService.Client.ExecuteAsync(issue.CreateComment(vm.Comment));
                    Comments.Add(comment.Data);
                    vm.DismissCommand.ExecuteIfCan();
                });
                ShowViewModel(vm);
            });

            ToggleStateCommand = ReactiveCommand.CreateAsyncTask(issuePresenceObservable, async t =>
            {
                var close = string.Equals(Issue.State, "open", StringComparison.OrdinalIgnoreCase);
                try
                {
                    var issue = _applicationService.Client.Users[RepositoryOwner].Repositories[RepositoryName].Issues[Issue.Number];
                    var data  = await _applicationService.Client.ExecuteAsync(issue.UpdateState(close ? "closed" : "open"));
                    Issue     = data.Data;
                }
                catch (Exception e)
                {
                    throw new Exception("Unable to " + (close ? "close" : "open") + " the item. " + e.Message, e);
                }
            });

            GoToEditCommand = ReactiveCommand.Create(issuePresenceObservable);
            GoToEditCommand.Subscribe(_ =>
            {
                var vm             = CreateViewModel <IssueEditViewModel>();
                vm.RepositoryOwner = RepositoryOwner;
                vm.RepositoryName  = RepositoryName;
                vm.Id    = IssueId;
                vm.Issue = Issue;
                vm.WhenAnyValue(x => x.Issue).Skip(1).Subscribe(x => Issue = x);
                ShowViewModel(vm);
            });

            GoToAssigneeCommand = ReactiveCommand.Create(issuePresenceObservable);
            GoToAssigneeCommand.Subscribe(_ =>
            {
                var vm             = CreateViewModel <IssueAssignedToViewModel>();
                vm.SaveOnSelect    = true;
                vm.RepositoryOwner = RepositoryOwner;
                vm.RepositoryName  = RepositoryName;
                vm.IssueId         = IssueId;
                vm.SelectedUser    = Issue.Assignee;
                vm.WhenAnyValue(x => x.SelectedUser).Subscribe(x =>
                {
                    Issue.Assignee = x;
                    this.RaisePropertyChanged("Issue");
                });
                ShowViewModel(vm);
            });

            GoToLabelsCommand = ReactiveCommand.Create(issuePresenceObservable);
            GoToLabelsCommand.Subscribe(_ =>
            {
                var vm             = CreateViewModel <IssueLabelsViewModel>();
                vm.SaveOnSelect    = true;
                vm.RepositoryOwner = RepositoryOwner;
                vm.RepositoryName  = RepositoryName;
                vm.IssueId         = IssueId;
                vm.SelectedLabels.Reset(Issue.Labels);
                vm.WhenAnyValue(x => x.SelectedLabels).Subscribe(x =>
                {
                    Issue.Labels = x.ToList();
                    this.RaisePropertyChanged("Issue");
                });
                ShowViewModel(vm);
            });

            GoToMilestoneCommand = ReactiveCommand.Create(issuePresenceObservable);
            GoToMilestoneCommand.Subscribe(_ =>
            {
                var vm               = CreateViewModel <IssueMilestonesViewModel>();
                vm.SaveOnSelect      = true;
                vm.RepositoryOwner   = RepositoryOwner;
                vm.RepositoryName    = RepositoryName;
                vm.IssueId           = IssueId;
                vm.SelectedMilestone = Issue.Milestone;
                vm.WhenAnyValue(x => x.SelectedMilestone).Subscribe(x =>
                {
                    Issue.Milestone = x;
                    this.RaisePropertyChanged("Issue");
                });
                ShowViewModel(vm);
            });

            LoadCommand = ReactiveCommand.CreateAsyncTask(t =>
            {
                var forceCacheInvalidation = t as bool?;
                var issue = _applicationService.Client.Users[RepositoryOwner].Repositories[RepositoryName].Issues[IssueId];
                var t1    = this.RequestModel(issue.Get(), forceCacheInvalidation, response => Issue = response.Data);
                Comments.SimpleCollectionLoad(issue.GetComments(), forceCacheInvalidation).FireAndForget();
                Events.SimpleCollectionLoad(issue.GetEvents(), forceCacheInvalidation).FireAndForget();
                return(t1);
            });
        }
コード例 #54
0
        public PullRequestViewModel(IApplicationService applicationService, IMarkdownService markdownService, IShareService shareService)
        {
            _applicationService = applicationService;
            _markdownService    = markdownService;

            Comments = new ReactiveList <IssueCommentModel>();
            Events   = new ReactiveList <IssueEventModel>();

            MergeCommand = ReactiveCommand.CreateAsyncTask(
                this.WhenAnyValue(x => x.PullRequest).Select(x =>
                                                             x != null && x.Merged.HasValue && !x.Merged.Value && x.Mergable.HasValue && x.Mergable.Value),
                async t =>
            {
                try
                {
                    var response = await _applicationService.Client.ExecuteAsync(_applicationService.Client.Users[RepositoryOwner]
                                                                                 .Repositories[RepositoryName].PullRequests[PullRequestId].Merge());
                    if (!response.Data.Merged)
                    {
                        throw new Exception(response.Data.Message);
                    }
                    var pullRequest = _applicationService.Client.Users[RepositoryOwner].Repositories[RepositoryName].PullRequests[PullRequestId].Get();
                    await this.RequestModel(pullRequest, true, r => PullRequest = r.Data);
                }
                catch (Exception e)
                {
                    throw new Exception("Unable to Merge: " + e.Message, e);
                }
            });

            ToggleStateCommand = ReactiveCommand.CreateAsyncTask(
                this.WhenAnyValue(x => x.PullRequest).Select(x => x != null), async t =>
            {
                var close = string.Equals(PullRequest.State, "open", StringComparison.OrdinalIgnoreCase);

                try
                {
                    var data = await _applicationService.Client.ExecuteAsync(
                        _applicationService.Client.Users[RepositoryOwner].Repositories[RepositoryName].PullRequests[PullRequestId].UpdateState(close ? "closed" : "open"));
                    PullRequest = data.Data;
                }
                catch (Exception e)
                {
                    throw new Exception("Unable to " + (close ? "close" : "open") + " the item. " + e.Message, e);
                }
            });

            GoToCommitsCommand = ReactiveCommand.Create().WithSubscription(_ =>
            {
                var vm             = CreateViewModel <PullRequestCommitsViewModel>();
                vm.RepositoryOwner = RepositoryOwner;
                vm.RepositoryName  = RepositoryName;
                vm.PullRequestId   = PullRequestId;
                ShowViewModel(vm);
            });

            GoToFilesCommand = ReactiveCommand.Create().WithSubscription(_ =>
            {
                var vm           = CreateViewModel <PullRequestFilesViewModel>();
                vm.Username      = RepositoryOwner;
                vm.Repository    = RepositoryName;
                vm.PullRequestId = PullRequestId;
                ShowViewModel(vm);
            });

            ShareCommand = ReactiveCommand.Create(this.WhenAnyValue(x => x.PullRequest).Select(x => x != null && !string.IsNullOrEmpty(x.HtmlUrl)))
                           .WithSubscription(_ => shareService.ShareUrl(PullRequest.HtmlUrl));

            GoToEditCommand = ReactiveCommand.Create().WithSubscription(_ =>
            {
                var vm             = CreateViewModel <IssueEditViewModel>();
                vm.RepositoryOwner = RepositoryOwner;
                vm.RepositoryName  = RepositoryName;
                vm.Id    = PullRequestId;
                vm.Issue = Issue;
                vm.WhenAnyValue(x => x.Issue).Skip(1).Subscribe(x => Issue = x);
                ShowViewModel(vm);
            });

            GoToLabelsCommand = ReactiveCommand.Create(this.WhenAnyValue(x => x.Issue).Select(x => x != null)).WithSubscription(_ =>
            {
                var vm             = CreateViewModel <IssueLabelsViewModel>();
                vm.RepositoryOwner = RepositoryOwner;
                vm.RepositoryName  = RepositoryName;
                vm.IssueId         = PullRequestId;
                vm.SaveOnSelect    = true;
                vm.SelectedLabels.Reset(Issue.Labels);
//                vm.WhenAnyValue(x => x.Labels).Skip(1).Subscribe(x =>
//                {
//                    Issue.Labels = x.ToList();
//                    this.RaisePropertyChanged("Issue");
//                });
                ShowViewModel(vm);
            });

            GoToMilestoneCommand = ReactiveCommand.Create(this.WhenAnyValue(x => x.Issue).Select(x => x != null)).WithSubscription(_ =>
            {
                var vm               = CreateViewModel <IssueMilestonesViewModel>();
                vm.RepositoryOwner   = RepositoryOwner;
                vm.RepositoryName    = RepositoryName;
                vm.IssueId           = PullRequestId;
                vm.SaveOnSelect      = true;
                vm.SelectedMilestone = Issue.Milestone;
                vm.WhenAnyValue(x => x.SelectedMilestone).Skip(1).Subscribe(x =>
                {
                    Issue.Milestone = x;
                    this.RaisePropertyChanged("Issue");
                });
                ShowViewModel(vm);
            });

            GoToAssigneeCommand = ReactiveCommand.Create(this.WhenAnyValue(x => x.Issue).Select(x => x != null)).WithSubscription(_ =>
            {
                var vm             = CreateViewModel <IssueAssignedToViewModel>();
                vm.RepositoryOwner = RepositoryOwner;
                vm.RepositoryName  = RepositoryName;
                vm.IssueId         = PullRequestId;
                vm.SaveOnSelect    = true;
                vm.SelectedUser    = Issue.Assignee;
                vm.WhenAnyValue(x => x.SelectedUser).Skip(1).Subscribe(x =>
                {
                    Issue.Assignee = x;
                    this.RaisePropertyChanged("Issue");
                });
                ShowViewModel(vm);
            });

            GoToAddCommentCommand = ReactiveCommand.Create().WithSubscription(_ =>
            {
                var vm = CreateViewModel <CommentViewModel>();
                ReactiveUI.Legacy.ReactiveCommandMixins.RegisterAsyncTask(vm.SaveCommand, async t =>
                {
                    var req =
                        _applicationService.Client.Users[RepositoryOwner]
                        .Repositories[RepositoryName].Issues[PullRequestId].CreateComment(vm.Comment);
                    var comment = await _applicationService.Client.ExecuteAsync(req);
                    Comments.Add(comment.Data);
                    vm.DismissCommand.ExecuteIfCan();
                });
            });

            _markdownDescription = this.WhenAnyValue(x => x.PullRequest).IsNotNull()
                                   .Select(x => _markdownService.Convert(x.Body))
                                   .ToProperty(this, x => x.MarkdownDescription);

            LoadCommand = ReactiveCommand.CreateAsyncTask(t =>
            {
                var forceCacheInvalidation = t as bool?;
                var pullRequest            = _applicationService.Client.Users[RepositoryOwner].Repositories[RepositoryName].PullRequests[PullRequestId].Get();
                var t1 = this.RequestModel(pullRequest, forceCacheInvalidation, response => PullRequest = response.Data);
                Events.SimpleCollectionLoad(_applicationService.Client.Users[RepositoryOwner].Repositories[RepositoryName].Issues[PullRequestId].GetEvents(), forceCacheInvalidation).FireAndForget();
                Comments.SimpleCollectionLoad(_applicationService.Client.Users[RepositoryOwner].Repositories[RepositoryName].Issues[PullRequestId].GetComments(), forceCacheInvalidation).FireAndForget();
                this.RequestModel(_applicationService.Client.Users[RepositoryOwner].Repositories[RepositoryName].Issues[PullRequestId].Get(), forceCacheInvalidation, response => Issue = response.Data).FireAndForget();
                return(t1);
            });
        }
コード例 #55
0
 public MainPageViewModel()
 {
     Dates          = new ReactiveList <DateCellViewModel>();
     AddDateCommand = ReactiveCommand.Create(() => Dates.Add(new DateCellViewModel(DateTime.Today, cellViewModel => Dates.Remove(cellViewModel))));
 }
コード例 #56
0
 public ShellViewModel()
 {
     Genres  = new ReactiveList <Genre>(Data.Genres);
     Albums  = new ReactiveList <Album>(Data.Albums);
     Artists = new ReactiveList <Artist>(Data.Artists);
 }
コード例 #57
0
        public StrategyWidgetViewModel(DemoWorkspaceViewModel host, String cacheId = null) : base(host, cacheId)
        {
            var pricesObservable = PriceService.All
                                   .Connect()
                                   .ObserveOn(AppScheduler.MainThread)
                                   .Do(changes =>
            {
                changes.ForEach(change =>
                {
                    var pnl = 0.0;

                    for (var i = 0; i < Trades.Count; i++)
                    {
                        if (Trades[i].Trade.Asset == change.Current.Asset.Name)
                        {
                            Trades[i].PnL = Trades[i].Trade.Price - change.Current.Value;
                        }

                        pnl += Trades[i].PnL;
                    }

                    StrategyPnL = pnl;
                });
            })
                                   .DisposeMany()
                                   .Subscribe();

            Cleanup(pricesObservable);


            this.WhenAnyValue(vm => vm.Workspace)
            .Where(obj => null != obj)
            .Subscribe((obs) =>
            {
                Strategy = obs.State.Strategy;
            });

            this.WhenAnyValue(vm => vm.Strategy)
            .Where(obj => null != obj)
            .Subscribe((obs) =>
            {
                Trades = new ReactiveList <TradeViewModel>();

                var tradeObservable = _strategy.Trades
                                      .Connect()
                                      .Transform(trade => new TradeViewModel(trade))
                                      .Bind(_trades)
                                      .DisposeMany()
                                      .Subscribe();

                Cleanup(tradeObservable);
            });

            _tradesCount = this.WhenAnyObservable(vm => vm.Trades.CountChanged)
                           .ToProperty(this, vm => vm.TradesCount);

            this.WhenAnyObservable(vm => vm.Trades.CountChanged)
            .Select(change => Trades.Sum(trade => trade.Price + trade.PnL))
            .Subscribe(chg =>
            {
                MarketValue = chg;
            });


            this.WhenAny(vm => vm.TradesCount, vm => vm.StrategyPnL, (trd, pnl) => String.Format("Strategy viewer - {0} Trades - PnL [{1}] ", TradesCount, StrategyPnL))
            .Subscribe(header =>
            {
                Header = header;
            });
        }
コード例 #58
0
        public MindMapRoot(string title, IEnumerable <XElement> content)
        {
            Title = title;

            Content = new ReactiveList <XElement>(content);

            var subscription = Children.Changed.Subscribe(x =>
            {
                using (var leftSupression = LeftChildren.SuppressChangeNotifications())
                    using (var rightSupression = RightChildren.SuppressChangeNotifications())
                    {
                        LeftChildren.Clear();
                        RightChildren.Clear();

                        int halfway = Children.Count / 2;

                        for (int i = 0; i < Children.Count; i++)
                        {
                            var mindMapElement = Children[i];

                            if (i <= halfway)
                            {
                                RightChildren.Add(mindMapElement);
                            }
                            else
                            {
                                LeftChildren.Add(mindMapElement);
                            }
                        }
                    }
            });

            _subscriptions.Add(subscription);

            var hasSelectedItem = this.WhenAnyValue(x => x.SelectedElement).Select(x => x != null);

            AddChild    = ReactiveCommand.Create(DoAddChild);
            DeleteChild = ReactiveCommand.Create(DoDeleteChild, hasSelectedItem);

            var selectedElementDepth = this.WhenAnyValue(x => x.SelectedElement).Select(x => x?.Depth ?? -1);

            var canPromote = selectedElementDepth.Select(x => x > 1);

            PromoteSelectedElement = ReactiveCommand.Create(DoPromoteSelectedElement, canPromote);

            var canDemote = this.WhenAnyValue(x => x.SelectedElement).Select(x =>
            {
                if (x == null)
                {
                    return(false);
                }

                return(x.Index > 0 && x.Index < x.Parent.Children.Count - 1);
            });

            DemoteSelectedElement = ReactiveCommand.Create(DoDemoteSelectedElement, canDemote);

            var selectedElementIndex = this.WhenAnyValue(x => x.SelectedElement).Select(x => x?.Index ?? -1);

            var canMoveUp = selectedElementIndex.Select(x => x > 0);

            MoveUpSelectedElement = ReactiveCommand.Create(DoMoveUpSelectedElement, canMoveUp);

            var canMoveDown = selectedElementIndex.Select(x => x != -1 && SelectedElement.Parent.Children.Count > x);

            MoveDownSelectedElement = ReactiveCommand.Create(DoMoveDownSelectedElement, canMoveDown);
        }
コード例 #59
0
 /// <summary>
 /// Initializes a new instance of the <see cref="ObservableCacheToReactiveListAdaptor{TObject,TKey}"/> class.
 /// </summary>
 /// <param name="target">The target.</param>
 /// <param name="resetThreshold">The reset threshold.</param>
 /// <exception cref="System.ArgumentNullException">target</exception>
 public ObservableListToReactiveListAdaptor(ReactiveList <TObject> target, int resetThreshold = 50)
 {
     _target         = target ?? throw new ArgumentNullException(nameof(target));
     _resetThreshold = resetThreshold;
 }
コード例 #60
0
        /// <summary>
        /// Clones the ReactiveList from all changes
        /// </summary>
        /// <typeparam name="TObject">The type of the object.</typeparam>
        /// <typeparam name="TKey">The type of the key.</typeparam>
        /// <param name="source">The source.</param>
        /// <param name="keySelector">The key selector.</param>
        /// <returns></returns>
        /// <exception cref="System.ArgumentNullException">source
        /// or
        /// keySelector</exception>
        public static IObservable <IChangeSet <TObject, TKey> > ToObservableChangeSet <TObject, TKey>(this  ReactiveList <TObject> source, Func <TObject, TKey> keySelector)
        {
            if (source == null)
            {
                throw new ArgumentNullException(nameof(source));
            }
            if (keySelector == null)
            {
                throw new ArgumentNullException(nameof(keySelector));
            }

            return(source.ToObservableChangeSet <ReactiveList <TObject>, TObject>().AddKey(keySelector));
        }