Update action run return type (#15568)

* Update action run return type

* fix tests

* Update rest

* Add back null checks
This commit is contained in:
Charles Gagnon
2021-05-25 14:52:39 -07:00
committed by GitHub
parent 25352fa39c
commit 399406b732
29 changed files with 379 additions and 637 deletions

View File

@@ -18,12 +18,7 @@ export class CloseTabAction extends Action {
super(CloseTabAction.ID, CloseTabAction.LABEL, CloseTabAction.ICON); super(CloseTabAction.ID, CloseTabAction.LABEL, CloseTabAction.ICON);
} }
run(): Promise<boolean> { async run(): Promise<void> {
try { this.closeFn.apply(this.context);
this.closeFn.apply(this.context);
return Promise.resolve(true);
} catch (e) {
return Promise.resolve(false);
}
} }
} }

View File

@@ -9,7 +9,7 @@ import { localize } from 'vs/nls';
import { Action } from 'vs/base/common/actions'; import { Action } from 'vs/base/common/actions';
import { IAccountManagementService } from 'sql/platform/accounts/common/interfaces'; import { IAccountManagementService } from 'sql/platform/accounts/common/interfaces';
import { IDialogService, IConfirmation, IConfirmationResult } from 'vs/platform/dialogs/common/dialogs'; import { IDialogService, IConfirmation } from 'vs/platform/dialogs/common/dialogs';
import { INotificationService } from 'vs/platform/notification/common/notification'; import { INotificationService } from 'vs/platform/notification/common/notification';
import Severity from 'vs/base/common/severity'; import Severity from 'vs/base/common/severity';
import { ILogService } from 'vs/platform/log/common/log'; import { ILogService } from 'vs/platform/log/common/log';
@@ -45,21 +45,18 @@ export class AddAccountAction extends Action {
this._addAccountStartEmitter = new Emitter<void>(); this._addAccountStartEmitter = new Emitter<void>();
} }
public run(): Promise<boolean> { public async run(): Promise<void> {
// Fire the event that we've started adding accounts // Fire the event that we've started adding accounts
this._addAccountStartEmitter.fire(); this._addAccountStartEmitter.fire();
try {
return Promise.resolve(this._accountManagementService.addAccount(this._providerId) await this._accountManagementService.addAccount(this._providerId);
.then(() => { this._addAccountCompleteEmitter.fire();
this._addAccountCompleteEmitter.fire(); } catch (err) {
return true; this.logService.error(`Error while adding account: ${err}`);
}, err => { this._addAccountErrorEmitter.fire(err);
this.logService.error(`Error while adding account: ${err}`); this._addAccountCompleteEmitter.fire();
this._addAccountErrorEmitter.fire(err); }
this._addAccountCompleteEmitter.fire();
return false;
}));
} }
} }
@@ -79,7 +76,7 @@ export class RemoveAccountAction extends Action {
super(RemoveAccountAction.ID, RemoveAccountAction.LABEL, 'remove-account-action codicon remove'); super(RemoveAccountAction.ID, RemoveAccountAction.LABEL, 'remove-account-action codicon remove');
} }
public run(): Promise<boolean> { public async run(): Promise<void> {
// Ask for Confirm // Ask for Confirm
const confirm: IConfirmation = { const confirm: IConfirmation = {
message: localize('confirmRemoveUserAccountMessage', "Are you sure you want to remove '{0}'?", this._account.displayInfo.displayName), message: localize('confirmRemoveUserAccountMessage', "Are you sure you want to remove '{0}'?", this._account.displayInfo.displayName),
@@ -88,20 +85,17 @@ export class RemoveAccountAction extends Action {
type: 'question' type: 'question'
}; };
return this._dialogService.confirm(confirm).then((result: IConfirmationResult) => { const result = await this._dialogService.confirm(confirm);
if (!result || !result.confirmed) { if (result?.confirmed) {
return Promise.resolve(false); try {
} else { await this._accountManagementService.removeAccount(this._account.key);
return Promise.resolve(this._accountManagementService.removeAccount(this._account.key)).catch(err => { } catch (err) {
// Must handle here as this is an independent action this._notificationService.notify({
this._notificationService.notify({ severity: Severity.Error,
severity: Severity.Error, message: localize('removeAccountFailed', "Failed to remove account")
message: localize('removeAccountFailed', "Failed to remove account")
});
return false;
}); });
} }
}); }
} }
} }
@@ -119,9 +113,8 @@ export class ApplyFilterAction extends Action {
super(id, label, 'apply-filters-action codicon filter'); super(id, label, 'apply-filters-action codicon filter');
} }
public run(): Promise<boolean> { public async run(): Promise<void> {
// Todo: apply filter to the account // Todo: apply filter to the account
return Promise.resolve(true);
} }
} }
@@ -139,18 +132,16 @@ export class RefreshAccountAction extends Action {
) { ) {
super(RefreshAccountAction.ID, RefreshAccountAction.LABEL, 'refresh-account-action codicon refresh'); super(RefreshAccountAction.ID, RefreshAccountAction.LABEL, 'refresh-account-action codicon refresh');
} }
public run(): Promise<boolean> { public async run(): Promise<void> {
if (this.account) { if (this.account) {
return Promise.resolve(this._accountManagementService.refreshAccount(this.account) try {
.then(() => true, await this._accountManagementService.refreshAccount(this.account);
err => { } catch (err) {
this.logService.error(`Error while refreshing account: ${err}`); this.logService.error(`Error while refreshing account: ${err}`);
return Promise.reject(err); }
}
));
} else { } else {
const errorMessage = localize('NoAccountToRefresh', "There is no account to refresh"); const errorMessage = localize('NoAccountToRefresh', "There is no account to refresh");
return Promise.reject(errorMessage); throw new Error(errorMessage);
} }
} }
} }

View File

@@ -45,13 +45,11 @@ export class ManageAction extends Action {
super(id, label); super(id, label);
} }
async run(actionContext: ManageActionContext): Promise<boolean> { async run(actionContext: ManageActionContext): Promise<void> {
if (actionContext.profile) { if (actionContext.profile) {
await this._connectionManagementService.connect(actionContext.profile, actionContext.uri, { showDashboard: true, saveTheConnection: false, params: undefined, showConnectionDialogOnError: false, showFirewallRuleOnError: true }); await this._connectionManagementService.connect(actionContext.profile, actionContext.uri, { showDashboard: true, saveTheConnection: false, params: undefined, showConnectionDialogOnError: false, showFirewallRuleOnError: true });
this._angularEventingService.sendAngularEvent(actionContext.uri, AngularEventType.NAV_DATABASE); this._angularEventingService.sendAngularEvent(actionContext.uri, AngularEventType.NAV_DATABASE);
return true;
} }
return false;
} }
} }

View File

@@ -26,8 +26,8 @@ export class ScriptSelectAction extends Action {
super(id, label); super(id, label);
} }
public async run(actionContext: BaseActionContext): Promise<boolean> { public async run(actionContext: BaseActionContext): Promise<void> {
return scriptSelect( await scriptSelect(
actionContext.profile!, actionContext.profile!,
actionContext.object!, actionContext.object!,
this._connectionManagementService, this._connectionManagementService,
@@ -51,8 +51,8 @@ export class ScriptExecuteAction extends Action {
super(id, label); super(id, label);
} }
public async run(actionContext: BaseActionContext): Promise<boolean> { public async run(actionContext: BaseActionContext): Promise<void> {
return script( await script(
actionContext.profile!, actionContext.profile!,
actionContext.object!, actionContext.object!,
this._connectionManagementService, this._connectionManagementService,
@@ -78,8 +78,8 @@ export class ScriptAlterAction extends Action {
super(id, label); super(id, label);
} }
public async run(actionContext: BaseActionContext): Promise<boolean> { public async run(actionContext: BaseActionContext): Promise<void> {
return script( await script(
actionContext.profile!, actionContext.profile!,
actionContext.object!, actionContext.object!,
this._connectionManagementService, this._connectionManagementService,
@@ -104,8 +104,8 @@ export class EditDataAction extends Action {
super(id, label); super(id, label);
} }
public async run(actionContext: BaseActionContext): Promise<boolean> { public async run(actionContext: BaseActionContext): Promise<void> {
return scriptEditSelect( await scriptEditSelect(
actionContext.profile!, actionContext.profile!,
actionContext.object!, actionContext.object!,
this._connectionManagementService, this._connectionManagementService,
@@ -129,8 +129,8 @@ export class ScriptCreateAction extends Action {
super(id, label); super(id, label);
} }
public async run(actionContext: BaseActionContext): Promise<boolean> { public async run(actionContext: BaseActionContext): Promise<void> {
return script( await script(
actionContext.profile!, actionContext.profile!,
actionContext.object!, actionContext.object!,
this._connectionManagementService, this._connectionManagementService,
@@ -156,8 +156,8 @@ export class ScriptDeleteAction extends Action {
super(id, label); super(id, label);
} }
public async run(actionContext: BaseActionContext): Promise<boolean> { public async run(actionContext: BaseActionContext): Promise<void> {
return script( await script(
actionContext.profile!, actionContext.profile!,
actionContext.object!, actionContext.object!,
this._connectionManagementService, this._connectionManagementService,

View File

@@ -60,7 +60,7 @@ abstract class AsmtServerAction extends Action {
super(id, label, TARGET_ICON_CLASS[AssessmentTargetType.Server]); super(id, label, TARGET_ICON_CLASS[AssessmentTargetType.Server]);
} }
public async run(context: IAsmtActionInfo): Promise<boolean> { public async run(context: IAsmtActionInfo): Promise<void> {
this._telemetryService.sendActionEvent(TelemetryView.SqlAssessment, this.id); this._telemetryService.sendActionEvent(TelemetryView.SqlAssessment, this.id);
if (context && context.component && !context.component.isBusy) { if (context && context.component && !context.component.isBusy) {
context.component.showProgress(this.asmtType); context.component.showProgress(this.asmtType);
@@ -87,11 +87,7 @@ abstract class AsmtServerAction extends Action {
} }
context.component.stopProgress(this.asmtType); context.component.stopProgress(this.asmtType);
return true;
} }
return false;
} }
abstract getServerItems(ownerUri: string): Thenable<SqlAssessmentResult>; abstract getServerItems(ownerUri: string): Thenable<SqlAssessmentResult>;
@@ -137,16 +133,14 @@ export class AsmtDatabaseSelectItemsAction extends Action {
TARGET_ICON_CLASS[AssessmentTargetType.Database]); TARGET_ICON_CLASS[AssessmentTargetType.Database]);
} }
public async run(context: IAsmtActionInfo): Promise<boolean> { public async run(context: IAsmtActionInfo): Promise<void> {
this._telemetryService.sendActionEvent(TelemetryView.SqlAssessment, this.id); this._telemetryService.sendActionEvent(TelemetryView.SqlAssessment, this.id);
if (context && context.component && !context.component.isBusy) { if (context && context.component && !context.component.isBusy) {
context.component.showProgress(AssessmentType.AvailableRules); context.component.showProgress(AssessmentType.AvailableRules);
let dbAsmtResults = await this._assessmentService.getAssessmentItems(context.ownerUri, AssessmentTargetType.Database); let dbAsmtResults = await this._assessmentService.getAssessmentItems(context.ownerUri, AssessmentTargetType.Database);
context.component.showInitialResults(dbAsmtResults, AssessmentType.AvailableRules); context.component.showInitialResults(dbAsmtResults, AssessmentType.AvailableRules);
context.component.stopProgress(AssessmentType.AvailableRules); context.component.stopProgress(AssessmentType.AvailableRules);
return true;
} }
return false;
} }
} }
@@ -185,16 +179,14 @@ export class AsmtDatabaseInvokeItemsAction extends Action {
TARGET_ICON_CLASS[AssessmentTargetType.Database]); TARGET_ICON_CLASS[AssessmentTargetType.Database]);
} }
public async run(context: IAsmtActionInfo): Promise<boolean> { public async run(context: IAsmtActionInfo): Promise<void> {
this._telemetryService.sendActionEvent(TelemetryView.SqlAssessment, this.id); this._telemetryService.sendActionEvent(TelemetryView.SqlAssessment, this.id);
if (context && context.component && !context.component.isBusy) { if (context && context.component && !context.component.isBusy) {
context.component.showProgress(AssessmentType.InvokeAssessment); context.component.showProgress(AssessmentType.InvokeAssessment);
let dbAsmtResults = await this._assessmentService.assessmentInvoke(context.ownerUri, AssessmentTargetType.Database); let dbAsmtResults = await this._assessmentService.assessmentInvoke(context.ownerUri, AssessmentTargetType.Database);
context.component.showInitialResults(dbAsmtResults, AssessmentType.InvokeAssessment); context.component.showInitialResults(dbAsmtResults, AssessmentType.InvokeAssessment);
context.component.stopProgress(AssessmentType.InvokeAssessment); context.component.stopProgress(AssessmentType.InvokeAssessment);
return true;
} }
return false;
} }
} }
@@ -209,14 +201,12 @@ export class AsmtExportAsScriptAction extends Action {
super(AsmtExportAsScriptAction.ID, AsmtExportAsScriptAction.LABEL, 'exportAsScriptIcon'); super(AsmtExportAsScriptAction.ID, AsmtExportAsScriptAction.LABEL, 'exportAsScriptIcon');
} }
public async run(context: IAsmtActionInfo): Promise<boolean> { public async run(context: IAsmtActionInfo): Promise<void> {
this._telemetryService.sendActionEvent(TelemetryView.SqlAssessment, AsmtExportAsScriptAction.ID); this._telemetryService.sendActionEvent(TelemetryView.SqlAssessment, AsmtExportAsScriptAction.ID);
const items = context?.component?.recentResult?.result.items; const items = context?.component?.recentResult?.result.items;
if (items) { if (items) {
await this._assessmentService.generateAssessmentScript(context.ownerUri, items); await this._assessmentService.generateAssessmentScript(context.ownerUri, items);
return true;
} }
return false;
} }
} }
@@ -234,9 +224,9 @@ export class AsmtSamplesLinkAction extends Action {
super(AsmtSamplesLinkAction.ID, AsmtSamplesLinkAction.LABEL, AsmtSamplesLinkAction.ICON); super(AsmtSamplesLinkAction.ID, AsmtSamplesLinkAction.LABEL, AsmtSamplesLinkAction.ICON);
} }
public async run(): Promise<boolean> { public async run(): Promise<void> {
this._telemetryService.sendActionEvent(TelemetryView.SqlAssessment, AsmtSamplesLinkAction.ID); this._telemetryService.sendActionEvent(TelemetryView.SqlAssessment, AsmtSamplesLinkAction.ID);
return this._openerService.open(URI.parse(AsmtSamplesLinkAction.configHelpUri)); await this._openerService.open(URI.parse(AsmtSamplesLinkAction.configHelpUri));
} }
} }
@@ -262,12 +252,12 @@ export class AsmtGenerateHTMLReportAction extends Action {
return URI.file(filePath); return URI.file(filePath);
} }
public async run(context: IAsmtActionInfo): Promise<boolean> { public async run(context: IAsmtActionInfo): Promise<void> {
context.component.showProgress(AssessmentType.ReportGeneration); context.component.showProgress(AssessmentType.ReportGeneration);
const choosenPath = await this._fileDialogService.pickFileToSave(this.suggestReportFile(context.component.recentResult.dateUpdated)); const choosenPath = await this._fileDialogService.pickFileToSave(this.suggestReportFile(context.component.recentResult.dateUpdated));
context.component.stopProgress(AssessmentType.ReportGeneration); context.component.stopProgress(AssessmentType.ReportGeneration);
if (!choosenPath) { if (!choosenPath) {
return false; return;
} }
this._telemetryService.sendActionEvent(TelemetryView.SqlAssessment, AsmtGenerateHTMLReportAction.ID); this._telemetryService.sendActionEvent(TelemetryView.SqlAssessment, AsmtGenerateHTMLReportAction.ID);
@@ -291,7 +281,6 @@ export class AsmtGenerateHTMLReportAction extends Action {
run: () => { } run: () => { }
}]); }]);
} }
return true;
} }
} }

View File

@@ -137,8 +137,7 @@ suite('Assessment Actions', () => {
assert.equal(action.id, AsmtServerSelectItemsAction.ID, 'Get Server Rules id action mismatch'); assert.equal(action.id, AsmtServerSelectItemsAction.ID, 'Get Server Rules id action mismatch');
assert.equal(action.label, AsmtServerSelectItemsAction.LABEL, 'Get Server Rules label action mismatch'); assert.equal(action.label, AsmtServerSelectItemsAction.LABEL, 'Get Server Rules label action mismatch');
let result = await action.run({ ownerUri: '', component: mockAsmtViewComponent.object, connectionId: '' }); await action.run({ ownerUri: '', component: mockAsmtViewComponent.object, connectionId: '' });
assert.ok(result, 'Get Server Rules action should succeed');
mockAsmtViewComponent.verify(s => s.showProgress(AssessmentType.AvailableRules), TypeMoq.Times.once()); mockAsmtViewComponent.verify(s => s.showProgress(AssessmentType.AvailableRules), TypeMoq.Times.once());
mockAssessmentService.verify(s => s.getAssessmentItems(TypeMoq.It.isAny(), AssessmentTargetType.Server), TypeMoq.Times.once()); mockAssessmentService.verify(s => s.getAssessmentItems(TypeMoq.It.isAny(), AssessmentTargetType.Server), TypeMoq.Times.once());
mockAsmtViewComponent.verify(s => s.showInitialResults(TypeMoq.It.isAny(), AssessmentType.AvailableRules), TypeMoq.Times.once()); mockAsmtViewComponent.verify(s => s.showInitialResults(TypeMoq.It.isAny(), AssessmentType.AvailableRules), TypeMoq.Times.once());
@@ -161,8 +160,7 @@ suite('Assessment Actions', () => {
assert.equal(action.id, AsmtServerInvokeItemsAction.ID, 'Invoke Server Assessment id action mismatch'); assert.equal(action.id, AsmtServerInvokeItemsAction.ID, 'Invoke Server Assessment id action mismatch');
assert.equal(action.label, AsmtServerInvokeItemsAction.LABEL, 'Invoke Server Assessment label action mismatch'); assert.equal(action.label, AsmtServerInvokeItemsAction.LABEL, 'Invoke Server Assessment label action mismatch');
let result = await action.run({ ownerUri: '', component: mockAsmtViewComponent.object, connectionId: '' }); await action.run({ ownerUri: '', component: mockAsmtViewComponent.object, connectionId: '' });
assert.ok(result, 'Invoke Server Assessment action should succeed');
mockAsmtViewComponent.verify(s => s.showProgress(AssessmentType.InvokeAssessment), TypeMoq.Times.once()); mockAsmtViewComponent.verify(s => s.showProgress(AssessmentType.InvokeAssessment), TypeMoq.Times.once());
mockAssessmentService.verify(s => s.assessmentInvoke(TypeMoq.It.isAny(), AssessmentTargetType.Server), TypeMoq.Times.once()); mockAssessmentService.verify(s => s.assessmentInvoke(TypeMoq.It.isAny(), AssessmentTargetType.Server), TypeMoq.Times.once());
mockAsmtViewComponent.verify(s => s.showInitialResults(TypeMoq.It.isAny(), AssessmentType.InvokeAssessment), TypeMoq.Times.once()); mockAsmtViewComponent.verify(s => s.showInitialResults(TypeMoq.It.isAny(), AssessmentType.InvokeAssessment), TypeMoq.Times.once());
@@ -177,8 +175,7 @@ suite('Assessment Actions', () => {
const action = new AsmtDatabaseSelectItemsAction('databaseName', mockAssessmentService.object, new NullAdsTelemetryService()); const action = new AsmtDatabaseSelectItemsAction('databaseName', mockAssessmentService.object, new NullAdsTelemetryService());
assert.equal(action.id, AsmtDatabaseSelectItemsAction.ID, 'Get Database Rules id action mismatch'); assert.equal(action.id, AsmtDatabaseSelectItemsAction.ID, 'Get Database Rules id action mismatch');
let result = await action.run({ ownerUri: '', component: mockAsmtViewComponent.object, connectionId: '' }); await action.run({ ownerUri: '', component: mockAsmtViewComponent.object, connectionId: '' });
assert.ok(result, 'Get Assessment Database action should succeed');
mockAsmtViewComponent.verify(s => s.showProgress(AssessmentType.AvailableRules), TypeMoq.Times.once()); mockAsmtViewComponent.verify(s => s.showProgress(AssessmentType.AvailableRules), TypeMoq.Times.once());
mockAsmtViewComponent.verify(s => s.showInitialResults(TypeMoq.It.isAny(), AssessmentType.AvailableRules), TypeMoq.Times.once()); mockAsmtViewComponent.verify(s => s.showInitialResults(TypeMoq.It.isAny(), AssessmentType.AvailableRules), TypeMoq.Times.once());
mockAsmtViewComponent.verify(s => s.stopProgress(AssessmentType.AvailableRules), TypeMoq.Times.once()); mockAsmtViewComponent.verify(s => s.stopProgress(AssessmentType.AvailableRules), TypeMoq.Times.once());
@@ -190,8 +187,7 @@ suite('Assessment Actions', () => {
const action = new AsmtDatabaseInvokeItemsAction('databaseName', mockAssessmentService.object, new NullAdsTelemetryService()); const action = new AsmtDatabaseInvokeItemsAction('databaseName', mockAssessmentService.object, new NullAdsTelemetryService());
assert.equal(action.id, AsmtDatabaseInvokeItemsAction.ID, 'Invoke Database Assessment id action mismatch'); assert.equal(action.id, AsmtDatabaseInvokeItemsAction.ID, 'Invoke Database Assessment id action mismatch');
let result = await action.run({ ownerUri: '', component: mockAsmtViewComponent.object, connectionId: '' }); await action.run({ ownerUri: '', component: mockAsmtViewComponent.object, connectionId: '' });
assert.ok(result, 'Invoke Database Assessment action should succeed');
mockAsmtViewComponent.verify(s => s.showProgress(AssessmentType.InvokeAssessment), TypeMoq.Times.once()); mockAsmtViewComponent.verify(s => s.showProgress(AssessmentType.InvokeAssessment), TypeMoq.Times.once());
mockAsmtViewComponent.verify(s => s.showInitialResults(TypeMoq.It.isAny(), AssessmentType.InvokeAssessment), TypeMoq.Times.once()); mockAsmtViewComponent.verify(s => s.showInitialResults(TypeMoq.It.isAny(), AssessmentType.InvokeAssessment), TypeMoq.Times.once());
mockAsmtViewComponent.verify(s => s.stopProgress(AssessmentType.InvokeAssessment), TypeMoq.Times.once()); mockAsmtViewComponent.verify(s => s.stopProgress(AssessmentType.InvokeAssessment), TypeMoq.Times.once());
@@ -204,8 +200,7 @@ suite('Assessment Actions', () => {
assert.equal(action.id, AsmtExportAsScriptAction.ID, 'Generate Assessment script id action mismatch'); assert.equal(action.id, AsmtExportAsScriptAction.ID, 'Generate Assessment script id action mismatch');
assert.equal(action.label, AsmtExportAsScriptAction.LABEL, 'Generate Assessment script label action mismatch'); assert.equal(action.label, AsmtExportAsScriptAction.LABEL, 'Generate Assessment script label action mismatch');
let result = await action.run({ ownerUri: '', component: mockAsmtViewComponent.object, connectionId: '' }); await action.run({ ownerUri: '', component: mockAsmtViewComponent.object, connectionId: '' });
assert.ok(result, 'Generate Script action should succeed');
mockAssessmentService.verify(s => s.generateAssessmentScript(TypeMoq.It.isAnyString(), TypeMoq.It.isAny()), TypeMoq.Times.once()); mockAssessmentService.verify(s => s.generateAssessmentScript(TypeMoq.It.isAnyString(), TypeMoq.It.isAny()), TypeMoq.Times.once());
}); });
@@ -217,8 +212,7 @@ suite('Assessment Actions', () => {
assert.equal(action.id, AsmtSamplesLinkAction.ID, 'Samples Link id action mismatch'); assert.equal(action.id, AsmtSamplesLinkAction.ID, 'Samples Link id action mismatch');
assert.equal(action.label, AsmtSamplesLinkAction.LABEL, 'Samples Link label action mismatch'); assert.equal(action.label, AsmtSamplesLinkAction.LABEL, 'Samples Link label action mismatch');
let result = await action.run(); await action.run();
assert.ok(result, 'Samples Link action should succeed');
openerService.verify(s => s.open(TypeMoq.It.isAny()), TypeMoq.Times.once()); openerService.verify(s => s.open(TypeMoq.It.isAny()), TypeMoq.Times.once());
}); });
@@ -259,8 +253,7 @@ suite('Assessment Actions', () => {
assert.equal(action.id, AsmtGenerateHTMLReportAction.ID, 'Generate HTML Report id action mismatch'); assert.equal(action.id, AsmtGenerateHTMLReportAction.ID, 'Generate HTML Report id action mismatch');
assert.equal(action.label, AsmtGenerateHTMLReportAction.LABEL, 'Generate HTML Report label action mismatch'); assert.equal(action.label, AsmtGenerateHTMLReportAction.LABEL, 'Generate HTML Report label action mismatch');
let result = await action.run({ ownerUri: '', component: mockAsmtViewComponent.object, connectionId: '' }); await action.run({ ownerUri: '', component: mockAsmtViewComponent.object, connectionId: '' });
assert.ok(result, 'Generate HTML Report action should succeed');
notificationService.verify(s => s.prompt(TypeMoq.It.isAny(), TypeMoq.It.isAny(), TypeMoq.It.isAny()), TypeMoq.Times.once()); notificationService.verify(s => s.prompt(TypeMoq.It.isAny(), TypeMoq.It.isAny(), TypeMoq.It.isAny()), TypeMoq.Times.once());
}); });
}); });

View File

@@ -45,11 +45,10 @@ export class CreateInsightAction extends Action {
super(CreateInsightAction.ID, CreateInsightAction.LABEL, CreateInsightAction.ICON); super(CreateInsightAction.ID, CreateInsightAction.LABEL, CreateInsightAction.ICON);
} }
public run(context: IChartActionContext): Promise<boolean> { public async run(context: IChartActionContext): Promise<void> {
let uriString = this.getActiveUriString(); let uriString = this.getActiveUriString();
if (!uriString) { if (!uriString) {
this.showError(localize('createInsightNoEditor', "Cannot create insight as the active editor is not a SQL Editor")); this.showError(localize('createInsightNoEditor', "Cannot create insight as the active editor is not a SQL Editor"));
return Promise.resolve(false);
} }
let uri: URI = URI.parse(uriString); let uri: URI = URI.parse(uriString);
@@ -78,18 +77,14 @@ export class CreateInsightAction extends Action {
}; };
let input = this.untitledEditorService.create({ mode: 'json', initialValue: JSON.stringify(widgetConfig) }); let input = this.untitledEditorService.create({ mode: 'json', initialValue: JSON.stringify(widgetConfig) });
try {
return this.editorService.openEditor(this.instantiationService.createInstance(UntitledTextEditorInput, input), { pinned: true }) await this.editorService.openEditor(this.instantiationService.createInstance(UntitledTextEditorInput, input), { pinned: true });
.then( } catch (error) {
() => true, this.notificationService.notify({
error => { severity: Severity.Error,
this.notificationService.notify({ message: error
severity: Severity.Error, });
message: error }
});
return false;
}
);
} }
private getActiveUriString(): string | undefined { private getActiveUriString(): string | undefined {
@@ -120,13 +115,12 @@ export class ConfigureChartAction extends Action {
super(ConfigureChartAction.ID, ConfigureChartAction.LABEL, ConfigureChartAction.ICON); super(ConfigureChartAction.ID, ConfigureChartAction.LABEL, ConfigureChartAction.ICON);
} }
public run(context: IChartActionContext): Promise<boolean> { public async run(context: IChartActionContext): Promise<void> {
if (!this.dialog) { if (!this.dialog) {
this.dialog = this.instantiationService.createInstance(ConfigureChartDialog, ConfigureChartAction.LABEL, ConfigureChartAction.ID, this._chart); this.dialog = this.instantiationService.createInstance(ConfigureChartDialog, ConfigureChartAction.LABEL, ConfigureChartAction.ID, this._chart);
this.dialog.render(); this.dialog.render();
} }
this.dialog.open(); this.dialog.open();
return Promise.resolve(true);
} }
} }
@@ -142,18 +136,16 @@ export class CopyAction extends Action {
super(CopyAction.ID, CopyAction.LABEL, CopyAction.ICON); super(CopyAction.ID, CopyAction.LABEL, CopyAction.ICON);
} }
public run(context: IChartActionContext): Promise<boolean> { public async run(context: IChartActionContext): Promise<void> {
if (context.insight instanceof Graph) { if (context.insight instanceof Graph) {
let data = context.insight.getCanvasData(); let data = context.insight.getCanvasData();
if (!data) { if (!data) {
this.showError(localize('chartNotFound', "Could not find chart to save")); this.showError(localize('chartNotFound', "Could not find chart to save"));
return Promise.resolve(false); return;
} }
this.clipboardService.writeImageDataUrl(data); this.clipboardService.writeImageDataUrl(data);
return Promise.resolve(true);
} }
return Promise.resolve(false);
} }
private showError(errorMsg: string) { private showError(errorMsg: string) {
@@ -178,7 +170,7 @@ export class SaveImageAction extends Action {
super(SaveImageAction.ID, SaveImageAction.LABEL, SaveImageAction.ICON); super(SaveImageAction.ID, SaveImageAction.LABEL, SaveImageAction.ICON);
} }
public async run(context: IChartActionContext): Promise<boolean> { public async run(context: IChartActionContext): Promise<void> {
if (context.insight instanceof Graph) { if (context.insight instanceof Graph) {
let fileFilters = new Array<FileFilter>({ extensions: ['png'], name: localize('resultsSerializer.saveAsFileExtensionPNGTitle', "PNG") }); let fileFilters = new Array<FileFilter>({ extensions: ['png'], name: localize('resultsSerializer.saveAsFileExtensionPNGTitle', "PNG") });
@@ -186,7 +178,7 @@ export class SaveImageAction extends Action {
const data = (<Graph>context.insight).getCanvasData(); const data = (<Graph>context.insight).getCanvasData();
if (!data) { if (!data) {
this.notificationService.error(localize('chartNotFound', "Could not find chart to save")); this.notificationService.error(localize('chartNotFound', "Could not find chart to save"));
return false; return;
} }
if (filePath) { if (filePath) {
let buffer = this.decodeBase64Image(data); let buffer = this.decodeBase64Image(data);
@@ -204,9 +196,7 @@ export class SaveImageAction extends Action {
} }
} }
} }
return true;
} }
return Promise.resolve(false);
} }
private decodeBase64Image(data: string): VSBuffer { private decodeBase64Image(data: string): VSBuffer {

View File

@@ -30,14 +30,9 @@ export class EditDashboardAction extends Action {
super(EditDashboardAction.ID, EditDashboardAction.EDITLABEL, EditDashboardAction.ICON); super(EditDashboardAction.ID, EditDashboardAction.EDITLABEL, EditDashboardAction.ICON);
} }
run(): Promise<boolean> { async run(): Promise<void> {
try { this.editFn.apply(this.context);
this.editFn.apply(this.context); this.toggleLabel();
this.toggleLabel();
return Promise.resolve(true);
} catch (e) {
return Promise.resolve(false);
}
} }
private toggleLabel(): void { private toggleLabel(): void {
@@ -64,13 +59,8 @@ export class RefreshWidgetAction extends Action {
super(RefreshWidgetAction.ID, RefreshWidgetAction.LABEL, RefreshWidgetAction.ICON); super(RefreshWidgetAction.ID, RefreshWidgetAction.LABEL, RefreshWidgetAction.ICON);
} }
run(): Promise<boolean> { async run(): Promise<void> {
try { this.refreshFn.apply(this.context);
this.refreshFn.apply(this.context);
return Promise.resolve(true);
} catch (e) {
return Promise.resolve(false);
}
} }
} }
@@ -86,13 +76,11 @@ export class ToolbarAction extends Action {
super(id, label, cssClass); super(id, label, cssClass);
} }
run(): Promise<boolean> { async run(): Promise<void> {
try { try {
this.runFn.apply(this.context, [this.id]); this.runFn.apply(this.context, [this.id]);
return Promise.resolve(true);
} catch (e) { } catch (e) {
this.logService.error(e); this.logService.error(e);
return Promise.resolve(false);
} }
} }
} }
@@ -111,13 +99,12 @@ export class ToggleMoreWidgetAction extends Action {
super(ToggleMoreWidgetAction.ID, ToggleMoreWidgetAction.LABEL, ToggleMoreWidgetAction.ICON); super(ToggleMoreWidgetAction.ID, ToggleMoreWidgetAction.LABEL, ToggleMoreWidgetAction.ICON);
} }
run(context: StandardKeyboardEvent): Promise<boolean> { async run(context: StandardKeyboardEvent): Promise<void> {
this._contextMenuService.showContextMenu({ this._contextMenuService.showContextMenu({
getAnchor: () => context.target, getAnchor: () => context.target,
getActions: () => this._actions, getActions: () => this._actions,
getActionsContext: () => this._context getActionsContext: () => this._context
}); });
return Promise.resolve(true);
} }
} }
@@ -134,9 +121,8 @@ export class DeleteWidgetAction extends Action {
super(DeleteWidgetAction.ID, DeleteWidgetAction.LABEL, DeleteWidgetAction.ICON); super(DeleteWidgetAction.ID, DeleteWidgetAction.LABEL, DeleteWidgetAction.ICON);
} }
run(): Promise<boolean> { async run(): Promise<void> {
this.angularEventService.sendAngularEvent(this._uri, AngularEventType.DELETE_WIDGET, { id: this._widgetId }); this.angularEventService.sendAngularEvent(this._uri, AngularEventType.DELETE_WIDGET, { id: this._widgetId });
return Promise.resolve(true);
} }
} }
@@ -167,11 +153,10 @@ export class PinUnpinTabAction extends Action {
} }
} }
public run(): Promise<boolean> { public async run(): Promise<void> {
this._isPinned = !this._isPinned; this._isPinned = !this._isPinned;
this.updatePinStatus(); this.updatePinStatus();
this.angularEventService.sendAngularEvent(this._uri, AngularEventType.PINUNPIN_TAB, { tabId: this._tabId, isPinned: this._isPinned }); this.angularEventService.sendAngularEvent(this._uri, AngularEventType.PINUNPIN_TAB, { tabId: this._tabId, isPinned: this._isPinned });
return Promise.resolve(true);
} }
} }
@@ -191,9 +176,8 @@ export class AddFeatureTabAction extends Action {
this._register(this._angularEventService.onAngularEvent(this._uri)(event => this.handleDashboardEvent(event))); this._register(this._angularEventService.onAngularEvent(this._uri)(event => this.handleDashboardEvent(event)));
} }
run(): Promise<boolean> { async run(): Promise<void> {
this._newDashboardTabService.showDialog(this._dashboardTabs, this._openedTabs, this._uri); this._newDashboardTabService.showDialog(this._dashboardTabs, this._openedTabs, this._uri);
return Promise.resolve(true);
} }
private handleDashboardEvent(event: IAngularEvent): void { private handleDashboardEvent(event: IAngularEvent): void {
@@ -236,10 +220,9 @@ export class CollapseWidgetAction extends Action {
this.expanded = !this.collpasedState; this.expanded = !this.collpasedState;
} }
run(): Promise<boolean> { async run(): Promise<void> {
this._toggleState(); this._toggleState();
this._angularEventService.sendAngularEvent(this._uri, AngularEventType.COLLAPSE_WIDGET, this._widgetUuid); this._angularEventService.sendAngularEvent(this._uri, AngularEventType.COLLAPSE_WIDGET, this._widgetUuid);
return Promise.resolve(true);
} }
private _toggleState(): void { private _toggleState(): void {

View File

@@ -72,20 +72,14 @@ export class OEManageConnectionAction extends Action {
super(id, label); super(id, label);
} }
run(actionContext: ObjectExplorerActionsContext): Promise<any> { async run(actionContext: ObjectExplorerActionsContext): Promise<void> {
this._treeSelectionHandler = this._instantiationService.createInstance(TreeSelectionHandler); this._treeSelectionHandler = this._instantiationService.createInstance(TreeSelectionHandler);
this._treeSelectionHandler.onTreeActionStateChange(true); this._treeSelectionHandler.onTreeActionStateChange(true);
let self = this; try {
let promise = new Promise<boolean>((resolve, reject) => { await this.doManage(actionContext);
self.doManage(actionContext).then((success) => { } finally {
self.done(); this.done();
resolve(success); }
}, error => {
self.done();
reject(error);
});
});
return promise;
} }
private async doManage(actionContext: ObjectExplorerActionsContext): Promise<boolean> { private async doManage(actionContext: ObjectExplorerActionsContext): Promise<boolean> {

View File

@@ -18,9 +18,8 @@ export class ExplorerManageAction extends ManageAction {
super(id, label, connectionManagementService, angularEventingService); super(id, label, connectionManagementService, angularEventingService);
} }
public run(actionContext: ManageActionContext): Promise<boolean> { public async run(actionContext: ManageActionContext): Promise<void> {
const promise = super.run(actionContext); await super.run(actionContext);
return promise;
} }
} }

View File

@@ -24,7 +24,7 @@ export class RunInsightQueryAction extends Action {
super(id, label); super(id, label);
} }
public run(context: InsightActionContext): Promise<boolean> { public async run(context: InsightActionContext): Promise<void> {
let queryString: string = undefined; let queryString: string = undefined;
let eol: string = this._textResourcePropertiesService.getEOL(undefined); let eol: string = this._textResourcePropertiesService.getEOL(undefined);
if (context.insight && context.insight.query) { if (context.insight && context.insight.query) {
@@ -34,9 +34,9 @@ export class RunInsightQueryAction extends Action {
queryString = context.insight.query.join(eol); queryString = context.insight.query.join(eol);
} }
} else { } else {
return Promise.resolve(false); return;
} }
return this.instantiationService.invokeFunction(openNewQuery, context.profile, queryString, await this.instantiationService.invokeFunction(openNewQuery, context.profile, queryString,
RunQueryOnConnectionMode.executeQuery).then(() => true, () => false); RunQueryOnConnectionMode.executeQuery);
} }
} }

View File

@@ -43,9 +43,8 @@ export class DeleteRowAction extends Action {
super(id, label); super(id, label);
} }
public run(gridInfo: IGridInfo): Promise<boolean> { public async run(gridInfo: IGridInfo): Promise<void> {
this.callback(gridInfo.rowIndex); this.callback(gridInfo.rowIndex);
return Promise.resolve(true);
} }
} }
@@ -61,8 +60,7 @@ export class RevertRowAction extends Action {
super(id, label); super(id, label);
} }
public run(gridInfo: IGridInfo): Promise<boolean> { public async run(gridInfo: IGridInfo): Promise<void> {
this.callback(); this.callback();
return Promise.resolve(true);
} }
} }

View File

@@ -74,14 +74,13 @@ class SaveResultAction extends Action {
super(id, label); super(id, label);
} }
public run(gridInfo: IGridInfo): Promise<boolean> { public async run(gridInfo: IGridInfo): Promise<void> {
this.dataService.sendSaveRequest({ this.dataService.sendSaveRequest({
batchIndex: gridInfo.batchIndex, batchIndex: gridInfo.batchIndex,
resultSetNumber: gridInfo.resultSetNumber, resultSetNumber: gridInfo.resultSetNumber,
selection: gridInfo.selection, selection: gridInfo.selection,
format: this.format format: this.format
}); });
return Promise.resolve(true);
} }
} }
@@ -101,9 +100,8 @@ class CopyResultAction extends Action {
super(id, label); super(id, label);
} }
public run(gridInfo: IGridInfo): Promise<boolean> { public async run(gridInfo: IGridInfo): Promise<void> {
this.dataService.copyResults(gridInfo.selection, gridInfo.batchIndex, gridInfo.resultSetNumber, this.copyHeader); this.dataService.copyResults(gridInfo.selection, gridInfo.batchIndex, gridInfo.resultSetNumber, this.copyHeader);
return Promise.resolve(true);
} }
} }
@@ -119,8 +117,7 @@ class SelectAllGridAction extends Action {
super(id, label); super(id, label);
} }
public run(gridInfo: IGridInfo): Promise<boolean> { public async run(gridInfo: IGridInfo): Promise<void> {
this.selectAllCallback(gridInfo.gridIndex); this.selectAllCallback(gridInfo.gridIndex);
return Promise.resolve(true);
} }
} }

View File

@@ -50,23 +50,20 @@ export class InstallRecommendedExtensionsByScenarioAction extends Action {
this.recommendations = recommendations; this.recommendations = recommendations;
} }
run(): Promise<any> { async run(): Promise<void> {
if (!this.recommendations.length) { return Promise.resolve(); } if (!this.recommendations.length) { return; }
return this.viewletService.openViewlet(VIEWLET_ID, true) const viewlet = await this.viewletService.openViewlet(VIEWLET_ID, true);
.then(viewlet => viewlet?.getViewPaneContainer() as IExtensionsViewPaneContainer) const viewPaneContainer = viewlet?.getViewPaneContainer() as IExtensionsViewPaneContainer;
.then(viewlet => { viewPaneContainer.search('@' + this.scenarioType);
viewlet.search('@' + this.scenarioType); viewlet.focus();
viewlet.focus(); const names = this.recommendations.map(({ extensionId }) => extensionId);
const names = this.recommendations.map(({ extensionId }) => extensionId); const pager = await this.extensionWorkbenchService.queryGallery({ names, source: 'install-' + this.scenarioType }, CancellationToken.None);
return this.extensionWorkbenchService.queryGallery({ names, source: 'install-' + this.scenarioType }, CancellationToken.None).then(pager => { let installPromises: Promise<any>[] = [];
let installPromises: Promise<any>[] = []; let model = new PagedModel(pager);
let model = new PagedModel(pager); for (let i = 0; i < pager.total; i++) {
for (let i = 0; i < pager.total; i++) { installPromises.push(model.resolve(i, CancellationToken.None).then(e => this.extensionWorkbenchService.install(e)));
installPromises.push(model.resolve(i, CancellationToken.None).then(e => this.extensionWorkbenchService.install(e))); }
} await Promise.all(installPromises);
return Promise.all(installPromises);
});
});
} }
} }
@@ -84,7 +81,7 @@ export class OpenExtensionAuthoringDocsAction extends Action {
super(id, label); super(id, label);
} }
run(): Promise<boolean> { async run(): Promise<void> {
return this.openerService.open(URI.parse(OpenExtensionAuthoringDocsAction.extensionAuthoringDocsURI)); await this.openerService.open(URI.parse(OpenExtensionAuthoringDocsAction.extensionAuthoringDocsURI));
} }
} }

View File

@@ -47,17 +47,8 @@ export class JobsRefreshAction extends Action {
super(JobsRefreshAction.ID, JobsRefreshAction.LABEL, 'refreshIcon'); super(JobsRefreshAction.ID, JobsRefreshAction.LABEL, 'refreshIcon');
} }
public run(context: IJobActionInfo): Promise<boolean> { public async run(context?: IJobActionInfo): Promise<void> {
return new Promise<boolean>((resolve, reject) => { context?.component?.refreshJobs();
if (context) {
if (context.component) {
context.component.refreshJobs();
}
resolve(true);
} else {
reject(false);
}
});
} }
} }
@@ -70,16 +61,9 @@ export class NewJobAction extends Action {
super(NewJobAction.ID, NewJobAction.LABEL, 'newStepIcon'); super(NewJobAction.ID, NewJobAction.LABEL, 'newStepIcon');
} }
public run(context: IJobActionInfo): Promise<boolean> { public async run(context: IJobActionInfo): Promise<void> {
let component = context.component as JobsViewComponent; const component = context.component as JobsViewComponent;
return new Promise<boolean>(async (resolve, reject) => { await component.openCreateJobDialog();
try {
await component.openCreateJobDialog();
resolve(true);
} catch (e) {
reject(e);
}
});
} }
} }
@@ -97,24 +81,19 @@ export class RunJobAction extends Action {
super(RunJobAction.ID, RunJobAction.LABEL, 'start'); super(RunJobAction.ID, RunJobAction.LABEL, 'start');
} }
public run(context: IJobActionInfo): Promise<boolean> { public async run(context: IJobActionInfo): Promise<void> {
let jobName = context.targetObject.job.name; let jobName = context.targetObject.job.name;
let ownerUri = context.ownerUri; let ownerUri = context.ownerUri;
let refreshAction = this.instantationService.createInstance(JobsRefreshAction); let refreshAction = this.instantationService.createInstance(JobsRefreshAction);
this.telemetryService.sendActionEvent(TelemetryView.Agent, TelemetryAction.RunAgentJob); this.telemetryService.sendActionEvent(TelemetryView.Agent, TelemetryAction.RunAgentJob);
return new Promise<boolean>((resolve, reject) => { const result = await this.jobManagementService.jobAction(ownerUri, jobName, JobActions.Run);
this.jobManagementService.jobAction(ownerUri, jobName, JobActions.Run).then(async (result) => { if (result.success) {
if (result.success) { let startMsg = nls.localize('jobSuccessfullyStarted', ": The job was successfully started.");
let startMsg = nls.localize('jobSuccessfullyStarted', ": The job was successfully started."); this.notificationService.info(jobName + startMsg);
this.notificationService.info(jobName + startMsg); await refreshAction.run(context);
await refreshAction.run(context); } else {
resolve(true); this.errorMessageService.showDialog(Severity.Error, errorLabel, result.errorMessage);
} else { }
this.errorMessageService.showDialog(Severity.Error, errorLabel, result.errorMessage);
resolve(false);
}
});
});
} }
} }
@@ -132,24 +111,19 @@ export class StopJobAction extends Action {
super(StopJobAction.ID, StopJobAction.LABEL, 'stop'); super(StopJobAction.ID, StopJobAction.LABEL, 'stop');
} }
public run(context: IJobActionInfo): Promise<boolean> { public async run(context: IJobActionInfo): Promise<void> {
let jobName = context.targetObject.name; let jobName = context.targetObject.name;
let ownerUri = context.ownerUri; let ownerUri = context.ownerUri;
let refreshAction = this.instantationService.createInstance(JobsRefreshAction); let refreshAction = this.instantationService.createInstance(JobsRefreshAction);
this.telemetryService.sendActionEvent(TelemetryView.Agent, TelemetryAction.StopAgentJob); this.telemetryService.sendActionEvent(TelemetryView.Agent, TelemetryAction.StopAgentJob);
return new Promise<boolean>((resolve, reject) => { const result = await this.jobManagementService.jobAction(ownerUri, jobName, JobActions.Stop);
this.jobManagementService.jobAction(ownerUri, jobName, JobActions.Stop).then(async (result) => { if (result.success) {
if (result.success) { await refreshAction.run(context);
await refreshAction.run(context); let stopMsg = nls.localize('jobSuccessfullyStopped', ": The job was successfully stopped.");
let stopMsg = nls.localize('jobSuccessfullyStopped', ": The job was successfully stopped."); this.notificationService.info(jobName + stopMsg);
this.notificationService.info(jobName + stopMsg); } else {
resolve(true); this.errorMessageService.showDialog(Severity.Error, 'Error', result.errorMessage);
} else { }
this.errorMessageService.showDialog(Severity.Error, 'Error', result.errorMessage);
resolve(false);
}
});
});
} }
} }
@@ -163,12 +137,11 @@ export class EditJobAction extends Action {
super(EditJobAction.ID, EditJobAction.LABEL, 'edit'); super(EditJobAction.ID, EditJobAction.LABEL, 'edit');
} }
public run(actionInfo: IJobActionInfo): Promise<boolean> { public async run(actionInfo: IJobActionInfo): Promise<void> {
this._commandService.executeCommand( await this._commandService.executeCommand(
'agent.openJobDialog', 'agent.openJobDialog',
actionInfo.ownerUri, actionInfo.ownerUri,
actionInfo.targetObject.job); actionInfo.targetObject.job);
return Promise.resolve(true);
} }
} }
@@ -180,9 +153,8 @@ export class OpenMaterializedNotebookAction extends Action {
super(OpenMaterializedNotebookAction.ID, OpenMaterializedNotebookAction.LABEL, 'openNotebook'); super(OpenMaterializedNotebookAction.ID, OpenMaterializedNotebookAction.LABEL, 'openNotebook');
} }
public run(context: any): Promise<boolean> { public async run(context: any): Promise<void> {
context.component.openNotebook(context.history); context.component.openNotebook(context.history);
return Promise.resolve(true);
} }
} }
@@ -199,24 +171,23 @@ export class DeleteJobAction extends Action {
super(DeleteJobAction.ID, DeleteJobAction.LABEL); super(DeleteJobAction.ID, DeleteJobAction.LABEL);
} }
public run(actionInfo: IJobActionInfo): Promise<boolean> { public async run(actionInfo: IJobActionInfo): Promise<void> {
let self = this;
let job = actionInfo.targetObject.job as azdata.AgentJobInfo; let job = actionInfo.targetObject.job as azdata.AgentJobInfo;
self._notificationService.prompt( this._notificationService.prompt(
Severity.Info, Severity.Info,
nls.localize('jobaction.deleteJobConfirm', "Are you sure you'd like to delete the job '{0}'?", job.name), nls.localize('jobaction.deleteJobConfirm', "Are you sure you'd like to delete the job '{0}'?", job.name),
[{ [{
label: DeleteJobAction.LABEL, label: DeleteJobAction.LABEL,
run: () => { run: () => {
this._telemetryService.sendActionEvent(TelemetryView.Agent, TelemetryAction.DeleteAgentJob); this._telemetryService.sendActionEvent(TelemetryView.Agent, TelemetryAction.DeleteAgentJob);
self._jobService.deleteJob(actionInfo.ownerUri, actionInfo.targetObject.job).then(result => { this._jobService.deleteJob(actionInfo.ownerUri, actionInfo.targetObject.job).then(result => {
if (!result || !result.success) { if (!result || !result.success) {
let errorMessage = nls.localize("jobaction.failedToDeleteJob", "Could not delete job '{0}'.\nError: {1}", let errorMessage = nls.localize("jobaction.failedToDeleteJob", "Could not delete job '{0}'.\nError: {1}",
job.name, result.errorMessage ? result.errorMessage : 'Unknown error'); job.name, result.errorMessage ? result.errorMessage : 'Unknown error');
self._errorMessageService.showDialog(Severity.Error, errorLabel, errorMessage); this._errorMessageService.showDialog(Severity.Error, errorLabel, errorMessage);
} else { } else {
let successMessage = nls.localize('jobaction.deletedJob', "The job was successfully deleted"); let successMessage = nls.localize('jobaction.deletedJob', "The job was successfully deleted");
self._notificationService.info(successMessage); this._notificationService.info(successMessage);
} }
}); });
} }
@@ -225,7 +196,6 @@ export class DeleteJobAction extends Action {
run: () => { } run: () => { }
}] }]
); );
return Promise.resolve(true);
} }
} }
@@ -241,13 +211,11 @@ export class NewStepAction extends Action {
super(NewStepAction.ID, NewStepAction.LABEL, 'newStepIcon'); super(NewStepAction.ID, NewStepAction.LABEL, 'newStepIcon');
} }
public run(context: JobHistoryComponent): Promise<boolean> { public async run(context: JobHistoryComponent): Promise<void> {
let ownerUri = context.ownerUri; let ownerUri = context.ownerUri;
let server = context.serverName; let server = context.serverName;
let jobInfo = context.agentJobInfo; let jobInfo = context.agentJobInfo;
return new Promise<boolean>((resolve, reject) => { await this._commandService.executeCommand('agent.openNewStepDialog', ownerUri, server, jobInfo, undefined);
resolve(this._commandService.executeCommand('agent.openNewStepDialog', ownerUri, server, jobInfo, null));
});
} }
} }
@@ -265,26 +233,25 @@ export class DeleteStepAction extends Action {
super(DeleteStepAction.ID, DeleteStepAction.LABEL); super(DeleteStepAction.ID, DeleteStepAction.LABEL);
} }
public run(actionInfo: IJobActionInfo): Promise<boolean> { public async run(actionInfo: IJobActionInfo): Promise<void> {
let self = this;
let step = actionInfo.targetObject as azdata.AgentJobStepInfo; let step = actionInfo.targetObject as azdata.AgentJobStepInfo;
let refreshAction = this.instantationService.createInstance(JobsRefreshAction); let refreshAction = this.instantationService.createInstance(JobsRefreshAction);
self._notificationService.prompt( this._notificationService.prompt(
Severity.Info, Severity.Info,
nls.localize('jobaction.deleteStepConfirm', "Are you sure you'd like to delete the step '{0}'?", step.stepName), nls.localize('jobaction.deleteStepConfirm', "Are you sure you'd like to delete the step '{0}'?", step.stepName),
[{ [{
label: DeleteStepAction.LABEL, label: DeleteStepAction.LABEL,
run: () => { run: () => {
this._telemetryService.sendActionEvent(TelemetryView.Agent, TelemetryAction.DeleteAgentJobStep); this._telemetryService.sendActionEvent(TelemetryView.Agent, TelemetryAction.DeleteAgentJobStep);
self._jobService.deleteJobStep(actionInfo.ownerUri, actionInfo.targetObject).then(async (result) => { this._jobService.deleteJobStep(actionInfo.ownerUri, actionInfo.targetObject).then(async (result) => {
if (!result || !result.success) { if (!result || !result.success) {
let errorMessage = nls.localize('jobaction.failedToDeleteStep', "Could not delete step '{0}'.\nError: {1}", let errorMessage = nls.localize('jobaction.failedToDeleteStep', "Could not delete step '{0}'.\nError: {1}",
step.stepName, result.errorMessage ? result.errorMessage : 'Unknown error'); step.stepName, result.errorMessage ? result.errorMessage : 'Unknown error');
self._errorMessageService.showDialog(Severity.Error, errorLabel, errorMessage); this._errorMessageService.showDialog(Severity.Error, errorLabel, errorMessage);
await refreshAction.run(actionInfo); await refreshAction.run(actionInfo);
} else { } else {
let successMessage = nls.localize('jobaction.deletedStep', "The job step was successfully deleted"); let successMessage = nls.localize('jobaction.deletedStep', "The job step was successfully deleted");
self._notificationService.info(successMessage); this._notificationService.info(successMessage);
} }
}); });
} }
@@ -293,7 +260,6 @@ export class DeleteStepAction extends Action {
run: () => { } run: () => { }
}] }]
); );
return Promise.resolve(true);
} }
} }
@@ -308,16 +274,9 @@ export class NewAlertAction extends Action {
super(NewAlertAction.ID, NewAlertAction.LABEL, 'newStepIcon'); super(NewAlertAction.ID, NewAlertAction.LABEL, 'newStepIcon');
} }
public run(context: IJobActionInfo): Promise<boolean> { public async run(context: IJobActionInfo): Promise<void> {
let component = context.component as AlertsViewComponent; let component = context.component as AlertsViewComponent;
return new Promise<boolean>((resolve, reject) => { await component.openCreateAlertDialog();
try {
component.openCreateAlertDialog();
resolve(true);
} catch (e) {
reject(e);
}
});
} }
} }
@@ -331,13 +290,12 @@ export class EditAlertAction extends Action {
super(EditAlertAction.ID, EditAlertAction.LABEL); super(EditAlertAction.ID, EditAlertAction.LABEL);
} }
public run(actionInfo: IJobActionInfo): Promise<boolean> { public async run(actionInfo: IJobActionInfo): Promise<void> {
this._commandService.executeCommand( await this._commandService.executeCommand(
'agent.openAlertDialog', 'agent.openAlertDialog',
actionInfo.ownerUri, actionInfo.ownerUri,
actionInfo.targetObject.jobInfo, actionInfo.targetObject.jobInfo,
actionInfo.targetObject.alertInfo); actionInfo.targetObject.alertInfo);
return Promise.resolve(true);
} }
} }
@@ -355,33 +313,30 @@ export class DeleteAlertAction extends Action {
super(DeleteAlertAction.ID, DeleteAlertAction.LABEL); super(DeleteAlertAction.ID, DeleteAlertAction.LABEL);
} }
public run(actionInfo: IJobActionInfo): Promise<boolean> { public async run(actionInfo: IJobActionInfo): Promise<void> {
let self = this;
let alert = actionInfo.targetObject.alertInfo as azdata.AgentAlertInfo; let alert = actionInfo.targetObject.alertInfo as azdata.AgentAlertInfo;
self._notificationService.prompt( this._notificationService.prompt(
Severity.Info, Severity.Info,
nls.localize('jobaction.deleteAlertConfirm', "Are you sure you'd like to delete the alert '{0}'?", alert.name), nls.localize('jobaction.deleteAlertConfirm', "Are you sure you'd like to delete the alert '{0}'?", alert.name),
[{ [{
label: DeleteAlertAction.LABEL, label: DeleteAlertAction.LABEL,
run: () => { run: async () => {
self._telemetryService.sendActionEvent(TelemetryView.Agent, TelemetryAction.DeleteAgentAlert); this._telemetryService.sendActionEvent(TelemetryView.Agent, TelemetryAction.DeleteAgentAlert);
self._jobService.deleteAlert(actionInfo.ownerUri, alert).then(result => { const result = await this._jobService.deleteAlert(actionInfo.ownerUri, alert);
if (!result || !result.success) { if (!result || !result.success) {
let errorMessage = nls.localize("jobaction.failedToDeleteAlert", "Could not delete alert '{0}'.\nError: {1}", let errorMessage = nls.localize("jobaction.failedToDeleteAlert", "Could not delete alert '{0}'.\nError: {1}",
alert.name, result.errorMessage ? result.errorMessage : 'Unknown error'); alert.name, result.errorMessage ? result.errorMessage : 'Unknown error');
self._errorMessageService.showDialog(Severity.Error, errorLabel, errorMessage); this._errorMessageService.showDialog(Severity.Error, errorLabel, errorMessage);
} else { } else {
let successMessage = nls.localize('jobaction.deletedAlert', "The alert was successfully deleted"); let successMessage = nls.localize('jobaction.deletedAlert', "The alert was successfully deleted");
self._notificationService.info(successMessage); this._notificationService.info(successMessage);
} }
});
} }
}, { }, {
label: DeleteAlertAction.CancelLabel, label: DeleteAlertAction.CancelLabel,
run: () => { } run: () => { }
}] }]
); );
return Promise.resolve(true);
} }
} }
@@ -396,16 +351,9 @@ export class NewOperatorAction extends Action {
super(NewOperatorAction.ID, NewOperatorAction.LABEL, 'newStepIcon'); super(NewOperatorAction.ID, NewOperatorAction.LABEL, 'newStepIcon');
} }
public run(context: IJobActionInfo): Promise<boolean> { public async run(context: IJobActionInfo): Promise<void> {
let component = context.component as OperatorsViewComponent; let component = context.component as OperatorsViewComponent;
return new Promise<boolean>((resolve, reject) => { await component.openCreateOperatorDialog();
try {
component.openCreateOperatorDialog();
resolve(true);
} catch (e) {
reject(e);
}
});
} }
} }
@@ -419,12 +367,11 @@ export class EditOperatorAction extends Action {
super(EditOperatorAction.ID, EditOperatorAction.LABEL); super(EditOperatorAction.ID, EditOperatorAction.LABEL);
} }
public run(actionInfo: IJobActionInfo): Promise<boolean> { public async run(actionInfo: IJobActionInfo): Promise<void> {
this._commandService.executeCommand( await this._commandService.executeCommand(
'agent.openOperatorDialog', 'agent.openOperatorDialog',
actionInfo.ownerUri, actionInfo.ownerUri,
actionInfo.targetObject); actionInfo.targetObject);
return Promise.resolve(true);
} }
} }
@@ -441,33 +388,30 @@ export class DeleteOperatorAction extends Action {
super(DeleteOperatorAction.ID, DeleteOperatorAction.LABEL); super(DeleteOperatorAction.ID, DeleteOperatorAction.LABEL);
} }
public run(actionInfo: IJobActionInfo): Promise<boolean> { public async run(actionInfo: IJobActionInfo): Promise<void> {
const self = this;
let operator = actionInfo.targetObject as azdata.AgentOperatorInfo; let operator = actionInfo.targetObject as azdata.AgentOperatorInfo;
self._notificationService.prompt( this._notificationService.prompt(
Severity.Info, Severity.Info,
nls.localize('jobaction.deleteOperatorConfirm', "Are you sure you'd like to delete the operator '{0}'?", operator.name), nls.localize('jobaction.deleteOperatorConfirm', "Are you sure you'd like to delete the operator '{0}'?", operator.name),
[{ [{
label: DeleteOperatorAction.LABEL, label: DeleteOperatorAction.LABEL,
run: () => { run: async () => {
self._telemetryService.sendActionEvent(TelemetryView.Agent, TelemetryAction.DeleteAgentOperator); this._telemetryService.sendActionEvent(TelemetryView.Agent, TelemetryAction.DeleteAgentOperator);
self._jobService.deleteOperator(actionInfo.ownerUri, actionInfo.targetObject).then(result => { const result = await this._jobService.deleteOperator(actionInfo.ownerUri, actionInfo.targetObject);
if (!result || !result.success) { if (!result || !result.success) {
let errorMessage = nls.localize("jobaction.failedToDeleteOperator", "Could not delete operator '{0}'.\nError: {1}", let errorMessage = nls.localize("jobaction.failedToDeleteOperator", "Could not delete operator '{0}'.\nError: {1}",
operator.name, result.errorMessage ? result.errorMessage : 'Unknown error'); operator.name, result.errorMessage ? result.errorMessage : 'Unknown error');
self._errorMessageService.showDialog(Severity.Error, errorLabel, errorMessage); this._errorMessageService.showDialog(Severity.Error, errorLabel, errorMessage);
} else { } else {
let successMessage = nls.localize('joaction.deletedOperator', "The operator was deleted successfully"); let successMessage = nls.localize('joaction.deletedOperator', "The operator was deleted successfully");
self._notificationService.info(successMessage); this._notificationService.info(successMessage);
} }
});
} }
}, { }, {
label: DeleteAlertAction.CancelLabel, label: DeleteAlertAction.CancelLabel,
run: () => { } run: () => { }
}] }]
); );
return Promise.resolve(true);
} }
} }
@@ -483,16 +427,9 @@ export class NewProxyAction extends Action {
super(NewProxyAction.ID, NewProxyAction.LABEL, 'newStepIcon'); super(NewProxyAction.ID, NewProxyAction.LABEL, 'newStepIcon');
} }
public run(context: IJobActionInfo): Promise<boolean> { public async run(context: IJobActionInfo): Promise<void> {
let component = context.component as ProxiesViewComponent; const component = context.component as ProxiesViewComponent;
return new Promise<boolean>((resolve, reject) => { component.openCreateProxyDialog();
try {
component.openCreateProxyDialog();
resolve(true);
} catch (e) {
reject(e);
}
});
} }
} }
@@ -507,19 +444,15 @@ export class EditProxyAction extends Action {
super(EditProxyAction.ID, EditProxyAction.LABEL); super(EditProxyAction.ID, EditProxyAction.LABEL);
} }
public run(actionInfo: IJobActionInfo): Promise<boolean> { public async run(actionInfo: IJobActionInfo): Promise<void> {
return Promise.resolve(this._jobManagementService.getCredentials(actionInfo.ownerUri).then((result) => { const result = await this._jobManagementService.getCredentials(actionInfo.ownerUri);
if (result && result.credentials) { if (result && result.credentials) {
this._commandService.executeCommand( await this._commandService.executeCommand(
'agent.openProxyDialog', 'agent.openProxyDialog',
actionInfo.ownerUri, actionInfo.ownerUri,
actionInfo.targetObject, actionInfo.targetObject,
result.credentials); result.credentials);
return true; }
} else {
return false;
}
}));
} }
} }
@@ -536,33 +469,30 @@ export class DeleteProxyAction extends Action {
super(DeleteProxyAction.ID, DeleteProxyAction.LABEL); super(DeleteProxyAction.ID, DeleteProxyAction.LABEL);
} }
public run(actionInfo: IJobActionInfo): Promise<boolean> { public async run(actionInfo: IJobActionInfo): Promise<void> {
let self = this;
let proxy = actionInfo.targetObject as azdata.AgentProxyInfo; let proxy = actionInfo.targetObject as azdata.AgentProxyInfo;
self._notificationService.prompt( this._notificationService.prompt(
Severity.Info, Severity.Info,
nls.localize('jobaction.deleteProxyConfirm', "Are you sure you'd like to delete the proxy '{0}'?", proxy.accountName), nls.localize('jobaction.deleteProxyConfirm', "Are you sure you'd like to delete the proxy '{0}'?", proxy.accountName),
[{ [{
label: DeleteProxyAction.LABEL, label: DeleteProxyAction.LABEL,
run: () => { run: async () => {
self._telemetryService.sendActionEvent(TelemetryView.Agent, TelemetryAction.DeleteAgentProxy); this._telemetryService.sendActionEvent(TelemetryView.Agent, TelemetryAction.DeleteAgentProxy);
self._jobService.deleteProxy(actionInfo.ownerUri, actionInfo.targetObject).then(result => { const result = await this._jobService.deleteProxy(actionInfo.ownerUri, actionInfo.targetObject);
if (!result || !result.success) { if (!result || !result.success) {
let errorMessage = nls.localize("jobaction.failedToDeleteProxy", "Could not delete proxy '{0}'.\nError: {1}", let errorMessage = nls.localize("jobaction.failedToDeleteProxy", "Could not delete proxy '{0}'.\nError: {1}",
proxy.accountName, result.errorMessage ? result.errorMessage : 'Unknown error'); proxy.accountName, result.errorMessage ? result.errorMessage : 'Unknown error');
self._errorMessageService.showDialog(Severity.Error, errorLabel, errorMessage); this._errorMessageService.showDialog(Severity.Error, errorLabel, errorMessage);
} else { } else {
let successMessage = nls.localize('jobaction.deletedProxy', "The proxy was deleted successfully"); let successMessage = nls.localize('jobaction.deletedProxy', "The proxy was deleted successfully");
self._notificationService.info(successMessage); this._notificationService.info(successMessage);
} }
});
} }
}, { }, {
label: DeleteAlertAction.CancelLabel, label: DeleteAlertAction.CancelLabel,
run: () => { } run: () => { }
}] }]
); );
return Promise.resolve(true);
} }
} }
@@ -577,10 +507,9 @@ export class NewNotebookJobAction extends Action {
super(NewNotebookJobAction.ID, NewNotebookJobAction.LABEL, 'newStepIcon'); super(NewNotebookJobAction.ID, NewNotebookJobAction.LABEL, 'newStepIcon');
} }
public async run(context: IJobActionInfo): Promise<boolean> { public async run(context: IJobActionInfo): Promise<void> {
let component = context.component as NotebooksViewComponent; let component = context.component as NotebooksViewComponent;
await component.openCreateNotebookDialog(); await component.openCreateNotebookDialog();
return true;
} }
} }
@@ -594,12 +523,11 @@ export class EditNotebookJobAction extends Action {
super(EditNotebookJobAction.ID, EditNotebookJobAction.LABEL, 'edit'); super(EditNotebookJobAction.ID, EditNotebookJobAction.LABEL, 'edit');
} }
public run(actionInfo: IJobActionInfo): Promise<boolean> { public async run(actionInfo: IJobActionInfo): Promise<void> {
this._commandService.executeCommand( await this._commandService.executeCommand(
'agent.openNotebookDialog', 'agent.openNotebookDialog',
actionInfo.ownerUri, actionInfo.ownerUri,
actionInfo.targetObject.job); actionInfo.targetObject.job);
return Promise.resolve(true);
} }
} }
@@ -611,9 +539,8 @@ export class OpenTemplateNotebookAction extends Action {
super(OpenTemplateNotebookAction.ID, OpenTemplateNotebookAction.LABEL, 'opennotebook'); super(OpenTemplateNotebookAction.ID, OpenTemplateNotebookAction.LABEL, 'opennotebook');
} }
public run(actionInfo: any): Promise<boolean> { public async run(actionInfo: any): Promise<void> {
actionInfo.component.openTemplateNotebook(); actionInfo.component.openTemplateNotebook();
return Promise.resolve(true);
} }
} }
@@ -631,35 +558,32 @@ export class DeleteNotebookAction extends Action {
super(DeleteNotebookAction.ID, DeleteNotebookAction.LABEL); super(DeleteNotebookAction.ID, DeleteNotebookAction.LABEL);
} }
public run(actionInfo: IJobActionInfo): Promise<boolean> { public async run(actionInfo: IJobActionInfo): Promise<void> {
let self = this;
let notebook = actionInfo.targetObject.job as azdata.AgentNotebookInfo; let notebook = actionInfo.targetObject.job as azdata.AgentNotebookInfo;
let refreshAction = this.instantationService.createInstance(JobsRefreshAction); let refreshAction = this.instantationService.createInstance(JobsRefreshAction);
self._notificationService.prompt( this._notificationService.prompt(
Severity.Info, Severity.Info,
nls.localize('jobaction.deleteNotebookConfirm', "Are you sure you'd like to delete the notebook '{0}'?", notebook.name), nls.localize('jobaction.deleteNotebookConfirm', "Are you sure you'd like to delete the notebook '{0}'?", notebook.name),
[{ [{
label: DeleteNotebookAction.LABEL, label: DeleteNotebookAction.LABEL,
run: () => { run: async () => {
self._telemetryService.sendActionEvent(TelemetryView.Agent, TelemetryAction.DeleteAgentJob); this._telemetryService.sendActionEvent(TelemetryView.Agent, TelemetryAction.DeleteAgentJob);
self._jobService.deleteNotebook(actionInfo.ownerUri, actionInfo.targetObject.job).then(async (result) => { const result = await this._jobService.deleteNotebook(actionInfo.ownerUri, actionInfo.targetObject.job);
if (!result || !result.success) { if (!result || !result.success) {
await refreshAction.run(actionInfo); await refreshAction.run(actionInfo);
let errorMessage = nls.localize("jobaction.failedToDeleteNotebook", "Could not delete notebook '{0}'.\nError: {1}", let errorMessage = nls.localize("jobaction.failedToDeleteNotebook", "Could not delete notebook '{0}'.\nError: {1}",
notebook.name, result.errorMessage ? result.errorMessage : 'Unknown error'); notebook.name, result.errorMessage ? result.errorMessage : 'Unknown error');
self._errorMessageService.showDialog(Severity.Error, errorLabel, errorMessage); this._errorMessageService.showDialog(Severity.Error, errorLabel, errorMessage);
} else { } else {
let successMessage = nls.localize('jobaction.deletedNotebook', "The notebook was successfully deleted"); let successMessage = nls.localize('jobaction.deletedNotebook', "The notebook was successfully deleted");
self._notificationService.info(successMessage); this._notificationService.info(successMessage);
} }
});
} }
}, { }, {
label: DeleteAlertAction.CancelLabel, label: DeleteAlertAction.CancelLabel,
run: () => { } run: () => { }
}] }]
); );
return Promise.resolve(true);
} }
} }
@@ -672,9 +596,8 @@ export class PinNotebookMaterializedAction extends Action {
super(PinNotebookMaterializedAction.ID, PinNotebookMaterializedAction.LABEL); super(PinNotebookMaterializedAction.ID, PinNotebookMaterializedAction.LABEL);
} }
public run(actionInfo: any): Promise<boolean> { public async run(actionInfo: any): Promise<void> {
actionInfo.component.toggleNotebookPin(actionInfo.history, true); actionInfo.component.toggleNotebookPin(actionInfo.history, true);
return Promise.resolve(true);
} }
} }
@@ -686,9 +609,8 @@ export class DeleteMaterializedNotebookAction extends Action {
super(DeleteMaterializedNotebookAction.ID, DeleteMaterializedNotebookAction.LABEL); super(DeleteMaterializedNotebookAction.ID, DeleteMaterializedNotebookAction.LABEL);
} }
public run(actionInfo: any): Promise<boolean> { public async run(actionInfo: any): Promise<void> {
actionInfo.component.deleteMaterializedNotebook(actionInfo.history); actionInfo.component.deleteMaterializedNotebook(actionInfo.history);
return Promise.resolve(true);
} }
} }
@@ -700,9 +622,8 @@ export class UnpinNotebookMaterializedAction extends Action {
super(UnpinNotebookMaterializedAction.ID, UnpinNotebookMaterializedAction.LABEL); super(UnpinNotebookMaterializedAction.ID, UnpinNotebookMaterializedAction.LABEL);
} }
public run(actionInfo: any): Promise<boolean> { public async run(actionInfo: any): Promise<void> {
actionInfo.component.toggleNotebookPin(actionInfo.history, false); actionInfo.component.toggleNotebookPin(actionInfo.history, false);
return Promise.resolve(true);
} }
} }
@@ -714,9 +635,8 @@ export class RenameNotebookMaterializedAction extends Action {
super(RenameNotebookMaterializedAction.ID, RenameNotebookMaterializedAction.LABEL); super(RenameNotebookMaterializedAction.ID, RenameNotebookMaterializedAction.LABEL);
} }
public run(actionInfo: any): Promise<boolean> { public async run(actionInfo: any): Promise<void> {
actionInfo.component.renameNotebook(actionInfo.history); actionInfo.component.renameNotebook(actionInfo.history);
return Promise.resolve(true);
} }
} }
@@ -728,8 +648,7 @@ export class OpenLatestRunMaterializedNotebook extends Action {
super(OpenLatestRunMaterializedNotebook.ID, OpenLatestRunMaterializedNotebook.LABEL); super(OpenLatestRunMaterializedNotebook.ID, OpenLatestRunMaterializedNotebook.LABEL);
} }
public run(actionInfo: IJobActionInfo): Promise<boolean> { public async run(actionInfo: IJobActionInfo): Promise<void> {
actionInfo.component.openLastNRun(actionInfo.targetObject.job, 0, 1); actionInfo.component.openLastNRun(actionInfo.targetObject.job, 0, 1);
return Promise.resolve(true);
} }
} }

View File

@@ -108,11 +108,7 @@ suite('Job Management Actions', () => {
test('Edit Job Action', async () => { test('Edit Job Action', async () => {
mockEditJobAction = TypeMoq.Mock.ofType(EditJobAction, TypeMoq.MockBehavior.Strict, EditJobAction.ID, EditJobAction.LABEL); mockEditJobAction = TypeMoq.Mock.ofType(EditJobAction, TypeMoq.MockBehavior.Strict, EditJobAction.ID, EditJobAction.LABEL);
let commandServiceCalled: boolean = false; mockEditJobAction.setup(s => s.run(TypeMoq.It.isAny()));
mockEditJobAction.setup(s => s.run(TypeMoq.It.isAny())).returns(() => {
commandServiceCalled = true;
return Promise.resolve(commandServiceCalled);
});
mockEditJobAction.setup(s => s.id).returns(() => EditJobAction.ID); mockEditJobAction.setup(s => s.id).returns(() => EditJobAction.ID);
mockEditJobAction.setup(s => s.label).returns(() => EditJobAction.LABEL); mockEditJobAction.setup(s => s.label).returns(() => EditJobAction.LABEL);
assert.equal(mockEditJobAction.object.id, EditJobAction.ID); assert.equal(mockEditJobAction.object.id, EditJobAction.ID);
@@ -120,14 +116,13 @@ suite('Job Management Actions', () => {
// Edit Job Action from Jobs View should open a dialog // Edit Job Action from Jobs View should open a dialog
await mockEditJobAction.object.run(null); await mockEditJobAction.object.run(null);
assert(commandServiceCalled); mockEditJobAction.verify(s => s.run(TypeMoq.It.isAny()), TypeMoq.Times.once());
}); });
test('Run Job Action', async () => { test('Run Job Action', async () => {
mockRunJobAction = TypeMoq.Mock.ofType(RunJobAction, TypeMoq.MockBehavior.Strict, RunJobAction.ID, RunJobAction.LABEL, null, null, mockJobManagementService); mockRunJobAction = TypeMoq.Mock.ofType(RunJobAction, TypeMoq.MockBehavior.Strict, RunJobAction.ID, RunJobAction.LABEL, null, null, mockJobManagementService);
mockRunJobAction.setup(s => s.run(TypeMoq.It.isAny())).returns(async () => { mockRunJobAction.setup(s => s.run(TypeMoq.It.isAny())).returns(async () => {
let result = await mockJobManagementService.object.jobAction(null, null, null).then((result) => result.success); await mockJobManagementService.object.jobAction(null, null, null);
return result;
}); });
mockRunJobAction.setup(s => s.id).returns(() => RunJobAction.ID); mockRunJobAction.setup(s => s.id).returns(() => RunJobAction.ID);
@@ -143,8 +138,7 @@ suite('Job Management Actions', () => {
test('Stop Job Action', async () => { test('Stop Job Action', async () => {
mockStopJobAction = TypeMoq.Mock.ofType(StopJobAction, TypeMoq.MockBehavior.Strict, StopJobAction.ID, StopJobAction.LABEL, null, null, mockJobManagementService); mockStopJobAction = TypeMoq.Mock.ofType(StopJobAction, TypeMoq.MockBehavior.Strict, StopJobAction.ID, StopJobAction.LABEL, null, null, mockJobManagementService);
mockStopJobAction.setup(s => s.run(TypeMoq.It.isAny())).returns(async () => { mockStopJobAction.setup(s => s.run(TypeMoq.It.isAny())).returns(async () => {
let result = await mockJobManagementService.object.jobAction(null, null, null).then((result) => result.success); await mockJobManagementService.object.jobAction(null, null, null);
return result;
}); });
mockStopJobAction.setup(s => s.id).returns(() => RunJobAction.ID); mockStopJobAction.setup(s => s.id).returns(() => RunJobAction.ID);
@@ -160,8 +154,7 @@ suite('Job Management Actions', () => {
test('Delete Job Action', async () => { test('Delete Job Action', async () => {
mockDeleteJobAction = TypeMoq.Mock.ofType(DeleteJobAction, TypeMoq.MockBehavior.Strict, DeleteJobAction.ID, DeleteJobAction.LABEL, null, null, mockJobManagementService); mockDeleteJobAction = TypeMoq.Mock.ofType(DeleteJobAction, TypeMoq.MockBehavior.Strict, DeleteJobAction.ID, DeleteJobAction.LABEL, null, null, mockJobManagementService);
mockDeleteJobAction.setup(s => s.run(TypeMoq.It.isAny())).returns(async () => { mockDeleteJobAction.setup(s => s.run(TypeMoq.It.isAny())).returns(async () => {
let result = await mockJobManagementService.object.jobAction(null, null, null).then((result) => result.success); await mockJobManagementService.object.jobAction(null, null, null);
return result;
}); });
mockDeleteJobAction.setup(s => s.id).returns(() => DeleteJobAction.ID); mockDeleteJobAction.setup(s => s.id).returns(() => DeleteJobAction.ID);
@@ -177,11 +170,7 @@ suite('Job Management Actions', () => {
// Step Actions // Step Actions
test('New Step Action', async () => { test('New Step Action', async () => {
mockNewStepAction = TypeMoq.Mock.ofType(NewStepAction, TypeMoq.MockBehavior.Strict, NewJobAction.ID, NewJobAction.LABEL); mockNewStepAction = TypeMoq.Mock.ofType(NewStepAction, TypeMoq.MockBehavior.Strict, NewJobAction.ID, NewJobAction.LABEL);
let commandServiceCalled = false; mockNewStepAction.setup(s => s.run(TypeMoq.It.isAny()));
mockNewStepAction.setup(s => s.run(TypeMoq.It.isAny())).returns(() => {
commandServiceCalled = true;
return Promise.resolve(commandServiceCalled);
});
mockNewStepAction.setup(s => s.id).returns(() => NewJobAction.ID); mockNewStepAction.setup(s => s.id).returns(() => NewJobAction.ID);
mockNewStepAction.setup(s => s.label).returns(() => NewJobAction.LABEL); mockNewStepAction.setup(s => s.label).returns(() => NewJobAction.LABEL);
assert.equal(mockNewStepAction.object.id, NewJobAction.ID); assert.equal(mockNewStepAction.object.id, NewJobAction.ID);
@@ -189,16 +178,13 @@ suite('Job Management Actions', () => {
// New Step Action should called command service // New Step Action should called command service
await mockNewStepAction.object.run(null); await mockNewStepAction.object.run(null);
assert(commandServiceCalled); mockNewStepAction.verify(s => s.run(TypeMoq.It.isAny()), TypeMoq.Times.once());
}); });
test('Delete Step Action', async () => { test('Delete Step Action', async () => {
mockDeleteStepAction = TypeMoq.Mock.ofType(DeleteStepAction, TypeMoq.MockBehavior.Strict, DeleteStepAction.ID, DeleteStepAction.LABEL); mockDeleteStepAction = TypeMoq.Mock.ofType(DeleteStepAction, TypeMoq.MockBehavior.Strict, DeleteStepAction.ID, DeleteStepAction.LABEL);
let commandServiceCalled = false;
mockDeleteStepAction.setup(s => s.run(TypeMoq.It.isAny())).returns(async () => { mockDeleteStepAction.setup(s => s.run(TypeMoq.It.isAny())).returns(async () => {
commandServiceCalled = true; await mockJobManagementService.object.deleteJobStep(null, null);
await mockJobManagementService.object.deleteJobStep(null, null).then((result) => result.success);
return commandServiceCalled;
}); });
mockDeleteStepAction.setup(s => s.id).returns(() => DeleteStepAction.ID); mockDeleteStepAction.setup(s => s.id).returns(() => DeleteStepAction.ID);
mockDeleteStepAction.setup(s => s.label).returns(() => DeleteStepAction.LABEL); mockDeleteStepAction.setup(s => s.label).returns(() => DeleteStepAction.LABEL);
@@ -207,7 +193,6 @@ suite('Job Management Actions', () => {
// Delete Step Action should called command service // Delete Step Action should called command service
await mockDeleteStepAction.object.run(null); await mockDeleteStepAction.object.run(null);
assert(commandServiceCalled);
mockJobManagementService.verify(s => s.deleteJobStep(null, null), TypeMoq.Times.once()); mockJobManagementService.verify(s => s.deleteJobStep(null, null), TypeMoq.Times.once());
}); });
@@ -227,11 +212,7 @@ suite('Job Management Actions', () => {
test('Edit Alert Action', async () => { test('Edit Alert Action', async () => {
mockEditAlertAction = TypeMoq.Mock.ofType(EditAlertAction, TypeMoq.MockBehavior.Strict, EditAlertAction.ID, EditAlertAction.LABEL); mockEditAlertAction = TypeMoq.Mock.ofType(EditAlertAction, TypeMoq.MockBehavior.Strict, EditAlertAction.ID, EditAlertAction.LABEL);
let commandServiceCalled: boolean = false; mockEditAlertAction.setup(s => s.run(TypeMoq.It.isAny()));
mockEditAlertAction.setup(s => s.run(TypeMoq.It.isAny())).returns(() => {
commandServiceCalled = true;
return Promise.resolve(commandServiceCalled);
});
mockEditAlertAction.setup(s => s.id).returns(() => EditAlertAction.ID); mockEditAlertAction.setup(s => s.id).returns(() => EditAlertAction.ID);
mockEditAlertAction.setup(s => s.label).returns(() => EditAlertAction.LABEL); mockEditAlertAction.setup(s => s.label).returns(() => EditAlertAction.LABEL);
assert.equal(mockEditAlertAction.object.id, EditAlertAction.ID); assert.equal(mockEditAlertAction.object.id, EditAlertAction.ID);
@@ -239,16 +220,13 @@ suite('Job Management Actions', () => {
// Edit Alert Action from Jobs View should open a dialog // Edit Alert Action from Jobs View should open a dialog
await mockEditAlertAction.object.run(null); await mockEditAlertAction.object.run(null);
assert(commandServiceCalled); mockEditAlertAction.verify(s => s.run(TypeMoq.It.isAny()), TypeMoq.Times.once());
}); });
test('Delete Alert Action', async () => { test('Delete Alert Action', async () => {
mockDeleteAlertAction = TypeMoq.Mock.ofType(DeleteAlertAction, TypeMoq.MockBehavior.Strict, DeleteAlertAction.ID, DeleteAlertAction.LABEL, null, null, mockJobManagementService); mockDeleteAlertAction = TypeMoq.Mock.ofType(DeleteAlertAction, TypeMoq.MockBehavior.Strict, DeleteAlertAction.ID, DeleteAlertAction.LABEL, null, null, mockJobManagementService);
let commandServiceCalled = false;
mockDeleteAlertAction.setup(s => s.run(TypeMoq.It.isAny())).returns(async () => { mockDeleteAlertAction.setup(s => s.run(TypeMoq.It.isAny())).returns(async () => {
commandServiceCalled = true; await mockJobManagementService.object.deleteAlert(null, null);
await mockJobManagementService.object.deleteAlert(null, null).then((result) => result.success);
return commandServiceCalled;
}); });
mockDeleteAlertAction.setup(s => s.id).returns(() => DeleteAlertAction.ID); mockDeleteAlertAction.setup(s => s.id).returns(() => DeleteAlertAction.ID);
mockDeleteAlertAction.setup(s => s.label).returns(() => DeleteAlertAction.LABEL); mockDeleteAlertAction.setup(s => s.label).returns(() => DeleteAlertAction.LABEL);
@@ -257,7 +235,6 @@ suite('Job Management Actions', () => {
// Delete Alert Action should call job management service // Delete Alert Action should call job management service
await mockDeleteAlertAction.object.run(null); await mockDeleteAlertAction.object.run(null);
assert(commandServiceCalled);
mockJobManagementService.verify(s => s.deleteAlert(null, null), TypeMoq.Times.once()); mockJobManagementService.verify(s => s.deleteAlert(null, null), TypeMoq.Times.once());
}); });
@@ -277,11 +254,7 @@ suite('Job Management Actions', () => {
test('Edit Operator Action', async () => { test('Edit Operator Action', async () => {
mockEditOperatorAction = TypeMoq.Mock.ofType(EditOperatorAction, TypeMoq.MockBehavior.Strict, EditOperatorAction.ID, EditOperatorAction.LABEL); mockEditOperatorAction = TypeMoq.Mock.ofType(EditOperatorAction, TypeMoq.MockBehavior.Strict, EditOperatorAction.ID, EditOperatorAction.LABEL);
let commandServiceCalled: boolean = false; mockEditOperatorAction.setup(s => s.run(TypeMoq.It.isAny()));
mockEditOperatorAction.setup(s => s.run(TypeMoq.It.isAny())).returns(() => {
commandServiceCalled = true;
return Promise.resolve(commandServiceCalled);
});
mockEditOperatorAction.setup(s => s.id).returns(() => EditOperatorAction.ID); mockEditOperatorAction.setup(s => s.id).returns(() => EditOperatorAction.ID);
mockEditOperatorAction.setup(s => s.label).returns(() => EditOperatorAction.LABEL); mockEditOperatorAction.setup(s => s.label).returns(() => EditOperatorAction.LABEL);
assert.equal(mockEditOperatorAction.object.id, EditOperatorAction.ID); assert.equal(mockEditOperatorAction.object.id, EditOperatorAction.ID);
@@ -289,16 +262,13 @@ suite('Job Management Actions', () => {
// Edit Operator Action from Jobs View should open a dialog // Edit Operator Action from Jobs View should open a dialog
await mockEditOperatorAction.object.run(null); await mockEditOperatorAction.object.run(null);
assert(commandServiceCalled); mockEditOperatorAction.verify(s => s.run(TypeMoq.It.isAny()), TypeMoq.Times.once());
}); });
test('Delete Operator Action', async () => { test('Delete Operator Action', async () => {
mockDeleteOperatorAction = TypeMoq.Mock.ofType(DeleteOperatorAction, TypeMoq.MockBehavior.Strict, DeleteOperatorAction.ID, DeleteOperatorAction.LABEL, null, null, mockJobManagementService); mockDeleteOperatorAction = TypeMoq.Mock.ofType(DeleteOperatorAction, TypeMoq.MockBehavior.Strict, null, null, mockJobManagementService);
let commandServiceCalled = false;
mockDeleteOperatorAction.setup(s => s.run(TypeMoq.It.isAny())).returns(async () => { mockDeleteOperatorAction.setup(s => s.run(TypeMoq.It.isAny())).returns(async () => {
commandServiceCalled = true; await mockJobManagementService.object.deleteOperator(null, null);
await mockJobManagementService.object.deleteOperator(null, null).then((result) => result.success);
return commandServiceCalled;
}); });
mockDeleteOperatorAction.setup(s => s.id).returns(() => DeleteOperatorAction.ID); mockDeleteOperatorAction.setup(s => s.id).returns(() => DeleteOperatorAction.ID);
mockDeleteOperatorAction.setup(s => s.label).returns(() => DeleteOperatorAction.LABEL); mockDeleteOperatorAction.setup(s => s.label).returns(() => DeleteOperatorAction.LABEL);
@@ -307,7 +277,6 @@ suite('Job Management Actions', () => {
// Delete Operator Action should call job management service // Delete Operator Action should call job management service
await mockDeleteOperatorAction.object.run(null); await mockDeleteOperatorAction.object.run(null);
assert(commandServiceCalled);
mockJobManagementService.verify(s => s.deleteOperator(null, null), TypeMoq.Times.once()); mockJobManagementService.verify(s => s.deleteOperator(null, null), TypeMoq.Times.once());
}); });
@@ -327,11 +296,7 @@ suite('Job Management Actions', () => {
test('Edit Proxy Action', async () => { test('Edit Proxy Action', async () => {
mockEditProxyAction = TypeMoq.Mock.ofType(EditProxyAction, TypeMoq.MockBehavior.Strict, EditProxyAction.ID, EditProxyAction.LABEL); mockEditProxyAction = TypeMoq.Mock.ofType(EditProxyAction, TypeMoq.MockBehavior.Strict, EditProxyAction.ID, EditProxyAction.LABEL);
let commandServiceCalled: boolean = false; mockEditProxyAction.setup(s => s.run(TypeMoq.It.isAny()));
mockEditProxyAction.setup(s => s.run(TypeMoq.It.isAny())).returns(() => {
commandServiceCalled = true;
return Promise.resolve(commandServiceCalled);
});
mockEditProxyAction.setup(s => s.id).returns(() => EditProxyAction.ID); mockEditProxyAction.setup(s => s.id).returns(() => EditProxyAction.ID);
mockEditProxyAction.setup(s => s.label).returns(() => EditProxyAction.LABEL); mockEditProxyAction.setup(s => s.label).returns(() => EditProxyAction.LABEL);
assert.equal(mockEditProxyAction.object.id, EditProxyAction.ID); assert.equal(mockEditProxyAction.object.id, EditProxyAction.ID);
@@ -339,16 +304,13 @@ suite('Job Management Actions', () => {
// Edit Proxy Action from Proxies View should open a dialog // Edit Proxy Action from Proxies View should open a dialog
await mockEditProxyAction.object.run(null); await mockEditProxyAction.object.run(null);
assert(commandServiceCalled); mockEditProxyAction.verify(s => s.run(TypeMoq.It.isAny()), TypeMoq.Times.once());
}); });
test('Delete Proxy Action', async () => { test('Delete Proxy Action', async () => {
mockDeleteProxyAction = TypeMoq.Mock.ofType(DeleteProxyAction, TypeMoq.MockBehavior.Strict, DeleteProxyAction.ID, DeleteProxyAction.LABEL, null, null, mockJobManagementService); mockDeleteProxyAction = TypeMoq.Mock.ofType(DeleteProxyAction, TypeMoq.MockBehavior.Strict, DeleteProxyAction.ID, DeleteProxyAction.LABEL, null, null, mockJobManagementService);
let commandServiceCalled = false;
mockDeleteProxyAction.setup(s => s.run(TypeMoq.It.isAny())).returns(async () => { mockDeleteProxyAction.setup(s => s.run(TypeMoq.It.isAny())).returns(async () => {
commandServiceCalled = true; await mockJobManagementService.object.deleteProxy(null, null);
await mockJobManagementService.object.deleteProxy(null, null).then((result) => result.success);
return commandServiceCalled;
}); });
mockDeleteProxyAction.setup(s => s.id).returns(() => DeleteProxyAction.ID); mockDeleteProxyAction.setup(s => s.id).returns(() => DeleteProxyAction.ID);
mockDeleteProxyAction.setup(s => s.label).returns(() => DeleteProxyAction.LABEL); mockDeleteProxyAction.setup(s => s.label).returns(() => DeleteProxyAction.LABEL);
@@ -357,7 +319,6 @@ suite('Job Management Actions', () => {
// Delete Proxy Action should call job management service // Delete Proxy Action should call job management service
await mockDeleteProxyAction.object.run(null); await mockDeleteProxyAction.object.run(null);
assert(commandServiceCalled);
mockJobManagementService.verify(s => s.deleteProxy(null, null), TypeMoq.Times.once()); mockJobManagementService.verify(s => s.deleteProxy(null, null), TypeMoq.Times.once());
}); });
}); });

View File

@@ -52,17 +52,9 @@ export class EditCellAction extends ToggleableAction {
this.toggle(value); this.toggle(value);
} }
public run(context: CellContext): Promise<boolean> { public async run(context: CellContext): Promise<void> {
let self = this; this.editMode = !this.editMode;
return new Promise<boolean>((resolve, reject) => { context.cell.isEditMode = this.editMode;
try {
self.editMode = !self.editMode;
context.cell.isEditMode = self.editMode;
resolve(true);
} catch (e) {
reject(e);
}
});
} }
} }
@@ -358,13 +350,12 @@ export class ToggleMoreActions extends Action {
super(ToggleMoreActions.ID, ToggleMoreActions.LABEL, ToggleMoreActions.ICON); super(ToggleMoreActions.ID, ToggleMoreActions.LABEL, ToggleMoreActions.ICON);
} }
run(context: StandardKeyboardEvent): Promise<boolean> { async run(context: StandardKeyboardEvent): Promise<void> {
this._contextMenuService.showContextMenu({ this._contextMenuService.showContextMenu({
getAnchor: () => context.target, getAnchor: () => context.target,
getActions: () => this._actions, getActions: () => this._actions,
getActionsContext: () => this._context getActionsContext: () => this._context
}); });
return Promise.resolve(true);
} }
} }

View File

@@ -53,11 +53,10 @@ export abstract class CellActionBase extends Action {
return true; return true;
} }
public run(context: CellContext): Promise<boolean> { public async run(context: CellContext): Promise<void> {
if (hasModelAndCell(context, this.notificationService)) { if (hasModelAndCell(context, this.notificationService)) {
return this.doRun(context).then(() => true); return this.doRun(context);
} }
return Promise.resolve(true);
} }
abstract doRun(context: CellContext): Promise<void>; abstract doRun(context: CellContext): Promise<void>;
@@ -172,8 +171,8 @@ export class RunCellAction extends MultiStateAction<CellExecutionState> {
this.ensureContextIsUpdated(context); this.ensureContextIsUpdated(context);
} }
public run(context?: CellContext): Promise<boolean> { public async run(context?: CellContext): Promise<void> {
return this.doRun(context).then(() => true); return this.doRun(context);
} }
public async doRun(context: CellContext): Promise<void> { public async doRun(context: CellContext): Promise<void> {

View File

@@ -31,14 +31,13 @@ export class TransformMarkdownAction extends Action {
super(id, label, cssClass); super(id, label, cssClass);
this._tooltip = tooltip; this._tooltip = tooltip;
} }
public async run(context: any): Promise<boolean> { public async run(context: any): Promise<void> {
if (!context?.cellModel?.showMarkdown && context?.cellModel?.showPreview) { if (!context?.cellModel?.showMarkdown && context?.cellModel?.showPreview) {
this.transformDocumentCommand(); this.transformDocumentCommand();
} else { } else {
let markdownTextTransformer = new MarkdownTextTransformer(this._notebookService, this._cellModel); let markdownTextTransformer = new MarkdownTextTransformer(this._notebookService, this._cellModel);
await markdownTextTransformer.transformText(this._type); await markdownTextTransformer.transformText(this._type);
} }
return true;
} }
private transformDocumentCommand() { private transformDocumentCommand() {
@@ -607,7 +606,7 @@ export class ToggleViewAction extends Action {
this._tooltip = tooltip; this._tooltip = tooltip;
} }
public async run(context: MarkdownToolbarComponent): Promise<boolean> { public async run(context: MarkdownToolbarComponent): Promise<void> {
context.removeActiveClassFromModeActions(); context.removeActiveClassFromModeActions();
this.class += ' active'; this.class += ' active';
context.cellModel.showPreview = this.showPreview; context.cellModel.showPreview = this.showPreview;
@@ -618,6 +617,5 @@ export class ToggleViewAction extends Action {
} else { } else {
context.showLinkAndImageButtons(); context.showLinkAndImageButtons();
} }
return true;
} }
} }

View File

@@ -126,9 +126,9 @@ export class ClearAllOutputsAction extends TooltipFromLabelAction {
}); });
} }
public run(context: URI): Promise<boolean> { public async run(context: URI): Promise<void> {
const editor = this._notebookService.findNotebookEditor(context); const editor = this._notebookService.findNotebookEditor(context);
return editor.clearAllOutputs(); await editor.clearAllOutputs();
} }
} }
@@ -208,11 +208,10 @@ export class TrustedAction extends ToggleableAction {
this.toggle(value); this.toggle(value);
} }
public async run(context: URI): Promise<boolean> { public async run(context: URI): Promise<void> {
const editor = this._notebookService.findNotebookEditor(context); const editor = this._notebookService.findNotebookEditor(context);
this.trusted = !this.trusted; this.trusted = !this.trusted;
editor.model.trustedMode = this.trusted; editor.model.trustedMode = this.trusted;
return true;
} }
} }
@@ -226,15 +225,13 @@ export class RunAllCellsAction extends Action {
) { ) {
super(id, label, cssClass); super(id, label, cssClass);
} }
public async run(context: URI): Promise<boolean> { public async run(context: URI): Promise<void> {
try { try {
this._telemetryService.sendActionEvent(TelemetryKeys.TelemetryView.Notebook, TelemetryKeys.NbTelemetryAction.RunAll); this._telemetryService.sendActionEvent(TelemetryKeys.TelemetryView.Notebook, TelemetryKeys.NbTelemetryAction.RunAll);
const editor = this._notebookService.findNotebookEditor(context); const editor = this._notebookService.findNotebookEditor(context);
await editor.runAllCells(); await editor.runAllCells();
return true;
} catch (e) { } catch (e) {
this.notificationService.error(getErrorMessage(e)); this.notificationService.error(getErrorMessage(e));
return false;
} }
} }
} }
@@ -270,13 +267,12 @@ export class CollapseCellsAction extends ToggleableAction {
this.expanded = !value; this.expanded = !value;
} }
public async run(context: URI): Promise<boolean> { public async run(context: URI): Promise<void> {
const editor = this._notebookService.findNotebookEditor(context); const editor = this._notebookService.findNotebookEditor(context);
this.setCollapsed(!this.isCollapsed); this.setCollapsed(!this.isCollapsed);
editor.cells.forEach(cell => { editor.cells.forEach(cell => {
cell.isCollapsed = this.isCollapsed; cell.isCollapsed = this.isCollapsed;
}); });
return true;
} }
} }

View File

@@ -557,7 +557,7 @@ export class NotebookChartAction extends ToggleableAction {
}); });
} }
public async run(context: IGridActionContext): Promise<boolean> { public async run(context: IGridActionContext): Promise<void> {
this.resourceTable.toggleChartVisibility(); this.resourceTable.toggleChartVisibility();
this.toggle(!this.state.isOn); this.toggle(!this.state.isOn);
if (this.state.isOn) { if (this.state.isOn) {
@@ -573,6 +573,5 @@ export class NotebookChartAction extends ToggleableAction {
).send(); ).send();
this.resourceTable.updateChartData(Math.min(rowCount, maxRowCount), columnCount, context.gridDataProvider); this.resourceTable.updateChartData(Math.min(rowCount, maxRowCount), columnCount, context.gridDataProvider);
} }
return true;
} }
} }

View File

@@ -151,16 +151,14 @@ suite('Notebook Actions', function (): void {
// Normal use case // Normal use case
mockNotebookEditor.setup(c => c.clearAllOutputs()).returns(() => Promise.resolve(true)); mockNotebookEditor.setup(c => c.clearAllOutputs()).returns(() => Promise.resolve(true));
let result = await action.run(testUri); await action.run(testUri);
assert.ok(result, 'Clear All Outputs Action should succeed');
mockNotebookEditor.verify(c => c.clearAllOutputs(), TypeMoq.Times.once()); mockNotebookEditor.verify(c => c.clearAllOutputs(), TypeMoq.Times.once());
// Handle failure case // Handle failure case
mockNotebookEditor.reset(); mockNotebookEditor.reset();
mockNotebookEditor.setup(c => c.clearAllOutputs()).returns(() => Promise.resolve(false)); mockNotebookEditor.setup(c => c.clearAllOutputs()).returns(() => Promise.resolve(false));
result = await action.run(testUri); await action.run(testUri);
assert.strictEqual(result, false, 'Clear All Outputs Action should have failed');
mockNotebookEditor.verify(c => c.clearAllOutputs(), TypeMoq.Times.once()); mockNotebookEditor.verify(c => c.clearAllOutputs(), TypeMoq.Times.once());
}); });
@@ -177,14 +175,12 @@ suite('Notebook Actions', function (): void {
mockNotebookEditor.setup(x => x.model).returns(() => testNotebookModel); mockNotebookEditor.setup(x => x.model).returns(() => testNotebookModel);
// Normal use case // Normal use case
let result = await action.run(testUri); await action.run(testUri);
assert.ok(result, 'Trusted Action should succeed');
assert.strictEqual(action.trusted, true, 'Should be trusted after toggling trusted state'); assert.strictEqual(action.trusted, true, 'Should be trusted after toggling trusted state');
assert.strictEqual(testNotebookModel.trustedMode, true, 'Model should be true after toggling trusted state'); assert.strictEqual(testNotebookModel.trustedMode, true, 'Model should be true after toggling trusted state');
// Should toggle trusted to false on subsequent action // Should toggle trusted to false on subsequent action
result = await action.run(testUri); await action.run(testUri);
assert.ok(result, 'Trusted Action should succeed again');
assert.strictEqual(action.trusted, false, 'Should toggle trusted to false'); assert.strictEqual(action.trusted, false, 'Should toggle trusted to false');
assert.strictEqual(testNotebookModel.trustedMode, false, 'Model should be false again after toggling trusted state'); assert.strictEqual(testNotebookModel.trustedMode, false, 'Model should be false again after toggling trusted state');
}); });
@@ -198,16 +194,14 @@ suite('Notebook Actions', function (): void {
// Normal use case // Normal use case
mockNotebookEditor.setup(c => c.runAllCells()).returns(() => Promise.resolve(true)); mockNotebookEditor.setup(c => c.runAllCells()).returns(() => Promise.resolve(true));
let result = await action.run(testUri); await action.run(testUri);
assert.ok(result, 'Run All Cells Action should succeed');
mockNotebookEditor.verify(c => c.runAllCells(), TypeMoq.Times.once()); mockNotebookEditor.verify(c => c.runAllCells(), TypeMoq.Times.once());
// Handle errors // Handle errors
mockNotebookEditor.reset(); mockNotebookEditor.reset();
mockNotebookEditor.setup(c => c.runAllCells()).throws(new Error('Test Error')); mockNotebookEditor.setup(c => c.runAllCells()).throws(new Error('Test Error'));
result = await action.run(testUri); await action.run(testUri);
assert.strictEqual(result, false, 'Run All Cells Action should fail on error');
}); });
test('Collapse Cells Action', async function (): Promise<void> { test('Collapse Cells Action', async function (): Promise<void> {
@@ -225,8 +219,7 @@ suite('Notebook Actions', function (): void {
mockNotebookEditor.setup(x => x.cells).returns(() => testCells); mockNotebookEditor.setup(x => x.cells).returns(() => testCells);
// Collapse cells case // Collapse cells case
let result = await action.run(testUri); await action.run(testUri);
assert.ok(result, 'Collapse Cells Action should succeed');
assert.strictEqual(action.isCollapsed, true, 'Action should be collapsed after first toggle'); assert.strictEqual(action.isCollapsed, true, 'Action should be collapsed after first toggle');
testCells.forEach(cell => { testCells.forEach(cell => {
@@ -234,8 +227,7 @@ suite('Notebook Actions', function (): void {
}); });
// Toggle cells to uncollapsed // Toggle cells to uncollapsed
result = await action.run(testUri); await action.run(testUri);
assert.ok(result, 'Collapse Cells Action should succeed');
assert.strictEqual(action.isCollapsed, false, 'Action should not be collapsed after second toggle'); assert.strictEqual(action.isCollapsed, false, 'Action should not be collapsed after second toggle');
testCells.forEach(cell => { testCells.forEach(cell => {
@@ -254,7 +246,7 @@ suite('Notebook Actions', function (): void {
}); });
let action = new NewNotebookAction('TestId', 'TestLabel', mockCommandService.object, undefined, new NullAdsTelemetryService()); let action = new NewNotebookAction('TestId', 'TestLabel', mockCommandService.object, undefined, new NullAdsTelemetryService());
action.run(undefined); await action.run(undefined);
assert.strictEqual(actualCmdId, NewNotebookAction.INTERNAL_NEW_NOTEBOOK_CMD_ID); assert.strictEqual(actualCmdId, NewNotebookAction.INTERNAL_NEW_NOTEBOOK_CMD_ID);
}); });

View File

@@ -34,22 +34,18 @@ export class ProfilerConnect extends Action {
super(id, label, 'connect'); super(id, label, 'connect');
} }
public run(input: ProfilerInput): Promise<boolean> { public async run(input: ProfilerInput): Promise<void> {
this.enabled = false; this.enabled = false;
if (!this._connected) { if (!this._connected) {
return Promise.resolve(this._profilerService.connectSession(input.id).then(() => { await this._profilerService.connectSession(input.id);
this.enabled = true; this.enabled = true;
this.connected = true; this.connected = true;
input.state.change({ isConnected: true, isRunning: false, isPaused: false, isStopped: true }); input.state.change({ isConnected: true, isRunning: false, isPaused: false, isStopped: true });
return true;
}));
} else { } else {
return Promise.resolve(this._profilerService.disconnectSession(input.id).then(() => { await this._profilerService.disconnectSession(input.id);
this.enabled = true; this.enabled = true;
this.connected = false; this.connected = false;
input.state.change({ isConnected: false, isRunning: false, isPaused: false, isStopped: false }); input.state.change({ isConnected: false, isRunning: false, isPaused: false, isStopped: false });
return true;
}));
} }
} }
@@ -75,9 +71,9 @@ export class ProfilerStart extends Action {
super(id, label, 'sql start'); super(id, label, 'sql start');
} }
public run(input: ProfilerInput): Promise<boolean> { public async run(input: ProfilerInput): Promise<void> {
input.data.clear(); input.data.clear();
return Promise.resolve(this._profilerService.startSession(input.id, input.sessionName)); await this._profilerService.startSession(input.id, input.sessionName);
} }
} }
@@ -92,10 +88,8 @@ export class ProfilerCreate extends Action {
super(id, label, 'add'); super(id, label, 'add');
} }
public run(input: ProfilerInput): Promise<boolean> { public async run(input: ProfilerInput): Promise<void> {
return Promise.resolve(this._profilerService.launchCreateSessionDialog(input).then(() => { return this._profilerService.launchCreateSessionDialog(input);
return true;
}));
} }
} }
@@ -117,12 +111,10 @@ export class ProfilerPause extends Action {
super(id, label, ProfilerPause.PauseCssClass); super(id, label, ProfilerPause.PauseCssClass);
} }
public run(input: ProfilerInput): Promise<boolean> { public async run(input: ProfilerInput): Promise<void> {
return Promise.resolve(this._profilerService.pauseSession(input.id).then(() => { await this._profilerService.pauseSession(input.id);
this.paused = !this._paused; this.paused = !this._paused;
input.state.change({ isPaused: this.paused, isStopped: false, isRunning: !this.paused }); input.state.change({ isPaused: this.paused, isStopped: false, isRunning: !this.paused });
return true;
}));
} }
public set paused(value: boolean) { public set paused(value: boolean) {
@@ -147,8 +139,8 @@ export class ProfilerStop extends Action {
super(id, label, 'sql stop'); super(id, label, 'sql stop');
} }
public run(input: ProfilerInput): Promise<boolean> { public async run(input: ProfilerInput): Promise<void> {
return Promise.resolve(this._profilerService.stopSession(input.id)); await this._profilerService.stopSession(input.id);
} }
} }
@@ -189,12 +181,11 @@ export class ProfilerAutoScroll extends Action {
super(id, label, ProfilerAutoScroll.CheckedCssClass); super(id, label, ProfilerAutoScroll.CheckedCssClass);
} }
run(input: ProfilerInput): Promise<boolean> { async run(input: ProfilerInput): Promise<void> {
this.checked = !this.checked; this.checked = !this.checked;
this.label = this.checked ? ProfilerAutoScroll.AutoScrollOnText : ProfilerAutoScroll.AutoScrollOffText; this.label = this.checked ? ProfilerAutoScroll.AutoScrollOnText : ProfilerAutoScroll.AutoScrollOffText;
this._setClass(this.checked ? ProfilerAutoScroll.CheckedCssClass : ''); this._setClass(this.checked ? ProfilerAutoScroll.CheckedCssClass : '');
input.state.change({ autoscroll: this.checked }); input.state.change({ autoscroll: this.checked });
return Promise.resolve(true);
} }
} }
@@ -208,10 +199,9 @@ export class ProfilerCollapsablePanelAction extends Action {
super(id, label, 'codicon-chevron-down'); super(id, label, 'codicon-chevron-down');
} }
public run(input: ProfilerInput): Promise<boolean> { public async run(input: ProfilerInput): Promise<void> {
this.collapsed = !this._collapsed; this.collapsed = !this._collapsed;
input.state.change({ isPanelCollapsed: this._collapsed }); input.state.change({ isPanelCollapsed: this._collapsed });
return Promise.resolve(true);
} }
get collapsed(): boolean { get collapsed(): boolean {
@@ -235,8 +225,8 @@ export class ProfilerEditColumns extends Action {
super(id, label); super(id, label);
} }
public run(input: ProfilerInput): Promise<boolean> { public async run(input: ProfilerInput): Promise<void> {
return Promise.resolve(this._profilerService.launchColumnEditor(input)).then(() => true); await this._profilerService.launchColumnEditor(input);
} }
} }
@@ -247,9 +237,8 @@ export class ProfilerFindNext implements IEditorAction {
constructor(private profiler: IProfilerController) { } constructor(private profiler: IProfilerController) { }
run(): Promise<void> { async run(): Promise<void> {
this.profiler.findNext(); this.profiler.findNext();
return Promise.resolve(null);
} }
isSupported(): boolean { isSupported(): boolean {
@@ -264,9 +253,8 @@ export class ProfilerFindPrevious implements IEditorAction {
constructor(private profiler: IProfilerController) { } constructor(private profiler: IProfilerController) { }
run(): Promise<void> { async run(): Promise<void> {
this.profiler.findPrevious(); this.profiler.findPrevious();
return Promise.resolve(null);
} }
isSupported(): boolean { isSupported(): boolean {
@@ -290,20 +278,17 @@ export class NewProfilerAction extends Task {
}); });
} }
public runTask(accessor: ServicesAccessor, profile: IConnectionProfile): Promise<void> { public async runTask(accessor: ServicesAccessor, profile: IConnectionProfile): Promise<void> {
let profilerInput = accessor.get<IInstantiationService>(IInstantiationService).createInstance(ProfilerInput, profile); let profilerInput = accessor.get<IInstantiationService>(IInstantiationService).createInstance(ProfilerInput, profile);
return accessor.get<IEditorService>(IEditorService).openEditor(profilerInput, { pinned: true }, ACTIVE_GROUP).then(() => { await accessor.get<IEditorService>(IEditorService).openEditor(profilerInput, { pinned: true }, ACTIVE_GROUP);
let options: IConnectionCompletionOptions = { let options: IConnectionCompletionOptions = {
params: undefined, params: undefined,
saveTheConnection: false, saveTheConnection: false,
showConnectionDialogOnError: true, showConnectionDialogOnError: true,
showDashboard: false, showDashboard: false,
showFirewallRuleOnError: true showFirewallRuleOnError: true
}; };
accessor.get<IConnectionManagementService>(IConnectionManagementService).connect(this._connectionProfile, profilerInput.id, options); await accessor.get<IConnectionManagementService>(IConnectionManagementService).connect(this._connectionProfile, profilerInput.id, options);
return Promise.resolve(void 0);
});
} }
} }
@@ -318,9 +303,8 @@ export class ProfilerFilterSession extends Action {
super(id, label, 'filterLabel'); super(id, label, 'filterLabel');
} }
public run(input: ProfilerInput): Promise<boolean> { public async run(input: ProfilerInput): Promise<void> {
this._profilerService.launchFilterSessionDialog(input); this._profilerService.launchFilterSessionDialog(input);
return Promise.resolve(true);
} }
} }

View File

@@ -71,7 +71,7 @@ export class SaveResultAction extends Action {
super(id, label, icon); super(id, label, icon);
} }
public async run(context: IGridActionContext): Promise<boolean> { public async run(context: IGridActionContext): Promise<void> {
const activeEditor = this.editorService.activeEditorPane as unknown as IEncodingSupport; const activeEditor = this.editorService.activeEditorPane as unknown as IEncodingSupport;
if (typeof activeEditor.getEncoding === 'function' && activeEditor.getEncoding() !== 'utf8') { if (typeof activeEditor.getEncoding === 'function' && activeEditor.getEncoding() !== 'utf8') {
@@ -84,15 +84,14 @@ export class SaveResultAction extends Action {
if (!context.gridDataProvider.canSerialize) { if (!context.gridDataProvider.canSerialize) {
this.notificationService.warn(localize('saveToFileNotSupported', "Save to file is not supported by the backing data source")); this.notificationService.warn(localize('saveToFileNotSupported', "Save to file is not supported by the backing data source"));
return false; return;
} }
try { try {
await context.gridDataProvider.serializeResults(this.format, mapForNumberColumn(context.selection)); await context.gridDataProvider.serializeResults(this.format, mapForNumberColumn(context.selection));
} catch (error) { } catch (error) {
this.notificationService.error(getErrorMessage(error)); this.notificationService.error(getErrorMessage(error));
return false; return;
} }
return true;
} }
} }
@@ -112,10 +111,9 @@ export class CopyResultAction extends Action {
super(id, label); super(id, label);
} }
public async run(context: IGridActionContext): Promise<boolean> { public async run(context: IGridActionContext): Promise<void> {
const selection = this.accountForNumberColumn ? mapForNumberColumn(context.selection) : context.selection; const selection = this.accountForNumberColumn ? mapForNumberColumn(context.selection) : context.selection;
context.gridDataProvider.copyResults(selection, this.copyHeader, context.table.getData()); await context.gridDataProvider.copyResults(selection, this.copyHeader, context.table.getData());
return true;
} }
} }
@@ -127,9 +125,8 @@ export class SelectAllGridAction extends Action {
super(SelectAllGridAction.ID, SelectAllGridAction.LABEL); super(SelectAllGridAction.ID, SelectAllGridAction.LABEL);
} }
public run(context: IGridActionContext): Promise<boolean> { public async run(context: IGridActionContext): Promise<void> {
context.selectionModel.setSelectedRanges([new Slick.Range(0, 0, context.table.getData().getLength() - 1, context.table.columns.length - 1)]); context.selectionModel.setSelectedRanges([new Slick.Range(0, 0, context.table.getData().getLength() - 1, context.table.columns.length - 1)]);
return Promise.resolve(true);
} }
} }
@@ -142,9 +139,8 @@ export class MaximizeTableAction extends Action {
super(MaximizeTableAction.ID, MaximizeTableAction.LABEL, MaximizeTableAction.ICON); super(MaximizeTableAction.ID, MaximizeTableAction.LABEL, MaximizeTableAction.ICON);
} }
public run(context: IGridActionContext): Promise<boolean> { public async run(context: IGridActionContext): Promise<void> {
context.tableState.maximized = true; context.tableState.maximized = true;
return Promise.resolve(true);
} }
} }
@@ -157,9 +153,8 @@ export class RestoreTableAction extends Action {
super(RestoreTableAction.ID, RestoreTableAction.LABEL, RestoreTableAction.ICON); super(RestoreTableAction.ID, RestoreTableAction.LABEL, RestoreTableAction.ICON);
} }
public run(context: IGridActionContext): Promise<boolean> { public async run(context: IGridActionContext): Promise<void> {
context.tableState.maximized = false; context.tableState.maximized = false;
return Promise.resolve(true);
} }
} }
@@ -179,7 +174,7 @@ export class ChartDataAction extends Action {
super(ChartDataAction.ID, ChartDataAction.LABEL, ChartDataAction.ICON); super(ChartDataAction.ID, ChartDataAction.LABEL, ChartDataAction.ICON);
} }
public run(context: IGridActionContext): Promise<boolean> { public async run(context: IGridActionContext): Promise<void> {
// show the visualizer extension recommendation notification // show the visualizer extension recommendation notification
this.extensionTipsService.promptRecommendedExtensionsByScenario(Constants.visualizerExtensions); this.extensionTipsService.promptRecommendedExtensionsByScenario(Constants.visualizerExtensions);
const maxRowCount = getChartMaxRowCount(this.configurationService); const maxRowCount = getChartMaxRowCount(this.configurationService);
@@ -188,12 +183,14 @@ export class ChartDataAction extends Action {
if (maxRowCountExceeded) { if (maxRowCountExceeded) {
notifyMaxRowCountExceeded(this.storageService, this.notificationService, this.configurationService); notifyMaxRowCountExceeded(this.storageService, this.notificationService, this.configurationService);
} }
this.adsTelemetryService.createActionEvent(TelemetryKeys.TelemetryView.ResultsPanel, TelemetryKeys.TelemetryAction.ShowChart).withAdditionalProperties( this.adsTelemetryService.createActionEvent(TelemetryKeys.TelemetryView.ResultsPanel, TelemetryKeys.TelemetryAction.ShowChart)
{ [TelemetryKeys.TelemetryPropertyName.ChartMaxRowCountExceeded]: maxRowCountExceeded } .withAdditionalProperties(
).send(); {
[TelemetryKeys.TelemetryPropertyName.ChartMaxRowCountExceeded]: maxRowCountExceeded
})
.send();
const activeEditor = this.editorService.activeEditorPane as QueryEditor; const activeEditor = this.editorService.activeEditorPane as QueryEditor;
activeEditor.chart({ batchId: context.batchId, resultId: context.resultId }); activeEditor.chart({ batchId: context.batchId, resultId: context.resultId });
return Promise.resolve(true);
} }
} }
@@ -209,7 +206,7 @@ export class VisualizerDataAction extends Action {
super(VisualizerDataAction.ID, VisualizerDataAction.LABEL, VisualizerDataAction.ICON); super(VisualizerDataAction.ID, VisualizerDataAction.LABEL, VisualizerDataAction.ICON);
} }
public run(context: IGridActionContext): Promise<boolean> { public async run(context: IGridActionContext): Promise<void> {
this.adsTelemetryService.sendActionEvent( this.adsTelemetryService.sendActionEvent(
TelemetryKeys.TelemetryView.ResultsPanel, TelemetryKeys.TelemetryView.ResultsPanel,
TelemetryKeys.TelemetryAction.Click, TelemetryKeys.TelemetryAction.Click,
@@ -217,6 +214,5 @@ export class VisualizerDataAction extends Action {
'VisualizerDataAction' 'VisualizerDataAction'
); );
this.runner.notifyVisualizeRequested(context.batchId, context.resultId); this.runner.notifyVisualizeRequested(context.batchId, context.resultId);
return Promise.resolve(true);
} }
} }

View File

@@ -40,7 +40,7 @@ export const EDIT_DATA_COMMAND_ID = 'dataExplorer.scriptAsEdit';
// Script as Create // Script as Create
CommandsRegistry.registerCommand({ CommandsRegistry.registerCommand({
id: SCRIPT_AS_CREATE_COMMAND_ID, id: SCRIPT_AS_CREATE_COMMAND_ID,
handler: async (accessor, args: TreeViewItemHandleArg): Promise<boolean | undefined> => { handler: async (accessor, args: TreeViewItemHandleArg): Promise<void> => {
if (args.$treeItem?.payload) { if (args.$treeItem?.payload) {
const capabilitiesService = accessor.get(ICapabilitiesService); const capabilitiesService = accessor.get(ICapabilitiesService);
const oeShimService = accessor.get(IOEShimService); const oeShimService = accessor.get(IOEShimService);
@@ -56,16 +56,15 @@ CommandsRegistry.registerCommand({
}; };
const scriptCreateAction = new ScriptCreateAction(ScriptCreateAction.ID, ScriptCreateAction.LABEL, const scriptCreateAction = new ScriptCreateAction(ScriptCreateAction.ID, ScriptCreateAction.LABEL,
queryEditorService, connectionManagementService, scriptingService, errorMessageService); queryEditorService, connectionManagementService, scriptingService, errorMessageService);
return progressService.withProgress({ location: VIEWLET_ID }, () => scriptCreateAction.run(baseContext)); await progressService.withProgress({ location: VIEWLET_ID }, async () => await scriptCreateAction.run(baseContext));
} }
return undefined;
} }
}); });
// Script as Delete // Script as Delete
CommandsRegistry.registerCommand({ CommandsRegistry.registerCommand({
id: SCRIPT_AS_DELETE_COMMAND_ID, id: SCRIPT_AS_DELETE_COMMAND_ID,
handler: async (accessor, args: TreeViewItemHandleArg): Promise<boolean | undefined> => { handler: async (accessor, args: TreeViewItemHandleArg): Promise<void> => {
if (args.$treeItem?.payload) { if (args.$treeItem?.payload) {
const capabilitiesService = accessor.get(ICapabilitiesService); const capabilitiesService = accessor.get(ICapabilitiesService);
const oeShimService = accessor.get(IOEShimService); const oeShimService = accessor.get(IOEShimService);
@@ -81,16 +80,15 @@ CommandsRegistry.registerCommand({
}; };
const scriptDeleteAction = new ScriptDeleteAction(ScriptDeleteAction.ID, ScriptDeleteAction.LABEL, const scriptDeleteAction = new ScriptDeleteAction(ScriptDeleteAction.ID, ScriptDeleteAction.LABEL,
queryEditorService, connectionManagementService, scriptingService, errorMessageService); queryEditorService, connectionManagementService, scriptingService, errorMessageService);
return progressService.withProgress({ location: VIEWLET_ID }, () => scriptDeleteAction.run(baseContext)); await progressService.withProgress({ location: VIEWLET_ID }, async () => await scriptDeleteAction.run(baseContext));
} }
return undefined;
} }
}); });
// Script as Select // Script as Select
CommandsRegistry.registerCommand({ CommandsRegistry.registerCommand({
id: SCRIPT_AS_SELECT_COMMAND_ID, id: SCRIPT_AS_SELECT_COMMAND_ID,
handler: async (accessor, args: TreeViewItemHandleArg): Promise<boolean | undefined> => { handler: async (accessor, args: TreeViewItemHandleArg): Promise<void> => {
if (args.$treeItem?.payload) { if (args.$treeItem?.payload) {
const capabilitiesService = accessor.get(ICapabilitiesService); const capabilitiesService = accessor.get(ICapabilitiesService);
const oeShimService = accessor.get(IOEShimService); const oeShimService = accessor.get(IOEShimService);
@@ -105,16 +103,15 @@ CommandsRegistry.registerCommand({
}; };
const scriptSelectAction = new ScriptSelectAction(ScriptSelectAction.ID, ScriptSelectAction.LABEL, const scriptSelectAction = new ScriptSelectAction(ScriptSelectAction.ID, ScriptSelectAction.LABEL,
queryEditorService, connectionManagementService, scriptingService); queryEditorService, connectionManagementService, scriptingService);
return progressService.withProgress({ location: VIEWLET_ID }, () => scriptSelectAction.run(baseContext)); await progressService.withProgress({ location: VIEWLET_ID }, async () => await scriptSelectAction.run(baseContext));
} }
return undefined;
} }
}); });
// Script as Execute // Script as Execute
CommandsRegistry.registerCommand({ CommandsRegistry.registerCommand({
id: SCRIPT_AS_EXECUTE_COMMAND_ID, id: SCRIPT_AS_EXECUTE_COMMAND_ID,
handler: async (accessor, args: TreeViewItemHandleArg): Promise<boolean | undefined> => { handler: async (accessor, args: TreeViewItemHandleArg): Promise<void> => {
if (args.$treeItem?.payload) { if (args.$treeItem?.payload) {
const capabilitiesService = accessor.get(ICapabilitiesService); const capabilitiesService = accessor.get(ICapabilitiesService);
const oeShimService = accessor.get(IOEShimService); const oeShimService = accessor.get(IOEShimService);
@@ -130,16 +127,15 @@ CommandsRegistry.registerCommand({
}; };
const scriptExecuteAction = new ScriptExecuteAction(ScriptExecuteAction.ID, ScriptExecuteAction.LABEL, const scriptExecuteAction = new ScriptExecuteAction(ScriptExecuteAction.ID, ScriptExecuteAction.LABEL,
queryEditorService, connectionManagementService, scriptingService, errorMessageService); queryEditorService, connectionManagementService, scriptingService, errorMessageService);
return progressService.withProgress({ location: VIEWLET_ID }, () => scriptExecuteAction.run(baseContext)); await progressService.withProgress({ location: VIEWLET_ID }, async () => await scriptExecuteAction.run(baseContext));
} }
return undefined;
} }
}); });
// Script as Alter // Script as Alter
CommandsRegistry.registerCommand({ CommandsRegistry.registerCommand({
id: SCRIPT_AS_ALTER_COMMAND_ID, id: SCRIPT_AS_ALTER_COMMAND_ID,
handler: async (accessor, args: TreeViewItemHandleArg): Promise<boolean | undefined> => { handler: async (accessor, args: TreeViewItemHandleArg): Promise<void> => {
if (args.$treeItem?.payload) { if (args.$treeItem?.payload) {
const capabilitiesService = accessor.get(ICapabilitiesService); const capabilitiesService = accessor.get(ICapabilitiesService);
const oeShimService = accessor.get(IOEShimService); const oeShimService = accessor.get(IOEShimService);
@@ -155,16 +151,15 @@ CommandsRegistry.registerCommand({
}; };
const scriptAlterAction = new ScriptAlterAction(ScriptAlterAction.ID, ScriptAlterAction.LABEL, const scriptAlterAction = new ScriptAlterAction(ScriptAlterAction.ID, ScriptAlterAction.LABEL,
queryEditorService, connectionManagementService, scriptingService, errorMessageService); queryEditorService, connectionManagementService, scriptingService, errorMessageService);
return progressService.withProgress({ location: VIEWLET_ID }, () => scriptAlterAction.run(baseContext)); await progressService.withProgress({ location: VIEWLET_ID }, async () => await scriptAlterAction.run(baseContext));
} }
return undefined;
} }
}); });
// Edit Data // Edit Data
CommandsRegistry.registerCommand({ CommandsRegistry.registerCommand({
id: EDIT_DATA_COMMAND_ID, id: EDIT_DATA_COMMAND_ID,
handler: async (accessor, args: TreeViewItemHandleArg): Promise<boolean | undefined> => { handler: async (accessor, args: TreeViewItemHandleArg): Promise<void> => {
if (args.$treeItem?.payload) { if (args.$treeItem?.payload) {
const capabilitiesService = accessor.get(ICapabilitiesService); const capabilitiesService = accessor.get(ICapabilitiesService);
const oeShimService = accessor.get(IOEShimService); const oeShimService = accessor.get(IOEShimService);
@@ -179,9 +174,8 @@ CommandsRegistry.registerCommand({
}; };
const editDataAction = new EditDataAction(EditDataAction.ID, EditDataAction.LABEL, const editDataAction = new EditDataAction(EditDataAction.ID, EditDataAction.LABEL,
queryEditorService, connectionManagementService, scriptingService); queryEditorService, connectionManagementService, scriptingService);
return progressService.withProgress({ location: VIEWLET_ID }, () => editDataAction.run(baseContext)); await progressService.withProgress({ location: VIEWLET_ID }, async () => await editDataAction.run(baseContext));
} }
return undefined;
} }
}); });
//#endregion //#endregion
@@ -367,8 +361,8 @@ export class ExplorerScriptSelectAction extends ScriptSelectAction {
super(id, label, queryEditorService, connectionManagementService, scriptingService); super(id, label, queryEditorService, connectionManagementService, scriptingService);
} }
public run(actionContext: BaseActionContext): Promise<boolean> { public async run(actionContext: BaseActionContext): Promise<void> {
return this.progressService.withProgress({ location: ProgressLocation.Window }, () => super.run(actionContext)); await this.progressService.withProgress({ location: ProgressLocation.Window }, async () => await super.run(actionContext));
} }
} }
@@ -384,8 +378,8 @@ export class ExplorerScriptCreateAction extends ScriptCreateAction {
super(id, label, queryEditorService, connectionManagementService, scriptingService, errorMessageService); super(id, label, queryEditorService, connectionManagementService, scriptingService, errorMessageService);
} }
public run(actionContext: BaseActionContext): Promise<boolean> { public async run(actionContext: BaseActionContext): Promise<void> {
return this.progressService.withProgress({ location: ProgressLocation.Window }, () => super.run(actionContext)); await this.progressService.withProgress({ location: ProgressLocation.Window }, async () => await super.run(actionContext));
} }
} }
@@ -401,8 +395,8 @@ export class ExplorerScriptAlterAction extends ScriptAlterAction {
super(id, label, queryEditorService, connectionManagementService, scriptingService, errorMessageService); super(id, label, queryEditorService, connectionManagementService, scriptingService, errorMessageService);
} }
public run(actionContext: BaseActionContext): Promise<boolean> { public async run(actionContext: BaseActionContext): Promise<void> {
return this.progressService.withProgress({ location: ProgressLocation.Window }, () => super.run(actionContext)); await this.progressService.withProgress({ location: ProgressLocation.Window }, async () => await super.run(actionContext));
} }
} }
@@ -418,8 +412,8 @@ export class ExplorerScriptExecuteAction extends ScriptExecuteAction {
super(id, label, queryEditorService, connectionManagementService, scriptingService, errorMessageService); super(id, label, queryEditorService, connectionManagementService, scriptingService, errorMessageService);
} }
public run(actionContext: BaseActionContext): Promise<boolean> { public async run(actionContext: BaseActionContext): Promise<void> {
return this.progressService.withProgress({ location: ProgressLocation.Window }, () => super.run(actionContext)); await this.progressService.withProgress({ location: ProgressLocation.Window }, async () => await super.run(actionContext));
} }
} }
//#endregion //#endregion

View File

@@ -23,19 +23,18 @@ export class CancelAction extends Action {
) { ) {
super(id, label); super(id, label);
} }
public run(element: TaskNode): Promise<boolean> { public async run(element: TaskNode): Promise<void> {
if (element instanceof TaskNode && element.providerName) { if (element instanceof TaskNode && element.providerName) {
this._taskService.cancelTask(element.providerName, element.id).then((result) => { try {
const result = await this._taskService.cancelTask(element.providerName, element.id);
if (!result) { if (!result) {
let error = localize('errorMsgFromCancelTask', "The task is failed to cancel."); let error = localize('errorMsgFromCancelTask', "The task failed to cancel.");
this.showError(error); this.showError(error);
} }
}, error => { } catch (error) {
this.showError(error); this.showError(error);
return Promise.resolve(true); }
});
} }
return Promise.resolve(true);
} }
private showError(errorMessage: string) { private showError(errorMessage: string) {
@@ -57,12 +56,11 @@ export class ScriptAction extends Action {
super(id, label); super(id, label);
} }
public async run(element: TaskNode): Promise<boolean> { public async run(element: TaskNode): Promise<void> {
if (element instanceof TaskNode) { if (element instanceof TaskNode) {
if (element.script && element.script !== '') { if (element.script) {
this._queryEditorService.newSqlEditor({ initalContent: element.script }); await this._queryEditorService.newSqlEditor({ initalContent: element.script });
} }
} }
return true;
} }
} }

View File

@@ -941,7 +941,7 @@ class MultipleSelectionActionRunner extends ActionRunner {
})); }));
} }
runAction(action: IAction, context: TreeViewItemHandleArg): Promise<void> { async runAction(action: IAction, context: TreeViewItemHandleArg): Promise<void> {
const selection = this.getSelectedResources(); const selection = this.getSelectedResources();
let selectionHandleArgs: TreeViewItemHandleArg[] | undefined = undefined; let selectionHandleArgs: TreeViewItemHandleArg[] | undefined = undefined;
let actionInSelected: boolean = false; let actionInSelected: boolean = false;
@@ -958,7 +958,7 @@ class MultipleSelectionActionRunner extends ActionRunner {
selectionHandleArgs = undefined; selectionHandleArgs = undefined;
} }
return action.run(...[context, selectionHandleArgs]); await action.run(...[context, selectionHandleArgs]);
} }
} }

View File

@@ -963,7 +963,7 @@ class MultipleSelectionActionRunner extends ActionRunner {
})); }));
} }
runAction(action: IAction, context: TreeViewItemHandleArg): Promise<void> { async runAction(action: IAction, context: TreeViewItemHandleArg): Promise<void> {
const selection = this.getSelectedResources(); const selection = this.getSelectedResources();
let selectionHandleArgs: TreeViewItemHandleArg[] | undefined = undefined; let selectionHandleArgs: TreeViewItemHandleArg[] | undefined = undefined;
let actionInSelected: boolean = false; let actionInSelected: boolean = false;
@@ -980,7 +980,7 @@ class MultipleSelectionActionRunner extends ActionRunner {
selectionHandleArgs = undefined; selectionHandleArgs = undefined;
} }
return action.run(...[context, selectionHandleArgs]); await action.run(...[context, selectionHandleArgs]);
} }
} }

View File

@@ -43,7 +43,7 @@ export class RefreshAction extends Action {
) { ) {
super(id, label); super(id, label);
} }
public async run(): Promise<boolean> { public async run(): Promise<void> {
let treeNode: TreeNode | undefined = undefined; let treeNode: TreeNode | undefined = undefined;
if (this.element instanceof ConnectionProfile) { if (this.element instanceof ConnectionProfile) {
let connection: ConnectionProfile = this.element; let connection: ConnectionProfile = this.element;
@@ -67,7 +67,7 @@ export class RefreshAction extends Action {
} }
} catch (error) { } catch (error) {
this.showError(error); this.showError(error);
return true; return;
} }
if (this._tree instanceof AsyncServerTree) { if (this._tree instanceof AsyncServerTree) {
await this._tree.updateChildren(this.element); await this._tree.updateChildren(this.element);
@@ -76,10 +76,9 @@ export class RefreshAction extends Action {
} }
} catch (ex) { } catch (ex) {
this._logService.error(ex); this._logService.error(ex);
return true; return;
} }
} }
return true;
} }
private showError(errorMessage: string) { private showError(errorMessage: string) {
@@ -104,13 +103,10 @@ export class EditConnectionAction extends Action {
this.class = 'edit-server-action'; this.class = 'edit-server-action';
} }
public async run(): Promise<boolean> { public async run(): Promise<void> {
if (!this._connectionProfile) { if (this._connectionProfile) {
return false; await this._connectionManagementService.showEditConnectionDialog(this._connectionProfile);
} }
await this._connectionManagementService.showEditConnectionDialog(this._connectionProfile);
return true;
} }
} }
@@ -162,7 +158,7 @@ export class AddServerAction extends Action {
super(id, label, SqlIconId.addServerAction); super(id, label, SqlIconId.addServerAction);
} }
public async run(element: ConnectionProfileGroup): Promise<boolean> { public async run(element: ConnectionProfileGroup): Promise<void> {
// Not sure how to fix this.... // Not sure how to fix this....
let connection: Partial<IConnectionProfile> | undefined = element === undefined ? undefined : { let connection: Partial<IConnectionProfile> | undefined = element === undefined ? undefined : {
connectionName: undefined, connectionName: undefined,
@@ -182,7 +178,6 @@ export class AddServerAction extends Action {
id: element.id! id: element.id!
} as Partial<IConnectionProfile>; } as Partial<IConnectionProfile>;
await this._connectionManagementService.showConnectionDialog(undefined, undefined, connection); await this._connectionManagementService.showConnectionDialog(undefined, undefined, connection);
return true;
} }
} }
@@ -201,9 +196,8 @@ export class AddServerGroupAction extends Action {
super(id, label, SqlIconId.addServerGroupAction); super(id, label, SqlIconId.addServerGroupAction);
} }
public async run(): Promise<boolean> { public async run(): Promise<void> {
await this.serverGroupController.showCreateGroupDialog(); return this.serverGroupController.showCreateGroupDialog();
return true;
} }
} }
@@ -224,9 +218,8 @@ export class EditServerGroupAction extends Action {
this.class = 'edit-server-group-action'; this.class = 'edit-server-group-action';
} }
public run(): Promise<boolean> { public run(): Promise<void> {
this.serverGroupController.showEditGroupDialog(this._group); return this.serverGroupController.showEditGroupDialog(this._group);
return Promise.resolve(true);
} }
} }
@@ -248,7 +241,7 @@ export class ActiveConnectionsFilterAction extends Action {
super(id, label, SqlIconId.activeConnectionsAction); super(id, label, SqlIconId.activeConnectionsAction);
} }
public async run(): Promise<boolean> { public async run(): Promise<void> {
const serverTreeView = this._objectExplorerService.getServerTreeView(); const serverTreeView = this._objectExplorerService.getServerTreeView();
if (serverTreeView.view !== ServerTreeViewView.active) { if (serverTreeView.view !== ServerTreeViewView.active) {
// show active connections in the tree // show active connections in the tree
@@ -257,7 +250,6 @@ export class ActiveConnectionsFilterAction extends Action {
// show full tree // show full tree
await serverTreeView.refreshTree(); await serverTreeView.refreshTree();
} }
return true;
} }
} }
@@ -289,12 +281,11 @@ export class DeleteConnectionAction extends Action {
} }
} }
public run(): Promise<boolean> { public async run(): Promise<void> {
if (this.element instanceof ConnectionProfile) { if (this.element instanceof ConnectionProfile) {
this._connectionManagementService.deleteConnection(this.element); await this._connectionManagementService.deleteConnection(this.element);
} else if (this.element instanceof ConnectionProfileGroup) { } else if (this.element instanceof ConnectionProfileGroup) {
this._connectionManagementService.deleteConnectionGroup(this.element); await this._connectionManagementService.deleteConnectionGroup(this.element);
} }
return Promise.resolve(true);
} }
} }