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(); }
/// <summary> /// Initializes an instance of <seealso cref="LogsViewerViewModel"/> class. /// </summary> public LogsViewerViewModel() { _dataSource = new Lazy <LoggingDataSource>(CreateDataSource); RefreshCommand = new ProtectedCommand(OnRefreshCommand); LogItemCollection = new ListCollectionView(_logs); LogItemCollection.GroupDescriptions.Add(new PropertyGroupDescription(nameof(LogItem.Date))); CancelRequestCommand = new ProtectedCommand(CancelRequest); SimpleTextSearchCommand = new ProtectedCommand(() => { EventsReporterWrapper.ReportEvent(LogsViewerSimpleTextSearchEvent.Create()); ErrorHandlerUtils.HandleAsyncExceptions(ReloadAsync); }); FilterSwitchCommand = new ProtectedCommand(SwapFilter); SubmitAdvancedFilterCommand = new ProtectedCommand(() => { EventsReporterWrapper.ReportEvent(LogsViewerAdvancedFilterEvent.Create()); ErrorHandlerUtils.HandleAsyncExceptions(ReloadAsync); }); AdvancedFilterHelpCommand = new ProtectedCommand(ShowAdvancedFilterHelp); DateTimePickerModel = new DateTimePickerViewModel( TimeZoneInfo.Local, DateTime.UtcNow, isDescendingOrder: true); DateTimePickerModel.DateTimeFilterChange += (sender, e) => ErrorHandlerUtils.HandleAsyncExceptions(ReloadAsync); PropertyChanged += OnPropertyChanged; ResourceTypeSelector = new ResourceTypeMenuViewModel(_dataSource); ResourceTypeSelector.PropertyChanged += OnPropertyChanged; OnDetailTreeNodeFilterCommand = new ProtectedCommand <ObjectNodeTree>(FilterOnTreeNodeValue); OnAutoReloadCommand = new ProtectedCommand(AutoReload); }
private async void UpdateCurrentState(string newPath) { GcsBrowserState newState; try { var startTimestamp = DateTime.Now; // Reset the error and empty state while loading. IsLoading = true; newState = await LoadStateForDirectoryAsync(newPath); EventsReporterWrapper.ReportEvent( GcsFileBrowserDirectoryLoadedEvent.Create(CommandStatus.Success, DateTime.Now - startTimestamp)); } catch (DataSourceException ex) { Debug.WriteLine($"Failed to update to path {newPath}: {ex.Message}"); newState = CreateErrorState(newPath); EventsReporterWrapper.ReportEvent(GcsFileBrowserDirectoryLoadedEvent.Create(CommandStatus.Failure)); } finally { IsLoading = false; } CurrentState = newState; }
protected override async Task LoadDataOverride() { try { Debug.WriteLine("Loading list of buckets."); _buckets = await LoadBucketList(); PresentViewModels(); EventsReporterWrapper.ReportEvent(GcsBucketsLoadedEvent.Create(CommandStatus.Success)); } catch (DataSourceException ex) { var innerEx = ex.InnerException as GoogleApiException; if (innerEx != null && innerEx.HttpStatusCode == System.Net.HttpStatusCode.Forbidden) { Debug.WriteLine("GCS API is not enabled."); Children.Clear(); Children.Add(new DisabledApiWarning( apiName: ComponentApiName, caption: Resources.CloudExplorerGcsSourceApiDisabledMessage, project: Context.CurrentProject)); return; } EventsReporterWrapper.ReportEvent(GcsBucketsLoadedEvent.Create(CommandStatus.Failure)); throw new CloudExplorerSourceException(ex.Message, ex); } }
/// <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; } }
/// <summary> /// Loads the topics, and creates child topic nodes. /// </summary> protected override async Task LoadDataOverride() { try { Task <IList <Subscription> > subscriptionsTask = DataSource.GetSubscriptionListAsync(); IEnumerable <Topic> topics = await DataSource.GetTopicListAsync(); IList <Subscription> subscriptions = await subscriptionsTask; Children.Clear(); foreach (Topic topic in topics.Where(IsIncludedTopic)) { Children.Add(new TopicViewModel(this, topic, subscriptions)); } if (subscriptions.Any(s => s.Topic.Equals(OrphanedSubscriptionsItem.DeletedTopicName))) { Children.Add(new OrphanedSubscriptionsViewModel(this, subscriptions)); } EventsReporterWrapper.ReportEvent(PubSubTopicsLoadedEvent.Create(CommandStatus.Success)); } catch (DataSourceException e) { EventsReporterWrapper.ReportEvent(PubSubTopicsLoadedEvent.Create(CommandStatus.Failure)); throw new CloudExplorerSourceException(e.Message, e); } }
/// <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; } }
private void OnStartInstanceCommand() { try { if (!UserPromptUtils.ActionPrompt( String.Format(Resources.CloudExplorerGceStartInstanceConfirmationPrompt, Instance.Name), String.Format(Resources.CloudExplorerGceStartInstanceConfirmationPromptCaption, Instance.Name), actionCaption: Resources.UiStartButtonCaption)) { Debug.WriteLine($"The user cancelled starting instance {Instance.Name}."); return; } var operation = _owner.DataSource.StartInstance(Instance); UpdateInstanceState(operation); EventsReporterWrapper.ReportEvent(StartGceInstanceEvent.Create(CommandStatus.Success)); } catch (DataSourceException ex) { GcpOutputWindow.Activate(); GcpOutputWindow.OutputLine(String.Format(Resources.CloudExplorerGceFailedToStartInstanceMessage, Instance.Name, ex.Message)); EventsReporterWrapper.ReportEvent(StartGceInstanceEvent.Create(CommandStatus.Failure)); } }
private async Task CreateRepoAsync() { var csrDatasource = CsrUtils.CreateCsrDataSource(_project.ProjectId); IsReady = false; try { var watch = Stopwatch.StartNew(); // No null check. By the time user gets here, csrDatasource won't be null. Result = await csrDatasource.CreateRepoAsync(RepositoryName.Trim()); EventsReporterWrapper.ReportEvent( CsrCreatedEvent.Create(CommandStatus.Success, duration: watch.Elapsed)); _owner.Close(); } catch (Exception) { EventsReporterWrapper.ReportEvent(CsrCreatedEvent.Create(CommandStatus.Failure)); throw; } finally { IsReady = true; } }
protected override async Task LoadDataOverride() { try { Debug.WriteLine("Loading list of services."); _gaeApplication = _dataSource.Value.GetApplicationAsync(); IList <ServiceViewModel> services = await LoadServiceList(); Children.Clear(); foreach (var item in services) { Children.Add(item); } if (Children.Count == 0) { Children.Add(s_noItemsPlacehoder); } EventsReporterWrapper.ReportEvent(GaeServicesLoadedEvent.Create(CommandStatus.Success)); } catch (DataSourceException ex) { GcpOutputWindow.OutputLine(Resources.CloudExplorerGaeFailedServicesMessage); GcpOutputWindow.OutputLine(ex.Message); GcpOutputWindow.Activate(); EventsReporterWrapper.ReportEvent(GaeServicesLoadedEvent.Create(CommandStatus.Failure)); throw new CloudExplorerSourceException(ex.Message, ex); } }
protected override async void OnIsExpandedChanged(bool newValue) { base.OnIsExpandedChanged(newValue); try { // If this is the first time the node has been expanded load it's resources. if (!_resourcesLoaded && newValue) { _resourcesLoaded = true; _versions = await root.DataSource.Value.GetVersionListAsync(Service.Id); Children.Clear(); if (_versions == null) { Children.Add(s_errorPlaceholder); } else { PresentViewModels(); UpdateContextMenu(); } } EventsReporterWrapper.ReportEvent(GaeVersionsLoadedEvent.Create(CommandStatus.Success)); } catch (DataSourceException ex) { GcpOutputWindow.OutputLine(Resources.CloudExplorerGaeFailedVersionsMessage); GcpOutputWindow.OutputLine(ex.Message); GcpOutputWindow.Activate(); EventsReporterWrapper.ReportEvent(GaeVersionsLoadedEvent.Create(CommandStatus.Failure)); throw new CloudExplorerSourceException(ex.Message, ex); } }
/// <summary> /// Runs the given <seealso cref="Action"/> and handles all non-critical exceptions by showing an /// error dialog to the user. If the exception is critical, as determiend by <seealso cref="ErrorHandler.IsCriticalException(Exception)"/> /// then it is re-thrown as this could be that the process is not in a good state to continue executing. /// </summary> /// <param name="action"></param> public static void HandleExceptions(Action action) { try { action(); } catch (AggregateException ex) { Debug.WriteLine($"Uncaught aggregate exception: {ex.Message}"); if (ErrorHandler.ContainsCriticalException(ex)) { throw; } EventsReporterWrapper.ReportEvent(UnhandledExceptionEvent.Create(ex)); UserPromptUtils.ExceptionPrompt(ex); } catch (Exception ex) { Debug.WriteLine($"Uncaught exception: {ex.Message}"); if (ErrorHandler.IsCriticalException(ex)) { throw; } EventsReporterWrapper.ReportEvent(UnhandledExceptionEvent.Create(ex)); UserPromptUtils.ExceptionPrompt(ex); } }
/// <summary> /// Initializes a new instance of the <see cref="ErrorReportingToolWindowCommand"/> class. /// Adds our command handlers for menu (commands must exist in the command table file) /// </summary> /// <param name="package">Owner package, not null.</param> private ErrorReportingToolWindowCommand(Package package) { if (package == null) { throw new ArgumentNullException("package"); } _package = package; IMenuCommandService commandService = this.ServiceProvider.GetService(typeof(IMenuCommandService)) as IMenuCommandService; if (commandService != null) { var menuCommandID = new CommandID(CommandSet, CommandId); var menuItem = new OleMenuCommand( (sender, e) => { ToolWindowCommandUtils.ShowToolWindow <ErrorReportingToolWindow>(); EventsReporterWrapper.ReportEvent(ErrorsViewerOpenEvent.Create()); }, menuCommandID); menuItem.BeforeQueryStatus += ToolWindowCommandUtils.EnableMenuItemOnValidProjectId; commandService.AddCommand(menuItem); } }
/// <summary> /// Get a list of local repositories. It is saved to local variable localRepos. /// For each local repository, get remote urls list. /// From each URL, get the project-id. /// Now, check if the list of 'cloud repositories' under the project-id contains the URL. /// If it does, the local repository with the URL will be shown to user. /// </summary> private async Task ListRepositoryAsync() { if (!IsReady) { return; } var projects = await GetProjectsAsync(); IsReady = false; Repositories.Clear(); try { var watch = Stopwatch.StartNew(); await AddLocalReposAsync(await GetLocalGitRepositoriesAsync(), projects); EventsReporterWrapper.ReportEvent( CsrListedEvent.Create(CommandStatus.Success, watch.Elapsed)); ShowActiveRepo(_teamExplorer.GetActiveRepository()); } catch (Exception) { EventsReporterWrapper.ReportEvent(CsrListedEvent.Create(CommandStatus.Failure)); throw; } finally { IsReady = true; } }
protected override async Task LoadDataOverrideAsync() { try { _instancesPerZone = null; _instancesPerZone = await _dataSource.Value.GetAllInstancesPerZonesAsync(); PresentViewModels(); EventsReporterWrapper.ReportEvent(GceVMsLoadedEvent.Create(CommandStatus.Success)); } catch (DataSourceException ex) { var innerEx = ex.InnerException as GoogleApiException; if (innerEx != null && innerEx.HttpStatusCode == System.Net.HttpStatusCode.Forbidden) { Debug.WriteLine("The GCE API is not enabled."); // Show the node that notifies users that the API is disabled. Children.Clear(); Children.Add(new DisabledApiWarning( apiName: ComputeApiName, caption: Resources.CloudExplorerGceSourceApiDisabledMessage, project: Context.CurrentProject)); return; } EventsReporterWrapper.ReportEvent(GceVMsLoadedEvent.Create(CommandStatus.Failure)); throw new CloudExplorerSourceException(ex.Message, ex); } }
private async Task OnStopInstanceCommandAsync() { try { if (!UserPromptService.Default.ActionPrompt( String.Format(Resources.CloudExplorerGceStopInstanceConfirmationPrompt, Instance.Name), String.Format(Resources.CloudExplorerGceStopInstanceConfirmationPromptCaption, Instance.Name), actionCaption: Resources.UiStopButtonCaption)) { Debug.WriteLine($"The user cancelled stopping instance {Instance.Name}."); return; } var operation = _owner.DataSource.StopInstance(Instance); await UpdateInstanceStateAsync(operation); EventsReporterWrapper.ReportEvent(StopGceInstanceEvent.Create(CommandStatus.Success)); } catch (DataSourceException ex) { await GcpOutputWindow.Default.ActivateAsync(); await GcpOutputWindow.Default.OutputLineAsync(String.Format(Resources.CloudExplorerGceFailedToStopInstanceMessage, Instance.Name, ex.Message)); EventsReporterWrapper.ReportEvent(StopGceInstanceEvent.Create(CommandStatus.Failure)); } }
/// <summary> /// Publishes the ASP.NET Core project to App Engine Flex and reports progress to the UI. /// </summary> /// <param name="project">The project to deploy.</param> /// <param name="options">The <see cref="DeploymentOptions"/> to use.</param> public async Task PublishProjectAsync(IParsedProject project, DeploymentOptions options) { try { ShellUtils.SaveAllFiles(); GcpOutputWindow.Activate(); GcpOutputWindow.Clear(); GcpOutputWindow.OutputLine(string.Format(Resources.FlexPublishStepStartMessage, project.Name)); TimeSpan deploymentDuration; AppEngineFlexDeploymentResult result; using (StatusbarHelper.Freeze()) using (StatusbarHelper.ShowDeployAnimation()) using (ProgressBarHelper progress = StatusbarHelper.ShowProgressBar(Resources.FlexPublishProgressMessage)) using (ShellUtils.SetShellUIBusy()) { DateTime startDeploymentTime = DateTime.Now; result = await PublishProjectAsync( project, options, progress, VsVersionUtils.ToolsPathProvider, GcpOutputWindow.OutputLine); deploymentDuration = DateTime.Now - startDeploymentTime; } if (result != null) { GcpOutputWindow.OutputLine(string.Format(Resources.FlexPublishSuccessMessage, project.Name)); StatusbarHelper.SetText(Resources.PublishSuccessStatusMessage); string url = result.GetDeploymentUrl(); GcpOutputWindow.OutputLine(string.Format(Resources.PublishUrlMessage, url)); if (options.OpenWebsite) { Process.Start(url); } EventsReporterWrapper.ReportEvent( GaeDeployedEvent.Create(CommandStatus.Success, deploymentDuration)); } else { GcpOutputWindow.OutputLine(string.Format(Resources.FlexPublishFailedMessage, project.Name)); StatusbarHelper.SetText(Resources.PublishFailureStatusMessage); EventsReporterWrapper.ReportEvent(GaeDeployedEvent.Create(CommandStatus.Failure, deploymentDuration)); } } catch (Exception) { EventsReporterWrapper.ReportEvent(GaeDeployedEvent.Create(CommandStatus.Failure)); GcpOutputWindow.OutputLine(string.Format(Resources.FlexPublishFailedMessage, project.Name)); StatusbarHelper.SetText(Resources.PublishFailureStatusMessage); } }
/// <summary> /// Load data from Google Cloud Error Reporting API service end point. /// It shows a progress control when waiting for data. /// In the end, if there is known type of exception, show a generic error.. /// </summary> private async Task LoadAsync() { if (DataSource == null) { return; } if (_isLoading) { Debug.WriteLine("_isLoading is true, quit LoadAsync."); return; } IsLoadingComplete = false; ListGroupStatsResponse results = null; ShowError = false; IsRefreshing = _nextPageToken == null; IsLoadingNextPage = _nextPageToken != null; try { var startTimestamp = DateTime.Now; if (SelectedTimeRangeItem == null) { throw new ErrorReportingException(new InvalidOperationException(nameof(SelectedTimeRangeItem))); } results = await DataSource?.GetPageOfGroupStatusAsync( SelectedTimeRangeItem.GroupTimeRange, SelectedTimeRangeItem.TimedCountDuration, nextPageToken : _nextPageToken); EventsReporterWrapper.ReportEvent(ErrorsViewerErrorsLoadedEvent.Create(CommandStatus.Success, DateTime.Now - startTimestamp)); } catch (DataSourceException) { ShowError = true; ErrorString = Resources.ErrorReportingDataSourceGenericErrorMessage; EventsReporterWrapper.ReportEvent(ErrorsViewerErrorsLoadedEvent.Create(CommandStatus.Failure)); } catch (ErrorReportingException) { ShowError = true; ErrorString = Resources.ErrorReportingInternalCodeErrorGenericMessage; EventsReporterWrapper.ReportEvent(ErrorsViewerErrorsLoadedEvent.Create(CommandStatus.Failure)); } finally { IsLoadingComplete = true; IsRefreshing = false; IsLoadingNextPage = false; } // results can be null when (1) there is exception. (2) current account is empty. _nextPageToken = results?.NextPageToken; AddItems(results?.ErrorGroupStats); }
/// <summary> /// Update the serving status of the version. /// </summary> /// <param name="status">The serving status to update the version to.</param> /// <param name="statusMessage">The message to display while updating the status</param> private async void UpdateServingStatus(string status, string statusMessage) { IsLoading = true; Children.Clear(); UpdateMenu(); Caption = statusMessage; GaeDataSource datasource = root.DataSource.Value; try { Task <Operation> operationTask = datasource.UpdateVersionServingStatus(status, _owner.Service.Id, version.Id); Func <Operation, Task <Operation> > fetch = (o) => datasource.GetOperationAsync(o.GetOperationId()); Predicate <Operation> stopPolling = (o) => o.Done ?? false; Operation operation = await Polling <Operation> .Poll(await operationTask, fetch, stopPolling); if (operation.Error != null) { throw new DataSourceException(operation.Error.Message); } version = await datasource.GetVersionAsync(_owner.Service.Id, version.Id); EventsReporterWrapper.ReportEvent( GaeVersionServingStatusUpdatedEvent.Create(CommandStatus.Success, statusMessage)); } catch (Exception ex) when(ex is DataSourceException || ex is TimeoutException || ex is OperationCanceledException) { EventsReporterWrapper.ReportEvent( GaeVersionServingStatusUpdatedEvent.Create(CommandStatus.Failure, statusMessage)); IsError = true; if (ex is DataSourceException) { Caption = Resources.CloudExplorerGaeUpdateServingStatusErrorMessage; } else if (ex is TimeoutException) { Caption = Resources.CloudExploreOperationTimeoutMessage; } else if (ex is OperationCanceledException) { Caption = Resources.CloudExploreOperationCanceledMessage; } } finally { IsLoading = false; // Re-initialize the instance as it will have a new version. if (!IsError) { Initialize(); } else { Caption = GetCaption(); } } }
private void OnOpenOnCloudConsoleCommand() { EventsReporterWrapper.ReportEvent(OpenGceInstanceOnCloudConsoleEvent.Create()); var url = $"https://console.cloud.google.com/compute/instancesDetail/zones/{_instance.GetZoneName()}/instances/{_instance.Name}?project={_owner.Context.CurrentProject.ProjectId}"; Process.Start(url); }
private void NavigateToDetailWindow(ErrorGroupItem groupItem) { var window = ToolWindowCommandUtils.ShowToolWindow <ErrorReportingDetailToolWindow>(); window.ViewModel.UpdateView(groupItem, _selectedTimeRange); EventsReporterWrapper.ReportEvent(ErrorsViewerNavigateToDetailWindowEvent.Create()); }
/// <summary> /// Cancel request button command. /// </summary> private void CancelRequest() { Debug.WriteLine("Cancel command is called"); RequestStatusText = Resources.LogViewerRequestCancellingMessage; ShowCancelRequestButton = false; _cancellationTokenSource?.Cancel(); EventsReporterWrapper.ReportEvent(LogsViewerCancelRequestEvent.Create()); }
private async Task NavigateToDetailWindowAsync(ErrorGroupItem groupItem) { ErrorReportingDetailToolWindow window = await ToolWindowCommandUtils.ShowToolWindowAsync <ErrorReportingDetailToolWindow>(); window.ViewModel.UpdateView(groupItem, _selectedTimeRange); EventsReporterWrapper.ReportEvent(ErrorsViewerNavigateToDetailWindowEvent.Create()); }
private void OnOpenWebsite() { EventsReporterWrapper.ReportEvent(OpenGceInstanceWebsiteEvent.Create()); var url = Instance.GetDestinationAppUri(); Debug.WriteLine($"Opening Web Site: {url}"); Process.Start(url); }
private void OnOpenConCloudConsoleCommand() { EventsReporterWrapper.ReportEvent(OpenGcsBucketOnCloudConsoleEvent.Create()); var url = $"https://console.cloud.google.com/storage/browser/{_bucket.Name}/?project={CredentialsStore.Default.CurrentProjectId}"; Debug.WriteLine($"Starting bucket browsing at: {url}"); Process.Start(url); }
/// <summary> /// Method called to upload the given set of files. /// </summary> /// <param name="files">The list of files to upload to the bucket.</param> public void StartDroppedFilesUpload(IEnumerable <string> files) { // Attempts to set VS as the foreground window so the user can see the progress // of the upload operation. Similar to what is done in the Windows explorer. ShellUtils.SetForegroundWindow(); EventsReporterWrapper.ReportEvent(GcsFileBrowserFilesDroppedEvent.Create()); UploadFiles(files); }
private async void OnAddAccountCommand() { Debug.WriteLine("Stating the oauth login flow."); if (await AccountsManager.StartAddAccountFlowAsync()) { EventsReporterWrapper.ReportEvent(NewLoginEvent.Create()); Debug.WriteLine($"The user logged in: {CredentialsStore.Default.CurrentAccount.AccountName}"); _owner.Close(); } }
protected override async Task LoadDataOverrideAsync() { try { Debug.WriteLine("Loading list of services."); GaeApplication = await _dataSource.Value.GetApplicationAsync(); if (GaeApplication == null) { var noAppEngineAppPlaceholder = new TreeLeaf { Caption = Resources.CloudExplorerGaeNoAppFoundCaption, IsError = true, ContextMenu = new ContextMenu { ItemsSource = new List <MenuItem> { new MenuItem { Header = Resources.CloudExplorerGaeSetAppRegionMenuHeader, Command = new ProtectedAsyncCommand(OnSetAppRegionAsync) } } } }; Children.Clear(); Children.Add(noAppEngineAppPlaceholder); return; } IList <ServiceViewModel> services = await LoadServiceListAsync(); Children.Clear(); foreach (var item in services) { Children.Add(item); } if (Children.Count == 0) { Children.Add(s_noItemsPlacehoder); } EventsReporterWrapper.ReportEvent(GaeServicesLoadedEvent.Create(CommandStatus.Success)); } catch (DataSourceException ex) { await GcpOutputWindow.Default.OutputLineAsync(Resources.CloudExplorerGaeFailedServicesMessage); await GcpOutputWindow.Default.OutputLineAsync(ex.Message); await GcpOutputWindow.Default.ActivateAsync(); EventsReporterWrapper.ReportEvent(GaeServicesLoadedEvent.Create(CommandStatus.Failure)); throw new CloudExplorerSourceException(ex.Message, ex); } }
/// <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="autoReload">Indicate if the request comes from autoReload event.</param> private async Task LoadLogsAsync(bool autoReload = false) { var tokenSource = new CancellationTokenSource(); CancellationToken cancellationToken = tokenSource.Token; CancellationTokenSource = tokenSource; if (_logs.Count >= MaxLogEntriesCount) { UserPromptService.Default.ErrorPrompt( message: Resources.LogViewerResultSetTooLargeMessage, title: Resources.UiDefaultPromptTitle); CancellationTokenSource?.Cancel(); return; } try { DateTime startTimestamp = DateTime.Now; string order = DateTimePickerModel.IsDescendingOrder ? "timestamp desc" : "timestamp asc"; int count = 0; do { // Here, it does not do pageSize: _defaultPageSize - count, // Because this is requried to use same page size for getting next page. LogEntryRequestResult results = await DataSource.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; } } while (count < DefaultPageSize && !cancellationToken.IsCancellationRequested && _nextPageToken != null); EventsReporterWrapper.ReportEvent(LogsViewerLogsLoadedEvent.Create(CommandStatus.Success, DateTime.Now - startTimestamp)); } catch (Exception) { _nextPageToken = null; EventsReporterWrapper.ReportEvent(LogsViewerLogsLoadedEvent.Create(CommandStatus.Failure)); throw; } }
#pragma warning disable VSTHRD100 // Avoid async void methods /// <summary> /// Runs the given <seealso cref="Task"/> and handles all non-critical exceptions by showing an /// error dialog to the user. If the exception is critical, as determined by /// <seealso cref="ErrorHandler.IsCriticalException(Exception)"/>, then it /// is re-thrown as this could be that the process is not in a good state to continue executing. /// </summary> /// <remarks> /// This method is intentionally async void, as it is meant to be the fire and forget method for tasks. /// </remarks> public static async void HandleExceptionsAsync(Func <Task> taskFunc) { try { await taskFunc(); } catch (Exception ex) when(!IsCriticalException(ex)) { EventsReporterWrapper.ReportEvent(UnhandledExceptionEvent.Create(ex)); UserPromptService.Default.ExceptionPrompt(ex); } }