public GistViewModel( ISessionService sessionService, IActionMenuFactory actionMenuService, IAlertDialogFactory alertDialogFactory) { Comments = new ReactiveList <GistCommentModel>(); Title = "Gist"; this.WhenAnyValue(x => x.Gist).Where(x => x != null && x.Files != null && x.Files.Count > 0) .Select(x => x.Files.First().Key).Subscribe(x => Title = x); ShareCommand = ReactiveCommand.Create(this.WhenAnyValue(x => x.Gist).Select(x => x != null)); ShareCommand.Subscribe(sender => actionMenuService.ShareUrl(sender, new Uri(Gist.HtmlUrl))); this.WhenAnyValue(x => x.Gist.Owner.AvatarUrl) .Select(x => new GitHubAvatar(x)) .ToProperty(this, x => x.Avatar, out _avatar); ToggleStarCommand = ReactiveCommand.CreateAsyncTask( this.WhenAnyValue(x => x.IsStarred).Select(x => x.HasValue), async t => { try { if (!IsStarred.HasValue) { return; } var request = IsStarred.Value ? sessionService.Client.Gists[Id].Unstar() : sessionService.Client.Gists[Id].Star(); await sessionService.Client.ExecuteAsync(request); IsStarred = !IsStarred.Value; } catch (Exception e) { throw new Exception("Unable to start gist. Please try again.", e); } }); ForkCommand = ReactiveCommand.CreateAsyncTask(async t => { var gist = await sessionService.GitHubClient.Gist.Fork(Id); var vm = this.CreateViewModel <GistViewModel>(); vm.Id = gist.Id; vm.Gist = gist; NavigateTo(vm); }); ForkCommand.IsExecuting.Subscribe(x => { if (x) { alertDialogFactory.Show("Forking..."); } else { alertDialogFactory.Hide(); } }); GoToEditCommand = ReactiveCommand.Create(); GoToEditCommand.Subscribe(_ => { var vm = this.CreateViewModel <GistEditViewModel>(); vm.Gist = Gist; vm.SaveCommand.Subscribe(x => Gist = x); NavigateTo(vm); }); GoToHtmlUrlCommand = ReactiveCommand.Create(this.WhenAnyValue(x => x.Gist).Select(x => x != null && !string.IsNullOrEmpty(x.HtmlUrl))); GoToHtmlUrlCommand .Select(_ => this.CreateViewModel <WebBrowserViewModel>()) .Select(x => x.Init(Gist.HtmlUrl)) .Subscribe(NavigateTo); GoToFileSourceCommand = ReactiveCommand.Create(); GoToFileSourceCommand.OfType <GistFile>().Subscribe(x => { var vm = this.CreateViewModel <GistFileViewModel>(); vm.Id = Id; vm.GistFile = x; vm.Filename = x.Filename; NavigateTo(vm); }); GoToOwnerCommand = ReactiveCommand.Create(this.WhenAnyValue(x => x.Gist.Owner).Select(x => x != null)); GoToOwnerCommand .Select(_ => this.CreateViewModel <UserViewModel>()) .Select(x => x.Init(Gist.Owner.Login)) .Subscribe(NavigateTo); AddCommentCommand = ReactiveCommand.Create().WithSubscription(_ => NavigateTo(new ComposerViewModel("Add Comment", async x => { var request = sessionService.Client.Gists[Id].CreateGistComment(x); Comments.Add((await sessionService.Client.ExecuteAsync(request)).Data); }, alertDialogFactory))); ShowMenuCommand = ReactiveCommand.CreateAsyncTask( this.WhenAnyValue(x => x.Gist).Select(x => x != null), sender => { var menu = actionMenuService.Create(); if (Gist.Owner != null && string.Equals(sessionService.Account.Username, Gist.Owner.Login, StringComparison.OrdinalIgnoreCase)) { menu.AddButton("Edit", GoToEditCommand); } else { menu.AddButton("Fork", ForkCommand); } menu.AddButton("Share", ShareCommand); menu.AddButton("Show in GitHub", GoToHtmlUrlCommand); return(menu.Show(sender)); }); LoadCommand = ReactiveCommand.CreateAsyncTask(async _ => { sessionService.GitHubClient.Gist.IsStarred(Id).ToBackground(x => IsStarred = x); Comments.SimpleCollectionLoad(sessionService.Client.Gists[Id].GetComments()); Gist = await sessionService.GitHubClient.Gist.Get(Id); }); }
public ReleaseViewModel(ISessionService applicationService, IUrlRouterService urlRouterService, IActionMenuFactory actionMenuService) { Title = "Release"; this.WhenAnyValue(x => x.ReleaseModel) .Select(x => { if (x == null) { return("Release"); } var name = string.IsNullOrEmpty(x.Name) ? x.TagName : x.Name; return(name ?? "Release"); }) .Subscribe(x => Title = x); var shareCommand = ReactiveCommand.Create(this.WhenAnyValue(x => x.ReleaseModel).Select(x => x != null)); shareCommand.Subscribe(sender => actionMenuService.ShareUrl(sender, ReleaseModel.HtmlUrl)); var gotoUrlCommand = new Action <string>(x => { var vm = this.CreateViewModel <WebBrowserViewModel>(); vm.Init(x); NavigateTo(vm); }); var gotoGitHubCommand = ReactiveCommand.Create(this.WhenAnyValue(x => x.ReleaseModel).Select(x => x != null)); gotoGitHubCommand.Select(_ => ReleaseModel.HtmlUrl).Subscribe(gotoUrlCommand); GoToLinkCommand = ReactiveCommand.Create(); GoToLinkCommand.OfType <string>().Subscribe(x => { var handledViewModel = urlRouterService.Handle(x); if (handledViewModel != null) { NavigateTo(handledViewModel); } else { gotoUrlCommand(x); } }); var canShowMenu = this.WhenAnyValue(x => x.ReleaseModel).Select(x => x != null); ShowMenuCommand = ReactiveCommand.CreateAsyncTask(canShowMenu, sender => { var menu = actionMenuService.Create(); menu.AddButton("Share", shareCommand); menu.AddButton("Show in GitHub", gotoGitHubCommand); return(menu.Show(sender)); }); _contentText = this.WhenAnyValue(x => x.ReleaseModel).IsNotNull() .Select(x => x.BodyHtml).ToProperty(this, x => x.ContentText); LoadCommand = ReactiveCommand.CreateAsyncTask(async _ => { var request = applicationService.Client.Users[RepositoryOwner].Repositories[RepositoryName].GetRelease(ReleaseId); ReleaseModel = (await applicationService.Client.ExecuteAsync(request)).Data; }); }
public SourceViewModel(ISessionService sessionService, IActionMenuFactory actionMenuFactory, IFilesystemService filesystemService) : base(sessionService) { var canEdit = this.WhenAnyValue(x => x.SourceItem, x => x.TrueBranch, x => x.PushAccess) .Select(x => x.Item1 != null && x.Item2 && !x.Item1.IsBinary && x.Item3.HasValue && x.Item3.Value); GoToEditCommand = ReactiveCommand.Create(canEdit); GoToEditCommand.Subscribe(_ => { var vm = this.CreateViewModel <EditFileViewModel>(); vm.Init(RepositoryOwner, RepositoryName, Path, null, Branch); vm.SaveCommand.Subscribe(x => { GitUrl = x.Content.GitUrl.AbsoluteUri; LoadCommand.ExecuteIfCan(); }); NavigateTo(vm); }); this.WhenAnyValue(x => x.Name).Subscribe(x => Title = x ?? string.Empty); _isMarkdown = this.WhenAnyValue(x => x.Path).IsNotNull().Select(x => MarkdownExtensions.Any(Path.EndsWith)).ToProperty(this, x => x.IsMarkdown); OpenInGitHubCommand = ReactiveCommand.Create(this.WhenAnyValue(x => x.HtmlUrl).Select(x => !string.IsNullOrEmpty(x))); OpenInGitHubCommand .Select(_ => this.CreateViewModel <WebBrowserViewModel>()) .Select(x => x.Init(this.HtmlUrl)) .Subscribe(NavigateTo); var canShowMenu = this.WhenAnyValue(x => x.SourceItem).Select(x => x != null); ShowMenuCommand = ReactiveCommand.CreateAsyncTask(canShowMenu, sender => { var menu = actionMenuFactory.Create(); if (GoToEditCommand.CanExecute(null)) { menu.AddButton("Edit", GoToEditCommand); } menu.AddButton("Open With", OpenWithCommand); if (OpenInGitHubCommand.CanExecute(null)) { menu.AddButton("Open in GitHub", OpenInGitHubCommand); } return(menu.Show(sender)); }); LoadCommand = ReactiveCommand.CreateAsyncTask(async t => { string filepath; bool isBinary = false; if (!PushAccess.HasValue) { sessionService.GitHubClient.Repository.Get(RepositoryOwner, RepositoryName) .ToBackground(x => PushAccess = x.Permissions.Push); } using (var stream = filesystemService.CreateTempFile(out filepath, Name)) { if (MarkdownExtensions.Any(Path.EndsWith)) { var renderedContent = await sessionService.Client.Users[RepositoryOwner].Repositories[RepositoryName].GetContentFileRendered(Path, Branch); using (var stringWriter = new StreamWriter(stream)) { await stringWriter.WriteAsync(renderedContent); } } else { if (string.IsNullOrEmpty(GitUrl) || string.IsNullOrEmpty(HtmlUrl)) { var req = sessionService.Client.Users[RepositoryOwner].Repositories[RepositoryName].GetContentFile(Path, Branch); var data = (await sessionService.Client.ExecuteAsync(req)).Data; GitUrl = data.GitUrl; HtmlUrl = data.HtmlUrl; } var mime = await sessionService.Client.DownloadRawResource2(GitUrl, stream) ?? string.Empty; isBinary = !(mime ?? string.Empty).Contains("charset"); } } // We can force a binary representation if it was passed during init. In which case we don't care to figure out via the mime. var fileUri = new Uri(filepath); SourceItem = new FileSourceItemViewModel(fileUri, ForceBinary || isBinary); }); }
public StarredGistsViewModel(IApplicationService applicationService) { Title = "Starred Gists"; LoadCommand = ReactiveCommand.CreateAsyncTask(t => GistsCollection.SimpleCollectionLoad(applicationService.Client.Gists.GetStarredGists(), t as bool?)); }
public PullRequestDetailViewModel( IPullRequestService pullRequestsService, IPullRequestSessionManager sessionManager, IModelServiceFactory modelServiceFactory, IUsageTracker usageTracker, ITeamExplorerContext teamExplorerContext, IPullRequestFilesViewModel files, ISyncSubmodulesCommand syncSubmodulesCommand, IViewViewModelFactory viewViewModelFactory) { Guard.ArgumentNotNull(pullRequestsService, nameof(pullRequestsService)); Guard.ArgumentNotNull(sessionManager, nameof(sessionManager)); Guard.ArgumentNotNull(modelServiceFactory, nameof(modelServiceFactory)); Guard.ArgumentNotNull(usageTracker, nameof(usageTracker)); Guard.ArgumentNotNull(teamExplorerContext, nameof(teamExplorerContext)); Guard.ArgumentNotNull(syncSubmodulesCommand, nameof(syncSubmodulesCommand)); Guard.ArgumentNotNull(viewViewModelFactory, nameof(viewViewModelFactory)); this.pullRequestsService = pullRequestsService; this.sessionManager = sessionManager; this.modelServiceFactory = modelServiceFactory; this.usageTracker = usageTracker; this.teamExplorerContext = teamExplorerContext; this.syncSubmodulesCommand = syncSubmodulesCommand; this.viewViewModelFactory = viewViewModelFactory; Files = files; Checkout = ReactiveCommand.CreateAsyncObservable( this.WhenAnyValue(x => x.CheckoutState) .Cast <CheckoutCommandState>() .Select(x => x != null && x.IsEnabled), DoCheckout); Checkout.IsExecuting.Subscribe(x => isInCheckout = x); SubscribeOperationError(Checkout); Pull = ReactiveCommand.CreateAsyncObservable( this.WhenAnyValue(x => x.UpdateState) .Cast <UpdateCommandState>() .Select(x => x != null && x.PullEnabled), DoPull); SubscribeOperationError(Pull); Push = ReactiveCommand.CreateAsyncObservable( this.WhenAnyValue(x => x.UpdateState) .Cast <UpdateCommandState>() .Select(x => x != null && x.PushEnabled), DoPush); SubscribeOperationError(Push); SyncSubmodules = ReactiveCommand.CreateAsyncTask( this.WhenAnyValue(x => x.UpdateState) .Cast <UpdateCommandState>() .Select(x => x != null && x.SyncSubmodulesEnabled), DoSyncSubmodules); SyncSubmodules.Subscribe(_ => Refresh().ToObservable()); SubscribeOperationError(SyncSubmodules); OpenOnGitHub = ReactiveCommand.Create().OnExecuteCompleted(DoOpenDetailsUrl); ShowReview = ReactiveCommand.Create().OnExecuteCompleted(DoShowReview); }
public UserFollowersViewModel(IApplicationService applicationService) { LoadCommand = ReactiveCommand.CreateAsyncTask(t => UsersCollection.SimpleCollectionLoad(applicationService.Client.Users[Username].GetFollowers(), t as bool?)); }
public OrderDetailVm(IReactiveDeliveryClient client) { _client = client; VisiblityStoreErrMsg = Visibility.Collapsed; CopyIdOrder = ReactiveCommand.CreateAsyncTask(Observable.Return(true), _ => OnCopyIdOrder()); }
public OrganizationViewModel(ISessionService applicationService) { this.WhenAnyValue(x => x.Organization, x => x.Username, (x, y) => x == null ? y : (string.IsNullOrEmpty(x.Name) ? x.Login : x.Name)) .Select(x => x ?? "Organization") .Subscribe(x => Title = x); this.WhenAnyValue(x => x.Organization.AvatarUrl) .Select(x => new GitHubAvatar(x)) .ToProperty(this, x => x.Avatar, out _avatar); GoToMembersCommand = ReactiveCommand.Create(); GoToMembersCommand .Select(_ => this.CreateViewModel <OrganizationMembersViewModel>()) .Select(x => x.Init(Username)) .Subscribe(NavigateTo); GoToTeamsCommand = ReactiveCommand.Create(); GoToTeamsCommand .Select(_ => this.CreateViewModel <TeamsViewModel>()) .Select(x => x.Init(Username)) .Subscribe(NavigateTo); GoToFollowersCommand = ReactiveCommand.Create(); GoToFollowersCommand .Select(_ => this.CreateViewModel <UserFollowersViewModel>()) .Select(x => x.Init(Username)) .Subscribe(NavigateTo); GoToFollowingCommand = ReactiveCommand.Create(); GoToFollowingCommand .Select(_ => this.CreateViewModel <UserFollowingsViewModel>()) .Select(x => x.Init(Username)) .Subscribe(NavigateTo); GoToEventsCommand = ReactiveCommand.Create(); GoToEventsCommand .Select(_ => this.CreateViewModel <UserEventsViewModel>()) .Select(x => x.Init(Username)) .Subscribe(NavigateTo); GoToGistsCommand = ReactiveCommand.Create(); GoToGistsCommand .Select(_ => this.CreateViewModel <UserGistsViewModel>()) .Select(x => x.Init(Username)) .Subscribe(NavigateTo); GoToRepositoriesCommand = ReactiveCommand.Create().WithSubscription(_ => { var vm = this.CreateViewModel <OrganizationRepositoriesViewModel>(); vm.Init(Username); NavigateTo(vm); }); LoadCommand = ReactiveCommand.CreateAsyncTask(async _ => { applicationService.GitHubClient.Organization.Team.GetAll(Username) .ToBackground(x => CanViewTeams = true); Organization = await applicationService.GitHubClient.Organization.Get(Username); }); }
public CommitViewModel(ISessionService applicationService, IActionMenuFactory actionMenuService, IAlertDialogFactory alertDialogFactory) { Title = "Commit"; var comments = new ReactiveList <CommentModel>(); Comments = comments.CreateDerivedCollection(x => new CommitCommentItemViewModel(x)); this.WhenAnyValue(x => x.Commit) .Select(x => new GitHubAvatar(x.GenerateGravatarUrl())) .ToProperty(this, x => x.Avatar, out _avatar); var files = this.WhenAnyValue(x => x.Commit.Files).IsNotNull(); files.Select(x => x.Count(y => string.Equals(y.Status, "added"))) .ToProperty(this, x => x.DiffAdditions, out _diffAdditions); files.Select(x => x.Count(y => string.Equals(y.Status, "removed"))) .ToProperty(this, x => x.DiffDeletions, out _diffDeletions); files.Select(x => x.Count(y => string.Equals(y.Status, "modified"))) .ToProperty(this, x => x.DiffModifications, out _diffModifications); GoToAddedFiles = ReactiveCommand.Create(this.WhenAnyValue(x => x.DiffAdditions).Select(x => x > 0)); GoToAddedFiles .Select(_ => new CommitFilesViewModel()) .Select(y => y.Init(RepositoryOwner, RepositoryName, Node, "Added", Commit.Files.Where(x => string.Equals(x.Status, "added")))) .Subscribe(NavigateTo); GoToRemovedFiles = ReactiveCommand.Create(this.WhenAnyValue(x => x.DiffDeletions).Select(x => x > 0)); GoToRemovedFiles .Select(_ => new CommitFilesViewModel()) .Select(y => y.Init(RepositoryOwner, RepositoryName, Node, "Removed", Commit.Files.Where(x => string.Equals(x.Status, "removed")))) .Subscribe(NavigateTo); GoToModifiedFiles = ReactiveCommand.Create(this.WhenAnyValue(x => x.DiffModifications).Select(x => x > 0)); GoToModifiedFiles .Select(_ => new CommitFilesViewModel()) .Select(y => y.Init(RepositoryOwner, RepositoryName, Node, "Modified", Commit.Files.Where(x => string.Equals(x.Status, "modified")))) .Subscribe(NavigateTo); GoToAllFiles = ReactiveCommand.Create(this.WhenAnyValue(x => x.Commit.Files).Select(x => x != null)); GoToAllFiles .Select(_ => new CommitFilesViewModel()) .Select(y => y.Init(RepositoryOwner, RepositoryName, Node, "All Changes", Commit.Files)) .Subscribe(NavigateTo); this.WhenAnyValue(x => x.Commit) .IsNotNull() .Select(x => x.GenerateCommiterName()) .ToProperty(this, x => x.CommiterName, out _commiterName); this.WhenAnyValue(x => x.Commit) .IsNotNull() .Select(x => x.Commit.Message ?? string.Empty) .Select(x => Emojis.FindAndReplace(x)) .ToProperty(this, x => x.CommitMessage, out _commitMessage); this.WhenAnyValue(x => x.CommitMessage) .IsNotNull() .Select(x => { var firstNewLine = x.IndexOf("\n", StringComparison.Ordinal); return(firstNewLine > 0 ? x.Substring(0, firstNewLine) : x); }) .ToProperty(this, x => x.CommitMessageSummary, out _commitMessageSummary); GoToHtmlUrlCommand = ReactiveCommand.Create(this.WhenAnyValue(x => x.Commit).Select(x => x != null)); GoToHtmlUrlCommand .Select(_ => this.CreateViewModel <WebBrowserViewModel>()) .Select(x => x.Init(Commit.HtmlUrl)) .Subscribe(NavigateTo); GoToRepositoryCommand = ReactiveCommand.Create(); GoToRepositoryCommand.Subscribe(_ => { var vm = this.CreateViewModel <RepositoryViewModel>(); vm.Init(RepositoryOwner, RepositoryName); NavigateTo(vm); }); AddCommentCommand = ReactiveCommand.Create().WithSubscription(_ => { var vm = new ComposerViewModel(async s => { var request = applicationService.Client.Users[RepositoryOwner].Repositories[RepositoryName].Commits[Node].Comments.Create(s); comments.Add((await applicationService.Client.ExecuteAsync(request)).Data); }, alertDialogFactory); NavigateTo(vm); }); var validCommitObservable = this.WhenAnyValue(x => x.Commit).Select(x => x != null); var copyShaCommand = ReactiveCommand.Create(validCommitObservable) .WithSubscription(x => actionMenuService.SendToPasteBoard(this.Commit.Sha)); var shareCommand = ReactiveCommand.Create(validCommitObservable) .WithSubscription(sender => actionMenuService.ShareUrl(sender, this.Commit.HtmlUrl)); var browseCodeCommand = ReactiveCommand.Create(validCommitObservable) .WithSubscription(x => { var vm = this.CreateViewModel <SourceTreeViewModel>(); vm.RepositoryName = RepositoryName; vm.RepositoryOwner = RepositoryOwner; vm.Branch = this.Commit.Sha; NavigateTo(vm); }); ShowMenuCommand = ReactiveCommand.CreateAsyncTask(sender => { var menu = actionMenuService.Create(); menu.AddButton("Add Comment", AddCommentCommand); menu.AddButton("Copy SHA", copyShaCommand); menu.AddButton("Browse Code", browseCodeCommand); menu.AddButton("Share", shareCommand); menu.AddButton("Show in GitHub", GoToHtmlUrlCommand); return(menu.Show(sender)); }); LoadCommand = ReactiveCommand.CreateAsyncTask(async t => { var commentRequest = applicationService.Client.Users[RepositoryOwner].Repositories[RepositoryName].Commits[Node].Comments.GetAll(); applicationService.Client.ExecuteAsync(commentRequest).ToBackground(x => comments.Reset(x.Data.Where(y => y.Position.HasValue))); Commit = await applicationService.GitHubClient.Repository.Commits.Get(RepositoryOwner, RepositoryName, Node); }); }
public CommitViewModel(IApplicationService applicationService, IActionMenuFactory actionMenuService) { Title = "Commit"; var comments = new ReactiveList <Octokit.CommitComment>(); Comments = comments.CreateDerivedCollection(x => x); this.WhenAnyValue(x => x.Commit) .IsNotNull() .Select(x => x.Commit.Message ?? string.Empty) .Select(x => { var firstNewLine = x.IndexOf("\n", StringComparison.Ordinal); return(firstNewLine > 0 ? x.Substring(0, firstNewLine) : x); }) .ToProperty(this, x => x.CommitMessageSummary, out _commitMessageSummary); GoToHtmlUrlCommand = ReactiveCommand.Create(this.WhenAnyValue(x => x.Commit).Select(x => x != null)); GoToHtmlUrlCommand.Select(x => Commit.HtmlUrl).Subscribe(x => { var vm = this.CreateViewModel <WebBrowserViewModel>(); vm.Url = x; NavigateTo(vm); }); GoToRepositoryCommand = ReactiveCommand.Create(); GoToRepositoryCommand.Subscribe(_ => { var vm = this.CreateViewModel <RepositoryViewModel>(); vm.RepositoryOwner = RepositoryOwner; vm.RepositoryName = RepositoryName; NavigateTo(vm); }); GoToCommentCommand = ReactiveCommand.Create().WithSubscription(_ => { var vm = this.CreateViewModel <CommitCommentViewModel>(); vm.RepositoryOwner = RepositoryOwner; vm.RepositoryName = RepositoryName; vm.Node = Node; vm.SaveCommand.Subscribe(comments.Add); NavigateTo(vm); }); GoToFileCommand = ReactiveCommand.Create(); GoToFileCommand.OfType <Octokit.GitHubCommitFile>().Subscribe(x => { if (x.Patch == null) { var vm = this.CreateViewModel <SourceViewModel>(); vm.Branch = Commit.Sha; vm.Path = x.Filename; vm.RepositoryOwner = RepositoryOwner; vm.RepositoryName = RepositoryName; vm.Name = System.IO.Path.GetFileName(x.Filename); vm.ForceBinary = true; NavigateTo(vm); } else { var vm = this.CreateViewModel <ChangesetDiffViewModel>(); vm.Username = RepositoryOwner; vm.Repository = RepositoryName; vm.Branch = Commit.Sha; vm.Filename = x.Filename; NavigateTo(vm); } }); var validCommitObservable = this.WhenAnyValue(x => x.Commit).Select(x => x != null); var copyShaCommand = ReactiveCommand.Create(validCommitObservable) .WithSubscription(x => actionMenuService.SendToPasteBoard(this.Commit.Sha)); var shareCommand = ReactiveCommand.Create(validCommitObservable) .WithSubscription(x => actionMenuService.ShareUrl(this.Commit.HtmlUrl)); var browseCodeCommand = ReactiveCommand.Create(validCommitObservable) .WithSubscription(x => { var vm = this.CreateViewModel <SourceTreeViewModel>(); vm.RepositoryName = RepositoryName; vm.RepositoryOwner = RepositoryOwner; vm.Branch = this.Commit.Sha; NavigateTo(vm); }); ShowMenuCommand = ReactiveCommand.CreateAsyncTask(_ => { var menu = actionMenuService.Create(Title); menu.AddButton("Add Comment", GoToCommentCommand); menu.AddButton("Copy SHA", copyShaCommand); menu.AddButton("Browse Code", browseCodeCommand); menu.AddButton("Share", shareCommand); menu.AddButton("Show in GitHub", GoToHtmlUrlCommand); return(menu.Show()); }); LoadCommand = ReactiveCommand.CreateAsyncTask(async t => { applicationService.GitHubClient.Repository.RepositoryComments.GetForCommit(RepositoryOwner, RepositoryName, Node) .ToBackground(x => comments.Reset(x)); Commit = await applicationService.GitHubClient.Repository.Commits.Get(RepositoryOwner, RepositoryName, Node); }); }
public ShellViewModel(Library library, ViewSettings viewSettings, CoreSettings coreSettings, IWindowManager windowManager, MobileApiInfo mobileApiInfo) { this.library = library; this.ViewSettings = viewSettings; this.coreSettings = coreSettings; this.disposable = new CompositeDisposable(); this.UpdateViewModel = new UpdateViewModel(viewSettings); this.library.Initialize(); this.accessToken = this.library.LocalAccessControl.RegisterLocalAccessToken(); this.library.WhenAnyValue(x => x.CurrentPlaylist).Subscribe(x => this.RaisePropertyChanged("CurrentPlaylist")); this.canChangeTime = this.library.LocalAccessControl.HasAccess(this.coreSettings.WhenAnyValue(x => x.LockTime), this.accessToken) .ToProperty(this, x => x.CanChangeTime); this.canChangeVolume = this.library.LocalAccessControl.HasAccess(this.coreSettings.WhenAnyValue(x => x.LockVolume), this.accessToken) .ToProperty(this, x => x.CanChangeVolume); this.canAlterPlaylist = this.library.LocalAccessControl.HasAccess(this.coreSettings.WhenAnyValue(x => x.LockPlaylist), this.accessToken) .ToProperty(this, x => x.CanAlterPlaylist); this.showVotes = this.library.RemoteAccessControl.WhenAnyValue(x => x.IsGuestSystemReallyEnabled) .CombineLatest(mobileApiInfo.ConnectedClientCount, (enableGuestSystem, connectedClients) => enableGuestSystem && connectedClients > 0) .ToProperty(this, x => x.ShowVotes); mobileApiInfo.VideoPlayerToggleRequest.Subscribe(_ => this.ShowVideoPlayer = !this.ShowVideoPlayer); this.isAdmin = this.library.LocalAccessControl.ObserveAccessPermission(this.accessToken) .Select(x => x == AccessPermission.Admin) .ToProperty(this, x => x.IsAdmin); this.NextSongCommand = ReactiveCommand.CreateAsyncTask(this.library.LocalAccessControl.HasAccess(this.coreSettings.WhenAnyValue(x => x.LockPlayPause), this.accessToken) .CombineLatest(this.library.WhenAnyValue(x => x.CurrentPlaylist.CanPlayNextSong), (x1, x2) => x1 && x2) .ObserveOn(RxApp.MainThreadScheduler), _ => this.library.PlayNextSongAsync(this.accessToken)); this.PreviousSongCommand = ReactiveCommand.CreateAsyncTask(this.library.LocalAccessControl.HasAccess(this.coreSettings.WhenAnyValue(x => x.LockPlayPause), this.accessToken) .CombineLatest(this.library.WhenAnyValue(x => x.CurrentPlaylist.CanPlayPreviousSong), (x1, x2) => x1 && x2) .ObserveOn(RxApp.MainThreadScheduler), _ => this.library.PlayPreviousSongAsync(this.accessToken)); if (!this.library.Playlists.Any()) { this.library.AddAndSwitchToPlaylist(this.GetNewPlaylistName(), this.accessToken); } else { this.library.SwitchToPlaylist(this.library.Playlists.First(), this.accessToken); } this.SettingsViewModel = new SettingsViewModel(this.library, this.ViewSettings, this.coreSettings, windowManager, this.accessToken, mobileApiInfo); this.LocalViewModel = new LocalViewModel(this.library, this.ViewSettings, this.coreSettings, accessToken); this.YoutubeViewModel = new YoutubeViewModel(this.library, this.ViewSettings, this.coreSettings, accessToken); this.SoundCloudViewModel = new SoundCloudViewModel(this.library, accessToken, this.coreSettings, this.ViewSettings); this.DirectYoutubeViewModel = new DirectYoutubeViewModel(this.library, this.coreSettings, accessToken); this.currentSongSource = this.WhenAnyValue(x => x.IsLocal, x => x.IsYoutube, x => x.IsSoundCloud, (local, youtube, soundcloud) => { if (local) { return((ISongSourceViewModel)this.LocalViewModel); } if (youtube) { return(this.YoutubeViewModel); } if (soundcloud) { return(this.SoundCloudViewModel); } return(this.LocalViewModel); }) .ToProperty(this, x => x.CurrentSongSource, null, ImmediateScheduler.Instance); this.MuteCommand = ReactiveCommand.Create(this.WhenAnyValue(x => x.IsAdmin)); this.MuteCommand.Subscribe(x => this.Volume = 0); this.UnMuteCommand = ReactiveCommand.Create(this.WhenAnyValue(x => x.IsAdmin)); this.UnMuteCommand.Subscribe(x => this.Volume = 1); this.canModifyWindow = this.library.LocalAccessControl.HasAccess(this.ViewSettings.WhenAnyValue(x => x.LockWindow), this.accessToken) .ToProperty(this, x => x.CanModifyWindow); this.isPlaying = this.library.PlaybackState .Select(x => x == AudioPlayerState.Playing) .ObserveOn(RxApp.MainThreadScheduler) .ToProperty(this, x => x.IsPlaying); this.currentTime = this.library.CurrentPlaybackTime .StartWith(TimeSpan.Zero) .Select(x => x.FormatAdaptive()) .ToProperty(this, x => x.CurrentTime); this.currentSeconds = this.library.CurrentPlaybackTime .Select(x => (int)x.TotalSeconds) .ToProperty(this, x => x.CurrentSeconds); this.totalTime = this.library.TotalTime .Select(x => x.FormatAdaptive()) .ToProperty(this, x => x.TotalTime); this.totalSeconds = this.library.TotalTime .Select(x => (int)x.TotalSeconds) .ToProperty(this, x => x.TotalSeconds); this.volume = this.library.WhenAnyValue(x => x.Volume, x => (double)x) .ToProperty(this, x => x.Volume); this.AddPlaylistCommand = ReactiveCommand.Create(this.WhenAnyValue(x => x.CanAlterPlaylist)); this.AddPlaylistCommand.Subscribe(x => this.AddPlaylist()); this.Playlists = this.library.Playlists.CreateDerivedCollection(this.CreatePlaylistViewModel, x => x.Dispose()); this.ShowSettingsCommand = ReactiveCommand.Create(); this.ShowSettingsCommand.Subscribe(x => this.SettingsViewModel.HandleSettings()); this.ShufflePlaylistCommand = ReactiveCommand.Create(this.WhenAnyValue(x => x.CanAlterPlaylist)); this.ShufflePlaylistCommand.Subscribe(x => this.library.ShufflePlaylist(this.accessToken)); IObservable <bool> canPlay = this.WhenAnyValue(x => x.CurrentPlaylist.SelectedEntries) .CombineLatest(this.library.LocalAccessControl.HasAccess(this.coreSettings.WhenAnyValue(x => x.LockPlayPause), this.accessToken), this.library.LoadedSong, this.library.PlaybackState, (selectedPlaylistEntries, hasPlayAccess, loadedSong, playBackState) => // The admin can always play, but if we are in party mode, we have to check // whether it is allowed to play hasPlayAccess && // If exactly one song is selected, the command can be executed (selectedPlaylistEntries != null && selectedPlaylistEntries.Count() == 1 || // If the current song is paused, the command can be executed (loadedSong != null || playBackState == AudioPlayerState.Paused))); this.PlayCommand = ReactiveCommand.CreateAsyncTask(canPlay, async _ => { if (await this.library.PlaybackState.FirstAsync() == AudioPlayerState.Paused || await this.library.LoadedSong.FirstAsync() != null) { await this.library.ContinueSongAsync(this.accessToken); } else { await this.library.PlaySongAsync(this.CurrentPlaylist.SelectedEntries.First().Index, this.accessToken); } }); this.PlayOverrideCommand = ReactiveCommand.CreateAsyncTask(this.WhenAnyValue(x => x.CurrentPlaylist.SelectedEntries) .CombineLatest(this.library.LocalAccessControl.HasAccess(this.coreSettings.WhenAnyValue(x => x.LockPlayPause), this.accessToken), (selectedPlaylistEntries, hasAccess) => hasAccess && (selectedPlaylistEntries != null && selectedPlaylistEntries.Count() == 1)), _ => this.library.PlaySongAsync(this.CurrentPlaylist.SelectedEntries.First().Index, this.accessToken)); this.PauseCommand = ReactiveCommand.CreateAsyncTask(this.library.LocalAccessControl.HasAccess(this.coreSettings.WhenAnyValue(x => x.LockPlayPause), this.accessToken) .CombineLatest(this.WhenAnyValue(x => x.IsPlaying), (hasAccess, isPlaying) => hasAccess && isPlaying), _ => this.library.PauseSongAsync(this.accessToken)); var pauseOrContinueCommand = this.WhenAnyValue(x => x.IsPlaying) .Select(x => x ? this.PauseCommand : this.PlayCommand).Publish(null); pauseOrContinueCommand.Connect(); this.PauseContinueCommand = ReactiveCommand.CreateAsyncTask( pauseOrContinueCommand.Select(x => x.CanExecuteObservable).Switch().ObserveOn(RxApp.MainThreadScheduler), async _ => { IReactiveCommand <Unit> command = await pauseOrContinueCommand.FirstAsync(); await command.ExecuteAsync(); }); this.EditPlaylistNameCommand = ReactiveCommand.Create(this.WhenAnyValue(x => x.CanAlterPlaylist, x => x.CurrentPlaylist, (x1, x2) => x1 && !x2.Model.IsTemporary)); this.EditPlaylistNameCommand.Subscribe(x => this.CurrentPlaylist.EditName = true); this.RemovePlaylistCommand = ReactiveCommand.Create(this.WhenAnyValue(x => x.CurrentEditedPlaylist, x => x.CurrentPlaylist, x => x.CanAlterPlaylist, (currentEditedPlaylist, currentPlaylist, canAlterPlaylist) => (currentEditedPlaylist != null || currentPlaylist != null) && canAlterPlaylist)); this.RemovePlaylistCommand.Subscribe(x => this.RemoveCurrentPlaylist()); this.IsLocal = true; }
public GitHubPaneViewModel( IViewViewModelFactory viewModelFactory, ISimpleApiClientFactory apiClientFactory, IConnectionManager connectionManager, ITeamExplorerContext teamExplorerContext, IVisualStudioBrowser browser, IUsageTracker usageTracker, INavigationViewModel navigator, ILoggedOutViewModel loggedOut, INotAGitHubRepositoryViewModel notAGitHubRepository, INotAGitRepositoryViewModel notAGitRepository) { Guard.ArgumentNotNull(viewModelFactory, nameof(viewModelFactory)); Guard.ArgumentNotNull(apiClientFactory, nameof(apiClientFactory)); Guard.ArgumentNotNull(connectionManager, nameof(connectionManager)); Guard.ArgumentNotNull(teamExplorerContext, nameof(teamExplorerContext)); Guard.ArgumentNotNull(browser, nameof(browser)); Guard.ArgumentNotNull(usageTracker, nameof(usageTracker)); Guard.ArgumentNotNull(navigator, nameof(navigator)); Guard.ArgumentNotNull(loggedOut, nameof(loggedOut)); Guard.ArgumentNotNull(notAGitHubRepository, nameof(notAGitHubRepository)); Guard.ArgumentNotNull(notAGitRepository, nameof(notAGitRepository)); this.viewModelFactory = viewModelFactory; this.apiClientFactory = apiClientFactory; this.connectionManager = connectionManager; this.teamExplorerContext = teamExplorerContext; this.browser = browser; this.usageTracker = usageTracker; this.navigator = navigator; this.loggedOut = loggedOut; this.notAGitHubRepository = notAGitHubRepository; this.notAGitRepository = notAGitRepository; var contentAndNavigatorContent = Observable.CombineLatest( this.WhenAnyValue(x => x.Content), navigator.WhenAnyValue(x => x.Content), (c, nc) => new { Content = c, NavigatorContent = nc }); contentOverride = contentAndNavigatorContent .SelectMany(x => { if (x.Content == null) { return(Observable.Return(ContentOverride.Spinner)); } else if (x.Content == navigator && x.NavigatorContent != null) { return(x.NavigatorContent.WhenAnyValue( y => y.IsLoading, y => y.Error, (l, e) => { if (l) { return ContentOverride.Spinner; } if (e != null) { return ContentOverride.Error; } else { return ContentOverride.None; } })); } else { return(Observable.Return(ContentOverride.None)); } }) .ToProperty(this, x => x.ContentOverride); // Returns navigator.Content if Content == navigator, otherwise null. var currentPage = contentAndNavigatorContent .Select(x => x.Content == navigator ? x.NavigatorContent : null); title = currentPage .SelectMany(x => x?.WhenAnyValue(y => y.Title) ?? Observable.Return <string>(null)) .Select(x => x ?? "GitHub") .ToProperty(this, x => x.Title); isSearchEnabled = currentPage .Select(x => x is ISearchablePageViewModel) .ToProperty(this, x => x.IsSearchEnabled); refresh = ReactiveCommand.CreateAsyncTask( currentPage.SelectMany(x => x?.WhenAnyValue( y => y.IsLoading, y => y.IsBusy, (loading, busy) => !loading && !busy) ?? Observable.Return(false)), _ => navigator.Content.Refresh()); refresh.ThrownExceptions.Subscribe(); showPullRequests = ReactiveCommand.CreateAsyncTask( this.WhenAny(x => x.Content, x => x.Value == navigator), _ => ShowPullRequests()); openInBrowser = ReactiveCommand.Create(currentPage.Select(x => x is IOpenInBrowser)); openInBrowser.Subscribe(_ => { var url = ((IOpenInBrowser)navigator.Content).WebUrl; if (url != null) { browser.OpenUrl(url); } }); navigator.WhenAnyObservable(x => x.Content.NavigationRequested) .Subscribe(x => NavigateTo(x).Forget()); this.WhenAnyValue(x => x.SearchQuery) .Where(x => navigator.Content is ISearchablePageViewModel) .ObserveOn(RxApp.MainThreadScheduler) .Subscribe(x => ((ISearchablePageViewModel)navigator.Content).SearchQuery = x); }
public OrganizationViewModel(IApplicationService applicationService) { _applicationService = applicationService; this.WhenAnyValue(x => x.Organization, x => x.Username, (x, y) => x == null ? y : (string.IsNullOrEmpty(x.Name) ? x.Login : x.Name)) .Select(x => x ?? "Organization") .Subscribe(x => Title = x); GoToMembersCommand = ReactiveCommand.Create().WithSubscription(_ => { var vm = CreateViewModel <OrganizationMembersViewModel>(); vm.OrganizationName = Username; ShowViewModel(vm); }); GoToTeamsCommand = ReactiveCommand.Create().WithSubscription(_ => { var vm = CreateViewModel <TeamsViewModel>(); vm.OrganizationName = Username; ShowViewModel(vm); }); GoToFollowersCommand = ReactiveCommand.Create().WithSubscription(_ => { var vm = CreateViewModel <UserFollowersViewModel>(); vm.Username = Username; ShowViewModel(vm); }); GoToFollowingCommand = ReactiveCommand.Create().WithSubscription(_ => { var vm = CreateViewModel <UserFollowingsViewModel>(); vm.Username = Username; ShowViewModel(vm); }); GoToEventsCommand = ReactiveCommand.Create().WithSubscription(_ => { var vm = CreateViewModel <UserEventsViewModel>(); vm.Username = Username; ShowViewModel(vm); }); GoToGistsCommand = ReactiveCommand.Create().WithSubscription(_ => { var vm = CreateViewModel <UserGistsViewModel>(); vm.Username = Username; ShowViewModel(vm); }); GoToRepositoriesCommand = ReactiveCommand.Create().WithSubscription(_ => { var vm = CreateViewModel <OrganizationRepositoriesViewModel>(); vm.Name = Username; ShowViewModel(vm); }); LoadCommand = ReactiveCommand.CreateAsyncTask(async _ => Organization = await _applicationService.GitHubClient.Organization.Get(Username)); }
public RepositoriesWatchedViewModel(IApplicationService applicationService) : base(applicationService) { LoadCommand = ReactiveCommand.CreateAsyncTask(t => RepositoryCollection.SimpleCollectionLoad( applicationService.Client.AuthenticatedUser.Repositories.GetWatching(), t as bool?)); }
protected BaseRepositoryViewModel(IApplicationService applicationService, INetworkActivityService networkActivity) { LikeCommand = ReactiveCommand.Create(); LikeCommand.Subscribe(_ => { if (StumbledRepository == null) { var repo = CreateStumbledRepository(); repo.Liked = true; applicationService.Account.StumbledRepositories.Insert(repo); StumbledRepository = repo; } else { StumbledRepository.Liked = true; StumbledRepository.Description = Repository.Description; StumbledRepository.Forks = Repository.ForksCount; StumbledRepository.Stars = Repository.WatchersCount; StumbledRepository.ImageUrl = Repository.Owner.AvatarUrl; applicationService.Account.StumbledRepositories.Update(StumbledRepository); } if (applicationService.Account.SyncWithGitHub) { applicationService.Client.Activity.Starring.StarRepo(Repository.Owner.Login, Repository.Name); } Liked = true; }); DislikeCommand = ReactiveCommand.Create(); DislikeCommand.Subscribe(_ => { if (StumbledRepository == null) { var repo = CreateStumbledRepository(); repo.Liked = false; applicationService.Account.StumbledRepositories.Insert(repo); StumbledRepository = repo; } else { StumbledRepository.Liked = false; StumbledRepository.Description = Repository.Description; StumbledRepository.Forks = Repository.ForksCount; StumbledRepository.Stars = Repository.WatchersCount; StumbledRepository.ImageUrl = Repository.Owner.AvatarUrl; applicationService.Account.StumbledRepositories.Update(StumbledRepository); } if (applicationService.Account.SyncWithGitHub) { applicationService.Client.Activity.Starring.RemoveStarFromRepo(Repository.Owner.Login, Repository.Name); } Liked = false; }); this.WhenAnyValue(x => x.RepositoryIdentifier) .Where(x => x != null) .Subscribe(x => { StumbledRepository = applicationService.Account.StumbledRepositories.FindByFullname(x.Owner, x.Name); }); this.WhenAnyValue(x => x.StumbledRepository) .Where(x => x != null) .Subscribe(x => Liked = x.Liked); GoToGitHubCommand = ReactiveCommand.Create(this.WhenAnyValue(x => x.Repository).Select(x => x != null)); GoToGitHubCommand.Subscribe(_ => GoToUrlCommand.ExecuteIfCan(Repository.HtmlUrl)); LoadCommand = ReactiveCommand.CreateAsyncTask(this.WhenAnyValue(x => x.RepositoryIdentifier).Select(x => x != null), async t => { Repository = (await applicationService.Client.Repository.Get(RepositoryIdentifier.Owner, RepositoryIdentifier.Name)); ContributorCount = (await applicationService.Client.Repository.GetAllContributors(RepositoryIdentifier.Owner, RepositoryIdentifier.Name)).Count; try { Readme = await applicationService.Client.Repository.GetReadmeHtml(RepositoryIdentifier.Owner, RepositoryIdentifier.Name); } catch (Exception e) { Readme = "<center>There is no readme for this repository :(</center>"; Debug.WriteLine(e.Message + " for " + RepositoryIdentifier.Owner + "/" + RepositoryIdentifier.Name); } }); LoadCommand.TriggerNetworkActivity(networkActivity); }
public GistCreateViewModel(IApplicationService applicationService, IAlertDialogFactory alertDialogFactory) { _applicationService = applicationService; CurrentAccount = applicationService.Account; Title = "Create Gist"; Files = new Dictionary <string, string>(); IsPublic = true; SaveCommand = ReactiveCommand.CreateAsyncTask( this.WhenAnyValue(x => x.Files).Select(x => x.Count > 0), async t => { var createGist = new GistCreateModel { Description = Description, Public = IsPublic, Files = Files.ToDictionary(x => x.Key, x => new GistCreateModel.File { Content = x.Value }) }; var request = _applicationService.Client.AuthenticatedUser.Gists.CreateGist(createGist); using (alertDialogFactory.Activate("Creating Gist...")) _createdGistSubject.OnNext((await _applicationService.Client.ExecuteAsync(request)).Data); Dismiss(); }); AddGistFileCommand = ReactiveCommand.Create().WithSubscription(_ => { var vm = this.CreateViewModel <ModifyGistViewModel>(); vm.Title = "New File"; vm.SaveCommand.Subscribe(__ => { if (Files.ContainsKey(vm.Filename)) { alertDialogFactory.Alert("File already exists!", "Gist already contains a file with that name!"); } else { Files.Add(vm.Filename, vm.Description); Files = new Dictionary <string, string>(Files); vm.Dismiss(); } }); NavigateTo(vm); }); ModifyGistFileCommand = ReactiveCommand.Create(); // Analysis disable once ConvertClosureToMethodGroup // Don't remove the lambda below. It doesn't actually seem to work correctly ModifyGistFileCommand.OfType <string>().Where(x => Files.ContainsKey(x)).Subscribe(x => { var vm = this.CreateViewModel <ModifyGistViewModel>(); vm.Title = vm.Filename = x; vm.Description = Files[x]; vm.SaveCommand.Subscribe(__ => { Files.Remove(x); Files[vm.Filename] = vm.Description; Files = new Dictionary <string, string>(Files); vm.Dismiss(); }); NavigateTo(vm); }); }
protected BaseIssueViewModel( IApplicationService applicationService, IMarkdownService markdownService) { _applicationService = applicationService; var issuePresenceObservable = this.WhenAnyValue(x => x.Issue, x => x.CanModify) .Select(x => x.Item1 != null && x.Item2); Events = InternalEvents.CreateDerivedCollection(x => x); _participants = Events.Changed .Select(_ => Events.Select(y => y.Actor).Distinct().Count()) .Select(x => x == 0 ? 1 : x) .ToProperty(this, x => x.Participants); GoToAssigneesCommand = ReactiveCommand.Create(issuePresenceObservable) .WithSubscription(_ => Assignees.LoadCommand.ExecuteIfCan()); GoToLabelsCommand = ReactiveCommand.Create(issuePresenceObservable) .WithSubscription(_ => Labels.LoadCommand.ExecuteIfCan()); GoToMilestonesCommand = ReactiveCommand.Create(issuePresenceObservable) .WithSubscription(_ => Milestones.LoadCommand.ExecuteIfCan()); _assignedUser = this.WhenAnyValue(x => x.Issue.Assignee) .ToProperty(this, x => x.AssignedUser); _assignedMilestone = this.WhenAnyValue(x => x.Issue.Milestone) .ToProperty(this, x => x.AssignedMilestone); _assignedLabels = this.WhenAnyValue(x => x.Issue.Labels) .ToProperty(this, x => x.AssignedLabels); _isClosed = this.WhenAnyValue(x => x.Issue.State) .Select(x => x == Octokit.ItemState.Closed) .ToProperty(this, x => x.IsClosed); Assignees = new IssueAssigneeViewModel( () => applicationService.GitHubClient.Issue.Assignee.GetForRepository(RepositoryOwner, RepositoryName), () => Task.FromResult(Issue.Assignee), x => UpdateIssue(new Octokit.IssueUpdate { Assignee = x.With(y => y.Login), Milestone = AssignedMilestone.With(y => (int?)y.Number) })); Milestones = new IssueMilestonesViewModel( () => applicationService.GitHubClient.Issue.Milestone.GetForRepository(RepositoryOwner, RepositoryName), () => Task.FromResult(Issue.Milestone), x => UpdateIssue(new Octokit.IssueUpdate { Assignee = AssignedUser.With(y => y.Login), Milestone = x.With(y => (int?)y.Number) })); Labels = new IssueLabelsViewModel( () => applicationService.GitHubClient.Issue.Labels.GetForRepository(RepositoryOwner, RepositoryName), () => Task.FromResult((IReadOnlyList <Octokit.Label>) new ReadOnlyCollection <Octokit.Label>(Issue.Labels.ToList())), x => { var update = new Octokit.IssueUpdate { Assignee = AssignedUser.With(y => y.Login), Milestone = AssignedMilestone.With(y => (int?)y.Number), }; foreach (var label in x.Select(y => y.Name)) { update.AddLabel(label); } return(UpdateIssue(update)); }); _markdownDescription = this.WhenAnyValue(x => x.Issue) .Select(x => ((x == null || string.IsNullOrEmpty(x.Body)) ? null : markdownService.Convert(x.Body))) .ToProperty(this, x => x.MarkdownDescription); LoadCommand = ReactiveCommand.CreateAsyncTask(t => Load(applicationService)); GoToOwnerCommand = ReactiveCommand.Create(this.WhenAnyValue(x => x.Issue).Select(x => x != null)); GoToOwnerCommand.Select(_ => Issue.User).Subscribe(x => { var vm = this.CreateViewModel <UserViewModel>(); vm.Username = x.Login; NavigateTo(vm); }); ToggleStateCommand = ReactiveCommand.CreateAsyncTask(issuePresenceObservable, async t => { try { Issue = await applicationService.GitHubClient.Issue.Update(RepositoryOwner, RepositoryName, Id, new Octokit.IssueUpdate { State = (Issue.State == Octokit.ItemState.Open) ? Octokit.ItemState.Closed : Octokit.ItemState.Open }); } catch (Exception e) { var close = (Issue.State == Octokit.ItemState.Open) ? "close" : "open"; throw new Exception("Unable to " + close + " the item. " + e.Message, e); } }); AddCommentCommand = ReactiveCommand.Create() .WithSubscription(_ => { var vm = this.CreateViewModel <IssueCommentViewModel>(); vm.RepositoryOwner = RepositoryOwner; vm.RepositoryName = RepositoryName; vm.Id = Id; vm.SaveCommand.Subscribe(x => InternalEvents.Add(new IssueCommentItemViewModel(x))); NavigateTo(vm); }); GoToUrlCommand = ReactiveCommand.Create(); GoToUrlCommand.OfType <string>().Subscribe(x => { var vm = this.CreateViewModel <WebBrowserViewModel>(); vm.Url = x; NavigateTo(vm); }); GoToUrlCommand.OfType <Uri>().Subscribe(x => { var vm = this.CreateViewModel <WebBrowserViewModel>(); vm.Url = x.AbsoluteUri; NavigateTo(vm); }); }
public UserViewModel(IApplicationService applicationService) { _applicationService = applicationService; ToggleFollowingCommand = ReactiveCommand.CreateAsyncTask( this.WhenAnyValue(x => x.IsFollowing).Select(x => x.HasValue), t => ToggleFollowing()); GoToGistsCommand = ReactiveCommand.Create(); GoToGistsCommand.Subscribe(_ => { var vm = CreateViewModel <UserGistsViewModel>(); vm.Username = Username; ShowViewModel(vm); }); GoToRepositoriesCommand = ReactiveCommand.Create(); GoToRepositoriesCommand.Subscribe(_ => { var vm = CreateViewModel <UserRepositoriesViewModel>(); vm.Username = Username; ShowViewModel(vm); }); GoToOrganizationsCommand = ReactiveCommand.Create(); GoToOrganizationsCommand.Subscribe(_ => { var vm = CreateViewModel <OrganizationsViewModel>(); vm.Username = Username; ShowViewModel(vm); }); GoToEventsCommand = ReactiveCommand.Create(); GoToEventsCommand.Subscribe(_ => { var vm = CreateViewModel <UserEventsViewModel>(); vm.Username = Username; ShowViewModel(vm); }); GoToFollowingCommand = ReactiveCommand.Create(); GoToFollowingCommand.Subscribe(_ => { var vm = CreateViewModel <UserFollowingsViewModel>(); vm.Username = Username; ShowViewModel(vm); }); GoToFollowersCommand = ReactiveCommand.Create(); GoToFollowersCommand.Subscribe(_ => { var vm = CreateViewModel <UserFollowersViewModel>(); vm.Username = Username; ShowViewModel(vm); }); LoadCommand = ReactiveCommand.CreateAsyncTask(t => { this.RequestModel(applicationService.Client.AuthenticatedUser.IsFollowing(Username), t as bool?, x => IsFollowing = x.Data).FireAndForget(); return(this.RequestModel(applicationService.Client.Users[Username].Get(), t as bool?, response => User = response.Data)); }); }
public RepositoryCollaboratorsViewModel(IApplicationService applicationService) { LoadCommand = ReactiveCommand.CreateAsyncTask(t => Load(applicationService.Client.Users[RepositoryOwner].Repositories[RepositoryName].GetCollaborators(), t as bool?)); }
public override void Init() { var addRepo = new Func <object, Task <Unit> >(o => { Action <string> okAction = url => { m_SettingsManager.Settings.Repositories.Add(url); }; var inputBoxVm = m_ViewModelFactory.CreateInputBoxViewModel("Enter URL of new repository", okAction, s => { }); ShowDialog(inputBoxVm); return(Task.FromResult(Unit.Default)); }); var removeRepo = new Func <object, Task <Unit> >(o => { string url = o as string; m_SettingsManager.Settings.Repositories.Remove(url); return(Task.FromResult(Unit.Default)); }); RepositoryEditorViewModel = new StringCollectionEditorViewModel(m_SettingsManager.Settings.Repositories, addRepo, removeRepo, "Repositories"); RepositoryEditorViewModel.Init(); var addExclusion = new Func <object, Task <Unit> >(o => { Action <string> okAction = packName => { m_SettingsManager.Settings.ExcludedPackages.Add(packName); }; var inputBoxVm = m_ViewModelFactory.CreateInputBoxViewModel("Enter name of excluded package", okAction, s => { }); ShowDialog(inputBoxVm); return(Task.FromResult(Unit.Default)); }); var removeExclusion = new Func <object, Task <Unit> >(o => { string packName = o as string; m_SettingsManager.Settings.ExcludedPackages.Remove(packName); return(Task.FromResult(Unit.Default)); }); ExclusionsEditorViewModel = new StringCollectionEditorViewModel(m_SettingsManager.Settings.ExcludedPackages, addExclusion, removeExclusion, "Excluded packages"); ExclusionsEditorViewModel.Init(); m_GraphManager.Documents.ToObservableChangeSet() .ObserveOnDispatcher() .Transform(CreateGraphViewModel) .Bind(Graphs) .Do(set => { var change = set.FirstOrDefault(); if (change == null) { return; } if (set.Adds > 0) { SwitchTo(change.Item.Current); } else if (set.Removes > 0) { ClearView(); } }) .DisposeMany() .Subscribe() .AddDisposableTo(Disposables); CmdAddNewGraph = ReactiveCommand.CreateAsyncTask(_ => { Action <string> okaction = name => { var graphHandler = m_GraphManager.CreateNewDocument(name); Task.Run(() => { graphHandler.ResolveDependencies(); }); }; Action <string> cancelAction = txt => { }; var inputVm = m_ViewModelFactory.CreateInputBoxViewModel("Enter name of Packge to investigate", okaction, cancelAction); ShowDialog(inputVm); return(Task.FromResult(Unit.Default)); }).AddDisposableTo(Disposables); CmdOpenSolution = ReactiveCommand.CreateAsyncTask(_ => { OpenFileDialog openFileDialog = new OpenFileDialog { Filter = "VS Solution (*.sln) | *.sln|C# Project (*.csproj)|*.csproj|Visual Basic Project (*.vbproj)|*.vbproj|Visual C++ Project (*.vcxproj)|*.vcxproj | All files (*.*)|*.*", Multiselect = false }; var result = openFileDialog.ShowDialog(); if (!result.HasValue || !result.Value) { return(Task.FromResult(false)); } var graphHandler = m_GraphManager.CreateNewDocument(openFileDialog.FileName); Task.Run(() => { graphHandler.ResolveDependencies(); }); return(Task.FromResult(Unit.Default)); }).AddDisposableTo(Disposables); CmdRefreshGraph = ReactiveCommand.CreateAsyncTask(o => { var result = o as ResolutionResult; var graphHandler = m_GraphManager.Documents.FirstOrDefault(handler => handler.Result == result); if (graphHandler == null) { return(Task.FromResult(Unit.Default)); } Task.Run(() => { graphHandler.ResolveDependencies(); }); return(Task.FromResult(Unit.Default)); }).AddDisposableTo(Disposables); CmdCancel = ReactiveCommand.CreateAsyncTask(o => { var result = o as ResolutionResult; var graphHandler = m_GraphManager.Documents.FirstOrDefault(handler => handler.Result == result); if (graphHandler == null) { return(Task.FromResult(Unit.Default)); } graphHandler.Cancel(); return(Task.FromResult(Unit.Default)); }).AddDisposableTo(Disposables); CmdDeleteGraph = ReactiveCommand.CreateAsyncTask(o => { var result = o as ResolutionResult; var graphHandler = m_GraphManager.Documents.FirstOrDefault(handler => handler.Result == result); if (graphHandler == null) { return(Task.FromResult(Unit.Default)); } m_GraphManager.Delete(graphHandler); return(Task.FromResult(Unit.Default)); }).AddDisposableTo(Disposables); }
public AuthenticationViewModel(INavigatableScreen screen = null) { NavigationScreen = (screen ?? Locator.Current.GetService <INavigatableScreen>()); var canLogin = this.WhenAny(x => x.Email, x => x.Password, (e, p) => !string.IsNullOrEmpty(e.Value) && !string.IsNullOrEmpty(p.Value)); Login = ReactiveCommand .CreateAsyncTask(canLogin, async _ => { IsBusy = true; AuthenticationStatus = "started logging..."; Debug.WriteLine(RestofitApiHelper.Address); var client = new HttpClient(NetCache.UserInitiated) { BaseAddress = new Uri(RestofitApiHelper.Address) }; var api = RestService.For <IRestaurantApi>(client); var token = await api.GetToken(Email, Password); AuthenticationStatus = "started authentication..."; Context.AuthenticationManager.AuthenticatedClient = new HttpClient(new AuthenticatedHttpClientHandler(token.access_token)) { BaseAddress = new Uri(RestofitApiHelper.Address) }; var info = await Context.AuthenticationManager.AuthenticatedApi.GetUserInfo(); return(info); }); Login. Subscribe(x => IsBusy = false); Login .ThrownExceptions .Subscribe(ex => { UserError.Throw("Invalid login or password!"); Debug.WriteLine("Error! - " + ex.Message); IsBusy = false; }); #region OpenRegester OpenRegester = ReactiveCommand.Create(); OpenRegester.Subscribe(x => { var viewModel = Locator.Current.GetService <SignUpViewModel>(); if (viewModel == null) { var regViewModel = new SignUpViewModel(NavigationScreen); Locator.CurrentMutable.RegisterConstant(regViewModel, typeof(SignUpViewModel)); NavigationScreen.Navigation.Navigate.Execute(regViewModel); } else { NavigationScreen.Navigation.Navigate.Execute(viewModel); } }); OpenLogin = ReactiveCommand.Create(); OpenLogin.Subscribe(x => { var authenViewModel = Locator.Current.GetService <AuthenticationViewModel>(); NavigationScreen.Navigation.Navigate.Execute(authenViewModel); }); #endregion }
public InjectorClientViewModel() { WatchMask = "*.dll, *.exe"; DiscoveredServiceResponses = new ReactiveList <InjectorHostServiceResponse>(); _discoverer = new InjectorServiceDefinition().CreateServiceDiscoverer(); // TODO: Use CreateDerivedCollection _discoverer .DiscoveredServices .ObserveOn(SynchronizationContext.Current) .Where(svc => !DiscoveredServiceResponses.Any(s => s.ServiceGuid == svc.ServiceGuid)) .Subscribe(svc => DiscoveredServiceResponses.Add(svc)); // can watch when valid path in watchpath var canStartWatching = this.WhenAnyValue(x => x.WatchPath) .Select(x => !String.IsNullOrEmpty(x) && Directory.Exists(x)); // can connect when address and valid port var canConnect = this.WhenAnyValue(x => x.ConnectToAddress, x => x.ConnectToPort, (a, p) => !String.IsNullOrEmpty(a) && !String.IsNullOrEmpty(p) && p.ToCharArray().All(char.IsDigit) && Int32.Parse(p).IsWithinRange(1, 65536)); Connect = ReactiveCommand.CreateAsyncTask(canConnect, async _ => { await _injectorClient.ConnectAsync(ConnectToAddress, Int32.Parse(ConnectToPort)); return(_injectorClient.IsConnected); }); Disconnect = ReactiveCommand.CreateAsyncTask(async _ => { await _injectorClient.DisconnectAsync(); return(_injectorClient.IsConnected); }); StartWatching = ReactiveCommand.CreateAsyncTask(canStartWatching, _ => { _injectorClient.StartWatching(); return(Task.FromResult(_injectorClient.IsWatching)); }); StopWatching = ReactiveCommand.CreateAsyncTask(_ => { _injectorClient.StopWatching(); return(Task.FromResult(_injectorClient.IsWatching)); }); // commands return whether or not watching Observable .Merge(StartWatching, StopWatching) .ToProperty(this, x => x.IsWatching, out _isWatching); // commands return whether or not connected Observable .Merge(Connect, Disconnect) .ToProperty(this, x => x.IsConnected, out _isConnected); // pass through path changes to the injectorclient this.WhenAnyValue(x => x.WatchPath) .BindTo(_injectorClient, c => c.WatchPath); // pass through mask changes to the injectorclient this.WhenAnyValue(x => x.WatchMask) .BindTo(_injectorClient, c => c.WatchMask); // pump out errors // TODO: view needs a usererror handler Observable.Merge( Observable.Merge(Connect.ThrownExceptions, Disconnect.ThrownExceptions), Observable.Merge(StartWatching.ThrownExceptions, StopWatching.ThrownExceptions)) .Subscribe(ex => UserError.Throw("Error", ex)); }
public GistViewModel(IApplicationService applicationService, IShareService shareService) { _applicationService = applicationService; Comments = new ReactiveList <GistCommentModel>(); ShareCommand = ReactiveCommand.Create(this.WhenAnyValue(x => x.Gist).Select(x => x != null)); ShareCommand.Subscribe(_ => shareService.ShareUrl(Gist.HtmlUrl)); ToggleStarCommand = ReactiveCommand.CreateAsyncTask( this.WhenAnyValue(x => x.IsStarred).Select(x => x.HasValue), async t => { try { if (!IsStarred.HasValue) { return; } var request = IsStarred.Value ? _applicationService.Client.Gists[Id].Unstar() : _applicationService.Client.Gists[Id].Star(); await _applicationService.Client.ExecuteAsync(request); IsStarred = !IsStarred.Value; } catch (Exception e) { throw new Exception("Unable to start gist. Please try again.", e); } }); ForkCommand = ReactiveCommand.CreateAsyncTask(async t => { var data = await _applicationService.Client.ExecuteAsync(_applicationService.Client.Gists[Id].ForkGist()); var forkedGist = data.Data; var vm = CreateViewModel <GistViewModel>(); vm.Id = forkedGist.Id; vm.Gist = forkedGist; ShowViewModel(vm); }); GoToViewableFileCommand = ReactiveCommand.Create(); GoToViewableFileCommand.OfType <GistFileModel>().Subscribe(x => { var vm = CreateViewModel <GistViewableFileViewModel>(); vm.GistFile = x; ShowViewModel(vm); }); GoToHtmlUrlCommand = ReactiveCommand.Create(this.WhenAnyValue(x => x.Gist).Select(x => x != null && !string.IsNullOrEmpty(x.HtmlUrl))); GoToHtmlUrlCommand.Subscribe(_ => GoToUrlCommand.ExecuteIfCan(Gist.HtmlUrl)); GoToFileSourceCommand = ReactiveCommand.Create(); GoToFileSourceCommand.OfType <GistFileModel>().Subscribe(x => { var vm = CreateViewModel <GistFileViewModel>(); vm.Id = Id; vm.GistFile = x; vm.Filename = x.Filename; ShowViewModel(vm); }); GoToUserCommand = ReactiveCommand.Create(this.WhenAnyValue(x => x.Gist).Select(x => x != null)); GoToUserCommand.Subscribe(x => { var vm = CreateViewModel <UserViewModel>(); vm.Username = Gist.Owner.Login; ShowViewModel(vm); }); GoToForksCommand = ReactiveCommand.Create(); LoadCommand = ReactiveCommand.CreateAsyncTask(t => { var forceCacheInvalidation = t as bool?; var t1 = this.RequestModel(_applicationService.Client.Gists[Id].Get(), forceCacheInvalidation, response => Gist = response.Data); this.RequestModel(_applicationService.Client.Gists[Id].IsGistStarred(), forceCacheInvalidation, response => IsStarred = response.Data).FireAndForget(); Comments.SimpleCollectionLoad(_applicationService.Client.Gists[Id].GetComments(), forceCacheInvalidation).FireAndForget(); return(t1); }); }
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); }); }
/// <summary> /// Initializes a new instance of the MainWindowViewModel class. /// </summary> /// <param name="dialogService">Service for view model friendly dialogs</param> /// <param name="dataReader">Service for reading raw files, id files, and feature files</param> public MainWindowViewModel(IMainDialogService dialogService, IDataReader dataReader) { this.dialogService = dialogService; this.dataReader = dataReader; // Initialize child view models this.DataSets = new ReactiveList <DataSetViewModel> { ChangeTrackingEnabled = true }; this.CreateSequenceViewModel = new CreateSequenceViewModel(this.dialogService); this.ScanViewModel = new ScanViewModel(this.dialogService, new List <PrSm>()); // Remove filter by unidentified scans from ScanViewModel filters this.ScanViewModel.Filters.Remove(this.ScanViewModel.Filters.FirstOrDefault(f => f.Name == "Hide Unidentified Scans")); // Create commands for file operations this.OpenDataSetCommand = ReactiveCommand.CreateAsyncTask(async _ => await this.OpenDataSetImplementation()); this.OpenRawFileCommand = ReactiveCommand.CreateAsyncTask(async _ => await this.OpenRawFileImplementation()); this.OpenTsvFileCommand = ReactiveCommand.CreateAsyncTask(async _ => await this.OpenIdFileImplementation()); this.OpenFeatureFileCommand = ReactiveCommand.CreateAsyncTask(async _ => await this.OpenFeatureFileImplementation()); this.OpenFromDmsCommand = ReactiveCommand.CreateAsyncTask(async _ => await this.OpenFromDmsImplementation()); // Create command to open settings window var openSettingsCommand = ReactiveCommand.Create(); openSettingsCommand.Subscribe(_ => this.dialogService.OpenSettings(new SettingsViewModel(this.dialogService))); this.OpenSettingsCommand = openSettingsCommand; // Create command to opne isotopic profile viewer this.OpenIsotopicProfileViewerCommand = ReactiveCommand.Create(); this.OpenIsotopicProfileViewerCommand.Subscribe(this.OpenIsotopicProfileViewer); //this.OpenIsotopicProfileViewer(new object()); // Create command to open about box var openAboutBoxCommand = ReactiveCommand.Create(); openAboutBoxCommand.Subscribe(_ => this.dialogService.OpenAboutBox()); this.OpenAboutBoxCommand = openAboutBoxCommand; // Create command to open new modification management window var openManageModificationsCommand = ReactiveCommand.Create(); openManageModificationsCommand.Subscribe(_ => this.ManageModificationsImplementation()); this.OpenManageModificationsCommand = openManageModificationsCommand; // Create MSPathFinder search command var runMsPathFinderSearchCommand = ReactiveCommand.Create(); runMsPathFinderSearchCommand.Subscribe(_ => this.RunMsPathFinderSearchImplementation()); this.RunMsPathFinderSearchCommand = runMsPathFinderSearchCommand; // Create export command var exportResultsCommand = ReactiveCommand.Create(this.DataSets.WhenAnyValue(x => x.Count).Select(count => count > 0)); exportResultsCommand.Subscribe(_ => this.ExportResultsImplementation()); this.ExportResultsCommand = exportResultsCommand; // Create export command var quitProgramCommand = ReactiveCommand.Create(); quitProgramCommand.Subscribe(_ => this.dialogService.QuitProgram()); this.QuitProgramCommand = quitProgramCommand; this.ShowSplash = true; // When a data set sets its ReadyToClose property to true, remove it from dataset list this.DataSets.ItemChanged.Where(x => x.PropertyName == "ReadyToClose") .Select(x => x.Sender).Where(sender => sender.ReadyToClose) .Subscribe(dataSet => { this.ScanViewModel.RemovePrSmsFromRawFile(dataSet.Title); this.DataSets.Remove(dataSet); }); // If all datasets are closed, show splash screen this.DataSets.BeforeItemsRemoved.Subscribe(x => this.ShowSplash = this.DataSets.Count == 1); // If a dataset is opened, show splash screen this.DataSets.BeforeItemsAdded.Subscribe(x => this.ShowSplash = false); // When the data reader is reading an ID file, show the loading screen this.dataReader.WhenAnyValue(x => x.ReadingIdFiles) .Subscribe(readingIdFiles => this.IdFileLoading = readingIdFiles); // When a PrSm is selected in the Protein Tree, make all data sets show the PrSm this.ScanViewModel.WhenAnyValue(x => x.SelectedPrSm) .Where(selectedPrSm => selectedPrSm != null) .Subscribe(selectedPrSm => { foreach (var dataSet in this.DataSets) { dataSet.SelectedPrSm = selectedPrSm; } }); // Warm up InformedProteomics Averagine using arbitrary mass Task.Run(() => Averagine.GetIsotopomerEnvelopeFromNominalMass(50000)); }
public KibanaInstallationModel( IWixStateProvider wixStateProvider, IServiceStateProvider serviceStateProvider, IPluginStateProvider pluginStateProvider, IKibanaEnvironmentStateProvider environmentStateProvider, ISession session, string[] args ) : base(wixStateProvider, session, args) { var versionConfig = new VersionConfiguration(wixStateProvider, this.Session.IsInstalled); this.KibanaEnvironmentState = environmentStateProvider; this.LocationsModel = new LocationsModel(versionConfig); this.NoticeModel = new NoticeModel(versionConfig, serviceStateProvider, this.LocationsModel); this.ServiceModel = new ServiceModel(serviceStateProvider, versionConfig); this.ConfigurationModel = new ConfigurationModel(); this.ConnectingModel = new ConnectingModel(); var pluginDependencies = this.WhenAnyValue( vm => vm.NoticeModel.AlreadyInstalled, vm => vm.LocationsModel.InstallDir, vm => vm.LocationsModel.ConfigDirectory ); this.PluginsModel = new PluginsModel(pluginStateProvider, pluginDependencies); var isUpgrade = versionConfig.InstallationDirection == InstallationDirection.Up; var observeHost = this.WhenAnyValue(x => x.ConfigurationModel.HostName, x => x.ConfigurationModel.HttpPort, (h, p) => $"http://{(string.IsNullOrWhiteSpace(h) ? "localhost" : h)}:{p}"); var observeInstallationLog = this.WhenAnyValue(vm => vm.MsiLogFileLocation); var observeKibanaLog = this.WhenAnyValue(vm => vm.LocationsModel.KibanaLog); var observeInstallXPack = this.PluginsModel.AvailablePlugins.ItemChanged .Where(x => x.PropertyName == nameof(Plugin.Selected) && x.Sender.PluginType == PluginType.XPack) .Select(x => x.Sender.Selected); this.ClosingModel = new ClosingModel(wixStateProvider.CurrentVersion, isUpgrade, observeHost, observeInstallationLog, observeKibanaLog, observeInstallXPack, serviceStateProvider); this.AllSteps = new ReactiveList <IStep> { this.NoticeModel, this.LocationsModel, this.ServiceModel, this.ConfigurationModel, this.ConnectingModel, this.PluginsModel, this.ClosingModel }; this.Steps = this.AllSteps.CreateDerivedCollection(x => x, x => x.IsRelevant); var observeValidationChanges = this.WhenAny( vm => vm.NoticeModel.ValidationFailures, vm => vm.LocationsModel.ValidationFailures, vm => vm.PluginsModel.ValidationFailures, vm => vm.ServiceModel.ValidationFailures, vm => vm.ConfigurationModel.ValidationFailures, vm => vm.ConnectingModel.ValidationFailures, vm => vm.ClosingModel.ValidationFailures, vm => vm.TabSelectedIndex, (notice, locations, plugins, service, config, connecting, closing, index) => { var firstInvalidScreen = this.Steps.FirstOrDefault(s => !s.IsValid) ?? this.ClosingModel; return(firstInvalidScreen); }); observeValidationChanges .Subscribe(selected => { var step = this.Steps[this.TabSelectedIndex]; var failures = step.ValidationFailures; this.CurrentStepValidationFailures = selected.ValidationFailures; }); this.WhenAny( vm => vm.NoticeModel.IsValid, vm => vm.LocationsModel.IsValid, vm => vm.PluginsModel.IsValid, vm => vm.ServiceModel.IsValid, vm => vm.ConfigurationModel.IsValid, vm => vm.ConnectingModel.IsValid, vm => vm.ClosingModel.IsValid, (notice, locations, plugins, service, config, connecting, closing) => { var firstInvalidScreen = this.Steps.Select((s, i) => new { s, i }).FirstOrDefault(s => !s.s.IsValid); return(firstInvalidScreen?.i ?? (this.Steps.Count - 1)); }) .Subscribe(selected => { this.TabSelectionMax = selected; //if one of the steps prior to the current selection is invalid jump back if (this.TabSelectedIndex > this.TabSelectionMax) { this.TabSelectedIndex = this.TabSelectionMax; } this.CurrentStepValidationFailures = this.ActiveStep.ValidationFailures; }); this.Install = ReactiveCommand.CreateAsyncTask(observeValidationChanges.Select(s => s.IsValid), _ => { this.TabSelectedIndex += 1; return(this.InstallUITask()); }); this.Install.Subscribe(installationObservable => { installationObservable.Subscribe(installed => { this.ClosingModel.Installed = installed; }); }); this.Refresh(); //validate the first stab explicitly on constructing this //main viewmodel. WPF triggers a validation already this.ParsedArguments = new KibanaArgumentParser( this.AllSteps.Cast <IValidatableReactiveObject>().Concat(new[] { this }).ToList(), args); this.ActiveStep.Validate(); }
public InstallationModel( IWixStateProvider wixStateProvider, JavaConfiguration javaConfiguration, IElasticsearchEnvironmentStateProvider environmentStateProvider, IServiceStateProvider serviceStateProvider, IPluginStateProvider pluginStateProvider, ElasticsearchYamlConfiguration yamlConfiguration, LocalJvmOptionsConfiguration localJvmOptions, ISession session, string[] args ) { this.Session = session; if (wixStateProvider == null) { throw new ArgumentNullException(nameof(wixStateProvider)); } if (javaConfiguration == null) { throw new ArgumentNullException(nameof(javaConfiguration)); } this._wixStateProvider = wixStateProvider; this.JavaConfiguration = javaConfiguration; this.ElasticsearchEnvironmentState = environmentStateProvider; this._yamlConfiguration = yamlConfiguration; var versionConfig = new VersionConfiguration(wixStateProvider); this.SameVersionAlreadyInstalled = versionConfig.SameVersionAlreadyInstalled; this.HigherVersionAlreadyInstalled = versionConfig.HigherVersionAlreadyInstalled; this.LocationsModel = new LocationsModel(environmentStateProvider, yamlConfiguration, versionConfig); this.NoticeModel = new NoticeModel(versionConfig, serviceStateProvider, this.LocationsModel); this.ServiceModel = new ServiceModel(serviceStateProvider, versionConfig); this.ConfigurationModel = new ConfigurationModel(yamlConfiguration, localJvmOptions); var pluginDependencies = this.WhenAnyValue( vm => vm.ConfigurationModel.IngestNode, vm => vm.NoticeModel.AlreadyInstalled, vm => vm.LocationsModel.InstallDir, vm => vm.LocationsModel.ConfigDirectory ); this.PluginsModel = new PluginsModel(pluginStateProvider, pluginDependencies); var observeHost = this.WhenAnyValue(vm => vm.ConfigurationModel.NetworkHost, vm => vm.ConfigurationModel.HttpPort, (h, p) => $"http://{(string.IsNullOrWhiteSpace(h) ? "localhost" : h)}:{p}"); var observeLog = this.WhenAnyValue(vm => vm.MsiLogFileLocation); var observeElasticsearchLog = this.WhenAnyValue(vm => vm.LocationsModel.ElasticsearchLog); var isUpgrade = versionConfig.InstallationDirection == InstallationDirection.Up; this.ClosingModel = new ClosingModel(wixStateProvider.CurrentVersion, isUpgrade, observeHost, observeLog, observeElasticsearchLog, serviceStateProvider); this.AllSteps = new ReactiveList <IStep> { this.NoticeModel, this.LocationsModel, this.ServiceModel, this.ConfigurationModel, this.PluginsModel, this.ClosingModel }; this.Steps = this.AllSteps.CreateDerivedCollection(x => x, x => x.IsRelevant); this.NextButtonText = TextResources.SetupView_NextText; var canMoveForwards = this.WhenAny(vm => vm.TabSelectedIndex, vm => vm.TabSelectionMax, (i, max) => i.GetValue() < max.GetValue()); this.Next = ReactiveCommand.Create(canMoveForwards); this.Next.Subscribe(i => { this.TabSelectedIndex = Math.Min(this.Steps.Count - 1, this.TabSelectedIndex + 1); }); var canMoveBackwards = this.WhenAny(vm => vm.TabSelectedIndex, (i) => i.GetValue() > 0); this.Back = ReactiveCommand.Create(canMoveBackwards); this.Back.Subscribe(i => { this.TabSelectedIndex = Math.Max(0, this.TabSelectedIndex - 1); }); this.Help = ReactiveCommand.Create(); this.ShowLicenseBlurb = ReactiveCommand.Create(); this.ShowCurrentStepErrors = ReactiveCommand.Create(); this.RefreshCurrentStep = ReactiveCommand.Create(); this.RefreshCurrentStep.Subscribe(x => { this.Steps[this.TabSelectedIndex].Refresh(); }); this.Exit = ReactiveCommand.Create(); var observeValidationChanges = this.WhenAny( vm => vm.NoticeModel.ValidationFailures, vm => vm.LocationsModel.ValidationFailures, vm => vm.ConfigurationModel.ValidationFailures, vm => vm.PluginsModel.ValidationFailures, vm => vm.ServiceModel.ValidationFailures, vm => vm.ClosingModel.ValidationFailures, vm => vm.TabSelectedIndex, (welcome, locations, configuration, plugins, service, install, index) => { var firstInvalidScreen = this.Steps.FirstOrDefault(s => !s.IsValid) ?? this.ClosingModel; return(firstInvalidScreen); }); var canInstall = observeValidationChanges.Select(s => s.IsValid); this.Install = ReactiveCommand.CreateAsyncTask(canInstall, _ => { this.TabSelectedIndex += 1; return(this.InstallUITask()); }); this.Install.Subscribe(installationObservable => { installationObservable.Subscribe(installed => { this.ClosingModel.Installed = installed; }); }); this.WhenAny(vm => vm.TabSelectedIndex, v => v.GetValue()) .Subscribe(i => { var c = this.Steps.Count; if (i == (c - 1)) { this.NextButtonText = TextResources.SetupView_ExitText; } else if (i == (c - 2)) { this.NextButtonText = TextResources.SetupView_InstallText; } else { this.NextButtonText = TextResources.SetupView_NextText; } }); observeValidationChanges .Subscribe(selected => { var step = this.Steps[this.TabSelectedIndex]; var failures = step.ValidationFailures; this.CurrentStepValidationFailures = selected.ValidationFailures; }); this.WhenAny( vm => vm.NoticeModel.IsValid, vm => vm.LocationsModel.IsValid, vm => vm.ConfigurationModel.IsValid, vm => vm.PluginsModel.IsValid, vm => vm.ServiceModel.IsValid, vm => vm.ClosingModel.IsValid, (welcome, locations, configuration, plugins, service, install) => { var firstInvalidScreen = this.Steps.Select((s, i) => new { s, i }).FirstOrDefault(s => !s.s.IsValid); return(firstInvalidScreen?.i ?? (this.Steps.Count - 1)); }) .Subscribe(selected => { this.TabSelectionMax = selected; //if one of the steps prior to the current selection is invalid jump back if (this.TabSelectedIndex > this.TabSelectionMax) { this.TabSelectedIndex = this.TabSelectionMax; } this.CurrentStepValidationFailures = this.ActiveStep.ValidationFailures; }); this.WhenAnyValue(view => view.ValidationFailures) .Subscribe(failures => { this.PrequisiteFailures = (failures ?? Enumerable.Empty <ValidationFailure>()) .Where(v => _prerequisiteProperties.Contains(v.PropertyName)) .ToList(); }); this.Refresh(); //validate the first stab explicitly on constructing this //main viewmodel. WPF triggers a validation already this.ParsedArguments = new InstallationModelArgumentParser(this.AllSteps.Cast <IValidatableReactiveObject>().Concat(new[] { this }).ToList(), args); this.ActiveStep.Validate(); }
public ElasticsearchInstallationModel( IWixStateProvider wixStateProvider, JavaConfiguration javaConfiguration, ElasticsearchEnvironmentConfiguration elasticsearchEnvironmentConfiguration, IServiceStateProvider serviceStateProvider, IPluginStateProvider pluginStateProvider, ElasticsearchYamlConfiguration yamlConfiguration, LocalJvmOptionsConfiguration localJvmOptions, TempDirectoryConfiguration tempDirectoryConfiguration, IFileSystem fileSystem, ISession session, string[] args) : base(wixStateProvider, session, args) { this.JavaConfiguration = javaConfiguration ?? throw new ArgumentNullException(nameof(javaConfiguration)); this.ElasticsearchEnvironmentConfiguration = elasticsearchEnvironmentConfiguration; this.TempDirectoryConfiguration = tempDirectoryConfiguration; this._yamlConfiguration = yamlConfiguration; var versionConfig = new VersionConfiguration(wixStateProvider, this.Session.IsInstalled); this.SameVersionAlreadyInstalled = versionConfig.SameVersionAlreadyInstalled; this.UnInstalling = this.Session.IsUninstalling; this.InstallationInProgress = this._wixStateProvider.InstallationInProgress; this.Installing = this.Session.IsInstalling; this.Installed = this.Session.IsInstalled; this.Upgrading = this.Session.IsUpgrading; this.HigherVersionAlreadyInstalled = versionConfig.HigherVersionAlreadyInstalled; this.LocationsModel = new LocationsModel(elasticsearchEnvironmentConfiguration, yamlConfiguration, versionConfig, fileSystem); this.ServiceModel = new ServiceModel(serviceStateProvider, versionConfig); this.NoticeModel = new NoticeModel(versionConfig, serviceStateProvider, this.LocationsModel, this.ServiceModel); this.ConfigurationModel = new ConfigurationModel(yamlConfiguration, localJvmOptions); var pluginDependencies = this.WhenAnyValue( vm => vm.NoticeModel.ExistingVersionInstalled, vm => vm.LocationsModel.PreviousInstallationDirectory, vm => vm.LocationsModel.ConfigDirectory ); this.PluginsModel = new PluginsModel(pluginStateProvider, versionConfig.CurrentVersion, pluginDependencies); var upgradeFromXPackPlugin = this.WhenAnyValue(vm => vm.PluginsModel.PreviousInstallationHasXPack); var canAutomaticallySetup = this.WhenAnyValue(vm => vm.ServiceModel.StartAfterInstall, vm => vm.ServiceModel.InstallAsService) .Select(t => t.Item1 && t.Item2); this.XPackModel = new XPackModel(versionConfig, canAutomaticallySetup, upgradeFromXPackPlugin); var isUpgrade = versionConfig.InstallationDirection == InstallationDirection.Up; var observeHost = this.WhenAnyValue(vm => vm.ConfigurationModel.NetworkHost, vm => vm.ConfigurationModel.HttpPort, (h, p) => $"http://{(string.IsNullOrWhiteSpace(h) ? "localhost" : h)}:{p}"); var observeInstallationLog = this.WhenAnyValue(vm => vm.MsiLogFileLocation); var observeElasticsearchLog = this.WhenAnyValue(vm => vm.LocationsModel.ElasticsearchLog); this.ClosingModel = new ClosingModel(wixStateProvider.CurrentVersion, isUpgrade, observeHost, observeInstallationLog, observeElasticsearchLog, serviceStateProvider); this.AllSteps.AddRange(new List <IStep> { this.NoticeModel, this.LocationsModel, this.ServiceModel, this.ConfigurationModel, this.PluginsModel, this.XPackModel, this.ClosingModel }); this.AllSteps.ChangeTrackingEnabled = true; var observeValidationChanges = this.WhenAny( vm => vm.NoticeModel.ValidationFailures, vm => vm.LocationsModel.ValidationFailures, vm => vm.ConfigurationModel.ValidationFailures, vm => vm.PluginsModel.ValidationFailures, vm => vm.XPackModel.ValidationFailures, vm => vm.ServiceModel.ValidationFailures, vm => vm.ClosingModel.ValidationFailures, vm => vm.TabSelectedIndex, (welcome, locations, configuration, plugins, xpack, service, install, index) => { var firstInvalidScreen = this.Steps.FirstOrDefault(s => !s.IsValid) ?? this.ClosingModel; return(firstInvalidScreen); }); observeValidationChanges .Subscribe(firstInvalidStep => { this.TabFirstInvalidIndex = this.Steps .Select((s, i) => new { s, i = (int?)i }) .Where(t => !t.s.IsValid) .Select(t => t.i) .FirstOrDefault(); this.FirstInvalidStepValidationFailures = firstInvalidStep.ValidationFailures; }); this.WhenAny( vm => vm.NoticeModel.IsValid, vm => vm.LocationsModel.IsValid, vm => vm.ConfigurationModel.IsValid, vm => vm.PluginsModel.IsValid, vm => vm.XPackModel.IsValid, vm => vm.ServiceModel.IsValid, vm => vm.ClosingModel.IsValid, (welcome, locations, configuration, plugins, xpack, service, install) => { var firstInvalidScreen = this.Steps.Select((s, i) => new { s, i }).FirstOrDefault(s => !s.s.IsValid); return(firstInvalidScreen?.i ?? (this.Steps.Count - 1)); }) .Subscribe(selected => { this.TabSelectionMax = selected; //if one of the steps prior to the current selection is invalid jump back if (this.TabSelectedIndex > this.TabSelectionMax) { this.TabSelectedIndex = this.TabSelectionMax; } this.FirstInvalidStepValidationFailures = this.ActiveStep.ValidationFailures; }); this.Steps.Changed.Subscribe(e => { var firstInvalidScreen = this.Steps.Select((s, i) => new { s, i }).FirstOrDefault(s => !s.s.IsValid); var selectedTabIndex = firstInvalidScreen?.i ?? (this.Steps.Count - 1); this.TabSelectionMax = selectedTabIndex; //if one of the steps prior to the current selection is invalid jump back if (this.TabSelectedIndex > this.TabSelectionMax) { this.TabSelectedIndex = this.TabSelectionMax; } this.FirstInvalidStepValidationFailures = this.ActiveStep.ValidationFailures; }); this.Install = ReactiveCommand.CreateAsyncTask(observeValidationChanges.Select(s => s.IsValid), _ => { this.TabSelectedIndex += 1; return(this.InstallUITask()); }); this.Install.Subscribe(installationObservable => { installationObservable.Subscribe(installed => this.ClosingModel.Installed = installed); }); this.Refresh(); //validate the first stab explicitly on constructing this //main viewmodel. WPF triggers a validation already this.ParsedArguments = new ElasticsearchArgumentParser( this.AllSteps.Cast <IValidatableReactiveObject>().Concat(new[] { this }).ToList(), args); this.ActiveStep.Validate(); }
public ProfileViewModel(IApplicationService applicationService, INetworkActivityService networkActivity, IFeaturesService featuresService) { StumbleHistory = new ReactiveList <StumbledRepository>(); GoToInterestsCommand = ReactiveCommand.Create(); Username = applicationService.Account.Username; Action updateStumbled = () => { var stumbledRepositories = applicationService.Account.StumbledRepositories.Count(); Interests = applicationService.Account.Interests.Count(); Likes = applicationService.Account.StumbledRepositories.LikedRepositories(); Dislikes = applicationService.Account.StumbledRepositories.DislikedRepositories(); HasMoreHistory = stumbledRepositories > 30; if (stumbledRepositories != StumbledRepositories) { StumbledRepositories = stumbledRepositories; StumbleHistory.Reset(applicationService.Account.StumbledRepositories.Query.OrderByDescending(x => x.CreatedAt).Take(30)); } }; this.WhenActivated(d => { if (applicationService.Account != null) { updateStumbled(); d(applicationService.RepositoryAdded .Buffer(TimeSpan.FromSeconds(5)) .Where(x => x.Count > 0) .ObserveOn(SynchronizationContext.Current) .Subscribe(x => updateStumbled())); } CanPurchase = !featuresService.ProEditionEnabled; }); GoToRepositoryCommand = ReactiveCommand.Create(); GoToRepositoryCommand.OfType <StumbledRepository>().Subscribe(x => { var vm = CreateViewModel <RepositoryViewModel>(); vm.RepositoryIdentifier = new BaseRepositoryViewModel.RepositoryIdentifierModel(x.Owner, x.Name); ShowViewModel(vm); }); GoToPurchaseCommand = ReactiveCommand.Create(); GoToPurchaseCommand.Subscribe(_ => CreateAndShowViewModel <PurchaseProViewModel>()); GoToHistoryCommand = ReactiveCommand.Create(); GoToHistoryCommand.Subscribe(_ => CreateAndShowViewModel <HistoryViewModel>()); GoToLikesCommand = ReactiveCommand.Create(); GoToLikesCommand.Subscribe(_ => CreateAndShowViewModel <LikedRepositoriesViewModel>()); GoToDislikesCommand = ReactiveCommand.Create(); GoToDislikesCommand.Subscribe(_ => CreateAndShowViewModel <DislikedRepositoriesViewModel>()); GoToSettingsCommand = ReactiveCommand.Create(); GoToSettingsCommand.Subscribe(_ => CreateAndShowViewModel <SettingsViewModel>()); LoadCommand = ReactiveCommand.CreateAsyncTask(async t => { User = await applicationService.Client.User.Current(); }); LoadCommand.TriggerNetworkActivity(networkActivity); }
public RepositoryViewModel(IApplicationService applicationService, IAccountsService accountsService, IActionMenuFactory actionMenuService) { ApplicationService = applicationService; _accountsService = accountsService; this.WhenAnyValue(x => x.RepositoryName).Subscribe(x => Title = x); this.WhenAnyValue(x => x.Repository).Subscribe(x => { Stargazers = x != null ? (int?)x.StargazersCount : null; Watchers = x != null ? (int?)x.SubscribersCount : null; }); ToggleStarCommand = ReactiveCommand.CreateAsyncTask( this.WhenAnyValue(x => x.IsStarred).Select(x => x.HasValue), t => ToggleStar()); ToggleWatchCommand = ReactiveCommand.CreateAsyncTask( this.WhenAnyValue(x => x.IsWatched, x => x.HasValue), t => ToggleWatch()); GoToOwnerCommand = ReactiveCommand.Create(this.WhenAnyValue(x => x.Repository).Select(x => x != null)); GoToOwnerCommand.Select(_ => Repository.Owner).Subscribe(x => { if (string.Equals(x.Type, "organization", StringComparison.OrdinalIgnoreCase)) { var vm = this.CreateViewModel <OrganizationViewModel>(); vm.Username = RepositoryOwner; NavigateTo(vm); } else { var vm = this.CreateViewModel <UserViewModel>(); vm.Username = RepositoryOwner; NavigateTo(vm); } }); PinCommand = ReactiveCommand.Create(this.WhenAnyValue(x => x.Repository).Select(x => x != null)); PinCommand.Subscribe(x => PinRepository()); GoToForkParentCommand = ReactiveCommand.Create(this.WhenAnyValue(x => x.Repository, x => x != null && x.Fork && x.Parent != null)); GoToForkParentCommand.Subscribe(x => { var vm = this.CreateViewModel <RepositoryViewModel>(); vm.RepositoryOwner = Repository.Parent.Owner.Login; vm.RepositoryName = Repository.Parent.Name; vm.Repository = Repository.Parent; NavigateTo(vm); }); GoToStargazersCommand = ReactiveCommand.Create(); GoToStargazersCommand.Subscribe(_ => { var vm = this.CreateViewModel <RepositoryStargazersViewModel>(); vm.RepositoryOwner = RepositoryOwner; vm.RepositoryName = RepositoryName; NavigateTo(vm); }); GoToWatchersCommand = ReactiveCommand.Create(); GoToWatchersCommand.Subscribe(_ => { var vm = this.CreateViewModel <RepositoryWatchersViewModel>(); vm.RepositoryOwner = RepositoryOwner; vm.RepositoryName = RepositoryName; NavigateTo(vm); }); GoToEventsCommand = ReactiveCommand.Create(); GoToEventsCommand.Subscribe(_ => { var vm = this.CreateViewModel <RepositoryEventsViewModel>(); vm.RepositoryOwner = RepositoryOwner; vm.RepositoryName = RepositoryName; NavigateTo(vm); }); GoToIssuesCommand = ReactiveCommand.Create(); GoToIssuesCommand.Subscribe(_ => { var vm = this.CreateViewModel <IssuesViewModel>(); vm.RepositoryOwner = RepositoryOwner; vm.RepositoryName = RepositoryName; NavigateTo(vm); }); GoToReadmeCommand = ReactiveCommand.Create(); GoToReadmeCommand.Subscribe(_ => { var vm = this.CreateViewModel <ReadmeViewModel>(); vm.RepositoryOwner = RepositoryOwner; vm.RepositoryName = RepositoryName; NavigateTo(vm); }); GoToBranchesCommand = ReactiveCommand.Create().WithSubscription(_ => { var vm = this.CreateViewModel <CommitBranchesViewModel>(); vm.RepositoryOwner = RepositoryOwner; vm.RepositoryName = RepositoryName; NavigateTo(vm); }); GoToCommitsCommand = ReactiveCommand.Create(); GoToCommitsCommand.Subscribe(_ => { if (Branches != null && Branches.Count == 1) { var vm = this.CreateViewModel <CommitsViewModel>(); vm.RepositoryOwner = RepositoryOwner; vm.RepositoryName = RepositoryName; vm.Branch = Repository == null ? null : Repository.DefaultBranch; NavigateTo(vm); } else { GoToBranchesCommand.ExecuteIfCan(); } }); GoToPullRequestsCommand = ReactiveCommand.Create(); GoToPullRequestsCommand.Subscribe(_ => { var vm = this.CreateViewModel <PullRequestsViewModel>(); vm.RepositoryOwner = RepositoryOwner; vm.RepositoryName = RepositoryName; NavigateTo(vm); }); GoToSourceCommand = ReactiveCommand.Create(); GoToSourceCommand.Subscribe(_ => { var vm = this.CreateViewModel <BranchesAndTagsViewModel>(); vm.RepositoryOwner = RepositoryOwner; vm.RepositoryName = RepositoryName; NavigateTo(vm); }); GoToContributors = ReactiveCommand.Create(); GoToContributors.Subscribe(_ => { var vm = this.CreateViewModel <RepositoryContributorsViewModel>(); vm.RepositoryOwner = RepositoryOwner; vm.RepositoryName = RepositoryName; NavigateTo(vm); }); GoToForksCommand = ReactiveCommand.Create().WithSubscription(_ => { var vm = this.CreateViewModel <RepositoryForksViewModel>(); vm.RepositoryOwner = RepositoryOwner; vm.RepositoryName = RepositoryName; NavigateTo(vm); }); GoToReleasesCommand = ReactiveCommand.Create().WithSubscription(_ => { var vm = this.CreateViewModel <ReleasesViewModel>(); vm.RepositoryOwner = RepositoryOwner; vm.RepositoryName = RepositoryName; NavigateTo(vm); }); ShowMenuCommand = ReactiveCommand.CreateAsyncTask( this.WhenAnyValue(x => x.Repository, x => x.IsStarred, x => x.IsWatched) .Select(x => x.Item1 != null && x.Item2 != null && x.Item3 != null), _ => { var menu = actionMenuService.Create(Title); menu.AddButton(IsPinned ? "Unpin from Slideout Menu" : "Pin to Slideout Menu", PinCommand); menu.AddButton(IsStarred.Value ? "Unstar This Repo" : "Star This Repo", ToggleStarCommand); menu.AddButton(IsWatched.Value ? "Unwatch This Repo" : "Watch This Repo", ToggleWatchCommand); menu.AddButton("Show in GitHub", GoToHtmlUrlCommand); return(menu.Show()); }); var gotoWebUrl = new Action <string>(x => { var vm = this.CreateViewModel <WebBrowserViewModel>(); vm.Url = x; NavigateTo(vm); }); GoToHtmlUrlCommand = ReactiveCommand.Create(this.WhenAnyValue(x => x.Repository, x => x != null && !string.IsNullOrEmpty(x.HtmlUrl))); GoToHtmlUrlCommand.Select(_ => Repository.HtmlUrl).Subscribe(gotoWebUrl); GoToHomepageCommand = ReactiveCommand.Create(this.WhenAnyValue(x => x.Repository, x => x != null && !string.IsNullOrEmpty(x.Homepage))); GoToHomepageCommand.Select(_ => Repository.Homepage).Subscribe(gotoWebUrl); LoadCommand = ReactiveCommand.CreateAsyncTask(t => { var forceCacheInvalidation = t as bool?; var t1 = this.RequestModel(ApplicationService.Client.Users[RepositoryOwner].Repositories[RepositoryName].Get(), forceCacheInvalidation, response => Repository = response.Data); this.RequestModel(ApplicationService.Client.Users[RepositoryOwner].Repositories[RepositoryName].GetReadme(), forceCacheInvalidation, response => Readme = response.Data); this.RequestModel(ApplicationService.Client.Users[RepositoryOwner].Repositories[RepositoryName].GetBranches(), forceCacheInvalidation, response => Branches = response.Data); this.RequestModel(ApplicationService.Client.Users[RepositoryOwner].Repositories[RepositoryName].IsWatching(), forceCacheInvalidation, response => IsWatched = response.Data); this.RequestModel(ApplicationService.Client.Users[RepositoryOwner].Repositories[RepositoryName].IsStarred(), forceCacheInvalidation, response => IsStarred = response.Data); this.RequestModel(ApplicationService.Client.Users[RepositoryOwner].Repositories[RepositoryName].GetContributors(), forceCacheInvalidation, response => Contributors = response.Data.Count); this.RequestModel(ApplicationService.Client.Users[RepositoryOwner].Repositories[RepositoryName].GetLanguages(), forceCacheInvalidation, response => Languages = response.Data.Count); this.RequestModel(ApplicationService.Client.Users[RepositoryOwner].Repositories[RepositoryName].GetReleases(), forceCacheInvalidation, response => Releases = response.Data.Count); return(t1); }); }