diff --git a/NuGet.Config b/NuGet.Config index 45f5379b9..6efc7f7b9 100644 --- a/NuGet.Config +++ b/NuGet.Config @@ -3,10 +3,4 @@ - - - - - - - \ No newline at end of file + diff --git a/PowerShellEditorServices.build.ps1 b/PowerShellEditorServices.build.ps1 index 0b36d5176..8f543c3a4 100644 --- a/PowerShellEditorServices.build.ps1 +++ b/PowerShellEditorServices.build.ps1 @@ -198,7 +198,7 @@ task SetupDotNet -Before Clean, Build, TestHost, TestServer, TestProtocol, Packa # dotnet --version can return a semver that System.Version can't handle # e.g.: 2.1.300-preview-01. The replace operator is used to remove any build suffix. $version = (& $dotnetExePath --version) -replace '[+-].*$','' - if ([version]$version -ge [version]$script:RequiredSdkVersion) { + if ($version -and [version]$version -ge [version]$script:RequiredSdkVersion) { $script:dotnetExe = $dotnetExePath } else { diff --git a/src/PowerShellEditorServices.Channel.WebSocket/WebsocketClientChannel.cs b/src/PowerShellEditorServices.Channel.WebSocket/WebsocketClientChannel.cs index ea1142f76..edf2fd52f 100644 --- a/src/PowerShellEditorServices.Channel.WebSocket/WebsocketClientChannel.cs +++ b/src/PowerShellEditorServices.Channel.WebSocket/WebsocketClientChannel.cs @@ -39,7 +39,7 @@ public WebsocketClientChannel(string url) this.serverUrl = url; } - public override async Task WaitForConnection() + public override async Task WaitForConnectionAsync() { try { @@ -52,7 +52,7 @@ public override async Task WaitForConnection() { Logger.Write(LogLevel.Warning, string.Format("Failed to connect to WebSocket server. Error was '{0}'", wsException.Message)); - + } throw; @@ -99,7 +99,7 @@ protected override void Shutdown() } /// - /// Extension of that sends data to a WebSocket during FlushAsync + /// Extension of that sends data to a WebSocket during FlushAsync /// and reads during WriteAsync. /// internal class ClientWebSocketStream : MemoryStream @@ -110,7 +110,7 @@ internal class ClientWebSocketStream : MemoryStream /// Constructor /// /// - /// It is expected that the socket is in an Open state. + /// It is expected that the socket is in an Open state. /// /// public ClientWebSocketStream(ClientWebSocket socket) @@ -119,7 +119,7 @@ public ClientWebSocketStream(ClientWebSocket socket) } /// - /// Reads from the WebSocket. + /// Reads from the WebSocket. /// /// /// @@ -138,7 +138,7 @@ public override async Task ReadAsync(byte[] buffer, int offset, int count, { result = await socket.ReceiveAsync(new ArraySegment(buffer, offset, count), cancellationToken); } while (!result.EndOfMessage); - + if (result.MessageType == WebSocketMessageType.Close) { await socket.CloseAsync(WebSocketCloseStatus.NormalClosure, "Closing", cancellationToken); diff --git a/src/PowerShellEditorServices.Channel.WebSocket/WebsocketServerChannel.cs b/src/PowerShellEditorServices.Channel.WebSocket/WebsocketServerChannel.cs index 07acf953a..c3cb907de 100644 --- a/src/PowerShellEditorServices.Channel.WebSocket/WebsocketServerChannel.cs +++ b/src/PowerShellEditorServices.Channel.WebSocket/WebsocketServerChannel.cs @@ -17,8 +17,8 @@ namespace Microsoft.PowerShell.EditorServices.Channel.WebSocket { /// - /// Implementation of that implements the streams necessary for - /// communicating via OWIN WebSockets. + /// Implementation of that implements the streams necessary for + /// communicating via OWIN WebSockets. /// public class WebSocketServerChannel : ChannelBase { @@ -42,22 +42,22 @@ protected override void Initialize(IMessageSerializer messageSerializer) this.MessageWriter = new MessageWriter( - new WebSocketStream(socketConnection), + new WebSocketStream(socketConnection), messageSerializer); } /// - /// Dispatches data received during calls to OnMessageReceived in the class. + /// Dispatches data received during calls to OnMessageReceivedAsync in the class. /// /// - /// This method calls an overriden version of the that dispatches messages on - /// demand rather than running on a background thread. + /// This method calls an overriden version of the that dispatches messages on + /// demand rather than running on a background thread. /// /// /// - public async Task Dispatch(ArraySegment message) + public async Task DispatchAsync(ArraySegment message) { - //Clear our stream + //Clear our stream inStream.SetLength(0); //Write data and dispatch to handlers @@ -70,7 +70,7 @@ protected override void Shutdown() this.socketConnection.Close(WebSocketCloseStatus.NormalClosure, "Server shutting down"); } - public override Task WaitForConnection() + public override Task WaitForConnectionAsync() { // TODO: Need to update behavior here return Task.FromResult(true); @@ -78,11 +78,11 @@ public override Task WaitForConnection() } /// - /// Overriden that sends data through a during the FlushAsync call. + /// Overriden that sends data through a during the FlushAsync call. /// /// /// FlushAsync will send data via the SendBinary method of the class. The memory streams length will - /// then be set to 0 to reset the stream for additional data to be written. + /// then be set to 0 to reset the stream for additional data to be written. /// internal class WebSocketStream : MemoryStream { @@ -106,7 +106,7 @@ public override async Task FlushAsync(CancellationToken cancellationToken) /// public abstract class EditorServiceWebSocketConnection : WebSocketConnection { - protected EditorServiceWebSocketConnection() + protected EditorServiceWebSocketConnection() { Channel = new WebSocketServerChannel(this); } @@ -120,9 +120,9 @@ public override void OnOpen() Server.Start(); } - public override async Task OnMessageReceived(ArraySegment message, WebSocketMessageType type) + public override async Task OnMessageReceivedAsync(ArraySegment message, WebSocketMessageType type) { - await Channel.Dispatch(message); + await Channel.DispatchAsync(message); } public override Task OnCloseAsync(WebSocketCloseStatus? closeStatus, string closeStatusDescription) diff --git a/src/PowerShellEditorServices.Host/CodeLens/CodeLensFeature.cs b/src/PowerShellEditorServices.Host/CodeLens/CodeLensFeature.cs index ac5f388a3..e7e2f6910 100644 --- a/src/PowerShellEditorServices.Host/CodeLens/CodeLensFeature.cs +++ b/src/PowerShellEditorServices.Host/CodeLens/CodeLensFeature.cs @@ -49,11 +49,11 @@ public static CodeLensFeature Create( messageHandlers.SetRequestHandler( CodeLensRequest.Type, - codeLenses.HandleCodeLensRequest); + codeLenses.HandleCodeLensRequestAsync); messageHandlers.SetRequestHandler( CodeLensResolveRequest.Type, - codeLenses.HandleCodeLensResolveRequest); + codeLenses.HandleCodeLensResolveRequestAsync); codeLenses.Providers.Add( new ReferencesCodeLensProvider( @@ -111,7 +111,7 @@ public CodeLens[] ProvideCodeLenses(ScriptFile scriptFile) /// /// Parameters on the CodeLens request that was received. /// - private async Task HandleCodeLensRequest( + private async Task HandleCodeLensRequestAsync( CodeLensRequest codeLensParams, RequestContext requestContext) { @@ -132,7 +132,7 @@ private async Task HandleCodeLensRequest( _jsonSerializer); } - await requestContext.SendResult(codeLensResponse); + await requestContext.SendResultAsync(codeLensResponse); } /// @@ -140,7 +140,7 @@ private async Task HandleCodeLensRequest( /// /// The CodeLens to be resolved/updated. /// - private async Task HandleCodeLensResolveRequest( + private async Task HandleCodeLensResolveRequestAsync( LanguageServer.CodeLens codeLens, RequestContext requestContext) { @@ -178,13 +178,13 @@ await originalProvider.ResolveCodeLensAsync( originalCodeLens, CancellationToken.None); - await requestContext.SendResult( + await requestContext.SendResultAsync( resolvedCodeLens.ToProtocolCodeLens( _jsonSerializer)); } else { - await requestContext.SendError( + await requestContext.SendErrorAsync( $"Could not find provider for the original CodeLens: {codeLensData.ProviderId}"); } } diff --git a/src/PowerShellEditorServices.Host/CodeLens/ReferencesCodeLensProvider.cs b/src/PowerShellEditorServices.Host/CodeLens/ReferencesCodeLensProvider.cs index c833aec27..6a5312a93 100644 --- a/src/PowerShellEditorServices.Host/CodeLens/ReferencesCodeLensProvider.cs +++ b/src/PowerShellEditorServices.Host/CodeLens/ReferencesCodeLensProvider.cs @@ -82,7 +82,7 @@ public async Task ResolveCodeLensAsync( codeLens.ScriptExtent.StartLineNumber, codeLens.ScriptExtent.StartColumnNumber); - FindReferencesResult referencesResult = await _editorSession.LanguageService.FindReferencesOfSymbol( + FindReferencesResult referencesResult = await _editorSession.LanguageService.FindReferencesOfSymbolAsync( foundSymbol, references, _editorSession.Workspace); diff --git a/src/PowerShellEditorServices.Host/EditorServicesHost.cs b/src/PowerShellEditorServices.Host/EditorServicesHost.cs index 51e4a2db3..2f3275bf3 100644 --- a/src/PowerShellEditorServices.Host/EditorServicesHost.cs +++ b/src/PowerShellEditorServices.Host/EditorServicesHost.cs @@ -191,7 +191,7 @@ public void StartLanguageService( this.languageServiceListener = CreateServiceListener(MessageProtocolType.LanguageServer, config); - this.languageServiceListener.ClientConnect += this.OnLanguageServiceClientConnect; + this.languageServiceListener.ClientConnect += this.OnLanguageServiceClientConnectAsync; this.languageServiceListener.Start(); this.logger.Write( @@ -201,7 +201,7 @@ public void StartLanguageService( config.TransportType, config.Endpoint)); } - private async void OnLanguageServiceClientConnect( + private async void OnLanguageServiceClientConnectAsync( object sender, ChannelBase serverChannel) { @@ -231,7 +231,7 @@ private async void OnLanguageServiceClientConnect( this.serverCompletedTask, this.logger); - await this.editorSession.PowerShellContext.ImportCommandsModule( + await this.editorSession.PowerShellContext.ImportCommandsModuleAsync( Path.Combine( Path.GetDirectoryName(this.GetType().GetTypeInfo().Assembly.Location), @"..\Commands")); @@ -247,7 +247,7 @@ await this.editorSession.PowerShellContext.ImportCommandsModule( .AddCommand("Microsoft.PowerShell.Core\\Import-Module") .AddParameter("Name", module); - await this.editorSession.PowerShellContext.ExecuteCommand( + await this.editorSession.PowerShellContext.ExecuteCommandAsync( command, sendOutputToHost: false, sendErrorToHost: true); diff --git a/src/PowerShellEditorServices.Host/PSHost/PromptHandlers.cs b/src/PowerShellEditorServices.Host/PSHost/PromptHandlers.cs index bae68616f..d8ec88c4e 100644 --- a/src/PowerShellEditorServices.Host/PSHost/PromptHandlers.cs +++ b/src/PowerShellEditorServices.Host/PSHost/PromptHandlers.cs @@ -37,7 +37,7 @@ protected override void ShowPrompt(PromptStyle promptStyle) base.ShowPrompt(promptStyle); messageSender - .SendRequest( + .SendRequestAsync( ShowChoicePromptRequest.Type, new ShowChoicePromptRequest { @@ -51,7 +51,7 @@ protected override void ShowPrompt(PromptStyle promptStyle) .ConfigureAwait(false); } - protected override Task ReadInputString(CancellationToken cancellationToken) + protected override Task ReadInputStringAsync(CancellationToken cancellationToken) { this.readLineTask = new TaskCompletionSource(); return this.readLineTask.Task; @@ -120,7 +120,7 @@ protected override void ShowFieldPrompt(FieldDetails fieldDetails) base.ShowFieldPrompt(fieldDetails); messageSender - .SendRequest( + .SendRequestAsync( ShowInputPromptRequest.Type, new ShowInputPromptRequest { @@ -131,7 +131,7 @@ protected override void ShowFieldPrompt(FieldDetails fieldDetails) .ConfigureAwait(false); } - protected override Task ReadInputString(CancellationToken cancellationToken) + protected override Task ReadInputStringAsync(CancellationToken cancellationToken) { this.readLineTask = new TaskCompletionSource(); return this.readLineTask.Task; @@ -176,7 +176,7 @@ private void HandlePromptResponse( this.readLineTask = null; } - protected override Task ReadSecureString(CancellationToken cancellationToken) + protected override Task ReadSecureStringAsync(CancellationToken cancellationToken) { // TODO: Write a message to the console throw new NotImplementedException(); diff --git a/src/PowerShellEditorServices.Host/PSHost/ProtocolPSHostUserInterface.cs b/src/PowerShellEditorServices.Host/PSHost/ProtocolPSHostUserInterface.cs index c9a07e4a6..76b1f7252 100644 --- a/src/PowerShellEditorServices.Host/PSHost/ProtocolPSHostUserInterface.cs +++ b/src/PowerShellEditorServices.Host/PSHost/ProtocolPSHostUserInterface.cs @@ -47,7 +47,7 @@ public void Dispose() // Make sure remaining output is flushed before exiting if (this.outputDebouncer != null) { - this.outputDebouncer.Flush().Wait(); + this.outputDebouncer.FlushAsync().Wait(); this.outputDebouncer = null; } } @@ -82,7 +82,7 @@ public override void WriteOutput( ConsoleColor backgroundColor) { // TODO: This should use a synchronous method! - this.outputDebouncer.Invoke( + this.outputDebouncer.InvokeAsync( new OutputWrittenEventArgs( outputString, includeNewLine, @@ -102,7 +102,7 @@ protected override void UpdateProgress( { } - protected override Task ReadCommandLine(CancellationToken cancellationToken) + protected override Task ReadCommandLineAsync(CancellationToken cancellationToken) { // This currently does nothing because the "evaluate" request // will cancel the current prompt and execute the user's diff --git a/src/PowerShellEditorServices.Host/Symbols/DocumentSymbolFeature.cs b/src/PowerShellEditorServices.Host/Symbols/DocumentSymbolFeature.cs index 3db2a8dc8..da3402bde 100644 --- a/src/PowerShellEditorServices.Host/Symbols/DocumentSymbolFeature.cs +++ b/src/PowerShellEditorServices.Host/Symbols/DocumentSymbolFeature.cs @@ -33,7 +33,7 @@ public DocumentSymbolFeature( messageHandlers.SetRequestHandler( DocumentSymbolRequest.Type, - this.HandleDocumentSymbolRequest); + this.HandleDocumentSymbolRequestAsync); } public static DocumentSymbolFeature Create( @@ -69,7 +69,7 @@ public IEnumerable ProvideDocumentSymbols( .SelectMany(r => r); } - protected async Task HandleDocumentSymbolRequest( + protected async Task HandleDocumentSymbolRequestAsync( DocumentSymbolParams documentSymbolParams, RequestContext requestContext) { @@ -109,7 +109,7 @@ protected async Task HandleDocumentSymbolRequest( symbols = new SymbolInformation[0]; } - await requestContext.SendResult(symbols); + await requestContext.SendResultAsync(symbols); } } } diff --git a/src/PowerShellEditorServices.Protocol/Client/DebugAdapterClientBase.cs b/src/PowerShellEditorServices.Protocol/Client/DebugAdapterClientBase.cs index c90730a6d..b226fd0c4 100644 --- a/src/PowerShellEditorServices.Protocol/Client/DebugAdapterClientBase.cs +++ b/src/PowerShellEditorServices.Protocol/Client/DebugAdapterClientBase.cs @@ -28,12 +28,12 @@ public DebugAdapterClient(ChannelBase clientChannel, ILogger logger) logger); } - public async Task Start() + public async Task StartAsync() { this.protocolEndpoint.Start(); // Initialize the debug adapter - await this.SendRequest( + await this.SendRequestAsync( InitializeRequest.Type, new InitializeRequestArguments { @@ -48,34 +48,34 @@ public void Stop() this.protocolEndpoint.Stop(); } - public async Task LaunchScript(string scriptFilePath) + public async Task LaunchScriptAsync(string scriptFilePath) { - await this.SendRequest( + await this.SendRequestAsync( LaunchRequest.Type, new LaunchRequestArguments { Script = scriptFilePath }, true); - await this.SendRequest( + await this.SendRequestAsync( ConfigurationDoneRequest.Type, null, true); } - public Task SendEvent(NotificationType eventType, TParams eventParams) + public Task SendEventAsync(NotificationType eventType, TParams eventParams) { - return ((IMessageSender)protocolEndpoint).SendEvent(eventType, eventParams); + return ((IMessageSender)protocolEndpoint).SendEventAsync(eventType, eventParams); } - public Task SendRequest(RequestType requestType, TParams requestParams, bool waitForResponse) + public Task SendRequestAsync(RequestType requestType, TParams requestParams, bool waitForResponse) { - return ((IMessageSender)protocolEndpoint).SendRequest(requestType, requestParams, waitForResponse); + return ((IMessageSender)protocolEndpoint).SendRequestAsync(requestType, requestParams, waitForResponse); } - public Task SendRequest(RequestType0 requestType0) + public Task SendRequestAsync(RequestType0 requestType0) { - return ((IMessageSender)protocolEndpoint).SendRequest(requestType0); + return ((IMessageSender)protocolEndpoint).SendRequestAsync(requestType0); } public void SetRequestHandler(RequestType requestType, Func, Task> requestHandler) diff --git a/src/PowerShellEditorServices.Protocol/Client/LanguageClientBase.cs b/src/PowerShellEditorServices.Protocol/Client/LanguageClientBase.cs index c8dc383dc..0ccb3d5b5 100644 --- a/src/PowerShellEditorServices.Protocol/Client/LanguageClientBase.cs +++ b/src/PowerShellEditorServices.Protocol/Client/LanguageClientBase.cs @@ -41,46 +41,46 @@ public Task Start() this.protocolEndpoint.Start(); // Initialize the implementation class - return this.Initialize(); + return this.InitializeAsync(); } - public async Task Stop() + public async Task StopAsync() { - await this.OnStop(); + await this.OnStopAsync(); // First, notify the language server that we're stopping var response = - await this.SendRequest( + await this.SendRequestAsync( ShutdownRequest.Type); - await this.SendEvent(ExitNotification.Type, new object()); + await this.SendEventAsync(ExitNotification.Type, new object()); this.protocolEndpoint.Stop(); } - protected virtual Task OnStop() + protected virtual Task OnStopAsync() { return Task.FromResult(true); } - protected virtual Task Initialize() + protected virtual Task InitializeAsync() { return Task.FromResult(true); } - public Task SendEvent(NotificationType eventType, TParams eventParams) + public Task SendEventAsync(NotificationType eventType, TParams eventParams) { - return ((IMessageSender)protocolEndpoint).SendEvent(eventType, eventParams); + return ((IMessageSender)protocolEndpoint).SendEventAsync(eventType, eventParams); } - public Task SendRequest(RequestType requestType, TParams requestParams, bool waitForResponse) + public Task SendRequestAsync(RequestType requestType, TParams requestParams, bool waitForResponse) { - return ((IMessageSender)protocolEndpoint).SendRequest(requestType, requestParams, waitForResponse); + return ((IMessageSender)protocolEndpoint).SendRequestAsync(requestType, requestParams, waitForResponse); } - public Task SendRequest(RequestType0 requestType0) + public Task SendRequestAsync(RequestType0 requestType0) { - return ((IMessageSender)protocolEndpoint).SendRequest(requestType0); + return ((IMessageSender)protocolEndpoint).SendRequestAsync(requestType0); } public void SetRequestHandler(RequestType requestType, Func, Task> requestHandler) diff --git a/src/PowerShellEditorServices.Protocol/Client/LanguageServiceClient.cs b/src/PowerShellEditorServices.Protocol/Client/LanguageServiceClient.cs index 8878814dd..e2b1491fd 100644 --- a/src/PowerShellEditorServices.Protocol/Client/LanguageServiceClient.cs +++ b/src/PowerShellEditorServices.Protocol/Client/LanguageServiceClient.cs @@ -24,10 +24,10 @@ public LanguageServiceClient(ChannelBase clientChannel, ILogger logger) { } - protected override Task Initialize() + protected override Task InitializeAsync() { // Add handlers for common events - this.SetEventHandler(PublishDiagnosticsNotification.Type, HandlePublishDiagnosticsEvent); + this.SetEventHandler(PublishDiagnosticsNotification.Type, HandlePublishDiagnosticsEventAsync); // Send the 'initialize' request and wait for the response var initializeParams = new InitializeParams @@ -36,7 +36,7 @@ protected override Task Initialize() Capabilities = new ClientCapabilities() }; - return this.SendRequest( + return this.SendRequestAsync( InitializeRequest.Type, initializeParams, true); @@ -58,7 +58,7 @@ protected void OnDiagnosticsReceived(string filePath) #region Private Methods - private Task HandlePublishDiagnosticsEvent( + private Task HandlePublishDiagnosticsEventAsync( PublishDiagnosticsNotification diagnostics, EventContext eventContext) { diff --git a/src/PowerShellEditorServices.Protocol/MessageProtocol/Channel/NamedPipeClientChannel.cs b/src/PowerShellEditorServices.Protocol/MessageProtocol/Channel/NamedPipeClientChannel.cs index 8a40b6a1b..07f2cfe39 100644 --- a/src/PowerShellEditorServices.Protocol/MessageProtocol/Channel/NamedPipeClientChannel.cs +++ b/src/PowerShellEditorServices.Protocol/MessageProtocol/Channel/NamedPipeClientChannel.cs @@ -49,7 +49,7 @@ protected override void Shutdown() } } - public static async Task Connect( + public static async Task ConnectAsync( string pipeFile, MessageProtocolType messageProtocolType, ILogger logger) diff --git a/src/PowerShellEditorServices.Protocol/MessageProtocol/EventContext.cs b/src/PowerShellEditorServices.Protocol/MessageProtocol/EventContext.cs index 7af362f4e..4da757913 100644 --- a/src/PowerShellEditorServices.Protocol/MessageProtocol/EventContext.cs +++ b/src/PowerShellEditorServices.Protocol/MessageProtocol/EventContext.cs @@ -21,11 +21,11 @@ public EventContext(MessageWriter messageWriter) this.messageWriter = messageWriter; } - public async Task SendEvent( + public async Task SendEventAsync( NotificationType eventType, TParams eventParams) { - await this.messageWriter.WriteEvent( + await this.messageWriter.WriteEventAsync( eventType, eventParams); } diff --git a/src/PowerShellEditorServices.Protocol/MessageProtocol/IMessageSender.cs b/src/PowerShellEditorServices.Protocol/MessageProtocol/IMessageSender.cs index e32556cdc..804bbe74c 100644 --- a/src/PowerShellEditorServices.Protocol/MessageProtocol/IMessageSender.cs +++ b/src/PowerShellEditorServices.Protocol/MessageProtocol/IMessageSender.cs @@ -9,16 +9,16 @@ namespace Microsoft.PowerShell.EditorServices.Protocol.MessageProtocol { public interface IMessageSender { - Task SendEvent( + Task SendEventAsync( NotificationType eventType, TParams eventParams); - Task SendRequest( + Task SendRequestAsync( RequestType requestType, TParams requestParams, bool waitForResponse); - Task SendRequest( + Task SendRequestAsync( RequestType0 requestType0); } } diff --git a/src/PowerShellEditorServices.Protocol/MessageProtocol/MessageDispatcher.cs b/src/PowerShellEditorServices.Protocol/MessageProtocol/MessageDispatcher.cs index a81ee4446..ff7ae487e 100644 --- a/src/PowerShellEditorServices.Protocol/MessageProtocol/MessageDispatcher.cs +++ b/src/PowerShellEditorServices.Protocol/MessageProtocol/MessageDispatcher.cs @@ -115,7 +115,7 @@ public void SetEventHandler( #region Private Methods - public async Task DispatchMessage( + public async Task DispatchMessageAsync( Message messageToDispatch, MessageWriter messageWriter) { diff --git a/src/PowerShellEditorServices.Protocol/MessageProtocol/MessageReader.cs b/src/PowerShellEditorServices.Protocol/MessageProtocol/MessageReader.cs index dcf7aaa94..fec0d175b 100644 --- a/src/PowerShellEditorServices.Protocol/MessageProtocol/MessageReader.cs +++ b/src/PowerShellEditorServices.Protocol/MessageProtocol/MessageReader.cs @@ -75,12 +75,12 @@ public MessageReader( #region Public Methods - public async Task ReadMessage() + public async Task ReadMessageAsync() { string messageContent = null; // Do we need to read more data or can we process the existing buffer? - while (!this.needsMoreData || await this.ReadNextChunk()) + while (!this.needsMoreData || await this.ReadNextChunkAsync()) { // Clear the flag since we should have what we need now this.needsMoreData = false; @@ -144,7 +144,7 @@ public async Task ReadMessage() #region Private Methods - private async Task ReadNextChunk() + private async Task ReadNextChunkAsync() { // Do we need to resize the buffer? See if less than 1/4 of the space is left. if (((double)(this.messageBuffer.Length - this.bufferEndOffset) / this.messageBuffer.Length) < 0.25) diff --git a/src/PowerShellEditorServices.Protocol/MessageProtocol/MessageWriter.cs b/src/PowerShellEditorServices.Protocol/MessageProtocol/MessageWriter.cs index f2082efba..5baa40038 100644 --- a/src/PowerShellEditorServices.Protocol/MessageProtocol/MessageWriter.cs +++ b/src/PowerShellEditorServices.Protocol/MessageProtocol/MessageWriter.cs @@ -49,7 +49,7 @@ public MessageWriter( // TODO: This method should be made protected or private - public async Task WriteMessage(Message messageToWrite) + public async Task WriteMessageAsync(Message messageToWrite) { Validate.IsNotNull("messageToWrite", messageToWrite); @@ -111,7 +111,7 @@ public async Task WriteMessage(Message messageToWrite) } } - public async Task WriteRequest( + public async Task WriteRequestAsync( RequestType requestType, TParams requestParams, int requestId) @@ -122,14 +122,14 @@ public async Task WriteRequest( JToken.FromObject(requestParams, contentSerializer) : null; - await this.WriteMessage( + await this.WriteMessageAsync( Message.Request( requestId.ToString(), requestType.Method, contentObject)); } - public async Task WriteResponse(TResult resultContent, string method, string requestId) + public async Task WriteResponseAsync(TResult resultContent, string method, string requestId) { // Allow null content JToken contentObject = @@ -137,14 +137,14 @@ public async Task WriteResponse(TResult resultContent, string method, s JToken.FromObject(resultContent, contentSerializer) : null; - await this.WriteMessage( + await this.WriteMessageAsync( Message.Response( requestId, method, contentObject)); } - public async Task WriteEvent(NotificationType eventType, TParams eventParams) + public async Task WriteEventAsync(NotificationType eventType, TParams eventParams) { // Allow null content JToken contentObject = @@ -152,7 +152,7 @@ public async Task WriteEvent(NotificationType SendRequest( + public Task SendRequestAsync( RequestType0 requestType0) { - return this.SendRequest( + return this.SendRequestAsync( RequestType.ConvertToRequestType(requestType0), null); } @@ -138,14 +138,14 @@ public Task SendRequest( /// /// /// - public Task SendRequest( + public Task SendRequestAsync( RequestType requestType, TParams requestParams) { - return this.SendRequest(requestType, requestParams, true); + return this.SendRequestAsync(requestType, requestParams, true); } - public async Task SendRequest( + public async Task SendRequestAsync( RequestType requestType, TParams requestParams, bool waitForResponse) @@ -170,7 +170,7 @@ public async Task SendRequest( + await this.protocolChannel.MessageWriter.WriteRequestAsync( requestType, requestParams, this.currentMessageId); @@ -198,7 +198,7 @@ await this.protocolChannel.MessageWriter.WriteRequestThe type of event being sent. /// The event parameters being sent. /// A Task that tracks completion of the send operation. - public Task SendEvent( + public Task SendEventAsync( NotificationType eventType, TParams eventParams) { @@ -221,7 +221,7 @@ public Task SendEvent( this.SynchronizationContext.Post( async (obj) => { - await this.protocolChannel.MessageWriter.WriteEvent( + await this.protocolChannel.MessageWriter.WriteEventAsync( eventType, eventParams); @@ -232,7 +232,7 @@ await this.protocolChannel.MessageWriter.WriteEvent( } else { - return this.protocolChannel.MessageWriter.WriteEvent( + return this.protocolChannel.MessageWriter.WriteEventAsync( eventType, eventParams); } @@ -261,7 +261,7 @@ private void StartMessageLoop() this.messageLoopThread = new AsyncContextThread("Message Dispatcher"); this.messageLoopThread .Run( - () => this.ListenForMessages(this.messageLoopCancellationToken.Token), + () => this.ListenForMessagesAsync(this.messageLoopCancellationToken.Token), this.Logger) .ContinueWith(this.OnListenTaskCompleted); } @@ -311,7 +311,7 @@ private void MessageDispatcher_UnhandledException(object sender, Exception e) #region Private Methods - private async Task ListenForMessages(CancellationToken cancellationToken) + private async Task ListenForMessagesAsync(CancellationToken cancellationToken) { this.SynchronizationContext = SynchronizationContext.Current; @@ -324,7 +324,7 @@ private async Task ListenForMessages(CancellationToken cancellationToken) try { // Read a message from the channel - newMessage = await this.protocolChannel.MessageReader.ReadMessage(); + newMessage = await this.protocolChannel.MessageReader.ReadMessageAsync(); } catch (MessageParseException e) { @@ -376,7 +376,7 @@ private async Task ListenForMessages(CancellationToken cancellationToken) else { // Process the message - await this.messageDispatcher.DispatchMessage( + await this.messageDispatcher.DispatchMessageAsync( newMessage, this.protocolChannel.MessageWriter); } diff --git a/src/PowerShellEditorServices.Protocol/MessageProtocol/RequestContext.cs b/src/PowerShellEditorServices.Protocol/MessageProtocol/RequestContext.cs index 55c473f01..94c9264b7 100644 --- a/src/PowerShellEditorServices.Protocol/MessageProtocol/RequestContext.cs +++ b/src/PowerShellEditorServices.Protocol/MessageProtocol/RequestContext.cs @@ -19,24 +19,24 @@ public RequestContext(Message requestMessage, MessageWriter messageWriter) this.messageWriter = messageWriter; } - public async Task SendResult(TResult resultDetails) + public async Task SendResultAsync(TResult resultDetails) { - await this.messageWriter.WriteResponse( + await this.messageWriter.WriteResponseAsync( resultDetails, requestMessage.Method, requestMessage.Id); } - public async Task SendEvent(NotificationType eventType, TParams eventParams) + public async Task SendEventAsync(NotificationType eventType, TParams eventParams) { - await this.messageWriter.WriteEvent( + await this.messageWriter.WriteEventAsync( eventType, eventParams); } - public async Task SendError(object errorDetails) + public async Task SendErrorAsync(object errorDetails) { - await this.messageWriter.WriteMessage( + await this.messageWriter.WriteMessageAsync( Message.ResponseError( requestMessage.Id, requestMessage.Method, diff --git a/src/PowerShellEditorServices.Protocol/Server/DebugAdapter.cs b/src/PowerShellEditorServices.Protocol/Server/DebugAdapter.cs index 96f04ba09..69a720f8e 100644 --- a/src/PowerShellEditorServices.Protocol/Server/DebugAdapter.cs +++ b/src/PowerShellEditorServices.Protocol/Server/DebugAdapter.cs @@ -63,33 +63,33 @@ public DebugAdapter( public void Start() { // Register all supported message types - _messageHandlers.SetRequestHandler(InitializeRequest.Type, HandleInitializeRequest); - - _messageHandlers.SetRequestHandler(LaunchRequest.Type, HandleLaunchRequest); - _messageHandlers.SetRequestHandler(AttachRequest.Type, HandleAttachRequest); - _messageHandlers.SetRequestHandler(ConfigurationDoneRequest.Type, HandleConfigurationDoneRequest); - _messageHandlers.SetRequestHandler(DisconnectRequest.Type, HandleDisconnectRequest); - - _messageHandlers.SetRequestHandler(SetBreakpointsRequest.Type, HandleSetBreakpointsRequest); - _messageHandlers.SetRequestHandler(SetExceptionBreakpointsRequest.Type, HandleSetExceptionBreakpointsRequest); - _messageHandlers.SetRequestHandler(SetFunctionBreakpointsRequest.Type, HandleSetFunctionBreakpointsRequest); - - _messageHandlers.SetRequestHandler(ContinueRequest.Type, HandleContinueRequest); - _messageHandlers.SetRequestHandler(NextRequest.Type, HandleNextRequest); - _messageHandlers.SetRequestHandler(StepInRequest.Type, HandleStepInRequest); - _messageHandlers.SetRequestHandler(StepOutRequest.Type, HandleStepOutRequest); - _messageHandlers.SetRequestHandler(PauseRequest.Type, HandlePauseRequest); - - _messageHandlers.SetRequestHandler(ThreadsRequest.Type, HandleThreadsRequest); - _messageHandlers.SetRequestHandler(StackTraceRequest.Type, HandleStackTraceRequest); - _messageHandlers.SetRequestHandler(ScopesRequest.Type, HandleScopesRequest); - _messageHandlers.SetRequestHandler(VariablesRequest.Type, HandleVariablesRequest); - _messageHandlers.SetRequestHandler(SetVariableRequest.Type, HandleSetVariablesRequest); - _messageHandlers.SetRequestHandler(SourceRequest.Type, HandleSourceRequest); - _messageHandlers.SetRequestHandler(EvaluateRequest.Type, HandleEvaluateRequest); + _messageHandlers.SetRequestHandler(InitializeRequest.Type, HandleInitializeRequestAsync); + + _messageHandlers.SetRequestHandler(LaunchRequest.Type, HandleLaunchRequestAsync); + _messageHandlers.SetRequestHandler(AttachRequest.Type, HandleAttachRequestAsync); + _messageHandlers.SetRequestHandler(ConfigurationDoneRequest.Type, HandleConfigurationDoneRequestAsync); + _messageHandlers.SetRequestHandler(DisconnectRequest.Type, HandleDisconnectRequestAsync); + + _messageHandlers.SetRequestHandler(SetBreakpointsRequest.Type, HandleSetBreakpointsRequestAsync); + _messageHandlers.SetRequestHandler(SetExceptionBreakpointsRequest.Type, HandleSetExceptionBreakpointsRequestAsync); + _messageHandlers.SetRequestHandler(SetFunctionBreakpointsRequest.Type, HandleSetFunctionBreakpointsRequestAsync); + + _messageHandlers.SetRequestHandler(ContinueRequest.Type, HandleContinueRequestAsync); + _messageHandlers.SetRequestHandler(NextRequest.Type, HandleNextRequestAsync); + _messageHandlers.SetRequestHandler(StepInRequest.Type, HandleStepInRequestAsync); + _messageHandlers.SetRequestHandler(StepOutRequest.Type, HandleStepOutRequestAsync); + _messageHandlers.SetRequestHandler(PauseRequest.Type, HandlePauseRequestAsync); + + _messageHandlers.SetRequestHandler(ThreadsRequest.Type, HandleThreadsRequestAsync); + _messageHandlers.SetRequestHandler(StackTraceRequest.Type, HandleStackTraceRequestAsync); + _messageHandlers.SetRequestHandler(ScopesRequest.Type, HandleScopesRequestAsync); + _messageHandlers.SetRequestHandler(VariablesRequest.Type, HandleVariablesRequestAsync); + _messageHandlers.SetRequestHandler(SetVariableRequest.Type, HandleSetVariablesRequestAsync); + _messageHandlers.SetRequestHandler(SourceRequest.Type, HandleSourceRequestAsync); + _messageHandlers.SetRequestHandler(EvaluateRequest.Type, HandleEvaluateRequestAsync); } - protected Task LaunchScript(RequestContext requestContext, string scriptToLaunch) + protected Task LaunchScriptAsync(RequestContext requestContext, string scriptToLaunch) { // Is this an untitled script? Task launchTask = null; @@ -99,18 +99,18 @@ protected Task LaunchScript(RequestContext requestContext, string script ScriptFile untitledScript = _editorSession.Workspace.GetFile(scriptToLaunch); launchTask = _editorSession.PowerShellContext - .ExecuteScriptString(untitledScript.Contents, true, true); + .ExecuteScriptStringAsync(untitledScript.Contents, true, true); } else { launchTask = _editorSession.PowerShellContext - .ExecuteScriptWithArgs(scriptToLaunch, _arguments, writeInputToHost: true); + .ExecuteScriptWithArgsAsync(scriptToLaunch, _arguments, writeInputToHost: true); } - return launchTask.ContinueWith(OnExecutionCompleted); + return launchTask.ContinueWith(OnExecutionCompletedAsync); } - private async Task OnExecutionCompleted(Task executeTask) + private async Task OnExecutionCompletedAsync(Task executeTask) { try { @@ -136,12 +136,12 @@ private async Task OnExecutionCompleted(Task executeTask) { try { - await _editorSession.PowerShellContext.ExecuteScriptString("Exit-PSHostProcess"); + await _editorSession.PowerShellContext.ExecuteScriptStringAsync("Exit-PSHostProcess"); if (_isRemoteAttach && _editorSession.PowerShellContext.CurrentRunspace.Location == RunspaceLocation.Remote) { - await _editorSession.PowerShellContext.ExecuteScriptString("Exit-PSSession"); + await _editorSession.PowerShellContext.ExecuteScriptStringAsync("Exit-PSSession"); } } catch (Exception e) @@ -156,12 +156,12 @@ private async Task OnExecutionCompleted(Task executeTask) if (_disconnectRequestContext != null) { // Respond to the disconnect request and stop the server - await _disconnectRequestContext.SendResult(null); + await _disconnectRequestContext.SendResultAsync(null); Stop(); } else { - await _messageSender.SendEvent( + await _messageSender.SendEventAsync( TerminatedEvent.Type, new TerminatedEvent()); } @@ -173,9 +173,9 @@ protected void Stop() if (_editorSession != null) { - _editorSession.PowerShellContext.RunspaceChanged -= powerShellContext_RunspaceChanged; - _editorSession.DebugService.DebuggerStopped -= DebugService_DebuggerStopped; - _editorSession.PowerShellContext.DebuggerResumed -= powerShellContext_DebuggerResumed; + _editorSession.PowerShellContext.RunspaceChanged -= powerShellContext_RunspaceChangedAsync; + _editorSession.DebugService.DebuggerStopped -= DebugService_DebuggerStoppedAsync; + _editorSession.PowerShellContext.DebuggerResumed -= powerShellContext_DebuggerResumedAsync; if (_ownsEditorSession) { @@ -190,15 +190,15 @@ protected void Stop() #region Built-in Message Handlers - private async Task HandleInitializeRequest( + private async Task HandleInitializeRequestAsync( object shutdownParams, RequestContext requestContext) { // Clear any existing breakpoints before proceeding - await ClearSessionBreakpoints(); + await ClearSessionBreakpointsAsync(); // Now send the Initialize response to continue setup - await requestContext.SendResult( + await requestContext.SendResultAsync( new InitializeResponseBody { SupportsConfigurationDoneRequest = true, SupportsFunctionBreakpoints = true, @@ -208,7 +208,7 @@ await requestContext.SendResult( }); } - protected async Task HandleConfigurationDoneRequest( + protected async Task HandleConfigurationDoneRequestAsync( object args, RequestContext requestContext) { @@ -219,7 +219,7 @@ protected async Task HandleConfigurationDoneRequest( if (_editorSession.PowerShellContext.SessionState == PowerShellContextState.Ready) { // Configuration is done, launch the script - var nonAwaitedTask = LaunchScript(requestContext, _scriptToLaunch) + var nonAwaitedTask = LaunchScriptAsync(requestContext, _scriptToLaunch) .ConfigureAwait(continueOnCapturedContext: false); } else @@ -230,7 +230,7 @@ protected async Task HandleConfigurationDoneRequest( } } - await requestContext.SendResult(null); + await requestContext.SendResultAsync(null); if (_isInteractiveDebugSession) { @@ -245,14 +245,14 @@ protected async Task HandleConfigurationDoneRequest( { // If this is an interactive session and there's a pending breakpoint, // send that information along to the debugger client - DebugService_DebuggerStopped( + DebugService_DebuggerStoppedAsync( this, _editorSession.DebugService.CurrentDebuggerStoppedEventArgs); } } } - protected async Task HandleLaunchRequest( + protected async Task HandleLaunchRequestAsync( LaunchRequestArguments launchParams, RequestContext requestContext) { @@ -298,7 +298,7 @@ protected async Task HandleLaunchRequest( // the working dir should not be changed. if (!string.IsNullOrEmpty(workingDir)) { - await _editorSession.PowerShellContext.SetWorkingDirectory(workingDir, isPathAlreadyEscaped: false); + await _editorSession.PowerShellContext.SetWorkingDirectoryAsync(workingDir, isPathAlreadyEscaped: false); } Logger.Write(LogLevel.Verbose, $"Working dir " + (string.IsNullOrEmpty(workingDir) ? "not set." : $"set to '{workingDir}'")); @@ -329,7 +329,7 @@ protected async Task HandleLaunchRequest( _editorSession.PowerShellContext.CurrentRunspace); } - await requestContext.SendResult(null); + await requestContext.SendResultAsync(null); // If no script is being launched, mark this as an interactive // debugging session @@ -337,12 +337,12 @@ protected async Task HandleLaunchRequest( // Send the InitializedEvent so that the debugger will continue // sending configuration requests - await _messageSender.SendEvent( + await _messageSender.SendEventAsync( InitializedEvent.Type, null); } - protected async Task HandleAttachRequest( + protected async Task HandleAttachRequestAsync( AttachRequestArguments attachParams, RequestContext requestContext) { @@ -360,7 +360,7 @@ protected async Task HandleAttachRequest( LogLevel.Normal, $"Attach request aborted, received {attachParams.ProcessId} for processId."); - await requestContext.SendError( + await requestContext.SendErrorAsync( "User aborted attach to PowerShell host process."); return; @@ -375,26 +375,26 @@ await requestContext.SendError( if (runspaceVersion.Version.Major < 4) { - await requestContext.SendError( + await requestContext.SendErrorAsync( $"Remote sessions are only available with PowerShell 4 and higher (current session is {runspaceVersion.Version})."); return; } else if (_editorSession.PowerShellContext.CurrentRunspace.Location == RunspaceLocation.Remote) { - await requestContext.SendError( + await requestContext.SendErrorAsync( $"Cannot attach to a process in a remote session when already in a remote session."); return; } - await _editorSession.PowerShellContext.ExecuteScriptString( + await _editorSession.PowerShellContext.ExecuteScriptStringAsync( $"Enter-PSSession -ComputerName \"{attachParams.ComputerName}\"", errorMessages); if (errorMessages.Length > 0) { - await requestContext.SendError( + await requestContext.SendErrorAsync( $"Could not establish remote session to computer '{attachParams.ComputerName}'"); return; @@ -410,26 +410,26 @@ await requestContext.SendError( if (runspaceVersion.Version.Major < 5) { - await requestContext.SendError( + await requestContext.SendErrorAsync( $"Attaching to a process is only available with PowerShell 5 and higher (current session is {runspaceVersion.Version})."); return; } - await _editorSession.PowerShellContext.ExecuteScriptString( + await _editorSession.PowerShellContext.ExecuteScriptStringAsync( $"Enter-PSHostProcess -Id {processId}", errorMessages); if (errorMessages.Length > 0) { - await requestContext.SendError( + await requestContext.SendErrorAsync( $"Could not attach to process '{processId}'"); return; } // Clear any existing breakpoints before proceeding - await ClearSessionBreakpoints(); + await ClearSessionBreakpointsAsync(); // Execute the Debug-Runspace command but don't await it because it // will block the debug adapter initialization process. The @@ -439,8 +439,8 @@ await requestContext.SendError( _waitingForAttach = true; Task nonAwaitedTask = _editorSession.PowerShellContext - .ExecuteScriptString($"\nDebug-Runspace -Id {runspaceId}") - .ContinueWith(OnExecutionCompleted); + .ExecuteScriptStringAsync($"\nDebug-Runspace -Id {runspaceId}") + .ContinueWith(OnExecutionCompletedAsync); } else { @@ -448,16 +448,16 @@ await requestContext.SendError( LogLevel.Error, $"Attach request failed, '{attachParams.ProcessId}' is an invalid value for the processId."); - await requestContext.SendError( + await requestContext.SendErrorAsync( "A positive integer must be specified for the processId field."); return; } - await requestContext.SendResult(null); + await requestContext.SendResultAsync(null); } - protected async Task HandleDisconnectRequest( + protected async Task HandleDisconnectRequestAsync( object disconnectParams, RequestContext requestContext) { @@ -472,20 +472,20 @@ protected async Task HandleDisconnectRequest( if (_isInteractiveDebugSession) { - await OnExecutionCompleted(null); + await OnExecutionCompletedAsync(null); } } else { UnregisterEventHandlers(); - await requestContext.SendResult(null); + await requestContext.SendResultAsync(null); Stop(); } } } - protected async Task HandleSetBreakpointsRequest( + protected async Task HandleSetBreakpointsRequestAsync( SetBreakpointsRequestArguments setBreakpointsParams, RequestContext requestContext) { @@ -504,7 +504,7 @@ protected async Task HandleSetBreakpointsRequest( srcBkpt, setBreakpointsParams.Source.Path, message, verified: _noDebug)); // Return non-verified breakpoint message. - await requestContext.SendResult( + await requestContext.SendResultAsync( new SetBreakpointsResponseBody { Breakpoints = srcBreakpoints.ToArray() }); @@ -527,7 +527,7 @@ await requestContext.SendResult( srcBkpt, setBreakpointsParams.Source.Path, message, verified: _noDebug)); // Return non-verified breakpoint message. - await requestContext.SendResult( + await requestContext.SendResultAsync( new SetBreakpointsResponseBody { Breakpoints = srcBreakpoints.ToArray() @@ -558,7 +558,7 @@ await requestContext.SendResult( try { updatedBreakpointDetails = - await _editorSession.DebugService.SetLineBreakpoints( + await _editorSession.DebugService.SetLineBreakpointsAsync( scriptFile, breakpointDetails); } @@ -573,7 +573,7 @@ await _editorSession.DebugService.SetLineBreakpoints( } } - await requestContext.SendResult( + await requestContext.SendResultAsync( new SetBreakpointsResponseBody { Breakpoints = updatedBreakpointDetails @@ -582,7 +582,7 @@ await requestContext.SendResult( }); } - protected async Task HandleSetFunctionBreakpointsRequest( + protected async Task HandleSetFunctionBreakpointsRequestAsync( SetFunctionBreakpointsRequestArguments setBreakpointsParams, RequestContext requestContext) { @@ -605,7 +605,7 @@ protected async Task HandleSetFunctionBreakpointsRequest( try { updatedBreakpointDetails = - await _editorSession.DebugService.SetCommandBreakpoints( + await _editorSession.DebugService.SetCommandBreakpointsAsync( breakpointDetails); } catch (Exception e) @@ -619,7 +619,7 @@ await _editorSession.DebugService.SetCommandBreakpoints( } } - await requestContext.SendResult( + await requestContext.SendResultAsync( new SetBreakpointsResponseBody { Breakpoints = updatedBreakpointDetails @@ -628,7 +628,7 @@ await requestContext.SendResult( }); } - protected async Task HandleSetExceptionBreakpointsRequest( + protected async Task HandleSetExceptionBreakpointsRequestAsync( SetExceptionBreakpointsRequestArguments setExceptionBreakpointsParams, RequestContext requestContext) { @@ -654,28 +654,28 @@ protected async Task HandleSetExceptionBreakpointsRequest( // } //} - await requestContext.SendResult(null); + await requestContext.SendResultAsync(null); } - protected async Task HandleContinueRequest( + protected async Task HandleContinueRequestAsync( object continueParams, RequestContext requestContext) { _editorSession.DebugService.Continue(); - await requestContext.SendResult(null); + await requestContext.SendResultAsync(null); } - protected async Task HandleNextRequest( + protected async Task HandleNextRequestAsync( object nextParams, RequestContext requestContext) { _editorSession.DebugService.StepOver(); - await requestContext.SendResult(null); + await requestContext.SendResultAsync(null); } - protected Task HandlePauseRequest( + protected Task HandlePauseRequestAsync( object pauseParams, RequestContext requestContext) { @@ -685,36 +685,36 @@ protected Task HandlePauseRequest( } catch (NotSupportedException e) { - return requestContext.SendError(e.Message); + return requestContext.SendErrorAsync(e.Message); } // This request is responded to by sending the "stopped" event return Task.FromResult(true); } - protected async Task HandleStepInRequest( + protected async Task HandleStepInRequestAsync( object stepInParams, RequestContext requestContext) { _editorSession.DebugService.StepIn(); - await requestContext.SendResult(null); + await requestContext.SendResultAsync(null); } - protected async Task HandleStepOutRequest( + protected async Task HandleStepOutRequestAsync( object stepOutParams, RequestContext requestContext) { _editorSession.DebugService.StepOut(); - await requestContext.SendResult(null); + await requestContext.SendResultAsync(null); } - protected async Task HandleThreadsRequest( + protected async Task HandleThreadsRequestAsync( object threadsParams, RequestContext requestContext) { - await requestContext.SendResult( + await requestContext.SendResultAsync( new ThreadsResponseBody { Threads = new Thread[] @@ -729,7 +729,7 @@ await requestContext.SendResult( }); } - protected async Task HandleStackTraceRequest( + protected async Task HandleStackTraceRequestAsync( StackTraceRequestArguments stackTraceParams, RequestContext requestContext) { @@ -740,7 +740,7 @@ protected async Task HandleStackTraceRequest( // begun building. if (stackFrames == null) { - await requestContext.SendResult( + await requestContext.SendResultAsync( new StackTraceResponseBody { StackFrames = new StackFrame[0], @@ -773,7 +773,7 @@ await requestContext.SendResult( i)); } - await requestContext.SendResult( + await requestContext.SendResultAsync( new StackTraceResponseBody { StackFrames = newStackFrames.ToArray(), @@ -781,7 +781,7 @@ await requestContext.SendResult( }); } - protected async Task HandleScopesRequest( + protected async Task HandleScopesRequestAsync( ScopesRequestArguments scopesParams, RequestContext requestContext) { @@ -789,7 +789,7 @@ protected async Task HandleScopesRequest( _editorSession.DebugService.GetVariableScopes( scopesParams.FrameId); - await requestContext.SendResult( + await requestContext.SendResultAsync( new ScopesResponseBody { Scopes = @@ -799,7 +799,7 @@ await requestContext.SendResult( }); } - protected async Task HandleVariablesRequest( + protected async Task HandleVariablesRequestAsync( VariablesRequestArguments variablesParams, RequestContext requestContext) { @@ -824,17 +824,17 @@ protected async Task HandleVariablesRequest( // TODO: This shouldn't be so broad } - await requestContext.SendResult(variablesResponse); + await requestContext.SendResultAsync(variablesResponse); } - protected async Task HandleSetVariablesRequest( + protected async Task HandleSetVariablesRequestAsync( SetVariableRequestArguments setVariableParams, RequestContext requestContext) { try { string updatedValue = - await _editorSession.DebugService.SetVariable( + await _editorSession.DebugService.SetVariableAsync( setVariableParams.VariablesReference, setVariableParams.Name, setVariableParams.Value); @@ -844,7 +844,7 @@ await _editorSession.DebugService.SetVariable( Value = updatedValue }; - await requestContext.SendResult(setVariableResponse); + await requestContext.SendResultAsync(setVariableResponse); } catch (Exception ex) when (ex is ArgumentTransformationMetadataException || ex is InvalidPowerShellExpressionException || @@ -852,18 +852,18 @@ ex is InvalidPowerShellExpressionException || { // Catch common, innocuous errors caused by the user supplying a value that can't be converted or the variable is not settable. Logger.Write(LogLevel.Verbose, $"Failed to set variable: {ex.Message}"); - await requestContext.SendError(ex.Message); + await requestContext.SendErrorAsync(ex.Message); } catch (Exception ex) { Logger.Write(LogLevel.Error, $"Unexpected error setting variable: {ex.Message}"); string msg = $"Unexpected error: {ex.GetType().Name} - {ex.Message} Please report this error to the PowerShellEditorServices project on GitHub."; - await requestContext.SendError(msg); + await requestContext.SendErrorAsync(msg); } } - protected Task HandleSourceRequest( + protected Task HandleSourceRequestAsync( SourceRequestArguments sourceParams, RequestContext requestContext) { @@ -873,7 +873,7 @@ protected Task HandleSourceRequest( return Task.FromResult(true); } - protected async Task HandleEvaluateRequest( + protected async Task HandleEvaluateRequestAsync( EvaluateRequestArguments evaluateParams, RequestContext requestContext) { @@ -891,7 +891,7 @@ protected async Task HandleEvaluateRequest( var notAwaited = _editorSession .PowerShellContext - .ExecuteScriptString(evaluateParams.Expression, false, true) + .ExecuteScriptStringAsync(evaluateParams.Expression, false, true) .ConfigureAwait(false); } else @@ -910,7 +910,7 @@ protected async Task HandleEvaluateRequest( if (result == null) { result = - await _editorSession.DebugService.EvaluateExpression( + await _editorSession.DebugService.EvaluateExpressionAsync( evaluateParams.Expression, evaluateParams.FrameId, isFromRepl); @@ -926,7 +926,7 @@ await _editorSession.DebugService.EvaluateExpression( } } - await requestContext.SendResult( + await requestContext.SendResultAsync( new EvaluateResponseBody { Result = valueString, @@ -934,9 +934,9 @@ await requestContext.SendResult( }); } - private async Task WriteUseIntegratedConsoleMessage() + private async Task WriteUseIntegratedConsoleMessageAsync() { - await _messageSender.SendEvent( + await _messageSender.SendEventAsync( OutputEvent.Type, new OutputEventBody { @@ -947,25 +947,25 @@ await _messageSender.SendEvent( private void RegisterEventHandlers() { - _editorSession.PowerShellContext.RunspaceChanged += powerShellContext_RunspaceChanged; - _editorSession.DebugService.BreakpointUpdated += DebugService_BreakpointUpdated; - _editorSession.DebugService.DebuggerStopped += DebugService_DebuggerStopped; - _editorSession.PowerShellContext.DebuggerResumed += powerShellContext_DebuggerResumed; + _editorSession.PowerShellContext.RunspaceChanged += powerShellContext_RunspaceChangedAsync; + _editorSession.DebugService.BreakpointUpdated += DebugService_BreakpointUpdatedAsync; + _editorSession.DebugService.DebuggerStopped += DebugService_DebuggerStoppedAsync; + _editorSession.PowerShellContext.DebuggerResumed += powerShellContext_DebuggerResumedAsync; } private void UnregisterEventHandlers() { - _editorSession.PowerShellContext.RunspaceChanged -= powerShellContext_RunspaceChanged; - _editorSession.DebugService.BreakpointUpdated -= DebugService_BreakpointUpdated; - _editorSession.DebugService.DebuggerStopped -= DebugService_DebuggerStopped; - _editorSession.PowerShellContext.DebuggerResumed -= powerShellContext_DebuggerResumed; + _editorSession.PowerShellContext.RunspaceChanged -= powerShellContext_RunspaceChangedAsync; + _editorSession.DebugService.BreakpointUpdated -= DebugService_BreakpointUpdatedAsync; + _editorSession.DebugService.DebuggerStopped -= DebugService_DebuggerStoppedAsync; + _editorSession.PowerShellContext.DebuggerResumed -= powerShellContext_DebuggerResumedAsync; } - private async Task ClearSessionBreakpoints() + private async Task ClearSessionBreakpointsAsync() { try { - await _editorSession.DebugService.ClearAllBreakpoints(); + await _editorSession.DebugService.ClearAllBreakpointsAsync(); } catch (Exception e) { @@ -977,7 +977,7 @@ private async Task ClearSessionBreakpoints() #region Event Handlers - async void DebugService_DebuggerStopped(object sender, DebuggerStoppedEventArgs e) + async void DebugService_DebuggerStoppedAsync(object sender, DebuggerStoppedEventArgs e) { // Provide the reason for why the debugger has stopped script execution. // See https://github.com/Microsoft/vscode/issues/3648 @@ -994,7 +994,7 @@ e.OriginalEvent.Breakpoints[0] is CommandBreakpoint : "breakpoint"; } - await _messageSender.SendEvent( + await _messageSender.SendEventAsync( StoppedEvent.Type, new StoppedEventBody { @@ -1007,7 +1007,7 @@ await _messageSender.SendEvent( }); } - async void powerShellContext_RunspaceChanged(object sender, RunspaceChangedEventArgs e) + async void powerShellContext_RunspaceChangedAsync(object sender, RunspaceChangedEventArgs e) { if (_waitingForAttach && e.ChangeAction == RunspaceChangeAction.Enter && @@ -1016,7 +1016,7 @@ async void powerShellContext_RunspaceChanged(object sender, RunspaceChangedEvent // Send the InitializedEvent so that the debugger will continue // sending configuration requests _waitingForAttach = false; - await _messageSender.SendEvent(InitializedEvent.Type, null); + await _messageSender.SendEventAsync(InitializedEvent.Type, null); } else if ( e.ChangeAction == RunspaceChangeAction.Exit && @@ -1026,7 +1026,7 @@ async void powerShellContext_RunspaceChanged(object sender, RunspaceChangedEvent // Exited the session while the debugger is stopped, // send a ContinuedEvent so that the client changes the // UI to appear to be running again - await _messageSender.SendEvent( + await _messageSender.SendEventAsync( ContinuedEvent.Type, new ContinuedEvent { @@ -1036,9 +1036,9 @@ await _messageSender.SendEvent( } } - private async void powerShellContext_DebuggerResumed(object sender, DebuggerResumeAction e) + private async void powerShellContext_DebuggerResumedAsync(object sender, DebuggerResumeAction e) { - await _messageSender.SendEvent( + await _messageSender.SendEventAsync( ContinuedEvent.Type, new ContinuedEvent { @@ -1047,7 +1047,7 @@ await _messageSender.SendEvent( }); } - private async void DebugService_BreakpointUpdated(object sender, BreakpointUpdatedEventArgs e) + private async void DebugService_BreakpointUpdatedAsync(object sender, BreakpointUpdatedEventArgs e) { string reason = "changed"; @@ -1088,7 +1088,7 @@ private async void DebugService_BreakpointUpdated(object sender, BreakpointUpdat breakpoint.Verified = e.UpdateType != BreakpointUpdateType.Disabled; - await _messageSender.SendEvent( + await _messageSender.SendEventAsync( BreakpointEvent.Type, new BreakpointEvent { diff --git a/src/PowerShellEditorServices.Protocol/Server/IMessageDispatcher.cs b/src/PowerShellEditorServices.Protocol/Server/IMessageDispatcher.cs index 45342a21b..156acb9b2 100644 --- a/src/PowerShellEditorServices.Protocol/Server/IMessageDispatcher.cs +++ b/src/PowerShellEditorServices.Protocol/Server/IMessageDispatcher.cs @@ -10,7 +10,7 @@ namespace Microsoft.PowerShell.EditorServices.Protocol { public interface IMessageDispatcher { - Task DispatchMessage( + Task DispatchMessageAsync( Message messageToDispatch, MessageWriter messageWriter); } diff --git a/src/PowerShellEditorServices.Protocol/Server/LanguageServer.cs b/src/PowerShellEditorServices.Protocol/Server/LanguageServer.cs index fe30cd1b2..d325b2d65 100644 --- a/src/PowerShellEditorServices.Protocol/Server/LanguageServer.cs +++ b/src/PowerShellEditorServices.Protocol/Server/LanguageServer.cs @@ -80,13 +80,13 @@ public LanguageServer( this.editorSession = editorSession; this.serverCompletedTask = serverCompletedTask; // Attach to the underlying PowerShell context to listen for changes in the runspace or execution status - this.editorSession.PowerShellContext.RunspaceChanged += PowerShellContext_RunspaceChanged; - this.editorSession.PowerShellContext.ExecutionStatusChanged += PowerShellContext_ExecutionStatusChanged; + this.editorSession.PowerShellContext.RunspaceChanged += PowerShellContext_RunspaceChangedAsync; + this.editorSession.PowerShellContext.ExecutionStatusChanged += PowerShellContext_ExecutionStatusChangedAsync; // Attach to ExtensionService events - this.editorSession.ExtensionService.CommandAdded += ExtensionService_ExtensionAdded; - this.editorSession.ExtensionService.CommandUpdated += ExtensionService_ExtensionUpdated; - this.editorSession.ExtensionService.CommandRemoved += ExtensionService_ExtensionRemoved; + this.editorSession.ExtensionService.CommandAdded += ExtensionService_ExtensionAddedAsync; + this.editorSession.ExtensionService.CommandUpdated += ExtensionService_ExtensionUpdatedAsync; + this.editorSession.ExtensionService.CommandRemoved += ExtensionService_ExtensionRemovedAsync; this.messageSender = messageSender; this.messageHandlers = messageHandlers; @@ -98,7 +98,7 @@ public LanguageServer( this.messageSender); this.editorSession.StartDebugService(this.editorOperations); - this.editorSession.DebugService.DebuggerStopped += DebugService_DebuggerStopped; + this.editorSession.DebugService.DebuggerStopped += DebugService_DebuggerStoppedAsync; } /// @@ -109,61 +109,61 @@ public void Start() { // Register all supported message types - this.messageHandlers.SetRequestHandler(ShutdownRequest.Type, this.HandleShutdownRequest); - this.messageHandlers.SetEventHandler(ExitNotification.Type, this.HandleExitNotification); - - this.messageHandlers.SetRequestHandler(InitializeRequest.Type, this.HandleInitializeRequest); - this.messageHandlers.SetEventHandler(InitializedNotification.Type, this.HandleInitializedNotification); - - this.messageHandlers.SetEventHandler(DidOpenTextDocumentNotification.Type, this.HandleDidOpenTextDocumentNotification); - this.messageHandlers.SetEventHandler(DidCloseTextDocumentNotification.Type, this.HandleDidCloseTextDocumentNotification); - this.messageHandlers.SetEventHandler(DidSaveTextDocumentNotification.Type, this.HandleDidSaveTextDocumentNotification); - this.messageHandlers.SetEventHandler(DidChangeTextDocumentNotification.Type, this.HandleDidChangeTextDocumentNotification); - this.messageHandlers.SetEventHandler(DidChangeConfigurationNotification.Type, this.HandleDidChangeConfigurationNotification); - - this.messageHandlers.SetRequestHandler(DefinitionRequest.Type, this.HandleDefinitionRequest); - this.messageHandlers.SetRequestHandler(ReferencesRequest.Type, this.HandleReferencesRequest); - this.messageHandlers.SetRequestHandler(CompletionRequest.Type, this.HandleCompletionRequest); - this.messageHandlers.SetRequestHandler(CompletionResolveRequest.Type, this.HandleCompletionResolveRequest); - this.messageHandlers.SetRequestHandler(SignatureHelpRequest.Type, this.HandleSignatureHelpRequest); - this.messageHandlers.SetRequestHandler(DocumentHighlightRequest.Type, this.HandleDocumentHighlightRequest); - this.messageHandlers.SetRequestHandler(HoverRequest.Type, this.HandleHoverRequest); - this.messageHandlers.SetRequestHandler(WorkspaceSymbolRequest.Type, this.HandleWorkspaceSymbolRequest); - this.messageHandlers.SetRequestHandler(CodeActionRequest.Type, this.HandleCodeActionRequest); - this.messageHandlers.SetRequestHandler(DocumentFormattingRequest.Type, this.HandleDocumentFormattingRequest); + this.messageHandlers.SetRequestHandler(ShutdownRequest.Type, this.HandleShutdownRequestAsync); + this.messageHandlers.SetEventHandler(ExitNotification.Type, this.HandleExitNotificationAsync); + + this.messageHandlers.SetRequestHandler(InitializeRequest.Type, this.HandleInitializeRequestAsync); + this.messageHandlers.SetEventHandler(InitializedNotification.Type, this.HandleInitializedNotificationAsync); + + this.messageHandlers.SetEventHandler(DidOpenTextDocumentNotification.Type, this.HandleDidOpenTextDocumentNotificationAsync); + this.messageHandlers.SetEventHandler(DidCloseTextDocumentNotification.Type, this.HandleDidCloseTextDocumentNotificationAsync); + this.messageHandlers.SetEventHandler(DidSaveTextDocumentNotification.Type, this.HandleDidSaveTextDocumentNotificationAsync); + this.messageHandlers.SetEventHandler(DidChangeTextDocumentNotification.Type, this.HandleDidChangeTextDocumentNotificationAsync); + this.messageHandlers.SetEventHandler(DidChangeConfigurationNotification.Type, this.HandleDidChangeConfigurationNotificationAsync); + + this.messageHandlers.SetRequestHandler(DefinitionRequest.Type, this.HandleDefinitionRequestAsync); + this.messageHandlers.SetRequestHandler(ReferencesRequest.Type, this.HandleReferencesRequestAsync); + this.messageHandlers.SetRequestHandler(CompletionRequest.Type, this.HandleCompletionRequestAsync); + this.messageHandlers.SetRequestHandler(CompletionResolveRequest.Type, this.HandleCompletionResolveRequestAsync); + this.messageHandlers.SetRequestHandler(SignatureHelpRequest.Type, this.HandleSignatureHelpRequestAsync); + this.messageHandlers.SetRequestHandler(DocumentHighlightRequest.Type, this.HandleDocumentHighlightRequestAsync); + this.messageHandlers.SetRequestHandler(HoverRequest.Type, this.HandleHoverRequestAsync); + this.messageHandlers.SetRequestHandler(WorkspaceSymbolRequest.Type, this.HandleWorkspaceSymbolRequestAsync); + this.messageHandlers.SetRequestHandler(CodeActionRequest.Type, this.HandleCodeActionRequestAsync); + this.messageHandlers.SetRequestHandler(DocumentFormattingRequest.Type, this.HandleDocumentFormattingRequestAsync); this.messageHandlers.SetRequestHandler( DocumentRangeFormattingRequest.Type, - this.HandleDocumentRangeFormattingRequest); + this.HandleDocumentRangeFormattingRequestAsync); this.messageHandlers.SetRequestHandler(FoldingRangeRequest.Type, this.HandleFoldingRangeRequestAsync); - this.messageHandlers.SetRequestHandler(ShowHelpRequest.Type, this.HandleShowHelpRequest); + this.messageHandlers.SetRequestHandler(ShowHelpRequest.Type, this.HandleShowHelpRequestAsync); - this.messageHandlers.SetRequestHandler(ExpandAliasRequest.Type, this.HandleExpandAliasRequest); + this.messageHandlers.SetRequestHandler(ExpandAliasRequest.Type, this.HandleExpandAliasRequestAsync); this.messageHandlers.SetRequestHandler(GetCommandRequest.Type, this.HandleGetCommandRequestAsync); - this.messageHandlers.SetRequestHandler(FindModuleRequest.Type, this.HandleFindModuleRequest); - this.messageHandlers.SetRequestHandler(InstallModuleRequest.Type, this.HandleInstallModuleRequest); + this.messageHandlers.SetRequestHandler(FindModuleRequest.Type, this.HandleFindModuleRequestAsync); + this.messageHandlers.SetRequestHandler(InstallModuleRequest.Type, this.HandleInstallModuleRequestAsync); - this.messageHandlers.SetRequestHandler(InvokeExtensionCommandRequest.Type, this.HandleInvokeExtensionCommandRequest); + this.messageHandlers.SetRequestHandler(InvokeExtensionCommandRequest.Type, this.HandleInvokeExtensionCommandRequestAsync); - this.messageHandlers.SetRequestHandler(PowerShellVersionRequest.Type, this.HandlePowerShellVersionRequest); + this.messageHandlers.SetRequestHandler(PowerShellVersionRequest.Type, this.HandlePowerShellVersionRequestAsync); - this.messageHandlers.SetRequestHandler(NewProjectFromTemplateRequest.Type, this.HandleNewProjectFromTemplateRequest); - this.messageHandlers.SetRequestHandler(GetProjectTemplatesRequest.Type, this.HandleGetProjectTemplatesRequest); + this.messageHandlers.SetRequestHandler(NewProjectFromTemplateRequest.Type, this.HandleNewProjectFromTemplateRequestAsync); + this.messageHandlers.SetRequestHandler(GetProjectTemplatesRequest.Type, this.HandleGetProjectTemplatesRequestAsync); - this.messageHandlers.SetRequestHandler(DebugAdapterMessages.EvaluateRequest.Type, this.HandleEvaluateRequest); + this.messageHandlers.SetRequestHandler(DebugAdapterMessages.EvaluateRequest.Type, this.HandleEvaluateRequestAsync); - this.messageHandlers.SetRequestHandler(GetPSSARulesRequest.Type, this.HandleGetPSSARulesRequest); - this.messageHandlers.SetRequestHandler(SetPSSARulesRequest.Type, this.HandleSetPSSARulesRequest); + this.messageHandlers.SetRequestHandler(GetPSSARulesRequest.Type, this.HandleGetPSSARulesRequestAsync); + this.messageHandlers.SetRequestHandler(SetPSSARulesRequest.Type, this.HandleSetPSSARulesRequestAsync); - this.messageHandlers.SetRequestHandler(ScriptRegionRequest.Type, this.HandleGetFormatScriptRegionRequest); + this.messageHandlers.SetRequestHandler(ScriptRegionRequest.Type, this.HandleGetFormatScriptRegionRequestAsync); - this.messageHandlers.SetRequestHandler(GetPSHostProcessesRequest.Type, this.HandleGetPSHostProcessesRequest); - this.messageHandlers.SetRequestHandler(CommentHelpRequest.Type, this.HandleCommentHelpRequest); + this.messageHandlers.SetRequestHandler(GetPSHostProcessesRequest.Type, this.HandleGetPSHostProcessesRequestAsync); + this.messageHandlers.SetRequestHandler(CommentHelpRequest.Type, this.HandleCommentHelpRequestAsync); // Initialize the extension service // TODO: This should be made awaited once Initialize is async! - this.editorSession.ExtensionService.Initialize( + this.editorSession.ExtensionService.InitializeAsync( this.editorOperations, this.editorSession.Components).Wait(); } @@ -180,15 +180,15 @@ protected Task Stop() #region Built-in Message Handlers - private async Task HandleShutdownRequest( + private async Task HandleShutdownRequestAsync( RequestContext requestContext) { // Allow the implementor to shut down gracefully - await requestContext.SendResult(new object()); + await requestContext.SendResultAsync(new object()); } - private async Task HandleExitNotification( + private async Task HandleExitNotificationAsync( object exitParams, EventContext eventContext) { @@ -196,14 +196,14 @@ private async Task HandleExitNotification( await this.Stop(); } - private Task HandleInitializedNotification(InitializedParams initializedParams, + private Task HandleInitializedNotificationAsync(InitializedParams initializedParams, EventContext eventContext) { // Can do dynamic registration of capabilities in this notification handler return Task.FromResult(true); } - protected async Task HandleInitializeRequest( + protected async Task HandleInitializeRequestAsync( InitializeParams initializeParams, RequestContext requestContext) { @@ -213,12 +213,12 @@ protected async Task HandleInitializeRequest( // Set the working directory of the PowerShell session to the workspace path if (editorSession.Workspace.WorkspacePath != null) { - await editorSession.PowerShellContext.SetWorkingDirectory( + await editorSession.PowerShellContext.SetWorkingDirectoryAsync( editorSession.Workspace.WorkspacePath, isPathAlreadyEscaped: false); } - await requestContext.SendResult( + await requestContext.SendResultAsync( new InitializeResult { Capabilities = new ServerCapabilities @@ -249,7 +249,7 @@ await requestContext.SendResult( }); } - protected async Task HandleShowHelpRequest( + protected async Task HandleShowHelpRequestAsync( string helpParams, RequestContext requestContext) { @@ -292,11 +292,11 @@ protected async Task HandleShowHelpRequest( // TODO: Rather than print the help in the console, we should send the string back // to VSCode to display in a help pop-up (or similar) - await editorSession.PowerShellContext.ExecuteCommand(checkHelpPSCommand, sendOutputToHost: true); - await requestContext.SendResult(null); + await editorSession.PowerShellContext.ExecuteCommandAsync(checkHelpPSCommand, sendOutputToHost: true); + await requestContext.SendResultAsync(null); } - private async Task HandleSetPSSARulesRequest( + private async Task HandleSetPSSARulesRequestAsync( object param, RequestContext requestContext) { @@ -316,16 +316,16 @@ private async Task HandleSetPSSARulesRequest( editorSession.AnalysisService.ActiveRules = activeRules.ToArray(); } - var sendresult = requestContext.SendResult(null); + var sendresult = requestContext.SendResultAsync(null); var scripFile = editorSession.Workspace.GetFile((string)dynParams.filepath); - await RunScriptDiagnostics( + await RunScriptDiagnosticsAsync( new ScriptFile[] { scripFile }, editorSession, - this.messageSender.SendEvent); + this.messageSender.SendEventAsync); await sendresult; } - private async Task HandleGetFormatScriptRegionRequest( + private async Task HandleGetFormatScriptRegionRequestAsync( ScriptRegionRequestParams requestParams, RequestContext requestContext) { @@ -361,13 +361,13 @@ private async Task HandleGetFormatScriptRegionRequest( break; } - await requestContext.SendResult(new ScriptRegionRequestResult + await requestContext.SendResultAsync(new ScriptRegionRequestResult { scriptRegion = scriptRegion }); } - private async Task HandleGetPSSARulesRequest( + private async Task HandleGetPSSARulesRequestAsync( object param, RequestContext requestContext) { @@ -384,10 +384,10 @@ private async Task HandleGetPSSARulesRequest( } } - await requestContext.SendResult(rules); + await requestContext.SendResultAsync(rules); } - private async Task HandleInstallModuleRequest( + private async Task HandleInstallModuleRequestAsync( string moduleName, RequestContext requestContext ) @@ -395,15 +395,15 @@ RequestContext requestContext var script = string.Format("Install-Module -Name {0} -Scope CurrentUser", moduleName); var executeTask = - editorSession.PowerShellContext.ExecuteScriptString( + editorSession.PowerShellContext.ExecuteScriptStringAsync( script, true, true).ConfigureAwait(false); - await requestContext.SendResult(null); + await requestContext.SendResultAsync(null); } - private Task HandleInvokeExtensionCommandRequest( + private Task HandleInvokeExtensionCommandRequestAsync( InvokeExtensionCommandRequest commandDetails, RequestContext requestContext) { @@ -416,29 +416,29 @@ private Task HandleInvokeExtensionCommandRequest( commandDetails.Context); Task commandTask = - this.editorSession.ExtensionService.InvokeCommand( + this.editorSession.ExtensionService.InvokeCommandAsync( commandDetails.Name, editorContext); commandTask.ContinueWith(t => { - return requestContext.SendResult(null); + return requestContext.SendResultAsync(null); }); return Task.FromResult(true); } - private Task HandleNewProjectFromTemplateRequest( + private Task HandleNewProjectFromTemplateRequestAsync( NewProjectFromTemplateRequest newProjectArgs, RequestContext requestContext) { // Don't await the Task here so that we don't block the session this.editorSession.TemplateService - .CreateFromTemplate(newProjectArgs.TemplatePath, newProjectArgs.DestinationPath) + .CreateFromTemplateAsync(newProjectArgs.TemplatePath, newProjectArgs.DestinationPath) .ContinueWith( async task => { - await requestContext.SendResult( + await requestContext.SendResultAsync( new NewProjectFromTemplateResponse { CreationSuccessful = task.Result @@ -448,19 +448,19 @@ await requestContext.SendResult( return Task.FromResult(true); } - private async Task HandleGetProjectTemplatesRequest( + private async Task HandleGetProjectTemplatesRequestAsync( GetProjectTemplatesRequest requestArgs, RequestContext requestContext) { - bool plasterInstalled = await this.editorSession.TemplateService.ImportPlasterIfInstalled(); + bool plasterInstalled = await this.editorSession.TemplateService.ImportPlasterIfInstalledAsync(); if (plasterInstalled) { var availableTemplates = - await this.editorSession.TemplateService.GetAvailableTemplates( + await this.editorSession.TemplateService.GetAvailableTemplatesAsync( requestArgs.IncludeInstalledModules); - await requestContext.SendResult( + await requestContext.SendResultAsync( new GetProjectTemplatesResponse { Templates = availableTemplates @@ -468,7 +468,7 @@ await requestContext.SendResult( } else { - await requestContext.SendResult( + await requestContext.SendResultAsync( new GetProjectTemplatesResponse { NeedsModuleInstall = true, @@ -477,7 +477,7 @@ await requestContext.SendResult( } } - private async Task HandleExpandAliasRequest( + private async Task HandleExpandAliasRequestAsync( string content, RequestContext requestContext) { @@ -506,13 +506,13 @@ function __Expand-Alias { }"; var psCommand = new PSCommand(); psCommand.AddScript(script); - await this.editorSession.PowerShellContext.ExecuteCommand(psCommand); + await this.editorSession.PowerShellContext.ExecuteCommandAsync(psCommand); psCommand = new PSCommand(); psCommand.AddCommand("__Expand-Alias").AddArgument(content); - var result = await this.editorSession.PowerShellContext.ExecuteCommand(psCommand); + var result = await this.editorSession.PowerShellContext.ExecuteCommandAsync(psCommand); - await requestContext.SendResult(result.First().ToString()); + await requestContext.SendResultAsync(result.First().ToString()); } private async Task HandleGetCommandRequestAsync( @@ -536,9 +536,10 @@ private async Task HandleGetCommandRequestAsync( .AddCommand("Microsoft.PowerShell.Utility\\Sort-Object") .AddParameter("Property", "Name"); } - IEnumerable result = await this.editorSession.PowerShellContext.ExecuteCommand(psCommand); - var commandList = new List(); + IEnumerable result = await this.editorSession.PowerShellContext.ExecuteCommandAsync(psCommand); + + var commandList = new List(); if (result != null) { foreach (dynamic command in result) @@ -554,17 +555,17 @@ private async Task HandleGetCommandRequestAsync( } } - await requestContext.SendResult(commandList); + await requestContext.SendResultAsync(commandList); } - private async Task HandleFindModuleRequest( + private async Task HandleFindModuleRequestAsync( object param, RequestContext requestContext) { var psCommand = new PSCommand(); psCommand.AddScript("Find-Module | Select Name, Description"); - var modules = await editorSession.PowerShellContext.ExecuteCommand(psCommand); + var modules = await editorSession.PowerShellContext.ExecuteCommandAsync(psCommand); var moduleList = new List(); @@ -576,10 +577,10 @@ private async Task HandleFindModuleRequest( } } - await requestContext.SendResult(moduleList); + await requestContext.SendResultAsync(moduleList); } - protected Task HandleDidOpenTextDocumentNotification( + protected Task HandleDidOpenTextDocumentNotificationAsync( DidOpenTextDocumentParams openParams, EventContext eventContext) { @@ -589,7 +590,7 @@ protected Task HandleDidOpenTextDocumentNotification( openParams.TextDocument.Text); // TODO: Get all recently edited files in the workspace - this.RunScriptDiagnostics( + this.RunScriptDiagnosticsAsync( new ScriptFile[] { openedFile }, editorSession, eventContext); @@ -599,7 +600,7 @@ protected Task HandleDidOpenTextDocumentNotification( return Task.FromResult(true); } - protected async Task HandleDidCloseTextDocumentNotification( + protected async Task HandleDidCloseTextDocumentNotificationAsync( DidCloseTextDocumentParams closeParams, EventContext eventContext) { @@ -609,12 +610,12 @@ protected async Task HandleDidCloseTextDocumentNotification( if (fileToClose != null) { editorSession.Workspace.CloseFile(fileToClose); - await ClearMarkers(fileToClose, eventContext); + await ClearMarkersAsync(fileToClose, eventContext); } Logger.Write(LogLevel.Verbose, "Finished closing document."); } - protected async Task HandleDidSaveTextDocumentNotification( + protected async Task HandleDidSaveTextDocumentNotificationAsync( DidSaveTextDocumentParams saveParams, EventContext eventContext) { @@ -626,13 +627,13 @@ protected async Task HandleDidSaveTextDocumentNotification( { if (this.editorSession.RemoteFileManager.IsUnderRemoteTempPath(savedFile.FilePath)) { - await this.editorSession.RemoteFileManager.SaveRemoteFile( + await this.editorSession.RemoteFileManager.SaveRemoteFileAsync( savedFile.FilePath); } } } - protected Task HandleDidChangeTextDocumentNotification( + protected Task HandleDidChangeTextDocumentNotificationAsync( DidChangeTextDocumentParams textChangeParams, EventContext eventContext) { @@ -652,7 +653,7 @@ protected Task HandleDidChangeTextDocumentNotification( } // TODO: Get all recently edited files in the workspace - this.RunScriptDiagnostics( + this.RunScriptDiagnosticsAsync( changedFiles.ToArray(), editorSession, eventContext); @@ -660,7 +661,7 @@ protected Task HandleDidChangeTextDocumentNotification( return Task.FromResult(true); } - protected async Task HandleDidChangeConfigurationNotification( + protected async Task HandleDidChangeConfigurationNotificationAsync( DidChangeConfigurationParams configChangeParams, EventContext eventContext) { @@ -679,7 +680,7 @@ protected async Task HandleDidChangeConfigurationNotification( this.currentSettings.EnableProfileLoading && oldLoadProfiles != this.currentSettings.EnableProfileLoading) { - await this.editorSession.PowerShellContext.LoadHostProfiles(); + await this.editorSession.PowerShellContext.LoadHostProfilesAsync(); this.profilesLoaded = true; } @@ -713,18 +714,18 @@ protected async Task HandleDidChangeConfigurationNotification( { foreach (var scriptFile in editorSession.Workspace.GetOpenedFiles()) { - await ClearMarkers(scriptFile, eventContext); + await ClearMarkersAsync(scriptFile, eventContext); } } - await this.RunScriptDiagnostics( + await this.RunScriptDiagnosticsAsync( this.editorSession.Workspace.GetOpenedFiles(), this.editorSession, eventContext); } } - protected async Task HandleDefinitionRequest( + protected async Task HandleDefinitionRequestAsync( TextDocumentPositionParams textDocumentPosition, RequestContext requestContext) { @@ -744,7 +745,7 @@ protected async Task HandleDefinitionRequest( if (foundSymbol != null) { definition = - await editorSession.LanguageService.GetDefinitionOfSymbol( + await editorSession.LanguageService.GetDefinitionOfSymbolAsync( scriptFile, foundSymbol, editorSession.Workspace); @@ -760,10 +761,10 @@ await editorSession.LanguageService.GetDefinitionOfSymbol( } } - await requestContext.SendResult(definitionLocations.ToArray()); + await requestContext.SendResultAsync(definitionLocations.ToArray()); } - protected async Task HandleReferencesRequest( + protected async Task HandleReferencesRequestAsync( ReferencesParams referencesParams, RequestContext requestContext) { @@ -778,7 +779,7 @@ protected async Task HandleReferencesRequest( referencesParams.Position.Character + 1); FindReferencesResult referencesResult = - await editorSession.LanguageService.FindReferencesOfSymbol( + await editorSession.LanguageService.FindReferencesOfSymbolAsync( foundSymbol, editorSession.Workspace.ExpandScriptReferences(scriptFile), editorSession.Workspace); @@ -799,10 +800,10 @@ await editorSession.LanguageService.FindReferencesOfSymbol( referenceLocations = locations.ToArray(); } - await requestContext.SendResult(referenceLocations); + await requestContext.SendResultAsync(referenceLocations); } - protected async Task HandleCompletionRequest( + protected async Task HandleCompletionRequestAsync( TextDocumentPositionParams textDocumentPositionParams, RequestContext requestContext) { @@ -814,7 +815,7 @@ protected async Task HandleCompletionRequest( textDocumentPositionParams.TextDocument.Uri); CompletionResults completionResults = - await editorSession.LanguageService.GetCompletionsInFile( + await editorSession.LanguageService.GetCompletionsInFileAsync( scriptFile, cursorLine, cursorColumn); @@ -830,10 +831,10 @@ await editorSession.LanguageService.GetCompletionsInFile( } } - await requestContext.SendResult(completionItems); + await requestContext.SendResultAsync(completionItems); } - protected async Task HandleCompletionResolveRequest( + protected async Task HandleCompletionResolveRequestAsync( CompletionItem completionItem, RequestContext requestContext) { @@ -841,24 +842,24 @@ protected async Task HandleCompletionResolveRequest( { // Get the documentation for the function CommandInfo commandInfo = - await CommandHelpers.GetCommandInfo( + await CommandHelpers.GetCommandInfoAsync( completionItem.Label, this.editorSession.PowerShellContext); if (commandInfo != null) { completionItem.Documentation = - await CommandHelpers.GetCommandSynopsis( + await CommandHelpers.GetCommandSynopsisAsync( commandInfo, this.editorSession.PowerShellContext); } } // Send back the updated CompletionItem - await requestContext.SendResult(completionItem); + await requestContext.SendResultAsync(completionItem); } - protected async Task HandleSignatureHelpRequest( + protected async Task HandleSignatureHelpRequestAsync( TextDocumentPositionParams textDocumentPositionParams, RequestContext requestContext) { @@ -867,7 +868,7 @@ protected async Task HandleSignatureHelpRequest( textDocumentPositionParams.TextDocument.Uri); ParameterSetSignatures parameterSets = - await editorSession.LanguageService.FindParameterSetsInFile( + await editorSession.LanguageService.FindParameterSetsInFileAsync( scriptFile, textDocumentPositionParams.Position.Line + 1, textDocumentPositionParams.Position.Character + 1); @@ -896,7 +897,7 @@ await editorSession.LanguageService.FindParameterSetsInFile( } } - await requestContext.SendResult( + await requestContext.SendResultAsync( new SignatureHelp { Signatures = signatures, @@ -905,7 +906,7 @@ await requestContext.SendResult( }); } - protected async Task HandleDocumentHighlightRequest( + protected async Task HandleDocumentHighlightRequestAsync( TextDocumentPositionParams textDocumentPositionParams, RequestContext requestContext) { @@ -935,10 +936,10 @@ protected async Task HandleDocumentHighlightRequest( documentHighlights = highlights.ToArray(); } - await requestContext.SendResult(documentHighlights); + await requestContext.SendResultAsync(documentHighlights); } - protected async Task HandleHoverRequest( + protected async Task HandleHoverRequestAsync( TextDocumentPositionParams textDocumentPositionParams, RequestContext requestContext) { @@ -949,7 +950,7 @@ protected async Task HandleHoverRequest( SymbolDetails symbolDetails = await editorSession .LanguageService - .FindSymbolDetailsAtLocation( + .FindSymbolDetailsAtLocationAsync( scriptFile, textDocumentPositionParams.Position.Line + 1, textDocumentPositionParams.Position.Character + 1); @@ -979,7 +980,7 @@ await editorSession symbolRange = GetRangeFromScriptRegion(symbolDetails.SymbolReference.ScriptRegion); } - await requestContext.SendResult( + await requestContext.SendResultAsync( new Hover { Contents = symbolInfo.ToArray(), @@ -987,7 +988,7 @@ await requestContext.SendResult( }); } - protected async Task HandleDocumentSymbolRequest( + protected async Task HandleDocumentSymbolRequestAsync( DocumentSymbolParams documentSymbolParams, RequestContext requestContext) { @@ -1024,7 +1025,7 @@ protected async Task HandleDocumentSymbolRequest( symbols = symbolAcc.ToArray(); } - await requestContext.SendResult(symbols); + await requestContext.SendResultAsync(symbols); } public static SymbolKind GetSymbolKind(SymbolType symbolType) @@ -1055,7 +1056,7 @@ public static string GetDecoratedSymbolName(SymbolReference symbolReference) return name; } - protected async Task HandleWorkspaceSymbolRequest( + protected async Task HandleWorkspaceSymbolRequestAsync( WorkspaceSymbolParams workspaceSymbolParams, RequestContext requestContext) { @@ -1096,19 +1097,19 @@ protected async Task HandleWorkspaceSymbolRequest( } } - await requestContext.SendResult(symbols.ToArray()); + await requestContext.SendResultAsync(symbols.ToArray()); } - protected async Task HandlePowerShellVersionRequest( + protected async Task HandlePowerShellVersionRequestAsync( object noParams, RequestContext requestContext) { - await requestContext.SendResult( + await requestContext.SendResultAsync( new PowerShellVersion( this.editorSession.PowerShellContext.LocalPowerShellVersion)); } - protected async Task HandleGetPSHostProcessesRequest( + protected async Task HandleGetPSHostProcessesRequestAsync( object noParams, RequestContext requestContext) { @@ -1124,7 +1125,7 @@ protected async Task HandleGetPSHostProcessesRequest( .AddParameter("NE") .AddParameter("Value", processId.ToString()); - var processes = await editorSession.PowerShellContext.ExecuteCommand(psCommand); + var processes = await editorSession.PowerShellContext.ExecuteCommandAsync(psCommand); if (processes != null) { foreach (dynamic p in processes) @@ -1141,10 +1142,10 @@ protected async Task HandleGetPSHostProcessesRequest( } } - await requestContext.SendResult(psHostProcesses.ToArray()); + await requestContext.SendResultAsync(psHostProcesses.ToArray()); } - protected async Task HandleCommentHelpRequest( + protected async Task HandleCommentHelpRequestAsync( CommentHelpRequestParams requestParams, RequestContext requestContext) { @@ -1153,7 +1154,7 @@ protected async Task HandleCommentHelpRequest( ScriptFile scriptFile; if (!this.editorSession.Workspace.TryGetFile(requestParams.DocumentUri, out scriptFile)) { - await requestContext.SendResult(result); + await requestContext.SendResultAsync(result); return; } @@ -1167,7 +1168,7 @@ protected async Task HandleCommentHelpRequest( if (functionDefinitionAst == null) { - await requestContext.SendResult(result); + await requestContext.SendResultAsync(result); return; } @@ -1200,7 +1201,7 @@ protected async Task HandleCommentHelpRequest( if (helpText == null) { - await requestContext.SendResult(result); + await requestContext.SendResultAsync(result); return; } @@ -1214,7 +1215,7 @@ protected async Task HandleCommentHelpRequest( result.Content = result.Content.Skip(1).ToArray(); } - await requestContext.SendResult(result); + await requestContext.SendResultAsync(result); } private bool IsQueryMatch(string query, string symbolName) @@ -1223,7 +1224,7 @@ private bool IsQueryMatch(string query, string symbolName) } // https://microsoft.github.io/language-server-protocol/specification#textDocument_codeAction - protected async Task HandleCodeActionRequest( + protected async Task HandleCodeActionRequestAsync( CodeActionParams codeActionParams, RequestContext requestContext) { @@ -1282,19 +1283,20 @@ protected async Task HandleCodeActionRequest( } } - await requestContext.SendResult(codeActionCommands.ToArray()); + await requestContext.SendResultAsync( + codeActionCommands.ToArray()); } - protected async Task HandleDocumentFormattingRequest( + protected async Task HandleDocumentFormattingRequestAsync( DocumentFormattingParams formattingParams, RequestContext requestContext) { - var result = await Format( + var result = await FormatAsync( formattingParams.TextDocument.Uri, formattingParams.options, null); - await requestContext.SendResult(new TextEdit[1] + await requestContext.SendResultAsync(new TextEdit[1] { new TextEdit { @@ -1304,16 +1306,16 @@ await requestContext.SendResult(new TextEdit[1] }); } - protected async Task HandleDocumentRangeFormattingRequest( + protected async Task HandleDocumentRangeFormattingRequestAsync( DocumentRangeFormattingParams formattingParams, RequestContext requestContext) { - var result = await Format( + var result = await FormatAsync( formattingParams.TextDocument.Uri, formattingParams.Options, formattingParams.Range); - await requestContext.SendResult(new TextEdit[1] + await requestContext.SendResultAsync(new TextEdit[1] { new TextEdit { @@ -1327,10 +1329,10 @@ protected async Task HandleFoldingRangeRequestAsync( FoldingRangeParams foldingParams, RequestContext requestContext) { - await requestContext.SendResult(Fold(foldingParams.TextDocument.Uri)); + await requestContext.SendResultAsync(Fold(foldingParams.TextDocument.Uri)); } - protected Task HandleEvaluateRequest( + protected Task HandleEvaluateRequestAsync( DebugAdapterMessages.EvaluateRequestArguments evaluateParams, RequestContext requestContext) { @@ -1339,7 +1341,7 @@ protected Task HandleEvaluateRequest( // 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( + this.editorSession.PowerShellContext.ExecuteScriptStringAsync( evaluateParams.Expression, writeInputToHost: true, writeOutputToHost: true, @@ -1353,7 +1355,7 @@ protected Task HandleEvaluateRequest( // Return an empty result since the result value is irrelevant // for this request in the LanguageServer return - requestContext.SendResult( + requestContext.SendResultAsync( new DebugAdapterMessages.EvaluateResponseBody { Result = "", @@ -1400,7 +1402,7 @@ private FoldingRange[] Fold(string documentUri) return result.ToArray(); } - private async Task> Format( + private async Task> FormatAsync( string documentUri, FormattingOptions options, Range range) @@ -1435,7 +1437,7 @@ private async Task> Format( } }; - formattedScript = await editorSession.AnalysisService.Format( + formattedScript = await editorSession.AnalysisService.FormatAsync( scriptFile.Contents, pssaSettings, rangeList); @@ -1443,9 +1445,9 @@ private async Task> Format( return Tuple.Create(formattedScript, editRange); } - private async void PowerShellContext_RunspaceChanged(object sender, Session.RunspaceChangedEventArgs e) + private async void PowerShellContext_RunspaceChangedAsync(object sender, Session.RunspaceChangedEventArgs e) { - await this.messageSender.SendEvent( + await this.messageSender.SendEventAsync( RunspaceChangedEvent.Type, new Protocol.LanguageServer.RunspaceDetails(e.NewRunspace)); } @@ -1455,16 +1457,16 @@ await this.messageSender.SendEvent( /// /// the PowerShell context sending the execution event /// details of the execution status change - private async void PowerShellContext_ExecutionStatusChanged(object sender, ExecutionStatusChangedEventArgs e) + private async void PowerShellContext_ExecutionStatusChangedAsync(object sender, ExecutionStatusChangedEventArgs e) { - await this.messageSender.SendEvent( + await this.messageSender.SendEventAsync( ExecutionStatusChangedEvent.Type, e); } - private async void ExtensionService_ExtensionAdded(object sender, EditorCommand e) + private async void ExtensionService_ExtensionAddedAsync(object sender, EditorCommand e) { - await this.messageSender.SendEvent( + await this.messageSender.SendEventAsync( ExtensionCommandAddedNotification.Type, new ExtensionCommandAddedNotification { @@ -1473,9 +1475,9 @@ await this.messageSender.SendEvent( }); } - private async void ExtensionService_ExtensionUpdated(object sender, EditorCommand e) + private async void ExtensionService_ExtensionUpdatedAsync(object sender, EditorCommand e) { - await this.messageSender.SendEvent( + await this.messageSender.SendEventAsync( ExtensionCommandUpdatedNotification.Type, new ExtensionCommandUpdatedNotification { @@ -1483,9 +1485,9 @@ await this.messageSender.SendEvent( }); } - private async void ExtensionService_ExtensionRemoved(object sender, EditorCommand e) + private async void ExtensionService_ExtensionRemovedAsync(object sender, EditorCommand e) { - await this.messageSender.SendEvent( + await this.messageSender.SendEventAsync( ExtensionCommandRemovedNotification.Type, new ExtensionCommandRemovedNotification { @@ -1493,11 +1495,11 @@ await this.messageSender.SendEvent( }); } - private async void DebugService_DebuggerStopped(object sender, DebuggerStoppedEventArgs e) + private async void DebugService_DebuggerStoppedAsync(object sender, DebuggerStoppedEventArgs e) { if (!this.editorSession.DebugService.IsClientAttached) { - await this.messageSender.SendEvent( + await this.messageSender.SendEventAsync( StartDebuggerEvent.Type, new StartDebuggerEvent()); } @@ -1550,15 +1552,15 @@ private static FileChange GetFileChangeDetails(Range changeRange, string insertS }; } - private Task RunScriptDiagnostics( + private Task RunScriptDiagnosticsAsync( ScriptFile[] filesToAnalyze, EditorSession editorSession, EventContext eventContext) { - return RunScriptDiagnostics(filesToAnalyze, editorSession, this.messageSender.SendEvent); + return RunScriptDiagnosticsAsync(filesToAnalyze, editorSession, this.messageSender.SendEventAsync); } - private Task RunScriptDiagnostics( + private Task RunScriptDiagnosticsAsync( ScriptFile[] filesToAnalyze, EditorSession editorSession, Func, PublishDiagnosticsNotification, Task> eventSender) @@ -1604,7 +1606,7 @@ private Task RunScriptDiagnostics( s_existingRequestCancellation = new CancellationTokenSource(); Task.Factory.StartNew( () => - DelayThenInvokeDiagnostics( + DelayThenInvokeDiagnosticsAsync( 750, filesToAnalyze, this.currentSettings.ScriptAnalysis?.Enable.Value ?? false, @@ -1620,7 +1622,29 @@ private Task RunScriptDiagnostics( return Task.FromResult(true); } - private static async Task DelayThenInvokeDiagnostics( + private static async Task DelayThenInvokeDiagnosticsAsync( + int delayMilliseconds, + ScriptFile[] filesToAnalyze, + bool isScriptAnalysisEnabled, + Dictionary> correctionIndex, + EditorSession editorSession, + EventContext eventContext, + ILogger Logger, + CancellationToken cancellationToken) + { + await DelayThenInvokeDiagnosticsAsync( + delayMilliseconds, + filesToAnalyze, + isScriptAnalysisEnabled, + correctionIndex, + editorSession, + eventContext.SendEventAsync, + Logger, + cancellationToken); + } + + + private static async Task DelayThenInvokeDiagnosticsAsync( int delayMilliseconds, ScriptFile[] filesToAnalyze, bool isScriptAnalysisEnabled, @@ -1641,7 +1665,7 @@ private static async Task DelayThenInvokeDiagnostics( // If the task is cancelled, exit directly foreach (var script in filesToAnalyze) { - await PublishScriptDiagnostics( + await PublishScriptDiagnosticsAsync( script, script.SyntaxMarkers, correctionIndex, @@ -1676,7 +1700,7 @@ await PublishScriptDiagnostics( semanticMarkers = new ScriptFileMarker[0]; } - await PublishScriptDiagnostics( + await PublishScriptDiagnosticsAsync( scriptFile, // Concat script analysis errors to any existing parse errors scriptFile.SyntaxMarkers.Concat(semanticMarkers).ToArray(), @@ -1685,30 +1709,30 @@ await PublishScriptDiagnostics( } } - private async Task ClearMarkers(ScriptFile scriptFile, EventContext eventContext) + private async Task ClearMarkersAsync(ScriptFile scriptFile, EventContext eventContext) { // send empty diagnostic markers to clear any markers associated with the given file - await PublishScriptDiagnostics( + await PublishScriptDiagnosticsAsync( scriptFile, new ScriptFileMarker[0], this.codeActionsPerFile, eventContext); } - private static async Task PublishScriptDiagnostics( + private static async Task PublishScriptDiagnosticsAsync( ScriptFile scriptFile, ScriptFileMarker[] markers, Dictionary> correctionIndex, EventContext eventContext) { - await PublishScriptDiagnostics( + await PublishScriptDiagnosticsAsync( scriptFile, markers, correctionIndex, - eventContext.SendEvent); + eventContext.SendEventAsync); } - private static async Task PublishScriptDiagnostics( + private static async Task PublishScriptDiagnosticsAsync( ScriptFile scriptFile, ScriptFileMarker[] markers, Dictionary> correctionIndex, diff --git a/src/PowerShellEditorServices.Protocol/Server/LanguageServerEditorOperations.cs b/src/PowerShellEditorServices.Protocol/Server/LanguageServerEditorOperations.cs index 8639f5ee3..5df247bd5 100644 --- a/src/PowerShellEditorServices.Protocol/Server/LanguageServerEditorOperations.cs +++ b/src/PowerShellEditorServices.Protocol/Server/LanguageServerEditorOperations.cs @@ -26,10 +26,10 @@ public LanguageServerEditorOperations( this.messageSender = messageSender; } - public async Task GetEditorContext() + public async Task GetEditorContextAsync() { ClientEditorContext clientContext = - await this.messageSender.SendRequest( + await this.messageSender.SendRequestAsync( GetEditorContextRequest.Type, new GetEditorContextRequest(), true); @@ -37,9 +37,9 @@ await this.messageSender.SendRequest( return this.ConvertClientEditorContext(clientContext); } - public async Task InsertText(string filePath, string text, BufferRange insertRange) + public async Task InsertTextAsync(string filePath, string text, BufferRange insertRange) { - await this.messageSender.SendRequest( + await this.messageSender.SendRequestAsync( InsertTextRequest.Type, new InsertTextRequest { @@ -64,9 +64,9 @@ await this.messageSender.SendRequest( // TODO: Set the last param back to true! } - public Task SetSelection(BufferRange selectionRange) + public Task SetSelectionAsync(BufferRange selectionRange) { - return this.messageSender.SendRequest( + return this.messageSender.SendRequestAsync( SetSelectionRequest.Type, new SetSelectionRequest { @@ -109,19 +109,19 @@ public EditorContext ConvertClientEditorContext( clientContext.CurrentFileLanguage); } - public Task NewFile() + public Task NewFileAsync() { return - this.messageSender.SendRequest( + this.messageSender.SendRequestAsync( NewFileRequest.Type, null, true); } - public Task OpenFile(string filePath) + public Task OpenFileAsync(string filePath) { return - this.messageSender.SendRequest( + this.messageSender.SendRequestAsync( OpenFileRequest.Type, new OpenFileDetails { @@ -131,10 +131,10 @@ public Task OpenFile(string filePath) true); } - public Task OpenFile(string filePath, bool preview) + public Task OpenFileAsync(string filePath, bool preview) { return - this.messageSender.SendRequest( + this.messageSender.SendRequestAsync( OpenFileRequest.Type, new OpenFileDetails { @@ -144,24 +144,24 @@ public Task OpenFile(string filePath, bool preview) true); } - public Task CloseFile(string filePath) + public Task CloseFileAsync(string filePath) { return - this.messageSender.SendRequest( + this.messageSender.SendRequestAsync( CloseFileRequest.Type, filePath, true); } - public Task SaveFile(string filePath) + public Task SaveFileAsync(string filePath) { - return SaveFile(filePath, null); + return SaveFileAsync(filePath, null); } - public Task SaveFile(string currentPath, string newSavePath) + public Task SaveFileAsync(string currentPath, string newSavePath) { return - this.messageSender.SendRequest( + this.messageSender.SendRequestAsync( SaveFileRequest.Type, new SaveFileDetails { @@ -181,37 +181,37 @@ public string GetWorkspaceRelativePath(string filePath) return this.editorSession.Workspace.GetRelativePath(filePath); } - public Task ShowInformationMessage(string message) + public Task ShowInformationMessageAsync(string message) { return - this.messageSender.SendRequest( + this.messageSender.SendRequestAsync( ShowInformationMessageRequest.Type, message, true); } - public Task ShowErrorMessage(string message) + public Task ShowErrorMessageAsync(string message) { return - this.messageSender.SendRequest( + this.messageSender.SendRequestAsync( ShowErrorMessageRequest.Type, message, true); } - public Task ShowWarningMessage(string message) + public Task ShowWarningMessageAsync(string message) { return - this.messageSender.SendRequest( + this.messageSender.SendRequestAsync( ShowWarningMessageRequest.Type, message, true); } - public Task SetStatusBarMessage(string message, int? timeout) + public Task SetStatusBarMessageAsync(string message, int? timeout) { return - this.messageSender.SendRequest( + this.messageSender.SendRequestAsync( SetStatusBarMessageRequest.Type, new StatusBarMessageDetails { diff --git a/src/PowerShellEditorServices.Protocol/Server/OutputDebouncer.cs b/src/PowerShellEditorServices.Protocol/Server/OutputDebouncer.cs index 20866655a..079183a26 100644 --- a/src/PowerShellEditorServices.Protocol/Server/OutputDebouncer.cs +++ b/src/PowerShellEditorServices.Protocol/Server/OutputDebouncer.cs @@ -47,7 +47,7 @@ public OutputDebouncer(IMessageSender messageSender) #region Private Methods - protected override async Task OnInvoke(OutputWrittenEventArgs output) + protected override async Task OnInvokeAsync(OutputWrittenEventArgs output) { bool outputIsError = output.OutputType == OutputType.Error; @@ -56,7 +56,7 @@ protected override async Task OnInvoke(OutputWrittenEventArgs output) if (this.currentOutputString != null) { // Flush the output - await this.OnFlush(); + await this.OnFlushAsync(); } this.currentOutputString = string.Empty; @@ -77,13 +77,13 @@ protected override async Task OnInvoke(OutputWrittenEventArgs output) string.Empty); } - protected override async Task OnFlush() + protected override async Task OnFlushAsync() { // Only flush output if there is some to flush if (this.currentOutputString != null) { // Send an event for the current output - await this.messageSender.SendEvent( + await this.messageSender.SendEventAsync( OutputEvent.Type, new OutputEventBody { diff --git a/src/PowerShellEditorServices.VSCode/CustomViews/CustomViewBase.cs b/src/PowerShellEditorServices.VSCode/CustomViews/CustomViewBase.cs index f212ee968..1fdb6ddf0 100644 --- a/src/PowerShellEditorServices.VSCode/CustomViews/CustomViewBase.cs +++ b/src/PowerShellEditorServices.VSCode/CustomViews/CustomViewBase.cs @@ -34,10 +34,10 @@ public CustomViewBase( this.logger = logger; } - internal Task Create() + internal Task CreateAsync() { return - this.messageSender.SendRequest( + this.messageSender.SendRequestAsync( NewCustomViewRequest.Type, new NewCustomViewRequest { @@ -50,7 +50,7 @@ internal Task Create() public Task Show(ViewColumn viewColumn) { return - this.messageSender.SendRequest( + this.messageSender.SendRequestAsync( ShowCustomViewRequest.Type, new ShowCustomViewRequest { @@ -62,7 +62,7 @@ public Task Show(ViewColumn viewColumn) public Task Close() { return - this.messageSender.SendRequest( + this.messageSender.SendRequestAsync( CloseCustomViewRequest.Type, new CloseCustomViewRequest { diff --git a/src/PowerShellEditorServices.VSCode/CustomViews/HtmlContentView.cs b/src/PowerShellEditorServices.VSCode/CustomViews/HtmlContentView.cs index 1ab72e04b..c7a553707 100644 --- a/src/PowerShellEditorServices.VSCode/CustomViews/HtmlContentView.cs +++ b/src/PowerShellEditorServices.VSCode/CustomViews/HtmlContentView.cs @@ -26,10 +26,10 @@ public HtmlContentView( { } - public Task SetContent(string htmlBodyContent) + public Task SetContentAsync(string htmlBodyContent) { return - this.messageSender.SendRequest( + this.messageSender.SendRequestAsync( SetHtmlContentViewRequest.Type, new SetHtmlContentViewRequest { @@ -38,7 +38,7 @@ public Task SetContent(string htmlBodyContent) }, true); } - public Task SetContent(HtmlContent htmlContent) + public Task SetContentAsync(HtmlContent htmlContent) { HtmlContent validatedContent = new HtmlContent() @@ -49,7 +49,7 @@ public Task SetContent(HtmlContent htmlContent) }; return - this.messageSender.SendRequest( + this.messageSender.SendRequestAsync( SetHtmlContentViewRequest.Type, new SetHtmlContentViewRequest { @@ -58,10 +58,10 @@ public Task SetContent(HtmlContent htmlContent) }, true); } - public Task AppendContent(string appendedHtmlBodyContent) + public Task AppendContentAsync(string appendedHtmlBodyContent) { return - this.messageSender.SendRequest( + this.messageSender.SendRequestAsync( AppendHtmlContentViewRequest.Type, new AppendHtmlContentViewRequest { diff --git a/src/PowerShellEditorServices.VSCode/CustomViews/HtmlContentViewsFeature.cs b/src/PowerShellEditorServices.VSCode/CustomViews/HtmlContentViewsFeature.cs index 4ae093c2e..a520fa610 100644 --- a/src/PowerShellEditorServices.VSCode/CustomViews/HtmlContentViewsFeature.cs +++ b/src/PowerShellEditorServices.VSCode/CustomViews/HtmlContentViewsFeature.cs @@ -19,7 +19,7 @@ public HtmlContentViewsFeature( { } - public async Task CreateHtmlContentView(string viewTitle) + public async Task CreateHtmlContentViewAsync(string viewTitle) { HtmlContentView htmlView = new HtmlContentView( @@ -27,7 +27,7 @@ public async Task CreateHtmlContentView(string viewTitle) this.messageSender, this.logger); - await htmlView.Create(); + await htmlView.CreateAsync(); this.AddView(htmlView); return htmlView; diff --git a/src/PowerShellEditorServices.VSCode/CustomViews/IHtmlContentView.cs b/src/PowerShellEditorServices.VSCode/CustomViews/IHtmlContentView.cs index 0d58f2719..c12bc531b 100644 --- a/src/PowerShellEditorServices.VSCode/CustomViews/IHtmlContentView.cs +++ b/src/PowerShellEditorServices.VSCode/CustomViews/IHtmlContentView.cs @@ -21,7 +21,7 @@ public interface IHtmlContentView : ICustomView /// The HTML content that is placed inside of the page's body tag. /// /// A Task which can be awaited for completion. - Task SetContent(string htmlBodyContent); + Task SetContentAsync(string htmlBodyContent); /// /// Sets the HTML content of the view. @@ -30,7 +30,7 @@ public interface IHtmlContentView : ICustomView /// The HTML content that is placed inside of the page's body tag. /// /// A Task which can be awaited for completion. - Task SetContent(HtmlContent htmlContent); + Task SetContentAsync(HtmlContent htmlContent); /// /// Appends HTML body content to the view. @@ -39,6 +39,6 @@ public interface IHtmlContentView : ICustomView /// The HTML fragment to be appended to the output stream. /// /// A Task which can be awaited for completion. - Task AppendContent(string appendedHtmlBodyContent); + Task AppendContentAsync(string appendedHtmlBodyContent); } } diff --git a/src/PowerShellEditorServices.VSCode/CustomViews/IHtmlContentViews.cs b/src/PowerShellEditorServices.VSCode/CustomViews/IHtmlContentViews.cs index 5b42b4540..396ddae4c 100644 --- a/src/PowerShellEditorServices.VSCode/CustomViews/IHtmlContentViews.cs +++ b/src/PowerShellEditorServices.VSCode/CustomViews/IHtmlContentViews.cs @@ -21,6 +21,6 @@ public interface IHtmlContentViews /// /// A Task to await for completion, returns the IHtmlContentView instance. /// - Task CreateHtmlContentView(string viewTitle); + Task CreateHtmlContentViewAsync(string viewTitle); } } diff --git a/src/PowerShellEditorServices/Analysis/AnalysisService.cs b/src/PowerShellEditorServices/Analysis/AnalysisService.cs index e089cd87b..d87226377 100644 --- a/src/PowerShellEditorServices/Analysis/AnalysisService.cs +++ b/src/PowerShellEditorServices/Analysis/AnalysisService.cs @@ -323,7 +323,7 @@ public IEnumerable GetPSScriptAnalyzerRules() /// ScriptAnalyzer settings /// The range within which formatting should be applied. /// The formatted script text. - public async Task Format( + public async Task FormatAsync( string scriptDefinition, Hashtable settings, int[] rangeList) diff --git a/src/PowerShellEditorServices/Console/ChoicePromptHandler.cs b/src/PowerShellEditorServices/Console/ChoicePromptHandler.cs index 3511d4483..579d5b708 100644 --- a/src/PowerShellEditorServices/Console/ChoicePromptHandler.cs +++ b/src/PowerShellEditorServices/Console/ChoicePromptHandler.cs @@ -110,7 +110,7 @@ public ChoicePromptHandler(ILogger logger) : base(logger) /// A Task instance that can be monitored for completion to get /// the user's choice. /// - public async Task PromptForChoice( + public async Task PromptForChoiceAsync( string promptCaption, string promptMessage, ChoiceDetails[] choices, @@ -132,8 +132,8 @@ public async Task PromptForChoice( cancellationToken.Register(this.CancelPrompt, true); // Convert the int[] result to int - return await this.WaitForTask( - this.StartPromptLoop(this.promptCancellationTokenSource.Token) + return await this.WaitForTaskAsync( + this.StartPromptLoopAsync(this.promptCancellationTokenSource.Token) .ContinueWith( task => { @@ -173,7 +173,7 @@ public async Task PromptForChoice( /// A Task instance that can be monitored for completion to get /// the user's choices. /// - public async Task PromptForChoice( + public async Task PromptForChoiceAsync( string promptCaption, string promptMessage, ChoiceDetails[] choices, @@ -191,12 +191,12 @@ public async Task PromptForChoice( // Cancel the TaskCompletionSource if the caller cancels the task cancellationToken.Register(this.CancelPrompt, true); - return await this.WaitForTask( - this.StartPromptLoop( + return await this.WaitForTaskAsync( + this.StartPromptLoopAsync( this.promptCancellationTokenSource.Token)); } - private async Task WaitForTask(Task taskToWait) + private async Task WaitForTaskAsync(Task taskToWait) { Task finishedTask = await Task.WhenAny( @@ -211,7 +211,7 @@ await Task.WhenAny( return taskToWait.Result; } - private async Task StartPromptLoop( + private async Task StartPromptLoopAsync( CancellationToken cancellationToken) { int[] choiceIndexes = null; @@ -221,7 +221,7 @@ private async Task StartPromptLoop( while (!cancellationToken.IsCancellationRequested) { - string responseString = await this.ReadInputString(cancellationToken); + string responseString = await this.ReadInputStringAsync(cancellationToken); if (responseString == null) { // If the response string is null, the prompt has been cancelled @@ -334,7 +334,7 @@ protected override void OnPromptCancelled() /// A Task instance that can be monitored for completion to get /// the user's input. /// - protected abstract Task ReadInputString(CancellationToken cancellationToken); + protected abstract Task ReadInputStringAsync(CancellationToken cancellationToken); #endregion diff --git a/src/PowerShellEditorServices/Console/ConsoleReadLine.cs b/src/PowerShellEditorServices/Console/ConsoleReadLine.cs index afe5c6b8f..e2824d635 100644 --- a/src/PowerShellEditorServices/Console/ConsoleReadLine.cs +++ b/src/PowerShellEditorServices/Console/ConsoleReadLine.cs @@ -34,17 +34,17 @@ public ConsoleReadLine(PowerShellContext powerShellContext) #region Public Methods - public Task ReadCommandLine(CancellationToken cancellationToken) + public Task ReadCommandLineAsync(CancellationToken cancellationToken) { return this.ReadLineAsync(true, cancellationToken); } - public Task ReadSimpleLine(CancellationToken cancellationToken) + public Task ReadSimpleLineAsync(CancellationToken cancellationToken) { return this.ReadLineAsync(false, cancellationToken); } - public async Task ReadSecureLine(CancellationToken cancellationToken) + public async Task ReadSecureLineAsync(CancellationToken cancellationToken) { SecureString secureString = new SecureString(); @@ -208,13 +208,13 @@ internal async Task InvokeLegacyReadLineAsync(bool isCommandLine, Cancel command.AddParameter("Options", null); var results = - await this.powerShellContext.ExecuteCommand(command, false, false); + await this.powerShellContext.ExecuteCommandAsync(command, false, false); currentCompletion = results.FirstOrDefault(); } else { - using (RunspaceHandle runspaceHandle = await this.powerShellContext.GetRunspaceHandle()) + using (RunspaceHandle runspaceHandle = await this.powerShellContext.GetRunspaceHandleAsync()) using (PowerShell powerShell = PowerShell.Create()) { powerShell.Runspace = runspaceHandle.Runspace; @@ -326,7 +326,7 @@ internal async Task InvokeLegacyReadLineAsync(bool isCommandLine, Cancel command.AddCommand("Get-History"); currentHistory = - await this.powerShellContext.ExecuteCommand( + await this.powerShellContext.ExecuteCommandAsync( command, false, false) as Collection; diff --git a/src/PowerShellEditorServices/Console/InputPromptHandler.cs b/src/PowerShellEditorServices/Console/InputPromptHandler.cs index 0b8e4ff22..7d626c9ab 100644 --- a/src/PowerShellEditorServices/Console/InputPromptHandler.cs +++ b/src/PowerShellEditorServices/Console/InputPromptHandler.cs @@ -58,11 +58,11 @@ public InputPromptHandler(ILogger logger) : base(logger) /// A Task instance that can be monitored for completion to get /// the user's input. /// - public Task PromptForInput( + public Task PromptForInputAsync( CancellationToken cancellationToken) { Task> innerTask = - this.PromptForInput( + this.PromptForInputAsync( null, null, new FieldDetails[] { new FieldDetails("", "", typeof(string), false, "") }, @@ -106,7 +106,7 @@ public Task PromptForInput( /// A Task instance that can be monitored for completion to get /// the user's input. /// - public async Task> PromptForInput( + public async Task> PromptForInputAsync( string promptCaption, string promptMessage, FieldDetails[] fields, @@ -120,7 +120,7 @@ public async Task> PromptForInput( this.ShowPromptMessage(promptCaption, promptMessage); Task> promptTask = - this.StartPromptLoop(this.promptCancellationTokenSource.Token); + this.StartPromptLoopAsync(this.promptCancellationTokenSource.Token); Task finishedTask = await Task.WhenAny( @@ -142,11 +142,11 @@ await Task.WhenAny( /// A Task instance that can be monitored for completion to get /// the user's input. /// - public Task PromptForSecureInput( + public Task PromptForSecureInputAsync( CancellationToken cancellationToken) { Task> innerTask = - this.PromptForInput( + this.PromptForInputAsync( null, null, new FieldDetails[] { new FieldDetails("", "", typeof(SecureString), false, "") }, @@ -209,7 +209,7 @@ protected override void OnPromptCancelled() /// A Task instance that can be monitored for completion to get /// the user's input. /// - protected abstract Task ReadInputString(CancellationToken cancellationToken); + protected abstract Task ReadInputStringAsync(CancellationToken cancellationToken); /// /// Reads a SecureString asynchronously from the console. @@ -221,7 +221,7 @@ protected override void OnPromptCancelled() /// A Task instance that can be monitored for completion to get /// the user's input. /// - protected abstract Task ReadSecureString(CancellationToken cancellationToken); + protected abstract Task ReadSecureStringAsync(CancellationToken cancellationToken); /// /// Called when an error should be displayed, such as when the @@ -237,7 +237,7 @@ protected override void OnPromptCancelled() #region Private Methods - private async Task> StartPromptLoop( + private async Task> StartPromptLoopAsync( CancellationToken cancellationToken) { this.GetNextField(); @@ -255,13 +255,13 @@ private async Task> StartPromptLoop( // Read input depending on field type if (this.currentField.FieldType == typeof(SecureString)) { - SecureString secureString = await this.ReadSecureString(cancellationToken); + SecureString secureString = await this.ReadSecureStringAsync(cancellationToken); responseValue = secureString; enteredValue = secureString != null; } else { - responseString = await this.ReadInputString(cancellationToken); + responseString = await this.ReadInputStringAsync(cancellationToken); responseValue = responseString; enteredValue = responseString != null && responseString.Length > 0; diff --git a/src/PowerShellEditorServices/Console/TerminalChoicePromptHandler.cs b/src/PowerShellEditorServices/Console/TerminalChoicePromptHandler.cs index b99b959cd..1bf5a5cc4 100644 --- a/src/PowerShellEditorServices/Console/TerminalChoicePromptHandler.cs +++ b/src/PowerShellEditorServices/Console/TerminalChoicePromptHandler.cs @@ -52,9 +52,9 @@ public TerminalChoicePromptHandler( /// /// A CancellationToken that can be used to cancel the prompt. /// A Task that can be awaited to get the user's response. - protected override async Task ReadInputString(CancellationToken cancellationToken) + protected override async Task ReadInputStringAsync(CancellationToken cancellationToken) { - string inputString = await this.consoleReadLine.ReadSimpleLine(cancellationToken); + string inputString = await this.consoleReadLine.ReadSimpleLineAsync(cancellationToken); this.hostOutput.WriteOutput(string.Empty); return inputString; diff --git a/src/PowerShellEditorServices/Console/TerminalInputPromptHandler.cs b/src/PowerShellEditorServices/Console/TerminalInputPromptHandler.cs index e77bf2f9a..67b58bc55 100644 --- a/src/PowerShellEditorServices/Console/TerminalInputPromptHandler.cs +++ b/src/PowerShellEditorServices/Console/TerminalInputPromptHandler.cs @@ -54,9 +54,9 @@ public TerminalInputPromptHandler( /// /// A CancellationToken that can be used to cancel the prompt. /// A Task that can be awaited to get the user's response. - protected override async Task ReadInputString(CancellationToken cancellationToken) + protected override async Task ReadInputStringAsync(CancellationToken cancellationToken) { - string inputString = await this.consoleReadLine.ReadSimpleLine(cancellationToken); + string inputString = await this.consoleReadLine.ReadSimpleLineAsync(cancellationToken); this.hostOutput.WriteOutput(string.Empty); return inputString; @@ -67,9 +67,9 @@ protected override async Task ReadInputString(CancellationToken cancella /// /// A CancellationToken that can be used to cancel the prompt. /// A Task that can be awaited to get the user's response. - protected override async Task ReadSecureString(CancellationToken cancellationToken) + protected override async Task ReadSecureStringAsync(CancellationToken cancellationToken) { - SecureString secureString = await this.consoleReadLine.ReadSecureLine(cancellationToken); + SecureString secureString = await this.consoleReadLine.ReadSecureLineAsync(cancellationToken); this.hostOutput.WriteOutput(string.Empty); return secureString; diff --git a/src/PowerShellEditorServices/Debugging/DebugService.cs b/src/PowerShellEditorServices/Debugging/DebugService.cs index 8226ab9be..98d47d7af 100644 --- a/src/PowerShellEditorServices/Debugging/DebugService.cs +++ b/src/PowerShellEditorServices/Debugging/DebugService.cs @@ -108,7 +108,7 @@ public DebugService( this.logger = logger; this.powerShellContext = powerShellContext; - this.powerShellContext.DebuggerStop += this.OnDebuggerStop; + this.powerShellContext.DebuggerStop += this.OnDebuggerStopAsync; this.powerShellContext.DebuggerResumed += this.OnDebuggerResumed; this.powerShellContext.BreakpointUpdated += this.OnBreakpointUpdated; @@ -133,7 +133,7 @@ public DebugService( /// BreakpointDetails for each breakpoint that will be set. /// If true, causes all existing breakpoints to be cleared before setting new ones. /// An awaitable Task that will provide details about the breakpoints that were set. - public async Task SetLineBreakpoints( + public async Task SetLineBreakpointsAsync( ScriptFile scriptFile, BreakpointDetails[] breakpoints, bool clearExisting = true) @@ -186,7 +186,7 @@ public async Task SetLineBreakpoints( { if (clearExisting) { - await this.ClearBreakpointsInFile(scriptFile); + await this.ClearBreakpointsInFileAsync(scriptFile); } foreach (BreakpointDetails breakpoint in breakpoints) @@ -224,7 +224,7 @@ public async Task SetLineBreakpoints( } IEnumerable configuredBreakpoints = - await this.powerShellContext.ExecuteCommand(psCommand); + await this.powerShellContext.ExecuteCommandAsync(psCommand); // The order in which the breakpoints are returned is significant to the // VSCode client and should match the order in which they are passed in. @@ -235,7 +235,7 @@ public async Task SetLineBreakpoints( else { resultBreakpointDetails = - await dscBreakpoints.SetLineBreakpoints( + await dscBreakpoints.SetLineBreakpointsAsync( this.powerShellContext, escapedScriptPath, breakpoints); @@ -250,7 +250,7 @@ await dscBreakpoints.SetLineBreakpoints( /// CommandBreakpointDetails for each command breakpoint that will be set. /// If true, causes all existing function breakpoints to be cleared before setting new ones. /// An awaitable Task that will provide details about the breakpoints that were set. - public async Task SetCommandBreakpoints( + public async Task SetCommandBreakpointsAsync( CommandBreakpointDetails[] breakpoints, bool clearExisting = true) { @@ -258,7 +258,7 @@ public async Task SetCommandBreakpoints( if (clearExisting) { - await this.ClearCommandBreakpoints(); + await this.ClearCommandBreakpointsAsync(); } if (breakpoints.Length > 0) @@ -287,7 +287,7 @@ public async Task SetCommandBreakpoints( } IEnumerable configuredBreakpoints = - await this.powerShellContext.ExecuteCommand(psCommand); + await this.powerShellContext.ExecuteCommandAsync(psCommand); // The order in which the breakpoints are returned is significant to the // VSCode client and should match the order in which they are passed in. @@ -470,7 +470,7 @@ public VariableDetailsBase GetVariableFromExpression(string variableExpression, /// The new string value. This value must not be null. If you want to set the variable to $null /// pass in the string "$null". /// The string representation of the value the variable was set to. - public async Task SetVariable(int variableContainerReferenceId, string name, string value) + public async Task SetVariableAsync(int variableContainerReferenceId, string name, string value) { Validate.IsNotNull(nameof(name), name); Validate.IsNotNull(nameof(value), value); @@ -488,7 +488,7 @@ public async Task SetVariable(int variableContainerReferenceId, string n psCommand.AddScript(value); var errorMessages = new StringBuilder(); var results = - await this.powerShellContext.ExecuteCommand( + await this.powerShellContext.ExecuteCommandAsync( psCommand, errorMessages, false, @@ -561,7 +561,7 @@ await this.powerShellContext.ExecuteCommand( psCommand.AddParameter("Name", name.TrimStart('$')); psCommand.AddParameter("Scope", scope); - IEnumerable result = await this.powerShellContext.ExecuteCommand(psCommand, sendErrorToHost: false); + IEnumerable result = await this.powerShellContext.ExecuteCommandAsync(psCommand, sendErrorToHost: false); PSVariable psVariable = result.FirstOrDefault(); if (psVariable == null) { @@ -590,7 +590,7 @@ await this.powerShellContext.ExecuteCommand( errorMessages.Clear(); var getExecContextResults = - await this.powerShellContext.ExecuteCommand( + await this.powerShellContext.ExecuteCommandAsync( psCommand, errorMessages, sendErrorToHost: false); @@ -628,13 +628,13 @@ await this.powerShellContext.ExecuteCommand( /// If true, writes the expression result as host output rather than returning the results. /// In this case, the return value of this function will be null. /// A VariableDetails object containing the result. - public async Task EvaluateExpression( + public async Task EvaluateExpressionAsync( string expressionString, int stackFrameId, bool writeResultAsOutput) { var results = - await this.powerShellContext.ExecuteScriptString( + await this.powerShellContext.ExecuteScriptStringAsync( expressionString, false, writeResultAsOutput); @@ -741,20 +741,20 @@ public VariableScope[] GetVariableScopes(int stackFrameId) /// /// Clears all breakpoints in the current session. /// - public async Task ClearAllBreakpoints() + public async Task ClearAllBreakpointsAsync() { PSCommand psCommand = new PSCommand(); psCommand.AddCommand(@"Microsoft.PowerShell.Utility\Get-PSBreakpoint"); psCommand.AddCommand(@"Microsoft.PowerShell.Utility\Remove-PSBreakpoint"); - await this.powerShellContext.ExecuteCommand(psCommand); + await this.powerShellContext.ExecuteCommandAsync(psCommand); } #endregion #region Private Methods - private async Task ClearBreakpointsInFile(ScriptFile scriptFile) + private async Task ClearBreakpointsInFileAsync(ScriptFile scriptFile) { List breakpoints = null; @@ -767,7 +767,7 @@ private async Task ClearBreakpointsInFile(ScriptFile scriptFile) psCommand.AddCommand(@"Microsoft.PowerShell.Utility\Remove-PSBreakpoint"); psCommand.AddParameter("Id", breakpoints.Select(b => b.Id).ToArray()); - await this.powerShellContext.ExecuteCommand(psCommand); + await this.powerShellContext.ExecuteCommandAsync(psCommand); // Clear the existing breakpoints list for the file breakpoints.Clear(); @@ -775,17 +775,17 @@ private async Task ClearBreakpointsInFile(ScriptFile scriptFile) } } - private async Task ClearCommandBreakpoints() + private async Task ClearCommandBreakpointsAsync() { PSCommand psCommand = new PSCommand(); psCommand.AddCommand(@"Microsoft.PowerShell.Utility\Get-PSBreakpoint"); psCommand.AddParameter("Type", "Command"); psCommand.AddCommand(@"Microsoft.PowerShell.Utility\Remove-PSBreakpoint"); - await this.powerShellContext.ExecuteCommand(psCommand); + await this.powerShellContext.ExecuteCommandAsync(psCommand); } - private async Task FetchStackFramesAndVariables(string scriptNameOverride) + private async Task FetchStackFramesAndVariablesAsync(string scriptNameOverride) { await this.debugInfoHandle.WaitAsync(); try @@ -798,8 +798,8 @@ private async Task FetchStackFramesAndVariables(string scriptNameOverride) // Must retrieve global/script variales before stack frame variables // as we check stack frame variables against globals. - await FetchGlobalAndScriptVariables(); - await FetchStackFrames(scriptNameOverride); + await FetchGlobalAndScriptVariablesAsync(); + await FetchStackFramesAsync(scriptNameOverride); } finally { @@ -807,17 +807,17 @@ private async Task FetchStackFramesAndVariables(string scriptNameOverride) } } - private async Task FetchGlobalAndScriptVariables() + private async Task FetchGlobalAndScriptVariablesAsync() { // Retrieve globals first as script variable retrieval needs to search globals. this.globalScopeVariables = - await FetchVariableContainer(VariableContainerDetails.GlobalScopeName, null); + await FetchVariableContainerAsync(VariableContainerDetails.GlobalScopeName, null); this.scriptScopeVariables = - await FetchVariableContainer(VariableContainerDetails.ScriptScopeName, null); + await FetchVariableContainerAsync(VariableContainerDetails.ScriptScopeName, null); } - private async Task FetchVariableContainer( + private async Task FetchVariableContainerAsync( string scope, VariableContainerDetails autoVariables) { @@ -829,7 +829,7 @@ private async Task FetchVariableContainer( new VariableContainerDetails(this.nextVariableId++, "Scope: " + scope); this.variables.Add(scopeVariableContainer); - var results = await this.powerShellContext.ExecuteCommand(psCommand, sendErrorToHost: false); + var results = await this.powerShellContext.ExecuteCommandAsync(psCommand, sendErrorToHost: false); if (results != null) { foreach (PSObject psVariableObject in results) @@ -923,7 +923,7 @@ private bool AddToAutoVariables(PSObject psvariable, string scope) return true; } - private async Task FetchStackFrames(string scriptNameOverride) + private async Task FetchStackFramesAsync(string scriptNameOverride) { PSCommand psCommand = new PSCommand(); @@ -934,7 +934,7 @@ private async Task FetchStackFrames(string scriptNameOverride) var callStackVarName = $"$global:{PsesGlobalVariableNamePrefix}CallStack"; psCommand.AddScript($"{callStackVarName} = Get-PSCallStack; {callStackVarName}"); - var results = await this.powerShellContext.ExecuteCommand(psCommand); + var results = await this.powerShellContext.ExecuteCommandAsync(psCommand); var callStackFrames = results.ToArray(); @@ -950,7 +950,7 @@ private async Task FetchStackFrames(string scriptNameOverride) this.variables.Add(autoVariables); VariableContainerDetails localVariables = - await FetchVariableContainer(i.ToString(), autoVariables); + await FetchVariableContainerAsync(i.ToString(), autoVariables); // When debugging, this is the best way I can find to get what is likely the workspace root. // This is controlled by the "cwd:" setting in the launch config. @@ -1190,7 +1190,7 @@ private string TrimScriptListingLine(PSObject scriptLineObj, ref int prefixLengt /// public event EventHandler DebuggerStopped; - private async void OnDebuggerStop(object sender, DebuggerStopEventArgs e) + private async void OnDebuggerStopAsync(object sender, DebuggerStopEventArgs e) { bool noScriptName = false; string localScriptPath = e.InvocationInfo.ScriptName; @@ -1203,7 +1203,7 @@ private async void OnDebuggerStop(object sender, DebuggerStopEventArgs e) command.AddScript($"list 1 {int.MaxValue}"); IEnumerable scriptListingLines = - await this.powerShellContext.ExecuteCommand( + await this.powerShellContext.ExecuteCommandAsync( command, false, false); if (scriptListingLines != null) @@ -1238,7 +1238,7 @@ await this.powerShellContext.ExecuteCommand( } // Get call stack and variables. - await this.FetchStackFramesAndVariables( + await this.FetchStackFramesAndVariablesAsync( noScriptName ? localScriptPath : null); // If this is a remote connection and the debugger stopped at a line @@ -1248,7 +1248,7 @@ await this.FetchStackFramesAndVariables( !noScriptName) { localScriptPath = - await this.remoteFileManager.FetchRemoteFile( + await this.remoteFileManager.FetchRemoteFileAsync( e.InvocationInfo.ScriptName, this.powerShellContext.CurrentRunspace); } diff --git a/src/PowerShellEditorServices/Extensions/EditorContext.cs b/src/PowerShellEditorServices/Extensions/EditorContext.cs index c29c60fcc..c669acd19 100644 --- a/src/PowerShellEditorServices/Extensions/EditorContext.cs +++ b/src/PowerShellEditorServices/Extensions/EditorContext.cs @@ -107,7 +107,7 @@ public void SetSelection( public void SetSelection(BufferRange selectionRange) { this.editorOperations - .SetSelection(selectionRange) + .SetSelectionAsync(selectionRange) .Wait(); } diff --git a/src/PowerShellEditorServices/Extensions/EditorObject.cs b/src/PowerShellEditorServices/Extensions/EditorObject.cs index e8f50d589..0013da684 100644 --- a/src/PowerShellEditorServices/Extensions/EditorObject.cs +++ b/src/PowerShellEditorServices/Extensions/EditorObject.cs @@ -105,7 +105,7 @@ public EditorCommand[] GetCommands() /// A instance of the EditorContext class. public EditorContext GetEditorContext() { - return this.editorOperations.GetEditorContext().Result; + return this.editorOperations.GetEditorContextAsync().Result; } } } diff --git a/src/PowerShellEditorServices/Extensions/EditorWindow.cs b/src/PowerShellEditorServices/Extensions/EditorWindow.cs index 0ffd125f0..8d241559a 100644 --- a/src/PowerShellEditorServices/Extensions/EditorWindow.cs +++ b/src/PowerShellEditorServices/Extensions/EditorWindow.cs @@ -28,7 +28,7 @@ internal EditorWindow(IEditorOperations editorOperations) this.editorOperations = editorOperations; } - #endregion + #endregion #region Public Methods @@ -38,7 +38,7 @@ internal EditorWindow(IEditorOperations editorOperations) /// The message to be shown. public void ShowInformationMessage(string message) { - this.editorOperations.ShowInformationMessage(message).Wait(); + this.editorOperations.ShowInformationMessageAsync(message).Wait(); } /// @@ -47,7 +47,7 @@ public void ShowInformationMessage(string message) /// The message to be shown. public void ShowErrorMessage(string message) { - this.editorOperations.ShowErrorMessage(message).Wait(); + this.editorOperations.ShowErrorMessageAsync(message).Wait(); } /// @@ -56,7 +56,7 @@ public void ShowErrorMessage(string message) /// The message to be shown. public void ShowWarningMessage(string message) { - this.editorOperations.ShowWarningMessage(message).Wait(); + this.editorOperations.ShowWarningMessageAsync(message).Wait(); } /// @@ -65,7 +65,7 @@ public void ShowWarningMessage(string message) /// The message to be shown. public void SetStatusBarMessage(string message) { - this.editorOperations.SetStatusBarMessage(message, null).Wait(); + this.editorOperations.SetStatusBarMessageAsync(message, null).Wait(); } /// @@ -75,9 +75,9 @@ public void SetStatusBarMessage(string message) /// A timeout in milliseconds for how long the message should remain visible. public void SetStatusBarMessage(string message, int timeout) { - this.editorOperations.SetStatusBarMessage(message, timeout).Wait(); + this.editorOperations.SetStatusBarMessageAsync(message, timeout).Wait(); } - #endregion + #endregion } } diff --git a/src/PowerShellEditorServices/Extensions/EditorWorkspace.cs b/src/PowerShellEditorServices/Extensions/EditorWorkspace.cs index 9bdd2c043..ad679f371 100644 --- a/src/PowerShellEditorServices/Extensions/EditorWorkspace.cs +++ b/src/PowerShellEditorServices/Extensions/EditorWorkspace.cs @@ -45,7 +45,7 @@ internal EditorWorkspace(IEditorOperations editorOperations) /// public void NewFile() { - this.editorOperations.NewFile().Wait(); + this.editorOperations.NewFileAsync().Wait(); } /// @@ -55,7 +55,7 @@ public void NewFile() /// The path to the file to be opened. public void OpenFile(string filePath) { - this.editorOperations.OpenFile(filePath).Wait(); + this.editorOperations.OpenFileAsync(filePath).Wait(); } /// @@ -67,7 +67,7 @@ public void OpenFile(string filePath) /// Determines wether the file is opened as a preview or as a durable editor. public void OpenFile(string filePath, bool preview) { - this.editorOperations.OpenFile(filePath, preview).Wait(); + this.editorOperations.OpenFileAsync(filePath, preview).Wait(); } #endregion diff --git a/src/PowerShellEditorServices/Extensions/ExtensionService.cs b/src/PowerShellEditorServices/Extensions/ExtensionService.cs index d9defe6a3..cc4e01af4 100644 --- a/src/PowerShellEditorServices/Extensions/ExtensionService.cs +++ b/src/PowerShellEditorServices/Extensions/ExtensionService.cs @@ -71,7 +71,7 @@ public ExtensionService(PowerShellContext powerShellContext) /// An IEditorOperations implementation. /// An IComponentRegistry instance which provides components in the session. /// A Task that can be awaited for completion. - public async Task Initialize( + public async Task InitializeAsync( IEditorOperations editorOperations, IComponentRegistry componentRegistry) { @@ -83,7 +83,7 @@ public async Task Initialize( // Register the editor object in the runspace PSCommand variableCommand = new PSCommand(); - using (RunspaceHandle handle = await this.PowerShellContext.GetRunspaceHandle()) + using (RunspaceHandle handle = await this.PowerShellContext.GetRunspaceHandleAsync()) { handle.Runspace.SessionStateProxy.PSVariable.Set( "psEditor", @@ -97,7 +97,7 @@ public async Task Initialize( /// The unique name of the command to be invoked. /// The context in which the command is being invoked. /// A Task that can be awaited for completion. - public async Task InvokeCommand(string commandName, EditorContext editorContext) + public async Task InvokeCommandAsync(string commandName, EditorContext editorContext) { EditorCommand editorCommand; @@ -108,7 +108,7 @@ public async Task InvokeCommand(string commandName, EditorContext editorContext) executeCommand.AddParameter("ScriptBlock", editorCommand.ScriptBlock); executeCommand.AddParameter("ArgumentList", new object[] { editorContext }); - await this.PowerShellContext.ExecuteCommand( + await this.PowerShellContext.ExecuteCommandAsync( executeCommand, !editorCommand.SuppressOutput, true); diff --git a/src/PowerShellEditorServices/Extensions/FileContext.cs b/src/PowerShellEditorServices/Extensions/FileContext.cs index 1b563dcb2..3fc5ac120 100644 --- a/src/PowerShellEditorServices/Extensions/FileContext.cs +++ b/src/PowerShellEditorServices/Extensions/FileContext.cs @@ -237,7 +237,7 @@ public void InsertText( public void InsertText(string textToInsert, BufferRange insertRange) { this.editorOperations - .InsertText(this.scriptFile.ClientFilePath, textToInsert, insertRange) + .InsertTextAsync(this.scriptFile.ClientFilePath, textToInsert, insertRange) .Wait(); } @@ -250,7 +250,7 @@ public void InsertText(string textToInsert, BufferRange insertRange) /// public void Save() { - this.editorOperations.SaveFile(this.scriptFile.FilePath); + this.editorOperations.SaveFileAsync(this.scriptFile.FilePath); } /// @@ -272,7 +272,7 @@ public void SaveAs(string newFilePath) throw new IOException(String.Format("The file '{0}' already exists", absolutePath)); } - this.editorOperations.SaveFile(this.scriptFile.FilePath, newFilePath); + this.editorOperations.SaveFileAsync(this.scriptFile.FilePath, newFilePath); } #endregion diff --git a/src/PowerShellEditorServices/Extensions/IEditorOperations.cs b/src/PowerShellEditorServices/Extensions/IEditorOperations.cs index 51d0ac5b7..7ef6bdf0e 100644 --- a/src/PowerShellEditorServices/Extensions/IEditorOperations.cs +++ b/src/PowerShellEditorServices/Extensions/IEditorOperations.cs @@ -18,7 +18,7 @@ public interface IEditorOperations /// Gets the EditorContext for the editor's current state. /// /// A new EditorContext object. - Task GetEditorContext(); + Task GetEditorContextAsync(); /// /// Gets the path to the editor's active workspace. @@ -37,7 +37,7 @@ public interface IEditorOperations /// Causes a new untitled file to be created in the editor. /// /// A task that can be awaited for completion. - Task NewFile(); + Task NewFileAsync(); /// /// Causes a file to be opened in the editor. If the file is @@ -45,7 +45,7 @@ public interface IEditorOperations /// /// The path of the file to be opened. /// A Task that can be tracked for completion. - Task OpenFile(string filePath); + Task OpenFileAsync(string filePath); /// /// Causes a file to be opened in the editor. If the file is @@ -55,21 +55,21 @@ public interface IEditorOperations /// The path of the file to be opened. /// Determines wether the file is opened as a preview or as a durable editor. /// A Task that can be tracked for completion. - Task OpenFile(string filePath, bool preview); + Task OpenFileAsync(string filePath, bool preview); /// /// Causes a file to be closed in the editor. /// /// The path of the file to be closed. /// A Task that can be tracked for completion. - Task CloseFile(string filePath); + Task CloseFileAsync(string filePath); /// /// Causes a file to be saved in the editor. /// /// The path of the file to be saved. /// A Task that can be tracked for completion. - Task SaveFile(string filePath); + Task SaveFileAsync(string filePath); /// /// Causes a file to be saved as a new file in a new editor window. @@ -77,7 +77,7 @@ public interface IEditorOperations /// the path of the current file being saved /// the path of the new file where the current window content will be saved /// - Task SaveFile(string oldFilePath, string newFilePath); + Task SaveFileAsync(string oldFilePath, string newFilePath); /// /// Inserts text into the specified range for the file at the specified path. @@ -86,35 +86,35 @@ public interface IEditorOperations /// The text to insert into the file. /// The range in the file to be replaced. /// A Task that can be tracked for completion. - Task InsertText(string filePath, string insertText, BufferRange insertRange); + Task InsertTextAsync(string filePath, string insertText, BufferRange insertRange); /// /// Causes the selection to be changed in the editor's active file buffer. /// /// The range over which the selection will be made. /// A Task that can be tracked for completion. - Task SetSelection(BufferRange selectionRange); + Task SetSelectionAsync(BufferRange selectionRange); /// /// Shows an informational message to the user. /// /// The message to be shown. /// A Task that can be tracked for completion. - Task ShowInformationMessage(string message); + Task ShowInformationMessageAsync(string message); /// /// Shows an error message to the user. /// /// The message to be shown. /// A Task that can be tracked for completion. - Task ShowErrorMessage(string message); + Task ShowErrorMessageAsync(string message); /// /// Shows a warning message to the user. /// /// The message to be shown. /// A Task that can be tracked for completion. - Task ShowWarningMessage(string message); + Task ShowWarningMessageAsync(string message); /// /// Sets the status bar message in the editor UI (if applicable). @@ -122,7 +122,7 @@ public interface IEditorOperations /// The message to be shown. /// If non-null, a timeout in milliseconds for how long the message should remain visible. /// A Task that can be tracked for completion. - Task SetStatusBarMessage(string message, int? timeout); + Task SetStatusBarMessageAsync(string message, int? timeout); } } diff --git a/src/PowerShellEditorServices/Language/AstOperations.cs b/src/PowerShellEditorServices/Language/AstOperations.cs index 218462c1c..354e5f188 100644 --- a/src/PowerShellEditorServices/Language/AstOperations.cs +++ b/src/PowerShellEditorServices/Language/AstOperations.cs @@ -56,7 +56,7 @@ internal static class AstOperations /// A CommandCompletion instance that contains completions for the /// symbol at the given offset. /// - static public async Task GetCompletions( + static public async Task GetCompletionsAsync( Ast scriptAst, Token[] currentTokens, int fileOffset, @@ -95,7 +95,7 @@ static public async Task GetCompletions( // main runspace. if (powerShellContext.IsCurrentRunspaceOutOfProcess()) { - using (RunspaceHandle runspaceHandle = await powerShellContext.GetRunspaceHandle(cancellationToken)) + using (RunspaceHandle runspaceHandle = await powerShellContext.GetRunspaceHandleAsync(cancellationToken)) using (PowerShell powerShell = PowerShell.Create()) { powerShell.Runspace = runspaceHandle.Runspace; @@ -118,7 +118,7 @@ static public async Task GetCompletions( } CommandCompletion commandCompletion = null; - await powerShellContext.InvokeOnPipelineThread( + await powerShellContext.InvokeOnPipelineThreadAsync( pwsh => { stopwatch.Start(); diff --git a/src/PowerShellEditorServices/Language/CommandHelpers.cs b/src/PowerShellEditorServices/Language/CommandHelpers.cs index 1a834c410..9c72e0eef 100644 --- a/src/PowerShellEditorServices/Language/CommandHelpers.cs +++ b/src/PowerShellEditorServices/Language/CommandHelpers.cs @@ -36,7 +36,7 @@ public class CommandHelpers /// The name of the command. /// The PowerShellContext to use for running Get-Command. /// A CommandInfo object with details about the specified command. - public static async Task GetCommandInfo( + public static async Task GetCommandInfoAsync( string commandName, PowerShellContext powerShellContext) { @@ -59,7 +59,7 @@ public static async Task GetCommandInfo( return (await powerShellContext - .ExecuteCommand(command, false, false)) + .ExecuteCommandAsync(command, false, false)) .Select(o => o.BaseObject) .OfType() .FirstOrDefault(); @@ -71,7 +71,7 @@ public static async Task GetCommandInfo( /// The CommandInfo instance for the command. /// The PowerShellContext to use for getting command documentation. /// - public static async Task GetCommandSynopsis( + public static async Task GetCommandSynopsisAsync( CommandInfo commandInfo, PowerShellContext powerShellContext) { @@ -89,7 +89,7 @@ public static async Task GetCommandSynopsis( command.AddArgument(commandInfo); command.AddParameter("ErrorAction", "Ignore"); - var results = await powerShellContext.ExecuteCommand(command, false, false); + var results = await powerShellContext.ExecuteCommandAsync(command, false, false); helpObject = results.FirstOrDefault(); if (helpObject != null) diff --git a/src/PowerShellEditorServices/Language/LanguageService.cs b/src/PowerShellEditorServices/Language/LanguageService.cs index 64ff08bd6..486306b58 100644 --- a/src/PowerShellEditorServices/Language/LanguageService.cs +++ b/src/PowerShellEditorServices/Language/LanguageService.cs @@ -103,7 +103,7 @@ public LanguageService( /// /// A CommandCompletion instance completions for the identified statement. /// - public async Task GetCompletionsInFile( + public async Task GetCompletionsInFileAsync( ScriptFile scriptFile, int lineNumber, int columnNumber) @@ -118,7 +118,7 @@ public async Task GetCompletionsInFile( columnNumber); CommandCompletion commandCompletion = - await AstOperations.GetCompletions( + await AstOperations.GetCompletionsAsync( scriptFile.ScriptAst, scriptFile.ScriptTokens, fileOffset, @@ -249,7 +249,7 @@ public SymbolReference FindFunctionDefinitionAtLocation( /// The line number at which the symbol can be located. /// The column number at which the symbol can be located. /// - public async Task FindSymbolDetailsAtLocation( + public async Task FindSymbolDetailsAtLocationAsync( ScriptFile scriptFile, int lineNumber, int columnNumber) @@ -269,7 +269,7 @@ public async Task FindSymbolDetailsAtLocation( symbolReference.FilePath = scriptFile.FilePath; symbolDetails = - await SymbolDetails.Create( + await SymbolDetails.CreateAsync( symbolReference, _powerShellContext); @@ -309,7 +309,7 @@ public FindOccurrencesResult FindSymbolsInFile(ScriptFile scriptFile) /// An array of scriptFiles too search for references in /// The workspace that will be searched for symbols /// FindReferencesResult - public async Task FindReferencesOfSymbol( + public async Task FindReferencesOfSymbolAsync( SymbolReference foundSymbol, ScriptFile[] referencedFiles, Workspace workspace) @@ -324,7 +324,7 @@ public async Task FindReferencesOfSymbol( foundSymbol.ScriptRegion.StartColumnNumber); // Make sure aliases have been loaded - await GetAliases(); + await GetAliasesAsync(); // We want to look for references first in referenced files, hence we use ordered dictionary // TODO: File system case-sensitivity is based on filesystem not OS, but OS is a much cheaper heuristic @@ -402,7 +402,7 @@ public async Task FindReferencesOfSymbol( /// The symbol for which a definition will be found. /// The Workspace to which the ScriptFile belongs. /// The resulting GetDefinitionResult for the symbol's definition. - public async Task GetDefinitionOfSymbol( + public async Task GetDefinitionOfSymbolAsync( ScriptFile sourceFile, SymbolReference foundSymbol, Workspace workspace) @@ -481,7 +481,7 @@ public async Task GetDefinitionOfSymbol( if (foundDefinition == null) { CommandInfo cmdInfo = - await CommandHelpers.GetCommandInfo( + await CommandHelpers.GetCommandInfoAsync( foundSymbol.SymbolName, _powerShellContext); @@ -556,7 +556,7 @@ public FindOccurrencesResult FindOccurrencesInFile( /// The line number of the cursor for the given script /// The coulumn number of the cursor for the given script /// ParameterSetSignatures - public async Task FindParameterSetsInFile( + public async Task FindParameterSetsInFileAsync( ScriptFile file, int lineNumber, int columnNumber) @@ -573,7 +573,7 @@ public async Task FindParameterSetsInFile( } CommandInfo commandInfo = - await CommandHelpers.GetCommandInfo( + await CommandHelpers.GetCommandInfoAsync( foundSymbol.SymbolName, _powerShellContext); @@ -727,7 +727,7 @@ public FunctionDefinitionAst GetFunctionDefinitionForHelpComment( /// /// Gets all aliases found in the runspace /// - private async Task GetAliases() + private async Task GetAliasesAsync() { if (_areAliasesLoaded) { @@ -743,7 +743,7 @@ private async Task GetAliases() return; } - var aliases = await _powerShellContext.ExecuteCommand( + var aliases = await _powerShellContext.ExecuteCommandAsync( new PSCommand() .AddCommand("Microsoft.PowerShell.Core\\Get-Command") .AddParameter("CommandType", CommandTypes.Alias), diff --git a/src/PowerShellEditorServices/Language/SymbolDetails.cs b/src/PowerShellEditorServices/Language/SymbolDetails.cs index 02f027415..e0971c2ec 100644 --- a/src/PowerShellEditorServices/Language/SymbolDetails.cs +++ b/src/PowerShellEditorServices/Language/SymbolDetails.cs @@ -38,8 +38,8 @@ public class SymbolDetails #region Constructors - static internal async Task Create( - SymbolReference symbolReference, + static internal async Task CreateAsync( + SymbolReference symbolReference, PowerShellContext powerShellContext) { SymbolDetails symbolDetails = new SymbolDetails(); @@ -49,14 +49,14 @@ static internal async Task Create( if (symbolReference.SymbolType == SymbolType.Function) { CommandInfo commandInfo = - await CommandHelpers.GetCommandInfo( + await CommandHelpers.GetCommandInfoAsync( symbolReference.SymbolName, powerShellContext); if (commandInfo != null) { symbolDetails.Documentation = - await CommandHelpers.GetCommandSynopsis( + await CommandHelpers.GetCommandSynopsisAsync( commandInfo, powerShellContext); diff --git a/src/PowerShellEditorServices/Session/Capabilities/DscBreakpointCapability.cs b/src/PowerShellEditorServices/Session/Capabilities/DscBreakpointCapability.cs index a5907b0d5..998b58a79 100644 --- a/src/PowerShellEditorServices/Session/Capabilities/DscBreakpointCapability.cs +++ b/src/PowerShellEditorServices/Session/Capabilities/DscBreakpointCapability.cs @@ -21,7 +21,7 @@ internal class DscBreakpointCapability : IRunspaceCapability private Dictionary breakpointsPerFile = new Dictionary(); - public async Task> SetLineBreakpoints( + public async Task> SetLineBreakpointsAsync( PowerShellContext powerShellContext, string scriptPath, BreakpointDetails[] breakpoints) @@ -52,7 +52,7 @@ public async Task> SetLineBreakpoints( // Run Enable-DscDebug as a script because running it as a PSCommand // causes an error which states that the Breakpoint parameter has not // been passed. - await powerShellContext.ExecuteScriptString( + await powerShellContext.ExecuteScriptStringAsync( hashtableString.Length > 0 ? $"Enable-DscDebug -Breakpoint {hashtableString}" : "Disable-DscDebug", diff --git a/src/PowerShellEditorServices/Session/Host/EditorServicesPSHostUserInterface.cs b/src/PowerShellEditorServices/Session/Host/EditorServicesPSHostUserInterface.cs index 2cbf29365..a1d17547f 100644 --- a/src/PowerShellEditorServices/Session/Host/EditorServicesPSHostUserInterface.cs +++ b/src/PowerShellEditorServices/Session/Host/EditorServicesPSHostUserInterface.cs @@ -146,7 +146,7 @@ private void ShowCommandPrompt() Task.Factory.StartNew( async () => { - await this.StartReplLoop(this.commandLoopCancellationToken.Token); + await this.StartReplLoopAsync(this.commandLoopCancellationToken.Token); }); } else @@ -198,7 +198,7 @@ public void SendControlC() /// A CancellationToken used to cancel the command line request. /// /// A Task that can be awaited for the resulting input string. - protected abstract Task ReadCommandLine(CancellationToken cancellationToken); + protected abstract Task ReadCommandLineAsync(CancellationToken cancellationToken); /// /// Creates an InputPrompt handle to use for displaying input @@ -278,7 +278,7 @@ public override Dictionary Prompt( CancellationTokenSource cancellationToken = new CancellationTokenSource(); Task> promptTask = this.CreateInputPromptHandler() - .PromptForInput( + .PromptForInputAsync( promptCaption, promptMessage, fields, @@ -333,7 +333,7 @@ public override int PromptForChoice( CancellationTokenSource cancellationToken = new CancellationTokenSource(); Task promptTask = this.CreateChoicePromptHandler() - .PromptForChoice( + .PromptForChoiceAsync( promptCaption, promptMessage, choices, @@ -372,7 +372,7 @@ public override PSCredential PromptForCredential( Task> promptTask = this.CreateInputPromptHandler() - .PromptForInput( + .PromptForInputAsync( promptCaption, promptMessage, new FieldDetails[] { new CredentialFieldDetails("Credential", "Credential", userName) }, @@ -446,7 +446,7 @@ public override string ReadLine() Task promptTask = this.CreateInputPromptHandler() - .PromptForInput(cancellationToken.Token); + .PromptForInputAsync(cancellationToken.Token); // Run the prompt task and wait for it to return this.WaitForPromptCompletion( @@ -467,7 +467,7 @@ public override SecureString ReadLineAsSecureString() Task promptTask = this.CreateInputPromptHandler() - .PromptForSecureInput(cancellationToken.Token); + .PromptForSecureInputAsync(cancellationToken.Token); // Run the prompt task and wait for it to return this.WaitForPromptCompletion( @@ -621,7 +621,7 @@ public Collection PromptForChoice( CancellationTokenSource cancellationToken = new CancellationTokenSource(); Task promptTask = this.CreateChoicePromptHandler() - .PromptForChoice( + .PromptForChoiceAsync( promptCaption, promptMessage, choices, @@ -644,7 +644,7 @@ public Collection PromptForChoice( private Coordinates lastPromptLocation; - private async Task WritePromptStringToHost(CancellationToken cancellationToken) + private async Task WritePromptStringToHostAsync(CancellationToken cancellationToken) { try { @@ -665,7 +665,7 @@ private async Task WritePromptStringToHost(CancellationToken cancellationToken) cancellationToken.ThrowIfCancellationRequested(); string promptString = - (await this.powerShellContext.ExecuteCommand(promptCommand, false, false)) + (await this.powerShellContext.ExecuteCommandAsync(promptCommand, false, false)) .Select(pso => pso.BaseObject) .OfType() .FirstOrDefault() ?? "PS> "; @@ -734,7 +734,7 @@ private void WriteDebuggerBanner(DebuggerStopEventArgs eventArgs) internal ConsoleColor ProgressForegroundColor { get; set; } = ConsoleColor.Yellow; internal ConsoleColor ProgressBackgroundColor { get; set; } = ConsoleColor.DarkCyan; - private async Task StartReplLoop(CancellationToken cancellationToken) + private async Task StartReplLoopAsync(CancellationToken cancellationToken) { while (!cancellationToken.IsCancellationRequested) { @@ -743,7 +743,7 @@ private async Task StartReplLoop(CancellationToken cancellationToken) try { - await this.WritePromptStringToHost(cancellationToken); + await this.WritePromptStringToHostAsync(cancellationToken); } catch (OperationCanceledException) { @@ -753,7 +753,7 @@ private async Task StartReplLoop(CancellationToken cancellationToken) try { originalCursorTop = await ConsoleProxy.GetCursorTopAsync(cancellationToken); - commandString = await this.ReadCommandLine(cancellationToken); + commandString = await this.ReadCommandLineAsync(cancellationToken); } catch (PipelineStoppedException) { @@ -790,7 +790,7 @@ private async Task StartReplLoop(CancellationToken cancellationToken) { var unusedTask = this.powerShellContext - .ExecuteScriptString( + .ExecuteScriptStringAsync( commandString, writeInputToHost: false, writeOutputToHost: true, @@ -949,7 +949,7 @@ private void PowerShellContext_ExecutionStatusChanged(object sender, ExecutionSt eventArgs.HadErrors)) { this.WriteOutput(string.Empty, true); - var unusedTask = this.WritePromptStringToHost(CancellationToken.None); + var unusedTask = this.WritePromptStringToHostAsync(CancellationToken.None); } } diff --git a/src/PowerShellEditorServices/Session/Host/TerminalPSHostUserInterface.cs b/src/PowerShellEditorServices/Session/Host/TerminalPSHostUserInterface.cs index 3752010f6..0d2e839ca 100644 --- a/src/PowerShellEditorServices/Session/Host/TerminalPSHostUserInterface.cs +++ b/src/PowerShellEditorServices/Session/Host/TerminalPSHostUserInterface.cs @@ -69,9 +69,9 @@ public TerminalPSHostUserInterface( /// A CancellationToken used to cancel the command line request. /// /// A Task that can be awaited for the resulting input string. - protected override Task ReadCommandLine(CancellationToken cancellationToken) + protected override Task ReadCommandLineAsync(CancellationToken cancellationToken) { - return this.consoleReadLine.ReadCommandLine(cancellationToken); + return this.consoleReadLine.ReadCommandLineAsync(cancellationToken); } /// diff --git a/src/PowerShellEditorServices/Session/InvocationEventQueue.cs b/src/PowerShellEditorServices/Session/InvocationEventQueue.cs index 77d85bf23..b6e9a9c0b 100644 --- a/src/PowerShellEditorServices/Session/InvocationEventQueue.cs +++ b/src/PowerShellEditorServices/Session/InvocationEventQueue.cs @@ -57,11 +57,11 @@ internal static InvocationEventQueue Create(PowerShellContext powerShellContext, /// Executes a command on the main pipeline thread through /// eventing. A event subscriber will /// be created that creates a nested PowerShell instance for - /// to utilize. + /// to utilize. /// /// /// Avoid using this method directly if possible. - /// will route commands + /// will route commands /// through this method if required. /// /// The expected result type. @@ -74,7 +74,7 @@ internal static InvocationEventQueue Create(PowerShellContext powerShellContext, /// An awaitable which will provide results once the command /// execution completes. /// - internal async Task> ExecuteCommandOnIdle( + internal async Task> ExecuteCommandOnIdleAsync( PSCommand psCommand, StringBuilder errorMessages, ExecutionOptions executionOptions) @@ -87,7 +87,7 @@ internal async Task> ExecuteCommandOnIdle( await SetInvocationRequestAsync( new InvocationRequest( - pwsh => request.Execute().GetAwaiter().GetResult())); + pwsh => request.ExecuteAsync().GetAwaiter().GetResult())); try { @@ -111,7 +111,7 @@ await SetInvocationRequestAsync( /// /// An awaitable that the caller can use to know when execution completes. /// - internal async Task InvokeOnPipelineThread(Action invocationAction) + internal async Task InvokeOnPipelineThreadAsync(Action invocationAction) { var request = new InvocationRequest(pwsh => { diff --git a/src/PowerShellEditorServices/Session/PSReadLinePromptContext.cs b/src/PowerShellEditorServices/Session/PSReadLinePromptContext.cs index 23c312fef..0b59e230b 100644 --- a/src/PowerShellEditorServices/Session/PSReadLinePromptContext.cs +++ b/src/PowerShellEditorServices/Session/PSReadLinePromptContext.cs @@ -131,7 +131,7 @@ public async Task InvokeReadLineAsync(bool isCommandLine, CancellationTo _readLineCancellationSource.Token); } - var result = (await _powerShellContext.ExecuteCommand( + var result = (await _powerShellContext.ExecuteCommandAsync( new PSCommand() .AddScript(ReadLineScript) .AddArgument(_readLineCancellationSource.Token), @@ -185,7 +185,7 @@ public void WaitForReadLineExit() { } } - public async Task WaitForReadLineExitAsync () { + public async Task WaitForReadLineExitAsync() { using (await _promptNest.GetRunspaceHandleAsync(CancellationToken.None, isReadLine: true)) { } } diff --git a/src/PowerShellEditorServices/Session/PipelineExecutionRequest.cs b/src/PowerShellEditorServices/Session/PipelineExecutionRequest.cs index cb1d66073..1c69f6a15 100644 --- a/src/PowerShellEditorServices/Session/PipelineExecutionRequest.cs +++ b/src/PowerShellEditorServices/Session/PipelineExecutionRequest.cs @@ -12,7 +12,7 @@ namespace Microsoft.PowerShell.EditorServices.Session { internal interface IPipelineExecutionRequest { - Task Execute(); + Task ExecuteAsync(); Task WaitTask { get; } } @@ -66,10 +66,10 @@ public PipelineExecutionRequest( _resultsTask = new TaskCompletionSource>(); } - public async Task Execute() + public async Task ExecuteAsync() { var results = - await _powerShellContext.ExecuteCommand( + await _powerShellContext.ExecuteCommandAsync( _psCommand, _errorMessages, _executionOptions); diff --git a/src/PowerShellEditorServices/Session/PowerShellContext.cs b/src/PowerShellEditorServices/Session/PowerShellContext.cs index 698d742fc..f5eb09494 100644 --- a/src/PowerShellEditorServices/Session/PowerShellContext.cs +++ b/src/PowerShellEditorServices/Session/PowerShellContext.cs @@ -351,7 +351,7 @@ public void Initialize( /// /// /// - public Task ImportCommandsModule(string moduleBasePath) + public Task ImportCommandsModuleAsync(string moduleBasePath) { PSCommand importCommand = new PSCommand(); importCommand @@ -361,7 +361,7 @@ public Task ImportCommandsModule(string moduleBasePath) moduleBasePath, "PowerShellEditorServices.Commands.psd1")); - return this.ExecuteCommand(importCommand, false, false); + return this.ExecuteCommandAsync(importCommand, false, false); } private static bool CheckIfRunspaceNeedsEventHandlers(RunspaceDetails runspaceDetails) @@ -409,9 +409,9 @@ private void CleanupRunspace(RunspaceDetails runspaceDetails) /// so that commands can be executed against it directly. /// /// A RunspaceHandle instance that gives access to the session's runspace. - public Task GetRunspaceHandle() + public Task GetRunspaceHandleAsync() { - return this.GetRunspaceHandleImpl(CancellationToken.None, isReadLine: false); + return this.GetRunspaceHandleImplAsync(CancellationToken.None, isReadLine: false); } /// @@ -421,9 +421,9 @@ public Task GetRunspaceHandle() /// /// A CancellationToken that can be used to cancel the request. /// A RunspaceHandle instance that gives access to the session's runspace. - public Task GetRunspaceHandle(CancellationToken cancellationToken) + public Task GetRunspaceHandleAsync(CancellationToken cancellationToken) { - return this.GetRunspaceHandleImpl(cancellationToken, isReadLine: false); + return this.GetRunspaceHandleImplAsync(cancellationToken, isReadLine: false); } /// @@ -442,12 +442,12 @@ public Task GetRunspaceHandle(CancellationToken cancellationToke /// An awaitable Task which will provide results once the command /// execution completes. /// - public async Task> ExecuteCommand( + public async Task> ExecuteCommandAsync( PSCommand psCommand, bool sendOutputToHost = false, bool sendErrorToHost = true) { - return await ExecuteCommand(psCommand, null, sendOutputToHost, sendErrorToHost); + return await ExecuteCommandAsync(psCommand, null, sendOutputToHost, sendErrorToHost); } /// @@ -470,7 +470,7 @@ public async Task> ExecuteCommand( /// An awaitable Task which will provide results once the command /// execution completes. /// - public Task> ExecuteCommand( + public Task> ExecuteCommandAsync( PSCommand psCommand, StringBuilder errorMessages, bool sendOutputToHost = false, @@ -478,7 +478,7 @@ public Task> ExecuteCommand( bool addToHistory = false) { return - this.ExecuteCommand( + this.ExecuteCommandAsync( psCommand, errorMessages, new ExecutionOptions @@ -501,7 +501,7 @@ public Task> ExecuteCommand( /// An awaitable Task which will provide results once the command /// execution completes. /// - public async Task> ExecuteCommand( + public async Task> ExecuteCommandAsync( PSCommand psCommand, StringBuilder errorMessages, ExecutionOptions executionOptions) @@ -550,7 +550,7 @@ public async Task> ExecuteCommand( } // Send the pipeline execution request to the pipeline thread - return await threadController.RequestPipelineExecution( + return await threadController.RequestPipelineExecutionAsync( new PipelineExecutionRequest( this, psCommand, @@ -579,7 +579,7 @@ public async Task> ExecuteCommand( // don't write output (e.g. command completion) if (executionTarget == ExecutionTarget.InvocationEvent) { - return (await this.InvocationEventQueue.ExecuteCommandOnIdle( + return (await this.InvocationEventQueue.ExecuteCommandOnIdleAsync( psCommand, errorMessages, executionOptions)); @@ -595,7 +595,7 @@ public async Task> ExecuteCommand( false); } - runspaceHandle = await this.GetRunspaceHandle(executionOptions.IsReadLine); + runspaceHandle = await this.GetRunspaceHandleAsync(executionOptions.IsReadLine); if (executionOptions.WriteInputToHost) { this.WriteOutput(psCommand.Commands[0].CommandText, true); @@ -786,7 +786,7 @@ public async Task> ExecuteCommand( // will exist already so we need to create one and then use it if (runspaceHandle == null) { - runspaceHandle = await this.GetRunspaceHandle(); + runspaceHandle = await this.GetRunspaceHandleAsync(); } sessionDetails = this.GetSessionDetailsInRunspace(runspaceHandle.Runspace); @@ -825,9 +825,9 @@ public async Task> ExecuteCommand( /// An awaitable Task that the caller can use to know when /// execution completes. /// - public Task ExecuteCommand(PSCommand psCommand) + public Task ExecuteCommandAsync(PSCommand psCommand) { - return this.ExecuteCommand(psCommand); + return this.ExecuteCommandAsync(psCommand); } /// @@ -835,10 +835,10 @@ public Task ExecuteCommand(PSCommand psCommand) /// /// The script string to execute. /// A Task that can be awaited for the script completion. - public Task> ExecuteScriptString( + public Task> ExecuteScriptStringAsync( string scriptString) { - return this.ExecuteScriptString(scriptString, false, true); + return this.ExecuteScriptStringAsync(scriptString, false, true); } /// @@ -847,11 +847,11 @@ public Task> ExecuteScriptString( /// The script string to execute. /// Error messages from PowerShell will be written to the StringBuilder. /// A Task that can be awaited for the script completion. - public Task> ExecuteScriptString( + public Task> ExecuteScriptStringAsync( string scriptString, StringBuilder errorMessages) { - return this.ExecuteScriptString(scriptString, errorMessages, false, true, false); + return this.ExecuteScriptStringAsync(scriptString, errorMessages, false, true, false); } /// @@ -861,12 +861,12 @@ public Task> ExecuteScriptString( /// If true, causes the script string to be written to the host. /// If true, causes the script output to be written to the host. /// A Task that can be awaited for the script completion. - public Task> ExecuteScriptString( + public Task> ExecuteScriptStringAsync( string scriptString, bool writeInputToHost, bool writeOutputToHost) { - return this.ExecuteScriptString(scriptString, null, writeInputToHost, writeOutputToHost, false); + return this.ExecuteScriptStringAsync(scriptString, null, writeInputToHost, writeOutputToHost, false); } /// @@ -877,13 +877,13 @@ public Task> ExecuteScriptString( /// If true, causes the script output to be written to the host. /// If true, adds the command to the user's command history. /// A Task that can be awaited for the script completion. - public Task> ExecuteScriptString( + public Task> ExecuteScriptStringAsync( string scriptString, bool writeInputToHost, bool writeOutputToHost, bool addToHistory) { - return this.ExecuteScriptString(scriptString, null, writeInputToHost, writeOutputToHost, addToHistory); + return this.ExecuteScriptStringAsync(scriptString, null, writeInputToHost, writeOutputToHost, addToHistory); } /// @@ -895,14 +895,14 @@ public Task> ExecuteScriptString( /// If true, causes the script output to be written to the host. /// If true, adds the command to the user's command history. /// A Task that can be awaited for the script completion. - public async Task> ExecuteScriptString( + public async Task> ExecuteScriptStringAsync( string scriptString, StringBuilder errorMessages, bool writeInputToHost, bool writeOutputToHost, bool addToHistory) { - return await this.ExecuteCommand( + return await this.ExecuteCommandAsync( new PSCommand().AddScript(scriptString.Trim()), errorMessages, new ExecutionOptions() @@ -920,7 +920,7 @@ public async Task> ExecuteScriptString( /// Arguments to pass to the script. /// Writes the executed script path and arguments to the host. /// A Task that can be awaited for completion. - public async Task ExecuteScriptWithArgs(string script, string arguments = null, bool writeInputToHost = false) + public async Task ExecuteScriptWithArgsAsync(string script, string arguments = null, bool writeInputToHost = false) { PSCommand command = new PSCommand(); @@ -931,7 +931,7 @@ public async Task ExecuteScriptWithArgs(string script, string arguments = null, try { // Assume we can only debug scripts from the FileSystem provider - string workingDir = (await ExecuteCommand( + string workingDir = (await ExecuteCommandAsync( new PSCommand() .AddCommand("Microsoft.PowerShell.Management\\Get-Location") .AddParameter("PSProvider", "FileSystem"), @@ -991,7 +991,7 @@ public async Task ExecuteScriptWithArgs(string script, string arguments = null, true); } - await this.ExecuteCommand( + await this.ExecuteCommandAsync( command, null, sendOutputToHost: true, @@ -1003,8 +1003,8 @@ await this.ExecuteCommand( /// reliquishing control of the pipeline thread during event processing. /// /// - /// This method is called automatically by and - /// . Consider using them instead of this method directly when + /// This method is called automatically by and + /// . Consider using them instead of this method directly when /// possible. /// internal void ForcePSEventHandling() @@ -1025,14 +1025,14 @@ internal void ForcePSEventHandling() /// An awaitable that the caller can use to know when execution completes. /// /// - /// This method is called automatically by . Consider using + /// This method is called automatically by . Consider using /// that method instead of calling this directly when possible. /// - internal async Task InvokeOnPipelineThread(Action invocationAction) + internal async Task InvokeOnPipelineThreadAsync(Action invocationAction) { if (this.PromptNest.IsReadLineBusy()) { - await this.InvocationEventQueue.InvokeOnPipelineThread(invocationAction); + await this.InvocationEventQueue.InvokeOnPipelineThreadAsync(invocationAction); return; } @@ -1065,7 +1065,7 @@ internal async Task InvokeReadLineAsync(bool isCommandLine, Cancellation /// loaded. /// /// A Task that can be awaited for completion. - public async Task LoadHostProfiles() + public async Task LoadHostProfilesAsync() { if (this.profilePaths != null) { @@ -1075,12 +1075,12 @@ public async Task LoadHostProfiles() { command = new PSCommand(); command.AddCommand(profilePath, false); - await this.ExecuteCommand(command, true, true); + await this.ExecuteCommandAsync(command, true, true); } // Gather the session details (particularly the prompt) after // loading the user's profiles. - await this.GetSessionDetailsInRunspace(); + await this.GetSessionDetailsInRunspaceAsync(); } } @@ -1279,12 +1279,12 @@ public void Dispose() this.initialRunspace = null; } - private async Task GetRunspaceHandle(bool isReadLine) + private async Task GetRunspaceHandleAsync(bool isReadLine) { - return await this.GetRunspaceHandleImpl(CancellationToken.None, isReadLine); + return await this.GetRunspaceHandleImplAsync(CancellationToken.None, isReadLine); } - private async Task GetRunspaceHandleImpl(CancellationToken cancellationToken, bool isReadLine) + private async Task GetRunspaceHandleImplAsync(CancellationToken cancellationToken, bool isReadLine) { return await this.PromptNest.GetRunspaceHandleAsync(cancellationToken, isReadLine); } @@ -1446,7 +1446,7 @@ internal void EnterNestedPrompt() this.ConsoleReader?.StopCommandLoop(); this.ConsoleReader?.StartCommandLoop(); - var localPipelineExecutionTask = localThreadController.TakeExecutionRequest(); + var localPipelineExecutionTask = localThreadController.TakeExecutionRequestAsync(); var localDebuggerStoppedTask = localThreadController.Exit(); // Wait for off-thread pipeline requests and/or ExitNestedPrompt @@ -1459,8 +1459,8 @@ internal void EnterNestedPrompt() if (taskIndex == 0) { var localExecutionTask = localPipelineExecutionTask.GetAwaiter().GetResult(); - localPipelineExecutionTask = localThreadController.TakeExecutionRequest(); - localExecutionTask.Execute().GetAwaiter().GetResult(); + localPipelineExecutionTask = localThreadController.TakeExecutionRequestAsync(); + localExecutionTask.ExecuteAsync().GetAwaiter().GetResult(); continue; } @@ -1494,9 +1494,9 @@ internal void ExitNestedPrompt() /// unescaped before calling this method. /// /// - public async Task SetWorkingDirectory(string path) + public async Task SetWorkingDirectoryAsync(string path) { - await this.SetWorkingDirectory(path, true); + await this.SetWorkingDirectoryAsync(path, true); } /// @@ -1504,7 +1504,7 @@ public async Task SetWorkingDirectory(string path) /// /// /// Specify false to have the path escaped, otherwise specify true if the path has already been escaped. - public async Task SetWorkingDirectory(string path, bool isPathAlreadyEscaped) + public async Task SetWorkingDirectoryAsync(string path, bool isPathAlreadyEscaped) { this.InitialWorkingDirectory = path; @@ -1513,7 +1513,7 @@ public async Task SetWorkingDirectory(string path, bool isPathAlreadyEscaped) path = WildcardEscapePath(path); } - await ExecuteCommand( + await ExecuteCommandAsync( new PSCommand().AddCommand("Set-Location").AddParameter("Path", path), null, sendOutputToHost: false, @@ -2039,9 +2039,9 @@ private SessionDetails GetSessionDetails(Func invokeAction) return this.mostRecentSessionDetails; } - private async Task GetSessionDetailsInRunspace() + private async Task GetSessionDetailsInRunspaceAsync() { - using (RunspaceHandle runspaceHandle = await this.GetRunspaceHandle()) + using (RunspaceHandle runspaceHandle = await this.GetRunspaceHandleAsync()) { return this.GetSessionDetailsInRunspace(runspaceHandle.Runspace); } @@ -2246,7 +2246,7 @@ private void OnDebuggerStop(object sender, DebuggerStopEventArgs e) this.logger.Write(LogLevel.Verbose, "Starting pipeline thread message loop..."); Task localPipelineExecutionTask = - localThreadController.TakeExecutionRequest(); + localThreadController.TakeExecutionRequestAsync(); Task localDebuggerStoppedTask = localThreadController.Exit(); while (true) @@ -2292,8 +2292,8 @@ private void OnDebuggerStop(object sender, DebuggerStopEventArgs e) this.logger.Write(LogLevel.Verbose, "Received pipeline thread execution request."); IPipelineExecutionRequest executionRequest = localPipelineExecutionTask.Result; - localPipelineExecutionTask = localThreadController.TakeExecutionRequest(); - executionRequest.Execute().GetAwaiter().GetResult(); + localPipelineExecutionTask = localThreadController.TakeExecutionRequestAsync(); + executionRequest.ExecuteAsync().GetAwaiter().GetResult(); this.logger.Write(LogLevel.Verbose, "Pipeline thread execution completed."); diff --git a/src/PowerShellEditorServices/Session/RemoteFileManager.cs b/src/PowerShellEditorServices/Session/RemoteFileManager.cs index e2d47dd88..c9885b84f 100644 --- a/src/PowerShellEditorServices/Session/RemoteFileManager.cs +++ b/src/PowerShellEditorServices/Session/RemoteFileManager.cs @@ -253,7 +253,7 @@ public RemoteFileManager( this.logger = logger; this.powerShellContext = powerShellContext; - this.powerShellContext.RunspaceChanged += HandleRunspaceChanged; + this.powerShellContext.RunspaceChanged += HandleRunspaceChangedAsync; this.editorOperations = editorOperations; @@ -287,7 +287,7 @@ public RemoteFileManager( /// /// The local file path where the remote file's contents have been stored. /// - public async Task FetchRemoteFile( + public async Task FetchRemoteFileAsync( string remoteFilePath, RunspaceDetails runspaceDetails) { @@ -313,7 +313,7 @@ public async Task FetchRemoteFile( command.AddParameter("Encoding", "Byte"); byte[] fileContent = - (await this.powerShellContext.ExecuteCommand(command, false, false)) + (await this.powerShellContext.ExecuteCommandAsync(command, false, false)) .FirstOrDefault(); if (fileContent != null) @@ -350,7 +350,7 @@ public async Task FetchRemoteFile( /// file to disk before this method is called. /// /// A Task to be awaited for completion. - public async Task SaveRemoteFile(string localFilePath) + public async Task SaveRemoteFileAsync(string localFilePath) { string remoteFilePath = this.GetMappedPath( @@ -383,7 +383,7 @@ public async Task SaveRemoteFile(string localFilePath) StringBuilder errorMessages = new StringBuilder(); - await this.powerShellContext.ExecuteCommand( + await this.powerShellContext.ExecuteCommandAsync( saveCommand, errorMessages, false, @@ -509,7 +509,7 @@ private RemotePathMappings GetPathMappings(RunspaceDetails runspaceDetails) return remotePathMappings; } - private async void HandleRunspaceChanged(object sender, RunspaceChangedEventArgs e) + private async void HandleRunspaceChangedAsync(object sender, RunspaceChangedEventArgs e) { if (e.ChangeAction == RunspaceChangeAction.Enter) { @@ -530,7 +530,7 @@ private async void HandleRunspaceChanged(object sender, RunspaceChangedEventArgs { foreach (string remotePath in remotePathMappings.OpenedPaths) { - await this.editorOperations?.CloseFile(remotePath); + await this.editorOperations?.CloseFileAsync(remotePath); } } } @@ -542,7 +542,7 @@ private async void HandleRunspaceChanged(object sender, RunspaceChangedEventArgs } } - private async void HandlePSEventReceived(object sender, PSEventArgs args) + private async void HandlePSEventReceivedAsync(object sender, PSEventArgs args) { if (string.Equals(RemoteSessionOpenFile, args.SourceIdentifier, StringComparison.CurrentCultureIgnoreCase)) { @@ -591,8 +591,8 @@ private async void HandlePSEventReceived(object sender, PSEventArgs args) } else { - await this.editorOperations?.NewFile(); - EditorContext context = await this.editorOperations?.GetEditorContext(); + await this.editorOperations?.NewFileAsync(); + EditorContext context = await this.editorOperations?.GetEditorContextAsync(); context?.CurrentFile.InsertText(Encoding.UTF8.GetString(fileContent, 0, fileContent.Length)); } } @@ -605,7 +605,7 @@ private async void HandlePSEventReceived(object sender, PSEventArgs args) } // Open the file in the editor - this.editorOperations?.OpenFile(localFilePath, preview); + this.editorOperations?.OpenFileAsync(localFilePath, preview); } } catch (NullReferenceException e) @@ -622,7 +622,7 @@ private void RegisterPSEditFunction(RunspaceDetails runspaceDetails) { try { - runspaceDetails.Runspace.Events.ReceivedEvents.PSEventReceived += HandlePSEventReceived; + runspaceDetails.Runspace.Events.ReceivedEvents.PSEventReceived += HandlePSEventReceivedAsync; PSCommand createCommand = new PSCommand(); createCommand @@ -631,7 +631,7 @@ private void RegisterPSEditFunction(RunspaceDetails runspaceDetails) if (runspaceDetails.Context == RunspaceContext.DebuggedRunspace) { - this.powerShellContext.ExecuteCommand(createCommand).Wait(); + this.powerShellContext.ExecuteCommandAsync(createCommand).Wait(); } else { @@ -659,7 +659,7 @@ private void RemovePSEditFunction(RunspaceDetails runspaceDetails) { if (runspaceDetails.Runspace.Events != null) { - runspaceDetails.Runspace.Events.ReceivedEvents.PSEventReceived -= HandlePSEventReceived; + runspaceDetails.Runspace.Events.ReceivedEvents.PSEventReceived -= HandlePSEventReceivedAsync; } if (runspaceDetails.Runspace.RunspaceStateInfo.State == RunspaceState.Opened) diff --git a/src/PowerShellEditorServices/Session/ThreadController.cs b/src/PowerShellEditorServices/Session/ThreadController.cs index 9a5583f5b..8720e3fa7 100644 --- a/src/PowerShellEditorServices/Session/ThreadController.cs +++ b/src/PowerShellEditorServices/Session/ThreadController.cs @@ -63,7 +63,7 @@ internal bool IsCurrentThread() /// A task object representing the asynchronous operation. The Result property will return /// the output of the command invocation. /// - internal async Task> RequestPipelineExecution( + internal async Task> RequestPipelineExecutionAsync( PipelineExecutionRequest executionRequest) { await PipelineRequestQueue.EnqueueAsync(executionRequest); @@ -78,7 +78,7 @@ internal async Task> RequestPipelineExecution( /// A task object representing the asynchronous operation. The Result property will return /// the retrieved pipeline execution request. /// - internal async Task TakeExecutionRequest() + internal async Task TakeExecutionRequestAsync() { return await PipelineRequestQueue.DequeueAsync(); } diff --git a/src/PowerShellEditorServices/Templates/TemplateService.cs b/src/PowerShellEditorServices/Templates/TemplateService.cs index 8ee3da496..18f58085c 100644 --- a/src/PowerShellEditorServices/Templates/TemplateService.cs +++ b/src/PowerShellEditorServices/Templates/TemplateService.cs @@ -50,7 +50,7 @@ public TemplateService(PowerShellContext powerShellContext, ILogger logger) /// Checks if Plaster is installed on the user's machine. /// /// A Task that can be awaited until the check is complete. The result will be true if Plaster is installed. - public async Task ImportPlasterIfInstalled() + public async Task ImportPlasterIfInstalledAsync() { if (!this.isPlasterInstalled.HasValue) { @@ -73,7 +73,7 @@ public async Task ImportPlasterIfInstalled() this.logger.Write(LogLevel.Verbose, "Checking if Plaster is installed..."); var getResult = - await this.powerShellContext.ExecuteCommand( + await this.powerShellContext.ExecuteCommandAsync( psCommand, false, false); PSObject moduleObject = getResult.First(); @@ -98,7 +98,7 @@ await this.powerShellContext.ExecuteCommand( .AddParameter("PassThru"); var importResult = - await this.powerShellContext.ExecuteCommand( + await this.powerShellContext.ExecuteCommandAsync( psCommand, false, false); this.isPlasterLoaded = importResult.Any(); @@ -124,7 +124,7 @@ await this.powerShellContext.ExecuteCommand( /// included templates. /// /// A Task which can be awaited for the TemplateDetails list to be returned. - public async Task GetAvailableTemplates( + public async Task GetAvailableTemplatesAsync( bool includeInstalledModules) { if (!this.isPlasterLoaded) @@ -141,7 +141,7 @@ public async Task GetAvailableTemplates( } var templateObjects = - await this.powerShellContext.ExecuteCommand( + await this.powerShellContext.ExecuteCommandAsync( psCommand, false, false); this.logger.Write( @@ -162,7 +162,7 @@ await this.powerShellContext.ExecuteCommand( /// The folder path containing the template. /// The folder path where the files will be created. /// A boolean-returning Task which communicates success or failure. - public async Task CreateFromTemplate( + public async Task CreateFromTemplateAsync( string templatePath, string destinationPath) { @@ -176,7 +176,7 @@ public async Task CreateFromTemplate( command.AddParameter("DestinationPath", destinationPath); var errorString = new System.Text.StringBuilder(); - await this.powerShellContext.ExecuteCommand( + await this.powerShellContext.ExecuteCommandAsync( command, errorString, new ExecutionOptions diff --git a/src/PowerShellEditorServices/Utility/AsyncDebouncer.cs b/src/PowerShellEditorServices/Utility/AsyncDebouncer.cs index f8bbd2422..9644eff77 100644 --- a/src/PowerShellEditorServices/Utility/AsyncDebouncer.cs +++ b/src/PowerShellEditorServices/Utility/AsyncDebouncer.cs @@ -59,12 +59,12 @@ public AsyncDebouncer(int flushInterval, bool restartOnInvoke) /// The argument for this implementation's Invoke method. /// /// A Task to be awaited until the Invoke is queued. - public async Task Invoke(TInvokeArgs invokeArgument) + public async Task InvokeAsync(TInvokeArgs invokeArgument) { using (await this.asyncLock.LockAsync()) { // Invoke the implementor - await this.OnInvoke(invokeArgument); + await this.OnInvokeAsync(invokeArgument); // If there's no timer, start one if (this.currentTimerTask == null) @@ -88,7 +88,7 @@ public async Task Invoke(TInvokeArgs invokeArgument) /// deadlocks could occur. /// /// A Task to be awaited until Flush completes. - public async Task Flush() + public async Task FlushAsync() { using (await this.asyncLock.LockAsync()) { @@ -96,7 +96,7 @@ public async Task Flush() this.CancelTimer(); // Flush the current output - await this.OnFlush(); + await this.OnFlushAsync(); } } @@ -112,13 +112,13 @@ public async Task Flush() /// The argument for this implementation's OnInvoke method. /// /// A Task to be awaited for the invoke to complete. - protected abstract Task OnInvoke(TInvokeArgs invokeArgument); + protected abstract Task OnInvokeAsync(TInvokeArgs invokeArgument); /// /// Implemented by the subclass to complete the current operation. /// /// A Task to be awaited for the operation to complete. - protected abstract Task OnFlush(); + protected abstract Task OnFlushAsync(); #endregion @@ -135,7 +135,7 @@ private void StartTimer() { if (!t.IsCanceled) { - return this.Flush(); + return this.FlushAsync(); } else { @@ -153,8 +153,8 @@ private bool CancelTimer() } // Was the task cancelled? - bool wasCancelled = - this.currentTimerTask == null || + bool wasCancelled = + this.currentTimerTask == null || this.currentTimerTask.IsCanceled; // Clear the current task so that another may be created diff --git a/test/PowerShellEditorServices.Test.Host/DebugAdapterTests.cs b/test/PowerShellEditorServices.Test.Host/DebugAdapterTests.cs index 7a2ccd197..14c6171a6 100644 --- a/test/PowerShellEditorServices.Test.Host/DebugAdapterTests.cs +++ b/test/PowerShellEditorServices.Test.Host/DebugAdapterTests.cs @@ -48,7 +48,7 @@ await this.LaunchService( this.debugAdapterClient = new DebugAdapterClient( - await NamedPipeClientChannel.Connect( + await NamedPipeClientChannel.ConnectAsync( pipeNames.Item2, MessageProtocolType.DebugAdapter, this.logger), @@ -57,7 +57,7 @@ await NamedPipeClientChannel.Connect( this.messageSender = this.debugAdapterClient; this.messageHandlers = this.debugAdapterClient; - await this.debugAdapterClient.Start(); + await this.debugAdapterClient.StartAsync(); } public Task DisposeAsync() @@ -136,7 +136,7 @@ public async Task DebugAdapterReceivesOutputEvents() private async Task LaunchScript(string scriptPath) { - await this.debugAdapterClient.LaunchScript(scriptPath); + await this.debugAdapterClient.LaunchScriptAsync(scriptPath); } } } diff --git a/test/PowerShellEditorServices.Test.Host/LanguageServerTests.cs b/test/PowerShellEditorServices.Test.Host/LanguageServerTests.cs index 50ec35f7f..5d25fccd3 100644 --- a/test/PowerShellEditorServices.Test.Host/LanguageServerTests.cs +++ b/test/PowerShellEditorServices.Test.Host/LanguageServerTests.cs @@ -51,7 +51,7 @@ await this.LaunchService( this.languageServiceClient = new LanguageServiceClient( - await NamedPipeClientChannel.Connect( + await NamedPipeClientChannel.ConnectAsync( pipeNames.Item1, MessageProtocolType.LanguageServer, this.logger), @@ -65,7 +65,7 @@ await NamedPipeClientChannel.Connect( public async Task DisposeAsync() { - await this.languageServiceClient.Stop(); + await this.languageServiceClient.StopAsync(); this.KillService(); } @@ -644,7 +644,7 @@ public async Task ServiceExecutesReplCommandAndReceivesChoicePrompt() Assert.Equal(1, showChoicePromptRequest.DefaultChoices[0]); // Respond to the prompt request - await requestContext.SendResult( + await requestContext.SendResultAsync( new ShowChoicePromptResponse { ResponseText = "a" @@ -695,7 +695,7 @@ public async Task ServiceExecutesReplCommandAndReceivesInputPrompt() Assert.Equal("Name", showInputPromptRequest.Name); // Respond to the prompt request - await requestContext.SendResult( + await requestContext.SendResultAsync( new ShowInputPromptResponse { ResponseText = "John" @@ -865,7 +865,7 @@ private async Task SendConfigurationRequest( bool enableProfileLoading = false) { // Send the configuration change to cause profiles to be loaded - await this.languageServiceClient.SendEvent( + await this.languageServiceClient.SendEventAsync( DidChangeConfigurationNotification.Type, new DidChangeConfigurationParams { diff --git a/test/PowerShellEditorServices.Test.Host/ServerTestsBase.cs b/test/PowerShellEditorServices.Test.Host/ServerTestsBase.cs index c126be90a..e805d85cd 100644 --- a/test/PowerShellEditorServices.Test.Host/ServerTestsBase.cs +++ b/test/PowerShellEditorServices.Test.Host/ServerTestsBase.cs @@ -170,7 +170,7 @@ protected Task SendRequest SendRequest(NotificationType eventType, TParams eventParams) { return - this.messageSender.SendEvent( + this.messageSender.SendEventAsync( eventType, eventParams); } diff --git a/test/PowerShellEditorServices.Test.Protocol/Message/MessageReaderWriterTests.cs b/test/PowerShellEditorServices.Test.Protocol/Message/MessageReaderWriterTests.cs index 5212a7a1c..9d637007d 100644 --- a/test/PowerShellEditorServices.Test.Protocol/Message/MessageReaderWriterTests.cs +++ b/test/PowerShellEditorServices.Test.Protocol/Message/MessageReaderWriterTests.cs @@ -42,7 +42,7 @@ public async Task WritesMessage() // Write the message and then roll back the stream to be read // TODO: This will need to be redone! - await messageWriter.WriteMessage(Message.Event("testEvent", null)); + await messageWriter.WriteMessageAsync(Message.Event("testEvent", null)); outputStream.Seek(0, SeekOrigin.Begin); string expectedHeaderString = @@ -87,7 +87,7 @@ public void ReadsMessage() inputStream.Flush(); inputStream.Seek(0, SeekOrigin.Begin); - Message messageResult = messageReader.ReadMessage().Result; + Message messageResult = messageReader.ReadMessageAsync().Result; Assert.Equal("testEvent", messageResult.Method); inputStream.Dispose(); @@ -123,7 +123,7 @@ public void ReadsManyBufferedMessages() // Read the written messages from the stream for (int i = 0; i < overflowMessageCount; i++) { - Message messageResult = messageReader.ReadMessage().Result; + Message messageResult = messageReader.ReadMessageAsync().Result; Assert.Equal("testEvent", messageResult.Method); } @@ -152,7 +152,7 @@ public void ReaderResizesBufferForLargeMessages() inputStream.Flush(); inputStream.Seek(0, SeekOrigin.Begin); - Message messageResult = messageReader.ReadMessage().Result; + Message messageResult = messageReader.ReadMessageAsync().Result; Assert.Equal("testEvent", messageResult.Method); inputStream.Dispose(); diff --git a/test/PowerShellEditorServices.Test.Protocol/Server/OutputDebouncerTests.cs b/test/PowerShellEditorServices.Test.Protocol/Server/OutputDebouncerTests.cs index 9e3db950f..fa70bd631 100644 --- a/test/PowerShellEditorServices.Test.Protocol/Server/OutputDebouncerTests.cs +++ b/test/PowerShellEditorServices.Test.Protocol/Server/OutputDebouncerTests.cs @@ -86,7 +86,7 @@ private static Task SendOutput( string outputText, bool includeNewLine = false) { - return debouncer.Invoke( + return debouncer.InvokeAsync( new OutputWrittenEventArgs( outputText, includeNewLine, @@ -100,7 +100,7 @@ internal class TestMessageSender : IMessageSender { public List OutputEvents { get; } = new List(); - public Task SendEvent( + public Task SendEventAsync( NotificationType eventType, TParams eventParams) { @@ -114,7 +114,7 @@ public Task SendEvent( return Task.FromResult(true); } - public Task SendRequest( + public Task SendRequestAsync( RequestType requestType, TParams requestParams, bool waitForResponse) { @@ -122,7 +122,7 @@ public Task SendRequest throw new NotImplementedException(); } - public Task SendRequest(RequestType0 requestType0) + public Task SendRequestAsync(RequestType0 requestType0) { // Legitimately not implemented for these tests. throw new NotImplementedException(); diff --git a/test/PowerShellEditorServices.Test/Console/ChoicePromptHandlerTests.cs b/test/PowerShellEditorServices.Test/Console/ChoicePromptHandlerTests.cs index 2fba1ea5e..55f8b60e9 100644 --- a/test/PowerShellEditorServices.Test/Console/ChoicePromptHandlerTests.cs +++ b/test/PowerShellEditorServices.Test/Console/ChoicePromptHandlerTests.cs @@ -28,7 +28,7 @@ public void ChoicePromptReturnsCorrectIdForChoice() { TestChoicePromptHandler choicePromptHandler = new TestChoicePromptHandler(); Task promptTask = - choicePromptHandler.PromptForChoice( + choicePromptHandler.PromptForChoiceAsync( "Test prompt", "Message is irrelevant", Choices, @@ -50,7 +50,7 @@ public void ChoicePromptReturnsCorrectIdForHotKey() { TestChoicePromptHandler choicePromptHandler = new TestChoicePromptHandler(); Task promptTask = - choicePromptHandler.PromptForChoice( + choicePromptHandler.PromptForChoiceAsync( "Test prompt", "Message is irrelevant", Choices, @@ -75,7 +75,7 @@ public void ChoicePromptRepromptsOnInvalidInput() new TestChoicePromptHandler(); Task promptTask = - choicePromptHandler.PromptForChoice( + choicePromptHandler.PromptForChoiceAsync( "Test prompt", "Message is irrelevant", Choices, @@ -105,7 +105,7 @@ public void ReturnInputString(string inputString) this.linePromptTask.SetResult(inputString); } - protected override Task ReadInputString(CancellationToken cancellationToken) + protected override Task ReadInputStringAsync(CancellationToken cancellationToken) { this.linePromptTask = new TaskCompletionSource(); return this.linePromptTask.Task; diff --git a/test/PowerShellEditorServices.Test/Console/InputPromptHandlerTests.cs b/test/PowerShellEditorServices.Test/Console/InputPromptHandlerTests.cs index 04bed7314..689ae1c8b 100644 --- a/test/PowerShellEditorServices.Test/Console/InputPromptHandlerTests.cs +++ b/test/PowerShellEditorServices.Test/Console/InputPromptHandlerTests.cs @@ -39,7 +39,7 @@ public void InputPromptHandlerReturnsValuesOfCorrectType() { TestInputPromptHandler inputPromptHandler = new TestInputPromptHandler(); Task> promptTask = - inputPromptHandler.PromptForInput( + inputPromptHandler.PromptForInputAsync( "Test Prompt", "Message is irrelevant", Fields, @@ -71,7 +71,7 @@ public void InputPromptHandlerAcceptsArrayOfNonStringValues() { TestInputPromptHandler inputPromptHandler = new TestInputPromptHandler(); Task> promptTask = - inputPromptHandler.PromptForInput( + inputPromptHandler.PromptForInputAsync( "Test Prompt", "Message is irrelevant", new FieldDetails[] @@ -95,7 +95,7 @@ public void InputPromptRetriesWhenCannotCastValue() { TestInputPromptHandler inputPromptHandler = new TestInputPromptHandler(); Task> promptTask = - inputPromptHandler.PromptForInput( + inputPromptHandler.PromptForInputAsync( "Test Prompt", "Message is irrelevant", Fields, @@ -146,13 +146,13 @@ public void ReturnSecureString(SecureString secureString) this.securePromptTask.SetResult(secureString); } - protected override Task ReadInputString(CancellationToken cancellationToken) + protected override Task ReadInputStringAsync(CancellationToken cancellationToken) { this.linePromptTask = new TaskCompletionSource(); return this.linePromptTask.Task; } - protected override Task ReadSecureString(CancellationToken cancellationToken) + protected override Task ReadSecureStringAsync(CancellationToken cancellationToken) { this.securePromptTask = new TaskCompletionSource(); return this.securePromptTask.Task; diff --git a/test/PowerShellEditorServices.Test/Debugging/DebugServiceTests.cs b/test/PowerShellEditorServices.Test/Debugging/DebugServiceTests.cs index 4a5d53e82..da956a640 100644 --- a/test/PowerShellEditorServices.Test/Debugging/DebugServiceTests.cs +++ b/test/PowerShellEditorServices.Test/Debugging/DebugServiceTests.cs @@ -111,7 +111,7 @@ public async Task DebuggerAcceptsScriptArgs(string[] args) this.workspace.GetFile( TestUtilities.NormalizePath("../../../../PowerShellEditorServices.Test.Shared/Debugging/Debug` W&ith Params `[Test].ps1")); - await this.debugService.SetLineBreakpoints( + await this.debugService.SetLineBreakpointsAsync( debugWithParamsFile, new[] { BreakpointDetails.Create("", 3) }); @@ -119,7 +119,7 @@ await this.debugService.SetLineBreakpoints( // Execute the script and wait for the breakpoint to be hit Task executeTask = - this.powerShellContext.ExecuteScriptWithArgs( + this.powerShellContext.ExecuteScriptWithArgsAsync( debugWithParamsFile.FilePath, arguments); await this.AssertDebuggerStopped(debugWithParamsFile.FilePath); @@ -164,7 +164,7 @@ await this.debugService.SetLineBreakpoints( public async Task DebuggerSetsAndClearsFunctionBreakpoints() { CommandBreakpointDetails[] breakpoints = - await this.debugService.SetCommandBreakpoints( + await this.debugService.SetCommandBreakpointsAsync( new[] { CommandBreakpointDetails.Create("Write-Host"), CommandBreakpointDetails.Create("Get-Date") @@ -175,14 +175,14 @@ await this.debugService.SetCommandBreakpoints( Assert.Equal("Get-Date", breakpoints[1].Name); breakpoints = - await this.debugService.SetCommandBreakpoints( + await this.debugService.SetCommandBreakpointsAsync( new[] { CommandBreakpointDetails.Create("Get-Host") }); Assert.Equal(1, breakpoints.Length); Assert.Equal("Get-Host", breakpoints[0].Name); breakpoints = - await this.debugService.SetCommandBreakpoints( + await this.debugService.SetCommandBreakpointsAsync( new CommandBreakpointDetails[] {}); Assert.Equal(0, breakpoints.Length); @@ -192,7 +192,7 @@ await this.debugService.SetCommandBreakpoints( public async Task DebuggerStopsOnFunctionBreakpoints() { CommandBreakpointDetails[] breakpoints = - await this.debugService.SetCommandBreakpoints( + await this.debugService.SetCommandBreakpointsAsync( new[] { CommandBreakpointDetails.Create("Write-Host") }); @@ -200,7 +200,7 @@ await this.debugService.SetCommandBreakpoints( await this.AssertStateChange(PowerShellContextState.Ready); Task executeTask = - this.powerShellContext.ExecuteScriptWithArgs( + this.powerShellContext.ExecuteScriptWithArgsAsync( this.debugScriptFile.FilePath); // Wait for function breakpoint to hit @@ -238,7 +238,7 @@ await this.debugService.SetCommandBreakpoints( public async Task DebuggerSetsAndClearsLineBreakpoints() { BreakpointDetails[] breakpoints = - await this.debugService.SetLineBreakpoints( + await this.debugService.SetLineBreakpointsAsync( this.debugScriptFile, new[] { BreakpointDetails.Create("", 5), @@ -252,7 +252,7 @@ await this.debugService.SetLineBreakpoints( Assert.Equal(10, breakpoints[1].LineNumber); breakpoints = - await this.debugService.SetLineBreakpoints( + await this.debugService.SetLineBreakpointsAsync( this.debugScriptFile, new[] { BreakpointDetails.Create("", 2) }); @@ -261,7 +261,7 @@ await this.debugService.SetLineBreakpoints( Assert.Equal(1, confirmedBreakpoints.Count()); Assert.Equal(2, breakpoints[0].LineNumber); - await this.debugService.SetLineBreakpoints( + await this.debugService.SetLineBreakpointsAsync( this.debugScriptFile, new[] { BreakpointDetails.Create("", 0) }); @@ -276,7 +276,7 @@ await this.debugService.SetLineBreakpoints( public async Task DebuggerStopsOnLineBreakpoints() { BreakpointDetails[] breakpoints = - await this.debugService.SetLineBreakpoints( + await this.debugService.SetLineBreakpointsAsync( this.debugScriptFile, new[] { BreakpointDetails.Create("", 5), @@ -286,7 +286,7 @@ await this.debugService.SetLineBreakpoints( await this.AssertStateChange(PowerShellContextState.Ready); Task executeTask = - this.powerShellContext.ExecuteScriptWithArgs( + this.powerShellContext.ExecuteScriptWithArgsAsync( this.debugScriptFile.FilePath); // Wait for a couple breakpoints @@ -307,7 +307,7 @@ public async Task DebuggerStopsOnConditionalBreakpoints() const int breakpointValue2 = 20; BreakpointDetails[] breakpoints = - await this.debugService.SetLineBreakpoints( + await this.debugService.SetLineBreakpointsAsync( this.debugScriptFile, new[] { BreakpointDetails.Create("", 7, null, $"$i -eq {breakpointValue1} -or $i -eq {breakpointValue2}"), @@ -316,7 +316,7 @@ await this.debugService.SetLineBreakpoints( await this.AssertStateChange(PowerShellContextState.Ready); Task executeTask = - this.powerShellContext.ExecuteScriptWithArgs( + this.powerShellContext.ExecuteScriptWithArgsAsync( this.debugScriptFile.FilePath); // Wait for conditional breakpoint to hit @@ -357,7 +357,7 @@ public async Task DebuggerStopsOnHitConditionBreakpoint() const int hitCount = 5; BreakpointDetails[] breakpoints = - await this.debugService.SetLineBreakpoints( + await this.debugService.SetLineBreakpointsAsync( this.debugScriptFile, new[] { BreakpointDetails.Create("", 6, null, null, $"{hitCount}"), @@ -366,7 +366,7 @@ await this.debugService.SetLineBreakpoints( await this.AssertStateChange(PowerShellContextState.Ready); Task executeTask = - this.powerShellContext.ExecuteScriptWithArgs( + this.powerShellContext.ExecuteScriptWithArgsAsync( this.debugScriptFile.FilePath); // Wait for conditional breakpoint to hit @@ -393,7 +393,7 @@ public async Task DebuggerStopsOnConditionalAndHitConditionBreakpoint() const int hitCount = 5; BreakpointDetails[] breakpoints = - await this.debugService.SetLineBreakpoints( + await this.debugService.SetLineBreakpointsAsync( this.debugScriptFile, new[] { BreakpointDetails.Create("", 6, null, $"$i % 2 -eq 0", $"{hitCount}"), @@ -402,7 +402,7 @@ await this.debugService.SetLineBreakpoints( await this.AssertStateChange(PowerShellContextState.Ready); Task executeTask = - this.powerShellContext.ExecuteScriptWithArgs( + this.powerShellContext.ExecuteScriptWithArgsAsync( this.debugScriptFile.FilePath); // Wait for conditional breakpoint to hit @@ -428,7 +428,7 @@ await this.debugService.SetLineBreakpoints( public async Task DebuggerProvidesMessageForInvalidConditionalBreakpoint() { BreakpointDetails[] breakpoints = - await this.debugService.SetLineBreakpoints( + await this.debugService.SetLineBreakpointsAsync( this.debugScriptFile, new[] { BreakpointDetails.Create("", 5), @@ -450,7 +450,7 @@ await this.debugService.SetLineBreakpoints( public async Task DebuggerFindsParseableButInvalidSimpleBreakpointConditions() { BreakpointDetails[] breakpoints = - await this.debugService.SetLineBreakpoints( + await this.debugService.SetLineBreakpointsAsync( this.debugScriptFile, new[] { BreakpointDetails.Create("", 5, column: null, condition: "$i == 100"), @@ -482,7 +482,7 @@ await this.AssertStateChange( "Unexpected breakpoint found in script file"); Task executeTask = - this.powerShellContext.ExecuteScriptString( + this.powerShellContext.ExecuteScriptStringAsync( this.debugScriptFile.FilePath); // Break execution and wait for the debugger to stop @@ -505,7 +505,7 @@ await this.AssertStateChange( public async Task DebuggerRunsCommandsWhileStopped() { Task executeTask = - this.powerShellContext.ExecuteScriptString( + this.powerShellContext.ExecuteScriptStringAsync( this.debugScriptFile.FilePath); // Break execution and wait for the debugger to stop @@ -515,7 +515,7 @@ await this.AssertStateChange( PowerShellExecutionResult.Stopped); // Try running a command from outside the pipeline thread - await this.powerShellContext.ExecuteScriptString("Get-Command Get-Process"); + await this.powerShellContext.ExecuteScriptStringAsync("Get-Command Get-Process"); // Abort execution and wait for the debugger to exit this.debugService.Abort(); @@ -528,13 +528,13 @@ await this.AssertStateChange( [Fact] public async Task DebuggerVariableStringDisplaysCorrectly() { - await this.debugService.SetLineBreakpoints( + await this.debugService.SetLineBreakpointsAsync( this.variableScriptFile, new[] { BreakpointDetails.Create("", 18) }); // Execute the script and wait for the breakpoint to be hit Task executeTask = - this.powerShellContext.ExecuteScriptString( + this.powerShellContext.ExecuteScriptStringAsync( this.variableScriptFile.FilePath); await this.AssertDebuggerStopped(this.variableScriptFile.FilePath); @@ -556,13 +556,13 @@ await this.debugService.SetLineBreakpoints( [Fact] public async Task DebuggerGetsVariables() { - await this.debugService.SetLineBreakpoints( + await this.debugService.SetLineBreakpointsAsync( this.variableScriptFile, new[] { BreakpointDetails.Create("", 14) }); // Execute the script and wait for the breakpoint to be hit Task executeTask = - this.powerShellContext.ExecuteScriptString( + this.powerShellContext.ExecuteScriptStringAsync( this.variableScriptFile.FilePath); await this.AssertDebuggerStopped(this.variableScriptFile.FilePath); @@ -606,13 +606,13 @@ await this.debugService.SetLineBreakpoints( [Fact] public async Task DebuggerSetsVariablesNoConversion() { - await this.debugService.SetLineBreakpoints( + await this.debugService.SetLineBreakpointsAsync( this.variableScriptFile, new[] { BreakpointDetails.Create("", 14) }); // Execute the script and wait for the breakpoint to be hit Task executeTask = - this.powerShellContext.ExecuteScriptString( + this.powerShellContext.ExecuteScriptStringAsync( this.variableScriptFile.FilePath); await this.AssertDebuggerStopped(this.variableScriptFile.FilePath); @@ -624,7 +624,7 @@ await this.debugService.SetLineBreakpoints( // Test set of a local string variable (not strongly typed) string newStrValue = "\"Goodbye\""; - string setStrValue = await debugService.SetVariable(stackFrames[0].LocalVariables.Id, "$strVar", newStrValue); + string setStrValue = await debugService.SetVariableAsync(stackFrames[0].LocalVariables.Id, "$strVar", newStrValue); Assert.Equal(newStrValue, setStrValue); VariableScope[] scopes = this.debugService.GetVariableScopes(0); @@ -633,13 +633,13 @@ await this.debugService.SetLineBreakpoints( VariableScope scriptScope = scopes.FirstOrDefault(s => s.Name == VariableContainerDetails.ScriptScopeName); string newIntValue = "49"; string newIntExpr = "7 * 7"; - string setIntValue = await debugService.SetVariable(scriptScope.Id, "$scriptInt", newIntExpr); + string setIntValue = await debugService.SetVariableAsync(scriptScope.Id, "$scriptInt", newIntExpr); Assert.Equal(newIntValue, setIntValue); // Test set of global scope int variable (not strongly typed) VariableScope globalScope = scopes.FirstOrDefault(s => s.Name == VariableContainerDetails.GlobalScopeName); string newGlobalIntValue = "4242"; - string setGlobalIntValue = await debugService.SetVariable(globalScope.Id, "$MaximumHistoryCount", newGlobalIntValue); + string setGlobalIntValue = await debugService.SetVariableAsync(globalScope.Id, "$MaximumHistoryCount", newGlobalIntValue); Assert.Equal(newGlobalIntValue, setGlobalIntValue); // The above just tests that the debug service returns the correct new value string. @@ -675,13 +675,13 @@ await this.debugService.SetLineBreakpoints( [Fact] public async Task DebuggerSetsVariablesWithConversion() { - await this.debugService.SetLineBreakpoints( + await this.debugService.SetLineBreakpointsAsync( this.variableScriptFile, new[] { BreakpointDetails.Create("", 14) }); // Execute the script and wait for the breakpoint to be hit Task executeTask = - this.powerShellContext.ExecuteScriptString( + this.powerShellContext.ExecuteScriptStringAsync( this.variableScriptFile.FilePath); await this.AssertDebuggerStopped(this.variableScriptFile.FilePath); @@ -694,7 +694,7 @@ await this.debugService.SetLineBreakpoints( // Test set of a local string variable (not strongly typed but force conversion) string newStrValue = "\"False\""; string newStrExpr = "$false"; - string setStrValue = await debugService.SetVariable(stackFrames[0].LocalVariables.Id, "$strVar2", newStrExpr); + string setStrValue = await debugService.SetVariableAsync(stackFrames[0].LocalVariables.Id, "$strVar2", newStrExpr); Assert.Equal(newStrValue, setStrValue); VariableScope[] scopes = this.debugService.GetVariableScopes(0); @@ -703,14 +703,14 @@ await this.debugService.SetLineBreakpoints( VariableScope scriptScope = scopes.FirstOrDefault(s => s.Name == VariableContainerDetails.ScriptScopeName); string newBoolValue = "$true"; string newBoolExpr = "1"; - string setBoolValue = await debugService.SetVariable(scriptScope.Id, "$scriptBool", newBoolExpr); + string setBoolValue = await debugService.SetVariableAsync(scriptScope.Id, "$scriptBool", newBoolExpr); Assert.Equal(newBoolValue, setBoolValue); // Test set of global scope ActionPreference variable (strongly typed) VariableScope globalScope = scopes.FirstOrDefault(s => s.Name == VariableContainerDetails.GlobalScopeName); string newGlobalValue = "Continue"; string newGlobalExpr = "'Continue'"; - string setGlobalValue = await debugService.SetVariable(globalScope.Id, "$VerbosePreference", newGlobalExpr); + string setGlobalValue = await debugService.SetVariableAsync(globalScope.Id, "$VerbosePreference", newGlobalExpr); Assert.Equal(newGlobalValue, setGlobalValue); // The above just tests that the debug service returns the correct new value string. @@ -746,13 +746,13 @@ await this.debugService.SetLineBreakpoints( [Fact] public async Task DebuggerVariableEnumDisplaysCorrectly() { - await this.debugService.SetLineBreakpoints( + await this.debugService.SetLineBreakpointsAsync( this.variableScriptFile, new[] { BreakpointDetails.Create("", 18) }); // Execute the script and wait for the breakpoint to be hit Task executeTask = - this.powerShellContext.ExecuteScriptString( + this.powerShellContext.ExecuteScriptStringAsync( this.variableScriptFile.FilePath); await this.AssertDebuggerStopped(this.variableScriptFile.FilePath); @@ -774,13 +774,13 @@ await this.debugService.SetLineBreakpoints( [Fact] public async Task DebuggerVariableHashtableDisplaysCorrectly() { - await this.debugService.SetLineBreakpoints( + await this.debugService.SetLineBreakpointsAsync( this.variableScriptFile, new[] { BreakpointDetails.Create("", 18) }); // Execute the script and wait for the breakpoint to be hit Task executeTask = - this.powerShellContext.ExecuteScriptString( + this.powerShellContext.ExecuteScriptStringAsync( this.variableScriptFile.FilePath); await this.AssertDebuggerStopped(this.variableScriptFile.FilePath); @@ -818,13 +818,13 @@ await this.debugService.SetLineBreakpoints( [Fact] public async Task DebuggerVariablePSObjectDisplaysCorrectly() { - await this.debugService.SetLineBreakpoints( + await this.debugService.SetLineBreakpointsAsync( this.variableScriptFile, new[] { BreakpointDetails.Create("", 18) }); // Execute the script and wait for the breakpoint to be hit Task executeTask = - this.powerShellContext.ExecuteScriptString( + this.powerShellContext.ExecuteScriptStringAsync( this.variableScriptFile.FilePath); await this.AssertDebuggerStopped(this.variableScriptFile.FilePath); @@ -853,13 +853,13 @@ await this.debugService.SetLineBreakpoints( [Fact] public async Task DebuggerVariablePSCustomObjectDisplaysCorrectly() { - await this.debugService.SetLineBreakpoints( + await this.debugService.SetLineBreakpointsAsync( this.variableScriptFile, new[] { BreakpointDetails.Create("", 18) }); // Execute the script and wait for the breakpoint to be hit Task executeTask = - this.powerShellContext.ExecuteScriptString( + this.powerShellContext.ExecuteScriptStringAsync( this.variableScriptFile.FilePath); await this.AssertDebuggerStopped(this.variableScriptFile.FilePath); @@ -896,13 +896,13 @@ await this.debugService.SetLineBreakpoints( #endif public async Task DebuggerVariableProcessObjDisplaysCorrectly() { - await this.debugService.SetLineBreakpoints( + await this.debugService.SetLineBreakpointsAsync( this.variableScriptFile, new[] { BreakpointDetails.Create("", 18) }); // Execute the script and wait for the breakpoint to be hit Task executeTask = - this.powerShellContext.ExecuteScriptString( + this.powerShellContext.ExecuteScriptStringAsync( this.variableScriptFile.FilePath); await this.AssertDebuggerStopped(this.variableScriptFile.FilePath); @@ -966,7 +966,7 @@ private async Task AssertStateChange( private async Task> GetConfirmedBreakpoints(ScriptFile scriptFile) { return - await this.powerShellContext.ExecuteCommand( + await this.powerShellContext.ExecuteCommandAsync( new PSCommand() .AddCommand("Get-PSBreakpoint") .AddParameter("Script", scriptFile.FilePath)); diff --git a/test/PowerShellEditorServices.Test/Extensions/ExtensionServiceTests.cs b/test/PowerShellEditorServices.Test/Extensions/ExtensionServiceTests.cs index 435d16ecb..60e3095b0 100644 --- a/test/PowerShellEditorServices.Test/Extensions/ExtensionServiceTests.cs +++ b/test/PowerShellEditorServices.Test/Extensions/ExtensionServiceTests.cs @@ -39,7 +39,7 @@ public async Task InitializeAsync() { var logger = Logging.NullLogger; this.powerShellContext = PowerShellContextFactory.Create(logger); - await this.powerShellContext.ImportCommandsModule( + await this.powerShellContext.ImportCommandsModuleAsync( TestUtilities.NormalizePath("../../../../../module/PowerShellEditorServices/Commands")); this.extensionService = new ExtensionService(this.powerShellContext); @@ -49,7 +49,7 @@ await this.powerShellContext.ImportCommandsModule( this.extensionService.CommandUpdated += ExtensionService_ExtensionUpdated; this.extensionService.CommandRemoved += ExtensionService_ExtensionRemoved; - await this.extensionService.Initialize( + await this.extensionService.InitializeAsync( this.editorOperations, new ComponentRegistry()); @@ -72,7 +72,7 @@ public Task DisposeAsync() [Fact] public async Task CanRegisterAndInvokeCommandWithCmdletName() { - await extensionService.PowerShellContext.ExecuteScriptString( + await extensionService.PowerShellContext.ExecuteScriptStringAsync( TestUtilities.NormalizeNewlines("function Invoke-Extension { $global:extensionValue = 5 }\n") + "Register-EditorCommand -Name \"test.function\" -DisplayName \"Function extension\" -Function \"Invoke-Extension\""); @@ -80,31 +80,31 @@ await extensionService.PowerShellContext.ExecuteScriptString( EditorCommand command = await this.AssertExtensionEvent(EventType.Add, "test.function"); // Invoke the command - await extensionService.InvokeCommand("test.function", this.commandContext); + await extensionService.InvokeCommandAsync("test.function", this.commandContext); // Assert the expected value PSCommand psCommand = new PSCommand(); psCommand.AddScript("$global:extensionValue"); - var results = await powerShellContext.ExecuteCommand(psCommand); + var results = await powerShellContext.ExecuteCommandAsync(psCommand); Assert.Equal(5, results.FirstOrDefault()); } [Fact] public async Task CanRegisterAndInvokeCommandWithScriptBlock() { - await extensionService.PowerShellContext.ExecuteScriptString( + await extensionService.PowerShellContext.ExecuteScriptStringAsync( "Register-EditorCommand -Name \"test.scriptblock\" -DisplayName \"ScriptBlock extension\" -ScriptBlock { $global:extensionValue = 10 }"); // Wait for the add event EditorCommand command = await this.AssertExtensionEvent(EventType.Add, "test.scriptblock"); // Invoke the command - await extensionService.InvokeCommand("test.scriptblock", this.commandContext); + await extensionService.InvokeCommandAsync("test.scriptblock", this.commandContext); // Assert the expected value PSCommand psCommand = new PSCommand(); psCommand.AddScript("$global:extensionValue"); - var results = await powerShellContext.ExecuteCommand(psCommand); + var results = await powerShellContext.ExecuteCommandAsync(psCommand); Assert.Equal(10, results.FirstOrDefault()); } @@ -112,7 +112,7 @@ await extensionService.PowerShellContext.ExecuteScriptString( public async Task CanUpdateRegisteredCommand() { // Register a command and then update it - await extensionService.PowerShellContext.ExecuteScriptString(TestUtilities.NormalizeNewlines( + await extensionService.PowerShellContext.ExecuteScriptStringAsync(TestUtilities.NormalizeNewlines( "function Invoke-Extension { Write-Output \"Extension output!\" }\n" + "Register-EditorCommand -Name \"test.function\" -DisplayName \"Function extension\" -Function \"Invoke-Extension\"\n" + "Register-EditorCommand -Name \"test.function\" -DisplayName \"Updated Function extension\" -Function \"Invoke-Extension\"")); @@ -128,19 +128,19 @@ await extensionService.PowerShellContext.ExecuteScriptString(TestUtilities.Norma public async Task CanUnregisterCommand() { // Add the command and wait for the add event - await extensionService.PowerShellContext.ExecuteScriptString( + await extensionService.PowerShellContext.ExecuteScriptStringAsync( "Register-EditorCommand -Name \"test.scriptblock\" -DisplayName \"ScriptBlock extension\" -ScriptBlock { Write-Output \"Extension output!\" }"); await this.AssertExtensionEvent(EventType.Add, "test.scriptblock"); // Remove the command and wait for the remove event - await extensionService.PowerShellContext.ExecuteScriptString( + await extensionService.PowerShellContext.ExecuteScriptStringAsync( "Unregister-EditorCommand -Name \"test.scriptblock\""); await this.AssertExtensionEvent(EventType.Remove, "test.scriptblock"); // Ensure that the command has been unregistered await Assert.ThrowsAsync( typeof(KeyNotFoundException), - () => extensionService.InvokeCommand("test.scriptblock", this.commandContext)); + () => extensionService.InvokeCommandAsync("test.scriptblock", this.commandContext)); } private async Task AssertExtensionEvent(EventType expectedEventType, string expectedExtensionName) @@ -187,67 +187,67 @@ public string GetWorkspaceRelativePath(string filePath) throw new NotImplementedException(); } - public Task NewFile() + public Task NewFileAsync() { throw new NotImplementedException(); } - public Task OpenFile(string filePath) + public Task OpenFileAsync(string filePath) { throw new NotImplementedException(); } - public Task OpenFile(string filePath, bool preview) + public Task OpenFileAsync(string filePath, bool preview) { throw new NotImplementedException(); } - public Task CloseFile(string filePath) + public Task CloseFileAsync(string filePath) { throw new NotImplementedException(); } - public Task SaveFile(string filePath) + public Task SaveFileAsync(string filePath) { - return SaveFile(filePath, null); + return SaveFileAsync(filePath, null); } - public Task SaveFile(string filePath, string newSavePath) + public Task SaveFileAsync(string filePath, string newSavePath) { throw new NotImplementedException(); } - public Task InsertText(string filePath, string text, BufferRange insertRange) + public Task InsertTextAsync(string filePath, string text, BufferRange insertRange) { throw new NotImplementedException(); } - public Task SetSelection(BufferRange selectionRange) + public Task SetSelectionAsync(BufferRange selectionRange) { throw new NotImplementedException(); } - public Task GetEditorContext() + public Task GetEditorContextAsync() { throw new NotImplementedException(); } - public Task ShowInformationMessage(string message) + public Task ShowInformationMessageAsync(string message) { throw new NotImplementedException(); } - public Task ShowErrorMessage(string message) + public Task ShowErrorMessageAsync(string message) { throw new NotImplementedException(); } - public Task ShowWarningMessage(string message) + public Task ShowWarningMessageAsync(string message) { throw new NotImplementedException(); } - public Task SetStatusBarMessage(string message, int? timeout) + public Task SetStatusBarMessageAsync(string message, int? timeout) { throw new NotImplementedException(); } diff --git a/test/PowerShellEditorServices.Test/Language/LanguageServiceTests.cs b/test/PowerShellEditorServices.Test/Language/LanguageServiceTests.cs index 1d4972053..656e5153b 100644 --- a/test/PowerShellEditorServices.Test/Language/LanguageServiceTests.cs +++ b/test/PowerShellEditorServices.Test/Language/LanguageServiceTests.cs @@ -283,7 +283,7 @@ await this.GetReferences( public async Task LanguageServiceFindsDetailsForBuiltInCommand() { SymbolDetails symbolDetails = - await this.languageService.FindSymbolDetailsAtLocation( + await this.languageService.FindSymbolDetailsAtLocationAsync( this.GetScriptFile(FindsDetailsForBuiltInCommand.SourceDetails), FindsDetailsForBuiltInCommand.SourceDetails.StartLineNumber, FindsDetailsForBuiltInCommand.SourceDetails.StartColumnNumber); @@ -366,7 +366,7 @@ private async Task GetCompletionResults(ScriptRegion scriptRe { // Run the completions request return - await this.languageService.GetCompletionsInFile( + await this.languageService.GetCompletionsInFileAsync( GetScriptFile(scriptRegion), scriptRegion.StartLineNumber, scriptRegion.StartColumnNumber); @@ -375,7 +375,7 @@ await this.languageService.GetCompletionsInFile( private async Task GetParamSetSignatures(ScriptRegion scriptRegion) { return - await this.languageService.FindParameterSetsInFile( + await this.languageService.FindParameterSetsInFileAsync( GetScriptFile(scriptRegion), scriptRegion.StartLineNumber, scriptRegion.StartColumnNumber); @@ -394,7 +394,7 @@ private async Task GetDefinition(ScriptRegion scriptRegion, Assert.NotNull(symbolReference); return - await this.languageService.GetDefinitionOfSymbol( + await this.languageService.GetDefinitionOfSymbolAsync( scriptFile, symbolReference, workspace); @@ -418,7 +418,7 @@ private async Task GetReferences(ScriptRegion scriptRegion Assert.NotNull(symbolReference); return - await this.languageService.FindReferencesOfSymbol( + await this.languageService.FindReferencesOfSymbolAsync( symbolReference, this.workspace.ExpandScriptReferences(scriptFile), this.workspace); diff --git a/test/PowerShellEditorServices.Test/PowerShellContextFactory.cs b/test/PowerShellEditorServices.Test/PowerShellContextFactory.cs index 22a41d2e9..6b9848251 100644 --- a/test/PowerShellEditorServices.Test/PowerShellContextFactory.cs +++ b/test/PowerShellEditorServices.Test/PowerShellContextFactory.cs @@ -59,7 +59,7 @@ protected override InputPromptHandler OnCreateInputPromptHandler() throw new NotImplementedException(); } - protected override Task ReadCommandLine(CancellationToken cancellationToken) + protected override Task ReadCommandLineAsync(CancellationToken cancellationToken) { return Task.FromResult("USER COMMAND"); } diff --git a/test/PowerShellEditorServices.Test/Session/PowerShellContextTests.cs b/test/PowerShellEditorServices.Test/Session/PowerShellContextTests.cs index dcb0e738a..88776c407 100644 --- a/test/PowerShellEditorServices.Test/Session/PowerShellContextTests.cs +++ b/test/PowerShellEditorServices.Test/Session/PowerShellContextTests.cs @@ -61,7 +61,7 @@ public async Task CanExecutePSCommand() psCommand.AddScript("$a = \"foo\"; $a"); var executeTask = - this.powerShellContext.ExecuteCommand(psCommand); + this.powerShellContext.ExecuteCommandAsync(psCommand); await this.AssertStateChange(PowerShellContextState.Running); await this.AssertStateChange(PowerShellContextState.Ready); @@ -74,14 +74,14 @@ public async Task CanExecutePSCommand() public async Task CanQueueParallelRunspaceRequests() { // Concurrently initiate 4 requests in the session - Task taskOne = this.powerShellContext.ExecuteScriptString("$x = 100"); - Task handleTask = this.powerShellContext.GetRunspaceHandle(); - Task taskTwo = this.powerShellContext.ExecuteScriptString("$x += 200"); - Task taskThree = this.powerShellContext.ExecuteScriptString("$x = $x / 100"); + Task taskOne = this.powerShellContext.ExecuteScriptStringAsync("$x = 100"); + Task handleTask = this.powerShellContext.GetRunspaceHandleAsync(); + Task taskTwo = this.powerShellContext.ExecuteScriptStringAsync("$x += 200"); + Task taskThree = this.powerShellContext.ExecuteScriptStringAsync("$x = $x / 100"); PSCommand psCommand = new PSCommand(); psCommand.AddScript("$x"); - Task> resultTask = this.powerShellContext.ExecuteCommand(psCommand); + Task> resultTask = this.powerShellContext.ExecuteCommandAsync(psCommand); // Wait for the requested runspace handle and then dispose it RunspaceHandle handle = await handleTask; @@ -105,7 +105,7 @@ public async Task CanAbortExecution() Task.Run( async () => { - var unusedTask = this.powerShellContext.ExecuteScriptWithArgs(s_debugTestFilePath); + var unusedTask = this.powerShellContext.ExecuteScriptWithArgsAsync(s_debugTestFilePath); await Task.Delay(50); this.powerShellContext.AbortExecution(); }); @@ -130,7 +130,7 @@ public async Task CanResolveAndLoadProfilesForHostId() }; // Load the profiles for the test host name - await this.powerShellContext.LoadHostProfiles(); + await this.powerShellContext.LoadHostProfilesAsync(); // Ensure that all the paths are set in the correct variables // and that the current user's host profile got loaded @@ -143,7 +143,7 @@ public async Task CanResolveAndLoadProfilesForHostId() "$(Assert-ProfileLoaded)\""); var result = - await this.powerShellContext.ExecuteCommand( + await this.powerShellContext.ExecuteCommandAsync( psCommand); string expectedString = diff --git a/test/PowerShellEditorServices.Test/Utility/AsyncDebouncerTests.cs b/test/PowerShellEditorServices.Test/Utility/AsyncDebouncerTests.cs index 443dc1ba1..9c40a351d 100644 --- a/test/PowerShellEditorServices.Test/Utility/AsyncDebouncerTests.cs +++ b/test/PowerShellEditorServices.Test/Utility/AsyncDebouncerTests.cs @@ -19,15 +19,15 @@ public async Task AsyncDebouncerFlushesAfterInterval() { TestAsyncDebouncer debouncer = new TestAsyncDebouncer(); - await debouncer.Invoke(1); - await debouncer.Invoke(2); - await debouncer.Invoke(3); + await debouncer.InvokeAsync(1); + await debouncer.InvokeAsync(2); + await debouncer.InvokeAsync(3); await Task.Delay(TestAsyncDebouncer.Interval + 100); // Add a few more items to ensure they are added after the initial interval - await debouncer.Invoke(4); - await debouncer.Invoke(5); - await debouncer.Invoke(6); + await debouncer.InvokeAsync(4); + await debouncer.InvokeAsync(5); + await debouncer.InvokeAsync(6); Assert.Equal(new List { 1, 2, 3 }, debouncer.FlushedBuffer); Assert.True( @@ -41,18 +41,18 @@ public async Task AsyncDebouncerFlushesAfterInterval() } [Fact] - public async Task AsyncDebouncerRestartsAfterInvoke() + public async Task AsyncDebouncerRestartsAfterInvokeAsync() { TestAsyncRestartDebouncer debouncer = new TestAsyncRestartDebouncer(); // Invoke the debouncer and wait a bit between each // invoke to make sure the debouncer isn't flushed // until after the last invoke. - await debouncer.Invoke(1); + await debouncer.InvokeAsync(1); await Task.Delay(TestAsyncRestartDebouncer.Interval - 100); - await debouncer.Invoke(2); + await debouncer.InvokeAsync(2); await Task.Delay(TestAsyncRestartDebouncer.Interval - 100); - await debouncer.Invoke(3); + await debouncer.InvokeAsync(3); await Task.Delay(TestAsyncRestartDebouncer.Interval + 100); // The only item flushed should be 3 since its interval has lapsed @@ -77,7 +77,7 @@ public TestAsyncDebouncer() : base(Interval, false) { } - protected override Task OnInvoke(int args) + protected override Task OnInvokeAsync(int args) { if (!this.firstInvoke.HasValue) { @@ -89,7 +89,7 @@ protected override Task OnInvoke(int args) return Task.FromResult(true); } - protected override Task OnFlush() + protected override Task OnFlushAsync() { // Mark the flush time this.TimeToFlush = DateTime.Now - this.firstInvoke.Value; @@ -118,13 +118,13 @@ public TestAsyncRestartDebouncer() : base(Interval, true) { } - protected override Task OnInvoke(int args) + protected override Task OnInvokeAsync(int args) { this.lastInvokeInt = args; return Task.FromResult(true); } - protected override Task OnFlush() + protected override Task OnFlushAsync() { this.FlushedBuffer.Add(this.lastInvokeInt); diff --git a/test/PowerShellEditorServices.Test/Utility/AsyncQueueTests.cs b/test/PowerShellEditorServices.Test/Utility/AsyncQueueTests.cs index fe161c8ca..af67e88f3 100644 --- a/test/PowerShellEditorServices.Test/Utility/AsyncQueueTests.cs +++ b/test/PowerShellEditorServices.Test/Utility/AsyncQueueTests.cs @@ -26,11 +26,11 @@ public async Task AsyncQueueSynchronizesAccess() { // Start 5 consumers await Task.WhenAll( - Task.Run(() => ConsumeItems(inputQueue, outputItems, cancellationTokenSource.Token)), - Task.Run(() => ConsumeItems(inputQueue, outputItems, cancellationTokenSource.Token)), - Task.Run(() => ConsumeItems(inputQueue, outputItems, cancellationTokenSource.Token)), - Task.Run(() => ConsumeItems(inputQueue, outputItems, cancellationTokenSource.Token)), - Task.Run(() => ConsumeItems(inputQueue, outputItems, cancellationTokenSource.Token)), + Task.Run(() => ConsumeItemsAsync(inputQueue, outputItems, cancellationTokenSource.Token)), + Task.Run(() => ConsumeItemsAsync(inputQueue, outputItems, cancellationTokenSource.Token)), + Task.Run(() => ConsumeItemsAsync(inputQueue, outputItems, cancellationTokenSource.Token)), + Task.Run(() => ConsumeItemsAsync(inputQueue, outputItems, cancellationTokenSource.Token)), + Task.Run(() => ConsumeItemsAsync(inputQueue, outputItems, cancellationTokenSource.Token)), Task.Run( async () => { @@ -76,7 +76,7 @@ public async Task AsyncQueueSkipsCancelledTasks() Assert.Equal(1, taskTwo.Result); } - private async Task ConsumeItems( + private async Task ConsumeItemsAsync( AsyncQueue inputQueue, ConcurrentBag outputItems, CancellationToken cancellationToken)