diff --git a/src/Microsoft.InsightsGenerator/Workflow.cs b/src/Microsoft.InsightsGenerator/Workflow.cs index 714c4e01..73d94456 100644 --- a/src/Microsoft.InsightsGenerator/Workflow.cs +++ b/src/Microsoft.InsightsGenerator/Workflow.cs @@ -12,7 +12,7 @@ namespace Microsoft.InsightsGenerator public class Workflow { - public async Task ProcessInputData(DataArray rulesData, + public Task ProcessInputData(DataArray rulesData, CancellationToken cancellationToken = new CancellationToken()) { // added cancellationToken just in case for future @@ -21,9 +21,7 @@ namespace Microsoft.InsightsGenerator //Get the signature result SignatureGenerator siggen = new SignatureGenerator(rulesData); - string insights = null; - - await Task.Run(() => + return Task.Run(() => { try { @@ -31,6 +29,8 @@ namespace Microsoft.InsightsGenerator transformer.Transform(rulesData); SignatureGeneratorResult result = siggen.Learn(); // call the rules engine processor + + string insights = null; if (result?.Insights == null) { // 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"); } + return insights; } catch (Exception) { @@ -50,8 +51,6 @@ namespace Microsoft.InsightsGenerator } }, cancellationToken); - - return insights; } } } diff --git a/src/Microsoft.SqlTools.Credentials/Credentials/CredentialService.cs b/src/Microsoft.SqlTools.Credentials/Credentials/CredentialService.cs index 90c3155d..821179b4 100644 --- a/src/Microsoft.SqlTools.Credentials/Credentials/CredentialService.cs +++ b/src/Microsoft.SqlTools.Credentials/Credentials/CredentialService.cs @@ -24,7 +24,7 @@ namespace Microsoft.SqlTools.Credentials { internal static string DefaultSecretsFolder = ".sqlsecrets"; internal const string DefaultSecretsFile = "sqlsecrets.json"; - + /// /// Singleton service instance @@ -49,11 +49,11 @@ namespace Microsoft.SqlTools.Credentials /// Default constructor is private since it's a singleton class /// private CredentialService() - : this(null, new StoreConfig() + : this(null, new StoreConfig() { CredentialFolder = DefaultSecretsFolder, CredentialFile = DefaultSecretsFile, IsRelativeToUserHomeDir = true}) { } - + /// /// Internal for testing purposes only /// @@ -102,12 +102,9 @@ namespace Microsoft.SqlTools.Credentials } - public async Task ReadCredentialAsync(Credential credential) + public Task ReadCredentialAsync(Credential credential) { - return await Task.Factory.StartNew(() => - { - return ReadCredential(credential); - }); + return Task.Run(() => ReadCredential(credential)); } public Credential ReadCredential(Credential credential) @@ -132,12 +129,9 @@ namespace Microsoft.SqlTools.Credentials await HandleRequest(doSave, requestContext, "HandleSaveCredentialRequest"); } - public async Task SaveCredentialAsync(Credential credential) + public Task SaveCredentialAsync(Credential credential) { - return await Task.Factory.StartNew(() => - { - return SaveCredential(credential); - }); + return Task.Run(() => SaveCredential(credential)); } public bool SaveCredential(Credential credential) @@ -155,9 +149,9 @@ namespace Microsoft.SqlTools.Credentials await HandleRequest(doDelete, requestContext, "HandleDeleteCredentialRequest"); } - private async Task DeletePasswordAsync(Credential credential) + private Task DeletePasswordAsync(Credential credential) { - return await Task.Factory.StartNew(() => + return Task.Run(() => { Credential.ValidateForLookup(credential); return credStore.DeletePassword(credential.CredentialId); diff --git a/src/Microsoft.SqlTools.ServiceLayer/Agent/AgentService.cs b/src/Microsoft.SqlTools.ServiceLayer/Agent/AgentService.cs index a93efac8..a3313103 100644 --- a/src/Microsoft.SqlTools.ServiceLayer/Agent/AgentService.cs +++ b/src/Microsoft.SqlTools.ServiceLayer/Agent/AgentService.cs @@ -133,10 +133,10 @@ namespace Microsoft.SqlTools.ServiceLayer.Agent this.ServiceHost.SetRequestHandler(UpdateAgentNotebookRunNameRequest.Type, HandleUpdateAgentNotebookRunNameRequest); this.ServiceHost.SetRequestHandler(DeleteNotebookMaterializedRequest.Type, HandleDeleteNotebookMaterializedRequest); - serviceHost.RegisterShutdownTask(async (shutdownParams, shutdownRequestContext) => + serviceHost.RegisterShutdownTask((_, _) => { DeleteAgentNotebooksTempFiles(); - await Task.FromResult(0); + return Task.FromResult(0); }); } @@ -148,41 +148,38 @@ namespace Microsoft.SqlTools.ServiceLayer.Agent /// internal async Task HandleAgentJobsRequest(AgentJobsParams parameters, RequestContext requestContext) { - await Task.Run(async () => + try { - try - { - var result = new AgentJobsResult(); - ConnectionInfo connInfo; - ConnectionServiceInstance.TryFindConnection( - parameters.OwnerUri, - out connInfo); + var result = new AgentJobsResult(); + ConnectionInfo connInfo; + ConnectionServiceInstance.TryFindConnection( + parameters.OwnerUri, + out connInfo); - if (connInfo != null) - { - var serverConnection = ConnectionService.OpenServerConnection(connInfo); - var fetcher = new JobFetcher(serverConnection); - var filter = new JobActivityFilter(); - var jobs = fetcher.FetchJobs(filter); - var agentJobs = new List(); - if (jobs != null) - { - foreach (var job in jobs.Values) - { - agentJobs.Add(AgentUtilities.ConvertToAgentJobInfo(job)); - } - } - result.Success = true; - result.Jobs = agentJobs.ToArray(); - serverConnection.SqlConnectionObject.Close(); - } - await requestContext.SendResult(result); - } - catch (Exception e) + if (connInfo != null) { - await requestContext.SendError(e); + var serverConnection = ConnectionService.OpenServerConnection(connInfo); + var fetcher = new JobFetcher(serverConnection); + var filter = new JobActivityFilter(); + var jobs = fetcher.FetchJobs(filter); + var agentJobs = new List(); + if (jobs != null) + { + foreach (var job in jobs.Values) + { + agentJobs.Add(AgentUtilities.ConvertToAgentJobInfo(job)); + } + } + result.Success = true; + result.Jobs = agentJobs.ToArray(); + serverConnection.SqlConnectionObject.Close(); } - }); + await requestContext.SendResult(result); + } + catch (Exception e) + { + await requestContext.SendError(e); + } } /// @@ -190,83 +187,80 @@ namespace Microsoft.SqlTools.ServiceLayer.Agent /// internal async Task HandleJobHistoryRequest(AgentJobHistoryParams parameters, RequestContext requestContext) { - await Task.Run(async () => + try { - try + var result = new AgentJobHistoryResult(); + ConnectionInfo connInfo; + ConnectionServiceInstance.TryFindConnection( + parameters.OwnerUri, + out connInfo); + if (connInfo != null) { - var result = new AgentJobHistoryResult(); - ConnectionInfo connInfo; - ConnectionServiceInstance.TryFindConnection( - parameters.OwnerUri, - out connInfo); - if (connInfo != null) + CDataContainer dataContainer = CDataContainer.CreateDataContainer(connInfo, databaseExists: true); + var jobServer = dataContainer.Server.JobServer; + var jobs = jobServer.Jobs; + Tuple tuple = CreateSqlConnection(connInfo, parameters.JobId); + SqlConnectionInfo sqlConnInfo = tuple.Item1; + DataTable dt = tuple.Item2; + ServerConnection connection = tuple.Item3; + + // Send Steps, Alerts and Schedules with job history in background + // Add steps to the job if any + JobStepCollection steps = jobs[parameters.JobName].JobSteps; + var jobSteps = new List(); + foreach (JobStep step in steps) { - CDataContainer dataContainer = CDataContainer.CreateDataContainer(connInfo, databaseExists: true); - var jobServer = dataContainer.Server.JobServer; - var jobs = jobServer.Jobs; - Tuple tuple = CreateSqlConnection(connInfo, parameters.JobId); - SqlConnectionInfo sqlConnInfo = tuple.Item1; - DataTable dt = tuple.Item2; - ServerConnection connection = tuple.Item3; - - // Send Steps, Alerts and Schedules with job history in background - // Add steps to the job if any - JobStepCollection steps = jobs[parameters.JobName].JobSteps; - var jobSteps = new List(); - foreach (JobStep step in steps) - { - jobSteps.Add(AgentUtilities.ConvertToAgentJobStepInfo(step, parameters.JobId, parameters.JobName)); - } - result.Steps = jobSteps.ToArray(); - - // Add schedules to the job if any - JobScheduleCollection schedules = jobs[parameters.JobName].JobSchedules; - var jobSchedules = new List(); - foreach (JobSchedule schedule in schedules) - { - jobSchedules.Add(AgentUtilities.ConvertToAgentScheduleInfo(schedule)); - } - result.Schedules = jobSchedules.ToArray(); - - // Alerts - AlertCollection alerts = jobServer.Alerts; - var jobAlerts = new List(); - foreach (Alert alert in alerts) - { - if (alert.JobName == parameters.JobName) - { - jobAlerts.Add(alert); - } - } - result.Alerts = AgentUtilities.ConvertToAgentAlertInfo(jobAlerts); - - // Add histories - int count = dt.Rows.Count; - List jobHistories = new List(); - if (count > 0) - { - var job = dt.Rows[0]; - Guid jobId = (Guid)job[AgentUtilities.UrnJobId]; - int runStatus = Convert.ToInt32(job[AgentUtilities.UrnRunStatus], System.Globalization.CultureInfo.InvariantCulture); - var t = new LogSourceJobHistory(parameters.JobName, sqlConnInfo, null, runStatus, jobId, null); - var tlog = t as ILogSource; - tlog.Initialize(); - var logEntries = t.LogEntries; - - // Finally add the job histories - jobHistories = AgentUtilities.ConvertToAgentJobHistoryInfo(logEntries, job, steps); - result.Histories = jobHistories.ToArray(); - result.Success = true; - tlog.CloseReader(); - } - await requestContext.SendResult(result); + jobSteps.Add(AgentUtilities.ConvertToAgentJobStepInfo(step, parameters.JobId, parameters.JobName)); } + result.Steps = jobSteps.ToArray(); + + // Add schedules to the job if any + JobScheduleCollection schedules = jobs[parameters.JobName].JobSchedules; + var jobSchedules = new List(); + foreach (JobSchedule schedule in schedules) + { + jobSchedules.Add(AgentUtilities.ConvertToAgentScheduleInfo(schedule)); + } + result.Schedules = jobSchedules.ToArray(); + + // Alerts + AlertCollection alerts = jobServer.Alerts; + var jobAlerts = new List(); + foreach (Alert alert in alerts) + { + if (alert.JobName == parameters.JobName) + { + jobAlerts.Add(alert); + } + } + result.Alerts = AgentUtilities.ConvertToAgentAlertInfo(jobAlerts); + + // Add histories + int count = dt.Rows.Count; + List jobHistories = new List(); + if (count > 0) + { + var job = dt.Rows[0]; + Guid jobId = (Guid)job[AgentUtilities.UrnJobId]; + int runStatus = Convert.ToInt32(job[AgentUtilities.UrnRunStatus], System.Globalization.CultureInfo.InvariantCulture); + var t = new LogSourceJobHistory(parameters.JobName, sqlConnInfo, null, runStatus, jobId, null); + var tlog = t as ILogSource; + tlog.Initialize(); + var logEntries = t.LogEntries; + + // Finally add the job histories + jobHistories = AgentUtilities.ConvertToAgentJobHistoryInfo(logEntries, job, steps); + result.Histories = jobHistories.ToArray(); + result.Success = true; + tlog.CloseReader(); + } + await requestContext.SendResult(result); } - catch (Exception e) - { - await requestContext.SendError(e); - } - }); + } + catch (Exception e) + { + await requestContext.SendError(e); + } } /// @@ -274,57 +268,54 @@ namespace Microsoft.SqlTools.ServiceLayer.Agent /// internal async Task HandleJobActionRequest(AgentJobActionParams parameters, RequestContext requestContext) { - await Task.Run(async () => + var result = new ResultStatus(); + try { - var result = new ResultStatus(); - try + ConnectionInfo connInfo; + ConnectionServiceInstance.TryFindConnection( + parameters.OwnerUri, + out connInfo); + if (connInfo != null) { - ConnectionInfo connInfo; - ConnectionServiceInstance.TryFindConnection( - parameters.OwnerUri, - out connInfo); - if (connInfo != null) + var serverConnection = ConnectionService.OpenServerConnection(connInfo); + var jobHelper = new JobHelper(serverConnection); + jobHelper.JobName = parameters.JobName; + switch (parameters.Action) { - var serverConnection = ConnectionService.OpenServerConnection(connInfo); - var jobHelper = new JobHelper(serverConnection); - jobHelper.JobName = parameters.JobName; - switch (parameters.Action) - { - case "run": - jobHelper.Start(); - break; - case "stop": - jobHelper.Stop(); - break; - case "delete": - jobHelper.Delete(); - break; - case "enable": - jobHelper.Enable(true); - break; - case "disable": - jobHelper.Enable(false); - break; - default: - break; - } - result.Success = true; - await requestContext.SendResult(result); - } - } - catch (Exception e) - { - result.Success = false; - result.ErrorMessage = e.Message; - Exception exception = e.InnerException; - while (exception != null) - { - result.ErrorMessage += Environment.NewLine + "\t" + exception.Message; - exception = exception.InnerException; + case "run": + jobHelper.Start(); + break; + case "stop": + jobHelper.Stop(); + break; + case "delete": + jobHelper.Delete(); + break; + case "enable": + jobHelper.Enable(true); + break; + case "disable": + jobHelper.Enable(false); + break; + default: + break; } + result.Success = true; await requestContext.SendResult(result); } - }); + } + catch (Exception e) + { + result.Success = false; + result.ErrorMessage = e.Message; + Exception exception = e.InnerException; + while (exception != null) + { + result.ErrorMessage += Environment.NewLine + "\t" + exception.Message; + exception = exception.InnerException; + } + await requestContext.SendResult(result); + } } internal async Task HandleCreateAgentJobRequest(CreateAgentJobParams parameters, RequestContext requestContext) @@ -422,39 +413,36 @@ namespace Microsoft.SqlTools.ServiceLayer.Agent internal async Task HandleAgentJobDefaultsRequest(AgentJobDefaultsParams parameters, RequestContext requestContext) { - await Task.Run(async () => + var result = new AgentJobDefaultsResult(); + try { - var result = new AgentJobDefaultsResult(); - try + JobData jobData; + CDataContainer dataContainer; + CreateJobData(parameters.OwnerUri, "default", out dataContainer, out jobData); + + // current connection user name for + result.Owner = dataContainer.ServerConnection.TrueLogin; + + var categories = jobData.Categories; + result.Categories = new AgentJobCategory[categories.Length]; + for (int i = 0; i < categories.Length; ++i) { - JobData jobData; - CDataContainer dataContainer; - CreateJobData(parameters.OwnerUri, "default", out dataContainer, out jobData); - - // current connection user name for - result.Owner = dataContainer.ServerConnection.TrueLogin; - - var categories = jobData.Categories; - result.Categories = new AgentJobCategory[categories.Length]; - for (int i = 0; i < categories.Length; ++i) + result.Categories[i] = new AgentJobCategory { - result.Categories[i] = new AgentJobCategory - { - Id = categories[i].SmoCategory.ID, - Name = categories[i].SmoCategory.Name - }; - } - - result.Success = true; - } - catch (Exception ex) - { - result.Success = false; - result.ErrorMessage = ex.ToString(); + Id = categories[i].SmoCategory.ID, + Name = categories[i].SmoCategory.Name + }; } - await requestContext.SendResult(result); - }); + result.Success = true; + } + catch (Exception ex) + { + result.Success = false; + result.ErrorMessage = ex.ToString(); + } + + await requestContext.SendResult(result); } #endregion // "Jobs Handlers" @@ -466,58 +454,55 @@ namespace Microsoft.SqlTools.ServiceLayer.Agent /// internal async Task HandleAgentAlertsRequest(AgentAlertsParams parameters, RequestContext requestContext) { - await Task.Run(async () => + var result = new AgentAlertsResult(); + try { - var result = new AgentAlertsResult(); - try - { - ConnectionInfo connInfo; - 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); - int alertsCount = dataContainer.Server.JobServer.Alerts.Count; - var alerts = new AgentAlertInfo[alertsCount]; - for (int i = 0; i < alertsCount; ++i) + int alertsCount = dataContainer.Server.JobServer.Alerts.Count; + var alerts = new AgentAlertInfo[alertsCount]; + for (int i = 0; i < alertsCount; ++i) + { + var alert = dataContainer.Server.JobServer.Alerts[i]; + alerts[i] = new AgentAlertInfo { - var alert = dataContainer.Server.JobServer.Alerts[i]; - alerts[i] = new AgentAlertInfo - { - Id = alert.ID, - Name = alert.Name, - DelayBetweenResponses = alert.DelayBetweenResponses, - EventDescriptionKeyword = alert.EventDescriptionKeyword, - EventSource = alert.EventSource, - HasNotification = alert.HasNotification, - IncludeEventDescription = (Contracts.NotifyMethods)alert.IncludeEventDescription, - IsEnabled = alert.IsEnabled, - JobId = alert.JobID.ToString(), - JobName = alert.JobName, - LastOccurrenceDate = alert.LastOccurrenceDate.ToString(), - LastResponseDate = alert.LastResponseDate.ToString(), - MessageId = alert.MessageID, - NotificationMessage = alert.NotificationMessage, - OccurrenceCount = alert.OccurrenceCount, - PerformanceCondition = alert.PerformanceCondition, - Severity = alert.Severity, - DatabaseName = alert.DatabaseName, - CountResetDate = alert.CountResetDate.ToString(), - CategoryName = alert.CategoryName, - AlertType = (Contracts.AlertType)alert.AlertType, - WmiEventNamespace = alert.WmiEventNamespace, - WmiEventQuery = alert.WmiEventQuery - }; - } + Id = alert.ID, + Name = alert.Name, + DelayBetweenResponses = alert.DelayBetweenResponses, + EventDescriptionKeyword = alert.EventDescriptionKeyword, + EventSource = alert.EventSource, + HasNotification = alert.HasNotification, + IncludeEventDescription = (Contracts.NotifyMethods)alert.IncludeEventDescription, + IsEnabled = alert.IsEnabled, + JobId = alert.JobID.ToString(), + JobName = alert.JobName, + LastOccurrenceDate = alert.LastOccurrenceDate.ToString(), + LastResponseDate = alert.LastResponseDate.ToString(), + MessageId = alert.MessageID, + NotificationMessage = alert.NotificationMessage, + OccurrenceCount = alert.OccurrenceCount, + PerformanceCondition = alert.PerformanceCondition, + Severity = alert.Severity, + DatabaseName = alert.DatabaseName, + CountResetDate = alert.CountResetDate.ToString(), + CategoryName = alert.CategoryName, + AlertType = (Contracts.AlertType)alert.AlertType, + WmiEventNamespace = alert.WmiEventNamespace, + WmiEventQuery = alert.WmiEventQuery + }; + } - result.Alerts = alerts; - result.Success = true; - } - catch (Exception ex) - { - result.Success = false; - result.ErrorMessage = ex.ToString(); - } - await requestContext.SendResult(result); - }); + result.Alerts = alerts; + result.Success = true; + } + catch (Exception ex) + { + result.Success = false; + result.ErrorMessage = ex.ToString(); + } + await requestContext.SendResult(result); } /// @@ -583,52 +568,49 @@ namespace Microsoft.SqlTools.ServiceLayer.Agent internal async Task HandleAgentOperatorsRequest(AgentOperatorsParams parameters, RequestContext requestContext) { - await Task.Run(async () => + var result = new AgentOperatorsResult(); + try { - var result = new AgentOperatorsResult(); - try - { - ConnectionInfo connInfo; - 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); - int operatorCount = dataContainer.Server.JobServer.Operators.Count; - var operators = new AgentOperatorInfo[operatorCount]; - for (int i = 0; i < operatorCount; ++i) + int operatorCount = dataContainer.Server.JobServer.Operators.Count; + var operators = new AgentOperatorInfo[operatorCount]; + for (int i = 0; i < operatorCount; ++i) + { + var item = dataContainer.Server.JobServer.Operators[i]; + operators[i] = new AgentOperatorInfo { - var item = dataContainer.Server.JobServer.Operators[i]; - operators[i] = new AgentOperatorInfo - { - Name = item.Name, - Id = item.ID, - EmailAddress = item.EmailAddress, - Enabled = item.Enabled, - LastEmailDate = item.LastEmailDate.ToString(), - LastNetSendDate = item.LastNetSendDate.ToString(), - LastPagerDate = item.LastPagerDate.ToString(), - PagerAddress = item.PagerAddress, - CategoryName = item.CategoryName, - PagerDays = (Contracts.WeekDays)item.PagerDays, - SaturdayPagerEndTime = item.SaturdayPagerEndTime.ToString(), - SaturdayPagerStartTime = item.SaturdayPagerEndTime.ToString(), - SundayPagerEndTime = item.SundayPagerEndTime.ToString(), - SundayPagerStartTime = item.SundayPagerStartTime.ToString(), - NetSendAddress = item.NetSendAddress, - WeekdayPagerStartTime = item.WeekdayPagerStartTime.ToString(), - WeekdayPagerEndTime = item.WeekdayPagerEndTime.ToString() - }; - } + Name = item.Name, + Id = item.ID, + EmailAddress = item.EmailAddress, + Enabled = item.Enabled, + LastEmailDate = item.LastEmailDate.ToString(), + LastNetSendDate = item.LastNetSendDate.ToString(), + LastPagerDate = item.LastPagerDate.ToString(), + PagerAddress = item.PagerAddress, + CategoryName = item.CategoryName, + PagerDays = (Contracts.WeekDays)item.PagerDays, + SaturdayPagerEndTime = item.SaturdayPagerEndTime.ToString(), + SaturdayPagerStartTime = item.SaturdayPagerEndTime.ToString(), + SundayPagerEndTime = item.SundayPagerEndTime.ToString(), + SundayPagerStartTime = item.SundayPagerStartTime.ToString(), + NetSendAddress = item.NetSendAddress, + WeekdayPagerStartTime = item.WeekdayPagerStartTime.ToString(), + WeekdayPagerEndTime = item.WeekdayPagerEndTime.ToString() + }; + } - result.Operators = operators; - result.Success = true; - } - catch (Exception ex) - { - result.Success = false; - result.ErrorMessage = ex.ToString(); - } - await requestContext.SendResult(result); - }); + result.Operators = operators; + result.Success = true; + } + catch (Exception ex) + { + result.Success = false; + result.ErrorMessage = ex.ToString(); + } + await requestContext.SendResult(result); } internal async Task HandleCreateAgentOperatorRequest( @@ -691,42 +673,39 @@ namespace Microsoft.SqlTools.ServiceLayer.Agent internal async Task HandleAgentProxiesRequest(AgentProxiesParams parameters, RequestContext requestContext) { - await Task.Run(async () => + var result = new AgentProxiesResult(); + try { - var result = new AgentProxiesResult(); - try - { - ConnectionInfo connInfo; - 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); - int proxyCount = dataContainer.Server.JobServer.ProxyAccounts.Count; - var proxies = new AgentProxyInfo[proxyCount]; - for (int i = 0; i < proxyCount; ++i) + int proxyCount = dataContainer.Server.JobServer.ProxyAccounts.Count; + var proxies = new AgentProxyInfo[proxyCount]; + for (int i = 0; i < proxyCount; ++i) + { + var proxy = dataContainer.Server.JobServer.ProxyAccounts[i]; + proxies[i] = new AgentProxyInfo { - var proxy = dataContainer.Server.JobServer.ProxyAccounts[i]; - proxies[i] = new AgentProxyInfo - { - Id = proxy.ID, - AccountName = proxy.Name, - Description = proxy.Description, - CredentialName = proxy.CredentialName, - CredentialIdentity = proxy.CredentialIdentity, - CredentialId = proxy.CredentialID, - IsEnabled = proxy.IsEnabled - }; - } - result.Proxies = proxies; - result.Success = true; - } - catch (Exception ex) - { - result.Success = false; - result.ErrorMessage = ex.ToString(); + Id = proxy.ID, + AccountName = proxy.Name, + Description = proxy.Description, + CredentialName = proxy.CredentialName, + CredentialIdentity = proxy.CredentialIdentity, + CredentialId = proxy.CredentialID, + IsEnabled = proxy.IsEnabled + }; } + result.Proxies = proxies; + result.Success = true; + } + catch (Exception ex) + { + result.Success = false; + result.ErrorMessage = ex.ToString(); + } - await requestContext.SendResult(result); - }); + await requestContext.SendResult(result); } internal async Task HandleCreateAgentProxyRequest(CreateAgentProxyParams parameters, RequestContext requestContext) @@ -785,51 +764,48 @@ namespace Microsoft.SqlTools.ServiceLayer.Agent internal async Task HandleAgentSchedulesRequest(AgentSchedulesParams parameters, RequestContext requestContext) { - await Task.Run(async () => + var result = new AgentSchedulesResult(); + try { - var result = new AgentSchedulesResult(); - try - { - ConnectionInfo connInfo; - 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); - int scheduleCount = dataContainer.Server.JobServer.SharedSchedules.Count; - var schedules = new AgentScheduleInfo[scheduleCount]; - for (int i = 0; i < scheduleCount; ++i) - { - var schedule = dataContainer.Server.JobServer.SharedSchedules[i]; - var scheduleData = new JobScheduleData(schedule); - schedules[i] = new AgentScheduleInfo(); - schedules[i].Id = schedule.ID; - schedules[i].Name = schedule.Name; - schedules[i].IsEnabled = schedule.IsEnabled; - schedules[i].FrequencyTypes = (Contracts.FrequencyTypes)schedule.FrequencyTypes; - schedules[i].FrequencySubDayTypes = (Contracts.FrequencySubDayTypes)schedule.FrequencySubDayTypes; - schedules[i].FrequencySubDayInterval = schedule.FrequencySubDayInterval; - schedules[i].FrequencyRelativeIntervals = (Contracts.FrequencyRelativeIntervals)schedule.FrequencyRelativeIntervals; - schedules[i].FrequencyRecurrenceFactor = schedule.FrequencyRecurrenceFactor; - schedules[i].FrequencyInterval = schedule.FrequencyInterval; - schedules[i].DateCreated = schedule.DateCreated; - schedules[i].ActiveStartTimeOfDay = schedule.ActiveStartTimeOfDay; - schedules[i].ActiveStartDate = schedule.ActiveStartDate; - schedules[i].ActiveEndTimeOfDay = schedule.ActiveEndTimeOfDay; - schedules[i].JobCount = schedule.JobCount; - schedules[i].ActiveEndDate = schedule.ActiveEndDate; - schedules[i].ScheduleUid = schedule.ScheduleUid; - schedules[i].Description = scheduleData.Description; - } - result.Schedules = schedules; - result.Success = true; - } - catch (Exception ex) + int scheduleCount = dataContainer.Server.JobServer.SharedSchedules.Count; + var schedules = new AgentScheduleInfo[scheduleCount]; + for (int i = 0; i < scheduleCount; ++i) { - result.Success = false; - result.ErrorMessage = ex.ToString(); + var schedule = dataContainer.Server.JobServer.SharedSchedules[i]; + var scheduleData = new JobScheduleData(schedule); + schedules[i] = new AgentScheduleInfo(); + schedules[i].Id = schedule.ID; + schedules[i].Name = schedule.Name; + schedules[i].IsEnabled = schedule.IsEnabled; + schedules[i].FrequencyTypes = (Contracts.FrequencyTypes)schedule.FrequencyTypes; + schedules[i].FrequencySubDayTypes = (Contracts.FrequencySubDayTypes)schedule.FrequencySubDayTypes; + schedules[i].FrequencySubDayInterval = schedule.FrequencySubDayInterval; + schedules[i].FrequencyRelativeIntervals = (Contracts.FrequencyRelativeIntervals)schedule.FrequencyRelativeIntervals; + schedules[i].FrequencyRecurrenceFactor = schedule.FrequencyRecurrenceFactor; + schedules[i].FrequencyInterval = schedule.FrequencyInterval; + schedules[i].DateCreated = schedule.DateCreated; + schedules[i].ActiveStartTimeOfDay = schedule.ActiveStartTimeOfDay; + schedules[i].ActiveStartDate = schedule.ActiveStartDate; + schedules[i].ActiveEndTimeOfDay = schedule.ActiveEndTimeOfDay; + schedules[i].JobCount = schedule.JobCount; + schedules[i].ActiveEndDate = schedule.ActiveEndDate; + schedules[i].ScheduleUid = schedule.ScheduleUid; + schedules[i].Description = scheduleData.Description; } + result.Schedules = schedules; + result.Success = true; + } + catch (Exception ex) + { + result.Success = false; + result.ErrorMessage = ex.ToString(); + } - await requestContext.SendResult(result); - }); + await requestContext.SendResult(result); } internal async Task HandleCreateAgentScheduleRequest(CreateAgentScheduleParams parameters, RequestContext requestContext) @@ -907,79 +883,76 @@ namespace Microsoft.SqlTools.ServiceLayer.Agent ConfigAction configAction, RunType runType) { - return await Task>.Run(async () => + try { - try + JobData jobData; + CDataContainer dataContainer; + CreateJobData(ownerUri, originalJobName, out dataContainer, out jobData, configAction, jobInfo); + + using (JobActions actions = new JobActions(dataContainer, jobData, configAction)) { - JobData jobData; - CDataContainer dataContainer; - CreateJobData(ownerUri, originalJobName, out dataContainer, out jobData, configAction, jobInfo); + ExecuteAction(actions, runType); + } - using (JobActions actions = new JobActions(dataContainer, jobData, configAction)) + + ConnectionInfo connInfo; + ConnectionServiceInstance.TryFindConnection(ownerUri, out connInfo); + if (connInfo != null) + { + dataContainer = CDataContainer.CreateDataContainer(connInfo, databaseExists: true); + } + + // Execute step actions if they exist + if (configAction != ConfigAction.Drop && jobInfo.JobSteps != null && jobInfo.JobSteps.Length > 0) + { + foreach (AgentJobStepInfo step in jobInfo.JobSteps) { - ExecuteAction(actions, runType); - } - - - ConnectionInfo connInfo; - ConnectionServiceInstance.TryFindConnection(ownerUri, out connInfo); - if (connInfo != null) - { - dataContainer = CDataContainer.CreateDataContainer(connInfo, databaseExists: true); - } - - // Execute step actions if they exist - if (configAction != ConfigAction.Drop && jobInfo.JobSteps != null && jobInfo.JobSteps.Length > 0) - { - foreach (AgentJobStepInfo step in jobInfo.JobSteps) + configAction = ConfigAction.Create; + foreach (JobStep jobStep in dataContainer.Server.JobServer.Jobs[originalJobName].JobSteps) { - configAction = ConfigAction.Create; - foreach (JobStep jobStep in dataContainer.Server.JobServer.Jobs[originalJobName].JobSteps) + // any changes made to step other than name or ordering + if ((step.StepName == jobStep.Name && step.Id == jobStep.ID) || + // if the step name was changed + (step.StepName != jobStep.Name && step.Id == jobStep.ID) || + // if the step ordering was changed + (step.StepName == jobStep.Name && step.Id != jobStep.ID)) { - // any changes made to step other than name or ordering - if ((step.StepName == jobStep.Name && step.Id == jobStep.ID) || - // if the step name was changed - (step.StepName != jobStep.Name && step.Id == jobStep.ID) || - // if the step ordering was changed - (step.StepName == jobStep.Name && step.Id != jobStep.ID)) - { - configAction = ConfigAction.Update; - break; - } + configAction = ConfigAction.Update; + break; } - await ConfigureAgentJobStep(ownerUri, step, configAction, runType, jobData, dataContainer); } + await ConfigureAgentJobStep(ownerUri, step, configAction, runType, jobData, dataContainer); } - - // Execute schedule actions if they exist - if (jobInfo.JobSchedules != null && jobInfo.JobSchedules.Length > 0) - { - foreach (AgentScheduleInfo schedule in jobInfo.JobSchedules) - { - await ConfigureAgentSchedule(ownerUri, schedule, configAction, runType, jobData, dataContainer); - } - } - - // Execute alert actions if they exist - if (jobInfo.Alerts != null && jobInfo.Alerts.Length > 0) - { - foreach (AgentAlertInfo alert in jobInfo.Alerts) - { - alert.JobId = jobData.Job.JobID.ToString(); - await ConfigureAgentAlert(ownerUri, alert.Name, alert, configAction, runType, jobData, dataContainer); - } - } - - return new Tuple(true, string.Empty); } - catch (Exception ex) + + // Execute schedule actions if they exist + if (jobInfo.JobSchedules != null && jobInfo.JobSchedules.Length > 0) { - return new Tuple(false, ex.ToString()); + foreach (AgentScheduleInfo schedule in jobInfo.JobSchedules) + { + await ConfigureAgentSchedule(ownerUri, schedule, configAction, runType, jobData, dataContainer); + } } - }); + + // Execute alert actions if they exist + if (jobInfo.Alerts != null && jobInfo.Alerts.Length > 0) + { + foreach (AgentAlertInfo alert in jobInfo.Alerts) + { + alert.JobId = jobData.Job.JobID.ToString(); + await ConfigureAgentAlert(ownerUri, alert.Name, alert, configAction, runType, jobData, dataContainer); + } + } + + return new Tuple(true, string.Empty); + } + catch (Exception ex) + { + return new Tuple(false, ex.ToString()); + } } - internal async Task> ConfigureAgentJobStep( + internal Task> ConfigureAgentJobStep( string ownerUri, AgentJobStepInfo stepInfo, ConfigAction configAction, @@ -987,7 +960,7 @@ namespace Microsoft.SqlTools.ServiceLayer.Agent JobData jobData = null, CDataContainer dataContainer = null) { - return await Task>.Run(() => + return Task.Run(() => { try { @@ -1016,7 +989,7 @@ namespace Microsoft.SqlTools.ServiceLayer.Agent }); } - internal async Task> ConfigureAgentAlert( + internal Task> ConfigureAgentAlert( string ownerUri, string alertName, AgentAlertInfo alert, @@ -1025,7 +998,7 @@ namespace Microsoft.SqlTools.ServiceLayer.Agent JobData jobData = null, CDataContainer dataContainer = null) { - return await Task>.Run(() => + return Task>.Run(() => { try { @@ -1063,13 +1036,13 @@ namespace Microsoft.SqlTools.ServiceLayer.Agent }); } - internal async Task> ConfigureAgentOperator( + internal Task> ConfigureAgentOperator( string ownerUri, AgentOperatorInfo operatorInfo, ConfigAction configAction, RunType runType) { - return await Task>.Run(() => + return Task.Run(() => { try { @@ -1093,14 +1066,14 @@ namespace Microsoft.SqlTools.ServiceLayer.Agent }); } - internal async Task> ConfigureAgentProxy( + internal Task> ConfigureAgentProxy( string ownerUri, string accountName, AgentProxyInfo proxy, ConfigAction configAction, RunType runType) { - return await Task.Run(() => + return Task.Run(() => { try { @@ -1124,7 +1097,7 @@ namespace Microsoft.SqlTools.ServiceLayer.Agent }); } - internal async Task> ConfigureAgentSchedule( + internal Task> ConfigureAgentSchedule( string ownerUri, AgentScheduleInfo schedule, ConfigAction configAction, @@ -1132,7 +1105,7 @@ namespace Microsoft.SqlTools.ServiceLayer.Agent JobData jobData = null, CDataContainer dataContainer = null) { - return await Task.Run(() => + return Task.Run(() => { try { @@ -1230,272 +1203,242 @@ namespace Microsoft.SqlTools.ServiceLayer.Agent internal async Task HandleAgentNotebooksRequest(AgentNotebooksParams parameters, RequestContext requestContext) { - await Task.Run(async () => + var result = new AgentNotebooksResult(); + try { - var result = new AgentNotebooksResult(); - try - { - ConnectionInfo connInfo; - ConnectionServiceInstance.TryFindConnection( - parameters.OwnerUri, - out connInfo); - result.Success = true; - result.Notebooks = AgentNotebookHelper.GetAgentNotebooks(connInfo).Result; - } - catch (Exception e) - { - result.Success = false; - result.ErrorMessage = e.ToString(); - } - await requestContext.SendResult(result); - }); + ConnectionInfo connInfo; + ConnectionServiceInstance.TryFindConnection( + parameters.OwnerUri, + out connInfo); + result.Success = true; + result.Notebooks = AgentNotebookHelper.GetAgentNotebooks(connInfo).Result; + } + catch (Exception e) + { + result.Success = false; + result.ErrorMessage = e.ToString(); + } + await requestContext.SendResult(result); } internal async Task HandleAgentNotebookHistoryRequest( AgentNotebookHistoryParams parameters, RequestContext requestContext) { - await Task.Run(async () => + var result = new AgentNotebookHistoryResult(); + try { - var result = new AgentNotebookHistoryResult(); - try - { - ConnectionInfo connInfo; - ConnectionServiceInstance.TryFindConnection( - parameters.OwnerUri, - out connInfo); + ConnectionInfo connInfo; + ConnectionServiceInstance.TryFindConnection( + parameters.OwnerUri, + out connInfo); - result = await GetAgentNotebookHistories( - connInfo, - parameters.JobId, - parameters.JobName, - parameters.TargetDatabase - ); + result = await GetAgentNotebookHistories( + connInfo, + parameters.JobId, + parameters.JobName, + parameters.TargetDatabase + ); - result.Success = true; - } - catch (Exception e) - { - result.Success = false; - result.ErrorMessage = e.ToString(); - } - await requestContext.SendResult(result); - }); + result.Success = true; + } + catch (Exception e) + { + result.Success = false; + result.ErrorMessage = e.ToString(); + } + await requestContext.SendResult(result); } internal async Task HandleAgentNotebookMaterializedRequest(AgentNotebookMaterializedParams parameters, RequestContext requestContext) { - await Task.Run(async () => + var result = new AgentNotebookMaterializedResult(); + try { - var result = new AgentNotebookMaterializedResult(); - try - { - ConnectionInfo connInfo; - ConnectionServiceInstance.TryFindConnection( - parameters.OwnerUri, - out connInfo); - result.NotebookMaterialized = AgentNotebookHelper.GetMaterializedNotebook(connInfo, parameters.NotebookMaterializedId, parameters.TargetDatabase).Result; - result.Success = true; - } - catch (Exception e) - { - result.Success = false; - result.ErrorMessage = e.ToString(); + ConnectionInfo connInfo; + ConnectionServiceInstance.TryFindConnection( + parameters.OwnerUri, + out connInfo); + result.NotebookMaterialized = AgentNotebookHelper.GetMaterializedNotebook(connInfo, parameters.NotebookMaterializedId, parameters.TargetDatabase).Result; + result.Success = true; + } + catch (Exception e) + { + result.Success = false; + result.ErrorMessage = e.ToString(); - } - await requestContext.SendResult(result); - }); + } + await requestContext.SendResult(result); } internal async Task HandleAgentNotebookTemplateRequest(AgentNotebookTemplateParams parameters, RequestContext requestContext) { - await Task.Run(async () => + var result = new AgentNotebookTemplateResult(); + try { - var result = new AgentNotebookTemplateResult(); - try - { - ConnectionInfo connInfo; - ConnectionServiceInstance.TryFindConnection( - parameters.OwnerUri, - out connInfo); - result.NotebookTemplate = await AgentNotebookHelper.GetTemplateNotebook(connInfo, parameters.JobId, parameters.TargetDatabase); - result.Success = true; - } - catch (Exception e) - { - result.Success = false; - result.ErrorMessage = e.ToString(); + ConnectionInfo connInfo; + ConnectionServiceInstance.TryFindConnection( + parameters.OwnerUri, + out connInfo); + result.NotebookTemplate = await AgentNotebookHelper.GetTemplateNotebook(connInfo, parameters.JobId, parameters.TargetDatabase); + result.Success = true; + } + catch (Exception e) + { + result.Success = false; + result.ErrorMessage = e.ToString(); - } - await requestContext.SendResult(result); - }); + } + await requestContext.SendResult(result); } internal async Task HandleCreateAgentNotebookRequest(CreateAgentNotebookParams parameters, RequestContext requestContext) { - await Task.Run(async () => + var result = new CreateAgentNotebookResult(); + try { - var result = new CreateAgentNotebookResult(); - try - { - // storing result - result.Success = true; - await AgentNotebookHelper.CreateNotebook( - this, - parameters.OwnerUri, - parameters.Notebook, - parameters.TemplateFilePath, - ManagementUtils.asRunType(parameters.TaskExecutionMode) - ); + // storing result + result.Success = true; + await AgentNotebookHelper.CreateNotebook( + this, + parameters.OwnerUri, + parameters.Notebook, + parameters.TemplateFilePath, + ManagementUtils.asRunType(parameters.TaskExecutionMode) + ); - } - catch (Exception e) - { - result.Success = false; - result.ErrorMessage = e.ToString(); - } - await requestContext.SendResult(result); - }); + } + catch (Exception e) + { + result.Success = false; + result.ErrorMessage = e.ToString(); + } + await requestContext.SendResult(result); } internal async Task HandleDeleteAgentNotebooksRequest(DeleteAgentNotebookParams parameters, RequestContext requestContext) { - await Task.Run(async () => + var result = new ResultStatus(); + try { - var result = new ResultStatus(); - try - { - // Calling delete notebook helper function - await AgentNotebookHelper.DeleteNotebook( - this, - parameters.OwnerUri, - parameters.Notebook, - ManagementUtils.asRunType(parameters.TaskExecutionMode) - ); - result.Success = true; - } - catch (Exception e) - { - result.Success = false; - result.ErrorMessage = e.ToString(); - } - await requestContext.SendResult(result); - }); + // Calling delete notebook helper function + await AgentNotebookHelper.DeleteNotebook( + this, + parameters.OwnerUri, + parameters.Notebook, + ManagementUtils.asRunType(parameters.TaskExecutionMode) + ); + result.Success = true; + } + catch (Exception e) + { + result.Success = false; + result.ErrorMessage = e.ToString(); + } + await requestContext.SendResult(result); } internal async Task HandleUpdateAgentNotebookRequest(UpdateAgentNotebookParams parameters, RequestContext requestContext) { - await Task.Run(async () => + var result = new UpdateAgentNotebookResult(); + try { - var result = new UpdateAgentNotebookResult(); - try - { - // Calling update helper function - await AgentNotebookHelper.UpdateNotebook( - this, - parameters.OwnerUri, - parameters.OriginalNotebookName, - parameters.Notebook, - parameters.TemplateFilePath, - ManagementUtils.asRunType(parameters.TaskExecutionMode)); - result.Success = true; - } - catch (Exception e) - { - result.Success = false; - result.ErrorMessage = e.ToString(); + // Calling update helper function + await AgentNotebookHelper.UpdateNotebook( + this, + parameters.OwnerUri, + parameters.OriginalNotebookName, + parameters.Notebook, + parameters.TemplateFilePath, + ManagementUtils.asRunType(parameters.TaskExecutionMode)); + result.Success = true; + } + catch (Exception e) + { + result.Success = false; + result.ErrorMessage = e.ToString(); - } - await requestContext.SendResult(result); - }); + } + await requestContext.SendResult(result); } internal async Task HandleUpdateAgentNotebookRunNameRequest(UpdateAgentNotebookRunNameParams parameters, RequestContext requestContext) { - await Task.Run(async () => + var result = new ResultStatus(); + try { - var result = new ResultStatus(); - try - { - ConnectionInfo connInfo; - ConnectionServiceInstance.TryFindConnection( - parameters.OwnerUri, - out connInfo); - // Calling update helper function - await AgentNotebookHelper.UpdateMaterializedNotebookName( - connInfo, - parameters.agentNotebookHistory, - parameters.TargetDatabase, - parameters.MaterializedNotebookName); - result.Success = true; - } - catch (Exception e) - { - result.Success = false; - result.ErrorMessage = e.ToString(); + ConnectionInfo connInfo; + ConnectionServiceInstance.TryFindConnection( + parameters.OwnerUri, + out connInfo); + // Calling update helper function + await AgentNotebookHelper.UpdateMaterializedNotebookName( + connInfo, + parameters.agentNotebookHistory, + parameters.TargetDatabase, + parameters.MaterializedNotebookName); + result.Success = true; + } + catch (Exception e) + { + result.Success = false; + result.ErrorMessage = e.ToString(); - } - await requestContext.SendResult(result); - }); + } + await requestContext.SendResult(result); } internal async Task HandleUpdateAgentNotebookRunPinRequest(UpdateAgentNotebookRunPinParams parameters, RequestContext requestContext) { - await Task.Run(async () => + var result = new ResultStatus(); + try { - var result = new ResultStatus(); - try - { - ConnectionInfo connInfo; - ConnectionServiceInstance.TryFindConnection( - parameters.OwnerUri, - out connInfo); - // Calling update helper function - await AgentNotebookHelper.UpdateMaterializedNotebookPin( - connInfo, - parameters.agentNotebookHistory, - parameters.TargetDatabase, - parameters.MaterializedNotebookPin); - result.Success = true; - } - catch (Exception e) - { - result.Success = false; - result.ErrorMessage = e.ToString(); + ConnectionInfo connInfo; + ConnectionServiceInstance.TryFindConnection( + parameters.OwnerUri, + out connInfo); + // Calling update helper function + await AgentNotebookHelper.UpdateMaterializedNotebookPin( + connInfo, + parameters.agentNotebookHistory, + parameters.TargetDatabase, + parameters.MaterializedNotebookPin); + result.Success = true; + } + catch (Exception e) + { + result.Success = false; + result.ErrorMessage = e.ToString(); - } - await requestContext.SendResult(result); - }); + } + await requestContext.SendResult(result); } internal async Task HandleDeleteNotebookMaterializedRequest(DeleteMaterializedNotebookParams parameters, RequestContext requestContext) { - await Task.Run(async () => + var result = new ResultStatus(); + try { - var result = new ResultStatus(); - try - { - ConnectionInfo connInfo; - ConnectionServiceInstance.TryFindConnection( - parameters.OwnerUri, - out connInfo); - // Calling update helper function - await AgentNotebookHelper.DeleteMaterializedNotebook( - connInfo, - parameters.agentNotebookHistory, - parameters.TargetDatabase); - result.Success = true; - } - catch (Exception e) - { - result.Success = false; - result.ErrorMessage = e.ToString(); + ConnectionInfo connInfo; + ConnectionServiceInstance.TryFindConnection( + parameters.OwnerUri, + out connInfo); + // Calling update helper function + await AgentNotebookHelper.DeleteMaterializedNotebook( + connInfo, + parameters.agentNotebookHistory, + parameters.TargetDatabase); + result.Success = true; + } + catch (Exception e) + { + result.Success = false; + result.ErrorMessage = e.ToString(); - } - await requestContext.SendResult(result); - }); + } + await requestContext.SendResult(result); } public async Task GetAgentNotebookHistories diff --git a/src/Microsoft.SqlTools.ServiceLayer/Connection/ConnectionService.cs b/src/Microsoft.SqlTools.ServiceLayer/Connection/ConnectionService.cs index 48d0a3dc..ec59b2ce 100644 --- a/src/Microsoft.SqlTools.ServiceLayer/Connection/ConnectionService.cs +++ b/src/Microsoft.SqlTools.ServiceLayer/Connection/ConnectionService.cs @@ -54,8 +54,8 @@ namespace Microsoft.SqlTools.ServiceLayer.Connection private DatabaseLocksManager lockedDatabaseManager; /// - /// 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. + /// 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. /// private readonly ConcurrentDictionary cancelTupleToCancellationTokenSourceMap = new ConcurrentDictionary(); @@ -238,7 +238,6 @@ namespace Microsoft.SqlTools.ServiceLayer.Connection /// /// The URI of the connection /// True if a refreshed was needed and requested, false otherwise - internal async Task TryRequestRefreshAuthToken(string ownerUri) { ConnectionInfo connInfo; @@ -273,7 +272,7 @@ namespace Microsoft.SqlTools.ServiceLayer.Connection Logger.Error("No accountId in connection details when refreshing token for connection {ownerUri}"); 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 if (!this.TokenUpdateUris.TryAdd(ownerUri, true)) { @@ -299,7 +298,7 @@ namespace Microsoft.SqlTools.ServiceLayer.Connection /// Requests an update of the azure auth token /// /// The token to update - /// true upon successful update, false if it failed to find + /// true upon successful update, false if it failed to find /// the connection internal void UpdateAuthToken(TokenRefreshedParams tokenRefreshedParams) { @@ -312,6 +311,12 @@ namespace Microsoft.SqlTools.ServiceLayer.Connection connection.UpdateAuthToken(tokenRefreshedParams.Token, tokenRefreshedParams.ExpiresOn); } + /// + /// Validates the given ConnectParams object. + /// + /// The params to validate + /// A ConnectionCompleteParams object upon validation error, + /// null upon validation success public ConnectionCompleteParams ValidateConnectParams(ConnectParams connectionParams) { string paramValidationErrorMessage; @@ -350,7 +355,7 @@ namespace Microsoft.SqlTools.ServiceLayer.Connection TrySetConnectionType(connectionParams); 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. ConnectionInfo connectionInfo; bool connectionChanged = false; @@ -388,7 +393,7 @@ namespace Microsoft.SqlTools.ServiceLayer.Connection // Return information about the connected SQL Server instance ConnectionCompleteParams completeParams = GetConnectionCompleteParams(connectionParams.Type, connectionInfo); - // Invoke callback notifications + // Invoke callback notifications InvokeOnConnectionActivities(connectionInfo, connectionParams); TryCloseConnectionTemporaryConnection(connectionParams, connectionInfo); @@ -486,7 +491,7 @@ namespace Microsoft.SqlTools.ServiceLayer.Connection } /// - /// 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. /// /// A ConnectionCompleteParams in response to the successful connection @@ -501,7 +506,7 @@ namespace Microsoft.SqlTools.ServiceLayer.Connection // 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 - // 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)) { connectionInfo.ConnectionDetails.DatabaseName = connection.Database; @@ -680,8 +685,8 @@ namespace Microsoft.SqlTools.ServiceLayer.Connection } /// - /// 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 + /// 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 /// connection if a default connection does not exist. /// /// URI identifying the resource mapped to this connection @@ -738,7 +743,7 @@ namespace Microsoft.SqlTools.ServiceLayer.Connection bool alwaysPersistSecurity, ConnectionInfo connectionInfo) { // 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. bool? originalPersistSecurityInfo = connectionInfo.ConnectionDetails.PersistSecurityInfo; 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 null, cancel all pending connections associated with ownerUri. /// - /// true if a single pending connection associated with the non-null connectionType was + /// true if a single pending connection associated with the non-null connectionType was /// found and cancelled, false otherwise private bool CancelConnections(string ownerUri, string connectionType) { // Cancel the connection of the given type 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 return CancelConnect(new CancelConnectParams() { OwnerUri = ownerUri, Type = connectionType }); } @@ -956,7 +961,7 @@ namespace Microsoft.SqlTools.ServiceLayer.Connection } /// - /// 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 null, closes all DbConnections. /// @@ -1036,10 +1041,10 @@ namespace Microsoft.SqlTools.ServiceLayer.Connection serviceHost.SetRequestHandler(BuildConnectionInfoRequest.Type, HandleBuildConnectionInfoRequest); } - /// - /// 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 + /// + /// public void RegisterOnConnectionTask(OnConnectionHandler activity) { onConnectionActivities.Add(activity); @@ -1083,7 +1088,7 @@ namespace Microsoft.SqlTools.ServiceLayer.Connection { try { - // result is null if the ConnectParams was successfully validated + // result is null if the ConnectParams was successfully validated ConnectionCompleteParams result = ValidateConnectParams(connectParams); if (result != null) { @@ -1395,42 +1400,39 @@ namespace Microsoft.SqlTools.ServiceLayer.Connection GetConnectionStringParams connStringParams, RequestContext requestContext) { - await Task.Run(async () => + string connectionString = string.Empty; + ConnectionInfo info; + SqlConnectionStringBuilder connStringBuilder; + try { - string connectionString = string.Empty; - ConnectionInfo info; - SqlConnectionStringBuilder connStringBuilder; - try + // set connection string using connection uri if connection details are undefined + if (connStringParams.ConnectionDetails == null) { - // set connection string using connection uri if connection details are undefined - if (connStringParams.ConnectionDetails == null) - { - 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; + TryFindConnection(connStringParams.OwnerUri, out info); + connStringBuilder = CreateConnectionStringBuilder(info.ConnectionDetails); } - 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); } /// @@ -1440,19 +1442,16 @@ namespace Microsoft.SqlTools.ServiceLayer.Connection string connectionString, RequestContext requestContext) { - await Task.Run(async () => + try { - try - { - await requestContext.SendResult(ParseConnectionString(connectionString)); - } - catch (Exception) - { - // If theres an error in the parse, it means we just can't parse, so we return undefined - // rather than an error. - await requestContext.SendResult(null); - } - }); + await requestContext.SendResult(ParseConnectionString(connectionString)); + } + catch (Exception) + { + // If theres an error in the parse, it means we just can't parse, so we return undefined + // rather than an error. + await requestContext.SendResult(null); + } } public ConnectionDetails ParseConnectionString(string connectionString) diff --git a/src/Microsoft.SqlTools.ServiceLayer/Formatter/TSqlFormatterService.cs b/src/Microsoft.SqlTools.ServiceLayer/Formatter/TSqlFormatterService.cs index 540f31c9..097ad6c4 100644 --- a/src/Microsoft.SqlTools.ServiceLayer/Formatter/TSqlFormatterService.cs +++ b/src/Microsoft.SqlTools.ServiceLayer/Formatter/TSqlFormatterService.cs @@ -110,9 +110,9 @@ namespace Microsoft.SqlTools.ServiceLayer.Formatter }; } - private async Task FormatRangeAndReturnEdits(DocumentRangeFormattingParams docFormatParams) + private Task FormatRangeAndReturnEdits(DocumentRangeFormattingParams docFormatParams) { - return await Task.Factory.StartNew(() => + return Task.Run(() => { if (ShouldSkipFormatting(docFormatParams)) { @@ -123,7 +123,7 @@ namespace Microsoft.SqlTools.ServiceLayer.Formatter ScriptFile scriptFile = GetFile(docFormatParams); if (scriptFile == null) { - return new TextEdit[0]; + return Array.Empty(); } TextEdit textEdit = new TextEdit { Range = range }; string text = scriptFile.GetTextInRange(range.ToBufferRange()); @@ -142,9 +142,9 @@ namespace Microsoft.SqlTools.ServiceLayer.Formatter return (LanguageService != null && LanguageService.ShouldSkipNonMssqlFile(docFormatParams.TextDocument.Uri)); } - private async Task FormatAndReturnEdits(DocumentFormattingParams docFormatParams) - { - return await Task.Factory.StartNew(() => + private Task FormatAndReturnEdits(DocumentFormattingParams docFormatParams) + { + return Task.Factory.StartNew(() => { if (ShouldSkipFormatting(docFormatParams)) { @@ -155,7 +155,7 @@ namespace Microsoft.SqlTools.ServiceLayer.Formatter if (scriptFile == null || scriptFile.FileLines.Count == 0) { - return new TextEdit[0]; + return Array.Empty(); } TextEdit textEdit = PrepareEdit(scriptFile); string text = scriptFile.Contents; @@ -205,12 +205,12 @@ namespace Microsoft.SqlTools.ServiceLayer.Formatter if (settings.PlaceSelectStatementReferencesOnNewLine.HasValue) { options.PlaceEachReferenceOnNewLineInQueryStatements = settings.PlaceSelectStatementReferencesOnNewLine.Value; } if (settings.UseBracketForIdentifiers.HasValue) { options.EncloseIdentifiersInSquareBrackets = settings.UseBracketForIdentifiers.Value; } - + options.DatatypeCasing = settings.DatatypeCasing; options.KeywordCasing = settings.KeywordCasing; } } - + private ScriptFile GetFile(DocumentFormattingParams docFormatParams) { return WorkspaceService.Workspace.GetFile(docFormatParams.TextDocument.Uri); diff --git a/src/Microsoft.SqlTools.ServiceLayer/HostLoader.cs b/src/Microsoft.SqlTools.ServiceLayer/HostLoader.cs index 44075086..7f7624fa 100644 --- a/src/Microsoft.SqlTools.ServiceLayer/HostLoader.cs +++ b/src/Microsoft.SqlTools.ServiceLayer/HostLoader.cs @@ -201,10 +201,10 @@ namespace Microsoft.SqlTools.ServiceLayer IDisposable disposable = service as IDisposable; if (serviceHost != null && disposable != null) { - serviceHost.RegisterShutdownTask(async (shutdownParams, shutdownRequestContext) => + serviceHost.RegisterShutdownTask((_, _) => { disposable.Dispose(); - await Task.FromResult(0); + return Task.FromResult(0); }); } } diff --git a/src/Microsoft.SqlTools.ServiceLayer/LanguageServices/LanguageService.cs b/src/Microsoft.SqlTools.ServiceLayer/LanguageServices/LanguageService.cs index f7d42ed3..5050a545 100644 --- a/src/Microsoft.SqlTools.ServiceLayer/LanguageServices/LanguageService.cs +++ b/src/Microsoft.SqlTools.ServiceLayer/LanguageServices/LanguageService.cs @@ -270,12 +270,12 @@ namespace Microsoft.SqlTools.ServiceLayer.LanguageServices serviceHost.SetEventHandler(TokenRefreshedNotification.Type, HandleTokenRefreshedNotification); // 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"); DeletePeekDefinitionScripts(); this.Dispose(); - await Task.FromResult(0); + return Task.FromResult(0); }); ServiceHostInstance = serviceHost; @@ -399,33 +399,30 @@ namespace Microsoft.SqlTools.ServiceLayer.LanguageServices /// internal async Task HandleSyntaxParseRequest(SyntaxParseParams param, RequestContext 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); - 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); + syntaxResult.Parseable = true; } - 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()); + } } /// @@ -674,8 +671,6 @@ namespace Microsoft.SqlTools.ServiceLayer.LanguageServices new ScriptFile[] { scriptFile }, eventContext); } - - await Task.FromResult(true); } catch (Exception ex) { @@ -700,8 +695,6 @@ namespace Microsoft.SqlTools.ServiceLayer.LanguageServices changedFiles.ToArray(), eventContext); } - - await Task.FromResult(true); } catch (Exception ex) { @@ -902,7 +895,7 @@ namespace Microsoft.SqlTools.ServiceLayer.LanguageServices { bool 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 }; await HandleRebuildIntelliSenseNotification(param, eventContext); } @@ -933,13 +926,13 @@ namespace Microsoft.SqlTools.ServiceLayer.LanguageServices /// it is the last URI connected to a particular connection, /// then remove the cache. /// - public async Task RemoveAutoCompleteCacheUriReference(IConnectionSummary summary, string ownerUri) + public Task RemoveAutoCompleteCacheUriReference(IConnectionSummary summary, string ownerUri) { RemoveScriptParseInfo(ownerUri); // currently this method is disabled, but we need to reimplement now that the // implementation of the 'cache' has changed. - await Task.FromResult(0); + return Task.CompletedTask; } /// @@ -1049,9 +1042,9 @@ namespace Microsoft.SqlTools.ServiceLayer.LanguageServices /// Update the autocomplete metadata provider when the user connects to a database /// /// - public async Task UpdateLanguageServiceOnConnection(ConnectionInfo info) + public Task UpdateLanguageServiceOnConnection(ConnectionInfo info) { - await Task.Run(() => + return Task.Run(() => { 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 this.currentCompletionParseInfo = scriptParseInfo; resultCompletionItems = result.CompletionItems; - + /* 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) { diff --git a/src/Microsoft.SqlTools.ServiceLayer/NotebookConvert/NotebookConvertService.cs b/src/Microsoft.SqlTools.ServiceLayer/NotebookConvert/NotebookConvertService.cs index bd795151..da7f081e 100644 --- a/src/Microsoft.SqlTools.ServiceLayer/NotebookConvert/NotebookConvertService.cs +++ b/src/Microsoft.SqlTools.ServiceLayer/NotebookConvert/NotebookConvertService.cs @@ -58,7 +58,7 @@ namespace Microsoft.SqlTools.ServiceLayer.NotebookConvert } /// - /// Initializes the service by doing tasks such as setting up request handlers. + /// Initializes the service by doing tasks such as setting up request handlers. /// /// public void InitializeService(ServiceHost serviceHost) @@ -75,49 +75,42 @@ namespace Microsoft.SqlTools.ServiceLayer.NotebookConvert internal async Task HandleConvertNotebookToSqlRequest(ConvertNotebookToSqlParams parameters, RequestContext requestContext) { - await Task.Run(async () => + try { - try - { - var notebookDoc = JsonConvert.DeserializeObject(parameters.Content); + var notebookDoc = JsonConvert.DeserializeObject(parameters.Content); - var result = new ConvertNotebookToSqlResult - { - Content = ConvertNotebookDocToSql(notebookDoc) - }; - await requestContext.SendResult(result); - } - catch (Exception e) + var result = new ConvertNotebookToSqlResult { - 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 requestContext) { - await Task.Run(async () => + try { - - try + // This URI doesn't come in escaped - so if it's a file path with reserved characters (such as %) + // 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.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 %) - // 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.Instance.Workspace.GetFile(escapedClientUri); - // Temporary notebook that we just fill in with the sql until the parsing logic is added - var result = new ConvertSqlToNotebookResult - { - Content = JsonConvert.SerializeObject(ConvertSqlToNotebook(file.Contents)) - }; - await requestContext.SendResult(result); - } - catch (Exception e) - { - await requestContext.SendError(e); - } - }); + Content = JsonConvert.SerializeObject(ConvertSqlToNotebook(file.Contents)) + }; + await requestContext.SendResult(result); + } + catch (Exception e) + { + await requestContext.SendError(e); + } } #endregion // Convert Handlers @@ -155,11 +148,11 @@ namespace Microsoft.SqlTools.ServiceLayer.NotebookConvert 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 * cell for the other blocks. - * 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 + * 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 * cells that could break the script */ var multilineComments = tokens @@ -252,7 +245,7 @@ namespace Microsoft.SqlTools.ServiceLayer.NotebookConvert /// /// Converts a Notebook document into a single string that can be inserted into a SQL - /// query. + /// query. /// private static string ConvertNotebookDocToSql(NotebookDocument doc) { diff --git a/src/Microsoft.SqlTools.ServiceLayer/ObjectExplorer/ObjectExplorerService.cs b/src/Microsoft.SqlTools.ServiceLayer/ObjectExplorer/ObjectExplorerService.cs index a3a1fb1c..2cfd7e8a 100644 --- a/src/Microsoft.SqlTools.ServiceLayer/ObjectExplorer/ObjectExplorerService.cs +++ b/src/Microsoft.SqlTools.ServiceLayer/ObjectExplorer/ObjectExplorerService.cs @@ -171,7 +171,7 @@ namespace Microsoft.SqlTools.ServiceLayer.ObjectExplorer { Validate.IsNotNull(nameof(connectionDetails), connectionDetails); Validate.IsNotNull(nameof(context), context); - return await Task.Factory.StartNew(() => + return await Task.Run(() => { string uri = GenerateUri(connectionDetails); @@ -384,13 +384,11 @@ namespace Microsoft.SqlTools.ServiceLayer.ObjectExplorer } - internal async Task ExpandNode(ObjectExplorerSession session, string nodePath, bool forceRefresh = false) + internal Task ExpandNode(ObjectExplorerSession session, string nodePath, bool forceRefresh = false) { - return await Task.Factory.StartNew(() => - { - return QueueExpandNodeRequest(session, nodePath, forceRefresh); - }); + return Task.Run(() => QueueExpandNodeRequest(session, nodePath, forceRefresh)); } + internal ExpandResponse QueueExpandNodeRequest(ObjectExplorerSession session, string nodePath, bool forceRefresh = false) { NodeInfo[] nodes = null; @@ -522,7 +520,7 @@ namespace Microsoft.SqlTools.ServiceLayer.ObjectExplorer await SendSessionFailedNotification(uri, ex.Message); return null; } - } + } private async Task Connect(ConnectParams connectParams, string uri) { @@ -541,7 +539,7 @@ namespace Microsoft.SqlTools.ServiceLayer.ObjectExplorer await SendSessionFailedNotification(uri, result.ErrorMessage); return null; } - + } catch (Exception ex) { @@ -581,7 +579,7 @@ namespace Microsoft.SqlTools.ServiceLayer.ObjectExplorer ExpandTask = task; Task.Run(async () => { - ObjectExplorerTaskResult result = await RunTaskWithTimeout(task, + ObjectExplorerTaskResult result = await RunTaskWithTimeout(task, settings?.ExpandTimeout ?? ObjectExplorerSettings.DefaultExpandTimeout); if (result != null && !result.IsCompleted) @@ -650,7 +648,7 @@ namespace Microsoft.SqlTools.ServiceLayer.ObjectExplorer internal static string GenerateUri(ConnectionDetails details) { return ConnectedBindingQueue.GetConnectionContextKey(details); - } + } public IEnumerable GetApplicableChildFactories(TreeNode item) { @@ -751,7 +749,7 @@ namespace Microsoft.SqlTools.ServiceLayer.ObjectExplorer { bindingQueue.OnUnhandledException -= OnUnhandledException; bindingQueue.Dispose(); - } + } } private async void OnUnhandledException(string queueKey, Exception ex) @@ -819,7 +817,7 @@ namespace Microsoft.SqlTools.ServiceLayer.ObjectExplorer return session; } - + } } diff --git a/src/Microsoft.SqlTools.ServiceLayer/Profiler/ProfilerService.cs b/src/Microsoft.SqlTools.ServiceLayer/Profiler/ProfilerService.cs index ecea4459..782ab19d 100644 --- a/src/Microsoft.SqlTools.ServiceLayer/Profiler/ProfilerService.cs +++ b/src/Microsoft.SqlTools.ServiceLayer/Profiler/ProfilerService.cs @@ -115,59 +115,56 @@ namespace Microsoft.SqlTools.ServiceLayer.Profiler /// internal async Task HandleCreateXEventSessionRequest(CreateXEventSessionParams parameters, RequestContext requestContext) { - await Task.Run(async () => + try { - try + ConnectionInfo connInfo; + ConnectionServiceInstance.TryFindConnection( + parameters.OwnerUri, + out connInfo); + if (connInfo == null) { - ConnectionInfo connInfo; - 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); - } + throw new Exception(SR.ProfilerConnectionNotFound); } - 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))); + } } /// @@ -175,34 +172,31 @@ namespace Microsoft.SqlTools.ServiceLayer.Profiler /// internal async Task HandleStartProfilingRequest(StartProfilingParams parameters, RequestContext requestContext) { - await Task.Run(async () => + try { - try + ConnectionInfo connInfo; + ConnectionServiceInstance.TryFindConnection( + parameters.OwnerUri, + out connInfo); + if (connInfo != null) { - ConnectionInfo connInfo; - ConnectionServiceInstance.TryFindConnection( - parameters.OwnerUri, - out connInfo); - 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); + // 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(); - await requestContext.SendResult(result); - } - else - { - throw new Exception(SR.ProfilerConnectionNotFound); - } + var result = new StartProfilingResult(); + await requestContext.SendResult(result); } - 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))); + } } /// @@ -210,47 +204,44 @@ namespace Microsoft.SqlTools.ServiceLayer.Profiler /// internal async Task HandleStopProfilingRequest(StopProfilingParams parameters, RequestContext 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 - // in progress, add the following retry logic will solve the problem. - int remainingAttempts = 3; - while (true) + try { - try + session.XEventSession.Stop(); + await requestContext.SendResult(new StopProfilingResult { }); + break; + } + catch (InvalidOperationException) + { + remainingAttempts--; + if (remainingAttempts == 0) { - session.XEventSession.Stop(); - await requestContext.SendResult(new StopProfilingResult { }); - break; - } - catch (InvalidOperationException) - { - remainingAttempts--; - if (remainingAttempts == 0) - { - throw; - } - Thread.Sleep(500); + throw; } + 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))); + } } /// @@ -258,19 +249,16 @@ namespace Microsoft.SqlTools.ServiceLayer.Profiler /// internal async Task HandlePauseProfilingRequest(PauseProfilingParams parameters, RequestContext requestContext) { - await Task.Run(async () => + try { - try - { - monitor.PauseViewer(parameters.OwnerUri); + monitor.PauseViewer(parameters.OwnerUri); - await requestContext.SendResult(new PauseProfilingResult { }); - } - catch (Exception e) - { - await requestContext.SendError(new Exception(SR.PauseSessionFailed(e.Message))); - } - }); + await requestContext.SendResult(new PauseProfilingResult { }); + } + catch (Exception e) + { + await requestContext.SendError(new Exception(SR.PauseSessionFailed(e.Message))); + } } /// @@ -278,31 +266,28 @@ namespace Microsoft.SqlTools.ServiceLayer.Profiler /// internal async Task HandleGetXEventSessionsRequest(GetXEventSessionsParams parameters, RequestContext 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(); - ConnectionInfo connInfo; - ConnectionServiceInstance.TryFindConnection( - parameters.OwnerUri, - out connInfo); - if (connInfo == null) - { - await requestContext.SendError(new Exception(SR.ProfilerConnectionNotFound)); - } - else - { - List sessions = GetXEventSessionList(parameters.OwnerUri, connInfo); - result.Sessions = sessions; - await requestContext.SendResult(result); - } + await requestContext.SendError(new Exception(SR.ProfilerConnectionNotFound)); } - catch (Exception e) + else { - await requestContext.SendError(e); + List sessions = GetXEventSessionList(parameters.OwnerUri, connInfo); + result.Sessions = sessions; + await requestContext.SendResult(result); } - }); + } + catch (Exception e) + { + await requestContext.SendError(e); + } } /// @@ -310,18 +295,14 @@ namespace Microsoft.SqlTools.ServiceLayer.Profiler /// internal async Task HandleDisconnectSessionRequest(DisconnectSessionParams parameters, RequestContext requestContext) { - await Task.Run(async () => - { - try - { - ProfilerSession session; - monitor.StopMonitoringSession(parameters.OwnerUri, out session); - } - catch (Exception e) - { - await requestContext.SendError(e); - } - }); + try + { + monitor.StopMonitoringSession(parameters.OwnerUri, out _); + } + catch (Exception e) + { + await requestContext.SendError(e); + } } /// diff --git a/src/Microsoft.SqlTools.ServiceLayer/QueryExecution/QueryExecutionService.cs b/src/Microsoft.SqlTools.ServiceLayer/QueryExecution/QueryExecutionService.cs index 7a6325fa..d59b079e 100644 --- a/src/Microsoft.SqlTools.ServiceLayer/QueryExecution/QueryExecutionService.cs +++ b/src/Microsoft.SqlTools.ServiceLayer/QueryExecution/QueryExecutionService.cs @@ -707,7 +707,7 @@ namespace Microsoft.SqlTools.ServiceLayer.QueryExecution /// /// /// - public async Task HandleDidCloseTextDocumentNotification( + public Task HandleDidCloseTextDocumentNotification( string uri, ScriptFile scriptFile, EventContext eventContext) @@ -725,7 +725,8 @@ namespace Microsoft.SqlTools.ServiceLayer.QueryExecution { Logger.Write(TraceEventType.Error, "Unknown error " + ex.ToString()); } - await Task.FromResult(true); + + return Task.CompletedTask; } #endregion @@ -765,7 +766,7 @@ namespace Microsoft.SqlTools.ServiceLayer.QueryExecution if (this.ActiveQueryExecutionSettings.TryGetValue(executeParams.OwnerUri, out settings)) { // 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 ExecutionPlanOptions executionPlanOptions = executeParams.ExecutionPlanOptions; if (settings.IncludeActualExecutionPlanXml) @@ -900,7 +901,7 @@ namespace Microsoft.SqlTools.ServiceLayer.QueryExecution // Setup the ResultSet updated callback ResultSet.ResultSetAsyncEventHandler resultUpdatedCallback = async r => { - + //Generating and sending an execution plan graphs if it is requested. List plans = null; string planErrors = ""; diff --git a/src/Microsoft.SqlTools.ServiceLayer/Security/SecurityService.cs b/src/Microsoft.SqlTools.ServiceLayer/Security/SecurityService.cs index 9d4f6f68..d6a7ee0b 100644 --- a/src/Microsoft.SqlTools.ServiceLayer/Security/SecurityService.cs +++ b/src/Microsoft.SqlTools.ServiceLayer/Security/SecurityService.cs @@ -88,7 +88,7 @@ namespace Microsoft.SqlTools.ServiceLayer.Security /// Handle request to create a credential /// internal async Task HandleCreateCredentialRequest(CreateCredentialParams parameters, RequestContext requestContext) - { + { var result = await ConfigureCredential(parameters.OwnerUri, parameters.Credential, ConfigAction.Create, @@ -106,7 +106,7 @@ namespace Microsoft.SqlTools.ServiceLayer.Security /// Handle request to update a credential /// internal async Task HandleUpdateCredentialRequest(UpdateCredentialParams parameters, RequestContext requestContext) - { + { var result = await ConfigureCredential(parameters.OwnerUri, parameters.Credential, ConfigAction.Update, @@ -137,69 +137,64 @@ namespace Microsoft.SqlTools.ServiceLayer.Security }); } - + /// /// Handle request to get all credentials /// internal async Task HandleGetCredentialsRequest(GetCredentialsParams parameters, RequestContext requestContext) { - await Task.Run(async () => + var result = new GetCredentialsResult(); + try { - var result = new GetCredentialsResult(); - try - { - 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(); - } + ConnectionInfo connInfo; + ConnectionServiceInstance.TryFindConnection(parameters.OwnerUri, out connInfo); + CDataContainer dataContainer = CDataContainer.CreateDataContainer(connInfo, databaseExists: true); - 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); } - - /// /// Disposes the service /// public void Dispose() { if (!disposed) - { + { disposed = true; } } #region "Helpers" - internal async Task> ConfigureCredential( + internal Task> ConfigureCredential( string ownerUri, CredentialInfo credential, ConfigAction configAction, RunType runType) { - return await Task>.Run(() => + return Task>.Run(() => { try { @@ -211,7 +206,7 @@ namespace Microsoft.SqlTools.ServiceLayer.Security { var executionHandler = new ExecutonHandler(actions); executionHandler.RunNow(runType, this); - } + } return new Tuple(true, string.Empty); } diff --git a/src/Microsoft.SqlTools.ServiceLayer/TaskServices/TaskOperationHelper.cs b/src/Microsoft.SqlTools.ServiceLayer/TaskServices/TaskOperationHelper.cs index 50b69630..2153549b 100644 --- a/src/Microsoft.SqlTools.ServiceLayer/TaskServices/TaskOperationHelper.cs +++ b/src/Microsoft.SqlTools.ServiceLayer/TaskServices/TaskOperationHelper.cs @@ -18,7 +18,7 @@ namespace Microsoft.SqlTools.ServiceLayer.TaskServices /// /// Sql Task /// Task Result - public static async Task ExecuteTaskAsync(SqlTask sqlTask) + public static Task ExecuteTaskAsync(SqlTask sqlTask) { sqlTask.AddMessage(SR.TaskInProgress, SqlTaskStatus.InProgress, true); ITaskOperation taskOperation = sqlTask.TaskMetadata.TaskOperation as ITaskOperation; @@ -27,8 +27,8 @@ namespace Microsoft.SqlTools.ServiceLayer.TaskServices if (taskOperation != null) { taskOperation.SqlTask = sqlTask; - - return await Task.Factory.StartNew(() => + + return Task.Run(() => { TaskResult result = new TaskResult(); try @@ -66,21 +66,21 @@ namespace Microsoft.SqlTools.ServiceLayer.TaskServices taskResult.TaskStatus = SqlTaskStatus.Failed; } - return taskResult; + return Task.FromResult(taskResult); } /// /// Async method to cancel the operations /// - public static async Task CancelTaskAsync(SqlTask sqlTask) + public static Task CancelTaskAsync(SqlTask sqlTask) { ITaskOperation taskOperation = sqlTask.TaskMetadata.TaskOperation as ITaskOperation; TaskResult taskResult = null; if (taskOperation != null) { - - return await Task.Factory.StartNew(() => + + return Task.Run(() => { try { @@ -107,7 +107,7 @@ namespace Microsoft.SqlTools.ServiceLayer.TaskServices taskResult.TaskStatus = SqlTaskStatus.Failed; } - return taskResult; + return Task.FromResult(taskResult); } } } diff --git a/src/Microsoft.SqlTools.ServiceLayer/Workspace/WorkspaceService.cs b/src/Microsoft.SqlTools.ServiceLayer/Workspace/WorkspaceService.cs index 792e6226..773803f9 100644 --- a/src/Microsoft.SqlTools.ServiceLayer/Workspace/WorkspaceService.cs +++ b/src/Microsoft.SqlTools.ServiceLayer/Workspace/WorkspaceService.cs @@ -116,7 +116,7 @@ namespace Microsoft.SqlTools.ServiceLayer.Workspace /// List of callbacks to call when a text document is closed /// private List TextDocCloseCallbacks { get; set; } - + #endregion @@ -132,9 +132,9 @@ namespace Microsoft.SqlTools.ServiceLayer.Workspace serviceHost.SetEventHandler(DidOpenTextDocumentNotification.Type, HandleDidOpenTextDocumentNotification); serviceHost.SetEventHandler(DidCloseTextDocumentNotification.Type, HandleDidCloseTextDocumentNotification); serviceHost.SetEventHandler(DidChangeConfigurationNotification.Type, HandleDidChangeConfigurationNotification); - + // 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"); @@ -142,11 +142,12 @@ namespace Microsoft.SqlTools.ServiceLayer.Workspace { Workspace.WorkspacePath = parameters.RootPath; } - await Task.FromResult(0); + + return Task.CompletedTask; }); // 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"); @@ -155,7 +156,8 @@ namespace Microsoft.SqlTools.ServiceLayer.Workspace Workspace.Dispose(); 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 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)); ScriptFile changedFile = Workspace.GetFile(fileUri); @@ -258,7 +260,7 @@ namespace Microsoft.SqlTools.ServiceLayer.Workspace 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); if (openedFile == null) { @@ -287,7 +289,7 @@ namespace Microsoft.SqlTools.ServiceLayer.Workspace { Logger.Write(TraceEventType.Verbose, "HandleDidCloseTextDocumentNotification"); - if (IsScmEvent(closeParams.TextDocument.Uri)) + if (IsScmEvent(closeParams.TextDocument.Uri)) { 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 return; } - } + } #endregion @@ -348,7 +350,7 @@ namespace Microsoft.SqlTools.ServiceLayer.Workspace /// Switch from 0-based offsets to 1 based offsets /// /// - /// + /// private static FileChange GetFileChangeDetails(Range changeRange, string insertString) { // 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 }; } - + internal static bool IsScmEvent(string filePath) { // if the URI is prefixed with git: then we want to skip processing that file