private async Task HandleShutdownRequest( RequestContext <object> requestContext) { // Allow the implementor to shut down gracefully await this.Shutdown(); await requestContext.SendResult(new object()); }
/// <summary> /// Handles a restore request /// </summary> internal async Task HandleCancelRestorePlanRequest( RestoreParams restoreParams, RequestContext <bool> requestContext) { bool result = false; try { result = this.restoreDatabaseService.CancelRestorePlan(restoreParams); await requestContext.SendResult(result); } catch (Exception ex) { Logger.Write(LogLevel.Error, "Failed to cancel restore session. error: " + ex.Message); await requestContext.SendResult(result); } }
protected async Task HandleContinueRequest( object continueParams, RequestContext <object> requestContext) { editorSession.DebugService.Continue(); await requestContext.SendResult(null); }
protected async Task HandleSetExceptionBreakpointsRequest( SetExceptionBreakpointsRequestArguments setExceptionBreakpointsParams, RequestContext <object> requestContext) { // TODO: Handle this appropriately await requestContext.SendResult(null); }
protected async Task HandleStepInRequest( object stepInParams, RequestContext <object> requestContext) { editorSession.DebugService.StepIn(); await requestContext.SendResult(null); }
protected async Task HandleNextRequest( object nextParams, RequestContext <object> requestContext) { editorSession.DebugService.StepOver(); await requestContext.SendResult(null); }
private Task HandleShutdownRequest( object shutdownParams, RequestContext <object> requestContext) { // Allow the implementor to shut down gracefully this.Shutdown(); return(requestContext.SendResult(new object())); }
private Task HandleShutdownRequest( object shutdownParams, RequestContext<object> requestContext) { // Allow the implementor to shut down gracefully this.Shutdown(); return requestContext.SendResult(new object()); }
public async Task ServiceExecutesReplCommandAndReceivesInputPrompt() { OutputReader outputReader = new OutputReader(this.protocolClient); string promptScript = @" $NameField = New-Object System.Management.Automation.Host.FieldDescription ""Name"" $NameField.SetParameterType([System.String]) $fields = [System.Management.Automation.Host.FieldDescription[]]($NameField) $host.ui.Prompt($null, $null, $fields)"; Task <Tuple <ShowInputPromptRequest, RequestContext <ShowInputPromptResponse> > > inputPromptTask = this.WaitForRequest(ShowInputPromptRequest.Type); // Execute the script but don't await the task yet because // the choice prompt will block execution from completing Task <EvaluateResponseBody> evaluateTask = this.SendRequest( EvaluateRequest.Type, new EvaluateRequestArguments { Expression = promptScript, Context = "repl" }); // Wait for the input prompt request and check expected values Tuple <ShowInputPromptRequest, RequestContext <ShowInputPromptResponse> > requestResponseContext = await inputPromptTask; ShowInputPromptRequest showInputPromptRequest = requestResponseContext.Item1; RequestContext <ShowInputPromptResponse> requestContext = requestResponseContext.Item2; Assert.Equal("Name", showInputPromptRequest.Name); // Respond to the prompt request await requestContext.SendResult( new ShowInputPromptResponse { ResponseText = "John" }); // Skip the initial script lines (4 script lines plus 2 blank lines) string[] scriptLines = await outputReader.ReadLines(6); // Verify the first line Assert.Equal("Name: John", await outputReader.ReadLine()); // Verify the rest of the output string[] outputLines = await outputReader.ReadLines(4); Assert.Equal("", outputLines[0]); Assert.Equal("Key Value", outputLines[1]); Assert.Equal("--- -----", outputLines[2]); Assert.Equal("Name John ", outputLines[3]); // Wait for execution to complete await evaluateTask; }
/// <summary> /// Handle request to start a profiling session /// </summary> internal async Task HandleCreateXEventSessionRequest(CreateXEventSessionParams parameters, RequestContext <CreateXEventSessionResult> requestContext) { await Task.Run(async() => { try { 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); } } catch (Exception e) { await requestContext.SendError(new Exception(SR.CreateSessionFailed(e.Message))); } }); }
protected async Task HandleLaunchRequest( LaunchRequestArguments launchParams, RequestContext <object> requestContext) { // Set the working directory for the PowerShell runspace to the cwd passed in via launch.json. // In case that is null, use the the folder of the script to be executed. If the resulting // working dir path is a file path then extract the directory and use that. string workingDir = launchParams.Cwd ?? launchParams.Program; workingDir = PowerShellContext.UnescapePath(workingDir); try { if ((File.GetAttributes(workingDir) & FileAttributes.Directory) != FileAttributes.Directory) { workingDir = Path.GetDirectoryName(workingDir); } } catch (Exception ex) { Logger.Write(LogLevel.Error, "cwd path is invalid: " + ex.Message); workingDir = Environment.CurrentDirectory; } editorSession.PowerShellContext.SetWorkingDirectory(workingDir); Logger.Write(LogLevel.Verbose, "Working dir set to: " + workingDir); // Prepare arguments to the script - if specified string arguments = null; if ((launchParams.Args != null) && (launchParams.Args.Length > 0)) { arguments = string.Join(" ", launchParams.Args); Logger.Write(LogLevel.Verbose, "Script arguments are: " + arguments); } // We may not actually launch the script in response to this // request unless it comes after the configurationDone request. // If the launch request comes first, then stash the launch // params so that the subsequent configurationDone request handler // can launch the script. this.noDebug = launchParams.NoDebug; this.scriptPathToLaunch = launchParams.Program; this.arguments = arguments; // The order of debug protocol messages apparently isn't as guaranteed as we might like. // Need to be able to handle the case where we get the launch request after the // configurationDone request. if (this.isConfigurationDoneRequestComplete) { this.LaunchScript(requestContext); } this.isLaunchRequestComplete = true; await requestContext.SendResult(null); }
protected async Task HandleEvaluateRequest( EvaluateRequestArguments evaluateParams, RequestContext <EvaluateResponseBody> requestContext) { string valueString = null; int variableId = 0; bool isFromRepl = string.Equals( evaluateParams.Context, "repl", StringComparison.CurrentCultureIgnoreCase); if (isFromRepl) { // Check for special commands if (string.Equals("!ctrlc", evaluateParams.Expression, StringComparison.CurrentCultureIgnoreCase)) { editorSession.PowerShellContext.AbortExecution(); } else if (string.Equals("!break", evaluateParams.Expression, StringComparison.CurrentCultureIgnoreCase)) { editorSession.DebugService.Break(); } else { // Send the input through the console service editorSession.ConsoleService.ExecuteCommand( evaluateParams.Expression, false); } } else { VariableDetails result = await editorSession.DebugService.EvaluateExpression( evaluateParams.Expression, evaluateParams.FrameId, isFromRepl); if (result != null) { valueString = result.ValueString; variableId = result.IsExpandable ? result.Id : 0; } } await requestContext.SendResult( new EvaluateResponseBody { Result = valueString, VariablesReference = variableId }); }
internal async Task HandleFindNodesRequest(FindNodesParams findNodesParams, RequestContext <FindNodesResponse> context) { var foundNodes = FindNodes(findNodesParams.SessionId, findNodesParams.Type, findNodesParams.Schema, findNodesParams.Name, findNodesParams.Database, findNodesParams.ParentObjectNames); if (foundNodes == null) { foundNodes = new List <TreeNode>(); } await context.SendResult(new FindNodesResponse { Nodes = foundNodes.Select(node => node.ToNodeInfo()).ToList() }); }
/// <summary> /// Handles a request to dispose of this query /// </summary> internal async Task HandleDisposeRequest(QueryDisposeParams disposeParams, RequestContext <QueryDisposeResult> requestContext) { // Setup action for success and failure Func <Task> successAction = () => requestContext.SendResult(new QueryDisposeResult()); Func <string, Task> failureAction = message => requestContext.SendError(message); // Use the inter-service dispose functionality await InterServiceDisposeQuery(disposeParams.OwnerUri, successAction, failureAction); }
private static async Task HandleHoverRequest( TextDocumentPosition textDocumentPosition, RequestContext <Hover> requestContext) { // check if Quick Info hover tooltips are enabled if (WorkspaceService <SqlToolsSettings> .Instance.CurrentSettings.IsQuickInfoEnabled) { var scriptFile = WorkspaceService <SqlToolsSettings> .Instance.Workspace.GetFile( textDocumentPosition.TextDocument.Uri); var hover = LanguageService.Instance.GetHoverItem(textDocumentPosition, scriptFile); if (hover != null) { await requestContext.SendResult(hover); } } await requestContext.SendResult(new Hover()); }
/// <summary> /// Handles request to execute a selection of a document in the workspace service /// </summary> internal Task HandleExecuteRequest(ExecuteRequestParamsBase executeParams, RequestContext <ExecuteRequestResult> requestContext) { // Setup actions to perform upon successful start and on failure to start Func <Task> queryCreationAction = () => requestContext.SendResult(new ExecuteRequestResult()); Func <string, Task> queryFailAction = requestContext.SendError; // Use the internal handler to launch the query return(InterServiceExecuteQuery(executeParams, requestContext, queryCreationAction, queryFailAction)); }
/// <summary> /// Process request to save a resultSet to a file in CSV format /// </summary> internal async Task HandleSaveResultsAsCsvRequest(SaveResultsAsCsvRequestParams saveParams, RequestContext <SaveResultRequestResult> requestContext) { // retrieve query for OwnerUri Query result; if (!ActiveQueries.TryGetValue(saveParams.OwnerUri, out result)) { await requestContext.SendResult(new SaveResultRequestResult { Messages = SR.QueryServiceRequestsNoQuery }); return; } ResultSet selectedResultSet = result.Batches[saveParams.BatchIndex].ResultSets[saveParams.ResultSetIndex]; if (!selectedResultSet.IsBeingDisposed) { // Create SaveResults object and add success and error handlers to respective events SaveResults saveAsCsv = new SaveResults(); SaveResults.AsyncSaveEventHandler successHandler = async message => { selectedResultSet.RemoveSaveTask(saveParams.FilePath); await requestContext.SendResult(new SaveResultRequestResult { Messages = message }); }; saveAsCsv.SaveCompleted += successHandler; SaveResults.AsyncSaveEventHandler errorHandler = async message => { selectedResultSet.RemoveSaveTask(saveParams.FilePath); await requestContext.SendError(new SaveResultRequestError { message = message }); }; saveAsCsv.SaveFailed += errorHandler; saveAsCsv.SaveResultSetAsCsv(saveParams, requestContext, result); // Associate the ResultSet with the save task selectedResultSet.AddSaveTask(saveParams.FilePath, saveAsCsv.SaveTask); } }
/// <summary> /// Handle request to get the alerts list /// </summary> internal async Task HandleAgentAlertsRequest(AgentAlertsParams parameters, RequestContext <AgentAlertsResult> requestContext) { await Task.Run(async() => { var result = new AgentAlertsResult(); try { 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) { 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 }; } result.Alerts = alerts; result.Success = true; } catch (Exception ex) { result.Success = false; result.ErrorMessage = ex.ToString(); } await requestContext.SendResult(result); }); }
protected async Task HandleEvaluateRequest( EvaluateRequestArguments evaluateParams, RequestContext <EvaluateResponseBody> requestContext) { string valueString = null; int variableId = 0; bool isFromRepl = string.Equals( evaluateParams.Context, "repl", StringComparison.CurrentCultureIgnoreCase); if (isFromRepl) { // TODO: Do we send the input through the command handler? // Send the input through the console service var notAwaited = this.editorSession .PowerShellContext .ExecuteScriptString(evaluateParams.Expression, false, true) .ConfigureAwait(false); } else { VariableDetails result = null; // VS Code might send this request after the debugger // has been resumed, return an empty result in this case. if (editorSession.PowerShellContext.IsDebuggerStopped) { result = await editorSession.DebugService.EvaluateExpression( evaluateParams.Expression, evaluateParams.FrameId, isFromRepl); } if (result != null) { valueString = result.ValueString; variableId = result.IsExpandable ? result.Id : 0; } } await requestContext.SendResult( new EvaluateResponseBody { Result = valueString, VariablesReference = variableId }); }
/// <summary> /// Handles schema compare save SCMP request /// </summary> /// <returns></returns> public async Task HandleSchemaCompareSaveScmpRequest(SchemaCompareSaveScmpParams parameters, RequestContext <ResultStatus> requestContext) { try { ConnectionInfo sourceConnInfo; ConnectionInfo targetConnInfo; ConnectionServiceInstance.TryFindConnection(parameters.SourceEndpointInfo.OwnerUri, out sourceConnInfo); ConnectionServiceInstance.TryFindConnection(parameters.TargetEndpointInfo.OwnerUri, out targetConnInfo); CurrentSchemaCompareTask = Task.Run(async() => { SchemaCompareSaveScmpOperation operation = null; try { operation = new SchemaCompareSaveScmpOperation(parameters, sourceConnInfo, targetConnInfo); operation.Execute(parameters.TaskExecutionMode); await requestContext.SendResult(new ResultStatus() { Success = true, ErrorMessage = operation.ErrorMessage, }); } catch (Exception e) { Logger.Write(TraceEventType.Error, "Failed to save scmp file. Error: " + e); await requestContext.SendResult(new SchemaCompareResult() { OperationId = operation != null ? operation.OperationId : null, Success = false, ErrorMessage = operation == null ? e.Message : operation.ErrorMessage, }); } }); } catch (Exception e) { await requestContext.SendError(e); } }
private async Task HandleInitializeRequest( object shutdownParams, RequestContext <object> requestContext) { // Send the Initialized event first so that we get breakpoints await requestContext.SendEvent( InitializedEvent.Type, null); // Now send the Initialize response to continue setup await requestContext.SendResult(new object()); }
private async Task HandleInitializeRequest( object shutdownParams, RequestContext<object> requestContext) { // Send the Initialized event first so that we get breakpoints await requestContext.SendEvent( InitializedEvent.Type, null); // Now send the Initialize response to continue setup await requestContext.SendResult(new object()); }
/// <summary> /// Runs the async task that performs the scripting operation. /// </summary> private void RunSelectTask(ConnectionInfo connInfo, ScriptingParams parameters, RequestContext <ScriptingResult> requestContext) { ConnectionServiceInstance.ConnectionQueue.QueueBindingOperation( key: ConnectionServiceInstance.ConnectionQueue.AddConnectionContext(connInfo, "Scripting"), bindingTimeout: ScriptingOperationTimeout, bindOperation: (bindingContext, cancelToken) => { string script = string.Empty; ScriptingObject scriptingObject = parameters.ScriptingObjects[0]; try { Server server = new Server(bindingContext.ServerConnection); server.DefaultTextMode = true; // build object URN SqlConnectionStringBuilder connectionStringBuilder = new SqlConnectionStringBuilder(parameters.ConnectionString); Urn objectUrn = BuildScriptingObjectUrn(server, connectionStringBuilder, scriptingObject); string typeName = objectUrn.GetNameForType(scriptingObject.Type); // select from service broker if (string.Compare(typeName, "ServiceBroker", StringComparison.CurrentCultureIgnoreCase) == 0) { script = Scripter.SelectAllValuesFromTransmissionQueue(objectUrn); } // select from queues else if (string.Compare(typeName, "Queues", StringComparison.CurrentCultureIgnoreCase) == 0 || string.Compare(typeName, "SystemQueues", StringComparison.CurrentCultureIgnoreCase) == 0) { script = Scripter.SelectAllValues(objectUrn); } // select from table or view else { Database db = server.Databases[connectionStringBuilder.InitialCatalog]; bool isDw = db.IsSqlDw; script = new Scripter().SelectFromTableOrView(server, objectUrn, isDw); } // send script result to client requestContext.SendResult(new ScriptingResult { Script = script }).Wait(); } catch (Exception e) { requestContext.SendError(e).Wait(); } return(null); }); }
public async Task HandleAddRegisteredServerRequest(AddRegisteredServerParams cmsCreateParams, RequestContext <bool> requestContext) { Logger.Write(TraceEventType.Verbose, "HandleAddRegisteredServerRequest"); try { CmsTask = Task.Run(async() => { try { ServerConnection serverConn = ValidateAndCreateConnection(cmsCreateParams.ParentOwnerUri); if (serverConn != null) { // Get Current Reg Servers RegisteredServersStore store = new RegisteredServersStore(serverConn); ServerGroup parentGroup = NavigateToServerGroup(store, cmsCreateParams.RelativePath); RegisteredServerCollection servers = parentGroup.RegisteredServers; // Add the new server (intentionally not cheching existence to reuse the exception message) RegisteredServer registeredServer = new RegisteredServer(parentGroup, cmsCreateParams.RegisteredServerName); registeredServer.Description = cmsCreateParams.RegisteredServerDescription; registeredServer.ConnectionString = serverConn.ConnectionString; registeredServer.ServerName = cmsCreateParams.RegisteredServerConnectionDetails.ServerName; registeredServer.Create(); await requestContext.SendResult(true); } else { await requestContext.SendResult(false); } } catch (Exception e) { await requestContext.SendError(e); } }); } catch (Exception e) { await requestContext.SendError(e); } }
private async Task HandleAssessmentRequest <TResult>( RequestContext <AssessmentResult <TResult> > requestContext, AssessmentParams requestParams, Func <SqlObjectLocator, Task <List <TResult> > > assessmentFunction) where TResult : AssessmentItemInfo { try { string randomUri = Guid.NewGuid().ToString(); // get connection if (!ConnectionService.TryFindConnection(requestParams.OwnerUri, out var connInfo)) { await requestContext.SendError(SR.SqlAssessmentQueryInvalidOwnerUri); return; } ConnectParams connectParams = new ConnectParams { OwnerUri = randomUri, Connection = connInfo.ConnectionDetails, Type = ConnectionType.Default }; if (!connInfo.TryGetConnection(ConnectionType.Default, out var connection)) { await requestContext.SendError(SR.SqlAssessmentConnectingError); } var workTask = CallAssessmentEngine <TResult>( requestParams, connectParams, randomUri, assessmentFunction) .ContinueWith(async tsk => { await requestContext.SendResult(tsk.Result); }); ActiveRequests.TryAdd(randomUri, workTask); } catch (Exception ex) { if (ex is StackOverflowException || ex is OutOfMemoryException) { throw; } await requestContext.SendError(ex.ToString()); } }
public async Task ServiceExecutesReplCommandAndReceivesChoicePrompt() { OutputReader outputReader = new OutputReader(this.messageHandlers); // Send the configuration request to initiate the command loop await this.SendConfigurationRequest(outputReader); string choiceScript = @" $caption = ""Test Choice""; $message = ""Make a selection""; $choiceA = New-Object System.Management.Automation.Host.ChoiceDescription ""&Apple"",""Help for Apple""; $choiceB = New-Object System.Management.Automation.Host.ChoiceDescription ""Banana"",""Help for Banana""; $choices = [System.Management.Automation.Host.ChoiceDescription[]]($choiceA,$choiceB); $host.ui.PromptForChoice($caption, $message, $choices, 1)"; Task <Tuple <ShowChoicePromptRequest, RequestContext <ShowChoicePromptResponse> > > choicePromptTask = this.WaitForRequest(ShowChoicePromptRequest.Type); // Execute the script but don't await the task yet because // the choice prompt will block execution from completing Task <EvaluateResponseBody> evaluateTask = this.SendRequest( EvaluateRequest.Type, new EvaluateRequestArguments { Expression = choiceScript, Context = "repl" }); // Wait for the choice prompt request and check expected values Tuple <ShowChoicePromptRequest, RequestContext <ShowChoicePromptResponse> > requestResponseContext = await choicePromptTask; ShowChoicePromptRequest showChoicePromptRequest = requestResponseContext.Item1; RequestContext <ShowChoicePromptResponse> requestContext = requestResponseContext.Item2; Assert.Equal(1, showChoicePromptRequest.DefaultChoices[0]); // Respond to the prompt request await requestContext.SendResult( new ShowChoicePromptResponse { ResponseText = "a" }); // Skip the initial script and prompt lines (6 script lines plus 3 prompt lines) string[] outputLines = await outputReader.ReadLines(9); // Wait for the selection to appear as output await evaluateTask; Assert.Equal("0", await outputReader.ReadLine()); }
internal async Task HandleUpdateAgentProxyRequest(UpdateAgentProxyParams parameters, RequestContext <UpdateAgentProxyResult> requestContext) { bool succeeded = await ConfigureAgentProxy( parameters.OwnerUri, parameters.OriginalProxyName, parameters.Proxy, AgentConfigAction.Update); await requestContext.SendResult(new UpdateAgentProxyResult() { Succeeded = succeeded }); }
private async Task HandleSignatureHelpRequest( TextDocumentPositionParams textDocumentPositionParams, RequestContext <SignatureHelp> requestContext) { var document = GetDocument(textDocumentPositionParams.TextDocument); var position = ConvertPosition(document, textDocumentPositionParams.Position); var signatureHelpHandler = document.Workspace.Services.GetService <SignatureHelpHandler>(); var result = await signatureHelpHandler.GetResultAsync(document, position, CancellationToken.None); await requestContext.SendResult(result); }
internal async Task HandleDeleteAgentProxyRequest(DeleteAgentProxyParams parameters, RequestContext <DeleteAgentProxyResult> requestContext) { bool succeeded = await ConfigureAgentProxy( parameters.OwnerUri, parameters.Proxy.AccountName, parameters.Proxy, AgentConfigAction.Drop); await requestContext.SendResult(new DeleteAgentProxyResult() { Succeeded = succeeded }); }
/// <summary> /// Handle request to pause a profiling session /// </summary> internal async Task HandlePauseProfilingRequest(PauseProfilingParams parameters, RequestContext <PauseProfilingResult> requestContext) { try { monitor.PauseViewer(parameters.OwnerUri); await requestContext.SendResult(new PauseProfilingResult {}); } catch (Exception e) { await requestContext.SendError(e); } }
/// <summary> /// Handle request to delete a credential /// </summary> internal async Task HandleDeleteCredentialRequest(DeleteCredentialParams parameters, RequestContext <ResultStatus> requestContext) { var result = await ConfigureCredential(parameters.OwnerUri, parameters.Credential, ConfigAction.Drop, RunType.RunNow); await requestContext.SendResult(new ResultStatus() { Success = result.Item1, ErrorMessage = result.Item2 }); }
protected async Task HandleInitializeRequest( InitializeRequestArguments initializeParams, EditorSession editorSession, RequestContext <object, object> requestContext) { // Send the Initialized event first so that we get breakpoints await requestContext.SendEvent( InitializedEvent.Type, null); // Now send the Initialize response to continue setup await requestContext.SendResult(new object()); }
protected async Task HandleEvaluateRequest( DebugAdapterMessages.EvaluateRequestArguments evaluateParams, RequestContext<DebugAdapterMessages.EvaluateResponseBody> requestContext) { var results = await this.editorSession.PowerShellContext.ExecuteScriptString( evaluateParams.Expression, true, true); // Return an empty result since the result value is irrelevant // for this request in the LanguageServer await requestContext.SendResult( new DebugAdapterMessages.EvaluateResponseBody { Result = "", VariablesReference = 0 }); }
protected async Task HandleLaunchRequest( LaunchRequestArguments launchParams, RequestContext<object> requestContext) { // Set the working directory for the PowerShell runspace to the cwd passed in via launch.json. // In case that is null, use the the folder of the script to be executed. If the resulting // working dir path is a file path then extract the directory and use that. string workingDir = launchParams.Cwd ?? launchParams.Program; try { if ((File.GetAttributes(workingDir) & FileAttributes.Directory) != FileAttributes.Directory) { workingDir = Path.GetDirectoryName(workingDir); } } catch (Exception ex) { Logger.Write(LogLevel.Error, "cwd path is bad: " + ex.Message); workingDir = Environment.CurrentDirectory; } var setWorkingDirCommand = new PSCommand(); setWorkingDirCommand.AddCommand(@"Microsoft.PowerShell.Management\Set-Location") .AddParameter("LiteralPath", workingDir); await editorSession.PowerShellContext.ExecuteCommand(setWorkingDirCommand); Logger.Write(LogLevel.Verbose, "Working dir set to: " + workingDir); // Prepare arguments to the script - if specified string arguments = null; if ((launchParams.Args != null) && (launchParams.Args.Length > 0)) { arguments = string.Join(" ", launchParams.Args); Logger.Write(LogLevel.Verbose, "Script arguments are: " + arguments); } // Execute the given PowerShell script and send the response. // Note that we aren't waiting for execution to complete here // because the debugger could stop while the script executes. Task executeTask = editorSession.PowerShellContext .ExecuteScriptAtPath(launchParams.Program, arguments) .ContinueWith( async (t) => { Logger.Write(LogLevel.Verbose, "Execution completed, terminating..."); await requestContext.SendEvent( TerminatedEvent.Type, null); // Stop the server this.Stop(); }); await requestContext.SendResult(null); }
protected async Task HandleInitializeRequest( InitializeRequest initializeParams, RequestContext<InitializeResult> requestContext) { // Grab the workspace path from the parameters editorSession.Workspace.WorkspacePath = initializeParams.RootPath; await requestContext.SendResult( new InitializeResult { Capabilities = new ServerCapabilities { TextDocumentSync = TextDocumentSyncKind.Incremental, DefinitionProvider = true, ReferencesProvider = true, DocumentHighlightProvider = true, DocumentSymbolProvider = true, WorkspaceSymbolProvider = true, HoverProvider = true, CompletionProvider = new CompletionOptions { ResolveProvider = true, TriggerCharacters = new string[] { ".", "-", ":", "\\" } }, SignatureHelpProvider = new SignatureHelpOptions { TriggerCharacters = new string[] { " " } // TODO: Other characters here? } } }); }
protected async Task HandleDefinitionRequest( TextDocumentPosition textDocumentPosition, RequestContext<Location[]> requestContext) { ScriptFile scriptFile = editorSession.Workspace.GetFile( textDocumentPosition.Uri); SymbolReference foundSymbol = editorSession.LanguageService.FindSymbolAtLocation( scriptFile, textDocumentPosition.Position.Line + 1, textDocumentPosition.Position.Character + 1); List<Location> definitionLocations = new List<Location>(); GetDefinitionResult definition = null; if (foundSymbol != null) { definition = await editorSession.LanguageService.GetDefinitionOfSymbol( scriptFile, foundSymbol, editorSession.Workspace); if (definition != null) { definitionLocations.Add( new Location { Uri = new Uri(definition.FoundDefinition.FilePath).AbsoluteUri, Range = GetRangeFromScriptRegion(definition.FoundDefinition.ScriptRegion) }); } } await requestContext.SendResult(definitionLocations.ToArray()); }
protected async Task HandleContinueRequest( object continueParams, RequestContext<object> requestContext) { editorSession.DebugService.Continue(); await requestContext.SendResult(null); }
protected async Task HandleEvaluateRequest( EvaluateRequestArguments evaluateParams, RequestContext<EvaluateResponseBody> requestContext) { bool isFromRepl = string.Equals( evaluateParams.Context, "repl", StringComparison.InvariantCultureIgnoreCase); VariableDetails result = await editorSession.DebugService.EvaluateExpression( evaluateParams.Expression, evaluateParams.FrameId, isFromRepl); string valueString = null; int variableId = 0; if (result != null) { valueString = result.ValueString; variableId = result.IsExpandable ? result.Id : 0; } await requestContext.SendResult( new EvaluateResponseBody { Result = valueString, VariablesReference = variableId }); }
protected async Task HandleLaunchRequest( LaunchRequestArguments launchParams, RequestContext<object> requestContext) { // Execute the given PowerShell script and send the response. // Note that we aren't waiting for execution to complete here // because the debugger could stop while the script executes. Task executeTask = editorSession.PowerShellContext .ExecuteScriptAtPath(launchParams.Program) .ContinueWith( async (t) => { Logger.Write(LogLevel.Verbose, "Execution completed, terminating..."); await requestContext.SendEvent( TerminatedEvent.Type, null); // Stop the server this.Stop(); }); await requestContext.SendResult(null); }
protected async Task HandleScopesRequest( ScopesRequestArguments scopesParams, RequestContext<ScopesResponseBody> requestContext) { VariableScope[] variableScopes = editorSession.DebugService.GetVariableScopes( scopesParams.FrameId); await requestContext.SendResult( new ScopesResponseBody { Scopes = variableScopes .Select(Scope.Create) .ToArray() }); }
protected async Task HandleVariablesRequest( VariablesRequestArguments variablesParams, RequestContext<VariablesResponseBody> requestContext) { VariableDetailsBase[] variables = editorSession.DebugService.GetVariables( variablesParams.VariablesReference); VariablesResponseBody variablesResponse = null; try { variablesResponse = new VariablesResponseBody { Variables = variables .Select(Variable.Create) .ToArray() }; } catch (Exception) { // TODO: This shouldn't be so broad } await requestContext.SendResult(variablesResponse); }
protected async Task HandleStackTraceRequest( StackTraceRequestArguments stackTraceParams, RequestContext<StackTraceResponseBody> requestContext) { StackFrameDetails[] stackFrames = editorSession.DebugService.GetStackFrames(); List<StackFrame> newStackFrames = new List<StackFrame>(); for (int i = 0; i < stackFrames.Length; i++) { // Create the new StackFrame object with an ID that can // be referenced back to the current list of stack frames newStackFrames.Add( StackFrame.Create( stackFrames[i], i)); } await requestContext.SendResult( new StackTraceResponseBody { StackFrames = newStackFrames.ToArray() }); }
protected async Task HandleThreadsRequest( object threadsParams, RequestContext<ThreadsResponseBody> requestContext) { await requestContext.SendResult( new ThreadsResponseBody { Threads = new Thread[] { // TODO: What do I do with these? new Thread { Id = 1, Name = "Main Thread" } } }); }
protected async Task HandleStepOutRequest( object stepOutParams, RequestContext<object> requestContext) { editorSession.DebugService.StepOut(); await requestContext.SendResult(null); }
protected async Task HandleShowOnlineHelpRequest( string helpParams, RequestContext<object> requestContext) { if (helpParams == null) { helpParams = "get-help"; } var psCommand = new PSCommand(); psCommand.AddCommand("Get-Help"); psCommand.AddArgument(helpParams); psCommand.AddParameter("Online"); await editorSession.PowerShellContext.ExecuteCommand<object>( psCommand); await requestContext.SendResult(null); }
protected async Task HandleCompletionRequest( TextDocumentPosition textDocumentPosition, RequestContext<CompletionItem[]> requestContext) { int cursorLine = textDocumentPosition.Position.Line + 1; int cursorColumn = textDocumentPosition.Position.Character + 1; ScriptFile scriptFile = editorSession.Workspace.GetFile( textDocumentPosition.Uri); CompletionResults completionResults = await editorSession.LanguageService.GetCompletionsInFile( scriptFile, cursorLine, cursorColumn); CompletionItem[] completionItems = null; if (completionResults != null) { // By default, insert the completion at the current location int startEditColumn = textDocumentPosition.Position.Character; int endEditColumn = textDocumentPosition.Position.Character; completionItems = completionResults .Completions .Select( c => CreateCompletionItem( c, completionResults.ReplacedRange)) .ToArray(); } else { completionItems = new CompletionItem[0]; } await requestContext.SendResult(completionItems); }
private async Task HandleExpandAliasRequest( string content, RequestContext<string> requestContext) { var script = @" function __Expand-Alias { param($targetScript) [ref]$errors=$null $tokens = [System.Management.Automation.PsParser]::Tokenize($targetScript, $errors).Where({$_.type -eq 'command'}) | Sort Start -Descending foreach ($token in $tokens) { $definition=(Get-Command ('`'+$token.Content) -CommandType Alias -ErrorAction SilentlyContinue).Definition if($definition) { $lhs=$targetScript.Substring(0, $token.Start) $rhs=$targetScript.Substring($token.Start + $token.Length) $targetScript=$lhs + $definition + $rhs } } $targetScript }"; var psCommand = new PSCommand(); psCommand.AddScript(script); await this.editorSession.PowerShellContext.ExecuteCommand<PSObject>(psCommand); psCommand = new PSCommand(); psCommand.AddCommand("__Expand-Alias").AddArgument(content); var result = await this.editorSession.PowerShellContext.ExecuteCommand<string>(psCommand); await requestContext.SendResult(result.First().ToString()); }
protected async Task HandleSignatureHelpRequest( TextDocumentPosition textDocumentPosition, RequestContext<SignatureHelp> requestContext) { ScriptFile scriptFile = editorSession.Workspace.GetFile( textDocumentPosition.Uri); ParameterSetSignatures parameterSets = await editorSession.LanguageService.FindParameterSetsInFile( scriptFile, textDocumentPosition.Position.Line + 1, textDocumentPosition.Position.Character + 1); SignatureInformation[] signatures = null; int? activeParameter = null; int? activeSignature = 0; if (parameterSets != null) { signatures = parameterSets .Signatures .Select(s => { return new SignatureInformation { Label = parameterSets.CommandName + " " + s.SignatureText, Documentation = null, Parameters = s.Parameters .Select(CreateParameterInfo) .ToArray() }; }) .ToArray(); } else { signatures = new SignatureInformation[0]; } await requestContext.SendResult( new SignatureHelp { Signatures = signatures, ActiveParameter = activeParameter, ActiveSignature = activeSignature }); }
protected async Task HandleReferencesRequest( ReferencesParams referencesParams, RequestContext<Location[]> requestContext) { ScriptFile scriptFile = editorSession.Workspace.GetFile( referencesParams.Uri); SymbolReference foundSymbol = editorSession.LanguageService.FindSymbolAtLocation( scriptFile, referencesParams.Position.Line + 1, referencesParams.Position.Character + 1); FindReferencesResult referencesResult = await editorSession.LanguageService.FindReferencesOfSymbol( foundSymbol, editorSession.Workspace.ExpandScriptReferences(scriptFile)); Location[] referenceLocations = null; if (referencesResult != null) { referenceLocations = referencesResult .FoundReferences .Select(r => { return new Location { Uri = new Uri(r.FilePath).AbsoluteUri, Range = GetRangeFromScriptRegion(r.ScriptRegion) }; }) .ToArray(); } else { referenceLocations = new Location[0]; } await requestContext.SendResult(referenceLocations); }
protected Task HandleEvaluateRequest( DebugAdapterMessages.EvaluateRequestArguments evaluateParams, RequestContext<DebugAdapterMessages.EvaluateResponseBody> requestContext) { // We don't await the result of the execution here because we want // to be able to receive further messages while the current script // is executing. This important in cases where the pipeline thread // gets blocked by something in the script like a prompt to the user. var executeTask = this.editorSession.PowerShellContext.ExecuteScriptString( evaluateParams.Expression, true, true); // Return the execution result after the task completes so that the // caller knows when command execution completed. executeTask.ContinueWith( (task) => { // Return an empty result since the result value is irrelevant // for this request in the LanguageServer return requestContext.SendResult( new DebugAdapterMessages.EvaluateResponseBody { Result = "", VariablesReference = 0 }); }); return Task.FromResult(true); }
protected async Task HandleCompletionResolveRequest( CompletionItem completionItem, RequestContext<CompletionItem> requestContext) { if (completionItem.Kind == CompletionItemKind.Function) { RunspaceHandle runspaceHandle = await editorSession.PowerShellContext.GetRunspaceHandle(); // Get the documentation for the function CommandInfo commandInfo = CommandHelpers.GetCommandInfo( completionItem.Label, runspaceHandle.Runspace); completionItem.Documentation = CommandHelpers.GetCommandSynopsis( commandInfo, runspaceHandle.Runspace); runspaceHandle.Dispose(); } // Send back the updated CompletionItem await requestContext.SendResult(completionItem); }
protected async Task HandleHoverRequest( TextDocumentPosition textDocumentPosition, RequestContext<Hover> requestContext) { ScriptFile scriptFile = editorSession.Workspace.GetFile( textDocumentPosition.Uri); SymbolDetails symbolDetails = await editorSession .LanguageService .FindSymbolDetailsAtLocation( scriptFile, textDocumentPosition.Position.Line + 1, textDocumentPosition.Position.Character + 1); List<MarkedString> symbolInfo = new List<MarkedString>(); Range? symbolRange = null; if (symbolDetails != null) { symbolInfo.Add( new MarkedString { Language = "PowerShell", Value = symbolDetails.DisplayString }); if (!string.IsNullOrEmpty(symbolDetails.Documentation)) { symbolInfo.Add( new MarkedString { Language = "markdown", Value = symbolDetails.Documentation }); } symbolRange = GetRangeFromScriptRegion(symbolDetails.SymbolReference.ScriptRegion); } await requestContext.SendResult( new Hover { Contents = symbolInfo.ToArray(), Range = symbolRange }); }
protected async Task HandleDocumentHighlightRequest( TextDocumentPosition textDocumentPosition, RequestContext<DocumentHighlight[]> requestContext) { ScriptFile scriptFile = editorSession.Workspace.GetFile( textDocumentPosition.Uri); FindOccurrencesResult occurrencesResult = editorSession.LanguageService.FindOccurrencesInFile( scriptFile, textDocumentPosition.Position.Line + 1, textDocumentPosition.Position.Character + 1); DocumentHighlight[] documentHighlights = null; if (occurrencesResult != null) { documentHighlights = occurrencesResult .FoundOccurrences .Select(o => { return new DocumentHighlight { Kind = DocumentHighlightKind.Write, // TODO: Which symbol types are writable? Range = GetRangeFromScriptRegion(o.ScriptRegion) }; }) .ToArray(); } else { documentHighlights = new DocumentHighlight[0]; } await requestContext.SendResult(documentHighlights); }
protected async Task HandleWorkspaceSymbolRequest( WorkspaceSymbolParams workspaceSymbolParams, RequestContext<SymbolInformation[]> requestContext) { var symbols = new List<SymbolInformation>(); foreach (ScriptFile scriptFile in editorSession.Workspace.GetOpenedFiles()) { FindOccurrencesResult foundSymbols = editorSession.LanguageService.FindSymbolsInFile( scriptFile); // TODO: Need to compute a relative path that is based on common path for all workspace files string containerName = Path.GetFileNameWithoutExtension(scriptFile.FilePath); if (foundSymbols != null) { var matchedSymbols = foundSymbols .FoundOccurrences .Where(r => IsQueryMatch(workspaceSymbolParams.Query, r.SymbolName)) .Select(r => { return new SymbolInformation { ContainerName = containerName, Kind = r.SymbolType == SymbolType.Variable ? SymbolKind.Variable : SymbolKind.Function, Location = new Location { Uri = new Uri(r.FilePath).AbsoluteUri, Range = GetRangeFromScriptRegion(r.ScriptRegion) }, Name = GetDecoratedSymbolName(r) }; }); symbols.AddRange(matchedSymbols); } } await requestContext.SendResult(symbols.ToArray()); }
protected async Task HandleDocumentSymbolRequest( TextDocumentIdentifier textDocumentIdentifier, RequestContext<SymbolInformation[]> requestContext) { ScriptFile scriptFile = editorSession.Workspace.GetFile( textDocumentIdentifier.Uri); FindOccurrencesResult foundSymbols = editorSession.LanguageService.FindSymbolsInFile( scriptFile); SymbolInformation[] symbols = null; string containerName = Path.GetFileNameWithoutExtension(scriptFile.FilePath); if (foundSymbols != null) { symbols = foundSymbols .FoundOccurrences .Select(r => { return new SymbolInformation { ContainerName = containerName, Kind = GetSymbolKind(r.SymbolType), Location = new Location { Uri = new Uri(r.FilePath).AbsolutePath, Range = GetRangeFromScriptRegion(r.ScriptRegion) }, Name = GetDecoratedSymbolName(r) }; }) .ToArray(); } else { symbols = new SymbolInformation[0]; } await requestContext.SendResult(symbols); }
protected Task HandleDisconnectRequest( object disconnectParams, RequestContext<object> requestContext) { EventHandler<SessionStateChangedEventArgs> handler = null; handler = async (o, e) => { if (e.NewSessionState == PowerShellContextState.Ready) { await requestContext.SendResult(null); editorSession.PowerShellContext.SessionStateChanged -= handler; // Stop the server this.Stop(); } }; editorSession.PowerShellContext.SessionStateChanged += handler; editorSession.PowerShellContext.AbortExecution(); return Task.FromResult(true); }
protected async Task HandleEvaluateRequest( DebugAdapterMessages.EvaluateRequestArguments evaluateParams, RequestContext<DebugAdapterMessages.EvaluateResponseBody> requestContext) { // We don't await the result of the execution here because we want // to be able to receive further messages while the current script // is executing. This important in cases where the pipeline thread // gets blocked by something in the script like a prompt to the user. var executeTask = this.editorSession.PowerShellContext.ExecuteScriptString( evaluateParams.Expression, true, true).ConfigureAwait(false); // Return an empty result since the result value is irrelevant // for this request in the LanguageServer await requestContext.SendResult( new DebugAdapterMessages.EvaluateResponseBody { Result = "", VariablesReference = 0 }); }
protected async Task HandleSetBreakpointsRequest( SetBreakpointsRequestArguments setBreakpointsParams, RequestContext<SetBreakpointsResponseBody> requestContext) { ScriptFile scriptFile = editorSession.Workspace.GetFile( setBreakpointsParams.Source.Path); BreakpointDetails[] breakpoints = await editorSession.DebugService.SetBreakpoints( scriptFile, setBreakpointsParams.Lines); await requestContext.SendResult( new SetBreakpointsResponseBody { Breakpoints = breakpoints .Select(Protocol.DebugAdapter.Breakpoint.Create) .ToArray() }); }
protected async Task HandleSetExceptionBreakpointsRequest( SetExceptionBreakpointsRequestArguments setExceptionBreakpointsParams, RequestContext<object> requestContext) { // TODO: Handle this appropriately await requestContext.SendResult(null); }
private async Task HandleFindModuleRequest( object param, RequestContext<object> requestContext) { var psCommand = new PSCommand(); psCommand.AddScript("Find-Module | Select Name, Description"); var modules = await editorSession.PowerShellContext.ExecuteCommand<PSObject>(psCommand); var moduleList = new List<PSModuleMessage>(); if (modules != null) { foreach (dynamic m in modules) { moduleList.Add(new PSModuleMessage { Name = m.Name, Description = m.Description }); } } await requestContext.SendResult(moduleList); }