Removing a lot of redundant async/await wrappers (#1486)

* Removing a lot of redundant async/await wrappers

* Removing kusto changes
This commit is contained in:
Benjamin Russell
2022-06-05 10:26:21 -05:00
committed by GitHub
parent 88a762014d
commit 97a106c575
14 changed files with 899 additions and 1001 deletions

View File

@@ -12,7 +12,7 @@ namespace Microsoft.InsightsGenerator
public class Workflow public class Workflow
{ {
public async Task<string> ProcessInputData(DataArray rulesData, public Task<string> ProcessInputData(DataArray rulesData,
CancellationToken cancellationToken = new CancellationToken()) CancellationToken cancellationToken = new CancellationToken())
{ {
// added cancellationToken just in case for future // added cancellationToken just in case for future
@@ -21,9 +21,7 @@ namespace Microsoft.InsightsGenerator
//Get the signature result //Get the signature result
SignatureGenerator siggen = new SignatureGenerator(rulesData); SignatureGenerator siggen = new SignatureGenerator(rulesData);
string insights = null; return Task.Run(() =>
await Task.Run(() =>
{ {
try try
{ {
@@ -31,6 +29,8 @@ namespace Microsoft.InsightsGenerator
transformer.Transform(rulesData); transformer.Transform(rulesData);
SignatureGeneratorResult result = siggen.Learn(); SignatureGeneratorResult result = siggen.Learn();
// call the rules engine processor // call the rules engine processor
string insights = null;
if (result?.Insights == null) if (result?.Insights == null)
{ {
// Console.WriteLine("Failure in generating insights, Input not recognized!"); // Console.WriteLine("Failure in generating insights, Input not recognized!");
@@ -42,6 +42,7 @@ namespace Microsoft.InsightsGenerator
// $"Good News! Insights generator has provided you the chart text: \n{insights}\n"); // $"Good News! Insights generator has provided you the chart text: \n{insights}\n");
} }
return insights;
} }
catch (Exception) catch (Exception)
{ {
@@ -50,8 +51,6 @@ namespace Microsoft.InsightsGenerator
} }
}, cancellationToken); }, cancellationToken);
return insights;
} }
} }
} }

View File

@@ -24,7 +24,7 @@ namespace Microsoft.SqlTools.Credentials
{ {
internal static string DefaultSecretsFolder = ".sqlsecrets"; internal static string DefaultSecretsFolder = ".sqlsecrets";
internal const string DefaultSecretsFile = "sqlsecrets.json"; internal const string DefaultSecretsFile = "sqlsecrets.json";
/// <summary> /// <summary>
/// Singleton service instance /// Singleton service instance
@@ -49,11 +49,11 @@ namespace Microsoft.SqlTools.Credentials
/// Default constructor is private since it's a singleton class /// Default constructor is private since it's a singleton class
/// </summary> /// </summary>
private CredentialService() private CredentialService()
: this(null, new StoreConfig() : this(null, new StoreConfig()
{ CredentialFolder = DefaultSecretsFolder, CredentialFile = DefaultSecretsFile, IsRelativeToUserHomeDir = true}) { CredentialFolder = DefaultSecretsFolder, CredentialFile = DefaultSecretsFile, IsRelativeToUserHomeDir = true})
{ {
} }
/// <summary> /// <summary>
/// Internal for testing purposes only /// Internal for testing purposes only
/// </summary> /// </summary>
@@ -102,12 +102,9 @@ namespace Microsoft.SqlTools.Credentials
} }
public async Task<Credential> ReadCredentialAsync(Credential credential) public Task<Credential> ReadCredentialAsync(Credential credential)
{ {
return await Task.Factory.StartNew(() => return Task.Run(() => ReadCredential(credential));
{
return ReadCredential(credential);
});
} }
public Credential ReadCredential(Credential credential) public Credential ReadCredential(Credential credential)
@@ -132,12 +129,9 @@ namespace Microsoft.SqlTools.Credentials
await HandleRequest(doSave, requestContext, "HandleSaveCredentialRequest"); await HandleRequest(doSave, requestContext, "HandleSaveCredentialRequest");
} }
public async Task<bool> SaveCredentialAsync(Credential credential) public Task<bool> SaveCredentialAsync(Credential credential)
{ {
return await Task.Factory.StartNew(() => return Task.Run(() => SaveCredential(credential));
{
return SaveCredential(credential);
});
} }
public bool SaveCredential(Credential credential) public bool SaveCredential(Credential credential)
@@ -155,9 +149,9 @@ namespace Microsoft.SqlTools.Credentials
await HandleRequest(doDelete, requestContext, "HandleDeleteCredentialRequest"); await HandleRequest(doDelete, requestContext, "HandleDeleteCredentialRequest");
} }
private async Task<bool> DeletePasswordAsync(Credential credential) private Task<bool> DeletePasswordAsync(Credential credential)
{ {
return await Task.Factory.StartNew(() => return Task.Run(() =>
{ {
Credential.ValidateForLookup(credential); Credential.ValidateForLookup(credential);
return credStore.DeletePassword(credential.CredentialId); return credStore.DeletePassword(credential.CredentialId);

File diff suppressed because it is too large Load Diff

View File

@@ -54,8 +54,8 @@ namespace Microsoft.SqlTools.ServiceLayer.Connection
private DatabaseLocksManager lockedDatabaseManager; private DatabaseLocksManager lockedDatabaseManager;
/// <summary> /// <summary>
/// A map containing all CancellationTokenSource objects that are associated with a given URI/ConnectionType pair. /// A map containing all CancellationTokenSource objects that are associated with a given URI/ConnectionType pair.
/// Entries in this map correspond to DbConnection instances that are in the process of connecting. /// Entries in this map correspond to DbConnection instances that are in the process of connecting.
/// </summary> /// </summary>
private readonly ConcurrentDictionary<CancelTokenKey, CancellationTokenSource> cancelTupleToCancellationTokenSourceMap = private readonly ConcurrentDictionary<CancelTokenKey, CancellationTokenSource> cancelTupleToCancellationTokenSourceMap =
new ConcurrentDictionary<CancelTokenKey, CancellationTokenSource>(); new ConcurrentDictionary<CancelTokenKey, CancellationTokenSource>();
@@ -238,7 +238,6 @@ namespace Microsoft.SqlTools.ServiceLayer.Connection
/// </summary> /// </summary>
/// <param name="ownerUri">The URI of the connection</param> /// <param name="ownerUri">The URI of the connection</param>
/// <returns> True if a refreshed was needed and requested, false otherwise </returns> /// <returns> True if a refreshed was needed and requested, false otherwise </returns>
internal async Task<bool> TryRequestRefreshAuthToken(string ownerUri) internal async Task<bool> TryRequestRefreshAuthToken(string ownerUri)
{ {
ConnectionInfo connInfo; ConnectionInfo connInfo;
@@ -273,7 +272,7 @@ namespace Microsoft.SqlTools.ServiceLayer.Connection
Logger.Error("No accountId in connection details when refreshing token for connection {ownerUri}"); Logger.Error("No accountId in connection details when refreshing token for connection {ownerUri}");
return false; return false;
} }
// Check if the token is updating already, in which case there is no need to request a new one, // Check if the token is updating already, in which case there is no need to request a new one,
// but still return true so that autocompletion is disabled until the token is refreshed // but still return true so that autocompletion is disabled until the token is refreshed
if (!this.TokenUpdateUris.TryAdd(ownerUri, true)) if (!this.TokenUpdateUris.TryAdd(ownerUri, true))
{ {
@@ -299,7 +298,7 @@ namespace Microsoft.SqlTools.ServiceLayer.Connection
/// Requests an update of the azure auth token /// Requests an update of the azure auth token
/// </summary> /// </summary>
/// <param name="refreshToken">The token to update</param> /// <param name="refreshToken">The token to update</param>
/// <returns>true upon successful update, false if it failed to find /// <returns>true upon successful update, false if it failed to find
/// the connection</returns> /// the connection</returns>
internal void UpdateAuthToken(TokenRefreshedParams tokenRefreshedParams) internal void UpdateAuthToken(TokenRefreshedParams tokenRefreshedParams)
{ {
@@ -312,6 +311,12 @@ namespace Microsoft.SqlTools.ServiceLayer.Connection
connection.UpdateAuthToken(tokenRefreshedParams.Token, tokenRefreshedParams.ExpiresOn); connection.UpdateAuthToken(tokenRefreshedParams.Token, tokenRefreshedParams.ExpiresOn);
} }
/// <summary>
/// Validates the given ConnectParams object.
/// </summary>
/// <param name="connectionParams">The params to validate</param>
/// <returns>A ConnectionCompleteParams object upon validation error,
/// null upon validation success</returns>
public ConnectionCompleteParams ValidateConnectParams(ConnectParams connectionParams) public ConnectionCompleteParams ValidateConnectParams(ConnectParams connectionParams)
{ {
string paramValidationErrorMessage; string paramValidationErrorMessage;
@@ -350,7 +355,7 @@ namespace Microsoft.SqlTools.ServiceLayer.Connection
TrySetConnectionType(connectionParams); TrySetConnectionType(connectionParams);
connectionParams.Connection.ApplicationName = GetApplicationNameWithFeature(connectionParams.Connection.ApplicationName, connectionParams.Purpose); connectionParams.Connection.ApplicationName = GetApplicationNameWithFeature(connectionParams.Connection.ApplicationName, connectionParams.Purpose);
// If there is no ConnectionInfo in the map, create a new ConnectionInfo, // If there is no ConnectionInfo in the map, create a new ConnectionInfo,
// but wait until later when we are connected to add it to the map. // but wait until later when we are connected to add it to the map.
ConnectionInfo connectionInfo; ConnectionInfo connectionInfo;
bool connectionChanged = false; bool connectionChanged = false;
@@ -388,7 +393,7 @@ namespace Microsoft.SqlTools.ServiceLayer.Connection
// Return information about the connected SQL Server instance // Return information about the connected SQL Server instance
ConnectionCompleteParams completeParams = GetConnectionCompleteParams(connectionParams.Type, connectionInfo); ConnectionCompleteParams completeParams = GetConnectionCompleteParams(connectionParams.Type, connectionInfo);
// Invoke callback notifications // Invoke callback notifications
InvokeOnConnectionActivities(connectionInfo, connectionParams); InvokeOnConnectionActivities(connectionInfo, connectionParams);
TryCloseConnectionTemporaryConnection(connectionParams, connectionInfo); TryCloseConnectionTemporaryConnection(connectionParams, connectionInfo);
@@ -486,7 +491,7 @@ namespace Microsoft.SqlTools.ServiceLayer.Connection
} }
/// <summary> /// <summary>
/// Creates a ConnectionCompleteParams as a response to a successful connection. /// Creates a ConnectionCompleteParams as a response to a successful connection.
/// Also sets the DatabaseName and IsAzure properties of ConnectionInfo. /// Also sets the DatabaseName and IsAzure properties of ConnectionInfo.
/// </summary> /// </summary>
/// <returns>A ConnectionCompleteParams in response to the successful connection</returns> /// <returns>A ConnectionCompleteParams in response to the successful connection</returns>
@@ -501,7 +506,7 @@ namespace Microsoft.SqlTools.ServiceLayer.Connection
// Update with the actual database name in connectionInfo and result // Update with the actual database name in connectionInfo and result
// Doing this here as we know the connection is open - expect to do this only on connecting // Doing this here as we know the connection is open - expect to do this only on connecting
// Do not update the DB name if it is a DB Pool database name (e.g. "db@pool") // Do not update the DB name if it is a DB Pool database name (e.g. "db@pool")
if (!ConnectionService.IsDbPool(connectionInfo.ConnectionDetails.DatabaseName)) if (!ConnectionService.IsDbPool(connectionInfo.ConnectionDetails.DatabaseName))
{ {
connectionInfo.ConnectionDetails.DatabaseName = connection.Database; connectionInfo.ConnectionDetails.DatabaseName = connection.Database;
@@ -680,8 +685,8 @@ namespace Microsoft.SqlTools.ServiceLayer.Connection
} }
/// <summary> /// <summary>
/// Gets the existing connection with the given URI and connection type string. If none exists, /// Gets the existing connection with the given URI and connection type string. If none exists,
/// creates a new connection. This cannot be used to create a default connection or to create a /// creates a new connection. This cannot be used to create a default connection or to create a
/// connection if a default connection does not exist. /// connection if a default connection does not exist.
/// </summary> /// </summary>
/// <param name="ownerUri">URI identifying the resource mapped to this connection</param> /// <param name="ownerUri">URI identifying the resource mapped to this connection</param>
@@ -738,7 +743,7 @@ namespace Microsoft.SqlTools.ServiceLayer.Connection
bool alwaysPersistSecurity, ConnectionInfo connectionInfo) bool alwaysPersistSecurity, ConnectionInfo connectionInfo)
{ {
// If the DbConnection does not exist and is not the default connection, create one. // If the DbConnection does not exist and is not the default connection, create one.
// We can't create the default (initial) connection here because we won't have a ConnectionDetails // We can't create the default (initial) connection here because we won't have a ConnectionDetails
// if Connect() has not yet been called. // if Connect() has not yet been called.
bool? originalPersistSecurityInfo = connectionInfo.ConnectionDetails.PersistSecurityInfo; bool? originalPersistSecurityInfo = connectionInfo.ConnectionDetails.PersistSecurityInfo;
if (alwaysPersistSecurity) if (alwaysPersistSecurity)
@@ -929,14 +934,14 @@ namespace Microsoft.SqlTools.ServiceLayer.Connection
/// If connectionType is not null, cancel the connection with the given connectionType /// If connectionType is not null, cancel the connection with the given connectionType
/// If connectionType is null, cancel all pending connections associated with ownerUri. /// If connectionType is null, cancel all pending connections associated with ownerUri.
/// </summary> /// </summary>
/// <returns>true if a single pending connection associated with the non-null connectionType was /// <returns>true if a single pending connection associated with the non-null connectionType was
/// found and cancelled, false otherwise</returns> /// found and cancelled, false otherwise</returns>
private bool CancelConnections(string ownerUri, string connectionType) private bool CancelConnections(string ownerUri, string connectionType)
{ {
// Cancel the connection of the given type // Cancel the connection of the given type
if (connectionType != null) if (connectionType != null)
{ {
// If we are trying to disconnect a specific connection and it was just cancelled, // If we are trying to disconnect a specific connection and it was just cancelled,
// this will return true // this will return true
return CancelConnect(new CancelConnectParams() { OwnerUri = ownerUri, Type = connectionType }); return CancelConnect(new CancelConnectParams() { OwnerUri = ownerUri, Type = connectionType });
} }
@@ -956,7 +961,7 @@ namespace Microsoft.SqlTools.ServiceLayer.Connection
} }
/// <summary> /// <summary>
/// Closes DbConnections associated with the given ConnectionInfo. /// Closes DbConnections associated with the given ConnectionInfo.
/// If connectionType is not null, closes the DbConnection with the type given by connectionType. /// If connectionType is not null, closes the DbConnection with the type given by connectionType.
/// If connectionType is null, closes all DbConnections. /// If connectionType is null, closes all DbConnections.
/// </summary> /// </summary>
@@ -1036,10 +1041,10 @@ namespace Microsoft.SqlTools.ServiceLayer.Connection
serviceHost.SetRequestHandler(BuildConnectionInfoRequest.Type, HandleBuildConnectionInfoRequest); serviceHost.SetRequestHandler(BuildConnectionInfoRequest.Type, HandleBuildConnectionInfoRequest);
} }
/// <summary> /// <summary>
/// Add a new method to be called when the onconnection request is submitted /// Add a new method to be called when the onconnection request is submitted
/// </summary> /// </summary>
/// <param name="activity"></param> /// <param name="activity"></param>
public void RegisterOnConnectionTask(OnConnectionHandler activity) public void RegisterOnConnectionTask(OnConnectionHandler activity)
{ {
onConnectionActivities.Add(activity); onConnectionActivities.Add(activity);
@@ -1083,7 +1088,7 @@ namespace Microsoft.SqlTools.ServiceLayer.Connection
{ {
try try
{ {
// result is null if the ConnectParams was successfully validated // result is null if the ConnectParams was successfully validated
ConnectionCompleteParams result = ValidateConnectParams(connectParams); ConnectionCompleteParams result = ValidateConnectParams(connectParams);
if (result != null) if (result != null)
{ {
@@ -1395,42 +1400,39 @@ namespace Microsoft.SqlTools.ServiceLayer.Connection
GetConnectionStringParams connStringParams, GetConnectionStringParams connStringParams,
RequestContext<string> requestContext) RequestContext<string> requestContext)
{ {
await Task.Run(async () => string connectionString = string.Empty;
ConnectionInfo info;
SqlConnectionStringBuilder connStringBuilder;
try
{ {
string connectionString = string.Empty; // set connection string using connection uri if connection details are undefined
ConnectionInfo info; if (connStringParams.ConnectionDetails == null)
SqlConnectionStringBuilder connStringBuilder;
try
{ {
// set connection string using connection uri if connection details are undefined TryFindConnection(connStringParams.OwnerUri, out info);
if (connStringParams.ConnectionDetails == null) connStringBuilder = CreateConnectionStringBuilder(info.ConnectionDetails);
{
TryFindConnection(connStringParams.OwnerUri, out info);
connStringBuilder = CreateConnectionStringBuilder(info.ConnectionDetails);
}
// set connection string using connection details
else
{
connStringBuilder = CreateConnectionStringBuilder(connStringParams.ConnectionDetails as ConnectionDetails);
}
if (!connStringParams.IncludePassword)
{
connStringBuilder.Password = ConnectionService.PasswordPlaceholder;
}
// default connection string application name to always be included unless set to false
if (!connStringParams.IncludeApplicationName.HasValue || connStringParams.IncludeApplicationName.Value == true)
{
connStringBuilder.ApplicationName = "sqlops-connection-string";
}
connectionString = connStringBuilder.ConnectionString;
} }
catch (Exception e) // set connection string using connection details
else
{ {
await requestContext.SendError(e.ToString()); connStringBuilder = CreateConnectionStringBuilder(connStringParams.ConnectionDetails as ConnectionDetails);
} }
if (!connStringParams.IncludePassword)
{
connStringBuilder.Password = ConnectionService.PasswordPlaceholder;
}
// default connection string application name to always be included unless set to false
if (!connStringParams.IncludeApplicationName.HasValue || connStringParams.IncludeApplicationName.Value == true)
{
connStringBuilder.ApplicationName = "sqlops-connection-string";
}
connectionString = connStringBuilder.ConnectionString;
}
catch (Exception e)
{
await requestContext.SendError(e.ToString());
}
await requestContext.SendResult(connectionString); await requestContext.SendResult(connectionString);
});
} }
/// <summary> /// <summary>
@@ -1440,19 +1442,16 @@ namespace Microsoft.SqlTools.ServiceLayer.Connection
string connectionString, string connectionString,
RequestContext<ConnectionDetails> requestContext) RequestContext<ConnectionDetails> requestContext)
{ {
await Task.Run(async () => try
{ {
try await requestContext.SendResult(ParseConnectionString(connectionString));
{ }
await requestContext.SendResult(ParseConnectionString(connectionString)); catch (Exception)
} {
catch (Exception) // If theres an error in the parse, it means we just can't parse, so we return undefined
{ // rather than an error.
// If theres an error in the parse, it means we just can't parse, so we return undefined await requestContext.SendResult(null);
// rather than an error. }
await requestContext.SendResult(null);
}
});
} }
public ConnectionDetails ParseConnectionString(string connectionString) public ConnectionDetails ParseConnectionString(string connectionString)

View File

@@ -110,9 +110,9 @@ namespace Microsoft.SqlTools.ServiceLayer.Formatter
}; };
} }
private async Task<TextEdit[]> FormatRangeAndReturnEdits(DocumentRangeFormattingParams docFormatParams) private Task<TextEdit[]> FormatRangeAndReturnEdits(DocumentRangeFormattingParams docFormatParams)
{ {
return await Task.Factory.StartNew(() => return Task.Run(() =>
{ {
if (ShouldSkipFormatting(docFormatParams)) if (ShouldSkipFormatting(docFormatParams))
{ {
@@ -123,7 +123,7 @@ namespace Microsoft.SqlTools.ServiceLayer.Formatter
ScriptFile scriptFile = GetFile(docFormatParams); ScriptFile scriptFile = GetFile(docFormatParams);
if (scriptFile == null) if (scriptFile == null)
{ {
return new TextEdit[0]; return Array.Empty<TextEdit>();
} }
TextEdit textEdit = new TextEdit { Range = range }; TextEdit textEdit = new TextEdit { Range = range };
string text = scriptFile.GetTextInRange(range.ToBufferRange()); string text = scriptFile.GetTextInRange(range.ToBufferRange());
@@ -142,9 +142,9 @@ namespace Microsoft.SqlTools.ServiceLayer.Formatter
return (LanguageService != null && LanguageService.ShouldSkipNonMssqlFile(docFormatParams.TextDocument.Uri)); return (LanguageService != null && LanguageService.ShouldSkipNonMssqlFile(docFormatParams.TextDocument.Uri));
} }
private async Task<TextEdit[]> FormatAndReturnEdits(DocumentFormattingParams docFormatParams) private Task<TextEdit[]> FormatAndReturnEdits(DocumentFormattingParams docFormatParams)
{ {
return await Task.Factory.StartNew(() => return Task.Factory.StartNew(() =>
{ {
if (ShouldSkipFormatting(docFormatParams)) if (ShouldSkipFormatting(docFormatParams))
{ {
@@ -155,7 +155,7 @@ namespace Microsoft.SqlTools.ServiceLayer.Formatter
if (scriptFile == null if (scriptFile == null
|| scriptFile.FileLines.Count == 0) || scriptFile.FileLines.Count == 0)
{ {
return new TextEdit[0]; return Array.Empty<TextEdit>();
} }
TextEdit textEdit = PrepareEdit(scriptFile); TextEdit textEdit = PrepareEdit(scriptFile);
string text = scriptFile.Contents; string text = scriptFile.Contents;
@@ -205,12 +205,12 @@ namespace Microsoft.SqlTools.ServiceLayer.Formatter
if (settings.PlaceSelectStatementReferencesOnNewLine.HasValue) { options.PlaceEachReferenceOnNewLineInQueryStatements = settings.PlaceSelectStatementReferencesOnNewLine.Value; } if (settings.PlaceSelectStatementReferencesOnNewLine.HasValue) { options.PlaceEachReferenceOnNewLineInQueryStatements = settings.PlaceSelectStatementReferencesOnNewLine.Value; }
if (settings.UseBracketForIdentifiers.HasValue) { options.EncloseIdentifiersInSquareBrackets = settings.UseBracketForIdentifiers.Value; } if (settings.UseBracketForIdentifiers.HasValue) { options.EncloseIdentifiersInSquareBrackets = settings.UseBracketForIdentifiers.Value; }
options.DatatypeCasing = settings.DatatypeCasing; options.DatatypeCasing = settings.DatatypeCasing;
options.KeywordCasing = settings.KeywordCasing; options.KeywordCasing = settings.KeywordCasing;
} }
} }
private ScriptFile GetFile(DocumentFormattingParams docFormatParams) private ScriptFile GetFile(DocumentFormattingParams docFormatParams)
{ {
return WorkspaceService.Workspace.GetFile(docFormatParams.TextDocument.Uri); return WorkspaceService.Workspace.GetFile(docFormatParams.TextDocument.Uri);

View File

@@ -201,10 +201,10 @@ namespace Microsoft.SqlTools.ServiceLayer
IDisposable disposable = service as IDisposable; IDisposable disposable = service as IDisposable;
if (serviceHost != null && disposable != null) if (serviceHost != null && disposable != null)
{ {
serviceHost.RegisterShutdownTask(async (shutdownParams, shutdownRequestContext) => serviceHost.RegisterShutdownTask((_, _) =>
{ {
disposable.Dispose(); disposable.Dispose();
await Task.FromResult(0); return Task.FromResult(0);
}); });
} }
} }

View File

@@ -270,12 +270,12 @@ namespace Microsoft.SqlTools.ServiceLayer.LanguageServices
serviceHost.SetEventHandler(TokenRefreshedNotification.Type, HandleTokenRefreshedNotification); serviceHost.SetEventHandler(TokenRefreshedNotification.Type, HandleTokenRefreshedNotification);
// Register a no-op shutdown task for validation of the shutdown logic // Register a no-op shutdown task for validation of the shutdown logic
serviceHost.RegisterShutdownTask(async (shutdownParams, shutdownRequestContext) => serviceHost.RegisterShutdownTask((shutdownParams, shutdownRequestContext) =>
{ {
Logger.Write(TraceEventType.Verbose, "Shutting down language service"); Logger.Write(TraceEventType.Verbose, "Shutting down language service");
DeletePeekDefinitionScripts(); DeletePeekDefinitionScripts();
this.Dispose(); this.Dispose();
await Task.FromResult(0); return Task.FromResult(0);
}); });
ServiceHostInstance = serviceHost; ServiceHostInstance = serviceHost;
@@ -399,33 +399,30 @@ namespace Microsoft.SqlTools.ServiceLayer.LanguageServices
/// <returns></returns> /// <returns></returns>
internal async Task HandleSyntaxParseRequest(SyntaxParseParams param, RequestContext<SyntaxParseResult> requestContext) internal async Task HandleSyntaxParseRequest(SyntaxParseParams param, RequestContext<SyntaxParseResult> requestContext)
{ {
await Task.Run(async () => try
{ {
try ParseResult result = Parser.Parse(param.Query);
SyntaxParseResult syntaxResult = new SyntaxParseResult();
if (result != null && !result.Errors.Any())
{ {
ParseResult result = Parser.Parse(param.Query); syntaxResult.Parseable = true;
SyntaxParseResult syntaxResult = new SyntaxParseResult();
if (result != null && result.Errors.Count() == 0)
{
syntaxResult.Parseable = true;
}
else
{
syntaxResult.Parseable = false;
string[] errorMessages = new string[result.Errors.Count()];
for (int i = 0; i < result.Errors.Count(); i++)
{
errorMessages[i] = result.Errors.ElementAt(i).Message;
}
syntaxResult.Errors = errorMessages;
}
await requestContext.SendResult(syntaxResult);
} }
catch (Exception ex) else
{ {
await requestContext.SendError(ex.ToString()); syntaxResult.Parseable = false;
string[] errorMessages = new string[result.Errors.Count()];
for (int i = 0; i < result.Errors.Count(); i++)
{
errorMessages[i] = result.Errors.ElementAt(i).Message;
}
syntaxResult.Errors = errorMessages;
} }
}); await requestContext.SendResult(syntaxResult);
}
catch (Exception ex)
{
await requestContext.SendError(ex.ToString());
}
} }
/// <summary> /// <summary>
@@ -674,8 +671,6 @@ namespace Microsoft.SqlTools.ServiceLayer.LanguageServices
new ScriptFile[] { scriptFile }, new ScriptFile[] { scriptFile },
eventContext); eventContext);
} }
await Task.FromResult(true);
} }
catch (Exception ex) catch (Exception ex)
{ {
@@ -700,8 +695,6 @@ namespace Microsoft.SqlTools.ServiceLayer.LanguageServices
changedFiles.ToArray(), changedFiles.ToArray(),
eventContext); eventContext);
} }
await Task.FromResult(true);
} }
catch (Exception ex) catch (Exception ex)
{ {
@@ -902,7 +895,7 @@ namespace Microsoft.SqlTools.ServiceLayer.LanguageServices
{ {
bool value; bool value;
this.nonMssqlUriMap.TryRemove(changeParams.Uri, out value); this.nonMssqlUriMap.TryRemove(changeParams.Uri, out value);
// should rebuild intellisense when re-considering as sql // should rebuild intellisense when re-considering as sql
RebuildIntelliSenseParams param = new RebuildIntelliSenseParams { OwnerUri = changeParams.Uri }; RebuildIntelliSenseParams param = new RebuildIntelliSenseParams { OwnerUri = changeParams.Uri };
await HandleRebuildIntelliSenseNotification(param, eventContext); await HandleRebuildIntelliSenseNotification(param, eventContext);
} }
@@ -933,13 +926,13 @@ namespace Microsoft.SqlTools.ServiceLayer.LanguageServices
/// it is the last URI connected to a particular connection, /// it is the last URI connected to a particular connection,
/// then remove the cache. /// then remove the cache.
/// </summary> /// </summary>
public async Task RemoveAutoCompleteCacheUriReference(IConnectionSummary summary, string ownerUri) public Task RemoveAutoCompleteCacheUriReference(IConnectionSummary summary, string ownerUri)
{ {
RemoveScriptParseInfo(ownerUri); RemoveScriptParseInfo(ownerUri);
// currently this method is disabled, but we need to reimplement now that the // currently this method is disabled, but we need to reimplement now that the
// implementation of the 'cache' has changed. // implementation of the 'cache' has changed.
await Task.FromResult(0); return Task.CompletedTask;
} }
/// <summary> /// <summary>
@@ -1049,9 +1042,9 @@ namespace Microsoft.SqlTools.ServiceLayer.LanguageServices
/// Update the autocomplete metadata provider when the user connects to a database /// Update the autocomplete metadata provider when the user connects to a database
/// </summary> /// </summary>
/// <param name="info"></param> /// <param name="info"></param>
public async Task UpdateLanguageServiceOnConnection(ConnectionInfo info) public Task UpdateLanguageServiceOnConnection(ConnectionInfo info)
{ {
await Task.Run(() => return Task.Run(() =>
{ {
if (ConnectionService.IsDedicatedAdminConnection(info.ConnectionDetails)) if (ConnectionService.IsDedicatedAdminConnection(info.ConnectionDetails))
{ {
@@ -1674,10 +1667,10 @@ namespace Microsoft.SqlTools.ServiceLayer.LanguageServices
// cache the current script parse info object to resolve completions later // cache the current script parse info object to resolve completions later
this.currentCompletionParseInfo = scriptParseInfo; this.currentCompletionParseInfo = scriptParseInfo;
resultCompletionItems = result.CompletionItems; resultCompletionItems = result.CompletionItems;
/* /*
Expanding star expressions in query only when the script is connected to a database Expanding star expressions in query only when the script is connected to a database
as the parser requires a connection to determine column names as the parser requires a connection to determine column names
*/ */
if (connInfo != null) if (connInfo != null)
{ {

View File

@@ -58,7 +58,7 @@ namespace Microsoft.SqlTools.ServiceLayer.NotebookConvert
} }
/// <summary> /// <summary>
/// Initializes the service by doing tasks such as setting up request handlers. /// Initializes the service by doing tasks such as setting up request handlers.
/// </summary> /// </summary>
/// <param name="serviceHost"></param> /// <param name="serviceHost"></param>
public void InitializeService(ServiceHost serviceHost) public void InitializeService(ServiceHost serviceHost)
@@ -75,49 +75,42 @@ namespace Microsoft.SqlTools.ServiceLayer.NotebookConvert
internal async Task HandleConvertNotebookToSqlRequest(ConvertNotebookToSqlParams parameters, RequestContext<ConvertNotebookToSqlResult> requestContext) internal async Task HandleConvertNotebookToSqlRequest(ConvertNotebookToSqlParams parameters, RequestContext<ConvertNotebookToSqlResult> requestContext)
{ {
await Task.Run(async () => try
{ {
try var notebookDoc = JsonConvert.DeserializeObject<NotebookDocument>(parameters.Content);
{
var notebookDoc = JsonConvert.DeserializeObject<NotebookDocument>(parameters.Content);
var result = new ConvertNotebookToSqlResult var result = new ConvertNotebookToSqlResult
{
Content = ConvertNotebookDocToSql(notebookDoc)
};
await requestContext.SendResult(result);
}
catch (Exception e)
{ {
await requestContext.SendError(e); Content = ConvertNotebookDocToSql(notebookDoc)
} };
}); await requestContext.SendResult(result);
}
catch (Exception e)
{
await requestContext.SendError(e);
}
} }
internal async Task HandleConvertSqlToNotebookRequest(ConvertSqlToNotebookParams parameters, RequestContext<ConvertSqlToNotebookResult> requestContext) internal async Task HandleConvertSqlToNotebookRequest(ConvertSqlToNotebookParams parameters, RequestContext<ConvertSqlToNotebookResult> requestContext)
{ {
await Task.Run(async () => try
{ {
// This URI doesn't come in escaped - so if it's a file path with reserved characters (such as %)
try // then we'll fail to find it since GetFile expects the URI to be a fully-escaped URI as that's
// what the document events are sent in as.
var escapedClientUri = Uri.EscapeUriString(parameters.ClientUri);
var file = WorkspaceService<SqlToolsSettings>.Instance.Workspace.GetFile(escapedClientUri);
// Temporary notebook that we just fill in with the sql until the parsing logic is added
var result = new ConvertSqlToNotebookResult
{ {
// This URI doesn't come in escaped - so if it's a file path with reserved characters (such as %) Content = JsonConvert.SerializeObject(ConvertSqlToNotebook(file.Contents))
// then we'll fail to find it since GetFile expects the URI to be a fully-escaped URI as that's };
// what the document events are sent in as. await requestContext.SendResult(result);
var escapedClientUri = Uri.EscapeUriString(parameters.ClientUri); }
var file = WorkspaceService<SqlToolsSettings>.Instance.Workspace.GetFile(escapedClientUri); catch (Exception e)
// Temporary notebook that we just fill in with the sql until the parsing logic is added {
var result = new ConvertSqlToNotebookResult await requestContext.SendError(e);
{ }
Content = JsonConvert.SerializeObject(ConvertSqlToNotebook(file.Contents))
};
await requestContext.SendResult(result);
}
catch (Exception e)
{
await requestContext.SendError(e);
}
});
} }
#endregion // Convert Handlers #endregion // Convert Handlers
@@ -155,11 +148,11 @@ namespace Microsoft.SqlTools.ServiceLayer.NotebookConvert
var tokens = parseResult.ScriptTokenStream; var tokens = parseResult.ScriptTokenStream;
/** /**
* Split the text into separate chunks - blocks of Mutliline comments and blocks * Split the text into separate chunks - blocks of Mutliline comments and blocks
* of everything else (batches). We then create a markdown cell for each multiline comment and a code * of everything else (batches). We then create a markdown cell for each multiline comment and a code
* cell for the other blocks. * cell for the other blocks.
* We only take multiline comments which aren't part of a batch - since otherwise they would * We only take multiline comments which aren't part of a batch - since otherwise they would
* break up the T-SQL in separate code cells and since we currently don't share state between * break up the T-SQL in separate code cells and since we currently don't share state between
* cells that could break the script * cells that could break the script
*/ */
var multilineComments = tokens var multilineComments = tokens
@@ -252,7 +245,7 @@ namespace Microsoft.SqlTools.ServiceLayer.NotebookConvert
/// <summary> /// <summary>
/// Converts a Notebook document into a single string that can be inserted into a SQL /// Converts a Notebook document into a single string that can be inserted into a SQL
/// query. /// query.
/// </summary> /// </summary>
private static string ConvertNotebookDocToSql(NotebookDocument doc) private static string ConvertNotebookDocToSql(NotebookDocument doc)
{ {

View File

@@ -171,7 +171,7 @@ namespace Microsoft.SqlTools.ServiceLayer.ObjectExplorer
{ {
Validate.IsNotNull(nameof(connectionDetails), connectionDetails); Validate.IsNotNull(nameof(connectionDetails), connectionDetails);
Validate.IsNotNull(nameof(context), context); Validate.IsNotNull(nameof(context), context);
return await Task.Factory.StartNew(() => return await Task.Run(() =>
{ {
string uri = GenerateUri(connectionDetails); string uri = GenerateUri(connectionDetails);
@@ -384,13 +384,11 @@ namespace Microsoft.SqlTools.ServiceLayer.ObjectExplorer
} }
internal async Task<ExpandResponse> ExpandNode(ObjectExplorerSession session, string nodePath, bool forceRefresh = false) internal Task<ExpandResponse> ExpandNode(ObjectExplorerSession session, string nodePath, bool forceRefresh = false)
{ {
return await Task.Factory.StartNew(() => return Task.Run(() => QueueExpandNodeRequest(session, nodePath, forceRefresh));
{
return QueueExpandNodeRequest(session, nodePath, forceRefresh);
});
} }
internal ExpandResponse QueueExpandNodeRequest(ObjectExplorerSession session, string nodePath, bool forceRefresh = false) internal ExpandResponse QueueExpandNodeRequest(ObjectExplorerSession session, string nodePath, bool forceRefresh = false)
{ {
NodeInfo[] nodes = null; NodeInfo[] nodes = null;
@@ -522,7 +520,7 @@ namespace Microsoft.SqlTools.ServiceLayer.ObjectExplorer
await SendSessionFailedNotification(uri, ex.Message); await SendSessionFailedNotification(uri, ex.Message);
return null; return null;
} }
} }
private async Task<ConnectionCompleteParams> Connect(ConnectParams connectParams, string uri) private async Task<ConnectionCompleteParams> Connect(ConnectParams connectParams, string uri)
{ {
@@ -541,7 +539,7 @@ namespace Microsoft.SqlTools.ServiceLayer.ObjectExplorer
await SendSessionFailedNotification(uri, result.ErrorMessage); await SendSessionFailedNotification(uri, result.ErrorMessage);
return null; return null;
} }
} }
catch (Exception ex) catch (Exception ex)
{ {
@@ -581,7 +579,7 @@ namespace Microsoft.SqlTools.ServiceLayer.ObjectExplorer
ExpandTask = task; ExpandTask = task;
Task.Run(async () => Task.Run(async () =>
{ {
ObjectExplorerTaskResult result = await RunTaskWithTimeout(task, ObjectExplorerTaskResult result = await RunTaskWithTimeout(task,
settings?.ExpandTimeout ?? ObjectExplorerSettings.DefaultExpandTimeout); settings?.ExpandTimeout ?? ObjectExplorerSettings.DefaultExpandTimeout);
if (result != null && !result.IsCompleted) if (result != null && !result.IsCompleted)
@@ -650,7 +648,7 @@ namespace Microsoft.SqlTools.ServiceLayer.ObjectExplorer
internal static string GenerateUri(ConnectionDetails details) internal static string GenerateUri(ConnectionDetails details)
{ {
return ConnectedBindingQueue.GetConnectionContextKey(details); return ConnectedBindingQueue.GetConnectionContextKey(details);
} }
public IEnumerable<ChildFactory> GetApplicableChildFactories(TreeNode item) public IEnumerable<ChildFactory> GetApplicableChildFactories(TreeNode item)
{ {
@@ -751,7 +749,7 @@ namespace Microsoft.SqlTools.ServiceLayer.ObjectExplorer
{ {
bindingQueue.OnUnhandledException -= OnUnhandledException; bindingQueue.OnUnhandledException -= OnUnhandledException;
bindingQueue.Dispose(); bindingQueue.Dispose();
} }
} }
private async void OnUnhandledException(string queueKey, Exception ex) private async void OnUnhandledException(string queueKey, Exception ex)
@@ -819,7 +817,7 @@ namespace Microsoft.SqlTools.ServiceLayer.ObjectExplorer
return session; return session;
} }
} }
} }

View File

@@ -115,59 +115,56 @@ namespace Microsoft.SqlTools.ServiceLayer.Profiler
/// </summary> /// </summary>
internal async Task HandleCreateXEventSessionRequest(CreateXEventSessionParams parameters, RequestContext<CreateXEventSessionResult> requestContext) internal async Task HandleCreateXEventSessionRequest(CreateXEventSessionParams parameters, RequestContext<CreateXEventSessionResult> requestContext)
{ {
await Task.Run(async () => try
{ {
try ConnectionInfo connInfo;
ConnectionServiceInstance.TryFindConnection(
parameters.OwnerUri,
out connInfo);
if (connInfo == null)
{ {
ConnectionInfo connInfo; throw new Exception(SR.ProfilerConnectionNotFound);
ConnectionServiceInstance.TryFindConnection(
parameters.OwnerUri,
out connInfo);
if (connInfo == null)
{
throw new Exception(SR.ProfilerConnectionNotFound);
}
else if (parameters.SessionName == null)
{
throw new ArgumentNullException("SessionName");
}
else if (parameters.Template == null)
{
throw new ArgumentNullException("Template");
}
else
{
IXEventSession xeSession = null;
// first check whether the session with the given name already exists.
// if so skip the creation part. An exception will be thrown if no session with given name can be found,
// and it can be ignored.
try
{
xeSession = this.XEventSessionFactory.GetXEventSession(parameters.SessionName, connInfo);
}
catch { }
if (xeSession == null)
{
// create a new XEvent session and Profiler session
xeSession = this.XEventSessionFactory.CreateXEventSession(parameters.Template.CreateStatement, parameters.SessionName, connInfo);
}
// start monitoring the profiler session
monitor.StartMonitoringSession(parameters.OwnerUri, xeSession);
var result = new CreateXEventSessionResult();
await requestContext.SendResult(result);
SessionCreatedNotification(parameters.OwnerUri, parameters.SessionName, parameters.Template.Name);
}
} }
catch (Exception e) else if (parameters.SessionName == null)
{ {
await requestContext.SendError(new Exception(SR.CreateSessionFailed(e.Message))); throw new ArgumentNullException("SessionName");
} }
}); else if (parameters.Template == null)
{
throw new ArgumentNullException("Template");
}
else
{
IXEventSession xeSession = null;
// first check whether the session with the given name already exists.
// if so skip the creation part. An exception will be thrown if no session with given name can be found,
// and it can be ignored.
try
{
xeSession = this.XEventSessionFactory.GetXEventSession(parameters.SessionName, connInfo);
}
catch { }
if (xeSession == null)
{
// create a new XEvent session and Profiler session
xeSession = this.XEventSessionFactory.CreateXEventSession(parameters.Template.CreateStatement, parameters.SessionName, connInfo);
}
// start monitoring the profiler session
monitor.StartMonitoringSession(parameters.OwnerUri, xeSession);
var result = new CreateXEventSessionResult();
await requestContext.SendResult(result);
SessionCreatedNotification(parameters.OwnerUri, parameters.SessionName, parameters.Template.Name);
}
}
catch (Exception e)
{
await requestContext.SendError(new Exception(SR.CreateSessionFailed(e.Message)));
}
} }
/// <summary> /// <summary>
@@ -175,34 +172,31 @@ namespace Microsoft.SqlTools.ServiceLayer.Profiler
/// </summary> /// </summary>
internal async Task HandleStartProfilingRequest(StartProfilingParams parameters, RequestContext<StartProfilingResult> requestContext) internal async Task HandleStartProfilingRequest(StartProfilingParams parameters, RequestContext<StartProfilingResult> requestContext)
{ {
await Task.Run(async () => try
{ {
try ConnectionInfo connInfo;
ConnectionServiceInstance.TryFindConnection(
parameters.OwnerUri,
out connInfo);
if (connInfo != null)
{ {
ConnectionInfo connInfo; // create a new XEvent session and Profiler session
ConnectionServiceInstance.TryFindConnection( var xeSession = this.XEventSessionFactory.GetXEventSession(parameters.SessionName, connInfo);
parameters.OwnerUri, // start monitoring the profiler session
out connInfo); monitor.StartMonitoringSession(parameters.OwnerUri, xeSession);
if (connInfo != null)
{
// create a new XEvent session and Profiler session
var xeSession = this.XEventSessionFactory.GetXEventSession(parameters.SessionName, connInfo);
// start monitoring the profiler session
monitor.StartMonitoringSession(parameters.OwnerUri, xeSession);
var result = new StartProfilingResult(); var result = new StartProfilingResult();
await requestContext.SendResult(result); await requestContext.SendResult(result);
}
else
{
throw new Exception(SR.ProfilerConnectionNotFound);
}
} }
catch (Exception e) else
{ {
await requestContext.SendError(new Exception(SR.StartSessionFailed(e.Message))); throw new Exception(SR.ProfilerConnectionNotFound);
} }
}); }
catch (Exception e)
{
await requestContext.SendError(new Exception(SR.StartSessionFailed(e.Message)));
}
} }
/// <summary> /// <summary>
@@ -210,47 +204,44 @@ namespace Microsoft.SqlTools.ServiceLayer.Profiler
/// </summary> /// </summary>
internal async Task HandleStopProfilingRequest(StopProfilingParams parameters, RequestContext<StopProfilingResult> requestContext) internal async Task HandleStopProfilingRequest(StopProfilingParams parameters, RequestContext<StopProfilingResult> requestContext)
{ {
await Task.Run(async () => try
{ {
try ProfilerSession session;
{ monitor.StopMonitoringSession(parameters.OwnerUri, out session);
ProfilerSession session;
monitor.StopMonitoringSession(parameters.OwnerUri, out session);
if (session != null) if (session != null)
{
// Occasionally we might see the InvalidOperationException due to a read is
// in progress, add the following retry logic will solve the problem.
int remainingAttempts = 3;
while (true)
{ {
// Occasionally we might see the InvalidOperationException due to a read is try
// in progress, add the following retry logic will solve the problem.
int remainingAttempts = 3;
while (true)
{ {
try session.XEventSession.Stop();
await requestContext.SendResult(new StopProfilingResult { });
break;
}
catch (InvalidOperationException)
{
remainingAttempts--;
if (remainingAttempts == 0)
{ {
session.XEventSession.Stop(); throw;
await requestContext.SendResult(new StopProfilingResult { });
break;
}
catch (InvalidOperationException)
{
remainingAttempts--;
if (remainingAttempts == 0)
{
throw;
}
Thread.Sleep(500);
} }
Thread.Sleep(500);
} }
} }
else
{
throw new Exception(SR.SessionNotFound);
}
} }
catch (Exception e) else
{ {
await requestContext.SendError(new Exception(SR.StopSessionFailed(e.Message))); throw new Exception(SR.SessionNotFound);
} }
}); }
catch (Exception e)
{
await requestContext.SendError(new Exception(SR.StopSessionFailed(e.Message)));
}
} }
/// <summary> /// <summary>
@@ -258,19 +249,16 @@ namespace Microsoft.SqlTools.ServiceLayer.Profiler
/// </summary> /// </summary>
internal async Task HandlePauseProfilingRequest(PauseProfilingParams parameters, RequestContext<PauseProfilingResult> requestContext) internal async Task HandlePauseProfilingRequest(PauseProfilingParams parameters, RequestContext<PauseProfilingResult> requestContext)
{ {
await Task.Run(async () => try
{ {
try monitor.PauseViewer(parameters.OwnerUri);
{
monitor.PauseViewer(parameters.OwnerUri);
await requestContext.SendResult(new PauseProfilingResult { }); await requestContext.SendResult(new PauseProfilingResult { });
} }
catch (Exception e) catch (Exception e)
{ {
await requestContext.SendError(new Exception(SR.PauseSessionFailed(e.Message))); await requestContext.SendError(new Exception(SR.PauseSessionFailed(e.Message)));
} }
});
} }
/// <summary> /// <summary>
@@ -278,31 +266,28 @@ namespace Microsoft.SqlTools.ServiceLayer.Profiler
/// </summary> /// </summary>
internal async Task HandleGetXEventSessionsRequest(GetXEventSessionsParams parameters, RequestContext<GetXEventSessionsResult> requestContext) internal async Task HandleGetXEventSessionsRequest(GetXEventSessionsParams parameters, RequestContext<GetXEventSessionsResult> requestContext)
{ {
await Task.Run(async () => try
{ {
try var result = new GetXEventSessionsResult();
ConnectionInfo connInfo;
ConnectionServiceInstance.TryFindConnection(
parameters.OwnerUri,
out connInfo);
if (connInfo == null)
{ {
var result = new GetXEventSessionsResult(); await requestContext.SendError(new Exception(SR.ProfilerConnectionNotFound));
ConnectionInfo connInfo;
ConnectionServiceInstance.TryFindConnection(
parameters.OwnerUri,
out connInfo);
if (connInfo == null)
{
await requestContext.SendError(new Exception(SR.ProfilerConnectionNotFound));
}
else
{
List<string> sessions = GetXEventSessionList(parameters.OwnerUri, connInfo);
result.Sessions = sessions;
await requestContext.SendResult(result);
}
} }
catch (Exception e) else
{ {
await requestContext.SendError(e); List<string> sessions = GetXEventSessionList(parameters.OwnerUri, connInfo);
result.Sessions = sessions;
await requestContext.SendResult(result);
} }
}); }
catch (Exception e)
{
await requestContext.SendError(e);
}
} }
/// <summary> /// <summary>
@@ -310,18 +295,14 @@ namespace Microsoft.SqlTools.ServiceLayer.Profiler
/// </summary> /// </summary>
internal async Task HandleDisconnectSessionRequest(DisconnectSessionParams parameters, RequestContext<DisconnectSessionResult> requestContext) internal async Task HandleDisconnectSessionRequest(DisconnectSessionParams parameters, RequestContext<DisconnectSessionResult> requestContext)
{ {
await Task.Run(async () => try
{ {
try monitor.StopMonitoringSession(parameters.OwnerUri, out _);
{ }
ProfilerSession session; catch (Exception e)
monitor.StopMonitoringSession(parameters.OwnerUri, out session); {
} await requestContext.SendError(e);
catch (Exception e) }
{
await requestContext.SendError(e);
}
});
} }
/// <summary> /// <summary>

View File

@@ -707,7 +707,7 @@ namespace Microsoft.SqlTools.ServiceLayer.QueryExecution
/// <param name="scriptFile"></param> /// <param name="scriptFile"></param>
/// <param name="eventContext"></param> /// <param name="eventContext"></param>
/// <returns></returns> /// <returns></returns>
public async Task HandleDidCloseTextDocumentNotification( public Task HandleDidCloseTextDocumentNotification(
string uri, string uri,
ScriptFile scriptFile, ScriptFile scriptFile,
EventContext eventContext) EventContext eventContext)
@@ -725,7 +725,8 @@ namespace Microsoft.SqlTools.ServiceLayer.QueryExecution
{ {
Logger.Write(TraceEventType.Error, "Unknown error " + ex.ToString()); Logger.Write(TraceEventType.Error, "Unknown error " + ex.ToString());
} }
await Task.FromResult(true);
return Task.CompletedTask;
} }
#endregion #endregion
@@ -765,7 +766,7 @@ namespace Microsoft.SqlTools.ServiceLayer.QueryExecution
if (this.ActiveQueryExecutionSettings.TryGetValue(executeParams.OwnerUri, out settings)) if (this.ActiveQueryExecutionSettings.TryGetValue(executeParams.OwnerUri, out settings))
{ {
// special-case handling for query plan options to maintain compat with query execution API parameters // special-case handling for query plan options to maintain compat with query execution API parameters
// the logic is that if either the query execute API parameters or the active query setttings // the logic is that if either the query execute API parameters or the active query setttings
// request a plan then enable the query option // request a plan then enable the query option
ExecutionPlanOptions executionPlanOptions = executeParams.ExecutionPlanOptions; ExecutionPlanOptions executionPlanOptions = executeParams.ExecutionPlanOptions;
if (settings.IncludeActualExecutionPlanXml) if (settings.IncludeActualExecutionPlanXml)
@@ -900,7 +901,7 @@ namespace Microsoft.SqlTools.ServiceLayer.QueryExecution
// Setup the ResultSet updated callback // Setup the ResultSet updated callback
ResultSet.ResultSetAsyncEventHandler resultUpdatedCallback = async r => ResultSet.ResultSetAsyncEventHandler resultUpdatedCallback = async r =>
{ {
//Generating and sending an execution plan graphs if it is requested. //Generating and sending an execution plan graphs if it is requested.
List<ExecutionPlanGraph> plans = null; List<ExecutionPlanGraph> plans = null;
string planErrors = ""; string planErrors = "";

View File

@@ -88,7 +88,7 @@ namespace Microsoft.SqlTools.ServiceLayer.Security
/// Handle request to create a credential /// Handle request to create a credential
/// </summary> /// </summary>
internal async Task HandleCreateCredentialRequest(CreateCredentialParams parameters, RequestContext<CredentialResult> requestContext) internal async Task HandleCreateCredentialRequest(CreateCredentialParams parameters, RequestContext<CredentialResult> requestContext)
{ {
var result = await ConfigureCredential(parameters.OwnerUri, var result = await ConfigureCredential(parameters.OwnerUri,
parameters.Credential, parameters.Credential,
ConfigAction.Create, ConfigAction.Create,
@@ -106,7 +106,7 @@ namespace Microsoft.SqlTools.ServiceLayer.Security
/// Handle request to update a credential /// Handle request to update a credential
/// </summary> /// </summary>
internal async Task HandleUpdateCredentialRequest(UpdateCredentialParams parameters, RequestContext<CredentialResult> requestContext) internal async Task HandleUpdateCredentialRequest(UpdateCredentialParams parameters, RequestContext<CredentialResult> requestContext)
{ {
var result = await ConfigureCredential(parameters.OwnerUri, var result = await ConfigureCredential(parameters.OwnerUri,
parameters.Credential, parameters.Credential,
ConfigAction.Update, ConfigAction.Update,
@@ -137,69 +137,64 @@ namespace Microsoft.SqlTools.ServiceLayer.Security
}); });
} }
/// <summary> /// <summary>
/// Handle request to get all credentials /// Handle request to get all credentials
/// </summary> /// </summary>
internal async Task HandleGetCredentialsRequest(GetCredentialsParams parameters, RequestContext<GetCredentialsResult> requestContext) internal async Task HandleGetCredentialsRequest(GetCredentialsParams parameters, RequestContext<GetCredentialsResult> requestContext)
{ {
await Task.Run(async () => var result = new GetCredentialsResult();
try
{ {
var result = new GetCredentialsResult(); ConnectionInfo connInfo;
try ConnectionServiceInstance.TryFindConnection(parameters.OwnerUri, out connInfo);
{ CDataContainer dataContainer = CDataContainer.CreateDataContainer(connInfo, databaseExists: true);
ConnectionInfo connInfo;
ConnectionServiceInstance.TryFindConnection(parameters.OwnerUri, out connInfo);
CDataContainer dataContainer = CDataContainer.CreateDataContainer(connInfo, databaseExists: true);
var credentials = dataContainer.Server.Credentials;
int credentialsCount = credentials.Count;
CredentialInfo[] credentialsInfos = new CredentialInfo[credentialsCount];
for (int i = 0; i < credentialsCount; ++i)
{
credentialsInfos[i] = new CredentialInfo();
credentialsInfos[i].Name = credentials[i].Name;
credentialsInfos[i].Identity = credentials[i].Identity;
credentialsInfos[i].Id = credentials[i].ID;
credentialsInfos[i].DateLastModified = credentials[i].DateLastModified;
credentialsInfos[i].CreateDate = credentials[i].CreateDate;
credentialsInfos[i].ProviderName = credentials[i].ProviderName;
}
result.Credentials = credentialsInfos;
result.Success = true;
}
catch (Exception ex)
{
result.Success = false;
result.ErrorMessage = ex.ToString();
}
await requestContext.SendResult(result); var credentials = dataContainer.Server.Credentials;
}); int credentialsCount = credentials.Count;
CredentialInfo[] credentialsInfos = new CredentialInfo[credentialsCount];
for (int i = 0; i < credentialsCount; ++i)
{
credentialsInfos[i] = new CredentialInfo();
credentialsInfos[i].Name = credentials[i].Name;
credentialsInfos[i].Identity = credentials[i].Identity;
credentialsInfos[i].Id = credentials[i].ID;
credentialsInfos[i].DateLastModified = credentials[i].DateLastModified;
credentialsInfos[i].CreateDate = credentials[i].CreateDate;
credentialsInfos[i].ProviderName = credentials[i].ProviderName;
}
result.Credentials = credentialsInfos;
result.Success = true;
}
catch (Exception ex)
{
result.Success = false;
result.ErrorMessage = ex.ToString();
}
await requestContext.SendResult(result);
} }
/// <summary> /// <summary>
/// Disposes the service /// Disposes the service
/// </summary> /// </summary>
public void Dispose() public void Dispose()
{ {
if (!disposed) if (!disposed)
{ {
disposed = true; disposed = true;
} }
} }
#region "Helpers" #region "Helpers"
internal async Task<Tuple<bool, string>> ConfigureCredential( internal Task<Tuple<bool, string>> ConfigureCredential(
string ownerUri, string ownerUri,
CredentialInfo credential, CredentialInfo credential,
ConfigAction configAction, ConfigAction configAction,
RunType runType) RunType runType)
{ {
return await Task<Tuple<bool, string>>.Run(() => return Task<Tuple<bool, string>>.Run(() =>
{ {
try try
{ {
@@ -211,7 +206,7 @@ namespace Microsoft.SqlTools.ServiceLayer.Security
{ {
var executionHandler = new ExecutonHandler(actions); var executionHandler = new ExecutonHandler(actions);
executionHandler.RunNow(runType, this); executionHandler.RunNow(runType, this);
} }
return new Tuple<bool, string>(true, string.Empty); return new Tuple<bool, string>(true, string.Empty);
} }

View File

@@ -18,7 +18,7 @@ namespace Microsoft.SqlTools.ServiceLayer.TaskServices
/// </summary> /// </summary>
/// <param name="sqlTask">Sql Task</param> /// <param name="sqlTask">Sql Task</param>
/// <returns>Task Result</returns> /// <returns>Task Result</returns>
public static async Task<TaskResult> ExecuteTaskAsync(SqlTask sqlTask) public static Task<TaskResult> ExecuteTaskAsync(SqlTask sqlTask)
{ {
sqlTask.AddMessage(SR.TaskInProgress, SqlTaskStatus.InProgress, true); sqlTask.AddMessage(SR.TaskInProgress, SqlTaskStatus.InProgress, true);
ITaskOperation taskOperation = sqlTask.TaskMetadata.TaskOperation as ITaskOperation; ITaskOperation taskOperation = sqlTask.TaskMetadata.TaskOperation as ITaskOperation;
@@ -27,8 +27,8 @@ namespace Microsoft.SqlTools.ServiceLayer.TaskServices
if (taskOperation != null) if (taskOperation != null)
{ {
taskOperation.SqlTask = sqlTask; taskOperation.SqlTask = sqlTask;
return await Task.Factory.StartNew(() => return Task.Run(() =>
{ {
TaskResult result = new TaskResult(); TaskResult result = new TaskResult();
try try
@@ -66,21 +66,21 @@ namespace Microsoft.SqlTools.ServiceLayer.TaskServices
taskResult.TaskStatus = SqlTaskStatus.Failed; taskResult.TaskStatus = SqlTaskStatus.Failed;
} }
return taskResult; return Task.FromResult(taskResult);
} }
/// <summary> /// <summary>
/// Async method to cancel the operations /// Async method to cancel the operations
/// </summary> /// </summary>
public static async Task<TaskResult> CancelTaskAsync(SqlTask sqlTask) public static Task<TaskResult> CancelTaskAsync(SqlTask sqlTask)
{ {
ITaskOperation taskOperation = sqlTask.TaskMetadata.TaskOperation as ITaskOperation; ITaskOperation taskOperation = sqlTask.TaskMetadata.TaskOperation as ITaskOperation;
TaskResult taskResult = null; TaskResult taskResult = null;
if (taskOperation != null) if (taskOperation != null)
{ {
return await Task.Factory.StartNew(() => return Task.Run(() =>
{ {
try try
{ {
@@ -107,7 +107,7 @@ namespace Microsoft.SqlTools.ServiceLayer.TaskServices
taskResult.TaskStatus = SqlTaskStatus.Failed; taskResult.TaskStatus = SqlTaskStatus.Failed;
} }
return taskResult; return Task.FromResult(taskResult);
} }
} }
} }

View File

@@ -116,7 +116,7 @@ namespace Microsoft.SqlTools.ServiceLayer.Workspace
/// List of callbacks to call when a text document is closed /// List of callbacks to call when a text document is closed
/// </summary> /// </summary>
private List<TextDocCloseCallback> TextDocCloseCallbacks { get; set; } private List<TextDocCloseCallback> TextDocCloseCallbacks { get; set; }
#endregion #endregion
@@ -132,9 +132,9 @@ namespace Microsoft.SqlTools.ServiceLayer.Workspace
serviceHost.SetEventHandler(DidOpenTextDocumentNotification.Type, HandleDidOpenTextDocumentNotification); serviceHost.SetEventHandler(DidOpenTextDocumentNotification.Type, HandleDidOpenTextDocumentNotification);
serviceHost.SetEventHandler(DidCloseTextDocumentNotification.Type, HandleDidCloseTextDocumentNotification); serviceHost.SetEventHandler(DidCloseTextDocumentNotification.Type, HandleDidCloseTextDocumentNotification);
serviceHost.SetEventHandler(DidChangeConfigurationNotification<TConfig>.Type, HandleDidChangeConfigurationNotification); serviceHost.SetEventHandler(DidChangeConfigurationNotification<TConfig>.Type, HandleDidChangeConfigurationNotification);
// Register an initialization handler that sets the workspace path // Register an initialization handler that sets the workspace path
serviceHost.RegisterInitializeTask(async (parameters, contect) => serviceHost.RegisterInitializeTask((parameters, contect) =>
{ {
Logger.Write(TraceEventType.Verbose, "Initializing workspace service"); Logger.Write(TraceEventType.Verbose, "Initializing workspace service");
@@ -142,11 +142,12 @@ namespace Microsoft.SqlTools.ServiceLayer.Workspace
{ {
Workspace.WorkspacePath = parameters.RootPath; Workspace.WorkspacePath = parameters.RootPath;
} }
await Task.FromResult(0);
return Task.CompletedTask;
}); });
// Register a shutdown request that disposes the workspace // Register a shutdown request that disposes the workspace
serviceHost.RegisterShutdownTask(async (parameters, context) => serviceHost.RegisterShutdownTask((parameters, context) =>
{ {
Logger.Write(TraceEventType.Verbose, "Shutting down workspace service"); Logger.Write(TraceEventType.Verbose, "Shutting down workspace service");
@@ -155,7 +156,8 @@ namespace Microsoft.SqlTools.ServiceLayer.Workspace
Workspace.Dispose(); Workspace.Dispose();
Workspace = null; Workspace = null;
} }
await Task.FromResult(0);
return Task.CompletedTask;
}); });
} }
@@ -216,7 +218,7 @@ namespace Microsoft.SqlTools.ServiceLayer.Workspace
// A text change notification can batch multiple change requests // A text change notification can batch multiple change requests
foreach (var textChange in textChangeParams.ContentChanges) foreach (var textChange in textChangeParams.ContentChanges)
{ {
string fileUri = textChangeParams.TextDocument.Uri ?? textChangeParams.TextDocument.Uri; string fileUri = textChangeParams.TextDocument.Uri ?? textChangeParams.TextDocument.Uri;
msg.AppendLine(string.Format(" File: {0}", fileUri)); msg.AppendLine(string.Format(" File: {0}", fileUri));
ScriptFile changedFile = Workspace.GetFile(fileUri); ScriptFile changedFile = Workspace.GetFile(fileUri);
@@ -258,7 +260,7 @@ namespace Microsoft.SqlTools.ServiceLayer.Workspace
return; return;
} }
// read the SQL file contents into the ScriptFile // read the SQL file contents into the ScriptFile
ScriptFile openedFile = Workspace.GetFileBuffer(openParams.TextDocument.Uri, openParams.TextDocument.Text); ScriptFile openedFile = Workspace.GetFileBuffer(openParams.TextDocument.Uri, openParams.TextDocument.Text);
if (openedFile == null) if (openedFile == null)
{ {
@@ -287,7 +289,7 @@ namespace Microsoft.SqlTools.ServiceLayer.Workspace
{ {
Logger.Write(TraceEventType.Verbose, "HandleDidCloseTextDocumentNotification"); Logger.Write(TraceEventType.Verbose, "HandleDidCloseTextDocumentNotification");
if (IsScmEvent(closeParams.TextDocument.Uri)) if (IsScmEvent(closeParams.TextDocument.Uri))
{ {
return; return;
} }
@@ -338,7 +340,7 @@ namespace Microsoft.SqlTools.ServiceLayer.Workspace
// TODO: this probably means the ScriptFile model is in a bad state or out of sync with the actual file; we should recover here // TODO: this probably means the ScriptFile model is in a bad state or out of sync with the actual file; we should recover here
return; return;
} }
} }
#endregion #endregion
@@ -348,7 +350,7 @@ namespace Microsoft.SqlTools.ServiceLayer.Workspace
/// Switch from 0-based offsets to 1 based offsets /// Switch from 0-based offsets to 1 based offsets
/// </summary> /// </summary>
/// <param name="changeRange"></param> /// <param name="changeRange"></param>
/// <param name="insertString"></param> /// <param name="insertString"></param>
private static FileChange GetFileChangeDetails(Range changeRange, string insertString) private static FileChange GetFileChangeDetails(Range changeRange, string insertString)
{ {
// The protocol's positions are zero-based so add 1 to all offsets // The protocol's positions are zero-based so add 1 to all offsets
@@ -361,7 +363,7 @@ namespace Microsoft.SqlTools.ServiceLayer.Workspace
EndOffset = changeRange.End.Character + 1 EndOffset = changeRange.End.Character + 1
}; };
} }
internal static bool IsScmEvent(string filePath) internal static bool IsScmEvent(string filePath)
{ {
// if the URI is prefixed with git: then we want to skip processing that file // if the URI is prefixed with git: then we want to skip processing that file