Create separate ScriptableDialogBase (#22974)

* Create separate ScriptableDialogBase

* more
This commit is contained in:
Charles Gagnon
2023-05-05 09:17:51 -07:00
committed by GitHub
parent 9af7a049e6
commit c3bf85f026
14 changed files with 236 additions and 169 deletions

View File

@@ -8,7 +8,7 @@ import { IObjectManagementService, ObjectManagement } from 'mssql';
import * as localizedConstants from '../localizedConstants';
import { AlterApplicationRoleDocUrl, CreateApplicationRoleDocUrl } from '../constants';
import { isValidSQLPassword } from '../utils';
import { DefaultMaxTableHeight } from './dialogBase';
import { DefaultMaxTableHeight } from '../../ui/dialogBase';
export class ApplicationRoleDialog extends ObjectManagementDialogBase<ObjectManagement.ApplicationRoleInfo, ObjectManagement.ApplicationRoleViewInfo> {
// Sections
@@ -32,7 +32,7 @@ export class ApplicationRoleDialog extends ObjectManagementDialogBase<ObjectMana
this.objectInfo.password = this.objectInfo.password ?? '';
}
protected override get docUrl(): string {
protected override get helpUrl(): string {
return this.options.isNewObject ? CreateApplicationRoleDocUrl : AlterApplicationRoleDocUrl;
}

View File

@@ -8,7 +8,7 @@ import { IObjectManagementService, ObjectManagement } from 'mssql';
import * as localizedConstants from '../localizedConstants';
import { AlterDatabaseRoleDocUrl, CreateDatabaseRoleDocUrl } from '../constants';
import { FindObjectDialog } from './findObjectDialog';
import { DefaultMaxTableHeight } from './dialogBase';
import { DefaultMaxTableHeight } from '../../ui/dialogBase';
export class DatabaseRoleDialog extends ObjectManagementDialogBase<ObjectManagement.DatabaseRoleInfo, ObjectManagement.DatabaseRoleViewInfo> {
// Sections
@@ -30,7 +30,7 @@ export class DatabaseRoleDialog extends ObjectManagementDialogBase<ObjectManagem
super(objectManagementService, options);
}
protected override get docUrl(): string {
protected override get helpUrl(): string {
return this.options.isNewObject ? CreateDatabaseRoleDocUrl : AlterDatabaseRoleDocUrl;
}

View File

@@ -1,332 +0,0 @@
/*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the Source EULA. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
import * as azdata from 'azdata';
import * as vscode from 'vscode';
import { EOL } from 'os';
import * as localizedConstants from '../localizedConstants';
export const DefaultLabelWidth = 150;
export const DefaultInputWidth = 300;
export const DefaultTableWidth = DefaultInputWidth + DefaultLabelWidth;
export const DefaultMaxTableHeight = 400;
export const DefaultMinTableRowCount = 1;
export const TableRowHeight = 25;
export const TableColumnHeaderHeight = 30;
export function getTableHeight(rowCount: number, minRowCount: number = DefaultMinTableRowCount, maxHeight: number = DefaultMaxTableHeight): number {
return Math.min(Math.max(rowCount, minRowCount) * TableRowHeight + TableColumnHeaderHeight, maxHeight);
}
export type TableListItemEnabledStateGetter<T> = (item: T) => boolean;
export type TableListItemValueGetter<T> = (item: T) => string[];
export type TableListItemComparer<T> = (item1: T, item2: T) => boolean;
export const DefaultTableListItemEnabledStateGetter: TableListItemEnabledStateGetter<any> = (item: any) => true;
export const DefaultTableListItemValueGetter: TableListItemValueGetter<any> = (item: any) => [item?.toString() ?? ''];
export const DefaultTableListItemComparer: TableListItemComparer<any> = (item1: any, item2: any) => item1 === item2;
export abstract class DialogBase<DialogResult> {
protected readonly disposables: vscode.Disposable[] = [];
protected readonly dialogObject: azdata.window.Dialog;
private _modelView: azdata.ModelView;
private _loadingComponent: azdata.LoadingComponent;
private _formContainer: azdata.DivContainer;
private _closePromise: Promise<DialogResult | undefined>;
constructor(title: string, name: string, width: azdata.window.DialogWidth = 'narrow', style: azdata.window.DialogStyle = 'flyout') {
this.dialogObject = azdata.window.createModelViewDialog(title, name, width, style);
this.dialogObject.okButton.label = localizedConstants.OkText;
this.dialogObject.registerCloseValidator(async (): Promise<boolean> => {
const confirmed = await this.onConfirmation();
if (!confirmed) {
return false;
}
return await this.runValidation();
});
this._closePromise = new Promise<DialogResult | undefined>(resolve => {
this.disposables.push(this.dialogObject.onClosed(async (reason: azdata.window.CloseReason) => {
await this.dispose(reason);
const result = reason === 'ok' ? this.dialogResult : undefined;
resolve(result);
}));
});
}
public waitForClose(): Promise<DialogResult | undefined> {
return this._closePromise;
}
protected get dialogResult(): DialogResult | undefined { return undefined; }
protected async onConfirmation(): Promise<boolean> { return true; }
protected abstract initialize(): Promise<void>;
protected get formContainer(): azdata.DivContainer { return this._formContainer; }
protected get modelView(): azdata.ModelView { return this._modelView; }
protected onFormFieldChange(): void { }
protected validateInput(): Promise<string[]> { return Promise.resolve([]); }
public async open(): Promise<void> {
try {
this.onLoadingStatusChanged(true);
const initializeDialogPromise = new Promise<void>((async resolve => {
await this.dialogObject.registerContent(async view => {
this._modelView = view;
this._formContainer = this.createFormContainer([]);
this._loadingComponent = view.modelBuilder.loadingComponent().withItem(this._formContainer).withProps({
loading: true,
loadingText: localizedConstants.LoadingDialogText,
showText: true,
CSSStyles: {
width: "100%",
height: "100%"
}
}).component();
await view.initializeModel(this._loadingComponent);
resolve();
});
}));
azdata.window.openDialog(this.dialogObject);
await initializeDialogPromise;
await this.initialize();
this.onLoadingStatusChanged(false);
} catch (err) {
azdata.window.closeDialog(this.dialogObject);
throw err;
}
}
protected async dispose(reason: azdata.window.CloseReason): Promise<void> {
this.disposables.forEach(disposable => disposable.dispose());
}
protected async runValidation(showErrorMessage: boolean = true): Promise<boolean> {
const errors = await this.validateInput();
if (errors.length > 0 && (this.dialogObject.message?.text || showErrorMessage)) {
this.dialogObject.message = {
text: errors.join(EOL),
level: azdata.window.MessageLevel.Error
};
} else {
this.dialogObject.message = undefined;
}
return errors.length === 0;
}
protected createLabelInputContainer(label: string, input: azdata.InputBoxComponent | azdata.DropDownComponent): azdata.FlexContainer {
const labelComponent = this.modelView.modelBuilder.text().withProps({ width: DefaultLabelWidth, value: label, requiredIndicator: input.required }).component();
const container = this.modelView.modelBuilder.flexContainer().withLayout({ flexFlow: 'horizontal', flexWrap: 'nowrap', alignItems: 'center' }).withItems([labelComponent], { flex: '0 0 auto' }).component();
container.addItem(input, { flex: '1 1 auto' });
return container;
}
protected createCheckbox(label: string, handler: (checked: boolean) => Promise<void>, checked: boolean = false, enabled: boolean = true): azdata.CheckBoxComponent {
const checkbox = this.modelView.modelBuilder.checkBox().withProps({
label: label,
checked: checked,
enabled: enabled
}).component();
this.disposables.push(checkbox.onChanged(async () => {
await handler(checkbox.checked!);
this.onFormFieldChange();
await this.runValidation(false);
}));
return checkbox;
}
protected createPasswordInputBox(ariaLabel: string, textChangeHandler: (newValue: string) => Promise<void>, value: string = '', enabled: boolean = true, width: number = DefaultInputWidth): azdata.InputBoxComponent {
return this.createInputBox(ariaLabel, textChangeHandler, value, enabled, 'password', width);
}
protected createInputBox(ariaLabel: string, textChangeHandler: (newValue: string) => Promise<void>, value: string = '', enabled: boolean = true, type: azdata.InputBoxInputType = 'text', width: number = DefaultInputWidth): azdata.InputBoxComponent {
const inputbox = this.modelView.modelBuilder.inputBox().withProps({ inputType: type, enabled: enabled, ariaLabel: ariaLabel, value: value, width: width }).component();
this.disposables.push(inputbox.onTextChanged(async () => {
await textChangeHandler(inputbox.value!);
this.onFormFieldChange();
await this.runValidation(false);
}));
return inputbox;
}
protected createGroup(header: string, items: azdata.Component[], collapsible: boolean = true, collapsed: boolean = false): azdata.GroupContainer {
return this.modelView.modelBuilder.groupContainer().withLayout({
header: header,
collapsible: collapsible,
collapsed: collapsed
}).withItems(items).component();
}
protected createTableList<T>(ariaLabel: string,
columnNames: string[],
allItems: T[],
selectedItems: T[],
maxHeight: number = DefaultMaxTableHeight,
enabledStateGetter: TableListItemEnabledStateGetter<T> = DefaultTableListItemEnabledStateGetter,
rowValueGetter: TableListItemValueGetter<T> = DefaultTableListItemValueGetter,
itemComparer: TableListItemComparer<T> = DefaultTableListItemComparer): azdata.TableComponent {
const data = this.getDataForTableList(allItems, selectedItems, enabledStateGetter, rowValueGetter, itemComparer);
const table = this.modelView.modelBuilder.table().withProps(
{
ariaLabel: ariaLabel,
data: data,
columns: [
{
value: localizedConstants.SelectedText,
type: azdata.ColumnType.checkBox,
options: { actionOnCheckbox: azdata.ActionOnCellCheckboxCheck.customAction }
}, ...columnNames.map(name => {
return { value: name };
})
],
width: DefaultTableWidth,
height: getTableHeight(data.length, DefaultMinTableRowCount, maxHeight)
}
).component();
this.disposables.push(table.onCellAction!((arg: azdata.ICheckboxCellActionEventArgs) => {
const item = allItems[arg.row];
const idx = selectedItems.findIndex(i => itemComparer(i, item));
if (arg.checked && idx === -1) {
selectedItems.push(item);
} else if (!arg.checked && idx !== -1) {
selectedItems.splice(idx, 1)
}
this.onFormFieldChange();
}));
return table;
}
protected setTableData(table: azdata.TableComponent, data: any[][], maxHeight: number = DefaultMaxTableHeight) {
table.data = data;
table.height = getTableHeight(data.length, DefaultMinTableRowCount, maxHeight);
}
protected getDataForTableList<T>(
allItems: T[],
selectedItems: T[],
enabledStateGetter: TableListItemEnabledStateGetter<T> = DefaultTableListItemEnabledStateGetter,
rowValueGetter: TableListItemValueGetter<T> = DefaultTableListItemValueGetter,
itemComparer: TableListItemComparer<T> = DefaultTableListItemComparer): any[][] {
return allItems.map(item => {
const idx = selectedItems.findIndex(i => itemComparer(i, item));
const stateColumnValue = { checked: idx !== -1, enabled: enabledStateGetter(item) };
return [stateColumnValue, ...rowValueGetter(item)];
});
}
protected createTable(ariaLabel: string, columns: azdata.TableColumn[], data: any[][], maxHeight: number = DefaultMaxTableHeight): azdata.TableComponent {
const table = this.modelView.modelBuilder.table().withProps(
{
ariaLabel: ariaLabel,
data: data,
columns: columns,
width: DefaultTableWidth,
height: getTableHeight(data.length, DefaultMinTableRowCount, maxHeight)
}
).component();
return table;
}
protected addButtonsForTable(table: azdata.TableComponent, addButtonAriaLabel: string, removeButtonAriaLabel: string, addHandler: () => Promise<void>, removeHandler: () => void): azdata.FlexContainer {
let addButton: azdata.ButtonComponent;
let removeButton: azdata.ButtonComponent;
const updateButtons = () => {
removeButton.enabled = table.selectedRows.length > 0;
}
addButton = this.createButton(localizedConstants.AddText, addButtonAriaLabel, async () => {
await addHandler();
updateButtons();
});
removeButton = this.createButton(localizedConstants.RemoveText, removeButtonAriaLabel, async () => {
await removeHandler();
updateButtons();
}, false);
this.disposables.push(table.onRowSelected(() => {
updateButtons();
}));
return this.createButtonContainer([addButton, removeButton]);
}
protected createDropdown(ariaLabel: string, handler: (newValue: string) => Promise<void>, values: string[], value: string | undefined, enabled: boolean = true, width: number = DefaultInputWidth): azdata.DropDownComponent {
// Automatically add an empty item to the beginning of the list if the current value is not specified.
// This is needed when no meaningful default value can be provided.
// Create a new array so that the original array isn't modified.
const dropdownValues = [];
dropdownValues.push(...values);
if (!value) {
dropdownValues.unshift('');
}
const dropdown = this.modelView.modelBuilder.dropDown().withProps({
ariaLabel: ariaLabel,
values: dropdownValues,
value: value,
width: width,
enabled: enabled
}).component();
this.disposables.push(dropdown.onValueChanged(async () => {
await handler(<string>dropdown.value!);
this.onFormFieldChange();
await this.runValidation(false);
}));
return dropdown;
}
protected createButton(label: string, ariaLabel: string, handler: () => Promise<void>, enabled: boolean = true): azdata.ButtonComponent {
const button = this.modelView.modelBuilder.button().withProps({
label: label,
ariaLabel: ariaLabel,
enabled: enabled,
secondary: true,
CSSStyles: { 'min-width': '70px', 'margin-left': '5px' }
}).component();
this.disposables.push(button.onDidClick(async () => {
await handler();
}));
return button;
}
protected createButtonContainer(items: azdata.ButtonComponent[], justifyContent: azdata.JustifyContentType = 'flex-end'): azdata.FlexContainer {
return this.modelView.modelBuilder.flexContainer().withProps({
CSSStyles: { 'margin': '5px 0' }
}).withLayout({
flexFlow: 'horizontal',
flexWrap: 'nowrap',
justifyContent: justifyContent
}).withItems(items, { flex: '0 0 auto' }).component();
}
protected removeItem(container: azdata.DivContainer | azdata.FlexContainer, item: azdata.Component): void {
if (container.items.indexOf(item) !== -1) {
container.removeItem(item);
}
}
protected addItem(container: azdata.DivContainer | azdata.FlexContainer, item: azdata.Component, index?: number): void {
if (container.items.indexOf(item) === -1) {
if (index === undefined) {
container.addItem(item);
} else {
container.insertItem(item, index);
}
}
}
protected onLoadingStatusChanged(isLoading: boolean): void {
if (this._loadingComponent) {
this._loadingComponent.loading = isLoading;
}
}
private createFormContainer(items: azdata.Component[]): azdata.DivContainer {
return this.modelView.modelBuilder.divContainer().withLayout({ width: 'calc(100% - 20px)', height: 'calc(100% - 20px)' }).withProps({
CSSStyles: { 'padding': '10px' }
}).withItems(items, { CSSStyles: { 'margin-block-end': '10px' } }).component();
}
}

View File

@@ -5,7 +5,7 @@
import * as azdata from 'azdata';
import * as mssql from 'mssql';
import { DefaultTableListItemEnabledStateGetter, DefaultMaxTableHeight, DialogBase, TableListItemComparer, TableListItemValueGetter } from './dialogBase';
import { DefaultTableListItemEnabledStateGetter, DefaultMaxTableHeight, DialogBase, TableListItemComparer, TableListItemValueGetter } from '../../ui/dialogBase';
import * as localizedConstants from '../localizedConstants';
import { getErrorMessage } from '../../utils';

View File

@@ -6,10 +6,11 @@ import * as azdata from 'azdata';
import * as vscode from 'vscode';
import { ObjectManagementDialogBase, ObjectManagementDialogOptions } from './objectManagementDialogBase';
import { IObjectManagementService, ObjectManagement } from 'mssql';
import * as localizedConstants from '../localizedConstants';
import * as objectManagementLoc from '../localizedConstants';
import * as uiLoc from '../../ui/localizedConstants';
import { AlterLoginDocUrl, CreateLoginDocUrl, PublicServerRoleName } from '../constants';
import { isValidSQLPassword } from '../utils';
import { DefaultMaxTableHeight } from './dialogBase';
import { DefaultMaxTableHeight } from '../../ui/dialogBase';
export class LoginDialog extends ObjectManagementDialogBase<ObjectManagement.Login, ObjectManagement.LoginViewInfo> {
private generalSection: azdata.GroupContainer;
@@ -36,7 +37,7 @@ export class LoginDialog extends ObjectManagementDialogBase<ObjectManagement.Log
super(objectManagementService, options);
}
protected override get docUrl(): string {
protected override get helpUrl(): string {
return this.options.isNewObject ? CreateLoginDocUrl : AlterLoginDocUrl
}
@@ -47,8 +48,8 @@ export class LoginDialog extends ObjectManagementDialogBase<ObjectManagement.Log
&& this.objectInfo.authenticationType === ObjectManagement.AuthenticationType.Sql
&& !this.objectInfo.password
&& !this.objectInfo.enforcePasswordPolicy) {
const result = await vscode.window.showWarningMessage(localizedConstants.BlankPasswordConfirmationText, { modal: true }, localizedConstants.YesText);
return result === localizedConstants.YesText;
const result = await vscode.window.showWarningMessage(objectManagementLoc.BlankPasswordConfirmationText, { modal: true }, uiLoc.YesText);
return result === uiLoc.YesText;
}
return true;
}
@@ -57,21 +58,21 @@ export class LoginDialog extends ObjectManagementDialogBase<ObjectManagement.Log
const errors = await super.validateInput();
if (this.objectInfo.authenticationType === ObjectManagement.AuthenticationType.Sql) {
if (!this.objectInfo.password && !(this.viewInfo.supportAdvancedPasswordOptions && !this.objectInfo.enforcePasswordPolicy)) {
errors.push(localizedConstants.PasswordCannotBeEmptyError);
errors.push(objectManagementLoc.PasswordCannotBeEmptyError);
}
if (this.objectInfo.password && (this.objectInfo.enforcePasswordPolicy || !this.viewInfo.supportAdvancedPasswordOptions)
&& !isValidSQLPassword(this.objectInfo.password, this.objectInfo.name)
&& (this.options.isNewObject || this.objectInfo.password !== this.originalObjectInfo.password)) {
errors.push(localizedConstants.InvalidPasswordError);
errors.push(objectManagementLoc.InvalidPasswordError);
}
if (this.objectInfo.password !== this.confirmPasswordInput.value) {
errors.push(localizedConstants.PasswordsNotMatchError);
errors.push(objectManagementLoc.PasswordsNotMatchError);
}
if (this.specifyOldPasswordCheckbox?.checked && !this.objectInfo.oldPassword) {
errors.push(localizedConstants.OldPasswordCannotBeEmptyError);
errors.push(objectManagementLoc.OldPasswordCannotBeEmptyError);
}
}
return errors;
@@ -102,55 +103,55 @@ export class LoginDialog extends ObjectManagementDialogBase<ObjectManagement.Log
}
private initializeGeneralSection(): void {
this.nameInput = this.createInputBox(localizedConstants.NameText, async (newValue) => {
this.nameInput = this.createInputBox(objectManagementLoc.NameText, async (newValue) => {
this.objectInfo.name = newValue;
}, this.objectInfo.name, this.options.isNewObject);
const nameContainer = this.createLabelInputContainer(localizedConstants.NameText, this.nameInput);
this.authTypeDropdown = this.createDropdown(localizedConstants.AuthTypeText,
const nameContainer = this.createLabelInputContainer(objectManagementLoc.NameText, this.nameInput);
this.authTypeDropdown = this.createDropdown(objectManagementLoc.AuthTypeText,
async (newValue) => {
this.objectInfo.authenticationType = localizedConstants.getAuthenticationTypeByDisplayName(newValue);
this.objectInfo.authenticationType = objectManagementLoc.getAuthenticationTypeByDisplayName(newValue);
this.setViewByAuthenticationType();
},
this.viewInfo.authenticationTypes.map(authType => localizedConstants.getAuthenticationTypeDisplayName(authType)),
localizedConstants.getAuthenticationTypeDisplayName(this.objectInfo.authenticationType),
this.viewInfo.authenticationTypes.map(authType => objectManagementLoc.getAuthenticationTypeDisplayName(authType)),
objectManagementLoc.getAuthenticationTypeDisplayName(this.objectInfo.authenticationType),
this.options.isNewObject);
const authTypeContainer = this.createLabelInputContainer(localizedConstants.AuthTypeText, this.authTypeDropdown);
const authTypeContainer = this.createLabelInputContainer(objectManagementLoc.AuthTypeText, this.authTypeDropdown);
this.enabledCheckbox = this.createCheckbox(localizedConstants.EnabledText, async (checked) => {
this.enabledCheckbox = this.createCheckbox(objectManagementLoc.EnabledText, async (checked) => {
this.objectInfo.isEnabled = checked;
}, this.objectInfo.isEnabled);
this.generalSection = this.createGroup(localizedConstants.GeneralSectionHeader, [nameContainer, authTypeContainer, this.enabledCheckbox], false);
this.generalSection = this.createGroup(objectManagementLoc.GeneralSectionHeader, [nameContainer, authTypeContainer, this.enabledCheckbox], false);
}
private initializeSqlAuthSection(): void {
const items: azdata.Component[] = [];
this.passwordInput = this.createPasswordInputBox(localizedConstants.PasswordText, async (newValue) => {
this.passwordInput = this.createPasswordInputBox(objectManagementLoc.PasswordText, async (newValue) => {
this.objectInfo.password = newValue;
}, this.objectInfo.password ?? '');
const passwordRow = this.createLabelInputContainer(localizedConstants.PasswordText, this.passwordInput);
this.confirmPasswordInput = this.createPasswordInputBox(localizedConstants.ConfirmPasswordText, async () => { }, this.objectInfo.password ?? '');
const confirmPasswordRow = this.createLabelInputContainer(localizedConstants.ConfirmPasswordText, this.confirmPasswordInput);
const passwordRow = this.createLabelInputContainer(objectManagementLoc.PasswordText, this.passwordInput);
this.confirmPasswordInput = this.createPasswordInputBox(objectManagementLoc.ConfirmPasswordText, async () => { }, this.objectInfo.password ?? '');
const confirmPasswordRow = this.createLabelInputContainer(objectManagementLoc.ConfirmPasswordText, this.confirmPasswordInput);
items.push(passwordRow, confirmPasswordRow);
if (!this.options.isNewObject) {
this.specifyOldPasswordCheckbox = this.createCheckbox(localizedConstants.SpecifyOldPasswordText, async (checked) => {
this.specifyOldPasswordCheckbox = this.createCheckbox(objectManagementLoc.SpecifyOldPasswordText, async (checked) => {
this.oldPasswordInput.enabled = this.specifyOldPasswordCheckbox.checked;
this.objectInfo.oldPassword = '';
if (!this.specifyOldPasswordCheckbox.checked) {
this.oldPasswordInput.value = '';
}
});
this.oldPasswordInput = this.createPasswordInputBox(localizedConstants.OldPasswordText, async (newValue) => {
this.oldPasswordInput = this.createPasswordInputBox(objectManagementLoc.OldPasswordText, async (newValue) => {
this.objectInfo.oldPassword = newValue;
}, '', false);
const oldPasswordRow = this.createLabelInputContainer(localizedConstants.OldPasswordText, this.oldPasswordInput);
const oldPasswordRow = this.createLabelInputContainer(objectManagementLoc.OldPasswordText, this.oldPasswordInput);
items.push(this.specifyOldPasswordCheckbox, oldPasswordRow);
}
if (this.viewInfo.supportAdvancedPasswordOptions) {
this.enforcePasswordPolicyCheckbox = this.createCheckbox(localizedConstants.EnforcePasswordPolicyText, async (checked) => {
this.enforcePasswordPolicyCheckbox = this.createCheckbox(objectManagementLoc.EnforcePasswordPolicyText, async (checked) => {
const enforcePolicy = checked;
this.objectInfo.enforcePasswordPolicy = enforcePolicy;
this.enforcePasswordExpirationCheckbox.enabled = enforcePolicy;
@@ -159,68 +160,68 @@ export class LoginDialog extends ObjectManagementDialogBase<ObjectManagement.Log
this.mustChangePasswordCheckbox.checked = enforcePolicy;
}, this.objectInfo.enforcePasswordPolicy);
this.enforcePasswordExpirationCheckbox = this.createCheckbox(localizedConstants.EnforcePasswordExpirationText, async (checked) => {
this.enforcePasswordExpirationCheckbox = this.createCheckbox(objectManagementLoc.EnforcePasswordExpirationText, async (checked) => {
const enforceExpiration = checked;
this.objectInfo.enforcePasswordExpiration = enforceExpiration;
this.mustChangePasswordCheckbox.enabled = enforceExpiration;
this.mustChangePasswordCheckbox.checked = enforceExpiration;
}, this.objectInfo.enforcePasswordPolicy);
this.mustChangePasswordCheckbox = this.createCheckbox(localizedConstants.MustChangePasswordText, async (checked) => {
this.mustChangePasswordCheckbox = this.createCheckbox(objectManagementLoc.MustChangePasswordText, async (checked) => {
this.objectInfo.mustChangePassword = checked;
}, this.objectInfo.mustChangePassword);
items.push(this.enforcePasswordPolicyCheckbox, this.enforcePasswordExpirationCheckbox, this.mustChangePasswordCheckbox);
if (!this.options.isNewObject) {
this.lockedOutCheckbox = this.createCheckbox(localizedConstants.LoginLockedOutText, async (checked) => {
this.lockedOutCheckbox = this.createCheckbox(objectManagementLoc.LoginLockedOutText, async (checked) => {
this.objectInfo.isLockedOut = checked;
}, this.objectInfo.isLockedOut, this.viewInfo.canEditLockedOutState);
items.push(this.lockedOutCheckbox);
}
}
this.sqlAuthSection = this.createGroup(localizedConstants.SQLAuthenticationSectionHeader, items);
this.sqlAuthSection = this.createGroup(objectManagementLoc.SQLAuthenticationSectionHeader, items);
}
private initializeAdvancedSection(): void {
const items: azdata.Component[] = [];
if (this.viewInfo.supportAdvancedOptions) {
this.defaultDatabaseDropdown = this.createDropdown(localizedConstants.DefaultDatabaseText, async (newValue) => {
this.defaultDatabaseDropdown = this.createDropdown(objectManagementLoc.DefaultDatabaseText, async (newValue) => {
this.objectInfo.defaultDatabase = newValue;
}, this.viewInfo.databases, this.objectInfo.defaultDatabase);
const defaultDatabaseContainer = this.createLabelInputContainer(localizedConstants.DefaultDatabaseText, this.defaultDatabaseDropdown);
const defaultDatabaseContainer = this.createLabelInputContainer(objectManagementLoc.DefaultDatabaseText, this.defaultDatabaseDropdown);
this.defaultLanguageDropdown = this.createDropdown(localizedConstants.DefaultLanguageText, async (newValue) => {
this.defaultLanguageDropdown = this.createDropdown(objectManagementLoc.DefaultLanguageText, async (newValue) => {
this.objectInfo.defaultLanguage = newValue;
}, this.viewInfo.languages, this.objectInfo.defaultLanguage);
const defaultLanguageContainer = this.createLabelInputContainer(localizedConstants.DefaultLanguageText, this.defaultLanguageDropdown);
const defaultLanguageContainer = this.createLabelInputContainer(objectManagementLoc.DefaultLanguageText, this.defaultLanguageDropdown);
this.connectPermissionCheckbox = this.createCheckbox(localizedConstants.PermissionToConnectText, async (checked) => {
this.connectPermissionCheckbox = this.createCheckbox(objectManagementLoc.PermissionToConnectText, async (checked) => {
this.objectInfo.connectPermission = checked;
}, this.objectInfo.connectPermission);
items.push(defaultDatabaseContainer, defaultLanguageContainer, this.connectPermissionCheckbox);
}
this.advancedSection = this.createGroup(localizedConstants.AdvancedSectionHeader, items);
this.advancedSection = this.createGroup(objectManagementLoc.AdvancedSectionHeader, items);
}
private initializeServerRolesSection(): void {
this.serverRoleTable = this.createTableList(localizedConstants.ServerRoleSectionHeader,
[localizedConstants.ServerRoleTypeDisplayNameInTitle],
this.serverRoleTable = this.createTableList(objectManagementLoc.ServerRoleSectionHeader,
[objectManagementLoc.ServerRoleTypeDisplayNameInTitle],
this.viewInfo.serverRoles,
this.objectInfo.serverRoles,
DefaultMaxTableHeight,
(item) => {
return item !== PublicServerRoleName
});
this.serverRoleSection = this.createGroup(localizedConstants.ServerRoleSectionHeader, [this.serverRoleTable]);
this.serverRoleSection = this.createGroup(objectManagementLoc.ServerRoleSectionHeader, [this.serverRoleTable]);
}
private setViewByAuthenticationType(): void {
if (this.authTypeDropdown.value === localizedConstants.SQLAuthenticationTypeDisplayText) {
if (this.authTypeDropdown.value === objectManagementLoc.SQLAuthenticationTypeDisplayText) {
this.addItem(this.formContainer, this.sqlAuthSection, 1);
} else if (this.authTypeDropdown.value !== localizedConstants.SQLAuthenticationTypeDisplayText) {
} else if (this.authTypeDropdown.value !== objectManagementLoc.SQLAuthenticationTypeDisplayText) {
this.removeItem(this.formContainer, this.sqlAuthSection);
}
}

View File

@@ -5,23 +5,21 @@
import * as azdata from 'azdata';
import { IObjectManagementService, ObjectManagement } from 'mssql';
import * as vscode from 'vscode';
import { generateUuid } from 'vscode-languageclient/lib/utils/uuid';
import * as localizedConstants from '../localizedConstants';
import { deepClone, refreshNode, refreshParentNode } from '../utils';
import { DialogBase } from './dialogBase';
import { refreshNode, refreshParentNode } from '../utils';
import { ObjectManagementViewName, TelemetryActions } from '../constants';
import { TelemetryReporter } from '../../telemetry';
import { getErrorMessage } from '../../utils';
import { providerId } from '../../constants';
import { equals } from '../../util/objects';
import { deepClone, equals } from '../../util/objects';
import { ScriptableDialogBase, ScriptableDialogOptions } from '../../ui/scriptableDialogBase';
function getDialogName(type: ObjectManagement.NodeType, isNewObject: boolean): string {
return isNewObject ? `New${type}` : `${type}Properties`
}
export interface ObjectManagementDialogOptions {
export interface ObjectManagementDialogOptions extends ScriptableDialogOptions {
connectionUri: string;
database?: string;
objectType: ObjectManagement.NodeType;
@@ -29,44 +27,25 @@ export interface ObjectManagementDialogOptions {
parentUrn: string;
objectUrn?: string;
objectExplorerContext?: azdata.ObjectExplorerContext;
width?: azdata.window.DialogWidth;
objectName?: string;
}
export abstract class ObjectManagementDialogBase<ObjectInfoType extends ObjectManagement.SqlObject, ViewInfoType extends ObjectManagement.ObjectViewInfo<ObjectInfoType>> extends DialogBase<void> {
export abstract class ObjectManagementDialogBase<ObjectInfoType extends ObjectManagement.SqlObject, ViewInfoType extends ObjectManagement.ObjectViewInfo<ObjectInfoType>> extends ScriptableDialogBase<ObjectManagementDialogOptions> {
private _contextId: string;
private _viewInfo: ViewInfoType;
private _originalObjectInfo: ObjectInfoType;
private _helpButton: azdata.window.Button;
private _scriptButton: azdata.window.Button;
constructor(protected readonly objectManagementService: IObjectManagementService, protected readonly options: ObjectManagementDialogOptions) {
constructor(protected readonly objectManagementService: IObjectManagementService, options: ObjectManagementDialogOptions) {
super(options.isNewObject ? localizedConstants.NewObjectDialogTitle(localizedConstants.getNodeTypeDisplayName(options.objectType, true)) :
localizedConstants.ObjectPropertiesDialogTitle(localizedConstants.getNodeTypeDisplayName(options.objectType, true), options.objectName),
getDialogName(options.objectType, options.isNewObject),
options.width || 'narrow', 'flyout'
options
);
this._helpButton = azdata.window.createButton(localizedConstants.HelpText, 'left');
this.disposables.push(this._helpButton.onClick(async () => {
await vscode.commands.executeCommand('vscode.open', vscode.Uri.parse(this.docUrl));
}));
this._scriptButton = azdata.window.createButton(localizedConstants.ScriptText, 'left');
this.disposables.push(this._scriptButton.onClick(async () => { await this.onScriptButtonClick(); }));
this.dialogObject.customButtons = [this._helpButton, this._scriptButton];
this._contextId = generateUuid();
}
protected abstract initializeUI(): Promise<void>;
protected abstract get docUrl(): string;
protected postInitializeData(): void { }
protected override onFormFieldChange(): void {
this._scriptButton.enabled = this.isDirty;
this.dialogObject.okButton.enabled = this.isDirty;
}
protected override async validateInput(): Promise<string[]> {
const errors: string[] = [];
if (!this.objectInfo.name) {
@@ -76,8 +55,7 @@ export abstract class ObjectManagementDialogBase<ObjectInfoType extends ObjectMa
}
protected override async initialize(): Promise<void> {
await this.initializeData();
await this.initializeUI();
await super.initialize();
const typeDisplayName = localizedConstants.getNodeTypeDisplayName(this.options.objectType);
this.dialogObject.registerOperation({
displayName: this.options.isNewObject ? localizedConstants.CreateObjectOperationDisplayName(typeDisplayName)
@@ -146,49 +124,18 @@ export abstract class ObjectManagementDialogBase<ObjectInfoType extends ObjectMa
await this.objectManagementService.disposeView(this._contextId);
}
private async initializeData(): Promise<void> {
protected override async initializeData(): Promise<void> {
const viewInfo = await this.objectManagementService.initializeView(this._contextId, this.options.objectType, this.options.connectionUri, this.options.database, this.options.isNewObject, this.options.parentUrn, this.options.objectUrn);
this._viewInfo = viewInfo as ViewInfoType;
this.postInitializeData();
this._originalObjectInfo = deepClone(this.objectInfo);
}
protected override onLoadingStatusChanged(isLoading: boolean): void {
super.onLoadingStatusChanged(isLoading);
this._helpButton.enabled = !isLoading;
this.dialogObject.okButton.enabled = this._scriptButton.enabled = isLoading ? false : this.isDirty;
protected override async generateScript(): Promise<string> {
return await this.objectManagementService.script(this._contextId, this.objectInfo);
}
private async onScriptButtonClick(): Promise<void> {
this.onLoadingStatusChanged(true);
try {
const isValid = await this.runValidation();
if (!isValid) {
return;
}
let message: string;
const script = await this.objectManagementService.script(this._contextId, this.objectInfo);
if (script) {
message = localizedConstants.ScriptGeneratedText;
await azdata.queryeditor.openQueryDocument({ content: script }, providerId);
} else {
message = localizedConstants.NoActionScriptedMessage;
}
this.dialogObject.message = {
text: message,
level: azdata.window.MessageLevel.Information
};
} catch (err) {
this.dialogObject.message = {
text: localizedConstants.ScriptError(getErrorMessage(err)),
level: azdata.window.MessageLevel.Error
};
} finally {
this.onLoadingStatusChanged(false);
}
}
private get isDirty(): boolean {
protected get isDirty(): boolean {
return !equals(this.objectInfo, this._originalObjectInfo, false);
}
}

View File

@@ -30,7 +30,7 @@ export class ServerRoleDialog extends ObjectManagementDialogBase<ObjectManagemen
super(objectManagementService, options);
}
protected override get docUrl(): string {
protected override get helpUrl(): string {
return this.options.isNewObject ? CreateServerRoleDocUrl : AlterServerRoleDocUrl;
}

View File

@@ -8,7 +8,7 @@ import { IObjectManagementService, ObjectManagement } from 'mssql';
import * as localizedConstants from '../localizedConstants';
import { AlterUserDocUrl, CreateUserDocUrl } from '../constants';
import { isValidSQLPassword } from '../utils';
import { DefaultMaxTableHeight } from './dialogBase';
import { DefaultMaxTableHeight } from '../../ui/dialogBase';
export class UserDialog extends ObjectManagementDialogBase<ObjectManagement.User, ObjectManagement.UserViewInfo> {
private generalSection: azdata.GroupContainer;
@@ -34,7 +34,7 @@ export class UserDialog extends ObjectManagementDialogBase<ObjectManagement.User
super(objectManagementService, options);
}
protected override get docUrl(): string {
protected override get helpUrl(): string {
return this.options.isNewObject ? CreateUserDocUrl : AlterUserDocUrl;
}