Пример #1
0
        protected IssueModifyViewModel(string username, string repository)
        {
            var alertDialogService = Locator.Current.GetService <IAlertDialogService>();

            Username   = username;
            Repository = repository;
            Kind       = "bug";
            Priority   = "major";

            Milestones = new IssueMilestonesViewModel(username, repository);
            Versions   = new IssueVersionsViewModel(username, repository);
            Components = new IssueComponentsViewModel(username, repository);
            Assignee   = new IssueAssigneeViewModel(username, repository);

            SaveCommand = ReactiveCommand.CreateFromTask(
                t => Save(),
                this.WhenAnyValue(x => x.IssueTitle).Select(y => !string.IsNullOrEmpty(y)));

            SaveCommand.BindCommand(DismissCommand);

            DiscardCommand = ReactiveCommand.CreateFromTask(async t =>
            {
                if (Content?.Length > 0 || IssueTitle?.Length > 0)
                {
                    var result = await alertDialogService.PromptYesNo(
                        "Discard Changes", "Are you sure you want to discard your changes?");
                    if (!result)
                    {
                        return;
                    }
                }

                DismissCommand.ExecuteNow();
            });
        }
Пример #2
0
        public NewCommentViewModel(
            Func <string, Task> doneAction,
            IAlertDialogService alertDialogService = null)
        {
            alertDialogService = alertDialogService ?? Locator.Current.GetService <IAlertDialogService>();

            DoneCommand = ReactiveCommand.CreateFromTask(async _ =>
            {
                await doneAction(Text);
                DismissCommand.ExecuteNow();
                Text = string.Empty;
            }, this.WhenAnyValue(x => x.Text).Select(x => x?.Length > 0));

            DiscardCommand = ReactiveCommand.CreateFromTask(async _ =>
            {
                if (Text?.Length > 0)
                {
                    var result = await alertDialogService.PromptYesNo(
                        "Discard Comment", "Are you sure you want to discard this comment?");
                    if (!result)
                    {
                        return;
                    }
                }

                Text = string.Empty;
                DismissCommand.ExecuteNow();
            });
        }
Пример #3
0
        protected override async Task Save()
        {
            if (string.IsNullOrEmpty(Title))
            {
                throw new Exception("Unable to save the issue: you must provide a title!");
            }

            try
            {
                var assignedTo = AssignedTo == null ? null : AssignedTo.Login;
                int?milestone  = null;
                if (Milestone != null)
                {
                    milestone = Milestone.Number;
                }
                var labels  = Labels.Select(x => x.Name).ToArray();
                var content = Content ?? string.Empty;

                var data = await _applicationService.Client.ExecuteAsync(_applicationService.Client.Users[RepositoryOwner].Repositories[RepositoryName].Issues.Create(Title, content, assignedTo, milestone, labels));

                _createdIssueSubject.OnNext(data.Data);
                DismissCommand.ExecuteIfCan();
            }
            catch (Exception e)
            {
                throw new Exception("Unable to save new issue! Please try again.", e);
            }
        }
Пример #4
0
        public GistCreateViewModel(IApplicationService applicationService)
        {
            _applicationService = applicationService;

            Title = "Create Gist";
            Files = new Dictionary <string, string>();

            SaveCommand = ReactiveCommand.CreateAsyncTask(async t =>
            {
                if (_files == null || _files.Count == 0)
                {
                    throw new Exception("You cannot create a Gist without atleast one file! Please correct and try again.");
                }

                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);
                _createdGistSubject.OnNext((await _applicationService.Client.ExecuteAsync(request)).Data);
                DismissCommand.ExecuteIfCan();
            });
        }
Пример #5
0
        protected MarkdownComposerViewModel(IStatusIndicatorService status, IAlertDialogService alert, IJsonHttpClientService jsonClient)
        {
            var saveCommand = ReactiveCommand.CreateAsyncTask(
                this.WhenAnyValue(x => x.Text).Select(x => !string.IsNullOrEmpty(x)),
                t => Save());

            saveCommand.IsExecuting.Where(x => x).Subscribe(_ => status.Show("Saving..."));
            saveCommand.IsExecuting.Where(x => !x).Subscribe(_ => status.Hide());
            saveCommand.Subscribe(x => DismissCommand.ExecuteIfCan());
            SaveCommand = saveCommand;

            PostToImgurCommand =
                ReactiveCommand.CreateAsyncTask(async data =>
            {
                var uploadData = data as byte[];
                if (uploadData == null)
                {
                    throw new Exception("There is no data to upload!");
                }

                return(await jsonClient.Post <ImgurModel>("https://api.imgur.com/3/image",
                                                          new { image = Convert.ToBase64String(uploadData) },
                                                          new Dictionary <string, string> {
                    { "Authorization", "Client-ID " + AuthorizationClientId }
                }));
            });

            PostToImgurCommand.IsExecuting.Where(x => x).Subscribe(_ => status.Show("Uploading..."));
            PostToImgurCommand.IsExecuting.Where(x => !x).Subscribe(_ => status.Hide());
            PostToImgurCommand.ThrownExceptions.SubscribeSafe(e => alert.Alert("Error", "Unable to upload image: " + e.Message));
        }
Пример #6
0
        public LoginViewModel(INetworkActivityService networkActivity)
        {
            LoginCommand = ReactiveCommand.CreateAsyncTask(async t =>
            {
                var account = new Account();

                var connection = new Octokit.Connection(new Octokit.ProductHeaderValue("RepoStumble"));
                var client     = new Octokit.OauthClient(connection);
                var token      = await client.CreateAccessToken(new Octokit.OauthTokenRequest(ClientId, ClientSecret, LoginCode));

                connection.Credentials = new Octokit.Credentials(token.AccessToken);
                var githubClient       = new Octokit.GitHubClient(connection);
                var info          = await githubClient.User.Current();
                account.AvatarUrl = info.AvatarUrl;
                account.Username  = info.Login;
                account.Fullname  = info.Name;
                account.OAuth     = token.AccessToken;
                account.Save();

                DismissCommand.ExecuteIfCan();
            });

            LoginCommand.IsExecuting.Skip(1).Where(x => x).Subscribe(x => networkActivity.PushNetworkActive());
            LoginCommand.IsExecuting.Skip(1).Where(x => !x).Subscribe(x => networkActivity.PopNetworkActive());
        }
Пример #7
0
	    protected override async Task Save()
		{
            if (string.IsNullOrEmpty(Title))
                throw new Exception("Issue must have a title!");

			try
			{
				var assignedTo = AssignedTo == null ? null : AssignedTo.Login;
				int? milestone = null;
				if (Milestone != null) 
					milestone = Milestone.Number;
				var labels = Labels.Select(x => x.Name).ToArray();
				var content = Content ?? string.Empty;
				var state = IsOpen ? "open" : "closed";
				var retried = false;

				// For some reason github needs to try again during an internal server error
				tryagain:

				try
				{
                    var data = await _applicationService.Client.ExecuteAsync(_applicationService.Client.Users[RepositoryOwner].Repositories[RepositoryName].Issues[Issue.Number].Update(Title, content, state, assignedTo, milestone, labels));
				    Issue = data.Data;
				}
				catch (GitHubSharp.InternalServerException)
				{
					if (retried)
						throw;

					//Do nothing. Something is wrong with github's service
					retried = true;
					goto tryagain;
				}

				DismissCommand.ExecuteIfCan();
			}
			catch (Exception e)
			{
                throw new Exception("Unable to save the issue! Please try again", e);
			}

//			//There is a wierd bug in GitHub when editing an existing issue and the assignedTo is null
//			catch (GitHubSharp.InternalServerException)
//			{
//				if (ExistingIssue != null && assignedTo == null)
//					tryEditAgain = true;
//				else
//					throw;
//			}
//
//			if (tryEditAgain)
//			{
//				var response = await Application.Client.ExecuteAsync(Application.Client.Users[Username].Repositories[RepoSlug].Issues[ExistingIssue.Number].Update(title, content, state, assignedTo, milestone, labels)); 
//				model = response.Data;
//			}
		}
Пример #8
0
        public EditFileViewModel(ISessionService sessionService, IAlertDialogFactory alertDialogFactory)
        {
            Title = "Edit";

            this.WhenAnyValue(x => x.Path)
            .IsNotNull()
            .Subscribe(x => CommitMessage = "Updated " + x.Substring(x.LastIndexOf('/') + 1));

            this.WhenAnyValue(x => x.Text)
            .Subscribe(x => _lastEdit = DateTime.Now);

            LoadCommand = ReactiveCommand.CreateAsyncTask(async t => {
                var path = Path;
                if (!path.StartsWith("/", StringComparison.Ordinal))
                {
                    path = "/" + path;
                }

                var request      = sessionService.Client.Users[RepositoryOwner].Repositories[RepositoryName].GetContentFile(path, Branch ?? "master");
                request.UseCache = false;
                var data         = await sessionService.Client.ExecuteAsync(request);
                BlobSha          = data.Data.Sha;
                var content      = Convert.FromBase64String(data.Data.Content);
                Text             = System.Text.Encoding.UTF8.GetString(content, 0, content.Length) ?? string.Empty;
                _lastLoad        = DateTime.Now;
            });

            GoToCommitMessageCommand = ReactiveCommand.Create();

            SaveCommand = ReactiveCommand.CreateAsyncTask(
                this.WhenAnyValue(x => x.CommitMessage).Select(x => !string.IsNullOrEmpty(x)), async _ => {
                var path    = Path.TrimStart('/');
                var request = new Octokit.UpdateFileRequest(CommitMessage, Text, BlobSha)
                {
                    Branch = Branch
                };
                using (alertDialogFactory.Activate("Commiting..."))
                    return(await sessionService.GitHubClient.Repository.Content.UpdateFile(RepositoryOwner, RepositoryName, path, request));
            });
            SaveCommand.Subscribe(x => Dismiss());

            DismissCommand = ReactiveCommand.CreateAsyncTask(async t => {
                if (string.IsNullOrEmpty(Text))
                {
                    return(true);
                }
                if (_lastEdit <= _lastLoad)
                {
                    return(true);
                }
                return(await alertDialogFactory.PromptYesNo("Discard Edit?", "Are you sure you want to discard these changes?"));
            });
            DismissCommand.Where(x => x).Subscribe(_ => Dismiss());
        }
Пример #9
0
 public CommitMessageViewModel(IApplicationService applicationService)
 {
     SaveCommand = ReactiveCommand.CreateAsyncTask(
         this.WhenAnyValue(x => x.Message).Select(x => !string.IsNullOrEmpty(x)),
         async _ =>
     {
         var request = applicationService.Client.Users[Username].Repositories[Repository]
                       .UpdateContentFile(Path, Message, Text, BlobSha, Branch);
         var response = await applicationService.Client.ExecuteAsync(request);
         _contentSubject.OnNext(response.Data);
         DismissCommand.ExecuteIfCan();
     });
 }
Пример #10
0
        public AccountsViewModel(IAccountsService accountsService)
        {
            _accountsService = accountsService;

            Title = "Accounts";

            _accounts = new ReactiveList <GitHubAccount>(accountsService.OrderBy(x => x.Username));
            this.WhenActivated(d => _accounts.Reset(accountsService.OrderBy(x => x.Username)));
            Accounts = _accounts.CreateDerivedCollection(CreateAccountItem);

            this.WhenAnyValue(x => x.ActiveAccount)
            .Subscribe(x =>
            {
                foreach (var account in Accounts)
                {
                    account.Selected = Equals(account.Account, x);
                }
            });

            DeleteAccountCommand = ReactiveCommand.Create();
            DeleteAccountCommand.OfType <GitHubAccount>().Subscribe(x =>
            {
                if (Equals(accountsService.ActiveAccount, x))
                {
                    ActiveAccount = null;
                }
                accountsService.Remove(x);
                _accounts.Remove(x);
            });

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

            DismissCommand = ReactiveCommand.Create(this.WhenAnyValue(x => x.ActiveAccount).Select(x => x != null))
                             .WithSubscription(x => base.DismissCommand.ExecuteIfCan(x));

            GoToAddAccountCommand = ReactiveCommand.Create()
                                    .WithSubscription(_ => ShowViewModel(CreateViewModel <NewAccountViewModel>()));
        }
Пример #11
0
        public PurchaseProViewModel(IFeaturesService featuresService)
        {
            var purchaseCommand = ReactiveCommand.CreateAsyncTask(x => featuresService.EnableProEdition());

            purchaseCommand.Subscribe(_ => DismissCommand.ExecuteIfCan());
            PurchaseCommand = purchaseCommand;

            var restoreCommand = ReactiveCommand.CreateAsyncTask(x => featuresService.RestorePurchase());

            restoreCommand.Subscribe(_ => DismissCommand.ExecuteIfCan());
            RestoreCommand = restoreCommand;

            GetPrice(featuresService);
        }
Пример #12
0
        public MyIssuesFilterViewModel(IActionMenuFactory actionMenu)
        {
            Title      = "Filter";
            State      = IssueState.Open;
            SortType   = IssueSort.None;
            FilterType = IssueFilterState.All;

            SaveCommand = ReactiveCommand.CreateAsyncTask(_ => Task.FromResult(new MyIssuesFilterModel(FilterType, State, SortType, Labels, Ascending)));
            SaveCommand.Subscribe(_ => DismissCommand.ExecuteIfCan());
            DismissCommand = ReactiveCommand.Create().WithSubscription(_ => Dismiss());

            SelectStateCommand = ReactiveCommand.CreateAsyncTask(async sender => {
                var options = Enum.GetValues(typeof(IssueState)).Cast <IssueState>().ToList();
                var picker  = actionMenu.CreatePicker();
                foreach (var option in options)
                {
                    picker.Options.Add(option.Humanize());
                }
                picker.SelectedOption = options.IndexOf(State);
                var ret = await picker.Show(sender);
                State   = options[ret];
            });

            SelectSortCommand = ReactiveCommand.CreateAsyncTask(async sender => {
                var options = Enum.GetValues(typeof(IssueSort)).Cast <IssueSort>().ToList();
                var picker  = actionMenu.CreatePicker();
                foreach (var option in options)
                {
                    picker.Options.Add(option.Humanize());
                }
                picker.SelectedOption = options.IndexOf(SortType);
                var ret  = await picker.Show(sender);
                SortType = options[ret];
            });

            SelectFilterTypeCommand = ReactiveCommand.CreateAsyncTask(async sender => {
                var options = Enum.GetValues(typeof(IssueFilterState)).Cast <IssueFilterState>().ToList();
                var picker  = actionMenu.CreatePicker();
                foreach (var option in options)
                {
                    picker.Options.Add(option.Humanize());
                }
                picker.SelectedOption = options.IndexOf(FilterType);
                var ret    = await picker.Show(sender);
                FilterType = options[ret];
            });
        }
Пример #13
0
        public IssueLabelsViewModel(IApplicationService applicationService)
        {
            Labels         = new ReactiveList <LabelModel>();
            SelectedLabels = new ReactiveList <LabelModel>();

            SelectLabelsCommand = ReactiveCommand.CreateAsyncTask(async t =>
            {
                var selectedLabels = t as IEnumerable <LabelModel>;
                if (selectedLabels != null)
                {
                    SelectedLabels.Reset(selectedLabels);
                }

                //If nothing has changed, dont do anything...
                if (OriginalLabels != null && OriginalLabels.Count() == SelectedLabels.Count() &&
                    OriginalLabels.Intersect(SelectedLabels).Count() == SelectedLabels.Count())
                {
                    DismissCommand.ExecuteIfCan();
                    return;
                }

                if (SaveOnSelect)
                {
                    try
                    {
                        var labels = (SelectedLabels != null && SelectedLabels.Count > 0)
                                    ? SelectedLabels.Select(y => y.Name).ToArray() : null;
                        var updateReq =
                            applicationService.Client.Users[RepositoryOwner].Repositories[RepositoryName].Issues[IssueId]
                            .UpdateLabels(labels);
                        await applicationService.Client.ExecuteAsync(updateReq);
                    }
                    catch (Exception e)
                    {
                        throw new Exception("Unable to save labels! Please try again.", e);
                    }
                }

                DismissCommand.ExecuteIfCan();
            });

            LoadCommand = ReactiveCommand.CreateAsyncTask(t =>
                                                          Labels.SimpleCollectionLoad(
                                                              applicationService.Client.Users[RepositoryOwner].Repositories[RepositoryName].Labels.GetAll(),
                                                              t as bool?));
        }
Пример #14
0
        protected DefaultStartupViewModel(IAccountsService accountsService, Type menuViewModelType)
        {
            StartupViews    = new ReactiveCollection <string>();
            AccountsService = accountsService;

            SelectedStartupView = AccountsService.ActiveAccount.DefaultStartupView;
            this.WhenAnyValue(x => x.SelectedStartupView).Skip(1).Subscribe(x =>
            {
                AccountsService.ActiveAccount.DefaultStartupView = x;
                AccountsService.Update(AccountsService.ActiveAccount);
                DismissCommand.ExecuteIfCan();
            });

            StartupViews.Reset(from p in menuViewModelType.GetProperties()
                               let attr = p.GetCustomAttributes(typeof(PotentialStartupViewAttribute), true)
                                          where attr.Length == 1 && attr[0] is PotentialStartupViewAttribute
                                          select((PotentialStartupViewAttribute)attr[0]).Name);
        }
Пример #15
0
        public DefaultStartupViewModel(IAccountsService accountsService)
        {
            AccountsService = accountsService;
            var menuViewModelType = typeof(MenuViewModel);

            SelectedStartupView = AccountsService.ActiveAccount.DefaultStartupView;
            this.WhenAnyValue(x => x.SelectedStartupView).Skip(1).Subscribe(x =>
            {
                AccountsService.ActiveAccount.DefaultStartupView = x;
                AccountsService.Update(AccountsService.ActiveAccount);
                DismissCommand.ExecuteIfCan();
            });

            StartupViews = new ReactiveList <string>(from p in menuViewModelType.GetRuntimeProperties()
                                                     let attr = p.GetCustomAttributes(typeof(PotentialStartupViewAttribute), true).ToList()
                                                                where attr.Count == 1 && attr[0] is PotentialStartupViewAttribute
                                                                select((PotentialStartupViewAttribute)attr[0]).Name);
        }
Пример #16
0
        public AddInterestViewModel(IApplicationService applicationService, IJsonSerializationService jsonSerializationService)
        {
            DoneCommand = ReactiveCommand.CreateAsyncTask(async _ =>
            {
                if (SelectedLanguage == null)
                {
                    throw new Exception("You must select a language for your interest!");
                }
                if (string.IsNullOrEmpty(Keyword))
                {
                    throw new Exception("Please specify a keyword to go with your interest!");
                }

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

                await DismissCommand.ExecuteAsync();
            });

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


            var str = System.IO.File.ReadAllText(PopularInterestsPath, System.Text.Encoding.UTF8);

            PopularInterests = new ReactiveList <PopularInterest>(jsonSerializationService.Deserialize <List <PopularInterest> >(str));
        }
Пример #17
0
        public FeedbackComposerViewModel(IApplicationService applicationService, IImgurService imgurService,
                                         IMediaPickerService mediaPicker, IStatusIndicatorService statusIndicatorService, IAlertDialogService alertDialogService)
        {
            this.WhenAnyValue(x => x.IsFeature).Subscribe(x => Title = x ? "New Feature" : "Bug Report");

            SubmitCommand = ReactiveCommand.CreateAsyncTask(
                this.WhenAnyValue(x => x.Subject).Select(x => !string.IsNullOrEmpty(x)),
                async _ =>
            {
                if (string.IsNullOrEmpty(Subject))
                {
                    throw new ArgumentException(string.Format("You must provide a title for this {0}!", IsFeature ? "feature" : "bug"));
                }
                var labels       = await applicationService.Client.ExecuteAsync(applicationService.Client.Users[CodeHubOwner].Repositories[CodeHubName].Labels.GetAll());
                var createLabels = labels.Data.Where(x => string.Equals(x.Name, IsFeature ? "feature request" : "bug", StringComparison.OrdinalIgnoreCase)).Select(x => x.Name).Distinct();
                var request      = applicationService.Client.Users[CodeHubOwner].Repositories[CodeHubName].Issues.Create(Subject, Description, null, null, createLabels.ToArray());
                var createdIssue = await applicationService.Client.ExecuteAsync(request);
                _createdIssueSubject.OnNext(createdIssue.Data);
                DismissCommand.ExecuteIfCan();
            });

            PostToImgurCommand = ReactiveCommand.CreateAsyncTask(async _ =>
            {
                var photo        = await mediaPicker.PickPhoto();
                var memoryStream = new MemoryStream();
                await photo.Save(Splat.CompressedBitmapFormat.Jpeg, 0.8f, memoryStream);
                using (statusIndicatorService.Activate("Uploading..."))
                {
                    var model = await imgurService.SendImage(memoryStream.ToArray());
                    if (model == null || model.Data == null || model.Data.Link == null)
                    {
                        throw new InvalidOperationException("Unable to upload to Imgur. Please try again later.");
                    }
                    return(model.Data.Link);
                }
            });

            PostToImgurCommand.ThrownExceptions
            .Where(x => !(x is TaskCanceledException))
            .Subscribe(x => alertDialogService.Alert("Upload Error", x.Message));
        }
Пример #18
0
        public IssueMilestonesViewModel(IApplicationService applicationService)
        {
            Milestones = new ReactiveList <MilestoneModel>();

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

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

                DismissCommand.ExecuteIfCan();
            });

            LoadCommand = ReactiveCommand.CreateAsyncTask(t =>
                                                          Milestones.SimpleCollectionLoad(
                                                              applicationService.Client.Users[RepositoryOwner].Repositories[RepositoryName].Milestones.GetAll(),
                                                              t as bool?));
        }
Пример #19
0
        public AccountsViewModel(IAccountsService accountsService)
        {
            _accountsService      = accountsService;
            Accounts              = new ReactiveList <IAccount>(accountsService);
            LoginCommand          = new ReactiveCommand();
            GoToAddAccountCommand = new ReactiveCommand();
            DeleteAccountCommand  = new ReactiveCommand();

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

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

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

            LoadCommand = new ReactiveCommand();
            LoadCommand.Subscribe(x => Accounts.Reset(accountsService));
        }
Пример #20
0
        public IssueAssignedToViewModel(IApplicationService applicationService)
        {
            _applicationService = applicationService;
            Users = new ReactiveList<BasicUserModel>();

            SelectUserCommand = ReactiveCommand.CreateAsyncTask(async t =>
            {
                var selectedUser = t as BasicUserModel;
                if (selectedUser != null)
                    SelectedUser = selectedUser;

                if (SaveOnSelect)
                {
                    var assignee = SelectedUser != null ? SelectedUser.Login : null;
                    var updateReq = _applicationService.Client.Users[RepositoryOwner].Repositories[RepositoryName].Issues[IssueId].UpdateAssignee(assignee);
                    await _applicationService.Client.ExecuteAsync(updateReq);
                }

                DismissCommand.ExecuteIfCan();
            });

            LoadCommand = ReactiveCommand.CreateAsyncTask(t => 
                Users.SimpleCollectionLoad(applicationService.Client.Users[RepositoryOwner].Repositories[RepositoryName].GetAssignees(), t as bool?));
        }
Пример #21
0
        public IssueLabelsViewModel(IApplicationService applicationService, IGraphicService graphicService)
        {
            var labels = new ReactiveList <LabelModel>();

            SelectedLabels = new ReactiveList <LabelModel>();

            Labels = labels.CreateDerivedCollection(x =>
            {
                var vm = new IssueLabelItemViewModel(graphicService, x);
                vm.SelectCommand.Subscribe(_ =>
                {
                    var selected = SelectedLabels.FirstOrDefault(y => string.Equals(y.Name, x.Name));
                    if (selected != null)
                    {
                        SelectedLabels.Remove(selected);
                        vm.Selected = false;
                    }
                    else
                    {
                        SelectedLabels.Add(x);
                        vm.Selected = true;
                    }
                });
                return(vm);
            });

            SelectLabelsCommand = ReactiveCommand.CreateAsyncTask(async t =>
            {
                var selectedLabels = t as IEnumerable <LabelModel>;
                if (selectedLabels != null)
                {
                    SelectedLabels.Reset(selectedLabels);
                }

                //If nothing has changed, dont do anything...
                if (OriginalLabels != null && OriginalLabels.Count() == SelectedLabels.Count() &&
                    OriginalLabels.Intersect(SelectedLabels).Count() == SelectedLabels.Count())
                {
                    DismissCommand.ExecuteIfCan();
                    return;
                }

                if (SaveOnSelect)
                {
//	                try
//	                {
//                        var labels = (SelectedLabels != null && SelectedLabels.Count > 0)
//                                    ? SelectedLabels.Select(y => y.Name).ToArray() : null;
//	                    var updateReq =
//	                        applicationService.Client.Users[RepositoryOwner].Repositories[RepositoryName].Issues[IssueId]
//	                            .UpdateLabels(labels);
//                        await applicationService.Client.ExecuteAsync(updateReq);
//	                }
//	                catch (Exception e)
//	                {
//	                    throw new Exception("Unable to save labels! Please try again.", e);
//	                }
                }

                DismissCommand.ExecuteIfCan();
            });

            LoadCommand = ReactiveCommand.CreateAsyncTask(t =>
                                                          labels.LoadAll(applicationService.Client.Users[RepositoryOwner].Repositories[RepositoryName].Labels.GetAll()));
        }
Пример #22
0
        public ICommand BuildCommand(string command, IUser author, IMessageChannel channel, IGuild guild, params string[] parameters)
        {
            ICommand _command = null;

            switch (command)
            {
            case CommandNames.exit:
                _command = new ExitCommand(author, _config, channel, _messageWriter, _validationHandler, parameters);
                break;

            case CommandNames.update:
                _command = new UpdateCommand(author, _config, channel, _messageWriter, _validationHandler, parameters);
                break;

            case CommandNames.restart:
                _command = new RestartCommand(author, _config, channel, _messageWriter, _validationHandler, parameters);
                break;

            case CommandNames.help:
                _command = new HelpCommand(author, _config, channel, _messageWriter, _commandsInfo, _validationHandler, parameters);
                break;

            case CommandNames.version:
                _command = new VersionCommand(author, _config, channel, _messageWriter, _validationHandler, parameters);
                break;

            case CommandNames.random:
                _command = new RandomCommand(author, _config, channel, _messageWriter, _validationHandler, parameters);
                break;

            case CommandNames.github:
                _command = new GithubCommand(author, _config, channel, _messageWriter, _validationHandler, parameters);
                break;

            case CommandNames.uptime:
                _command = new UptimeCommand(author, _config, channel, _messageWriter, _validationHandler, parameters);
                break;

            case CommandNames.color:
                _command = new ColorCommand(author, _config, channel, _messageWriter, _validationHandler, parameters);
                break;

            case CommandNames.flipcoin:
                _command = new FlipcoinCommand(author, _config, channel, _messageWriter, _validationHandler, parameters);
                break;

            case CommandNames.roll:
                _command = new RollCommand(author, _config, channel, _messageWriter, _validationHandler, parameters);
                break;

            case CommandNames.purge:
                _command = new PurgeCommand(author, _config, channel, _messageWriter, _connectionHandler, _validationHandler, parameters);
                break;

            case CommandNames.summon:
                _command = new SummonCommand(author, _config, channel, _messageWriter, _audioService, guild, _validationHandler, parameters);
                break;

            case CommandNames.dismiss:
                _command = new DismissCommand(author, _config, channel, _messageWriter, _audioService, guild, _validationHandler, parameters);
                break;

            case CommandNames.play:
                _command = new PlayCommand(author, _config, channel, _messageWriter, _audioService, guild, _validationHandler, parameters);
                break;

            default:
                break;
            }
            return(_command);
        }
Пример #23
0
        public IssueViewModel(
            string username, string repository, int issueId,
            IApplicationService applicationService = null, IMarkdownService markdownService       = null,
            IMessageService messageService         = null, IAlertDialogService alertDialogService = null,
            IActionMenuService actionMenuService   = null)
        {
            _applicationService = applicationService = applicationService ?? Locator.Current.GetService <IApplicationService>();
            messageService      = messageService ?? Locator.Current.GetService <IMessageService>();
            markdownService     = markdownService ?? Locator.Current.GetService <IMarkdownService>();
            alertDialogService  = alertDialogService ?? Locator.Current.GetService <IAlertDialogService>();
            actionMenuService   = actionMenuService ?? Locator.Current.GetService <IActionMenuService>();

            Title      = "Issue #" + issueId;
            Username   = username;
            Repository = repository;
            IssueId    = issueId;

            GoToWebCommand = ReactiveCommand.Create <string>(
                url => NavigateTo(new WebBrowserViewModel(url)));

            GoToReporterCommand = ReactiveCommand.Create(
                () => NavigateTo(new UserViewModel(Issue.ReportedBy.Username)),
                this.WhenAnyValue(x => x.Issue.ReportedBy.Username).Select(x => x != null));

            GoToAssigneeCommand = ReactiveCommand.Create(
                () => NavigateTo(new UserViewModel(Issue.Responsible.Username)),
                this.WhenAnyValue(x => x.Issue.Responsible.Username).Select(x => x != null));

            GoToEditCommand = ReactiveCommand.Create(
                () => NavigateTo(new IssueEditViewModel(username, repository, Issue)),
                this.WhenAnyValue(x => x.Issue).Select(x => x != null));

            this.WhenAnyValue(x => x.Issue)
            .Select(x => x?.Responsible?.Username ?? "Unassigned")
            .ToProperty(this, x => x.Assigned, out _assigned, "Unassigned");

            this.WhenAnyValue(x => x.Issue.Content)
            .Select(x => string.IsNullOrEmpty(x) ? null : markdownService.ConvertMarkdown(x))
            .ToProperty(this, x => x.Description, out _description);

            this.WhenAnyValue(x => x.Description)
            .Select(x => !string.IsNullOrEmpty(x))
            .ToProperty(this, x => x.ShowDescription, out _showDescription);

            Comments = _comments.CreateDerivedCollection(x =>
                                                         new CommentItemViewModel(x.AuthorInfo.Username,
                                                                                  new Utils.Avatar(x.AuthorInfo.Avatar),
                                                                                  x.UtcCreatedOn.Humanize(),
                                                                                  markdownService.ConvertMarkdown(x.Content)));

            LoadCommand = ReactiveCommand.CreateFromTask(async t => {
                var issueTask = applicationService.Client.Issues.Get(username, repository, issueId);
                applicationService.Client.Issues.GetComments(username, repository, issueId)
                .ToBackground(x => _comments.Reset(x.Where(y => !string.IsNullOrEmpty(y.Content))));
                Issue = await issueTask;
            });

            DeleteCommand = ReactiveCommand.CreateFromTask(async _ =>
            {
                try
                {
                    var prompt = await alertDialogService.PromptYesNo(
                        "Are you sure?", "You are about to permanently delete issue #" + Issue.LocalId + ".");

                    if (prompt)
                    {
                        await applicationService.Client.Issues.Delete(username, repository, Issue.LocalId);
                        messageService.Send(new IssueDeleteMessage(Issue));
                        DismissCommand.ExecuteNow();
                    }
                }
                catch (Exception e)
                {
                    this.Log().ErrorException("Error deleting issue", e);
                }
            });

            ShowMenuCommand = ReactiveCommand.CreateFromTask(sender =>
            {
                var menu = actionMenuService.Create();
                menu.AddButton("Edit", _ => GoToEditCommand.ExecuteNow());
                menu.AddButton("Delete", _ => DeleteCommand.ExecuteNow());
                return(menu.Show(sender));
            });

            _issueMessageBus = messageService.Listen <IssueUpdateMessage>(x =>
            {
                if (x.Issue.LocalId == issueId)
                {
                    Issue = x.Issue;
                }
            });
        }
Пример #24
0
        public LoginViewModel(ILoginService loginFactory,
                              IAccountsService accountsService,
                              IActionMenuService actionMenuService,
                              IStatusIndicatorService statusIndicatorService,
                              IAlertDialogService alertDialogService)
        {
            _loginFactory = loginFactory;

            Title = "Login";

            GoToOldLoginWaysCommand = ReactiveCommand.Create();
            GoToOldLoginWaysCommand.Subscribe(_ => ShowViewModel(CreateViewModel <AddAccountViewModel>()));

            var loginCommand = ReactiveCommand.CreateAsyncTask(
                this.WhenAnyValue(x => x.Code).Select(x => !string.IsNullOrEmpty(x)), _ => Login(Code));

            loginCommand.Subscribe(x => accountsService.ActiveAccount = x);
            loginCommand.Subscribe(x => MessageBus.Current.SendMessage(new LogoutMessage()));
            LoginCommand = loginCommand;

            ShowLoginOptionsCommand = ReactiveCommand.CreateAsyncTask(t =>
            {
                var actionMenu = actionMenuService.Create(Title);
                actionMenu.AddButton("Login via BASIC", GoToOldLoginWaysCommand);
                return(actionMenu.Show());
            });

            LoginCommand.IsExecuting.Skip(1).Subscribe(x =>
            {
                if (x)
                {
                    statusIndicatorService.Show("Logging in...");
                }
                else
                {
                    statusIndicatorService.Hide();
                }
            });

            _loginUrl = this.WhenAnyValue(x => x.WebDomain)
                        .IsNotNull()
                        .Select(x => x.TrimEnd('/'))
                        .Select(x =>
                                string.Format(x + "/login/oauth/authorize?client_id={0}&redirect_uri={1}&scope={2}",
                                              ClientId, Uri.EscapeDataString(RedirectUri), Uri.EscapeDataString("user,repo,notifications,gist")))
                        .ToProperty(this, x => x.LoginUrl);

            LoadCommand = ReactiveCommand.CreateAsyncTask(async t =>
            {
                if (IsEnterprise && string.IsNullOrEmpty(WebDomain))
                {
                    var response = await alertDialogService.PromptTextBox("Enterprise URL",
                                                                          "Please enter the webpage address for the GitHub Enterprise installation",
                                                                          DefaultWebDomain, "Ok");
                    WebDomain = response;
                }
                else
                {
                    WebDomain = DefaultWebDomain;
                }
            });

            LoadCommand.ThrownExceptions.Take(1).Subscribe(x => DismissCommand.ExecuteIfCan());
        }