Ejemplo n.º 1
0
        private void UploadFiles(IEnumerable <string> files)
        {
            try
            {
                CancellationTokenSource cancellationTokenSource = new CancellationTokenSource();
                var uploadOperationsQueue = _fileOperationsEngine.StartUploadOperations(
                    files,
                    bucket: Bucket.Name,
                    bucketPath: _currentState.CurrentPath,
                    cancellationToken: cancellationTokenSource.Token);

                GcsFileProgressDialogWindow.PromptUser(
                    caption: Resources.GcsFileBrowserUploadingProgressCaption,
                    message: Resources.GcsFileBrowserUploadingProgressMessage,
                    progressMessage: Resources.GcsFileBrowserUploadingOverallProgressMessage,
                    operations: uploadOperationsQueue.Operations,
                    cancellationTokenSource: cancellationTokenSource);

                EventsReporterWrapper.ReportEvent(GcsFileBrowserStartUploadEvent.Create(CommandStatus.Success));
            }
            catch (IOException ex)
            {
                UserPromptUtils.ErrorPrompt(
                    message: Resources.GcsFileProgressDialogFailedToEnumerateFiles,
                    title: Resources.UiErrorCaption,
                    errorDetails: ex.Message);

                EventsReporterWrapper.ReportEvent(GcsFileBrowserStartUploadEvent.Create(CommandStatus.Failure));
            }

            UpdateCurrentState();
        }
Ejemplo n.º 2
0
        /// <summary>
        /// Prompts the user about deleting the subscription, then calls the datasource to delete it.
        /// </summary>
        internal async void OnDeleteSubscriptionCommand()
        {
            IsLoading = true;
            try
            {
                bool doDelete = UserPromptUtils.ActionPrompt(
                    string.Format(Resources.PubSubDeleteSubscriptionWindowMessage, _subscriptionItem.Name),
                    Resources.PubSubDeleteSubscriptionWindowHeader,
                    actionCaption: Resources.UiDeleteButtonCaption);
                if (doDelete)
                {
                    try
                    {
                        await DataSource.DeleteSubscriptionAsync(_subscriptionItem.FullName);

                        EventsReporterWrapper.ReportEvent(PubSubSubscriptionDeletedEvent.Create(CommandStatus.Success));
                    }
                    catch (DataSourceException e)
                    {
                        Debug.Write(e.Message, "Delete Subscription");
                        EventsReporterWrapper.ReportEvent(PubSubSubscriptionDeletedEvent.Create(CommandStatus.Failure));
                        UserPromptUtils.ErrorPrompt(
                            Resources.PubSubDeleteSubscriptionErrorMessage,
                            Resources.PubSubDeleteSubscriptionErrorHeader,
                            e.Message);
                    }
                    await _owner.Refresh();
                }
            }
            finally
            {
                IsLoading = false;
            }
        }
Ejemplo n.º 3
0
        private bool Validate()
        {
            if (String.IsNullOrEmpty(UserName))
            {
                UserPromptUtils.ErrorPrompt(
                    Resources.AddWindowsCredentialValidationEmptyUser,
                    Resources.AddWindowsCredentialValidationErrorTtitle);
                return(false);
            }

            var invalidChars = UserName.Intersect(UserNameInvalidChars).ToArray();

            if (invalidChars.Length > 0)
            {
                UserPromptUtils.ErrorPrompt(
                    String.Format(Resources.AddWindowsCredentialValidationInvalidChars, new string(invalidChars)),
                    Resources.AddWindowsCredentialValidationErrorTtitle);
                return(false);
            }

            if (ManualPassword && String.IsNullOrEmpty(Password))
            {
                UserPromptUtils.ErrorPrompt(
                    Resources.AddWindowsCredentialValidationEmptyPassword,
                    Resources.AddWindowsCredentialValidationErrorTtitle);
                return(false);
            }

            // Valid entry.
            return(true);
        }
        /// <summary>
        /// Prompts the user for a new subscription, and creates it.
        /// </summary>
        internal async void OnNewSubscriptionCommand()
        {
            IsLoading = true;
            try
            {
                Subscription subscription = NewSubscriptionUserPrompt(Item.FullName);
                if (subscription != null)
                {
                    try
                    {
                        await DataSource.NewSubscriptionAsync(subscription);

                        EventsReporterWrapper.ReportEvent(PubSubSubscriptionCreatedEvent.Create(CommandStatus.Success));
                        await Refresh();
                    }
                    catch (DataSourceException e)
                    {
                        Debug.Write(e.Message, "New Subscription");
                        EventsReporterWrapper.ReportEvent(PubSubSubscriptionCreatedEvent.Create(CommandStatus.Failure));

                        Owner.Refresh();
                        UserPromptUtils.ErrorPrompt(
                            Resources.PubSubNewSubscriptionErrorMessage,
                            Resources.PubSubNewSubscriptionErrorHeader,
                            e.Message);
                    }
                }
            }
            finally
            {
                IsLoading = false;
            }
        }
Ejemplo n.º 5
0
 /// <summary>
 /// Prompts the user about deleting the subscription, then calls the datasource to delete it.
 /// </summary>
 private async void OnDeleteSubscriptionCommand()
 {
     IsLoading = true;
     try
     {
         try
         {
             bool doDelete = UserPromptUtils.ActionPrompt(
                 string.Format(Resources.PubSubDeleteSubscriptionWindowMessage, _subscriptionItem.Name),
                 Resources.PubSubDeleteSubscriptionWindowHeader,
                 actionCaption: Resources.UiDeleteButtonCaption);
             if (doDelete)
             {
                 await DataSource.DeleteSubscriptionAsync(_subscriptionItem.FullName);
             }
         }
         catch (DataSourceException e)
         {
             Debug.Write(e.Message, "Delete Subscription");
             UserPromptUtils.ErrorPrompt(
                 Resources.PubSubDeleteSubscriptionErrorMessage,
                 Resources.PubSubDeleteSubscriptionErrorHeader);
         }
         await _owner.Refresh();
     }
     finally
     {
         IsLoading = false;
     }
 }
        /// <summary>
        /// This method will enable the list of services given.
        /// </summary>
        /// <param name="serviceNames">The list of services to enable.</param>
        /// <returns>A task that will be completed once the operation finishes.</returns>
        public async Task EnableServicesAsync(IEnumerable <string> serviceNames)
        {
            ServiceManagementDataSource dataSource = _dataSource.Value;

            if (dataSource == null)
            {
                return;
            }

            try
            {
                await ProgressDialogWindow.PromptUser(
                    dataSource.EnableAllServicesAsync(serviceNames),
                    new ProgressDialogWindow.Options
                {
                    Title         = Resources.ApiManagerEnableServicesTitle,
                    Message       = Resources.ApiManagerEnableServicesProgressMessage,
                    IsCancellable = false
                });
            }
            catch (DataSourceException ex)
            {
                UserPromptUtils.ErrorPrompt(
                    message: Resources.ApiManagerEnableServicesErrorMessage,
                    title: Resources.UiErrorCaption,
                    errorDetails: ex.Message);
            }
        }
Ejemplo n.º 7
0
 /// <summary>
 /// Prompts the user for a new subscription, and creates it.
 /// </summary>
 private async void OnNewSubscriptionCommand()
 {
     IsLoading = true;
     try
     {
         try
         {
             Subscription subscription = NewSubscriptionWindow.PromptUser(TopicItem.FullName);
             if (subscription != null)
             {
                 await DataSource.NewSubscriptionAsync(subscription);
             }
         }
         catch (DataSourceException e)
         {
             Debug.Write(e.Message, "New Subscription");
             UserPromptUtils.ErrorPrompt(
                 Resources.PubSubNewSubscriptionErrorMessage, Resources.PubSubNewSubscriptionErrorHeader);
         }
         await Refresh();
     }
     finally
     {
         IsLoading = false;
     }
 }
Ejemplo n.º 8
0
        private bool GetAllProcessesList()
        {
            var dte       = Shell.Package.GetGlobalService(typeof(DTE)) as DTE;
            var debugger  = dte.Debugger as Debugger2;
            var transport = debugger.Transports.Item("Default");

            // Show engine types
            EngineTypes = new List <string>();
            EngineTypes.Add(Resources.AttachDebuggerAutomaticallyDetectEngineTypeItemName);
            foreach (var engineType in transport.Engines)
            {
                var engine = engineType as Engine;
                if (engine == null)
                {
                    Debug.WriteLine("engine is null, might be a code bug.");
                    continue;
                }
                EngineTypes.Add(engine.Name);
            }
            SelectedEngine = s_detectEngineTypeItemName;

            Processes processes = debugger.GetProcesses(transport, Context.PublicIp);

            _allProcesses = new List <ProcessItem>();
            foreach (var process in processes)      // Linq does not work on COM list
            {
                var pro2 = process as Process2;
                _allProcesses.Add(new ProcessItem(pro2));
            }

            if (_allProcesses.Count == 0)
            {
                UserPromptUtils.ErrorPrompt(
                    message: Resources.AttachDebuggerListProcessEmptyResultErrorMessage,
                    title: Resources.UiDefaultPromptTitle);
                return(false);
            }

            if (!String.IsNullOrWhiteSpace(AttachDebuggerSettings.Current.DefaultDebuggeeProcessName))
            {
                var matching = _allProcesses
                               .Where(x => x.Name.ToLowerInvariant() == AttachDebuggerSettings.Current.DefaultDebuggeeProcessName.ToLowerInvariant());
                if (!matching.Any())
                {
                    ResetDefaultSelection();
                }
                else if (matching.Count() == 1)
                {
                    Processes       = matching;
                    SelectedProcess = matching.First();
                    SelectedEngine  = AttachDebuggerSettings.Current.DefaultDebuggerEngineType;
                    return(true);
                }
            }

            Processes       = _allProcesses;
            SelectedProcess = Processes.FirstOrDefault();
            return(true);
        }
Ejemplo n.º 9
0
        public void TestErrorPrompt_PromptsWithGivenTitle()
        {
            UserPromptWindow userPrompt =
                GetWindow(() => _objectUnderTest.ErrorPrompt(DefaultPrompt, ExpectedTitle));

            Assert.AreEqual(ExpectedTitle, userPrompt.Title);
        }
Ejemplo n.º 10
0
        /// <summary>
        /// This method will check that all given services are enabled and if not will prompt the user to enable the
        /// necessary services.
        /// </summary>
        /// <param name="serviceNames">The services to check.</param>
        /// <param name="prompt">The prompt to use in the prompt dialog to ask the user for permission to enable the services.</param>
        /// <returns>A task that will be true if all services where enabled, false if the user cancelled or if the operation failed.</returns>
        public async Task <bool> EnsureAllServicesEnabledAsync(
            IEnumerable <string> serviceNames,
            string prompt)
        {
            ServiceManagementDataSource dataSource = _dataSource.Value;

            if (dataSource == null)
            {
                return(false);
            }

            try
            {
                // Check all services in parallel.
                IList <string> servicesToEnable = (await dataSource.CheckServicesStatusAsync(serviceNames))
                                                  .Where(x => !x.Enabled)
                                                  .Select(x => x.Name)
                                                  .ToList();
                if (servicesToEnable.Count == 0)
                {
                    Debug.WriteLine("All the services are already enabled.");
                    return(true);
                }

                // Need to enable the services, prompt the user.
                Debug.WriteLine($"Need to enable the services: {string.Join(",", servicesToEnable)}.");
                if (!UserPromptUtils.ActionPrompt(
                        prompt: prompt,
                        title: Resources.ApiManagerEnableServicesTitle,
                        actionCaption: Resources.UiEnableButtonCaption))
                {
                    return(false);
                }

                // Enable all services in parallel.
                await ProgressDialogWindow.PromptUser(
                    dataSource.EnableAllServicesAsync(servicesToEnable),
                    new ProgressDialogWindow.Options
                {
                    Title         = Resources.ApiManagerEnableServicesTitle,
                    Message       = Resources.ApiManagerEnableServicesProgressMessage,
                    IsCancellable = false
                });

                return(true);
            }
            catch (DataSourceException ex)
            {
                UserPromptUtils.ErrorPrompt(
                    message: Resources.ApiManagerEnableServicesErrorMessage,
                    title: Resources.UiErrorCaption,
                    errorDetails: ex.Message);
                return(false);
            }
        }
Ejemplo n.º 11
0
 private void OnCopyCommand()
 {
     try
     {
         Clipboard.SetText(Password);
     }
     catch
     {
         Debug.WriteLine("Failed to copy the string to the clipboard.");
         UserPromptUtils.ErrorPrompt(Resources.ShowPasswordCopyFailedMessage, Resources.ShowPasswordCopyFailedTitle);
     }
 }
Ejemplo n.º 12
0
        private bool ValidateInput()
        {
            int replicas = 0;

            if (!int.TryParse(Replicas, out replicas))
            {
                UserPromptUtils.ErrorPrompt(Resources.GkePublishInvalidReplicasMessage, Resources.UiInvalidValueTitle);
                return(false);
            }

            return(true);
        }
Ejemplo n.º 13
0
        private async void OnRenameFolderCommand()
        {
            var newLeafName = NamePromptWindow.PromptUser(new NamePromptWindow.Options
            {
                InitialName = SelectedItem.LeafName,
                Title       = Resources.GcsFileBrowserRenameFolderTitle
            });

            if (newLeafName == null)
            {
                return;
            }

            try
            {
                IsLoading = true;

                CancellationTokenSource cancellationTokenSource = new CancellationTokenSource();
                var renameDirectoryOperations = await _fileOperationsEngine.StartDirectoryRenameOperationsAsync(
                    bucket : Bucket.Name,
                    parentName : CurrentState.CurrentPath,
                    oldLeafName : SelectedItem.LeafName,
                    newLeafName : newLeafName,
                    cancellationToken : cancellationTokenSource.Token);

                GcsFileProgressDialogWindow.PromptUser(
                    caption: Resources.GcsFileBrowserRenamingFilesCaption,
                    message: Resources.GcsFileBrowserRenamingFilesMessage,
                    progressMessage: Resources.GcsFileBrowserRenamingFilesProgressMessage,
                    operations: renameDirectoryOperations.Operations,
                    cancellationTokenSource: cancellationTokenSource);

                EventsReporterWrapper.ReportEvent(GcsFileBrowserStartRenameDirectoryEvent.Create(CommandStatus.Success));
            }
            catch (DataSourceException ex)
            {
                UserPromptUtils.ErrorPrompt(
                    message: string.Format(Resources.GcsFileBrowserRenameFailedMessage, SelectedItem.LeafName),
                    title: Resources.UiErrorCaption,
                    errorDetails: ex.Message);

                EventsReporterWrapper.ReportEvent(GcsFileBrowserStartRenameDirectoryEvent.Create(CommandStatus.Failure));
            }
            finally
            {
                IsLoading = false;
            }

            UpdateCurrentState();
        }
Ejemplo n.º 14
0
        private async void OnRenameFileCommand()
        {
            var choosenName = NamePromptWindow.PromptUser(new NamePromptWindow.Options
            {
                InitialName = SelectedItem.LeafName,
                Title       = Resources.GcsFileBrowserRenameFileTitle
            });

            if (choosenName == null)
            {
                return;
            }

            try
            {
                IsLoading = true;

                var newName = GcsPathUtils.Combine(CurrentState.CurrentPath, choosenName);
                Debug.WriteLine($"Renaming {SelectedItem.BlobName} to {newName}");
                await ProgressDialogWindow.PromptUser(
                    _dataSource.MoveFileAsync(
                        bucket: Bucket.Name,
                        sourceName: SelectedItem.BlobName,
                        destName: newName),
                    new ProgressDialogWindow.Options
                {
                    Message       = Resources.GcsFileBrowserRenamingProgressMessage,
                    Title         = Resources.UiDefaultPromptTitle,
                    IsCancellable = false
                });

                EventsReporterWrapper.ReportEvent(GcsFileBrowserRenameFileEvent.Create(CommandStatus.Success));
            }
            catch (DataSourceException ex)
            {
                UserPromptUtils.ErrorPrompt(
                    message: string.Format(Resources.GcsFileBrowserRenameFailedMessage, SelectedItem.LeafName),
                    title: Resources.UiErrorCaption,
                    errorDetails: ex.Message);

                EventsReporterWrapper.ReportEvent(GcsFileBrowserRenameFileEvent.Create(CommandStatus.Failure));
            }
            finally
            {
                IsLoading = false;
            }

            UpdateCurrentState();
        }
Ejemplo n.º 15
0
        private async void OnDownloadCommand()
        {
            FBD dialog = new FBD();

            dialog.Description         = Resources.GcsFileBrowserFolderSelectionMessage;
            dialog.ShowNewFolderButton = true;

            var result = dialog.ShowDialog();

            if (result == System.Windows.Forms.DialogResult.Cancel)
            {
                return;
            }
            var downloadRoot = dialog.SelectedPath;

            try
            {
                IsLoading = true;

                CancellationTokenSource cancellationTokenSource = new CancellationTokenSource();
                var downloadOperationsQueue = await _fileOperationsEngine.StartDownloadOperationsAsync(
                    SelectedItems.Select(x => new GcsUtils.GcsItemRef(x.Bucket, x.BlobName)),
                    downloadRoot,
                    cancellationTokenSource.Token);

                GcsFileProgressDialogWindow.PromptUser(
                    caption: Resources.GcsFileBrowserDownloadingProgressCaption,
                    message: Resources.GcsFileBrowserDownloadingProgressMessage,
                    progressMessage: Resources.GcsFileBrowserDownloadingOverallProgressMessage,
                    operations: downloadOperationsQueue.Operations,
                    cancellationTokenSource: cancellationTokenSource);

                EventsReporterWrapper.ReportEvent(GcsFileBrowserStartDownloadEvent.Create(CommandStatus.Success));
            }
            catch (IOException ex)
            {
                UserPromptUtils.ErrorPrompt(
                    message: Resources.GcsFileBrowserFailedToCreateDirMessage,
                    title: Resources.UiErrorCaption,
                    errorDetails: ex.Message);

                EventsReporterWrapper.ReportEvent(GcsFileBrowserStartDownloadEvent.Create(CommandStatus.Failure));
                return;
            }
            finally
            {
                IsLoading = false;
            }
        }
        /// <summary>
        /// Repeatedly make list log entries request till it gets desired number of logs or it reaches end.
        /// _nextPageToken is used to control if it is getting first page or continuous page.
        ///
        /// On complex filters, scanning through logs take time. The server returns empty results
        ///   with a next page token. Continue to send request till some logs are found.
        /// </summary>
        /// <param name="cancellationToken">A cancellation token. The caller can monitor the cancellation event.</param>
        /// <param name="autoReload">Indicate if the request comes from autoReload event.</param>
        private async Task LoadLogsAsync(CancellationToken cancellationToken, bool autoReload = false)
        {
            if (_logs.Count >= MaxLogEntriesCount)
            {
                UserPromptUtils.ErrorPrompt(
                    message: Resources.LogViewerResultSetTooLargeMessage,
                    title: Resources.UiDefaultPromptTitle);
                _cancellationTokenSource?.Cancel();
                return;
            }

            try
            {
                var startTimestamp = DateTime.Now;

                var order = DateTimePickerModel.IsDescendingOrder ? "timestamp desc" : "timestamp asc";
                int count = 0;
                while (count < DefaultPageSize && !cancellationToken.IsCancellationRequested)
                {
                    Debug.WriteLine($"LoadLogs, count={count}, firstPage={_nextPageToken == null}");

                    // Here, it does not do pageSize: _defaultPageSize - count,
                    // Because this is requried to use same page size for getting next page.
                    var results = await _dataSource.Value.ListLogEntriesAsync(_filter, order,
                                                                              pageSize : DefaultPageSize, nextPageToken : _nextPageToken, cancelToken : cancellationToken);

                    _nextPageToken = results.NextPageToken;
                    if (results?.LogEntries != null)
                    {
                        count += results.LogEntries.Count;
                        AddLogs(results.LogEntries, autoReload);
                    }

                    if (String.IsNullOrWhiteSpace(_nextPageToken))
                    {
                        _nextPageToken = null;
                        break;
                    }
                }

                EventsReporterWrapper.ReportEvent(LogsViewerLogsLoadedEvent.Create(CommandStatus.Success, DateTime.Now - startTimestamp));
            }
            catch (Exception ex) when(!ErrorHandlerUtils.IsCriticalException(ex))
            {
                EventsReporterWrapper.ReportEvent(LogsViewerLogsLoadedEvent.Create(CommandStatus.Failure));
                throw;
            }
        }
        /// <summary>
        /// Validates the input. Prompts the user on validation errors.
        /// </summary>
        /// <returns>Returns true if validation succeded, false if the user had to be prompted</returns>
        private bool ValidateInput()
        {
            var results = PubSubNameValidationRule.Validate(TopicName, Resources.NewTopicWindowNameFieldName);
            var details = String.Join("\n", results.Select(result => result.Message));

            if (!String.IsNullOrEmpty(details))
            {
                string message = String.Format(Resources.PubSubNewTopicNameInvalidMessage, TopicName);
                UserPromptUtils.ErrorPrompt(message, Resources.PubSubNewTopicNameInvalidTitle, details);
                return(false);
            }
            else
            {
                return(true);
            }
        }
Ejemplo n.º 18
0
        private bool Validate()
        {
            if (String.IsNullOrEmpty(Name))
            {
                UserPromptUtils.ErrorPrompt(Resources.NamePromptEmptyNameMessage, Resources.UiErrorCaption);
                return(false);
            }

            if (Name.Contains('/'))
            {
                UserPromptUtils.ErrorPrompt(Resources.NamePromptInvalidCharsMessage, Resources.UiErrorCaption);
                return(false);
            }

            return(true);
        }
        /// <summary>
        /// This function is the callback used to execute the command when the menu item is clicked.
        /// See the constructor to see how the menu item is associated with this function using
        /// OleMenuCommandService service and MenuCommand class.
        /// </summary>
        /// <param name="sender">Event sender.</param>
        /// <param name="e">Event args.</param>
        private void OnGenerateConfiguration(object sender, EventArgs e)
        {
            ErrorHandlerUtils.HandleExceptions(() =>
            {
                var selectedProject = SolutionHelper.CurrentSolution.SelectedProject;
                Debug.WriteLine($"Generating configuration for project: {selectedProject.FullPath}");
                var configurationStatus = AppEngineFlexDeployment.CheckProjectConfiguration(selectedProject);

                // If the app.yaml already exists allow the user to skip its generation to preserve the existing file.
                if (!configurationStatus.HasAppYaml ||
                    UserPromptUtils.ActionPrompt(
                        prompt: Resources.GenerateConfigurationAppYamlOverwriteMessage,
                        title: Resources.GenerateConfigurationOverwritePromptTitle,
                        actionCaption: Resources.UiOverwriteButtonCaption,
                        cancelCaption: Resources.UiSkipFileButtonCaption))
                {
                    Debug.WriteLine($"Generating app.yaml for {selectedProject.FullPath}");
                    if (!AppEngineFlexDeployment.GenerateAppYaml(selectedProject))
                    {
                        UserPromptUtils.ErrorPrompt(
                            String.Format(Resources.GenerateConfigurationFileGenerationErrorMessage, AppEngineFlexDeployment.AppYamlName),
                            Resources.GenerateConfigurationFileGeneratinErrorTitle);
                        return;
                    }
                    GcpOutputWindow.OutputLine(Resources.GenerateConfigurationAppYamlGeneratedMessage);
                }

                // If the Dockerfile already exists allow the user to skip its generation to preserve the existing file.
                if (!configurationStatus.HasDockerfile ||
                    UserPromptUtils.ActionPrompt(
                        prompt: Resources.GenerateConfigurationDockerfileOverwriteMessage,
                        title: Resources.GenerateConfigurationOverwritePromptTitle,
                        actionCaption: Resources.UiOverwriteButtonCaption,
                        cancelCaption: Resources.UiSkipFileButtonCaption))
                {
                    Debug.WriteLine($"Generating Dockerfile for {selectedProject.FullPath}");
                    if (!AppEngineFlexDeployment.GenerateDockerfile(selectedProject))
                    {
                        UserPromptUtils.ErrorPrompt(
                            String.Format(Resources.GenerateConfigurationFileGenerationErrorMessage, AppEngineFlexDeployment.DockerfileName),
                            Resources.GenerateConfigurationFileGeneratinErrorTitle);
                        return;
                    }
                    GcpOutputWindow.OutputLine(Resources.GenerateConfigurationDockerfileGeneratedMessage);
                }
            });
        }
Ejemplo n.º 20
0
        private async Task <WindowsInstanceCredentials> CreateOrResetCredentials(string user)
        {
            try
            {
                Debug.WriteLine("The user requested the password to be generated.");
                if (!UserPromptUtils.ActionPrompt(
                        prompt: String.Format(Resources.ResetPasswordConfirmationPromptMessage, user, _instance.Name),
                        title: Resources.ResetPasswordConfirmationPromptTitle,
                        message: Resources.UiOperationCannotBeUndone,
                        actionCaption: Resources.UiResetButtonCaption,
                        isWarning: true))
                {
                    Debug.WriteLine("The user cancelled resetting the password.");
                    return(null);
                }

                Debug.WriteLine($"Resetting the password for the user {user}");

                // Check that gcloud is in the right state to invoke the reset credentials method.
                if (!await VerifyGCloudDependencies())
                {
                    Debug.WriteLine("Missing gcloud dependencies for resetting password.");
                    return(null);
                }

                var context = new GCloudContext
                {
                    CredentialsPath = CredentialsStore.Default.CurrentAccountPath,
                    ProjectId       = CredentialsStore.Default.CurrentProjectId,
                    AppName         = GoogleCloudExtensionPackage.ApplicationName,
                    AppVersion      = GoogleCloudExtensionPackage.ApplicationVersion,
                };
                return(await GCloudWrapper.ResetWindowsCredentialsAsync(
                           instanceName : _instance.Name,
                           zoneName : _instance.GetZoneName(),
                           userName : user,
                           context : context));
            }
            catch (GCloudException ex)
            {
                UserPromptUtils.ErrorPrompt(
                    message: String.Format(Resources.ResetPasswordFailedPromptMessage, _instance.Name),
                    title: Resources.ResetPasswordConfirmationPromptTitle,
                    errorDetails: ex.Message);
                return(null);
            }
        }
Ejemplo n.º 21
0
        private bool ValidateInput()
        {
            if (String.IsNullOrEmpty(Version))
            {
                UserPromptUtils.ErrorPrompt(Resources.FlexPublishEmptyVersionMessage, Resources.UiInvalidValueTitle);
                return(false);
            }
            if (!GcpPublishStepsUtils.IsValidName(Version))
            {
                UserPromptUtils.ErrorPrompt(
                    String.Format(Resources.FlexPublishInvalidVersionMessage, Version),
                    Resources.UiInvalidValueTitle);
                return(false);
            }

            return(true);
        }
Ejemplo n.º 22
0
        private async void OnDeleteCommand()
        {
            if (!UserPromptUtils.ActionPrompt(
                    prompt: Resources.GcsFileBrowserDeletePromptMessage,
                    title: Resources.UiDefaultPromptTitle,
                    actionCaption: Resources.UiDeleteButtonCaption,
                    cancelCaption: Resources.UiCancelButtonCaption))
            {
                return;
            }

            try
            {
                IsLoading = true;


                var cancellationTokenSource = new CancellationTokenSource();
                var deleteOperationsQueue   = await _fileOperationsEngine.StartDeleteOperationsAsync(
                    SelectedItems.Select(x => new GcsItemRef(x.Bucket, x.BlobName)),
                    cancellationTokenSource.Token);

                GcsFileProgressDialogWindow.PromptUser(
                    caption: Resources.GcsFileBrowserDeletingProgressCaption,
                    message: Resources.GcsFileBrowserDeletingProgressMessage,
                    progressMessage: Resources.GcsFileBrowserDeletingOverallProgressMessage,
                    operations: deleteOperationsQueue.Operations,
                    cancellationTokenSource: cancellationTokenSource);

                EventsReporterWrapper.ReportEvent(GcsFileBrowserStartDeleteEvent.Create(CommandStatus.Success));
            }
            catch (DataSourceException ex)
            {
                UserPromptUtils.ErrorPrompt(
                    message: Resources.GcsFileBrowserDeleteListErrorMessage,
                    title: Resources.UiErrorCaption,
                    errorDetails: ex.Message);

                EventsReporterWrapper.ReportEvent(GcsFileBrowserStartDeleteEvent.Create(CommandStatus.Failure));
            }
            finally
            {
                IsLoading = false;
            }

            UpdateCurrentState();
        }
        /// <summary>
        /// projectRepos is used to cache the list of 'cloud repos' of the project-id.
        /// </summary>
        private async Task AddLocalReposAsync(IList <GitRepository> localRepos, IList <Project> projects)
        {
            List <string> dataSourceErrorProjects = new List <string>();
            Dictionary <string, IList <Repo> > projectRepos
                = new Dictionary <string, IList <Repo> >(StringComparer.OrdinalIgnoreCase);

            foreach (var localGitRepo in localRepos)
            {
                IList <string> remoteUrls = await localGitRepo.GetRemotesUrls();

                foreach (var url in remoteUrls)
                {
                    string projectId = CsrUtils.ParseProjectId(url);
                    var    project   = projects.FirstOrDefault(x => x.ProjectId == projectId);
                    if (String.IsNullOrWhiteSpace(projectId) || project == null)
                    {
                        continue;
                    }

                    try
                    {
                        var cloudRepo = await TryGetCloudRepoAsync(url, projectId, projectRepos);

                        if (cloudRepo == null)
                        {
                            Debug.WriteLine($"{projectId} repos does not contain {url}");
                            continue;
                        }
                        Repositories.Add(new RepoItemViewModel(cloudRepo, localGitRepo.Root));
                        break;
                    }
                    catch (DataSourceException)
                    {
                        dataSourceErrorProjects.Add(project.Name);
                    }
                }
            }

            if (dataSourceErrorProjects.Any())
            {
                UserPromptUtils.ErrorPrompt(
                    message: String.Format(
                        Resources.CsrFetchReposErrorMessage, String.Join(", ", dataSourceErrorProjects)),
                    title: Resources.CsrConnectSectionTitle);
            }
        }
        private async Task CloneAsync()
        {
            if (IsDefaultLocation(LocalPath) && !Directory.Exists(s_defaultLocalPath))
            {
                Directory.CreateDirectory(s_defaultLocalPath);
            }

            // If OkCommand is enabled, SelectedRepository and LocalPath is valid
            string destPath = Path.Combine(LocalPath, SelectedRepository.GetRepoName());

            if (!CsrGitUtils.StoreCredential(
                    SelectedRepository.Url,
                    CredentialsStore.Default.CurrentAccount.RefreshToken,
                    CsrGitUtils.StoreCredentialPathOption.UrlPath))
            {
                UserPromptUtils.ErrorPrompt(
                    message: Resources.CsrCloneFailedToSetCredentialMessage,
                    title: Resources.UiDefaultPromptTitle);
                return;
            }

            try
            {
                var           watch     = Stopwatch.StartNew();
                GitRepository localRepo = await CsrGitUtils.CloneAsync(SelectedRepository.Url, destPath);

                Result = new CloneDialogResult
                {
                    RepoItem        = new RepoItemViewModel(SelectedRepository, localRepo.Root),
                    JustCreatedRepo = _newReposList.Contains(SelectedRepository.Name)
                };
                _closeOwnerFunc();
                EventsReporterWrapper.ReportEvent(
                    CsrClonedEvent.Create(CommandStatus.Success, watch.Elapsed));
            }
            catch (GitCommandException)
            {
                UserPromptUtils.ErrorPrompt(
                    message: Resources.CsrCloneFailedMessage,
                    title: Resources.UiDefaultPromptTitle);
                EventsReporterWrapper.ReportEvent(CsrClonedEvent.Create(CommandStatus.Failure));
                return;
            }
        }
Ejemplo n.º 25
0
        /// <summary>
        /// Opens the new pub sub topic dialog.
        /// </summary>
        private async void OnNewTopicCommand()
        {
            try
            {
                string topicName = NewTopicWindow.PromptUser(CurrentProjectId);
                if (topicName != null)
                {
                    await DataSource.NewTopicAsync(topicName);

                    Refresh();
                }
            }
            catch (DataSourceException e)
            {
                Debug.Write(e.Message, "New Topic");
                UserPromptUtils.ErrorPrompt(
                    Resources.PubSubNewTopicErrorMessage, Resources.PubSubNewTopicErrorHeader);
            }
        }
Ejemplo n.º 26
0
 private void OnManageFirewallPortsCommand()
 {
     try
     {
         var changes = PortManagerWindow.PromptUser(Instance);
         if (changes?.HasChanges ?? false)
         {
             var operation = _owner.DataSource.UpdateInstancePorts(
                 Instance,
                 portsToEnable: changes.PortsToEnable,
                 portsToDisable: changes.PortsToDisable);
             UpdateInstanceState(operation);
         }
     }
     catch (DataSourceException)
     {
         UserPromptUtils.ErrorPrompt(Resources.CloudExplorerGceFailedToUpdateFirewallMessage, Resources.CloudExplorerGceFailedToUpdateFirewallCaption);
     }
 }
Ejemplo n.º 27
0
        /// <summary>
        /// Starts the flow to add a new account to the credentials store.
        /// </summary>
        /// <returns>Will return true if the accound was added, false if the user cancelled.</returns>
        public static async Task <bool> StartAddAccountFlowAsync()
        {
            try
            {
                ExtensionAnalytics.ReportEvent(OAuthEventCategory, "FlowStarted");
                string refreshToken = OAuthLoginFlowWindow.PromptUser(s_extensionCredentials, s_extensionScopes);
                if (refreshToken == null)
                {
                    ExtensionAnalytics.ReportEvent(OAuthEventCategory, "FlowCancelled");
                    Debug.WriteLine("The user cancelled the OAUTH login flow.");
                    return(false);
                }

                var credentials = await GetUserAccountForRefreshToken(refreshToken);

                ExtensionAnalytics.ReportEvent(OAuthEventCategory, "FlowFinished");

                var existingUserAccount = CredentialsStore.Default.GetAccount(credentials.AccountName);
                if (existingUserAccount != null)
                {
                    Debug.WriteLine($"Duplicate account {credentials.AccountName}");
                    UserPromptUtils.ErrorPrompt(
                        string.Format(Resources.ManageAccountsAccountAlreadyExistsPromptMessage, credentials.AccountName),
                        Resources.ManageAccountsAccountAlreadyExistsPromptTitle);
                    return(false);
                }

                // Store the new account and set it as the current account. The project is not changed so if the
                // new account also have access to it, it remains as the current project.
                CredentialsStore.Default.AddAccount(credentials);
                CredentialsStore.Default.CurrentAccount = credentials;
                return(true);
            }
            catch (OAuthException ex)
            {
                ExtensionAnalytics.ReportEvent(OAuthEventCategory, "FlowFailed");
                UserPromptUtils.ErrorPrompt(
                    String.Format(Resources.CloudExplorerGceFailedToGetOauthCredentialsMessage, ex.Message),
                    Resources.CloudExplorerGceFailedToGetOauthCredentialsCaption);
                return(false);
            }
        }
Ejemplo n.º 28
0
        private async void OnCopyCommand()
        {
            try
            {
                Clipboard.SetText(Password);

                if (!ShowCopyFeedback)
                {
                    ShowCopyFeedback = true;
                    await Task.Delay(2000);

                    ShowCopyFeedback = false;
                }
            }
            catch
            {
                Debug.WriteLine("Failed to copy the string to the clipboard.");
                UserPromptUtils.ErrorPrompt(Resources.ShowPasswordCopyFailedMessage, Resources.ShowPasswordCopyFailedTitle);
            }
        }
        private bool Validate()
        {
            int allocationValue = 0;

            if (!Int32.TryParse(Allocation, out allocationValue))
            {
                UserPromptUtils.ErrorPrompt(
                    message: String.Format(Resources.AddGaeTrafficSplitInvalidValueMessage, Allocation),
                    title: Resources.AddGaeTrafficSplitInvalidValueTitle);
                return(false);
            }

            if (allocationValue > 100 || allocationValue < 0)
            {
                UserPromptUtils.ErrorPrompt(
                    message: String.Format(Resources.AddGaeTrafficSplitValueOutOfRangeMessage, Allocation),
                    title: Resources.AddGaeTrafficSplitInvalidValueTitle);
                return(false);
            }

            return(true);
        }
Ejemplo n.º 30
0
        private IAttachDebuggerStep Attach()
        {
            IsListVisible   = false;
            ProgressMessage = String.Format(
                Resources.AttachDebuggerAttachingProcessMessageFormat,
                SelectedProcess.Name);

            var startTimestamp = DateTime.Now;

            try
            {
                if (SelectedEngine == s_detectEngineTypeItemName)
                {
                    SelectedProcess.Process.Attach();
                }
                else
                {
                    SelectedProcess.Process.Attach2(SelectedEngine);
                }
            }
            catch (COMException ex)
            {
                EventsReporterWrapper.ReportEvent(
                    RemoteDebuggerAttachedEvent.Create(CommandStatus.Failure));

                Debug.WriteLine($"Attach debugger got exception. {ex}");
                UserPromptUtils.ErrorPrompt(
                    message: String.Format(Resources.AttachDebuggerAttachErrorMessageFormat, SelectedProcess.Name),
                    title: Resources.UiDefaultPromptTitle);
                ResetDefaultSelection();
                return(HelpStepViewModel.CreateStep(Context));
            }

            EventsReporterWrapper.ReportEvent(RemoteDebuggerAttachedEvent.Create(
                                                  CommandStatus.Success, DateTime.Now - startTimestamp));

            Context.DialogWindow.Close();
            return(null);
        }