From ea3d0159612ad1e252a69ae41e574219e9b75fd4 Mon Sep 17 00:00:00 2001 From: Karl Burtram Date: Sat, 16 Jul 2016 01:20:56 -0700 Subject: [PATCH 1/6] Dev (#2) * Misc. clean-ups related to removing unneeded PowerShell Language Service code. * Remove unneeded files and clean up remaining code. * Enable file change tracking with Workspace and EditorSession. --- ServiceHost/.vscode/launch.json | 4 +- ServiceHost/Client/DebugAdapterClientBase.cs | 48 - ServiceHost/Client/LanguageClientBase.cs | 44 - ServiceHost/Client/LanguageServiceClient.cs | 121 -- ServiceHost/DebugAdapter/AttachRequest.cs | 23 - ServiceHost/DebugAdapter/Breakpoint.cs | 81 -- .../DebugAdapter/ConfigurationDoneRequest.cs | 16 - ServiceHost/DebugAdapter/ContinueRequest.cs | 17 - ServiceHost/DebugAdapter/DisconnectRequest.cs | 17 - ServiceHost/DebugAdapter/EvaluateRequest.cs | 53 - ServiceHost/DebugAdapter/ExitedEvent.cs | 22 - ServiceHost/DebugAdapter/InitializeRequest.cs | 56 - ServiceHost/DebugAdapter/InitializedEvent.cs | 16 - ServiceHost/DebugAdapter/LaunchRequest.cs | 66 - ServiceHost/DebugAdapter/NextRequest.cs | 20 - ServiceHost/DebugAdapter/OutputEvent.cs | 24 - ServiceHost/DebugAdapter/PauseRequest.cs | 17 - ServiceHost/DebugAdapter/Scope.cs | 40 - ServiceHost/DebugAdapter/ScopesRequest.cs | 29 - .../DebugAdapter/SetBreakpointsRequest.cs | 43 - .../SetExceptionBreakpointsRequest.cs | 31 - .../SetFunctionBreakpointsRequest.cs | 31 - ServiceHost/DebugAdapter/Source.cs | 17 - ServiceHost/DebugAdapter/SourceRequest.cs | 29 - ServiceHost/DebugAdapter/StackFrame.cs | 53 - ServiceHost/DebugAdapter/StackTraceRequest.cs | 33 - ServiceHost/DebugAdapter/StartedEvent.cs | 16 - ServiceHost/DebugAdapter/StepInRequest.cs | 17 - ServiceHost/DebugAdapter/StepOutRequest.cs | 16 - ServiceHost/DebugAdapter/StoppedEvent.cs | 41 - ServiceHost/DebugAdapter/TerminatedEvent.cs | 17 - ServiceHost/DebugAdapter/Thread.cs | 15 - ServiceHost/DebugAdapter/ThreadsRequest.cs | 22 - ServiceHost/DebugAdapter/Variable.cs | 33 - ServiceHost/DebugAdapter/VariablesRequest.cs | 29 - .../LanguageServer/ClientCapabilities.cs | 5 - ServiceHost/LanguageServer/Completion.cs | 1 - ServiceHost/LanguageServer/Diagnostics.cs | 5 - ServiceHost/LanguageServer/EditorCommands.cs | 111 -- ServiceHost/LanguageServer/Hover.cs | 5 - ServiceHost/LanguageServer/TextDocument.cs | 15 + .../Channel/NamedPipeClientChannel.cs | 83 -- .../Channel/NamedPipeServerChannel.cs | 65 - .../Channel/StdioClientChannel.cs | 2 - .../Channel/StdioServerChannel.cs | 2 - .../MessageProtocol/MessageDispatcher.cs | 2 +- .../Serializers/JsonRpcMessageSerializer.cs | 3 - .../Serializers/V8MessageSerializer.cs | 2 - ServiceHost/Messages/PromptEvents.cs | 58 - ServiceHost/Properties/AssemblyInfo.cs | 8 +- ServiceHost/Server/DebugAdapter.cs | 584 -------- ServiceHost/Server/DebugAdapterBase.cs | 73 - ServiceHost/Server/LanguageServer.cs | 1186 ++--------------- ServiceHost/Server/LanguageServerSettings.cs | 2 + ServiceHost/Server/OutputDebouncer.cs | 102 -- ServiceHost/Server/PromptHandlers.cs | 190 --- ServiceHost/Session/EditorSession.cs | 64 +- ServiceHost/Session/SqlToolsContext.cs | 25 + ServiceHost/Utility/AsyncDebouncer.cs | 169 --- ServiceHost/Workspace/ScriptFile.cs | 24 + ServiceHost/Workspace/Workspace.cs | 109 +- 61 files changed, 275 insertions(+), 3777 deletions(-) delete mode 100644 ServiceHost/Client/DebugAdapterClientBase.cs delete mode 100644 ServiceHost/Client/LanguageClientBase.cs delete mode 100644 ServiceHost/Client/LanguageServiceClient.cs delete mode 100644 ServiceHost/DebugAdapter/AttachRequest.cs delete mode 100644 ServiceHost/DebugAdapter/Breakpoint.cs delete mode 100644 ServiceHost/DebugAdapter/ConfigurationDoneRequest.cs delete mode 100644 ServiceHost/DebugAdapter/ContinueRequest.cs delete mode 100644 ServiceHost/DebugAdapter/DisconnectRequest.cs delete mode 100644 ServiceHost/DebugAdapter/EvaluateRequest.cs delete mode 100644 ServiceHost/DebugAdapter/ExitedEvent.cs delete mode 100644 ServiceHost/DebugAdapter/InitializeRequest.cs delete mode 100644 ServiceHost/DebugAdapter/InitializedEvent.cs delete mode 100644 ServiceHost/DebugAdapter/LaunchRequest.cs delete mode 100644 ServiceHost/DebugAdapter/NextRequest.cs delete mode 100644 ServiceHost/DebugAdapter/OutputEvent.cs delete mode 100644 ServiceHost/DebugAdapter/PauseRequest.cs delete mode 100644 ServiceHost/DebugAdapter/Scope.cs delete mode 100644 ServiceHost/DebugAdapter/ScopesRequest.cs delete mode 100644 ServiceHost/DebugAdapter/SetBreakpointsRequest.cs delete mode 100644 ServiceHost/DebugAdapter/SetExceptionBreakpointsRequest.cs delete mode 100644 ServiceHost/DebugAdapter/SetFunctionBreakpointsRequest.cs delete mode 100644 ServiceHost/DebugAdapter/Source.cs delete mode 100644 ServiceHost/DebugAdapter/SourceRequest.cs delete mode 100644 ServiceHost/DebugAdapter/StackFrame.cs delete mode 100644 ServiceHost/DebugAdapter/StackTraceRequest.cs delete mode 100644 ServiceHost/DebugAdapter/StartedEvent.cs delete mode 100644 ServiceHost/DebugAdapter/StepInRequest.cs delete mode 100644 ServiceHost/DebugAdapter/StepOutRequest.cs delete mode 100644 ServiceHost/DebugAdapter/StoppedEvent.cs delete mode 100644 ServiceHost/DebugAdapter/TerminatedEvent.cs delete mode 100644 ServiceHost/DebugAdapter/Thread.cs delete mode 100644 ServiceHost/DebugAdapter/ThreadsRequest.cs delete mode 100644 ServiceHost/DebugAdapter/Variable.cs delete mode 100644 ServiceHost/DebugAdapter/VariablesRequest.cs delete mode 100644 ServiceHost/LanguageServer/EditorCommands.cs delete mode 100644 ServiceHost/MessageProtocol/Channel/NamedPipeClientChannel.cs delete mode 100644 ServiceHost/MessageProtocol/Channel/NamedPipeServerChannel.cs delete mode 100644 ServiceHost/Messages/PromptEvents.cs delete mode 100644 ServiceHost/Server/DebugAdapter.cs delete mode 100644 ServiceHost/Server/DebugAdapterBase.cs delete mode 100644 ServiceHost/Server/OutputDebouncer.cs delete mode 100644 ServiceHost/Server/PromptHandlers.cs create mode 100644 ServiceHost/Session/SqlToolsContext.cs delete mode 100644 ServiceHost/Utility/AsyncDebouncer.cs diff --git a/ServiceHost/.vscode/launch.json b/ServiceHost/.vscode/launch.json index 51cdc900..18ebbb27 100644 --- a/ServiceHost/.vscode/launch.json +++ b/ServiceHost/.vscode/launch.json @@ -10,13 +10,15 @@ "args": [], "cwd": "${workspaceRoot}", "externalConsole": true, + "requireExactSource": false, "stopAtEntry": false }, { "name": ".NET Core Attach", "type": "coreclr", "request": "attach", - "processId": 16900 + "requireExactSource": false, + "processId": 17264 } ] } \ No newline at end of file diff --git a/ServiceHost/Client/DebugAdapterClientBase.cs b/ServiceHost/Client/DebugAdapterClientBase.cs deleted file mode 100644 index e2949307..00000000 --- a/ServiceHost/Client/DebugAdapterClientBase.cs +++ /dev/null @@ -1,48 +0,0 @@ -// -// Copyright (c) Microsoft. All rights reserved. -// Licensed under the MIT license. See LICENSE file in the project root for full license information. -// - -using Microsoft.SqlTools.EditorServices.Protocol.DebugAdapter; -using Microsoft.SqlTools.EditorServices.Protocol.MessageProtocol; -using Microsoft.SqlTools.EditorServices.Protocol.MessageProtocol.Channel; -using System.Threading.Tasks; - -namespace Microsoft.SqlTools.EditorServices.Protocol.Client -{ - public class DebugAdapterClient : ProtocolEndpoint - { - public DebugAdapterClient(ChannelBase clientChannel) - : base(clientChannel, MessageProtocolType.DebugAdapter) - { - } - - public async Task LaunchScript(string scriptFilePath) - { - await this.SendRequest( - LaunchRequest.Type, - new LaunchRequestArguments { - Program = scriptFilePath - }); - - await this.SendRequest(ConfigurationDoneRequest.Type, null); - } - - protected override Task OnStart() - { - return Task.FromResult(true); - } - - protected override Task OnConnect() - { - // Initialize the debug adapter - return this.SendRequest( - InitializeRequest.Type, - new InitializeRequestArguments - { - LinesStartAt1 = true - }); - } - } -} - diff --git a/ServiceHost/Client/LanguageClientBase.cs b/ServiceHost/Client/LanguageClientBase.cs deleted file mode 100644 index 22522252..00000000 --- a/ServiceHost/Client/LanguageClientBase.cs +++ /dev/null @@ -1,44 +0,0 @@ -// -// Copyright (c) Microsoft. All rights reserved. -// Licensed under the MIT license. See LICENSE file in the project root for full license information. -// - -using Microsoft.SqlTools.EditorServices.Protocol.LanguageServer; -using Microsoft.SqlTools.EditorServices.Protocol.MessageProtocol; -using Microsoft.SqlTools.EditorServices.Protocol.MessageProtocol.Channel; -using System.Threading.Tasks; - -namespace Microsoft.SqlTools.EditorServices.Protocol.Client -{ - /// - /// Provides a base implementation for language server clients. - /// - public abstract class LanguageClientBase : ProtocolEndpoint - { - /// - /// Initializes an instance of the language client using the - /// specified channel for communication. - /// - /// The channel to use for communication with the server. - public LanguageClientBase(ChannelBase clientChannel) - : base(clientChannel, MessageProtocolType.LanguageServer) - { - } - - protected override Task OnStart() - { - // Initialize the implementation class - return this.Initialize(); - } - - protected override async Task OnStop() - { - // First, notify the language server that we're stopping - var response = await this.SendRequest(ShutdownRequest.Type, new object()); - await this.SendEvent(ExitNotification.Type, new object()); - } - - protected abstract Task Initialize(); - } -} - diff --git a/ServiceHost/Client/LanguageServiceClient.cs b/ServiceHost/Client/LanguageServiceClient.cs deleted file mode 100644 index 7ec5fba0..00000000 --- a/ServiceHost/Client/LanguageServiceClient.cs +++ /dev/null @@ -1,121 +0,0 @@ -// -// Copyright (c) Microsoft. All rights reserved. -// Licensed under the MIT license. See LICENSE file in the project root for full license information. -// - -using Microsoft.SqlTools.EditorServices.Protocol.LanguageServer; -using Microsoft.SqlTools.EditorServices.Protocol.MessageProtocol; -using Microsoft.SqlTools.EditorServices.Protocol.MessageProtocol.Channel; -using System; -using System.Collections.Generic; -using System.Linq; -using System.Threading.Tasks; - -namespace Microsoft.SqlTools.EditorServices.Protocol.Client -{ - public class LanguageServiceClient : LanguageClientBase - { - private Dictionary cachedDiagnostics = - new Dictionary(); - - public LanguageServiceClient(ChannelBase clientChannel) - : base(clientChannel) - { - } - - protected override Task Initialize() - { - // Add handlers for common events - this.SetEventHandler(PublishDiagnosticsNotification.Type, HandlePublishDiagnosticsEvent); - - return Task.FromResult(true); - } - - protected override Task OnConnect() - { - // Send the 'initialize' request and wait for the response - var initializeRequest = new InitializeRequest - { - RootPath = "", - Capabilities = new ClientCapabilities() - }; - - return this.SendRequest( - InitializeRequest.Type, - initializeRequest); - } - - #region Events - - public event EventHandler DiagnosticsReceived; - - protected void OnDiagnosticsReceived(string filePath) - { - if (this.DiagnosticsReceived != null) - { - this.DiagnosticsReceived(this, filePath); - } - } - - #endregion - - #region Private Methods - - private Task HandlePublishDiagnosticsEvent( - PublishDiagnosticsNotification diagnostics, - EventContext eventContext) - { - string normalizedPath = diagnostics.Uri.ToLower(); - - this.cachedDiagnostics[normalizedPath] = - diagnostics.Diagnostics - .Select(GetMarkerFromDiagnostic) - .ToArray(); - - this.OnDiagnosticsReceived(normalizedPath); - - return Task.FromResult(true); - } - - private static ScriptFileMarker GetMarkerFromDiagnostic(Diagnostic diagnostic) - { - DiagnosticSeverity severity = - diagnostic.Severity.GetValueOrDefault( - DiagnosticSeverity.Error); - - return new ScriptFileMarker - { - Level = MapDiagnosticSeverityToLevel(severity), - Message = diagnostic.Message, - ScriptRegion = new ScriptRegion - { - StartLineNumber = diagnostic.Range.Start.Line + 1, - StartColumnNumber = diagnostic.Range.Start.Character + 1, - EndLineNumber = diagnostic.Range.End.Line + 1, - EndColumnNumber = diagnostic.Range.End.Character + 1 - } - }; - } - - private static ScriptFileMarkerLevel MapDiagnosticSeverityToLevel(DiagnosticSeverity severity) - { - switch (severity) - { - case DiagnosticSeverity.Hint: - case DiagnosticSeverity.Information: - return ScriptFileMarkerLevel.Information; - - case DiagnosticSeverity.Warning: - return ScriptFileMarkerLevel.Warning; - - case DiagnosticSeverity.Error: - return ScriptFileMarkerLevel.Error; - - default: - return ScriptFileMarkerLevel.Error; - } - } - - #endregion - } -} diff --git a/ServiceHost/DebugAdapter/AttachRequest.cs b/ServiceHost/DebugAdapter/AttachRequest.cs deleted file mode 100644 index 49fdc5b2..00000000 --- a/ServiceHost/DebugAdapter/AttachRequest.cs +++ /dev/null @@ -1,23 +0,0 @@ -// -// Copyright (c) Microsoft. All rights reserved. -// Licensed under the MIT license. See LICENSE file in the project root for full license information. -// - -using Microsoft.SqlTools.EditorServices.Protocol.MessageProtocol; - -namespace Microsoft.SqlTools.EditorServices.Protocol.DebugAdapter -{ - public class AttachRequest - { - public static readonly - RequestType Type = - RequestType.Create("attach"); - } - - public class AttachRequestArguments - { - public string Address { get; set; } - - public int Port { get; set; } - } -} diff --git a/ServiceHost/DebugAdapter/Breakpoint.cs b/ServiceHost/DebugAdapter/Breakpoint.cs deleted file mode 100644 index 14de1790..00000000 --- a/ServiceHost/DebugAdapter/Breakpoint.cs +++ /dev/null @@ -1,81 +0,0 @@ -// -// Copyright (c) Microsoft. All rights reserved. -// Licensed under the MIT license. See LICENSE file in the project root for full license information. -// - -using Microsoft.SqlTools.EditorServices.Utility; - -namespace Microsoft.SqlTools.EditorServices.Protocol.DebugAdapter -{ - public class Breakpoint - { - /// - /// Gets an boolean indicator that if true, breakpoint could be set - /// (but not necessarily at the desired location). - /// - public bool Verified { get; set; } - - /// - /// Gets an optional message about the state of the breakpoint. This is shown to the user - /// and can be used to explain why a breakpoint could not be verified. - /// - public string Message { get; set; } - - public string Source { get; set; } - - public int? Line { get; set; } - - public int? Column { get; set; } - - private Breakpoint() - { - } - -#if false - public static Breakpoint Create( - BreakpointDetails breakpointDetails) - { - //Validate.IsNotNull(nameof(breakpointDetails), breakpointDetails); - - return new Breakpoint - { - Verified = breakpointDetails.Verified, - Message = breakpointDetails.Message, - Source = breakpointDetails.Source, - Line = breakpointDetails.LineNumber, - Column = breakpointDetails.ColumnNumber - }; - } - - public static Breakpoint Create( - CommandBreakpointDetails breakpointDetails) - { - //Validate.IsNotNull(nameof(breakpointDetails), breakpointDetails); - - return new Breakpoint { - Verified = breakpointDetails.Verified, - Message = breakpointDetails.Message - }; - } -#endif - - public static Breakpoint Create( - SourceBreakpoint sourceBreakpoint, - string source, - string message, - bool verified = false) - { - Validate.IsNotNull(nameof(sourceBreakpoint), sourceBreakpoint); - Validate.IsNotNull(nameof(source), source); - Validate.IsNotNull(nameof(message), message); - - return new Breakpoint { - Verified = verified, - Message = message, - Source = source, - Line = sourceBreakpoint.Line, - Column = sourceBreakpoint.Column - }; - } - } -} diff --git a/ServiceHost/DebugAdapter/ConfigurationDoneRequest.cs b/ServiceHost/DebugAdapter/ConfigurationDoneRequest.cs deleted file mode 100644 index 2fc2203f..00000000 --- a/ServiceHost/DebugAdapter/ConfigurationDoneRequest.cs +++ /dev/null @@ -1,16 +0,0 @@ -// -// Copyright (c) Microsoft. All rights reserved. -// Licensed under the MIT license. See LICENSE file in the project root for full license information. -// - -using Microsoft.SqlTools.EditorServices.Protocol.MessageProtocol; - -namespace Microsoft.SqlTools.EditorServices.Protocol.DebugAdapter -{ - public class ConfigurationDoneRequest - { - public static readonly - RequestType Type = - RequestType.Create("configurationDone"); - } -} diff --git a/ServiceHost/DebugAdapter/ContinueRequest.cs b/ServiceHost/DebugAdapter/ContinueRequest.cs deleted file mode 100644 index c78dd0c3..00000000 --- a/ServiceHost/DebugAdapter/ContinueRequest.cs +++ /dev/null @@ -1,17 +0,0 @@ -// -// Copyright (c) Microsoft. All rights reserved. -// Licensed under the MIT license. See LICENSE file in the project root for full license information. -// - -using Microsoft.SqlTools.EditorServices.Protocol.MessageProtocol; - -namespace Microsoft.SqlTools.EditorServices.Protocol.DebugAdapter -{ - public class ContinueRequest - { - public static readonly - RequestType Type = - RequestType.Create("continue"); - } -} - diff --git a/ServiceHost/DebugAdapter/DisconnectRequest.cs b/ServiceHost/DebugAdapter/DisconnectRequest.cs deleted file mode 100644 index 43a25908..00000000 --- a/ServiceHost/DebugAdapter/DisconnectRequest.cs +++ /dev/null @@ -1,17 +0,0 @@ -// -// Copyright (c) Microsoft. All rights reserved. -// Licensed under the MIT license. See LICENSE file in the project root for full license information. -// - -using Microsoft.SqlTools.EditorServices.Protocol.MessageProtocol; - -namespace Microsoft.SqlTools.EditorServices.Protocol.DebugAdapter -{ - public class DisconnectRequest - { - public static readonly - RequestType Type = - RequestType.Create("disconnect"); - } -} - diff --git a/ServiceHost/DebugAdapter/EvaluateRequest.cs b/ServiceHost/DebugAdapter/EvaluateRequest.cs deleted file mode 100644 index 627a3c65..00000000 --- a/ServiceHost/DebugAdapter/EvaluateRequest.cs +++ /dev/null @@ -1,53 +0,0 @@ -// -// Copyright (c) Microsoft. All rights reserved. -// Licensed under the MIT license. See LICENSE file in the project root for full license information. -// - -using Microsoft.SqlTools.EditorServices.Protocol.MessageProtocol; - -namespace Microsoft.SqlTools.EditorServices.Protocol.DebugAdapter -{ - public class EvaluateRequest - { - public static readonly - RequestType Type = - RequestType.Create("evaluate"); - } - - public class EvaluateRequestArguments - { - /// - /// The expression to evaluate. - /// - public string Expression { get; set; } - - /// - /// The context in which the evaluate request is run. Possible - /// values are 'watch' if evaluate is run in a watch or 'repl' - /// if run from the REPL console. - /// - public string Context { get; set; } - - /// - /// Evaluate the expression in the context of this stack frame. - /// If not specified, the top most frame is used. - /// - public int FrameId { get; set; } - } - - public class EvaluateResponseBody - { - /// - /// The evaluation result. - /// - public string Result { get; set; } - - /// - /// If variablesReference is > 0, the evaluate result is - /// structured and its children can be retrieved by passing - /// variablesReference to the VariablesRequest - /// - public int VariablesReference { get; set; } - } -} - diff --git a/ServiceHost/DebugAdapter/ExitedEvent.cs b/ServiceHost/DebugAdapter/ExitedEvent.cs deleted file mode 100644 index 5f35dbf5..00000000 --- a/ServiceHost/DebugAdapter/ExitedEvent.cs +++ /dev/null @@ -1,22 +0,0 @@ -// -// Copyright (c) Microsoft. All rights reserved. -// Licensed under the MIT license. See LICENSE file in the project root for full license information. -// - -using Microsoft.SqlTools.EditorServices.Protocol.MessageProtocol; - -namespace Microsoft.SqlTools.EditorServices.Protocol.DebugAdapter -{ - public class ExitedEvent - { - public static readonly - EventType Type = - EventType.Create("exited"); - } - - public class ExitedEventBody - { - public int ExitCode { get; set; } - } -} - diff --git a/ServiceHost/DebugAdapter/InitializeRequest.cs b/ServiceHost/DebugAdapter/InitializeRequest.cs deleted file mode 100644 index d85de828..00000000 --- a/ServiceHost/DebugAdapter/InitializeRequest.cs +++ /dev/null @@ -1,56 +0,0 @@ -// -// Copyright (c) Microsoft. All rights reserved. -// Licensed under the MIT license. See LICENSE file in the project root for full license information. -// - -using Microsoft.SqlTools.EditorServices.Protocol.MessageProtocol; - -namespace Microsoft.SqlTools.EditorServices.Protocol.DebugAdapter -{ - public class InitializeRequest - { - public static readonly - RequestType Type = - RequestType.Create("initialize"); - } - - public class InitializeRequestArguments - { - public string AdapterId { get; set; } - - public bool LinesStartAt1 { get; set; } - - public string PathFormat { get; set; } - - public bool SourceMaps { get; set; } - - public string GeneratedCodeDirectory { get; set; } - } - - public class InitializeResponseBody - { - /// - /// Gets or sets a boolean value that determines whether the debug adapter - /// supports the configurationDoneRequest. - /// - public bool SupportsConfigurationDoneRequest { get; set; } - - /// - /// Gets or sets a boolean value that determines whether the debug adapter - /// supports functionBreakpoints. - /// - public bool SupportsFunctionBreakpoints { get; set; } - - /// - /// Gets or sets a boolean value that determines whether the debug adapter - /// supports conditionalBreakpoints. - /// - public bool SupportsConditionalBreakpoints { get; set; } - - /// - /// Gets or sets a boolean value that determines whether the debug adapter - /// supports a (side effect free) evaluate request for data hovers. - /// - public bool SupportsEvaluateForHovers { get; set; } - } -} diff --git a/ServiceHost/DebugAdapter/InitializedEvent.cs b/ServiceHost/DebugAdapter/InitializedEvent.cs deleted file mode 100644 index 2025ab07..00000000 --- a/ServiceHost/DebugAdapter/InitializedEvent.cs +++ /dev/null @@ -1,16 +0,0 @@ -// -// Copyright (c) Microsoft. All rights reserved. -// Licensed under the MIT license. See LICENSE file in the project root for full license information. -// - -using Microsoft.SqlTools.EditorServices.Protocol.MessageProtocol; - -namespace Microsoft.SqlTools.EditorServices.Protocol.DebugAdapter -{ - public class InitializedEvent - { - public static readonly - EventType Type = - EventType.Create("initialized"); - } -} diff --git a/ServiceHost/DebugAdapter/LaunchRequest.cs b/ServiceHost/DebugAdapter/LaunchRequest.cs deleted file mode 100644 index 0f1f3c55..00000000 --- a/ServiceHost/DebugAdapter/LaunchRequest.cs +++ /dev/null @@ -1,66 +0,0 @@ -// -// Copyright (c) Microsoft. All rights reserved. -// Licensed under the MIT license. See LICENSE file in the project root for full license information. -// - -using System.Collections.Generic; -using Microsoft.SqlTools.EditorServices.Protocol.MessageProtocol; - -namespace Microsoft.SqlTools.EditorServices.Protocol.DebugAdapter -{ - public class LaunchRequest - { - public static readonly - RequestType Type = - RequestType.Create("launch"); - } - - public class LaunchRequestArguments - { - /// - /// Gets or sets the absolute path to the program to debug. - /// - public string Program { get; set; } - - /// - /// Gets or sets a boolean value that indicates whether the script should be - /// run with (false) or without (true) debugging support. - /// - public bool NoDebug { get; set; } - - /// - /// Gets or sets a boolean value that determines whether to automatically stop - /// target after launch. If not specified, target does not stop. - /// - public bool StopOnEntry { get; set; } - - /// - /// Gets or sets optional arguments passed to the debuggee. - /// - public string[] Args { get; set; } - - /// - /// Gets or sets the working directory of the launched debuggee (specified as an absolute path). - /// If omitted the debuggee is lauched in its own directory. - /// - public string Cwd { get; set; } - - /// - /// Gets or sets the absolute path to the runtime executable to be used. - /// Default is the runtime executable on the PATH. - /// - public string RuntimeExecutable { get; set; } - - /// - /// Gets or sets the optional arguments passed to the runtime executable. - /// - public string[] RuntimeArgs { get; set; } - - /// - /// Gets or sets optional environment variables to pass to the debuggee. The string valued - /// properties of the 'environmentVariables' are used as key/value pairs. - /// - public Dictionary Env { get; set; } - } -} - diff --git a/ServiceHost/DebugAdapter/NextRequest.cs b/ServiceHost/DebugAdapter/NextRequest.cs deleted file mode 100644 index 8d41b539..00000000 --- a/ServiceHost/DebugAdapter/NextRequest.cs +++ /dev/null @@ -1,20 +0,0 @@ -// -// Copyright (c) Microsoft. All rights reserved. -// Licensed under the MIT license. See LICENSE file in the project root for full license information. -// - -using Microsoft.SqlTools.EditorServices.Protocol.MessageProtocol; - -namespace Microsoft.SqlTools.EditorServices.Protocol.DebugAdapter -{ - // /** StepOver request; value of command field is "next". - // he request starts the debuggee to run again for one step. - // penDebug will respond with a StoppedEvent (event type 'step') after running the step. - public class NextRequest - { - public static readonly - RequestType Type = - RequestType.Create("next"); - } -} - diff --git a/ServiceHost/DebugAdapter/OutputEvent.cs b/ServiceHost/DebugAdapter/OutputEvent.cs deleted file mode 100644 index ffc92491..00000000 --- a/ServiceHost/DebugAdapter/OutputEvent.cs +++ /dev/null @@ -1,24 +0,0 @@ -// -// Copyright (c) Microsoft. All rights reserved. -// Licensed under the MIT license. See LICENSE file in the project root for full license information. -// - -using Microsoft.SqlTools.EditorServices.Protocol.MessageProtocol; - -namespace Microsoft.SqlTools.EditorServices.Protocol.DebugAdapter -{ - public class OutputEvent - { - public static readonly - EventType Type = - EventType.Create("output"); - } - - public class OutputEventBody - { - public string Category { get; set; } - - public string Output { get; set; } - } -} - diff --git a/ServiceHost/DebugAdapter/PauseRequest.cs b/ServiceHost/DebugAdapter/PauseRequest.cs deleted file mode 100644 index d99ec234..00000000 --- a/ServiceHost/DebugAdapter/PauseRequest.cs +++ /dev/null @@ -1,17 +0,0 @@ -// -// Copyright (c) Microsoft. All rights reserved. -// Licensed under the MIT license. See LICENSE file in the project root for full license information. -// - -using Microsoft.SqlTools.EditorServices.Protocol.MessageProtocol; - -namespace Microsoft.SqlTools.EditorServices.Protocol.DebugAdapter -{ - public class PauseRequest - { - public static readonly - RequestType Type = - RequestType.Create("pause"); - } -} - diff --git a/ServiceHost/DebugAdapter/Scope.cs b/ServiceHost/DebugAdapter/Scope.cs deleted file mode 100644 index a5235ece..00000000 --- a/ServiceHost/DebugAdapter/Scope.cs +++ /dev/null @@ -1,40 +0,0 @@ -// -// Copyright (c) Microsoft. All rights reserved. -// Licensed under the MIT license. See LICENSE file in the project root for full license information. -// - -namespace Microsoft.SqlTools.EditorServices.Protocol.DebugAdapter -{ - public class Scope - { - /// - /// Gets or sets the name of the scope (as such 'Arguments', 'Locals') - /// - public string Name { get; set; } - - /// - /// Gets or sets the variables of this scope can be retrieved by passing the - /// value of variablesReference to the VariablesRequest. - /// - public int VariablesReference { get; set; } - - /// - /// Gets or sets a boolean value indicating if number of variables in - /// this scope is large or expensive to retrieve. - /// - public bool Expensive { get; set; } - -#if false - public static Scope Create(VariableScope scope) - { - return new Scope { - Name = scope.Name, - VariablesReference = scope.Id, - // Temporary fix for #95 to get debug hover tips to work well at least for the local scope. - Expensive = (scope.Name != VariableContainerDetails.LocalScopeName) - }; - } -#endif - } -} - diff --git a/ServiceHost/DebugAdapter/ScopesRequest.cs b/ServiceHost/DebugAdapter/ScopesRequest.cs deleted file mode 100644 index 691f2eb5..00000000 --- a/ServiceHost/DebugAdapter/ScopesRequest.cs +++ /dev/null @@ -1,29 +0,0 @@ -// -// Copyright (c) Microsoft. All rights reserved. -// Licensed under the MIT license. See LICENSE file in the project root for full license information. -// - -using System.Diagnostics; -using Microsoft.SqlTools.EditorServices.Protocol.MessageProtocol; - -namespace Microsoft.SqlTools.EditorServices.Protocol.DebugAdapter -{ - public class ScopesRequest - { - public static readonly - RequestType Type = - RequestType.Create("scopes"); - } - - [DebuggerDisplay("FrameId = {FrameId}")] - public class ScopesRequestArguments - { - public int FrameId { get; set; } - } - - public class ScopesResponseBody - { - public Scope[] Scopes { get; set; } - } -} - diff --git a/ServiceHost/DebugAdapter/SetBreakpointsRequest.cs b/ServiceHost/DebugAdapter/SetBreakpointsRequest.cs deleted file mode 100644 index f8f3d416..00000000 --- a/ServiceHost/DebugAdapter/SetBreakpointsRequest.cs +++ /dev/null @@ -1,43 +0,0 @@ -// -// Copyright (c) Microsoft. All rights reserved. -// Licensed under the MIT license. See LICENSE file in the project root for full license information. -// - -using Microsoft.SqlTools.EditorServices.Protocol.MessageProtocol; - -namespace Microsoft.SqlTools.EditorServices.Protocol.DebugAdapter -{ - /// - /// SetBreakpoints request; value of command field is "setBreakpoints". - /// Sets multiple breakpoints for a single source and clears all previous breakpoints in that source. - /// To clear all breakpoint for a source, specify an empty array. - /// When a breakpoint is hit, a StoppedEvent (event type 'breakpoint') is generated. - /// - public class SetBreakpointsRequest - { - public static readonly - RequestType Type = - RequestType.Create("setBreakpoints"); - } - - public class SetBreakpointsRequestArguments - { - public Source Source { get; set; } - - public SourceBreakpoint[] Breakpoints { get; set; } - } - - public class SourceBreakpoint - { - public int Line { get; set; } - - public int? Column { get; set; } - - public string Condition { get; set; } - } - - public class SetBreakpointsResponseBody - { - public Breakpoint[] Breakpoints { get; set; } - } -} diff --git a/ServiceHost/DebugAdapter/SetExceptionBreakpointsRequest.cs b/ServiceHost/DebugAdapter/SetExceptionBreakpointsRequest.cs deleted file mode 100644 index 1ced918a..00000000 --- a/ServiceHost/DebugAdapter/SetExceptionBreakpointsRequest.cs +++ /dev/null @@ -1,31 +0,0 @@ -// -// Copyright (c) Microsoft. All rights reserved. -// Licensed under the MIT license. See LICENSE file in the project root for full license information. -// - -using Microsoft.SqlTools.EditorServices.Protocol.MessageProtocol; - -namespace Microsoft.SqlTools.EditorServices.Protocol.DebugAdapter -{ - /// - /// SetExceptionBreakpoints request; value of command field is "setExceptionBreakpoints". - /// Enable that the debuggee stops on exceptions with a StoppedEvent (event type 'exception'). - /// - public class SetExceptionBreakpointsRequest - { - public static readonly - RequestType Type = - RequestType.Create("setExceptionBreakpoints"); - } - - /// - /// Arguments for "setExceptionBreakpoints" request. - /// - public class SetExceptionBreakpointsRequestArguments - { - /// - /// Gets or sets the names of enabled exception breakpoints. - /// - public string[] Filters { get; set; } - } -} diff --git a/ServiceHost/DebugAdapter/SetFunctionBreakpointsRequest.cs b/ServiceHost/DebugAdapter/SetFunctionBreakpointsRequest.cs deleted file mode 100644 index e274fcd1..00000000 --- a/ServiceHost/DebugAdapter/SetFunctionBreakpointsRequest.cs +++ /dev/null @@ -1,31 +0,0 @@ -// -// Copyright (c) Microsoft. All rights reserved. -// Licensed under the MIT license. See LICENSE file in the project root for full license information. -// - -using Microsoft.SqlTools.EditorServices.Protocol.MessageProtocol; - -namespace Microsoft.SqlTools.EditorServices.Protocol.DebugAdapter -{ - public class SetFunctionBreakpointsRequest - { - public static readonly - RequestType Type = - RequestType.Create("setFunctionBreakpoints"); - } - - public class SetFunctionBreakpointsRequestArguments - { - public FunctionBreakpoint[] Breakpoints { get; set; } - } - - public class FunctionBreakpoint - { - /// - /// Gets or sets the name of the function to break on when it is invoked. - /// - public string Name { get; set; } - - public string Condition { get; set; } - } -} diff --git a/ServiceHost/DebugAdapter/Source.cs b/ServiceHost/DebugAdapter/Source.cs deleted file mode 100644 index e36b659d..00000000 --- a/ServiceHost/DebugAdapter/Source.cs +++ /dev/null @@ -1,17 +0,0 @@ -// -// Copyright (c) Microsoft. All rights reserved. -// Licensed under the MIT license. See LICENSE file in the project root for full license information. -// - -namespace Microsoft.SqlTools.EditorServices.Protocol.DebugAdapter -{ - public class Source - { - public string Name { get; set; } - - public string Path { get; set; } - - public int? SourceReference { get; set; } - } -} - diff --git a/ServiceHost/DebugAdapter/SourceRequest.cs b/ServiceHost/DebugAdapter/SourceRequest.cs deleted file mode 100644 index f627aefc..00000000 --- a/ServiceHost/DebugAdapter/SourceRequest.cs +++ /dev/null @@ -1,29 +0,0 @@ -// -// Copyright (c) Microsoft. All rights reserved. -// Licensed under the MIT license. See LICENSE file in the project root for full license information. -// - -using Microsoft.SqlTools.EditorServices.Protocol.MessageProtocol; - -namespace Microsoft.SqlTools.EditorServices.Protocol.DebugAdapter -{ - public class SourceRequest - { - public static readonly - RequestType Type = - RequestType.Create("source"); - } - - public class SourceRequestArguments - { - /// - /// Gets or sets the reference to the source. This is the value received in Source.reference. - /// - public int SourceReference { get; set; } - } - - public class SourceResponseBody - { - public string Content { get; set; } - } -} diff --git a/ServiceHost/DebugAdapter/StackFrame.cs b/ServiceHost/DebugAdapter/StackFrame.cs deleted file mode 100644 index 90e6c243..00000000 --- a/ServiceHost/DebugAdapter/StackFrame.cs +++ /dev/null @@ -1,53 +0,0 @@ -// -// Copyright (c) Microsoft. All rights reserved. -// Licensed under the MIT license. See LICENSE file in the project root for full license information. -// - -namespace Microsoft.SqlTools.EditorServices.Protocol.DebugAdapter -{ - public class StackFrame - { - public int Id { get; set; } - - public string Name { get; set; } - - public Source Source { get; set; } - - public int Line { get; set; } - - public int Column { get; set; } - - // /** An identifier for the stack frame. */ - //id: number; - ///** The name of the stack frame, typically a method name */ - //name: string; - ///** The source of the frame. */ - //source: Source; - ///** The line within the file of the frame. */ - //line: number; - ///** The column within the line. */ - //column: number; - ///** All arguments and variables declared in this stackframe. */ - //scopes: Scope[]; - -#if false - public static StackFrame Create( - StackFrameDetails stackFrame, - int id) - { - return new StackFrame - { - Id = id, - Name = stackFrame.FunctionName, - Line = stackFrame.LineNumber, - Column = stackFrame.ColumnNumber, - Source = new Source - { - Path = stackFrame.ScriptPath - } - }; - } -#endif - } -} - diff --git a/ServiceHost/DebugAdapter/StackTraceRequest.cs b/ServiceHost/DebugAdapter/StackTraceRequest.cs deleted file mode 100644 index cd0301c7..00000000 --- a/ServiceHost/DebugAdapter/StackTraceRequest.cs +++ /dev/null @@ -1,33 +0,0 @@ -// -// Copyright (c) Microsoft. All rights reserved. -// Licensed under the MIT license. See LICENSE file in the project root for full license information. -// - -using System.Diagnostics; -using Microsoft.SqlTools.EditorServices.Protocol.MessageProtocol; - -namespace Microsoft.SqlTools.EditorServices.Protocol.DebugAdapter -{ - public class StackTraceRequest - { - public static readonly - RequestType Type = - RequestType.Create("stackTrace"); - } - - [DebuggerDisplay("ThreadId = {ThreadId}, Levels = {Levels}")] - public class StackTraceRequestArguments - { - public int ThreadId { get; private set; } - - /// - /// Gets the maximum number of frames to return. If levels is not specified or 0, all frames are returned. - /// - public int Levels { get; private set; } - } - - public class StackTraceResponseBody - { - public StackFrame[] StackFrames { get; set; } - } -} diff --git a/ServiceHost/DebugAdapter/StartedEvent.cs b/ServiceHost/DebugAdapter/StartedEvent.cs deleted file mode 100644 index 9ecfd6a0..00000000 --- a/ServiceHost/DebugAdapter/StartedEvent.cs +++ /dev/null @@ -1,16 +0,0 @@ -// -// Copyright (c) Microsoft. All rights reserved. -// Licensed under the MIT license. See LICENSE file in the project root for full license information. -// - -using Microsoft.SqlTools.EditorServices.Protocol.MessageProtocol; - -namespace Microsoft.SqlTools.EditorServices.Protocol.DebugAdapter -{ - public class StartedEvent - { - public static readonly - EventType Type = - EventType.Create("started"); - } -} diff --git a/ServiceHost/DebugAdapter/StepInRequest.cs b/ServiceHost/DebugAdapter/StepInRequest.cs deleted file mode 100644 index 42d935fb..00000000 --- a/ServiceHost/DebugAdapter/StepInRequest.cs +++ /dev/null @@ -1,17 +0,0 @@ -// -// Copyright (c) Microsoft. All rights reserved. -// Licensed under the MIT license. See LICENSE file in the project root for full license information. -// - -using Microsoft.SqlTools.EditorServices.Protocol.MessageProtocol; - -namespace Microsoft.SqlTools.EditorServices.Protocol.DebugAdapter -{ - public class StepInRequest - { - public static readonly - RequestType Type = - RequestType.Create("stepIn"); - } -} - diff --git a/ServiceHost/DebugAdapter/StepOutRequest.cs b/ServiceHost/DebugAdapter/StepOutRequest.cs deleted file mode 100644 index 17e090a2..00000000 --- a/ServiceHost/DebugAdapter/StepOutRequest.cs +++ /dev/null @@ -1,16 +0,0 @@ -// -// Copyright (c) Microsoft. All rights reserved. -// Licensed under the MIT license. See LICENSE file in the project root for full license information. -// - -using Microsoft.SqlTools.EditorServices.Protocol.MessageProtocol; - -namespace Microsoft.SqlTools.EditorServices.Protocol.DebugAdapter -{ - public class StepOutRequest - { - public static readonly - RequestType Type = - RequestType.Create("stepOut"); - } -} diff --git a/ServiceHost/DebugAdapter/StoppedEvent.cs b/ServiceHost/DebugAdapter/StoppedEvent.cs deleted file mode 100644 index 698bd698..00000000 --- a/ServiceHost/DebugAdapter/StoppedEvent.cs +++ /dev/null @@ -1,41 +0,0 @@ -// -// Copyright (c) Microsoft. All rights reserved. -// Licensed under the MIT license. See LICENSE file in the project root for full license information. -// - -using Microsoft.SqlTools.EditorServices.Protocol.MessageProtocol; - -namespace Microsoft.SqlTools.EditorServices.Protocol.DebugAdapter -{ - public class StoppedEvent - { - public static readonly - EventType Type = - EventType.Create("stopped"); - } - - public class StoppedEventBody - { - /// - /// A value such as "step", "breakpoint", "exception", or "pause" - /// - public string Reason { get; set; } - - /// - /// Gets or sets the current thread ID, if any. - /// - public int? ThreadId { get; set; } - - public Source Source { get; set; } - - public int Line { get; set; } - - public int Column { get; set; } - - /// - /// Gets or sets additional information such as an error message. - /// - public string Text { get; set; } - } -} - diff --git a/ServiceHost/DebugAdapter/TerminatedEvent.cs b/ServiceHost/DebugAdapter/TerminatedEvent.cs deleted file mode 100644 index 5671a88e..00000000 --- a/ServiceHost/DebugAdapter/TerminatedEvent.cs +++ /dev/null @@ -1,17 +0,0 @@ -// -// Copyright (c) Microsoft. All rights reserved. -// Licensed under the MIT license. See LICENSE file in the project root for full license information. -// - -using Microsoft.SqlTools.EditorServices.Protocol.MessageProtocol; - -namespace Microsoft.SqlTools.EditorServices.Protocol.DebugAdapter -{ - public class TerminatedEvent - { - public static readonly - EventType Type = - EventType.Create("terminated"); - } -} - diff --git a/ServiceHost/DebugAdapter/Thread.cs b/ServiceHost/DebugAdapter/Thread.cs deleted file mode 100644 index 6bc26693..00000000 --- a/ServiceHost/DebugAdapter/Thread.cs +++ /dev/null @@ -1,15 +0,0 @@ -// -// Copyright (c) Microsoft. All rights reserved. -// Licensed under the MIT license. See LICENSE file in the project root for full license information. -// - -namespace Microsoft.SqlTools.EditorServices.Protocol.DebugAdapter -{ - public class Thread - { - public int Id { get; set; } - - public string Name { get; set; } - } -} - diff --git a/ServiceHost/DebugAdapter/ThreadsRequest.cs b/ServiceHost/DebugAdapter/ThreadsRequest.cs deleted file mode 100644 index c720cb5b..00000000 --- a/ServiceHost/DebugAdapter/ThreadsRequest.cs +++ /dev/null @@ -1,22 +0,0 @@ -// -// Copyright (c) Microsoft. All rights reserved. -// Licensed under the MIT license. See LICENSE file in the project root for full license information. -// - -using Microsoft.SqlTools.EditorServices.Protocol.MessageProtocol; - -namespace Microsoft.SqlTools.EditorServices.Protocol.DebugAdapter -{ - public class ThreadsRequest - { - public static readonly - RequestType Type = - RequestType.Create("threads"); - } - - public class ThreadsResponseBody - { - public Thread[] Threads { get; set; } - } -} - diff --git a/ServiceHost/DebugAdapter/Variable.cs b/ServiceHost/DebugAdapter/Variable.cs deleted file mode 100644 index e805dde9..00000000 --- a/ServiceHost/DebugAdapter/Variable.cs +++ /dev/null @@ -1,33 +0,0 @@ -// -// Copyright (c) Microsoft. All rights reserved. -// Licensed under the MIT license. See LICENSE file in the project root for full license information. -// - -namespace Microsoft.SqlTools.EditorServices.Protocol.DebugAdapter -{ - public class Variable - { - public string Name { get; set; } - - // /** The variable's value. For structured objects this can be a multi line text, e.g. for a function the body of a function. */ - public string Value { get; set; } - - // /** If variablesReference is > 0, the variable is structured and its children can be retrieved by passing variablesReference to the VariablesRequest. */ - public int VariablesReference { get; set; } - -#if false - public static Variable Create(VariableDetailsBase variable) - { - return new Variable - { - Name = variable.Name, - Value = variable.ValueString ?? string.Empty, - VariablesReference = - variable.IsExpandable ? - variable.Id : 0 - }; - } -#endif - } -} - diff --git a/ServiceHost/DebugAdapter/VariablesRequest.cs b/ServiceHost/DebugAdapter/VariablesRequest.cs deleted file mode 100644 index cd260b1b..00000000 --- a/ServiceHost/DebugAdapter/VariablesRequest.cs +++ /dev/null @@ -1,29 +0,0 @@ -// -// Copyright (c) Microsoft. All rights reserved. -// Licensed under the MIT license. See LICENSE file in the project root for full license information. -// - -using System.Diagnostics; -using Microsoft.SqlTools.EditorServices.Protocol.MessageProtocol; - -namespace Microsoft.SqlTools.EditorServices.Protocol.DebugAdapter -{ - public class VariablesRequest - { - public static readonly - RequestType Type = - RequestType.Create("variables"); - } - - [DebuggerDisplay("VariablesReference = {VariablesReference}")] - public class VariablesRequestArguments - { - public int VariablesReference { get; set; } - } - - public class VariablesResponseBody - { - public Variable[] Variables { get; set; } - } -} - diff --git a/ServiceHost/LanguageServer/ClientCapabilities.cs b/ServiceHost/LanguageServer/ClientCapabilities.cs index 6537e7b5..70e2d068 100644 --- a/ServiceHost/LanguageServer/ClientCapabilities.cs +++ b/ServiceHost/LanguageServer/ClientCapabilities.cs @@ -3,11 +3,6 @@ // Licensed under the MIT license. See LICENSE file in the project root for full license information. // -using System; -using System.Collections.Generic; -using System.Linq; -using System.Text; -using System.Threading.Tasks; namespace Microsoft.SqlTools.EditorServices.Protocol.LanguageServer { diff --git a/ServiceHost/LanguageServer/Completion.cs b/ServiceHost/LanguageServer/Completion.cs index 3af67735..5f26ea96 100644 --- a/ServiceHost/LanguageServer/Completion.cs +++ b/ServiceHost/LanguageServer/Completion.cs @@ -83,4 +83,3 @@ namespace Microsoft.SqlTools.EditorServices.Protocol.LanguageServer public object Data { get; set; } } } - diff --git a/ServiceHost/LanguageServer/Diagnostics.cs b/ServiceHost/LanguageServer/Diagnostics.cs index 87c2f98f..a5472607 100644 --- a/ServiceHost/LanguageServer/Diagnostics.cs +++ b/ServiceHost/LanguageServer/Diagnostics.cs @@ -4,11 +4,6 @@ // using Microsoft.SqlTools.EditorServices.Protocol.MessageProtocol; -using System; -using System.Collections.Generic; -using System.Linq; -using System.Text; -using System.Threading.Tasks; namespace Microsoft.SqlTools.EditorServices.Protocol.LanguageServer { diff --git a/ServiceHost/LanguageServer/EditorCommands.cs b/ServiceHost/LanguageServer/EditorCommands.cs deleted file mode 100644 index 426d7885..00000000 --- a/ServiceHost/LanguageServer/EditorCommands.cs +++ /dev/null @@ -1,111 +0,0 @@ -// -// Copyright (c) Microsoft. All rights reserved. -// Licensed under the MIT license. See LICENSE file in the project root for full license information. -// - -using Microsoft.SqlTools.EditorServices.Protocol.MessageProtocol; - -namespace Microsoft.SqlTools.EditorServices.Protocol.LanguageServer -{ - public class ExtensionCommandAddedNotification - { - public static readonly - EventType Type = - EventType.Create("SqlTools/extensionCommandAdded"); - - public string Name { get; set; } - - public string DisplayName { get; set; } - } - - public class ExtensionCommandUpdatedNotification - { - public static readonly - EventType Type = - EventType.Create("SqlTools/extensionCommandUpdated"); - - public string Name { get; set; } - } - - public class ExtensionCommandRemovedNotification - { - public static readonly - EventType Type = - EventType.Create("SqlTools/extensionCommandRemoved"); - - public string Name { get; set; } - } - - public class ClientEditorContext - { - public string CurrentFilePath { get; set; } - - public Position CursorPosition { get; set; } - - public Range SelectionRange { get; set; } - - } - - public class InvokeExtensionCommandRequest - { - public static readonly - RequestType Type = - RequestType.Create("SqlTools/invokeExtensionCommand"); - - public string Name { get; set; } - - public ClientEditorContext Context { get; set; } - } - - public class GetEditorContextRequest - { - public static readonly - RequestType Type = - RequestType.Create("editor/getEditorContext"); - } - - public enum EditorCommandResponse - { - Unsupported, - OK - } - - public class InsertTextRequest - { - public static readonly - RequestType Type = - RequestType.Create("editor/insertText"); - - public string FilePath { get; set; } - - public string InsertText { get; set; } - - public Range InsertRange { get; set; } - } - - public class SetSelectionRequest - { - public static readonly - RequestType Type = - RequestType.Create("editor/setSelection"); - - public Range SelectionRange { get; set; } - } - - public class SetCursorPositionRequest - { - public static readonly - RequestType Type = - RequestType.Create("editor/setCursorPosition"); - - public Position CursorPosition { get; set; } - } - - public class OpenFileRequest - { - public static readonly - RequestType Type = - RequestType.Create("editor/openFile"); - } -} - diff --git a/ServiceHost/LanguageServer/Hover.cs b/ServiceHost/LanguageServer/Hover.cs index 7a8b6cbf..2e196fba 100644 --- a/ServiceHost/LanguageServer/Hover.cs +++ b/ServiceHost/LanguageServer/Hover.cs @@ -4,11 +4,6 @@ // using Microsoft.SqlTools.EditorServices.Protocol.MessageProtocol; -using System; -using System.Collections.Generic; -using System.Linq; -using System.Text; -using System.Threading.Tasks; namespace Microsoft.SqlTools.EditorServices.Protocol.LanguageServer { diff --git a/ServiceHost/LanguageServer/TextDocument.cs b/ServiceHost/LanguageServer/TextDocument.cs index 9b477c96..9f477374 100644 --- a/ServiceHost/LanguageServer/TextDocument.cs +++ b/ServiceHost/LanguageServer/TextDocument.cs @@ -61,12 +61,27 @@ namespace Microsoft.SqlTools.EditorServices.Protocol.LanguageServer public class DidChangeTextDocumentParams : TextDocumentIdentifier { + public TextDocumentUriChangeEvent TextDocument { get; set; } + /// /// Gets or sets the list of changes to the document content. /// public TextDocumentChangeEvent[] ContentChanges { get; set; } } + public class TextDocumentUriChangeEvent + { + /// + /// Gets or sets the Uri of the changed text document + /// + public string Uri { get; set; } + + /// + /// Gets or sets the Version of the changed text document + /// + public int Version { get; set; } + } + public class TextDocumentChangeEvent { /// diff --git a/ServiceHost/MessageProtocol/Channel/NamedPipeClientChannel.cs b/ServiceHost/MessageProtocol/Channel/NamedPipeClientChannel.cs deleted file mode 100644 index 5af3711d..00000000 --- a/ServiceHost/MessageProtocol/Channel/NamedPipeClientChannel.cs +++ /dev/null @@ -1,83 +0,0 @@ -// -// Copyright (c) Microsoft. All rights reserved. -// Licensed under the MIT license. See LICENSE file in the project root for full license information. -// - -#if false - -using System; -using System.IO.Pipes; -using System.Threading.Tasks; - -namespace Microsoft.SqlTools.EditorServices.Protocol.MessageProtocol.Channel -{ - public class NamedPipeClientChannel : ChannelBase - { - private string pipeName; - private bool isClientConnected; - private NamedPipeClientStream pipeClient; - - public NamedPipeClientChannel(string pipeName) - { - this.pipeName = pipeName; - } - - public override async Task WaitForConnection() - { -#if NanoServer - await this.pipeClient.ConnectAsync(); -#else - this.IsConnected = false; - - while (!this.IsConnected) - { - try - { - // Wait for 500 milliseconds so that we don't tie up the thread - this.pipeClient.Connect(500); - this.IsConnected = this.pipeClient.IsConnected; - } - catch (TimeoutException) - { - // Connect timed out, wait and try again - await Task.Delay(1000); - continue; - } - } -#endif - - // If we've reached this point, we're connected - this.IsConnected = true; - } - - protected override void Initialize(IMessageSerializer messageSerializer) - { - this.pipeClient = - new NamedPipeClientStream( - ".", - this.pipeName, - PipeDirection.InOut, - PipeOptions.Asynchronous); - - this.MessageReader = - new MessageReader( - this.pipeClient, - messageSerializer); - - this.MessageWriter = - new MessageWriter( - this.pipeClient, - messageSerializer); - } - - protected override void Shutdown() - { - if (this.pipeClient != null) - { - this.pipeClient.Dispose(); - } - } - } -} - -#endif \ No newline at end of file diff --git a/ServiceHost/MessageProtocol/Channel/NamedPipeServerChannel.cs b/ServiceHost/MessageProtocol/Channel/NamedPipeServerChannel.cs deleted file mode 100644 index 1a3a954a..00000000 --- a/ServiceHost/MessageProtocol/Channel/NamedPipeServerChannel.cs +++ /dev/null @@ -1,65 +0,0 @@ -// -// Copyright (c) Microsoft. All rights reserved. -// Licensed under the MIT license. See LICENSE file in the project root for full license information. -// - -#if false -using System; -using System.IO.Pipes; -using System.Threading.Tasks; - -namespace Microsoft.SqlTools.EditorServices.Protocol.MessageProtocol.Channel -{ - public class NamedPipeServerChannel : ChannelBase - { - private string pipeName; - private NamedPipeServerStream pipeServer; - - public NamedPipeServerChannel(string pipeName) - { - this.pipeName = pipeName; - } - - public override async Task WaitForConnection() - { -#if NanoServer - await this.pipeServer.WaitForConnectionAsync(); -#else - await Task.Factory.FromAsync(this.pipeServer.BeginWaitForConnection, this.pipeServer.EndWaitForConnection, null); -#endif - - this.IsConnected = true; - } - - protected override void Initialize(IMessageSerializer messageSerializer) - { - this.pipeServer = - new NamedPipeServerStream( - pipeName, - PipeDirection.InOut, - 1, - PipeTransmissionMode.Byte, - PipeOptions.Asynchronous); - - this.MessageReader = - new MessageReader( - this.pipeServer, - messageSerializer); - - this.MessageWriter = - new MessageWriter( - this.pipeServer, - messageSerializer); - } - - protected override void Shutdown() - { - if (this.pipeServer != null) - { - this.pipeServer.Dispose(); - } - } - } -} - -#endif diff --git a/ServiceHost/MessageProtocol/Channel/StdioClientChannel.cs b/ServiceHost/MessageProtocol/Channel/StdioClientChannel.cs index 3cf87be4..5390f52d 100644 --- a/ServiceHost/MessageProtocol/Channel/StdioClientChannel.cs +++ b/ServiceHost/MessageProtocol/Channel/StdioClientChannel.cs @@ -3,11 +3,9 @@ // Licensed under the MIT license. See LICENSE file in the project root for full license information. // -using Microsoft.SqlTools.EditorServices.Protocol.MessageProtocol.Serializers; using System.Diagnostics; using System.IO; using System.Text; -using System; using System.Threading.Tasks; namespace Microsoft.SqlTools.EditorServices.Protocol.MessageProtocol.Channel diff --git a/ServiceHost/MessageProtocol/Channel/StdioServerChannel.cs b/ServiceHost/MessageProtocol/Channel/StdioServerChannel.cs index deb692e1..0b9376d4 100644 --- a/ServiceHost/MessageProtocol/Channel/StdioServerChannel.cs +++ b/ServiceHost/MessageProtocol/Channel/StdioServerChannel.cs @@ -3,10 +3,8 @@ // Licensed under the MIT license. See LICENSE file in the project root for full license information. // -using Microsoft.SqlTools.EditorServices.Protocol.MessageProtocol.Serializers; using System.IO; using System.Text; -using System; using System.Threading.Tasks; namespace Microsoft.SqlTools.EditorServices.Protocol.MessageProtocol.Channel diff --git a/ServiceHost/MessageProtocol/MessageDispatcher.cs b/ServiceHost/MessageProtocol/MessageDispatcher.cs index 7d2d9c4c..21c179e2 100644 --- a/ServiceHost/MessageProtocol/MessageDispatcher.cs +++ b/ServiceHost/MessageProtocol/MessageDispatcher.cs @@ -18,7 +18,7 @@ namespace Microsoft.SqlTools.EditorServices.Protocol.MessageProtocol #region Fields private ChannelBase protocolChannel; - // private AsyncQueue messagesToWrite; + private AsyncContextThread messageLoopThread; private Dictionary> requestHandlers = diff --git a/ServiceHost/MessageProtocol/Serializers/JsonRpcMessageSerializer.cs b/ServiceHost/MessageProtocol/Serializers/JsonRpcMessageSerializer.cs index edf14712..fa1d1518 100644 --- a/ServiceHost/MessageProtocol/Serializers/JsonRpcMessageSerializer.cs +++ b/ServiceHost/MessageProtocol/Serializers/JsonRpcMessageSerializer.cs @@ -3,10 +3,7 @@ // Licensed under the MIT license. See LICENSE file in the project root for full license information. // -using Microsoft.SqlTools.EditorServices.Protocol.MessageProtocol; -using Newtonsoft.Json; using Newtonsoft.Json.Linq; -using System; namespace Microsoft.SqlTools.EditorServices.Protocol.MessageProtocol.Serializers { diff --git a/ServiceHost/MessageProtocol/Serializers/V8MessageSerializer.cs b/ServiceHost/MessageProtocol/Serializers/V8MessageSerializer.cs index 4088a223..941e249a 100644 --- a/ServiceHost/MessageProtocol/Serializers/V8MessageSerializer.cs +++ b/ServiceHost/MessageProtocol/Serializers/V8MessageSerializer.cs @@ -3,8 +3,6 @@ // Licensed under the MIT license. See LICENSE file in the project root for full license information. // -using Microsoft.SqlTools.EditorServices.Protocol.MessageProtocol; -using Newtonsoft.Json; using Newtonsoft.Json.Linq; using System; diff --git a/ServiceHost/Messages/PromptEvents.cs b/ServiceHost/Messages/PromptEvents.cs deleted file mode 100644 index 3be10f75..00000000 --- a/ServiceHost/Messages/PromptEvents.cs +++ /dev/null @@ -1,58 +0,0 @@ -// -// Copyright (c) Microsoft. All rights reserved. -// Licensed under the MIT license. See LICENSE file in the project root for full license information. -// - -#if false -using Microsoft.SqlTools.EditorServices.Protocol.MessageProtocol; - -namespace Microsoft.SqlTools.EditorServices.Protocol.Messages -{ - public class ShowChoicePromptRequest - { - public static readonly - RequestType Type = - RequestType.Create("SqlTools/showChoicePrompt"); - - public string Caption { get; set; } - - public string Message { get; set; } - - public ChoiceDetails[] Choices { get; set; } - - public int DefaultChoice { get; set; } - } - - public class ShowChoicePromptResponse - { - public bool PromptCancelled { get; set; } - - public string ChosenItem { get; set; } - } - - public class ShowInputPromptRequest - { - public static readonly - RequestType Type = - RequestType.Create("SqlTools/showInputPrompt"); - - /// - /// Gets or sets the name of the field. - /// - public string Name { get; set; } - - /// - /// Gets or sets the descriptive label for the field. - /// - public string Label { get; set; } - } - - public class ShowInputPromptResponse - { - public bool PromptCancelled { get; set; } - - public string ResponseText { get; set; } - } -} - -#endif \ No newline at end of file diff --git a/ServiceHost/Properties/AssemblyInfo.cs b/ServiceHost/Properties/AssemblyInfo.cs index 8f6b28ad..27c1daba 100644 --- a/ServiceHost/Properties/AssemblyInfo.cs +++ b/ServiceHost/Properties/AssemblyInfo.cs @@ -15,7 +15,7 @@ using System.Runtime.InteropServices; [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("Microsoft")] [assembly: AssemblyProduct("SqlTools Editor Services")] -[assembly: AssemblyCopyright("© Microsoft Corporation. All rights reserved.")] +[assembly: AssemblyCopyright("� Microsoft Corporation. All rights reserved.")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] @@ -37,8 +37,8 @@ using System.Runtime.InteropServices; // You can specify all the values or you can default the Build and Revision Numbers // by using the '*' as shown below: // [assembly: AssemblyVersion("1.0.*")] -[assembly: AssemblyVersion("0.0.0.0")] -[assembly: AssemblyFileVersion("0.0.0.0")] -[assembly: AssemblyInformationalVersion("0.0.0.0")] +[assembly: AssemblyVersion("1.0.0.0")] +[assembly: AssemblyFileVersion("1.0.0.0")] +[assembly: AssemblyInformationalVersion("1.0.0.0")] [assembly: InternalsVisibleTo("Microsoft.SqlTools.EditorServices.Test.Protocol")] diff --git a/ServiceHost/Server/DebugAdapter.cs b/ServiceHost/Server/DebugAdapter.cs deleted file mode 100644 index d62b10e9..00000000 --- a/ServiceHost/Server/DebugAdapter.cs +++ /dev/null @@ -1,584 +0,0 @@ -// -// Copyright (c) Microsoft. All rights reserved. -// Licensed under the MIT license. See LICENSE file in the project root for full license information. -// - -#if false - -using Microsoft.SqlTools.EditorServices.Protocol.DebugAdapter; -using Microsoft.SqlTools.EditorServices.Protocol.MessageProtocol; -using Microsoft.SqlTools.EditorServices.Protocol.MessageProtocol.Channel; -using Microsoft.SqlTools.EditorServices.Session; -using Microsoft.SqlTools.EditorServices.Utility; -using System; -using System.Collections.Generic; -using System.IO; -using System.Linq; -using System.Management.Automation; -using System.Threading.Tasks; - -namespace Microsoft.SqlTools.EditorServices.Protocol.Server -{ - public class DebugAdapter : DebugAdapterBase - { - private EditorSession editorSession; - private OutputDebouncer outputDebouncer; - private bool isConfigurationDoneRequestComplete; - private bool isLaunchRequestComplete; - private bool noDebug; - private string scriptPathToLaunch; - private string arguments; - - public DebugAdapter(HostDetails hostDetails, ProfilePaths profilePaths) - : this(hostDetails, profilePaths, new StdioServerChannel()) - { - } - - public DebugAdapter(HostDetails hostDetails, ProfilePaths profilePaths, ChannelBase serverChannel) - : base(serverChannel) - { - this.editorSession = new EditorSession(); - this.editorSession.StartSession(hostDetails, profilePaths); - this.editorSession.DebugService.DebuggerStopped += this.DebugService_DebuggerStopped; - this.editorSession.ConsoleService.OutputWritten += this.SqlToolsContext_OutputWritten; - - // Set up the output debouncer to throttle output event writes - this.outputDebouncer = new OutputDebouncer(this); - } - - protected override void Initialize() - { - // Register all supported message types - - this.SetRequestHandler(LaunchRequest.Type, this.HandleLaunchRequest); - this.SetRequestHandler(AttachRequest.Type, this.HandleAttachRequest); - this.SetRequestHandler(ConfigurationDoneRequest.Type, this.HandleConfigurationDoneRequest); - this.SetRequestHandler(DisconnectRequest.Type, this.HandleDisconnectRequest); - - this.SetRequestHandler(SetBreakpointsRequest.Type, this.HandleSetBreakpointsRequest); - this.SetRequestHandler(SetExceptionBreakpointsRequest.Type, this.HandleSetExceptionBreakpointsRequest); - this.SetRequestHandler(SetFunctionBreakpointsRequest.Type, this.HandleSetFunctionBreakpointsRequest); - - this.SetRequestHandler(ContinueRequest.Type, this.HandleContinueRequest); - this.SetRequestHandler(NextRequest.Type, this.HandleNextRequest); - this.SetRequestHandler(StepInRequest.Type, this.HandleStepInRequest); - this.SetRequestHandler(StepOutRequest.Type, this.HandleStepOutRequest); - this.SetRequestHandler(PauseRequest.Type, this.HandlePauseRequest); - - this.SetRequestHandler(ThreadsRequest.Type, this.HandleThreadsRequest); - this.SetRequestHandler(StackTraceRequest.Type, this.HandleStackTraceRequest); - this.SetRequestHandler(ScopesRequest.Type, this.HandleScopesRequest); - this.SetRequestHandler(VariablesRequest.Type, this.HandleVariablesRequest); - this.SetRequestHandler(SourceRequest.Type, this.HandleSourceRequest); - this.SetRequestHandler(EvaluateRequest.Type, this.HandleEvaluateRequest); - } - - protected Task LaunchScript(RequestContext requestContext) - { - return editorSession.SqlToolsContext - .ExecuteScriptAtPath(this.scriptPathToLaunch, this.arguments) - .ContinueWith( - async (t) => { - Logger.Write(LogLevel.Verbose, "Execution completed, terminating..."); - - await requestContext.SendEvent( - TerminatedEvent.Type, - null); - - // Stop the server - await this.Stop(); - - // Notify that the session has ended - this.OnSessionEnded(); - }); - } - - protected override void Shutdown() - { - // Make sure remaining output is flushed before exiting - this.outputDebouncer.Flush().Wait(); - - Logger.Write(LogLevel.Normal, "Debug adapter is shutting down..."); - - if (this.editorSession != null) - { - this.editorSession.Dispose(); - this.editorSession = null; - } - } - - #region Built-in Message Handlers - - protected async Task HandleConfigurationDoneRequest( - object args, - RequestContext requestContext) - { - // The order of debug protocol messages apparently isn't as guaranteed as we might like. - // Need to be able to handle the case where we get the configurationDone request after the - // launch request. - if (this.isLaunchRequestComplete) - { - this.LaunchScript(requestContext); - } - - this.isConfigurationDoneRequestComplete = true; - - await requestContext.SendResult(null); - } - - protected async Task HandleLaunchRequest( - LaunchRequestArguments launchParams, - RequestContext requestContext) - { - // Set the working directory for the SqlTools runspace to the cwd passed in via launch.json. - // In case that is null, use the the folder of the script to be executed. If the resulting - // working dir path is a file path then extract the directory and use that. - string workingDir = launchParams.Cwd ?? launchParams.Program; - workingDir = SqlToolsContext.UnescapePath(workingDir); - try - { - if ((File.GetAttributes(workingDir) & FileAttributes.Directory) != FileAttributes.Directory) - { - workingDir = Path.GetDirectoryName(workingDir); - } - } - catch (Exception ex) - { - Logger.Write(LogLevel.Error, "cwd path is invalid: " + ex.Message); - -#if NanoServer - workingDir = AppContext.BaseDirectory; -#else - workingDir = Environment.CurrentDirectory; -#endif - } - - editorSession.SqlToolsContext.SetWorkingDirectory(workingDir); - Logger.Write(LogLevel.Verbose, "Working dir set to: " + workingDir); - - // Prepare arguments to the script - if specified - string arguments = null; - if ((launchParams.Args != null) && (launchParams.Args.Length > 0)) - { - arguments = string.Join(" ", launchParams.Args); - Logger.Write(LogLevel.Verbose, "Script arguments are: " + arguments); - } - - // We may not actually launch the script in response to this - // request unless it comes after the configurationDone request. - // If the launch request comes first, then stash the launch - // params so that the subsequent configurationDone request handler - // can launch the script. - this.noDebug = launchParams.NoDebug; - this.scriptPathToLaunch = launchParams.Program; - this.arguments = arguments; - - // The order of debug protocol messages apparently isn't as guaranteed as we might like. - // Need to be able to handle the case where we get the launch request after the - // configurationDone request. - if (this.isConfigurationDoneRequestComplete) - { - this.LaunchScript(requestContext); - } - - this.isLaunchRequestComplete = true; - - await requestContext.SendResult(null); - } - - protected Task HandleAttachRequest( - AttachRequestArguments attachParams, - RequestContext requestContext) - { - // TODO: Implement this once we support attaching to processes - throw new NotImplementedException(); - } - - protected Task HandleDisconnectRequest( - object disconnectParams, - RequestContext requestContext) - { - EventHandler handler = null; - - handler = - async (o, e) => - { - if (e.NewSessionState == SqlToolsContextState.Ready) - { - await requestContext.SendResult(null); - editorSession.SqlToolsContext.SessionStateChanged -= handler; - - // Stop the server - this.Stop(); - } - }; - - editorSession.SqlToolsContext.SessionStateChanged += handler; - editorSession.SqlToolsContext.AbortExecution(); - - return Task.FromResult(true); - } - - protected async Task HandleSetBreakpointsRequest( - SetBreakpointsRequestArguments setBreakpointsParams, - RequestContext requestContext) - { - ScriptFile scriptFile; - - // Fix for issue #195 - user can change name of file outside of VSCode in which case - // VSCode sends breakpoint requests with the original filename that doesn't exist anymore. - try - { - scriptFile = editorSession.Workspace.GetFile(setBreakpointsParams.Source.Path); - } - catch (FileNotFoundException) - { - Logger.Write( - LogLevel.Warning, - $"Attempted to set breakpoints on a non-existing file: {setBreakpointsParams.Source.Path}"); - - string message = this.noDebug ? string.Empty : "Source does not exist, breakpoint not set."; - - var srcBreakpoints = setBreakpointsParams.Breakpoints - .Select(srcBkpt => Protocol.DebugAdapter.Breakpoint.Create( - srcBkpt, setBreakpointsParams.Source.Path, message, verified: this.noDebug)); - - // Return non-verified breakpoint message. - await requestContext.SendResult( - new SetBreakpointsResponseBody { - Breakpoints = srcBreakpoints.ToArray() - }); - - return; - } - - var breakpointDetails = new BreakpointDetails[setBreakpointsParams.Breakpoints.Length]; - for (int i = 0; i < breakpointDetails.Length; i++) - { - SourceBreakpoint srcBreakpoint = setBreakpointsParams.Breakpoints[i]; - breakpointDetails[i] = BreakpointDetails.Create( - scriptFile.FilePath, - srcBreakpoint.Line, - srcBreakpoint.Column, - srcBreakpoint.Condition); - } - - // If this is a "run without debugging (Ctrl+F5)" session ignore requests to set breakpoints. - BreakpointDetails[] updatedBreakpointDetails = breakpointDetails; - if (!this.noDebug) - { - updatedBreakpointDetails = - await editorSession.DebugService.SetLineBreakpoints( - scriptFile, - breakpointDetails); - } - - await requestContext.SendResult( - new SetBreakpointsResponseBody { - Breakpoints = - updatedBreakpointDetails - .Select(Protocol.DebugAdapter.Breakpoint.Create) - .ToArray() - }); - } - - protected async Task HandleSetFunctionBreakpointsRequest( - SetFunctionBreakpointsRequestArguments setBreakpointsParams, - RequestContext requestContext) - { - var breakpointDetails = new CommandBreakpointDetails[setBreakpointsParams.Breakpoints.Length]; - for (int i = 0; i < breakpointDetails.Length; i++) - { - FunctionBreakpoint funcBreakpoint = setBreakpointsParams.Breakpoints[i]; - breakpointDetails[i] = CommandBreakpointDetails.Create( - funcBreakpoint.Name, - funcBreakpoint.Condition); - } - - // If this is a "run without debugging (Ctrl+F5)" session ignore requests to set breakpoints. - CommandBreakpointDetails[] updatedBreakpointDetails = breakpointDetails; - if (!this.noDebug) - { - updatedBreakpointDetails = - await editorSession.DebugService.SetCommandBreakpoints( - breakpointDetails); - } - - await requestContext.SendResult( - new SetBreakpointsResponseBody { - Breakpoints = - updatedBreakpointDetails - .Select(Protocol.DebugAdapter.Breakpoint.Create) - .ToArray() - }); - } - - protected async Task HandleSetExceptionBreakpointsRequest( - SetExceptionBreakpointsRequestArguments setExceptionBreakpointsParams, - RequestContext requestContext) - { - // TODO: Handle this appropriately - - await requestContext.SendResult(null); - } - - protected async Task HandleContinueRequest( - object continueParams, - RequestContext requestContext) - { - editorSession.DebugService.Continue(); - - await requestContext.SendResult(null); - } - - protected async Task HandleNextRequest( - object nextParams, - RequestContext requestContext) - { - editorSession.DebugService.StepOver(); - - await requestContext.SendResult(null); - } - - protected Task HandlePauseRequest( - object pauseParams, - RequestContext requestContext) - { - try - { - editorSession.DebugService.Break(); - } - catch (NotSupportedException e) - { - return requestContext.SendError(e.Message); - } - - // This request is responded to by sending the "stopped" event - return Task.FromResult(true); - } - - protected async Task HandleStepInRequest( - object stepInParams, - RequestContext requestContext) - { - editorSession.DebugService.StepIn(); - - await requestContext.SendResult(null); - } - - protected async Task HandleStepOutRequest( - object stepOutParams, - RequestContext requestContext) - { - editorSession.DebugService.StepOut(); - - await requestContext.SendResult(null); - } - - protected async Task HandleThreadsRequest( - object threadsParams, - RequestContext requestContext) - { - await requestContext.SendResult( - new ThreadsResponseBody - { - Threads = new Thread[] - { - // TODO: What do I do with these? - new Thread - { - Id = 1, - Name = "Main Thread" - } - } - }); - } - - protected async Task HandleStackTraceRequest( - StackTraceRequestArguments stackTraceParams, - RequestContext requestContext) - { - StackFrameDetails[] stackFrames = - editorSession.DebugService.GetStackFrames(); - - List newStackFrames = new List(); - - for (int i = 0; i < stackFrames.Length; i++) - { - // Create the new StackFrame object with an ID that can - // be referenced back to the current list of stack frames - newStackFrames.Add( - StackFrame.Create( - stackFrames[i], - i)); - } - - await requestContext.SendResult( - new StackTraceResponseBody - { - StackFrames = newStackFrames.ToArray() - }); - } - - protected async Task HandleScopesRequest( - ScopesRequestArguments scopesParams, - RequestContext requestContext) - { - VariableScope[] variableScopes = - editorSession.DebugService.GetVariableScopes( - scopesParams.FrameId); - - await requestContext.SendResult( - new ScopesResponseBody - { - Scopes = - variableScopes - .Select(Scope.Create) - .ToArray() - }); - } - - protected async Task HandleVariablesRequest( - VariablesRequestArguments variablesParams, - RequestContext requestContext) - { - VariableDetailsBase[] variables = - editorSession.DebugService.GetVariables( - variablesParams.VariablesReference); - - VariablesResponseBody variablesResponse = null; - - try - { - variablesResponse = new VariablesResponseBody - { - Variables = - variables - .Select(Variable.Create) - .ToArray() - }; - } - catch (Exception) - { - // TODO: This shouldn't be so broad - } - - await requestContext.SendResult(variablesResponse); - } - - protected Task HandleSourceRequest( - SourceRequestArguments sourceParams, - RequestContext requestContext) - { - // TODO: Implement this message. For now, doesn't seem to - // be a problem that it's missing. - - return Task.FromResult(true); - } - - protected async Task HandleEvaluateRequest( - EvaluateRequestArguments evaluateParams, - RequestContext requestContext) - { - string valueString = null; - int variableId = 0; - - bool isFromRepl = - string.Equals( - evaluateParams.Context, - "repl", - StringComparison.CurrentCultureIgnoreCase); - - if (isFromRepl) - { - // Send the input through the console service - editorSession.ConsoleService.ExecuteCommand( - evaluateParams.Expression, - false); - } - else - { - VariableDetails result = - await editorSession.DebugService.EvaluateExpression( - evaluateParams.Expression, - evaluateParams.FrameId, - isFromRepl); - - if (result != null) - { - valueString = result.ValueString; - variableId = - result.IsExpandable ? - result.Id : 0; - } - } - - await requestContext.SendResult( - new EvaluateResponseBody - { - Result = valueString, - VariablesReference = variableId - }); - } - - #endregion - - #region Events - - public event EventHandler SessionEnded; - - protected virtual void OnSessionEnded() - { - this.SessionEnded?.Invoke(this, null); - } - - #endregion - - #region Event Handlers - - async void DebugService_DebuggerStopped(object sender, DebuggerStopEventArgs e) - { - // Flush pending output before sending the event - await this.outputDebouncer.Flush(); - - // Provide the reason for why the debugger has stopped script execution. - // See https://github.com/Microsoft/vscode/issues/3648 - // The reason is displayed in the breakpoints viewlet. Some recommended reasons are: - // "step", "breakpoint", "function breakpoint", "exception" and "pause". - // We don't support exception breakpoints and for "pause", we can't distinguish - // between stepping and the user pressing the pause/break button in the debug toolbar. - string debuggerStoppedReason = "step"; - if (e.Breakpoints.Count > 0) - { - debuggerStoppedReason = - e.Breakpoints[0] is CommandBreakpoint - ? "function breakpoint" - : "breakpoint"; - } - - await this.SendEvent( - StoppedEvent.Type, - new StoppedEventBody - { - Source = new Source - { - Path = e.InvocationInfo.ScriptName, - }, - Line = e.InvocationInfo.ScriptLineNumber, - Column = e.InvocationInfo.OffsetInLine, - ThreadId = 1, // TODO: Change this based on context - Reason = debuggerStoppedReason - }); - } - - async void SqlToolsContext_OutputWritten(object sender, OutputWrittenEventArgs e) - { - // Queue the output for writing - await this.outputDebouncer.Invoke(e); - } - - #endregion - } -} - -#endif \ No newline at end of file diff --git a/ServiceHost/Server/DebugAdapterBase.cs b/ServiceHost/Server/DebugAdapterBase.cs deleted file mode 100644 index b0f85aab..00000000 --- a/ServiceHost/Server/DebugAdapterBase.cs +++ /dev/null @@ -1,73 +0,0 @@ -// -// Copyright (c) Microsoft. All rights reserved. -// Licensed under the MIT license. See LICENSE file in the project root for full license information. -// -#if false -using Microsoft.SqlTools.EditorServices.Protocol.DebugAdapter; -using Microsoft.SqlTools.EditorServices.Protocol.MessageProtocol; -using Microsoft.SqlTools.EditorServices.Protocol.MessageProtocol.Channel; -using System.Threading.Tasks; - -namespace Microsoft.SqlTools.EditorServices.Protocol.Server -{ - public abstract class DebugAdapterBase : ProtocolEndpoint - { - public DebugAdapterBase(ChannelBase serverChannel) - : base (serverChannel, MessageProtocolType.DebugAdapter) - { - } - - /// - /// Overridden by the subclass to provide initialization - /// logic after the server channel is started. - /// - protected abstract void Initialize(); - - /// - /// Can be overridden by the subclass to provide shutdown - /// logic before the server exits. - /// - protected virtual void Shutdown() - { - // No default implementation yet. - } - - protected override Task OnStart() - { - // Register handlers for server lifetime messages - this.SetRequestHandler(InitializeRequest.Type, this.HandleInitializeRequest); - - // Initialize the implementation class - this.Initialize(); - - return Task.FromResult(true); - } - - protected override Task OnStop() - { - this.Shutdown(); - - return Task.FromResult(true); - } - - private async Task HandleInitializeRequest( - object shutdownParams, - RequestContext requestContext) - { - // Now send the Initialize response to continue setup - await requestContext.SendResult( - new InitializeResponseBody { - SupportsConfigurationDoneRequest = true, - SupportsConditionalBreakpoints = true, - SupportsFunctionBreakpoints = true - }); - - // Send the Initialized event so that we get breakpoints - await requestContext.SendEvent( - InitializedEvent.Type, - null); - } - } -} - -#endif \ No newline at end of file diff --git a/ServiceHost/Server/LanguageServer.cs b/ServiceHost/Server/LanguageServer.cs index 69fddc5e..2f0f7963 100644 --- a/ServiceHost/Server/LanguageServer.cs +++ b/ServiceHost/Server/LanguageServer.cs @@ -2,171 +2,70 @@ // Copyright (c) Microsoft. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. // - - -//using Microsoft.SqlTools.EditorServices.Extensions; using Microsoft.SqlTools.EditorServices.Protocol.LanguageServer; using Microsoft.SqlTools.EditorServices.Protocol.MessageProtocol; using Microsoft.SqlTools.EditorServices.Protocol.MessageProtocol.Channel; using Microsoft.SqlTools.EditorServices.Session; -//using Microsoft.SqlTools.EditorServices.Utility; -using System; -using System.Collections.Generic; -using System.IO; -using System.Linq; -//using System.Management.Automation; -//using System.Text.RegularExpressions; -using System.Threading; using System.Threading.Tasks; -using DebugAdapterMessages = Microsoft.SqlTools.EditorServices.Protocol.DebugAdapter; +using Microsoft.SqlTools.EditorServices.Utility; +using System.Collections.Generic; +using System.Text; namespace Microsoft.SqlTools.EditorServices.Protocol.Server { public class LanguageServer : LanguageServerBase { - // private static CancellationTokenSource existingRequestCancellation; - - // private bool profilesLoaded; - // private EditorSession editorSession; - // private OutputDebouncer outputDebouncer; - // private LanguageServerEditorOperations editorOperations; - // private LanguageServerSettings currentSettings = new LanguageServerSettings(); + private EditorSession editorSession; /// /// Provides details about the host application. /// public LanguageServer(HostDetails hostDetails, ProfilePaths profilePaths) - : this(hostDetails, profilePaths, new StdioServerChannel()) + : base(new StdioServerChannel()) { - } - - /// - /// Provides details about the host application. - /// - public LanguageServer(HostDetails hostDetails, ProfilePaths profilePaths, ChannelBase serverChannel) - : base(serverChannel) - { -#if false this.editorSession = new EditorSession(); this.editorSession.StartSession(hostDetails, profilePaths); - this.editorSession.ConsoleService.OutputWritten += this.SqlToolsContext_OutputWritten; - - // Attach to ExtensionService events - this.editorSession.ExtensionService.CommandAdded += ExtensionService_ExtensionAdded; - this.editorSession.ExtensionService.CommandUpdated += ExtensionService_ExtensionUpdated; - this.editorSession.ExtensionService.CommandRemoved += ExtensionService_ExtensionRemoved; - - // Create the IEditorOperations implementation - this.editorOperations = - new LanguageServerEditorOperations( - this.editorSession, - this); - - // Always send console prompts through the UI in the language service - // TODO: This will change later once we have a general REPL available - // in VS Code. - this.editorSession.ConsoleService.PushPromptHandlerContext( - new ProtocolPromptHandlerContext( - this, - this.editorSession.ConsoleService)); - - // Set up the output debouncer to throttle output event writes - this.outputDebouncer = new OutputDebouncer(this); -#endif - } - -protected async Task HandleInitializeRequest( - InitializeRequest initializeParams, - RequestContext requestContext) - { - // Grab the workspace path from the parameters - //editorSession.Workspace.WorkspacePath = initializeParams.RootPath; - - await requestContext.SendResult( - new InitializeResult - { - Capabilities = new ServerCapabilities - { - TextDocumentSync = TextDocumentSyncKind.Incremental, - DefinitionProvider = true, - ReferencesProvider = true, - DocumentHighlightProvider = true, - DocumentSymbolProvider = true, - WorkspaceSymbolProvider = true, - HoverProvider = true, - CompletionProvider = new CompletionOptions - { - ResolveProvider = true, - TriggerCharacters = new string[] { ".", "-", ":", "\\" } - }, - SignatureHelpProvider = new SignatureHelpOptions - { - TriggerCharacters = new string[] { " " } // TODO: Other characters here? - } - } - }); } protected override void Initialize() { // Register all supported message types - this.SetRequestHandler(InitializeRequest.Type, this.HandleInitializeRequest); + this.SetEventHandler(DidChangeTextDocumentNotification.Type, this.HandleDidChangeTextDocumentNotification); + this.SetEventHandler(DidOpenTextDocumentNotification.Type, this.HandleDidOpenTextDocumentNotification); + this.SetEventHandler(DidCloseTextDocumentNotification.Type, this.HandleDidCloseTextDocumentNotification); + this.SetEventHandler(DidChangeConfigurationNotification.Type, this.HandleDidChangeConfigurationNotification); - // this.SetEventHandler(DidOpenTextDocumentNotification.Type, this.HandleDidOpenTextDocumentNotification); - // this.SetEventHandler(DidCloseTextDocumentNotification.Type, this.HandleDidCloseTextDocumentNotification); - // this.SetEventHandler(DidChangeTextDocumentNotification.Type, this.HandleDidChangeTextDocumentNotification); - // this.SetEventHandler(DidChangeConfigurationNotification.Type, this.HandleDidChangeConfigurationNotification); - - // this.SetRequestHandler(DefinitionRequest.Type, this.HandleDefinitionRequest); - // this.SetRequestHandler(ReferencesRequest.Type, this.HandleReferencesRequest); - // this.SetRequestHandler(CompletionRequest.Type, this.HandleCompletionRequest); - // this.SetRequestHandler(CompletionResolveRequest.Type, this.HandleCompletionResolveRequest); - // this.SetRequestHandler(SignatureHelpRequest.Type, this.HandleSignatureHelpRequest); - // this.SetRequestHandler(DocumentHighlightRequest.Type, this.HandleDocumentHighlightRequest); - // this.SetRequestHandler(HoverRequest.Type, this.HandleHoverRequest); - // this.SetRequestHandler(DocumentSymbolRequest.Type, this.HandleDocumentSymbolRequest); - // this.SetRequestHandler(WorkspaceSymbolRequest.Type, this.HandleWorkspaceSymbolRequest); - - // this.SetRequestHandler(ShowOnlineHelpRequest.Type, this.HandleShowOnlineHelpRequest); - // this.SetRequestHandler(ExpandAliasRequest.Type, this.HandleExpandAliasRequest); - - // this.SetRequestHandler(FindModuleRequest.Type, this.HandleFindModuleRequest); - // this.SetRequestHandler(InstallModuleRequest.Type, this.HandleInstallModuleRequest); - - // this.SetRequestHandler(InvokeExtensionCommandRequest.Type, this.HandleInvokeExtensionCommandRequest); - - // this.SetRequestHandler(DebugAdapterMessages.EvaluateRequest.Type, this.HandleEvaluateRequest); - -#if false - // Initialize the extension service - // TODO: This should be made awaited once Initialize is async! - this.editorSession.ExtensionService.Initialize( - this.editorOperations).Wait(); -#endif + this.SetRequestHandler(DefinitionRequest.Type, this.HandleDefinitionRequest); + this.SetRequestHandler(ReferencesRequest.Type, this.HandleReferencesRequest); + this.SetRequestHandler(CompletionRequest.Type, this.HandleCompletionRequest); + this.SetRequestHandler(CompletionResolveRequest.Type, this.HandleCompletionResolveRequest); + this.SetRequestHandler(SignatureHelpRequest.Type, this.HandleSignatureHelpRequest); + this.SetRequestHandler(DocumentHighlightRequest.Type, this.HandleDocumentHighlightRequest); + this.SetRequestHandler(HoverRequest.Type, this.HandleHoverRequest); + this.SetRequestHandler(DocumentSymbolRequest.Type, this.HandleDocumentSymbolRequest); + this.SetRequestHandler(WorkspaceSymbolRequest.Type, this.HandleWorkspaceSymbolRequest); } -#if false protected override async Task Shutdown() { - // Make sure remaining output is flushed before exiting - await this.outputDebouncer.Flush(); - - //Logger.Write(LogLevel.Normal, "Language service is shutting down..."); + Logger.Write(LogLevel.Normal, "Language service is shutting down..."); if (this.editorSession != null) { this.editorSession.Dispose(); this.editorSession = null; } - } - #region Built-in Message Handlers + await Task.FromResult(true); + } protected async Task HandleInitializeRequest( InitializeRequest initializeParams, RequestContext requestContext) { + Logger.Write(LogLevel.Normal, "HandleDidChangeTextDocumentNotification"); + // Grab the workspace path from the parameters //editorSession.Workspace.WorkspacePath = initializeParams.RootPath; @@ -195,185 +94,62 @@ protected async Task HandleInitializeRequest( }); } - protected async Task HandleShowOnlineHelpRequest( - string helpParams, - RequestContext requestContext) + /// + /// Handles text document change events + /// + /// + /// + /// + protected Task HandleDidChangeTextDocumentNotification( + DidChangeTextDocumentParams textChangeParams, + EventContext eventContext) { - if (helpParams == null) { helpParams = "get-help"; } + StringBuilder msg = new StringBuilder(); + msg.Append("HandleDidChangeTextDocumentNotification"); + List changedFiles = new List(); - var psCommand = new PSCommand(); - psCommand.AddCommand("Get-Help"); - psCommand.AddArgument(helpParams); - psCommand.AddParameter("Online"); - - await editorSession.SqlToolsContext.ExecuteCommand(psCommand); - - await requestContext.SendResult(null); - } - - private async Task HandleInstallModuleRequest( - string moduleName, - RequestContext requestContext - ) - { - var script = string.Format("Install-Module -Name {0} -Scope CurrentUser", moduleName); - - var executeTask = - editorSession.SqlToolsContext.ExecuteScriptString( - script, - true, - true).ConfigureAwait(false); - - await requestContext.SendResult(null); - } - - private Task HandleInvokeExtensionCommandRequest( - InvokeExtensionCommandRequest commandDetails, - RequestContext requestContext) - { - // We don't await the result of the execution here because we want - // to be able to receive further messages while the editor command - // is executing. This important in cases where the pipeline thread - // gets blocked by something in the script like a prompt to the user. - EditorContext editorContext = - this.editorOperations.ConvertClientEditorContext( - commandDetails.Context); - - Task commandTask = - this.editorSession.ExtensionService.InvokeCommand( - commandDetails.Name, - editorContext); - - commandTask.ContinueWith(t => + // A text change notification can batch multiple change requests + foreach (var textChange in textChangeParams.ContentChanges) { - return requestContext.SendResult(null); - }); + string fileUri = textChangeParams.TextDocument.Uri; + msg.AppendLine(); + msg.Append(" File: "); + msg.Append(fileUri); - return Task.FromResult(true); - } + ScriptFile changedFile = editorSession.Workspace.GetFile(fileUri); - private async Task HandleExpandAliasRequest( - string content, - RequestContext requestContext) - { - var script = @" -function __Expand-Alias { + // changedFile.ApplyChange( + // GetFileChangeDetails( + // textChange.Range.Value, + // textChange.Text)); - param($targetScript) - - [ref]$errors=$null - - $tokens = [System.Management.Automation.PsParser]::Tokenize($targetScript, $errors).Where({$_.type -eq 'command'}) | - Sort Start -Descending - - foreach ($token in $tokens) { - $definition=(Get-Command ('`'+$token.Content) -CommandType Alias -ErrorAction SilentlyContinue).Definition - - if($definition) { - $lhs=$targetScript.Substring(0, $token.Start) - $rhs=$targetScript.Substring($token.Start + $token.Length) - - $targetScript=$lhs + $definition + $rhs - } - } - - $targetScript -}"; - var psCommand = new PSCommand(); - psCommand.AddScript(script); - await this.editorSession.SqlToolsContext.ExecuteCommand(psCommand); - - psCommand = new PSCommand(); - psCommand.AddCommand("__Expand-Alias").AddArgument(content); - var result = await this.editorSession.SqlToolsContext.ExecuteCommand(psCommand); - - await requestContext.SendResult(result.First().ToString()); - } - - private async Task HandleFindModuleRequest( - object param, - RequestContext requestContext) - { - var psCommand = new PSCommand(); - psCommand.AddScript("Find-Module | Select Name, Description"); - - var modules = await editorSession.SqlToolsContext.ExecuteCommand(psCommand); - - var moduleList = new List(); - - if (modules != null) - { - foreach (dynamic m in modules) - { - moduleList.Add(new PSModuleMessage { Name = m.Name, Description = m.Description }); - } + // changedFiles.Add(changedFile); } - await requestContext.SendResult(moduleList); + Logger.Write(LogLevel.Normal, msg.ToString()); + + // // TODO: Get all recently edited files in the workspace + // this.RunScriptDiagnostics( + // changedFiles.ToArray(), + // editorSession, + // eventContext); + + return Task.FromResult(true); } protected Task HandleDidOpenTextDocumentNotification( DidOpenTextDocumentNotification openParams, EventContext eventContext) { - ScriptFile openedFile = - editorSession.Workspace.GetFileBuffer( - openParams.Uri, - openParams.Text); - - // TODO: Get all recently edited files in the workspace - this.RunScriptDiagnostics( - new ScriptFile[] { openedFile }, - editorSession, - eventContext); - - Logger.Write(LogLevel.Verbose, "Finished opening document."); - + Logger.Write(LogLevel.Normal, "HandleDidOpenTextDocumentNotification"); return Task.FromResult(true); } - protected Task HandleDidCloseTextDocumentNotification( + protected Task HandleDidCloseTextDocumentNotification( TextDocumentIdentifier closeParams, EventContext eventContext) { - // Find and close the file in the current session - var fileToClose = editorSession.Workspace.GetFile(closeParams.Uri); - - if (fileToClose != null) - { - editorSession.Workspace.CloseFile(fileToClose); - } - - Logger.Write(LogLevel.Verbose, "Finished closing document."); - - return Task.FromResult(true); - } - - protected Task HandleDidChangeTextDocumentNotification( - DidChangeTextDocumentParams textChangeParams, - EventContext eventContext) - { - List changedFiles = new List(); - - // A text change notification can batch multiple change requests - foreach (var textChange in textChangeParams.ContentChanges) - { - ScriptFile changedFile = editorSession.Workspace.GetFile(textChangeParams.Uri); - - changedFile.ApplyChange( - GetFileChangeDetails( - textChange.Range.Value, - textChange.Text)); - - changedFiles.Add(changedFile); - } - - // TODO: Get all recently edited files in the workspace - this.RunScriptDiagnostics( - changedFiles.ToArray(), - editorSession, - eventContext); - + Logger.Write(LogLevel.Normal, "HandleDidCloseTextDocumentNotification"); return Task.FromResult(true); } @@ -381,882 +157,80 @@ function __Expand-Alias { DidChangeConfigurationParams configChangeParams, EventContext eventContext) { - bool oldLoadProfiles = this.currentSettings.EnableProfileLoading; - bool oldScriptAnalysisEnabled = - this.currentSettings.ScriptAnalysis.Enable.HasValue; - string oldScriptAnalysisSettingsPath = - this.currentSettings.ScriptAnalysis.SettingsPath; - - this.currentSettings.Update( - configChangeParams.Settings.SqlTools, - this.editorSession.Workspace.WorkspacePath); - - if (!this.profilesLoaded && - this.currentSettings.EnableProfileLoading && - oldLoadProfiles != this.currentSettings.EnableProfileLoading) - { - await this.editorSession.SqlToolsContext.LoadHostProfiles(); - this.profilesLoaded = true; - } - - // If there is a new settings file path, restart the analyzer with the new settigs. - bool settingsPathChanged = false; - string newSettingsPath = this.currentSettings.ScriptAnalysis.SettingsPath; - if (!string.Equals(oldScriptAnalysisSettingsPath, newSettingsPath, StringComparison.OrdinalIgnoreCase)) - { - this.editorSession.RestartAnalysisService(newSettingsPath); - settingsPathChanged = true; - } - - // If script analysis settings have changed we need to clear & possibly update the current diagnostic records. - if ((oldScriptAnalysisEnabled != this.currentSettings.ScriptAnalysis.Enable) || settingsPathChanged) - { - // If the user just turned off script analysis or changed the settings path, send a diagnostics - // event to clear the analysis markers that they already have. - if (!this.currentSettings.ScriptAnalysis.Enable.Value || settingsPathChanged) - { - ScriptFileMarker[] emptyAnalysisDiagnostics = new ScriptFileMarker[0]; - - foreach (var scriptFile in editorSession.Workspace.GetOpenedFiles()) - { - await PublishScriptDiagnostics( - scriptFile, - emptyAnalysisDiagnostics, - eventContext); - } - } - - // If script analysis is enabled and the settings file changed get new diagnostic records. - if (this.currentSettings.ScriptAnalysis.Enable.Value && settingsPathChanged) - { - await this.RunScriptDiagnostics( - this.editorSession.Workspace.GetOpenedFiles(), - this.editorSession, - eventContext); - } - } + Logger.Write(LogLevel.Normal, "HandleDidChangeConfigurationNotification"); + await Task.FromResult(true); } protected async Task HandleDefinitionRequest( TextDocumentPosition textDocumentPosition, RequestContext requestContext) { - ScriptFile scriptFile = - editorSession.Workspace.GetFile( - textDocumentPosition.Uri); - - SymbolReference foundSymbol = - editorSession.LanguageService.FindSymbolAtLocation( - scriptFile, - textDocumentPosition.Position.Line + 1, - textDocumentPosition.Position.Character + 1); - - List definitionLocations = new List(); - - GetDefinitionResult definition = null; - if (foundSymbol != null) - { - definition = - await editorSession.LanguageService.GetDefinitionOfSymbol( - scriptFile, - foundSymbol, - editorSession.Workspace); - - if (definition != null) - { - definitionLocations.Add( - new Location - { - Uri = new Uri(definition.FoundDefinition.FilePath).AbsoluteUri, - Range = GetRangeFromScriptRegion(definition.FoundDefinition.ScriptRegion) - }); - } - } - - await requestContext.SendResult(definitionLocations.ToArray()); + Logger.Write(LogLevel.Normal, "HandleDefinitionRequest"); + await Task.FromResult(true); } protected async Task HandleReferencesRequest( ReferencesParams referencesParams, RequestContext requestContext) { - ScriptFile scriptFile = - editorSession.Workspace.GetFile( - referencesParams.Uri); - - SymbolReference foundSymbol = - editorSession.LanguageService.FindSymbolAtLocation( - scriptFile, - referencesParams.Position.Line + 1, - referencesParams.Position.Character + 1); - - FindReferencesResult referencesResult = - await editorSession.LanguageService.FindReferencesOfSymbol( - foundSymbol, - editorSession.Workspace.ExpandScriptReferences(scriptFile)); - - Location[] referenceLocations = null; - - if (referencesResult != null) - { - referenceLocations = - referencesResult - .FoundReferences - .Select(r => - { - return new Location - { - Uri = new Uri(r.FilePath).AbsoluteUri, - Range = GetRangeFromScriptRegion(r.ScriptRegion) - }; - }) - .ToArray(); - } - else - { - referenceLocations = new Location[0]; - } - - await requestContext.SendResult(referenceLocations); + Logger.Write(LogLevel.Normal, "HandleReferencesRequest"); + await Task.FromResult(true); } protected async Task HandleCompletionRequest( TextDocumentPosition textDocumentPosition, RequestContext requestContext) { - int cursorLine = textDocumentPosition.Position.Line + 1; - int cursorColumn = textDocumentPosition.Position.Character + 1; - - ScriptFile scriptFile = - editorSession.Workspace.GetFile( - textDocumentPosition.Uri); - - CompletionResults completionResults = - await editorSession.LanguageService.GetCompletionsInFile( - scriptFile, - cursorLine, - cursorColumn); - - CompletionItem[] completionItems = null; - - if (completionResults != null) - { - int sortIndex = 1; - completionItems = - completionResults - .Completions - .Select( - c => CreateCompletionItem( - c, - completionResults.ReplacedRange, - sortIndex++)) - .ToArray(); - } - else - { - completionItems = new CompletionItem[0]; - } - - await requestContext.SendResult(completionItems); + Logger.Write(LogLevel.Normal, "HandleCompletionRequest"); + await Task.FromResult(true); } protected async Task HandleCompletionResolveRequest( CompletionItem completionItem, RequestContext requestContext) { - if (completionItem.Kind == CompletionItemKind.Function) - { - // Get the documentation for the function - CommandInfo commandInfo = - await CommandHelpers.GetCommandInfo( - completionItem.Label, - this.editorSession.SqlToolsContext); - - completionItem.Documentation = - await CommandHelpers.GetCommandSynopsis( - commandInfo, - this.editorSession.SqlToolsContext); - } - - // Send back the updated CompletionItem - await requestContext.SendResult(completionItem); + Logger.Write(LogLevel.Normal, "HandleCompletionResolveRequest"); + await Task.FromResult(true); } protected async Task HandleSignatureHelpRequest( TextDocumentPosition textDocumentPosition, RequestContext requestContext) { - ScriptFile scriptFile = - editorSession.Workspace.GetFile( - textDocumentPosition.Uri); - - ParameterSetSignatures parameterSets = - await editorSession.LanguageService.FindParameterSetsInFile( - scriptFile, - textDocumentPosition.Position.Line + 1, - textDocumentPosition.Position.Character + 1); - - SignatureInformation[] signatures = null; - int? activeParameter = null; - int? activeSignature = 0; - - if (parameterSets != null) - { - signatures = - parameterSets - .Signatures - .Select(s => - { - return new SignatureInformation - { - Label = parameterSets.CommandName + " " + s.SignatureText, - Documentation = null, - Parameters = - s.Parameters - .Select(CreateParameterInfo) - .ToArray() - }; - }) - .ToArray(); - } - else - { - signatures = new SignatureInformation[0]; - } - - await requestContext.SendResult( - new SignatureHelp - { - Signatures = signatures, - ActiveParameter = activeParameter, - ActiveSignature = activeSignature - }); + Logger.Write(LogLevel.Normal, "HandleSignatureHelpRequest"); + await Task.FromResult(true); } protected async Task HandleDocumentHighlightRequest( TextDocumentPosition textDocumentPosition, RequestContext requestContext) { - ScriptFile scriptFile = - editorSession.Workspace.GetFile( - textDocumentPosition.Uri); - - FindOccurrencesResult occurrencesResult = - editorSession.LanguageService.FindOccurrencesInFile( - scriptFile, - textDocumentPosition.Position.Line + 1, - textDocumentPosition.Position.Character + 1); - - DocumentHighlight[] documentHighlights = null; - - if (occurrencesResult != null) - { - documentHighlights = - occurrencesResult - .FoundOccurrences - .Select(o => - { - return new DocumentHighlight - { - Kind = DocumentHighlightKind.Write, // TODO: Which symbol types are writable? - Range = GetRangeFromScriptRegion(o.ScriptRegion) - }; - }) - .ToArray(); - } - else - { - documentHighlights = new DocumentHighlight[0]; - } - - await requestContext.SendResult(documentHighlights); + Logger.Write(LogLevel.Normal, "HandleDocumentHighlightRequest"); + await Task.FromResult(true); } protected async Task HandleHoverRequest( TextDocumentPosition textDocumentPosition, RequestContext requestContext) { - ScriptFile scriptFile = - editorSession.Workspace.GetFile( - textDocumentPosition.Uri); - - SymbolDetails symbolDetails = - await editorSession - .LanguageService - .FindSymbolDetailsAtLocation( - scriptFile, - textDocumentPosition.Position.Line + 1, - textDocumentPosition.Position.Character + 1); - - List symbolInfo = new List(); - Range? symbolRange = null; - - if (symbolDetails != null) - { - symbolInfo.Add( - new MarkedString - { - Language = "SqlTools", - Value = symbolDetails.DisplayString - }); - - if (!string.IsNullOrEmpty(symbolDetails.Documentation)) - { - symbolInfo.Add( - new MarkedString - { - Language = "markdown", - Value = symbolDetails.Documentation - }); - } - - symbolRange = GetRangeFromScriptRegion(symbolDetails.SymbolReference.ScriptRegion); - } - - await requestContext.SendResult( - new Hover - { - Contents = symbolInfo.ToArray(), - Range = symbolRange - }); + Logger.Write(LogLevel.Normal, "HandleHoverRequest"); + await Task.FromResult(true); } protected async Task HandleDocumentSymbolRequest( TextDocumentIdentifier textDocumentIdentifier, RequestContext requestContext) { - ScriptFile scriptFile = - editorSession.Workspace.GetFile( - textDocumentIdentifier.Uri); - - FindOccurrencesResult foundSymbols = - editorSession.LanguageService.FindSymbolsInFile( - scriptFile); - - SymbolInformation[] symbols = null; - - string containerName = Path.GetFileNameWithoutExtension(scriptFile.FilePath); - - if (foundSymbols != null) - { - symbols = - foundSymbols - .FoundOccurrences - .Select(r => - { - return new SymbolInformation - { - ContainerName = containerName, - Kind = GetSymbolKind(r.SymbolType), - Location = new Location - { - Uri = new Uri(r.FilePath).AbsolutePath, - Range = GetRangeFromScriptRegion(r.ScriptRegion) - }, - Name = GetDecoratedSymbolName(r) - }; - }) - .ToArray(); - } - else - { - symbols = new SymbolInformation[0]; - } - - await requestContext.SendResult(symbols); - } - - - private SymbolKind GetSymbolKind(SymbolType symbolType) - { - switch (symbolType) - { - case SymbolType.Configuration: - case SymbolType.Function: - case SymbolType.Workflow: - return SymbolKind.Function; - - default: - return SymbolKind.Variable; - } - } - - - private string GetDecoratedSymbolName(SymbolReference symbolReference) - { - string name = symbolReference.SymbolName; - - if (symbolReference.SymbolType == SymbolType.Configuration || - symbolReference.SymbolType == SymbolType.Function || - symbolReference.SymbolType == SymbolType.Workflow) - { - name += " { }"; - } - - return name; + Logger.Write(LogLevel.Normal, "HandleDocumentSymbolRequest"); + await Task.FromResult(true); } protected async Task HandleWorkspaceSymbolRequest( WorkspaceSymbolParams workspaceSymbolParams, RequestContext requestContext) { - var symbols = new List(); - - foreach (ScriptFile scriptFile in editorSession.Workspace.GetOpenedFiles()) - { - FindOccurrencesResult foundSymbols = - editorSession.LanguageService.FindSymbolsInFile( - scriptFile); - - // TODO: Need to compute a relative path that is based on common path for all workspace files - string containerName = Path.GetFileNameWithoutExtension(scriptFile.FilePath); - - if (foundSymbols != null) - { - var matchedSymbols = - foundSymbols - .FoundOccurrences - .Where(r => IsQueryMatch(workspaceSymbolParams.Query, r.SymbolName)) - .Select(r => - { - return new SymbolInformation - { - ContainerName = containerName, - Kind = r.SymbolType == SymbolType.Variable ? SymbolKind.Variable : SymbolKind.Function, - Location = new Location - { - Uri = new Uri(r.FilePath).AbsoluteUri, - Range = GetRangeFromScriptRegion(r.ScriptRegion) - }, - Name = GetDecoratedSymbolName(r) - }; - }); - - symbols.AddRange(matchedSymbols); - } - } - - await requestContext.SendResult(symbols.ToArray()); - } - - private bool IsQueryMatch(string query, string symbolName) - { - return symbolName.IndexOf(query, StringComparison.OrdinalIgnoreCase) >= 0; - } - - protected Task HandleEvaluateRequest( - DebugAdapterMessages.EvaluateRequestArguments evaluateParams, - RequestContext requestContext) - { - // We don't await the result of the execution here because we want - // to be able to receive further messages while the current script - // is executing. This important in cases where the pipeline thread - // gets blocked by something in the script like a prompt to the user. - var executeTask = - this.editorSession.SqlToolsContext.ExecuteScriptString( - evaluateParams.Expression, - true, - true); - - // Return the execution result after the task completes so that the - // caller knows when command execution completed. - executeTask.ContinueWith( - (task) => - { - // Return an empty result since the result value is irrelevant - // for this request in the LanguageServer - return - requestContext.SendResult( - new DebugAdapterMessages.EvaluateResponseBody - { - Result = "", - VariablesReference = 0 - }); - }); - - return Task.FromResult(true); - } - - #endregion - - #region Event Handlers - - private async void SqlToolsContext_OutputWritten(object sender, OutputWrittenEventArgs e) - { - // Queue the output for writing - await this.outputDebouncer.Invoke(e); - } - - private async void ExtensionService_ExtensionAdded(object sender, EditorCommand e) - { - await this.SendEvent( - ExtensionCommandAddedNotification.Type, - new ExtensionCommandAddedNotification - { - Name = e.Name, - DisplayName = e.DisplayName - }); - } - - private async void ExtensionService_ExtensionUpdated(object sender, EditorCommand e) - { - await this.SendEvent( - ExtensionCommandUpdatedNotification.Type, - new ExtensionCommandUpdatedNotification - { - Name = e.Name, - }); - } - - private async void ExtensionService_ExtensionRemoved(object sender, EditorCommand e) - { - await this.SendEvent( - ExtensionCommandRemovedNotification.Type, - new ExtensionCommandRemovedNotification - { - Name = e.Name, - }); - } - - - #endregion -#endif - #region Helper Methods - - private static Range GetRangeFromScriptRegion(ScriptRegion scriptRegion) - { - return new Range - { - Start = new Position - { - Line = scriptRegion.StartLineNumber - 1, - Character = scriptRegion.StartColumnNumber - 1 - }, - End = new Position - { - Line = scriptRegion.EndLineNumber - 1, - Character = scriptRegion.EndColumnNumber - 1 - } - }; - } - - private static FileChange GetFileChangeDetails(Range changeRange, string insertString) - { - // The protocol's positions are zero-based so add 1 to all offsets - - return new FileChange - { - InsertString = insertString, - Line = changeRange.Start.Line + 1, - Offset = changeRange.Start.Character + 1, - EndLine = changeRange.End.Line + 1, - EndOffset = changeRange.End.Character + 1 - }; - } - -#if false - private Task RunScriptDiagnostics( - ScriptFile[] filesToAnalyze, - EditorSession editorSession, - EventContext eventContext) - { - if (!this.currentSettings.ScriptAnalysis.Enable.Value) - { - // If the user has disabled script analysis, skip it entirely - return Task.FromResult(true); - } - - // If there's an existing task, attempt to cancel it - try - { - if (existingRequestCancellation != null) - { - // Try to cancel the request - existingRequestCancellation.Cancel(); - - // If cancellation didn't throw an exception, - // clean up the existing token - existingRequestCancellation.Dispose(); - existingRequestCancellation = null; - } - } - catch (Exception e) - { - // TODO: Catch a more specific exception! - Logger.Write( - LogLevel.Error, - string.Format( - "Exception while cancelling analysis task:\n\n{0}", - e.ToString())); - - TaskCompletionSource cancelTask = new TaskCompletionSource(); - cancelTask.SetCanceled(); - return cancelTask.Task; - } - - // Create a fresh cancellation token and then start the task. - // We create this on a different TaskScheduler so that we - // don't block the main message loop thread. - // TODO: Is there a better way to do this? - existingRequestCancellation = new CancellationTokenSource(); - Task.Factory.StartNew( - () => - DelayThenInvokeDiagnostics( - 750, - filesToAnalyze, - editorSession, - eventContext, - existingRequestCancellation.Token), - CancellationToken.None, - TaskCreationOptions.None, - TaskScheduler.Default); - - return Task.FromResult(true); - } - - private static async Task DelayThenInvokeDiagnostics( - int delayMilliseconds, - ScriptFile[] filesToAnalyze, - EditorSession editorSession, - EventContext eventContext, - CancellationToken cancellationToken) - { - // First of all, wait for the desired delay period before - // analyzing the provided list of files - try - { - await Task.Delay(delayMilliseconds, cancellationToken); - } - catch (TaskCanceledException) - { - // If the task is cancelled, exit directly - return; - } - - // If we've made it past the delay period then we don't care - // about the cancellation token anymore. This could happen - // when the user stops typing for long enough that the delay - // period ends but then starts typing while analysis is going - // on. It makes sense to send back the results from the first - // delay period while the second one is ticking away. - - // Get the requested files - foreach (ScriptFile scriptFile in filesToAnalyze) - { - ScriptFileMarker[] semanticMarkers = null; - if (editorSession.AnalysisService != null) - { - Logger.Write(LogLevel.Verbose, "Analyzing script file: " + scriptFile.FilePath); - - semanticMarkers = - editorSession.AnalysisService.GetSemanticMarkers( - scriptFile); - - Logger.Write(LogLevel.Verbose, "Analysis complete."); - } - else - { - // Semantic markers aren't available if the AnalysisService - // isn't available - semanticMarkers = new ScriptFileMarker[0]; - } - - var allMarkers = scriptFile.SyntaxMarkers.Concat(semanticMarkers); - - await PublishScriptDiagnostics( - scriptFile, - semanticMarkers, - eventContext); - } - } - - - private static async Task PublishScriptDiagnostics( - ScriptFile scriptFile, - ScriptFileMarker[] semanticMarkers, - EventContext eventContext) - { - var allMarkers = scriptFile.SyntaxMarkers.Concat(semanticMarkers); - - // Always send syntax and semantic errors. We want to - // make sure no out-of-date markers are being displayed. - await eventContext.SendEvent( - PublishDiagnosticsNotification.Type, - new PublishDiagnosticsNotification - { - Uri = scriptFile.ClientFilePath, - Diagnostics = - allMarkers - .Select(GetDiagnosticFromMarker) - .ToArray() - }); - } - - private static Diagnostic GetDiagnosticFromMarker(ScriptFileMarker scriptFileMarker) - { - return new Diagnostic - { - Severity = MapDiagnosticSeverity(scriptFileMarker.Level), - Message = scriptFileMarker.Message, - Range = new Range - { - // TODO: What offsets should I use? - Start = new Position - { - Line = scriptFileMarker.ScriptRegion.StartLineNumber - 1, - Character = scriptFileMarker.ScriptRegion.StartColumnNumber - 1 - }, - End = new Position - { - Line = scriptFileMarker.ScriptRegion.EndLineNumber - 1, - Character = scriptFileMarker.ScriptRegion.EndColumnNumber - 1 - } - } - }; - } - - private static CompletionItemKind MapCompletionKind(CompletionType completionType) - { - switch (completionType) - { - case CompletionType.Command: - return CompletionItemKind.Function; - - case CompletionType.Method: - return CompletionItemKind.Method; - - case CompletionType.Variable: - case CompletionType.ParameterName: - return CompletionItemKind.Variable; - - case CompletionType.Path: - return CompletionItemKind.File; - - default: - return CompletionItemKind.Text; - } - } - - private static CompletionItem CreateCompletionItem( - CompletionDetails completionDetails, - BufferRange completionRange, - int sortIndex) - { - string detailString = null; - string documentationString = null; - - if ((completionDetails.CompletionType == CompletionType.Variable) || - (completionDetails.CompletionType == CompletionType.ParameterName)) - { - // Look for type encoded in the tooltip for parameters and variables. - // Display SqlTools type names in [] to be consistent with SqlTools syntax - // and now the debugger displays type names. - var matches = Regex.Matches(completionDetails.ToolTipText, @"^(\[.+\])"); - if ((matches.Count > 0) && (matches[0].Groups.Count > 1)) - { - detailString = matches[0].Groups[1].Value; - } - } - else if ((completionDetails.CompletionType == CompletionType.Method) || - (completionDetails.CompletionType == CompletionType.Property)) - { - // We have a raw signature for .NET members, heck let's display it. It's - // better than nothing. - documentationString = completionDetails.ToolTipText; - } - else if (completionDetails.CompletionType == CompletionType.Command) - { - // For Commands, let's extract the resolved command or the path for an exe - // from the ToolTipText - if there is any ToolTipText. - if (completionDetails.ToolTipText != null) - { - // Fix for #240 - notepad++.exe in tooltip text caused regex parser to throw. - string escapedToolTipText = Regex.Escape(completionDetails.ToolTipText); - - // Don't display ToolTipText if it is the same as the ListItemText. - // Reject command syntax ToolTipText - it's too much to display as a detailString. - if (!completionDetails.ListItemText.Equals( - completionDetails.ToolTipText, - StringComparison.OrdinalIgnoreCase) && - !Regex.IsMatch(completionDetails.ToolTipText, - @"^\s*" + escapedToolTipText + @"\s+\[")) - { - detailString = completionDetails.ToolTipText; - } - } - } - - // We want a special "sort order" for parameters that is not lexicographical. - // Fortunately, SqlTools returns parameters in the preferred sort order by - // default (with common params at the end). We just need to make sure the default - // order also be the lexicographical order which we do by prefixig the ListItemText - // with a leading 0's four digit index. This would not sort correctly for a list - // > 999 parameters but surely we won't have so many items in the "parameter name" - // completion list. Technically we don't need the ListItemText at all but it may come - // in handy during debug. - var sortText = (completionDetails.CompletionType == CompletionType.ParameterName) - ? $"{sortIndex:D3}{completionDetails.ListItemText}" - : null; - - return new CompletionItem - { - InsertText = completionDetails.CompletionText, - Label = completionDetails.ListItemText, - Kind = MapCompletionKind(completionDetails.CompletionType), - Detail = detailString, - Documentation = documentationString, - SortText = sortText, - TextEdit = new TextEdit - { - NewText = completionDetails.CompletionText, - Range = new Range - { - Start = new Position - { - Line = completionRange.Start.Line - 1, - Character = completionRange.Start.Column - 1 - }, - End = new Position - { - Line = completionRange.End.Line - 1, - Character = completionRange.End.Column - 1 - } - } - } - }; - } -#endif - - private static DiagnosticSeverity MapDiagnosticSeverity(ScriptFileMarkerLevel markerLevel) - { - switch (markerLevel) - { - case ScriptFileMarkerLevel.Error: - return DiagnosticSeverity.Error; - - case ScriptFileMarkerLevel.Warning: - return DiagnosticSeverity.Warning; - - case ScriptFileMarkerLevel.Information: - return DiagnosticSeverity.Information; - - default: - return DiagnosticSeverity.Error; - } - } - -#if false - private static ParameterInformation CreateParameterInfo(ParameterInfo parameterInfo) - { - return new ParameterInformation - { - Label = parameterInfo.Name, - Documentation = string.Empty - }; - } -#endif - - #endregion + Logger.Write(LogLevel.Normal, "HandleWorkspaceSymbolRequest"); + await Task.FromResult(true); + } } } - diff --git a/ServiceHost/Server/LanguageServerSettings.cs b/ServiceHost/Server/LanguageServerSettings.cs index 5e9421b6..be09984a 100644 --- a/ServiceHost/Server/LanguageServerSettings.cs +++ b/ServiceHost/Server/LanguageServerSettings.cs @@ -28,6 +28,7 @@ namespace Microsoft.SqlTools.EditorServices.Protocol.Server } } } + public class ScriptAnalysisSettings { @@ -77,6 +78,7 @@ namespace Microsoft.SqlTools.EditorServices.Protocol.Server } } + public class LanguageServerSettingsWrapper { // NOTE: This property is capitalized as 'SqlTools' because the diff --git a/ServiceHost/Server/OutputDebouncer.cs b/ServiceHost/Server/OutputDebouncer.cs deleted file mode 100644 index d80673f7..00000000 --- a/ServiceHost/Server/OutputDebouncer.cs +++ /dev/null @@ -1,102 +0,0 @@ -// -// Copyright (c) Microsoft. All rights reserved. -// Licensed under the MIT license. See LICENSE file in the project root for full license information. -// - -using Microsoft.SqlTools.EditorServices.Protocol.DebugAdapter; -using Microsoft.SqlTools.EditorServices.Protocol.MessageProtocol; -using Microsoft.SqlTools.EditorServices.Utility; -using System.Threading.Tasks; - -namespace Microsoft.SqlTools.EditorServices.Protocol.Server -{ - /// - /// Throttles output written via OutputEvents by batching all output - /// written within a short time window and writing it all out at once. - /// - internal class OutputDebouncer : AsyncDebouncer - { - #region Private Fields - - private IMessageSender messageSender; - private bool currentOutputIsError = false; - private string currentOutputString = null; - - #endregion - - #region Constants - - // Set a really short window for output flushes. This - // gives the appearance of fast output without the crushing - // overhead of sending an OutputEvent for every single line - // written. At this point it seems that around 10-20 lines get - // batched for each flush when Get-Process is called. - public const int OutputFlushInterval = 200; - - #endregion - - #region Constructors - - public OutputDebouncer(IMessageSender messageSender) - : base(OutputFlushInterval, false) - { - this.messageSender = messageSender; - } - - #endregion - - #region Private Methods - - protected override async Task OnInvoke(OutputWrittenEventArgs output) - { - bool outputIsError = output.OutputType == OutputType.Error; - - if (this.currentOutputIsError != outputIsError) - { - if (this.currentOutputString != null) - { - // Flush the output - await this.OnFlush(); - } - - this.currentOutputString = string.Empty; - this.currentOutputIsError = outputIsError; - } - - // Output string could be null if the last output was already flushed - if (this.currentOutputString == null) - { - this.currentOutputString = string.Empty; - } - - // Add to string (and include newline) - this.currentOutputString += - output.OutputText + - (output.IncludeNewLine ? - System.Environment.NewLine : - string.Empty); - } - - protected override async Task OnFlush() - { - // Only flush output if there is some to flush - if (this.currentOutputString != null) - { - // Send an event for the current output - await this.messageSender.SendEvent( - OutputEvent.Type, - new OutputEventBody - { - Output = this.currentOutputString, - Category = (this.currentOutputIsError) ? "stderr" : "stdout" - }); - - // Clear the output string for the next batch - this.currentOutputString = null; - } - } - - #endregion - } -} - diff --git a/ServiceHost/Server/PromptHandlers.cs b/ServiceHost/Server/PromptHandlers.cs deleted file mode 100644 index 7af7a88c..00000000 --- a/ServiceHost/Server/PromptHandlers.cs +++ /dev/null @@ -1,190 +0,0 @@ -// -// Copyright (c) Microsoft. All rights reserved. -// Licensed under the MIT license. See LICENSE file in the project root for full license information. -// - -#if false -using System; -using Microsoft.SqlTools.EditorServices.Console; -using Microsoft.SqlTools.EditorServices.Protocol.Messages; -using Microsoft.SqlTools.EditorServices.Protocol.MessageProtocol; -using Microsoft.SqlTools.EditorServices.Utility; -using System.Threading.Tasks; - -namespace Microsoft.SqlTools.EditorServices.Protocol.Server -{ - internal class ProtocolPromptHandlerContext : IPromptHandlerContext - { - private IMessageSender messageSender; - private ConsoleService consoleService; - - public ProtocolPromptHandlerContext( - IMessageSender messageSender, - ConsoleService consoleService) - { - this.messageSender = messageSender; - this.consoleService = consoleService; - } - - public ChoicePromptHandler GetChoicePromptHandler() - { - return new ProtocolChoicePromptHandler( - this.messageSender, - this.consoleService); - } - - public InputPromptHandler GetInputPromptHandler() - { - return new ProtocolInputPromptHandler( - this.messageSender, - this.consoleService); - } - } - - internal class ProtocolChoicePromptHandler : ChoicePromptHandler - { - private IMessageSender messageSender; - private ConsoleService consoleService; - - public ProtocolChoicePromptHandler( - IMessageSender messageSender, - ConsoleService consoleService) - { - this.messageSender = messageSender; - this.consoleService = consoleService; - } - - protected override void ShowPrompt(PromptStyle promptStyle) - { - messageSender - .SendRequest( - ShowChoicePromptRequest.Type, - new ShowChoicePromptRequest - { - Caption = this.Caption, - Message = this.Message, - Choices = this.Choices, - DefaultChoice = this.DefaultChoice - }, true) - .ContinueWith(HandlePromptResponse) - .ConfigureAwait(false); - } - - private void HandlePromptResponse( - Task responseTask) - { - if (responseTask.IsCompleted) - { - ShowChoicePromptResponse response = responseTask.Result; - - if (!response.PromptCancelled) - { - this.consoleService.ReceivePromptResponse( - response.ChosenItem, - false); - } - else - { - // Cancel the current prompt - this.consoleService.SendControlC(); - } - } - else - { - if (responseTask.IsFaulted) - { - // Log the error - Logger.Write( - LogLevel.Error, - "ShowChoicePrompt request failed with error:\r\n{0}", - responseTask.Exception.ToString()); - } - - // Cancel the current prompt - this.consoleService.SendControlC(); - } - } - } - - internal class ProtocolInputPromptHandler : ConsoleInputPromptHandler - { - private IMessageSender messageSender; - private ConsoleService consoleService; - - public ProtocolInputPromptHandler( - IMessageSender messageSender, - ConsoleService consoleService) - : base(consoleService) - { - this.messageSender = messageSender; - this.consoleService = consoleService; - } - - protected override void ShowErrorMessage(Exception e) - { - // Use default behavior for writing the error message - base.ShowErrorMessage(e); - } - - protected override void ShowPromptMessage(string caption, string message) - { - // Use default behavior for writing the prompt message - base.ShowPromptMessage(caption, message); - } - - protected override void ShowFieldPrompt(FieldDetails fieldDetails) - { - // Write the prompt to the console first so that there's a record - // of it occurring - base.ShowFieldPrompt(fieldDetails); - - messageSender - .SendRequest( - ShowInputPromptRequest.Type, - new ShowInputPromptRequest - { - Name = fieldDetails.Name, - Label = fieldDetails.Label - }, true) - .ContinueWith(HandlePromptResponse) - .ConfigureAwait(false); - } - - private void HandlePromptResponse( - Task responseTask) - { - if (responseTask.IsCompleted) - { - ShowInputPromptResponse response = responseTask.Result; - - if (!response.PromptCancelled) - { - this.consoleService.ReceivePromptResponse( - response.ResponseText, - true); - } - else - { - // Cancel the current prompt - this.consoleService.SendControlC(); - } - } - else - { - if (responseTask.IsFaulted) - { - // Log the error - Logger.Write( - LogLevel.Error, - "ShowInputPrompt request failed with error:\r\n{0}", - responseTask.Exception.ToString()); - } - - // Cancel the current prompt - this.consoleService.SendControlC(); - } - } - } -} - -#endif \ No newline at end of file diff --git a/ServiceHost/Session/EditorSession.cs b/ServiceHost/Session/EditorSession.cs index 21c1b577..4b6c9a49 100644 --- a/ServiceHost/Session/EditorSession.cs +++ b/ServiceHost/Session/EditorSession.cs @@ -3,11 +3,8 @@ // Licensed under the MIT license. See LICENSE file in the project root for full license information. // -// using Microsoft.SqlTools.EditorServices.Console; -// using Microsoft.SqlTools.EditorServices.Extensions; +using System; using Microsoft.SqlTools.EditorServices.Session; -// using Microsoft.SqlTools.EditorServices.Utility; -// using System.IO; namespace Microsoft.SqlTools.EditorServices { @@ -15,12 +12,8 @@ namespace Microsoft.SqlTools.EditorServices /// Manages a single session for all editor services. This /// includes managing all open script files for the session. /// - public class EditorSession + public class EditorSession : IDisposable { - public void StartSession(HostDetails hostDetails, ProfilePaths profilePaths) - { - } -#if false #region Properties /// @@ -33,6 +26,59 @@ namespace Microsoft.SqlTools.EditorServices /// public SqlToolsContext SqlToolsContext { get; private set; } + #endregion + + #region Public Methods + + /// + /// Starts the session using the provided IConsoleHost implementation + /// for the ConsoleService. + /// + /// + /// Provides details about the host application. + /// + /// + /// An object containing the profile paths for the session. + /// + public void StartSession(HostDetails hostDetails, ProfilePaths profilePaths) + { + // Initialize all services + this.SqlToolsContext = new SqlToolsContext(hostDetails, profilePaths); + + + // this.LanguageService = new LanguageService(this.SqlToolsContext); + // this.DebugService = new DebugService(this.SqlToolsContext); + // this.ConsoleService = new ConsoleService(this.SqlToolsContext); + // this.ExtensionService = new ExtensionService(this.SqlToolsContext); + + // this.InstantiateAnalysisService(); + + // Create a workspace to contain open files + this.Workspace = new Workspace(this.SqlToolsContext.SqlToolsVersion); + } + + #endregion + + #region IDisposable Implementation + + /// + /// Disposes of any Runspaces that were created for the + /// services used in this session. + /// + public void Dispose() + { + } + + #endregion + + +#if false + #region Properties + + + + + /// /// Gets the LanguageService instance for this session. /// diff --git a/ServiceHost/Session/SqlToolsContext.cs b/ServiceHost/Session/SqlToolsContext.cs new file mode 100644 index 00000000..d8016afd --- /dev/null +++ b/ServiceHost/Session/SqlToolsContext.cs @@ -0,0 +1,25 @@ +// +// Copyright (c) Microsoft. All rights reserved. +// Licensed under the MIT license. See LICENSE file in the project root for full license information. +// + +using System; + +namespace Microsoft.SqlTools.EditorServices.Session +{ + public class SqlToolsContext + { + /// + /// Gets the PowerShell version of the current runspace. + /// + public Version SqlToolsVersion + { + get; private set; + } + + public SqlToolsContext(HostDetails hostDetails, ProfilePaths profilePaths) + { + + } + } +} diff --git a/ServiceHost/Utility/AsyncDebouncer.cs b/ServiceHost/Utility/AsyncDebouncer.cs deleted file mode 100644 index 86d05a2b..00000000 --- a/ServiceHost/Utility/AsyncDebouncer.cs +++ /dev/null @@ -1,169 +0,0 @@ -// -// Copyright (c) Microsoft. All rights reserved. -// Licensed under the MIT license. See LICENSE file in the project root for full license information. -// - -using System.Threading; -using System.Threading.Tasks; - -namespace Microsoft.SqlTools.EditorServices.Utility -{ - /// - /// Restricts the invocation of an operation to a specified time - /// interval. Can also cause previous requests to be cancelled - /// by new requests within that time window. Typically used for - /// buffering information for an operation or ensuring that an - /// operation only runs after some interval. - /// - /// The argument type for the Invoke method. - public abstract class AsyncDebouncer - { - #region Private Fields - - private int flushInterval; - private bool restartOnInvoke; - - private Task currentTimerTask; - private CancellationTokenSource timerCancellationSource; - - private AsyncLock asyncLock = new AsyncLock(); - - #endregion - - #region Public Methods - - /// - /// Creates a new instance of the AsyncDebouncer class with the - /// specified flush interval. If restartOnInvoke is true, any - /// calls to Invoke will cancel previous calls which have not yet - /// passed the flush interval. - /// - /// - /// A millisecond interval to use for flushing prior Invoke calls. - /// - /// - /// If true, Invoke calls will reset prior calls which haven't passed the flush interval. - /// - public AsyncDebouncer(int flushInterval, bool restartOnInvoke) - { - this.flushInterval = flushInterval; - this.restartOnInvoke = restartOnInvoke; - } - - /// - /// Invokes the debouncer with the given input. The debouncer will - /// wait for the specified interval before calling the Flush method - /// to complete the operation. - /// - /// - /// The argument for this implementation's Invoke method. - /// - /// A Task to be awaited until the Invoke is queued. - public async Task Invoke(TInvokeArgs invokeArgument) - { - using (await this.asyncLock.LockAsync()) - { - // Invoke the implementor - await this.OnInvoke(invokeArgument); - - // If there's no timer, start one - if (this.currentTimerTask == null) - { - this.StartTimer(); - } - else if (this.currentTimerTask != null && this.restartOnInvoke) - { - // Restart the existing timer - if (this.CancelTimer()) - { - this.StartTimer(); - } - } - } - } - - /// - /// Flushes the latest state regardless of the current interval. - /// An AsyncDebouncer MUST NOT invoke its own Flush method otherwise - /// deadlocks could occur. - /// - /// A Task to be awaited until Flush completes. - public async Task Flush() - { - using (await this.asyncLock.LockAsync()) - { - // Cancel the current timer - this.CancelTimer(); - - // Flush the current output - await this.OnFlush(); - } - } - - #endregion - - #region Abstract Methods - - /// - /// Implemented by the subclass to take the argument for the - /// future operation that will be performed by OnFlush. - /// - /// - /// The argument for this implementation's OnInvoke method. - /// - /// A Task to be awaited for the invoke to complete. - protected abstract Task OnInvoke(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(); - - #endregion - - #region Private Methods - - private void StartTimer() - { - this.timerCancellationSource = new CancellationTokenSource(); - - this.currentTimerTask = - Task.Delay(this.flushInterval, this.timerCancellationSource.Token) - .ContinueWith( - t => - { - if (!t.IsCanceled) - { - return this.Flush(); - } - else - { - return Task.FromResult(true); - } - }); - } - - private bool CancelTimer() - { - if (this.timerCancellationSource != null) - { - // Attempt to cancel the timer task - this.timerCancellationSource.Cancel(); - } - - // Was the task cancelled? - bool wasCancelled = - this.currentTimerTask == null || - this.currentTimerTask.IsCanceled; - - // Clear the current task so that another may be created - this.currentTimerTask = null; - - return wasCancelled; - } - - #endregion - } -} - diff --git a/ServiceHost/Workspace/ScriptFile.cs b/ServiceHost/Workspace/ScriptFile.cs index c68ecb96..7b041832 100644 --- a/ServiceHost/Workspace/ScriptFile.cs +++ b/ServiceHost/Workspace/ScriptFile.cs @@ -18,6 +18,30 @@ namespace Microsoft.SqlTools.EditorServices /// public class ScriptFile { + public ScriptFile( + string filePath, + string clientFilePath, + TextReader textReader, + Version SqlToolsVersion) + { + } + + /// + /// Creates a new ScriptFile instance with the specified file contents. + /// + /// The path at which the script file resides. + /// The path which the client uses to identify the file. + /// The initial contents of the script file. + /// The version of SqlTools for which the script is being parsed. + public ScriptFile( + string filePath, + string clientFilePath, + string initialBuffer, + Version SqlToolsVersion) + { + } + + #if false #region Private Fields diff --git a/ServiceHost/Workspace/Workspace.cs b/ServiceHost/Workspace/Workspace.cs index b8635ef2..6188a806 100644 --- a/ServiceHost/Workspace/Workspace.cs +++ b/ServiceHost/Workspace/Workspace.cs @@ -6,9 +6,9 @@ using Microsoft.SqlTools.EditorServices.Utility; using System; using System.Collections.Generic; -using System.Linq; using System.IO; using System.Text; +using System.Text.RegularExpressions; namespace Microsoft.SqlTools.EditorServices { @@ -18,8 +18,7 @@ namespace Microsoft.SqlTools.EditorServices /// public class Workspace { -#if false - #region Private Fields + #region Private Fields private Version SqlToolsVersion; private Dictionary workspaceFiles = new Dictionary(); @@ -93,6 +92,70 @@ namespace Microsoft.SqlTools.EditorServices return scriptFile; } + + private string ResolveFilePath(string filePath) + { + if (!IsPathInMemory(filePath)) + { + if (filePath.StartsWith(@"file://")) + { + // Client sent the path in URI format, extract the local path and trim + // any extraneous slashes + Uri fileUri = new Uri(filePath); + filePath = fileUri.LocalPath.TrimStart('/'); + } + + // Some clients send paths with UNIX-style slashes, replace those if necessary + filePath = filePath.Replace('/', '\\'); + + // Clients could specify paths with escaped space, [ and ] characters which .NET APIs + // will not handle. These paths will get appropriately escaped just before being passed + // into the SqlTools engine. + filePath = UnescapePath(filePath); + + // Get the absolute file path + filePath = Path.GetFullPath(filePath); + } + + Logger.Write(LogLevel.Verbose, "Resolved path: " + filePath); + + return filePath; + } + + internal static bool IsPathInMemory(string filePath) + { + // When viewing SqlTools files in the Git diff viewer, VS Code + // sends the contents of the file at HEAD with a URI that starts + // with 'inmemory'. Untitled files which have been marked of + // type SqlTools have a path starting with 'untitled'. + return + filePath.StartsWith("inmemory") || + filePath.StartsWith("untitled"); + } + + /// + /// Unescapes any escaped [, ] or space characters. Typically use this before calling a + /// .NET API that doesn't understand PowerShell escaped chars. + /// + /// The path to unescape. + /// The path with the ` character before [, ] and spaces removed. + public static string UnescapePath(string path) + { + if (!path.Contains("`")) + { + return path; + } + + return Regex.Replace(path, @"`(?=[ \[\]])", ""); + } + + #endregion + +#if false + + + #region Public Methods + /// /// Gets a new ScriptFile instance which is identified by the given file @@ -222,46 +285,6 @@ namespace Microsoft.SqlTools.EditorServices } } - private string ResolveFilePath(string filePath) - { - if (!IsPathInMemory(filePath)) - { - if (filePath.StartsWith(@"file://")) - { - // Client sent the path in URI format, extract the local path and trim - // any extraneous slashes - Uri fileUri = new Uri(filePath); - filePath = fileUri.LocalPath.TrimStart('/'); - } - - // Some clients send paths with UNIX-style slashes, replace those if necessary - filePath = filePath.Replace('/', '\\'); - - // Clients could specify paths with escaped space, [ and ] characters which .NET APIs - // will not handle. These paths will get appropriately escaped just before being passed - // into the SqlTools engine. - filePath = SqlToolsContext.UnescapePath(filePath); - - // Get the absolute file path - filePath = Path.GetFullPath(filePath); - } - - Logger.Write(LogLevel.Verbose, "Resolved path: " + filePath); - - return filePath; - } - - internal static bool IsPathInMemory(string filePath) - { - // When viewing SqlTools files in the Git diff viewer, VS Code - // sends the contents of the file at HEAD with a URI that starts - // with 'inmemory'. Untitled files which have been marked of - // type SqlTools have a path starting with 'untitled'. - return - filePath.StartsWith("inmemory") || - filePath.StartsWith("untitled"); - } - private string GetBaseFilePath(string filePath) { if (IsPathInMemory(filePath)) From 569183134a6c68dbb948fa71c351a05431a7dff1 Mon Sep 17 00:00:00 2001 From: Karl Burtram Date: Sat, 16 Jul 2016 13:06:00 -0700 Subject: [PATCH 2/6] Update README.md --- README.md | 146 ++++++++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 146 insertions(+) diff --git a/README.md b/README.md index 7029280f..534081b2 100644 --- a/README.md +++ b/README.md @@ -4,3 +4,149 @@ The SQL Tools Service is an application that provides core functionality for var * Language Service support using VS Code protocol * Query execution and resultset management * Schema discovery + +# Contribution Guidelines + +We welcome many kinds of community contributions to this project! Whether it's a feature implementation, +bug fix, or a good idea, please create an issue so that we can discuss it. It is not necessary to create an +issue before sending a pull request but it may speed up the process if we can discuss your idea before +you start implementing it. + +Because this project exposes a couple different public APIs, we must be very mindful of any potential breaking +changes. Some contributions may not be accepted if they risk introducing breaking changes or if they +don't match the goals of the project. The core maintainer team has the right of final approval over +any contribution to this project. However, we are very happy to hear community feedback on any decision +so that we can ensure we are solving the right problems in the right way. + +## Ways to Contribute + +- File a bug or feature request as an [issue](https://github.com/Microsoft/sqltoolsservice/issues) +- Comment on existing issues to give your feedback on how they should be fixed/implemented +- Contribute a bug fix or feature implementation by submitting a pull request +- Contribute more unit tests for feature areas that lack good coverage +- Review the pull requests that others submit to ensure they follow [established guidelines] + (#pull-request-guidelines) + +## Code Contribution Guidelines + +Here's a high level list of guidelines to follow to ensure your code contribution is accepted: + +- Follow established guidelines for coding style and design +- Follow established guidelines for commit hygiene +- Write unit tests to validate new features and bug fixes +- Ensure that the 'Release' build and unit tests pass locally +- Ensure that the AppVeyor build passes for your change +- Respond to all review feedback and final commit cleanup + +### Practice Good Commit Hygiene + +First of all, make sure you are practicing [good commit hygiene](http://blog.ericbmerritt.com/2011/09/21/commit-hygiene-and-git.html) +so that your commits provide a good history of the changes you are making. To be more specific: + +- **Write good commit messages** + + Commit messages should be clearly written so that a person can look at the commit log and understand + how and why a given change was made. Here is a great model commit message taken from a [blog post + by Tim Pope](http://tbaggery.com/2008/04/19/a-note-about-git-commit-messages.html): + + Capitalized, short (50 chars or less) summary + + More detailed explanatory text, if necessary. Wrap it to about 72 + characters or so. In some contexts, the first line is treated as the + subject of an email and the rest of the text as the body. The blank + line separating the summary from the body is critical (unless you omit + the body entirely); tools like rebase can get confused if you run the + two together. + + Write your commit message in the imperative: "Fix bug" and not "Fixed bug" + or "Fixes bug." This convention matches up with commit messages generated + by commands like git merge and git revert. + + Further paragraphs come after blank lines. + + - Bullet points are okay, too + + - Typically a hyphen or asterisk is used for the bullet, followed by a + single space, with blank lines in between, but conventions vary here + + - Use a hanging indent + + A change that fixes a known bug with an issue filed should use the proper syntax so that the [issue + is automatically closed](https://help.github.com/articles/closing-issues-via-commit-messages/) once + your change is merged. Here's an example of what such a commit message should look like: + + Fix #3: Catch NullReferenceException from DoThing + + This change adds a try/catch block to catch a NullReferenceException that + gets thrown by DoThing [...] + +- **Squash your commits** + + If you are introducing a new feature but have implemented it over multiple commits, + please [squash those commits](http://gitready.com/advanced/2009/02/10/squashing-commits-with-rebase.html) + into a single commit that contains all the changes in one place. This especially applies to any "oops" + commits where a file is forgotten or a typo is being fixed. Following this approach makes it a lot easier + to pull those changes to other branches or roll back the change if necessary. + +- **Keep individual commits for larger changes** + + You can certainly maintain individual commits for different phases of a big change. For example, if + you want to reorganize some files before adding new functionality, have your first commit contain all + of the file move changes and then the following commit can have all of the feature additions. We + highly recommend this approach so that larger commits don't turn into a jumbled mess. + +### Add Unit Tests for New Code + +If you're adding a new feature to the project, please make sure to include adequate [xUnit](http://xunit.github.io/) +tests with your change. In this project, we have chosen write out unit tests in a way that uses the +actual PowerShell environment rather than extensive interface mocking. This allows us to be sure that +our features will work in practice. + +We do both component-level and scenario-level testing depending on what code is being tested. We don't +expect contributors to test every possible edge case. Testing mainline scenarios and the most common +failure scenarios is often good enough. + +We are very happy to accept unit test contributions for any feature areas that are more error-prone than +others. Also, if you find that a feature fails for you in a specific case, please feel free to file an issue +that includes a unit test which reproduces the problem. This will allow us to quickly implement a fix +that resolves the problem. + +### Build 'Release' Before Submitting + +Before you send out your pull request, make sure that you have run a Release configuration build of the +project and that all new and existing tests are passing. The Release configuration build ensures that +all public API interfaces have been documented correctly otherwise it throws an error. We have turned +on this check so that our project will always have good generated documentation. + +### Follow the Pull Request Process + +- **Create your pull request** + + Use the [typical process](https://help.github.com/articles/using-pull-requests/) to send a pull request + from your fork of the project. In your pull request message, please give a high-level summary of the + changes that you have made so that reviewers understand the intent of the changes. You should receive + initial comments within a day or two, but please feel free to ping if things are taking longer than + expected. + +- **The build and unit tests must run green** + + When you submit your pull request, our automated build system on AppVeyor will attempt to run a + Release build of your changes and then run all unit tests against the build. If you notice that + any of your unit tests have failed, please fix them by creating a new commit and then pushing it + to your branch. If you see that some unrelated test has failed, try re-running the build for your + pull request. If you continue to see issues, write a comment on the pull request and we will + look into it. + +- **Respond to code review feedback** + + If the reviewers ask you to make changes, make them as a new commit to your branch and push them so + that they are made available for a final review pass. Do not rebase the fixes just yet so that the + commit hash changes don't upset GitHub's pull request UI. + +- **If necessary, do a final rebase** + + Once your final changes have been accepted, we may ask you to do a final rebase to have your commits + so that they follow our commit guidelines. If specific guidance is given, please follow it when + rebasing your commits. Once you do your final push and we see the AppVeyor build pass, we will + merge your changes! + From 37d3cebc42efb01438816d3c92d8cef81a3dd0f8 Mon Sep 17 00:00:00 2001 From: Karl Burtram Date: Sun, 17 Jul 2016 12:01:56 -0700 Subject: [PATCH 3/6] Mege dev to master (#6) * Merge master to dev (#4) * Misc. clean-ups related to removing unneeded PowerShell Language Service code. * Remove unneeded files and clean up remaining code. * Enable file change tracking with Workspace and EditorSession. * Merge ServiceHost xUnit test project into dev. (#5) * Setup standard src, test folder structure. Add unit test project. * Actually stage the deletes. Update .gitignore --- .gitignore | 273 +++++++++++++++++- ServiceHost/.vscode/launch.json | 24 -- ServiceHost/.vscode/tasks.json | 14 - global.json | 5 + .../LanguageServer/ClientCapabilities.cs | 0 .../ServiceHost}/LanguageServer/Completion.cs | 0 .../LanguageServer/Configuration.cs | 0 .../ServiceHost}/LanguageServer/Definition.cs | 0 .../LanguageServer/Diagnostics.cs | 0 .../LanguageServer/DocumentHighlight.cs | 0 .../LanguageServer/ExpandAliasRequest.cs | 0 .../LanguageServer/FindModuleRequest.cs | 0 .../ServiceHost}/LanguageServer/Hover.cs | 0 .../ServiceHost}/LanguageServer/Initialize.cs | 0 .../LanguageServer/InstallModuleRequest.cs | 0 .../ServiceHost}/LanguageServer/References.cs | 0 .../LanguageServer/ServerCapabilities.cs | 0 .../LanguageServer/ShowOnlineHelpRequest.cs | 0 .../ServiceHost}/LanguageServer/Shutdown.cs | 0 .../LanguageServer/SignatureHelp.cs | 0 .../LanguageServer/TextDocument.cs | 0 .../LanguageServer/WorkspaceSymbols.cs | 0 .../LanguageSupport/LanguageService.cs | 0 .../MessageProtocol/Channel/ChannelBase.cs | 0 .../Channel/StdioClientChannel.cs | 0 .../Channel/StdioServerChannel.cs | 0 .../ServiceHost}/MessageProtocol/Constants.cs | 0 .../MessageProtocol/EventContext.cs | 0 .../ServiceHost}/MessageProtocol/EventType.cs | 0 .../MessageProtocol/IMessageSender.cs | 0 .../MessageProtocol/IMessageSerializer.cs | 0 .../ServiceHost}/MessageProtocol/Message.cs | 0 .../MessageProtocol/MessageDispatcher.cs | 0 .../MessageProtocol/MessageParseException.cs | 0 .../MessageProtocol/MessageProtocolType.cs | 0 .../MessageProtocol/MessageReader.cs | 0 .../MessageProtocol/MessageWriter.cs | 0 .../MessageProtocol/ProtocolEndpoint.cs | 0 .../MessageProtocol/RequestContext.cs | 0 .../MessageProtocol/RequestType.cs | 0 .../Serializers/JsonRpcMessageSerializer.cs | 0 .../Serializers/V8MessageSerializer.cs | 0 {ServiceHost => src/ServiceHost}/Program.cs | 0 .../ServiceHost}/Properties/AssemblyInfo.cs | 0 .../ServiceHost}/Server/LanguageServer.cs | 0 .../ServiceHost}/Server/LanguageServerBase.cs | 0 .../Server/LanguageServerEditorOperations.cs | 0 .../Server/LanguageServerSettings.cs | 0 .../ServiceHost}/Session/EditorSession.cs | 0 .../ServiceHost}/Session/HostDetails.cs | 0 .../ServiceHost}/Session/OutputType.cs | 0 .../Session/OutputWrittenEventArgs.cs | 0 .../ServiceHost}/Session/ProfilePaths.cs | 0 .../ServiceHost}/Session/SqlToolsContext.cs | 0 .../ServiceHost}/Utility/AsyncContext.cs | 0 .../Utility/AsyncContextThread.cs | 0 .../ServiceHost}/Utility/AsyncLock.cs | 0 .../ServiceHost}/Utility/AsyncQueue.cs | 0 .../ServiceHost}/Utility/Extensions.cs | 0 .../ServiceHost}/Utility/Logger.cs | 0 .../Utility/ThreadSynchronizationContext.cs | 0 .../ServiceHost}/Utility/Validate.cs | 0 .../ServiceHost}/Workspace/BufferPosition.cs | 0 .../ServiceHost}/Workspace/BufferRange.cs | 0 .../ServiceHost}/Workspace/FileChange.cs | 0 .../ServiceHost}/Workspace/FilePosition.cs | 0 .../ServiceHost}/Workspace/ScriptFile.cs | 0 .../Workspace/ScriptFileMarker.cs | 0 .../ServiceHost}/Workspace/ScriptRegion.cs | 0 .../ServiceHost}/Workspace/Workspace.cs | 0 {ServiceHost => src/ServiceHost}/project.json | 2 +- test/ServiceHost.Test/App.config | 9 + .../JsonRpcMessageSerializerTests.cs | 144 +++++++++ .../Message/MessageReaderWriterTests.cs | 177 ++++++++++++ .../Message/TestMessageTypes.cs | 56 ++++ ...erShellEditorServices.Test.Protocol.csproj | 109 +++++++ .../Properties/AssemblyInfo.cs | 42 +++ test/ServiceHost.Test/packages.config | 11 + test/ServiceHost.Test/project.json | 30 ++ 79 files changed, 854 insertions(+), 42 deletions(-) delete mode 100644 ServiceHost/.vscode/launch.json delete mode 100644 ServiceHost/.vscode/tasks.json create mode 100644 global.json rename {ServiceHost => src/ServiceHost}/LanguageServer/ClientCapabilities.cs (100%) rename {ServiceHost => src/ServiceHost}/LanguageServer/Completion.cs (100%) rename {ServiceHost => src/ServiceHost}/LanguageServer/Configuration.cs (100%) rename {ServiceHost => src/ServiceHost}/LanguageServer/Definition.cs (100%) rename {ServiceHost => src/ServiceHost}/LanguageServer/Diagnostics.cs (100%) rename {ServiceHost => src/ServiceHost}/LanguageServer/DocumentHighlight.cs (100%) rename {ServiceHost => src/ServiceHost}/LanguageServer/ExpandAliasRequest.cs (100%) rename {ServiceHost => src/ServiceHost}/LanguageServer/FindModuleRequest.cs (100%) rename {ServiceHost => src/ServiceHost}/LanguageServer/Hover.cs (100%) rename {ServiceHost => src/ServiceHost}/LanguageServer/Initialize.cs (100%) rename {ServiceHost => src/ServiceHost}/LanguageServer/InstallModuleRequest.cs (100%) rename {ServiceHost => src/ServiceHost}/LanguageServer/References.cs (100%) rename {ServiceHost => src/ServiceHost}/LanguageServer/ServerCapabilities.cs (100%) rename {ServiceHost => src/ServiceHost}/LanguageServer/ShowOnlineHelpRequest.cs (100%) rename {ServiceHost => src/ServiceHost}/LanguageServer/Shutdown.cs (100%) rename {ServiceHost => src/ServiceHost}/LanguageServer/SignatureHelp.cs (100%) rename {ServiceHost => src/ServiceHost}/LanguageServer/TextDocument.cs (100%) rename {ServiceHost => src/ServiceHost}/LanguageServer/WorkspaceSymbols.cs (100%) rename {ServiceHost => src/ServiceHost}/LanguageSupport/LanguageService.cs (100%) rename {ServiceHost => src/ServiceHost}/MessageProtocol/Channel/ChannelBase.cs (100%) rename {ServiceHost => src/ServiceHost}/MessageProtocol/Channel/StdioClientChannel.cs (100%) rename {ServiceHost => src/ServiceHost}/MessageProtocol/Channel/StdioServerChannel.cs (100%) rename {ServiceHost => src/ServiceHost}/MessageProtocol/Constants.cs (100%) rename {ServiceHost => src/ServiceHost}/MessageProtocol/EventContext.cs (100%) rename {ServiceHost => src/ServiceHost}/MessageProtocol/EventType.cs (100%) rename {ServiceHost => src/ServiceHost}/MessageProtocol/IMessageSender.cs (100%) rename {ServiceHost => src/ServiceHost}/MessageProtocol/IMessageSerializer.cs (100%) rename {ServiceHost => src/ServiceHost}/MessageProtocol/Message.cs (100%) rename {ServiceHost => src/ServiceHost}/MessageProtocol/MessageDispatcher.cs (100%) rename {ServiceHost => src/ServiceHost}/MessageProtocol/MessageParseException.cs (100%) rename {ServiceHost => src/ServiceHost}/MessageProtocol/MessageProtocolType.cs (100%) rename {ServiceHost => src/ServiceHost}/MessageProtocol/MessageReader.cs (100%) rename {ServiceHost => src/ServiceHost}/MessageProtocol/MessageWriter.cs (100%) rename {ServiceHost => src/ServiceHost}/MessageProtocol/ProtocolEndpoint.cs (100%) rename {ServiceHost => src/ServiceHost}/MessageProtocol/RequestContext.cs (100%) rename {ServiceHost => src/ServiceHost}/MessageProtocol/RequestType.cs (100%) rename {ServiceHost => src/ServiceHost}/MessageProtocol/Serializers/JsonRpcMessageSerializer.cs (100%) rename {ServiceHost => src/ServiceHost}/MessageProtocol/Serializers/V8MessageSerializer.cs (100%) rename {ServiceHost => src/ServiceHost}/Program.cs (100%) rename {ServiceHost => src/ServiceHost}/Properties/AssemblyInfo.cs (100%) rename {ServiceHost => src/ServiceHost}/Server/LanguageServer.cs (100%) rename {ServiceHost => src/ServiceHost}/Server/LanguageServerBase.cs (100%) rename {ServiceHost => src/ServiceHost}/Server/LanguageServerEditorOperations.cs (100%) rename {ServiceHost => src/ServiceHost}/Server/LanguageServerSettings.cs (100%) rename {ServiceHost => src/ServiceHost}/Session/EditorSession.cs (100%) rename {ServiceHost => src/ServiceHost}/Session/HostDetails.cs (100%) rename {ServiceHost => src/ServiceHost}/Session/OutputType.cs (100%) rename {ServiceHost => src/ServiceHost}/Session/OutputWrittenEventArgs.cs (100%) rename {ServiceHost => src/ServiceHost}/Session/ProfilePaths.cs (100%) rename {ServiceHost => src/ServiceHost}/Session/SqlToolsContext.cs (100%) rename {ServiceHost => src/ServiceHost}/Utility/AsyncContext.cs (100%) rename {ServiceHost => src/ServiceHost}/Utility/AsyncContextThread.cs (100%) rename {ServiceHost => src/ServiceHost}/Utility/AsyncLock.cs (100%) rename {ServiceHost => src/ServiceHost}/Utility/AsyncQueue.cs (100%) rename {ServiceHost => src/ServiceHost}/Utility/Extensions.cs (100%) rename {ServiceHost => src/ServiceHost}/Utility/Logger.cs (100%) rename {ServiceHost => src/ServiceHost}/Utility/ThreadSynchronizationContext.cs (100%) rename {ServiceHost => src/ServiceHost}/Utility/Validate.cs (100%) rename {ServiceHost => src/ServiceHost}/Workspace/BufferPosition.cs (100%) rename {ServiceHost => src/ServiceHost}/Workspace/BufferRange.cs (100%) rename {ServiceHost => src/ServiceHost}/Workspace/FileChange.cs (100%) rename {ServiceHost => src/ServiceHost}/Workspace/FilePosition.cs (100%) rename {ServiceHost => src/ServiceHost}/Workspace/ScriptFile.cs (100%) rename {ServiceHost => src/ServiceHost}/Workspace/ScriptFileMarker.cs (100%) rename {ServiceHost => src/ServiceHost}/Workspace/ScriptRegion.cs (100%) rename {ServiceHost => src/ServiceHost}/Workspace/Workspace.cs (100%) rename {ServiceHost => src/ServiceHost}/project.json (91%) create mode 100644 test/ServiceHost.Test/App.config create mode 100644 test/ServiceHost.Test/LanguageServer/JsonRpcMessageSerializerTests.cs create mode 100644 test/ServiceHost.Test/Message/MessageReaderWriterTests.cs create mode 100644 test/ServiceHost.Test/Message/TestMessageTypes.cs create mode 100644 test/ServiceHost.Test/PowerShellEditorServices.Test.Protocol.csproj create mode 100644 test/ServiceHost.Test/Properties/AssemblyInfo.cs create mode 100644 test/ServiceHost.Test/packages.config create mode 100644 test/ServiceHost.Test/project.json diff --git a/.gitignore b/.gitignore index d1fcfc4e..4c997e2b 100644 --- a/.gitignore +++ b/.gitignore @@ -1,3 +1,270 @@ -bin -obj -project.lock.json \ No newline at end of file +syntax: glob + +### VisualStudio ### + +# Project.json lock file +project.lock.json + +# Tool Runtime Dir +/[Tt]ools/ + +# User-specific files +*.suo +*.user +*.userosscache +*.sln.docstates + +# Build results +[Dd]ebug/ +[Dd]ebugPublic/ +[Rr]elease/ +[Rr]eleases/ +x64/ +x86/ +build/ +bld/ +[Bb]in/ +[Oo]bj/ +msbuild.log +msbuild.err +msbuild.wrn + + + +# Cross building rootfs +cross/rootfs/ + +# Visual Studio 2015 +.vs/ + +# Visual Studio 2015 Pre-CTP6 +*.sln.ide +*.ide/ + +# MSTest test Results +[Tt]est[Rr]esult*/ +[Bb]uild[Ll]og.* + +#NUNIT +*.VisualState.xml +TestResult.xml + +# Build Results of an ATL Project +[Dd]ebugPS/ +[Rr]eleasePS/ +dlldata.c + +*_i.c +*_p.c +*_i.h +*.ilk +*.meta +*.obj +*.pch +*.pdb +*.pgc +*.pgd +*.rsp +*.sbr +*.tlb +*.tli +*.tlh +*.tmp +*.tmp_proj +*.log +*.vspscc +*.vssscc +.builds +*.pidb +*.svclog +*.scc + +# Chutzpah Test files +_Chutzpah* + +# Visual C++ cache files +ipch/ +*.aps +*.ncb +*.opendb +*.opensdf +*.sdf +*.cachefile +*.VC.db + +# Visual Studio profiler +*.psess +*.vsp +*.vspx + +# TFS 2012 Local Workspace +$tf/ + +# Guidance Automation Toolkit +*.gpState + +# ReSharper is a .NET coding add-in +_ReSharper*/ +*.[Rr]e[Ss]harper +*.DotSettings.user + +# JustCode is a .NET coding addin-in +.JustCode + +# TeamCity is a build add-in +_TeamCity* + +# DotCover is a Code Coverage Tool +*.dotCover + +# NCrunch +_NCrunch_* +.*crunch*.local.xml + +# MightyMoose +*.mm.* +AutoTest.Net/ + +# Web workbench (sass) +.sass-cache/ + +# Installshield output folder +[Ee]xpress/ + +# DocProject is a documentation generator add-in +DocProject/buildhelp/ +DocProject/Help/*.HxT +DocProject/Help/*.HxC +DocProject/Help/*.hhc +DocProject/Help/*.hhk +DocProject/Help/*.hhp +DocProject/Help/Html2 +DocProject/Help/html + +# Click-Once directory +publish/ + +# Publish Web Output +*.[Pp]ublish.xml +*.azurePubxml +*.pubxml +*.publishproj + +# NuGet Packages +*.nuget.props +*.nuget.targets +*.nupkg +**/packages/* + +# NuGet package restore lockfiles +project.lock.json + +# Windows Azure Build Output +csx/ +*.build.csdef + +# Windows Store app package directory +AppPackages/ + +# Others +*.Cache +ClientBin/ +[Ss]tyle[Cc]op.* +~$* +*.dbmdl +*.dbproj.schemaview +*.pfx +*.publishsettings +node_modules/ +*.metaproj +*.metaproj.tmp + +# RIA/Silverlight projects +Generated_Code/ + +# Backup & report files from converting an old project file +# to a newer Visual Studio version. Backup files are not needed, +# because we have git ;-) +_UpgradeReport_Files/ +Backup*/ +UpgradeLog*.XML +UpgradeLog*.htm + +# SQL Server files +*.mdf +*.ldf + +# Business Intelligence projects +*.rdl.data +*.bim.layout +*.bim_*.settings + +# Microsoft Fakes +FakesAssemblies/ + +### MonoDevelop ### + +*.pidb +*.userprefs + +### Windows ### + +# Windows image file caches +Thumbs.db +ehthumbs.db + +# Folder config file +Desktop.ini + +# Recycle Bin used on file shares +$RECYCLE.BIN/ + +# Windows Installer files +*.cab +*.msi +*.msm +*.msp + +# Windows shortcuts +*.lnk + +### Linux ### + +*~ + +# KDE directory preferences +.directory + +### OSX ### + +.DS_Store +.AppleDouble +.LSOverride + +# Icon must end with two \r +Icon + +# Thumbnails +._* + +# Files that might appear on external disk +.Spotlight-V100 +.Trashes + +# Directories potentially created on remote AFP share +.AppleDB +.AppleDesktop +Network Trash Folder +Temporary Items +.apdisk + +# vim temporary files +[._]*.s[a-w][a-z] +[._]s[a-w][a-z] +*.un~ +Session.vim +.netrwhist +*~ + +# Visual Studio Code +.vscode/ diff --git a/ServiceHost/.vscode/launch.json b/ServiceHost/.vscode/launch.json deleted file mode 100644 index 18ebbb27..00000000 --- a/ServiceHost/.vscode/launch.json +++ /dev/null @@ -1,24 +0,0 @@ -{ - "version": "0.2.0", - "configurations": [ - { - "name": ".NET Core Launch (console)", - "type": "coreclr", - "request": "launch", - "preLaunchTask": "build", - "program": "${workspaceRoot}/bin/Debug/netcoreapp1.0/servicehost.dll", - "args": [], - "cwd": "${workspaceRoot}", - "externalConsole": true, - "requireExactSource": false, - "stopAtEntry": false - }, - { - "name": ".NET Core Attach", - "type": "coreclr", - "request": "attach", - "requireExactSource": false, - "processId": 17264 - } - ] -} \ No newline at end of file diff --git a/ServiceHost/.vscode/tasks.json b/ServiceHost/.vscode/tasks.json deleted file mode 100644 index 67d6eb75..00000000 --- a/ServiceHost/.vscode/tasks.json +++ /dev/null @@ -1,14 +0,0 @@ -{ - "version": "0.1.0", - "command": "dotnet", - "isShellCommand": true, - "args": [], - "tasks": [ - { - "taskName": "build", - "args": [], - "isBuildCommand": true, - "problemMatcher": "$msCompile" - } - ] -} \ No newline at end of file diff --git a/global.json b/global.json new file mode 100644 index 00000000..db6ba19b --- /dev/null +++ b/global.json @@ -0,0 +1,5 @@ +{ + "projects": [ "src", "test" ] +} + + diff --git a/ServiceHost/LanguageServer/ClientCapabilities.cs b/src/ServiceHost/LanguageServer/ClientCapabilities.cs similarity index 100% rename from ServiceHost/LanguageServer/ClientCapabilities.cs rename to src/ServiceHost/LanguageServer/ClientCapabilities.cs diff --git a/ServiceHost/LanguageServer/Completion.cs b/src/ServiceHost/LanguageServer/Completion.cs similarity index 100% rename from ServiceHost/LanguageServer/Completion.cs rename to src/ServiceHost/LanguageServer/Completion.cs diff --git a/ServiceHost/LanguageServer/Configuration.cs b/src/ServiceHost/LanguageServer/Configuration.cs similarity index 100% rename from ServiceHost/LanguageServer/Configuration.cs rename to src/ServiceHost/LanguageServer/Configuration.cs diff --git a/ServiceHost/LanguageServer/Definition.cs b/src/ServiceHost/LanguageServer/Definition.cs similarity index 100% rename from ServiceHost/LanguageServer/Definition.cs rename to src/ServiceHost/LanguageServer/Definition.cs diff --git a/ServiceHost/LanguageServer/Diagnostics.cs b/src/ServiceHost/LanguageServer/Diagnostics.cs similarity index 100% rename from ServiceHost/LanguageServer/Diagnostics.cs rename to src/ServiceHost/LanguageServer/Diagnostics.cs diff --git a/ServiceHost/LanguageServer/DocumentHighlight.cs b/src/ServiceHost/LanguageServer/DocumentHighlight.cs similarity index 100% rename from ServiceHost/LanguageServer/DocumentHighlight.cs rename to src/ServiceHost/LanguageServer/DocumentHighlight.cs diff --git a/ServiceHost/LanguageServer/ExpandAliasRequest.cs b/src/ServiceHost/LanguageServer/ExpandAliasRequest.cs similarity index 100% rename from ServiceHost/LanguageServer/ExpandAliasRequest.cs rename to src/ServiceHost/LanguageServer/ExpandAliasRequest.cs diff --git a/ServiceHost/LanguageServer/FindModuleRequest.cs b/src/ServiceHost/LanguageServer/FindModuleRequest.cs similarity index 100% rename from ServiceHost/LanguageServer/FindModuleRequest.cs rename to src/ServiceHost/LanguageServer/FindModuleRequest.cs diff --git a/ServiceHost/LanguageServer/Hover.cs b/src/ServiceHost/LanguageServer/Hover.cs similarity index 100% rename from ServiceHost/LanguageServer/Hover.cs rename to src/ServiceHost/LanguageServer/Hover.cs diff --git a/ServiceHost/LanguageServer/Initialize.cs b/src/ServiceHost/LanguageServer/Initialize.cs similarity index 100% rename from ServiceHost/LanguageServer/Initialize.cs rename to src/ServiceHost/LanguageServer/Initialize.cs diff --git a/ServiceHost/LanguageServer/InstallModuleRequest.cs b/src/ServiceHost/LanguageServer/InstallModuleRequest.cs similarity index 100% rename from ServiceHost/LanguageServer/InstallModuleRequest.cs rename to src/ServiceHost/LanguageServer/InstallModuleRequest.cs diff --git a/ServiceHost/LanguageServer/References.cs b/src/ServiceHost/LanguageServer/References.cs similarity index 100% rename from ServiceHost/LanguageServer/References.cs rename to src/ServiceHost/LanguageServer/References.cs diff --git a/ServiceHost/LanguageServer/ServerCapabilities.cs b/src/ServiceHost/LanguageServer/ServerCapabilities.cs similarity index 100% rename from ServiceHost/LanguageServer/ServerCapabilities.cs rename to src/ServiceHost/LanguageServer/ServerCapabilities.cs diff --git a/ServiceHost/LanguageServer/ShowOnlineHelpRequest.cs b/src/ServiceHost/LanguageServer/ShowOnlineHelpRequest.cs similarity index 100% rename from ServiceHost/LanguageServer/ShowOnlineHelpRequest.cs rename to src/ServiceHost/LanguageServer/ShowOnlineHelpRequest.cs diff --git a/ServiceHost/LanguageServer/Shutdown.cs b/src/ServiceHost/LanguageServer/Shutdown.cs similarity index 100% rename from ServiceHost/LanguageServer/Shutdown.cs rename to src/ServiceHost/LanguageServer/Shutdown.cs diff --git a/ServiceHost/LanguageServer/SignatureHelp.cs b/src/ServiceHost/LanguageServer/SignatureHelp.cs similarity index 100% rename from ServiceHost/LanguageServer/SignatureHelp.cs rename to src/ServiceHost/LanguageServer/SignatureHelp.cs diff --git a/ServiceHost/LanguageServer/TextDocument.cs b/src/ServiceHost/LanguageServer/TextDocument.cs similarity index 100% rename from ServiceHost/LanguageServer/TextDocument.cs rename to src/ServiceHost/LanguageServer/TextDocument.cs diff --git a/ServiceHost/LanguageServer/WorkspaceSymbols.cs b/src/ServiceHost/LanguageServer/WorkspaceSymbols.cs similarity index 100% rename from ServiceHost/LanguageServer/WorkspaceSymbols.cs rename to src/ServiceHost/LanguageServer/WorkspaceSymbols.cs diff --git a/ServiceHost/LanguageSupport/LanguageService.cs b/src/ServiceHost/LanguageSupport/LanguageService.cs similarity index 100% rename from ServiceHost/LanguageSupport/LanguageService.cs rename to src/ServiceHost/LanguageSupport/LanguageService.cs diff --git a/ServiceHost/MessageProtocol/Channel/ChannelBase.cs b/src/ServiceHost/MessageProtocol/Channel/ChannelBase.cs similarity index 100% rename from ServiceHost/MessageProtocol/Channel/ChannelBase.cs rename to src/ServiceHost/MessageProtocol/Channel/ChannelBase.cs diff --git a/ServiceHost/MessageProtocol/Channel/StdioClientChannel.cs b/src/ServiceHost/MessageProtocol/Channel/StdioClientChannel.cs similarity index 100% rename from ServiceHost/MessageProtocol/Channel/StdioClientChannel.cs rename to src/ServiceHost/MessageProtocol/Channel/StdioClientChannel.cs diff --git a/ServiceHost/MessageProtocol/Channel/StdioServerChannel.cs b/src/ServiceHost/MessageProtocol/Channel/StdioServerChannel.cs similarity index 100% rename from ServiceHost/MessageProtocol/Channel/StdioServerChannel.cs rename to src/ServiceHost/MessageProtocol/Channel/StdioServerChannel.cs diff --git a/ServiceHost/MessageProtocol/Constants.cs b/src/ServiceHost/MessageProtocol/Constants.cs similarity index 100% rename from ServiceHost/MessageProtocol/Constants.cs rename to src/ServiceHost/MessageProtocol/Constants.cs diff --git a/ServiceHost/MessageProtocol/EventContext.cs b/src/ServiceHost/MessageProtocol/EventContext.cs similarity index 100% rename from ServiceHost/MessageProtocol/EventContext.cs rename to src/ServiceHost/MessageProtocol/EventContext.cs diff --git a/ServiceHost/MessageProtocol/EventType.cs b/src/ServiceHost/MessageProtocol/EventType.cs similarity index 100% rename from ServiceHost/MessageProtocol/EventType.cs rename to src/ServiceHost/MessageProtocol/EventType.cs diff --git a/ServiceHost/MessageProtocol/IMessageSender.cs b/src/ServiceHost/MessageProtocol/IMessageSender.cs similarity index 100% rename from ServiceHost/MessageProtocol/IMessageSender.cs rename to src/ServiceHost/MessageProtocol/IMessageSender.cs diff --git a/ServiceHost/MessageProtocol/IMessageSerializer.cs b/src/ServiceHost/MessageProtocol/IMessageSerializer.cs similarity index 100% rename from ServiceHost/MessageProtocol/IMessageSerializer.cs rename to src/ServiceHost/MessageProtocol/IMessageSerializer.cs diff --git a/ServiceHost/MessageProtocol/Message.cs b/src/ServiceHost/MessageProtocol/Message.cs similarity index 100% rename from ServiceHost/MessageProtocol/Message.cs rename to src/ServiceHost/MessageProtocol/Message.cs diff --git a/ServiceHost/MessageProtocol/MessageDispatcher.cs b/src/ServiceHost/MessageProtocol/MessageDispatcher.cs similarity index 100% rename from ServiceHost/MessageProtocol/MessageDispatcher.cs rename to src/ServiceHost/MessageProtocol/MessageDispatcher.cs diff --git a/ServiceHost/MessageProtocol/MessageParseException.cs b/src/ServiceHost/MessageProtocol/MessageParseException.cs similarity index 100% rename from ServiceHost/MessageProtocol/MessageParseException.cs rename to src/ServiceHost/MessageProtocol/MessageParseException.cs diff --git a/ServiceHost/MessageProtocol/MessageProtocolType.cs b/src/ServiceHost/MessageProtocol/MessageProtocolType.cs similarity index 100% rename from ServiceHost/MessageProtocol/MessageProtocolType.cs rename to src/ServiceHost/MessageProtocol/MessageProtocolType.cs diff --git a/ServiceHost/MessageProtocol/MessageReader.cs b/src/ServiceHost/MessageProtocol/MessageReader.cs similarity index 100% rename from ServiceHost/MessageProtocol/MessageReader.cs rename to src/ServiceHost/MessageProtocol/MessageReader.cs diff --git a/ServiceHost/MessageProtocol/MessageWriter.cs b/src/ServiceHost/MessageProtocol/MessageWriter.cs similarity index 100% rename from ServiceHost/MessageProtocol/MessageWriter.cs rename to src/ServiceHost/MessageProtocol/MessageWriter.cs diff --git a/ServiceHost/MessageProtocol/ProtocolEndpoint.cs b/src/ServiceHost/MessageProtocol/ProtocolEndpoint.cs similarity index 100% rename from ServiceHost/MessageProtocol/ProtocolEndpoint.cs rename to src/ServiceHost/MessageProtocol/ProtocolEndpoint.cs diff --git a/ServiceHost/MessageProtocol/RequestContext.cs b/src/ServiceHost/MessageProtocol/RequestContext.cs similarity index 100% rename from ServiceHost/MessageProtocol/RequestContext.cs rename to src/ServiceHost/MessageProtocol/RequestContext.cs diff --git a/ServiceHost/MessageProtocol/RequestType.cs b/src/ServiceHost/MessageProtocol/RequestType.cs similarity index 100% rename from ServiceHost/MessageProtocol/RequestType.cs rename to src/ServiceHost/MessageProtocol/RequestType.cs diff --git a/ServiceHost/MessageProtocol/Serializers/JsonRpcMessageSerializer.cs b/src/ServiceHost/MessageProtocol/Serializers/JsonRpcMessageSerializer.cs similarity index 100% rename from ServiceHost/MessageProtocol/Serializers/JsonRpcMessageSerializer.cs rename to src/ServiceHost/MessageProtocol/Serializers/JsonRpcMessageSerializer.cs diff --git a/ServiceHost/MessageProtocol/Serializers/V8MessageSerializer.cs b/src/ServiceHost/MessageProtocol/Serializers/V8MessageSerializer.cs similarity index 100% rename from ServiceHost/MessageProtocol/Serializers/V8MessageSerializer.cs rename to src/ServiceHost/MessageProtocol/Serializers/V8MessageSerializer.cs diff --git a/ServiceHost/Program.cs b/src/ServiceHost/Program.cs similarity index 100% rename from ServiceHost/Program.cs rename to src/ServiceHost/Program.cs diff --git a/ServiceHost/Properties/AssemblyInfo.cs b/src/ServiceHost/Properties/AssemblyInfo.cs similarity index 100% rename from ServiceHost/Properties/AssemblyInfo.cs rename to src/ServiceHost/Properties/AssemblyInfo.cs diff --git a/ServiceHost/Server/LanguageServer.cs b/src/ServiceHost/Server/LanguageServer.cs similarity index 100% rename from ServiceHost/Server/LanguageServer.cs rename to src/ServiceHost/Server/LanguageServer.cs diff --git a/ServiceHost/Server/LanguageServerBase.cs b/src/ServiceHost/Server/LanguageServerBase.cs similarity index 100% rename from ServiceHost/Server/LanguageServerBase.cs rename to src/ServiceHost/Server/LanguageServerBase.cs diff --git a/ServiceHost/Server/LanguageServerEditorOperations.cs b/src/ServiceHost/Server/LanguageServerEditorOperations.cs similarity index 100% rename from ServiceHost/Server/LanguageServerEditorOperations.cs rename to src/ServiceHost/Server/LanguageServerEditorOperations.cs diff --git a/ServiceHost/Server/LanguageServerSettings.cs b/src/ServiceHost/Server/LanguageServerSettings.cs similarity index 100% rename from ServiceHost/Server/LanguageServerSettings.cs rename to src/ServiceHost/Server/LanguageServerSettings.cs diff --git a/ServiceHost/Session/EditorSession.cs b/src/ServiceHost/Session/EditorSession.cs similarity index 100% rename from ServiceHost/Session/EditorSession.cs rename to src/ServiceHost/Session/EditorSession.cs diff --git a/ServiceHost/Session/HostDetails.cs b/src/ServiceHost/Session/HostDetails.cs similarity index 100% rename from ServiceHost/Session/HostDetails.cs rename to src/ServiceHost/Session/HostDetails.cs diff --git a/ServiceHost/Session/OutputType.cs b/src/ServiceHost/Session/OutputType.cs similarity index 100% rename from ServiceHost/Session/OutputType.cs rename to src/ServiceHost/Session/OutputType.cs diff --git a/ServiceHost/Session/OutputWrittenEventArgs.cs b/src/ServiceHost/Session/OutputWrittenEventArgs.cs similarity index 100% rename from ServiceHost/Session/OutputWrittenEventArgs.cs rename to src/ServiceHost/Session/OutputWrittenEventArgs.cs diff --git a/ServiceHost/Session/ProfilePaths.cs b/src/ServiceHost/Session/ProfilePaths.cs similarity index 100% rename from ServiceHost/Session/ProfilePaths.cs rename to src/ServiceHost/Session/ProfilePaths.cs diff --git a/ServiceHost/Session/SqlToolsContext.cs b/src/ServiceHost/Session/SqlToolsContext.cs similarity index 100% rename from ServiceHost/Session/SqlToolsContext.cs rename to src/ServiceHost/Session/SqlToolsContext.cs diff --git a/ServiceHost/Utility/AsyncContext.cs b/src/ServiceHost/Utility/AsyncContext.cs similarity index 100% rename from ServiceHost/Utility/AsyncContext.cs rename to src/ServiceHost/Utility/AsyncContext.cs diff --git a/ServiceHost/Utility/AsyncContextThread.cs b/src/ServiceHost/Utility/AsyncContextThread.cs similarity index 100% rename from ServiceHost/Utility/AsyncContextThread.cs rename to src/ServiceHost/Utility/AsyncContextThread.cs diff --git a/ServiceHost/Utility/AsyncLock.cs b/src/ServiceHost/Utility/AsyncLock.cs similarity index 100% rename from ServiceHost/Utility/AsyncLock.cs rename to src/ServiceHost/Utility/AsyncLock.cs diff --git a/ServiceHost/Utility/AsyncQueue.cs b/src/ServiceHost/Utility/AsyncQueue.cs similarity index 100% rename from ServiceHost/Utility/AsyncQueue.cs rename to src/ServiceHost/Utility/AsyncQueue.cs diff --git a/ServiceHost/Utility/Extensions.cs b/src/ServiceHost/Utility/Extensions.cs similarity index 100% rename from ServiceHost/Utility/Extensions.cs rename to src/ServiceHost/Utility/Extensions.cs diff --git a/ServiceHost/Utility/Logger.cs b/src/ServiceHost/Utility/Logger.cs similarity index 100% rename from ServiceHost/Utility/Logger.cs rename to src/ServiceHost/Utility/Logger.cs diff --git a/ServiceHost/Utility/ThreadSynchronizationContext.cs b/src/ServiceHost/Utility/ThreadSynchronizationContext.cs similarity index 100% rename from ServiceHost/Utility/ThreadSynchronizationContext.cs rename to src/ServiceHost/Utility/ThreadSynchronizationContext.cs diff --git a/ServiceHost/Utility/Validate.cs b/src/ServiceHost/Utility/Validate.cs similarity index 100% rename from ServiceHost/Utility/Validate.cs rename to src/ServiceHost/Utility/Validate.cs diff --git a/ServiceHost/Workspace/BufferPosition.cs b/src/ServiceHost/Workspace/BufferPosition.cs similarity index 100% rename from ServiceHost/Workspace/BufferPosition.cs rename to src/ServiceHost/Workspace/BufferPosition.cs diff --git a/ServiceHost/Workspace/BufferRange.cs b/src/ServiceHost/Workspace/BufferRange.cs similarity index 100% rename from ServiceHost/Workspace/BufferRange.cs rename to src/ServiceHost/Workspace/BufferRange.cs diff --git a/ServiceHost/Workspace/FileChange.cs b/src/ServiceHost/Workspace/FileChange.cs similarity index 100% rename from ServiceHost/Workspace/FileChange.cs rename to src/ServiceHost/Workspace/FileChange.cs diff --git a/ServiceHost/Workspace/FilePosition.cs b/src/ServiceHost/Workspace/FilePosition.cs similarity index 100% rename from ServiceHost/Workspace/FilePosition.cs rename to src/ServiceHost/Workspace/FilePosition.cs diff --git a/ServiceHost/Workspace/ScriptFile.cs b/src/ServiceHost/Workspace/ScriptFile.cs similarity index 100% rename from ServiceHost/Workspace/ScriptFile.cs rename to src/ServiceHost/Workspace/ScriptFile.cs diff --git a/ServiceHost/Workspace/ScriptFileMarker.cs b/src/ServiceHost/Workspace/ScriptFileMarker.cs similarity index 100% rename from ServiceHost/Workspace/ScriptFileMarker.cs rename to src/ServiceHost/Workspace/ScriptFileMarker.cs diff --git a/ServiceHost/Workspace/ScriptRegion.cs b/src/ServiceHost/Workspace/ScriptRegion.cs similarity index 100% rename from ServiceHost/Workspace/ScriptRegion.cs rename to src/ServiceHost/Workspace/ScriptRegion.cs diff --git a/ServiceHost/Workspace/Workspace.cs b/src/ServiceHost/Workspace/Workspace.cs similarity index 100% rename from ServiceHost/Workspace/Workspace.cs rename to src/ServiceHost/Workspace/Workspace.cs diff --git a/ServiceHost/project.json b/src/ServiceHost/project.json similarity index 91% rename from ServiceHost/project.json rename to src/ServiceHost/project.json index 28565355..11340892 100644 --- a/ServiceHost/project.json +++ b/src/ServiceHost/project.json @@ -5,7 +5,7 @@ "emitEntryPoint": true }, "dependencies": { - "Newtonsoft.Json": "9.0.1", + "Newtonsoft.Json": "9.0.1" }, "frameworks": { "netcoreapp1.0": { diff --git a/test/ServiceHost.Test/App.config b/test/ServiceHost.Test/App.config new file mode 100644 index 00000000..570b96df --- /dev/null +++ b/test/ServiceHost.Test/App.config @@ -0,0 +1,9 @@ + + + + + + + + + \ No newline at end of file diff --git a/test/ServiceHost.Test/LanguageServer/JsonRpcMessageSerializerTests.cs b/test/ServiceHost.Test/LanguageServer/JsonRpcMessageSerializerTests.cs new file mode 100644 index 00000000..9ec341c5 --- /dev/null +++ b/test/ServiceHost.Test/LanguageServer/JsonRpcMessageSerializerTests.cs @@ -0,0 +1,144 @@ +// +// Copyright (c) Microsoft. All rights reserved. +// Licensed under the MIT license. See LICENSE file in the project root for full license information. +// + +using Microsoft.SqlTools.EditorServices.Protocol.MessageProtocol; +using Microsoft.SqlTools.EditorServices.Protocol.MessageProtocol.Serializers; +using Newtonsoft.Json.Linq; +using Xunit; + +namespace Microsoft.SqlTools.EditorServices.Test.Protocol.LanguageServer +{ + public class TestMessageContents + { + public const string SomeFieldValue = "Some value"; + public const int NumberValue = 42; + + public string SomeField { get; set; } + + public int Number { get; set; } + + public TestMessageContents() + { + this.SomeField = SomeFieldValue; + this.Number = NumberValue; + } + } + + public class JsonRpcMessageSerializerTests + { + private IMessageSerializer messageSerializer; + + private const string MessageId = "42"; + private const string MethodName = "testMethod"; + private static readonly JToken MessageContent = JToken.FromObject(new TestMessageContents()); + + public JsonRpcMessageSerializerTests() + { + this.messageSerializer = new JsonRpcMessageSerializer(); + } + + [Fact] + public void SerializesRequestMessages() + { + var messageObj = + this.messageSerializer.SerializeMessage( + Message.Request( + MessageId, + MethodName, + MessageContent)); + + AssertMessageFields( + messageObj, + checkId: true, + checkMethod: true, + checkParams: true); + } + + [Fact] + public void SerializesEventMessages() + { + var messageObj = + this.messageSerializer.SerializeMessage( + Message.Event( + MethodName, + MessageContent)); + + AssertMessageFields( + messageObj, + checkMethod: true, + checkParams: true); + } + + [Fact] + public void SerializesResponseMessages() + { + var messageObj = + this.messageSerializer.SerializeMessage( + Message.Response( + MessageId, + null, + MessageContent)); + + AssertMessageFields( + messageObj, + checkId: true, + checkResult: true); + } + + [Fact] + public void SerializesResponseWithErrorMessages() + { + var messageObj = + this.messageSerializer.SerializeMessage( + Message.ResponseError( + MessageId, + null, + MessageContent)); + + AssertMessageFields( + messageObj, + checkId: true, + checkError: true); + } + + private static void AssertMessageFields( + JObject messageObj, + bool checkId = false, + bool checkMethod = false, + bool checkParams = false, + bool checkResult = false, + bool checkError = false) + { + JToken token = null; + + Assert.True(messageObj.TryGetValue("jsonrpc", out token)); + Assert.Equal("2.0", token.ToString()); + + if (checkId) + { + Assert.True(messageObj.TryGetValue("id", out token)); + Assert.Equal(MessageId, token.ToString()); + } + + if (checkMethod) + { + Assert.True(messageObj.TryGetValue("method", out token)); + Assert.Equal(MethodName, token.ToString()); + } + + if (checkError) + { + // TODO + } + else + { + string contentField = checkParams ? "params" : "result"; + Assert.True(messageObj.TryGetValue(contentField, out token)); + Assert.True(JToken.DeepEquals(token, MessageContent)); + } + } + } +} + diff --git a/test/ServiceHost.Test/Message/MessageReaderWriterTests.cs b/test/ServiceHost.Test/Message/MessageReaderWriterTests.cs new file mode 100644 index 00000000..82e619f5 --- /dev/null +++ b/test/ServiceHost.Test/Message/MessageReaderWriterTests.cs @@ -0,0 +1,177 @@ +// +// Copyright (c) Microsoft. All rights reserved. +// Licensed under the MIT license. See LICENSE file in the project root for full license information. +// + +using Microsoft.SqlTools.EditorServices.Protocol.MessageProtocol; +using Microsoft.SqlTools.EditorServices.Protocol.MessageProtocol.Serializers; +using System; +using System.IO; +using System.Text; +using System.Threading.Tasks; +using Xunit; + +namespace Microsoft.SqlTools.EditorServices.Test.Protocol.MessageProtocol +{ + public class MessageReaderWriterTests + { + const string TestEventString = "{\"type\":\"event\",\"event\":\"testEvent\",\"body\":null}"; + const string TestEventFormatString = "{{\"event\":\"testEvent\",\"body\":{{\"someString\":\"{0}\"}},\"seq\":0,\"type\":\"event\"}}"; + readonly int ExpectedMessageByteCount = Encoding.UTF8.GetByteCount(TestEventString); + + private IMessageSerializer messageSerializer; + + public MessageReaderWriterTests() + { + this.messageSerializer = new V8MessageSerializer(); + } + + [Fact] + public async Task WritesMessage() + { + MemoryStream outputStream = new MemoryStream(); + + MessageWriter messageWriter = + new MessageWriter( + outputStream, + this.messageSerializer); + + // 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)); + outputStream.Seek(0, SeekOrigin.Begin); + + string expectedHeaderString = + string.Format( + Constants.ContentLengthFormatString, + ExpectedMessageByteCount); + + byte[] buffer = new byte[128]; + await outputStream.ReadAsync(buffer, 0, expectedHeaderString.Length); + + Assert.Equal( + expectedHeaderString, + Encoding.ASCII.GetString(buffer, 0, expectedHeaderString.Length)); + + // Read the message + await outputStream.ReadAsync(buffer, 0, ExpectedMessageByteCount); + + Assert.Equal( + TestEventString, + Encoding.UTF8.GetString(buffer, 0, ExpectedMessageByteCount)); + + outputStream.Dispose(); + } + + [Fact] + public void ReadsMessage() + { + MemoryStream inputStream = new MemoryStream(); + MessageReader messageReader = + new MessageReader( + inputStream, + this.messageSerializer); + + // Write a message to the stream + byte[] messageBuffer = this.GetMessageBytes(TestEventString); + inputStream.Write( + this.GetMessageBytes(TestEventString), + 0, + messageBuffer.Length); + + inputStream.Flush(); + inputStream.Seek(0, SeekOrigin.Begin); + + Message messageResult = messageReader.ReadMessage().Result; + Assert.Equal("testEvent", messageResult.Method); + + inputStream.Dispose(); + } + + [Fact] + public void ReadsManyBufferedMessages() + { + MemoryStream inputStream = new MemoryStream(); + MessageReader messageReader = + new MessageReader( + inputStream, + this.messageSerializer); + + // Get a message to use for writing to the stream + byte[] messageBuffer = this.GetMessageBytes(TestEventString); + + // How many messages of this size should we write to overflow the buffer? + int overflowMessageCount = + (int)Math.Ceiling( + (MessageReader.DefaultBufferSize * 1.5) / messageBuffer.Length); + + // Write the necessary number of messages to the stream + for (int i = 0; i < overflowMessageCount; i++) + { + inputStream.Write(messageBuffer, 0, messageBuffer.Length); + } + + inputStream.Flush(); + inputStream.Seek(0, SeekOrigin.Begin); + + // Read the written messages from the stream + for (int i = 0; i < overflowMessageCount; i++) + { + Message messageResult = messageReader.ReadMessage().Result; + Assert.Equal("testEvent", messageResult.Method); + } + + inputStream.Dispose(); + } + + [Fact] + public void ReaderResizesBufferForLargeMessages() + { + MemoryStream inputStream = new MemoryStream(); + MessageReader messageReader = + new MessageReader( + inputStream, + this.messageSerializer); + + // Get a message with content so large that the buffer will need + // to be resized to fit it all. + byte[] messageBuffer = + this.GetMessageBytes( + string.Format( + TestEventFormatString, + new String('X', (int)(MessageReader.DefaultBufferSize * 3)))); + + inputStream.Write(messageBuffer, 0, messageBuffer.Length); + inputStream.Flush(); + inputStream.Seek(0, SeekOrigin.Begin); + + Message messageResult = messageReader.ReadMessage().Result; + Assert.Equal("testEvent", messageResult.Method); + + inputStream.Dispose(); + } + + private byte[] GetMessageBytes(string messageString, Encoding encoding = null) + { + if (encoding == null) + { + encoding = Encoding.UTF8; + } + + byte[] messageBytes = Encoding.UTF8.GetBytes(messageString); + byte[] headerBytes = + Encoding.ASCII.GetBytes( + string.Format( + Constants.ContentLengthFormatString, + messageBytes.Length)); + + // Copy the bytes into a single buffer + byte[] finalBytes = new byte[headerBytes.Length + messageBytes.Length]; + Buffer.BlockCopy(headerBytes, 0, finalBytes, 0, headerBytes.Length); + Buffer.BlockCopy(messageBytes, 0, finalBytes, headerBytes.Length, messageBytes.Length); + + return finalBytes; + } + } +} + diff --git a/test/ServiceHost.Test/Message/TestMessageTypes.cs b/test/ServiceHost.Test/Message/TestMessageTypes.cs new file mode 100644 index 00000000..cc5981dc --- /dev/null +++ b/test/ServiceHost.Test/Message/TestMessageTypes.cs @@ -0,0 +1,56 @@ +// +// Copyright (c) Microsoft. All rights reserved. +// Licensed under the MIT license. See LICENSE file in the project root for full license information. +// + +using Microsoft.SqlTools.EditorServices.Protocol.MessageProtocol; +using System; +using System.Threading.Tasks; + +namespace Microsoft.SqlTools.EditorServices.Test.Protocol.MessageProtocol +{ + #region Request Types + + internal class TestRequest + { + public Task ProcessMessage( + EditorSession editorSession, + MessageWriter messageWriter) + { + return Task.FromResult(false); + } + } + + internal class TestRequestArguments + { + public string SomeString { get; set; } + } + + #endregion + + #region Response Types + + internal class TestResponse + { + } + + internal class TestResponseBody + { + public string SomeString { get; set; } + } + + #endregion + + #region Event Types + + internal class TestEvent + { + } + + internal class TestEventBody + { + public string SomeString { get; set; } + } + + #endregion +} diff --git a/test/ServiceHost.Test/PowerShellEditorServices.Test.Protocol.csproj b/test/ServiceHost.Test/PowerShellEditorServices.Test.Protocol.csproj new file mode 100644 index 00000000..54e20896 --- /dev/null +++ b/test/ServiceHost.Test/PowerShellEditorServices.Test.Protocol.csproj @@ -0,0 +1,109 @@ + + + + + + + Debug + AnyCPU + {E3A5CF5D-6E41-44AC-AE0A-4C227E4BACD4} + Library + Properties + Microsoft.SqlTools.EditorServices.Test.Protocol + Microsoft.SqlTools.EditorServices.Test.Protocol + v4.6.1 + 512 + 69e9ba79 + ..\..\ + true + + + + true + full + false + bin\Debug\ + DEBUG;TRACE + prompt + 4 + + + pdbonly + true + bin\Release\ + TRACE + prompt + 4 + + + + ..\..\packages\Newtonsoft.Json.8.0.2\lib\net45\Newtonsoft.Json.dll + True + + + + + + + + + + ..\..\packages\xunit.abstractions.2.0.0\lib\net35\xunit.abstractions.dll + True + + + ..\..\packages\xunit.assert.2.1.0\lib\portable-net45+win8+wp8+wpa81\xunit.assert.dll + True + + + ..\..\packages\xunit.extensibility.core.2.1.0\lib\portable-net45+win8+wp8+wpa81\xunit.core.dll + True + + + ..\..\packages\xunit.extensibility.execution.2.1.0\lib\net45\xunit.execution.desktop.dll + True + + + + + + + + + + + + + + + + + {f8a0946a-5d25-4651-8079-b8d5776916fb} + SqlToolsEditorServices.Protocol + + + {81e8cbcd-6319-49e7-9662-0475bd0791f4} + SqlToolsEditorServices + + + + + + + + + This project references NuGet package(s) that are missing on this computer. Enable NuGet Package Restore to download them. For more information, see http://go.microsoft.com/fwlink/?LinkID=322105. The missing file is {0}. + + + + + + + + \ No newline at end of file diff --git a/test/ServiceHost.Test/Properties/AssemblyInfo.cs b/test/ServiceHost.Test/Properties/AssemblyInfo.cs new file mode 100644 index 00000000..5cf54b90 --- /dev/null +++ b/test/ServiceHost.Test/Properties/AssemblyInfo.cs @@ -0,0 +1,42 @@ +// +// Copyright (c) Microsoft. All rights reserved. +// Licensed under the MIT license. See LICENSE file in the project root for full license information. +// + +using System.Reflection; +using System.Runtime.CompilerServices; +using System.Runtime.InteropServices; + +// General Information about an assembly is controlled through the following +// set of attributes. Change these attribute values to modify the information +// associated with an assembly. +[assembly: AssemblyTitle("SqlToolsEditorServices.Test.Transport.Stdio")] +[assembly: AssemblyDescription("")] +[assembly: AssemblyConfiguration("")] +[assembly: AssemblyCompany("")] +[assembly: AssemblyProduct("SqlToolsEditorServices.Test.Transport.Stdio")] +[assembly: AssemblyCopyright("Copyright � 2015")] +[assembly: AssemblyTrademark("")] +[assembly: AssemblyCulture("")] + +// Setting ComVisible to false makes the types in this assembly not visible +// to COM components. If you need to access a type in this assembly from +// COM, set the ComVisible attribute to true on that type. +[assembly: ComVisible(false)] + +// The following GUID is for the ID of the typelib if this project is exposed to COM +[assembly: Guid("07137FCA-76D0-4CE7-9764-C21DB7A57093")] + +// Version information for an assembly consists of the following four values: +// +// Major Version +// Minor Version +// Build Number +// Revision +// +// You can specify all the values or you can default the Build and Revision Numbers +// by using the '*' as shown below: +// [assembly: AssemblyVersion("1.0.*")] +[assembly: AssemblyVersion("1.0.0.0")] +[assembly: AssemblyFileVersion("1.0.0.0")] + diff --git a/test/ServiceHost.Test/packages.config b/test/ServiceHost.Test/packages.config new file mode 100644 index 00000000..d01e8969 --- /dev/null +++ b/test/ServiceHost.Test/packages.config @@ -0,0 +1,11 @@ + + + + + + + + + + + \ No newline at end of file diff --git a/test/ServiceHost.Test/project.json b/test/ServiceHost.Test/project.json new file mode 100644 index 00000000..b7f00724 --- /dev/null +++ b/test/ServiceHost.Test/project.json @@ -0,0 +1,30 @@ +{ + "version": "1.0.0-*", + "buildOptions": { + "debugType": "portable" + }, + "dependencies": { + "Newtonsoft.Json": "9.0.1", + "System.Runtime.Serialization.Primitives": "4.1.1", + "xunit": "2.1.0", + "dotnet-test-xunit": "1.0.0-rc2-192208-24", + "ServiceHost": { + "target": "project" + } + }, + "testRunner": "xunit", + "frameworks": { + "netcoreapp1.0": { + "dependencies": { + "Microsoft.NETCore.App": { + "type": "platform", + "version": "1.0.0" + } + }, + "imports": [ + "dotnet5.4", + "portable-net451+win8" + ] + } + } +} From 01e8f9c3f5eb36c2c808aa0278d218d9ef86fb6b Mon Sep 17 00:00:00 2001 From: Karl Burtram Date: Sun, 17 Jul 2016 11:56:11 -0700 Subject: [PATCH 4/6] Merge ServiceHost xUnit test project into dev. (#5) * Setup standard src, test folder structure. Add unit test project. * Actually stage the deletes. Update .gitignore --- .gitignore | 273 +++++++++++++++++- ServiceHost/.vscode/launch.json | 24 -- ServiceHost/.vscode/tasks.json | 14 - global.json | 5 + .../LanguageServer/ClientCapabilities.cs | 0 .../ServiceHost}/LanguageServer/Completion.cs | 0 .../LanguageServer/Configuration.cs | 0 .../ServiceHost}/LanguageServer/Definition.cs | 0 .../LanguageServer/Diagnostics.cs | 0 .../LanguageServer/DocumentHighlight.cs | 0 .../LanguageServer/ExpandAliasRequest.cs | 0 .../LanguageServer/FindModuleRequest.cs | 0 .../ServiceHost}/LanguageServer/Hover.cs | 0 .../ServiceHost}/LanguageServer/Initialize.cs | 0 .../LanguageServer/InstallModuleRequest.cs | 0 .../ServiceHost}/LanguageServer/References.cs | 0 .../LanguageServer/ServerCapabilities.cs | 0 .../LanguageServer/ShowOnlineHelpRequest.cs | 0 .../ServiceHost}/LanguageServer/Shutdown.cs | 0 .../LanguageServer/SignatureHelp.cs | 0 .../LanguageServer/TextDocument.cs | 0 .../LanguageServer/WorkspaceSymbols.cs | 0 .../LanguageSupport/LanguageService.cs | 0 .../MessageProtocol/Channel/ChannelBase.cs | 0 .../Channel/StdioClientChannel.cs | 0 .../Channel/StdioServerChannel.cs | 0 .../ServiceHost}/MessageProtocol/Constants.cs | 0 .../MessageProtocol/EventContext.cs | 0 .../ServiceHost}/MessageProtocol/EventType.cs | 0 .../MessageProtocol/IMessageSender.cs | 0 .../MessageProtocol/IMessageSerializer.cs | 0 .../ServiceHost}/MessageProtocol/Message.cs | 0 .../MessageProtocol/MessageDispatcher.cs | 0 .../MessageProtocol/MessageParseException.cs | 0 .../MessageProtocol/MessageProtocolType.cs | 0 .../MessageProtocol/MessageReader.cs | 0 .../MessageProtocol/MessageWriter.cs | 0 .../MessageProtocol/ProtocolEndpoint.cs | 0 .../MessageProtocol/RequestContext.cs | 0 .../MessageProtocol/RequestType.cs | 0 .../Serializers/JsonRpcMessageSerializer.cs | 0 .../Serializers/V8MessageSerializer.cs | 0 {ServiceHost => src/ServiceHost}/Program.cs | 0 .../ServiceHost}/Properties/AssemblyInfo.cs | 0 .../ServiceHost}/Server/LanguageServer.cs | 0 .../ServiceHost}/Server/LanguageServerBase.cs | 0 .../Server/LanguageServerEditorOperations.cs | 0 .../Server/LanguageServerSettings.cs | 0 .../ServiceHost}/Session/EditorSession.cs | 0 .../ServiceHost}/Session/HostDetails.cs | 0 .../ServiceHost}/Session/OutputType.cs | 0 .../Session/OutputWrittenEventArgs.cs | 0 .../ServiceHost}/Session/ProfilePaths.cs | 0 .../ServiceHost}/Session/SqlToolsContext.cs | 0 .../ServiceHost}/Utility/AsyncContext.cs | 0 .../Utility/AsyncContextThread.cs | 0 .../ServiceHost}/Utility/AsyncLock.cs | 0 .../ServiceHost}/Utility/AsyncQueue.cs | 0 .../ServiceHost}/Utility/Extensions.cs | 0 .../ServiceHost}/Utility/Logger.cs | 0 .../Utility/ThreadSynchronizationContext.cs | 0 .../ServiceHost}/Utility/Validate.cs | 0 .../ServiceHost}/Workspace/BufferPosition.cs | 0 .../ServiceHost}/Workspace/BufferRange.cs | 0 .../ServiceHost}/Workspace/FileChange.cs | 0 .../ServiceHost}/Workspace/FilePosition.cs | 0 .../ServiceHost}/Workspace/ScriptFile.cs | 0 .../Workspace/ScriptFileMarker.cs | 0 .../ServiceHost}/Workspace/ScriptRegion.cs | 0 .../ServiceHost}/Workspace/Workspace.cs | 0 {ServiceHost => src/ServiceHost}/project.json | 2 +- test/ServiceHost.Test/App.config | 9 + .../JsonRpcMessageSerializerTests.cs | 144 +++++++++ .../Message/MessageReaderWriterTests.cs | 177 ++++++++++++ .../Message/TestMessageTypes.cs | 56 ++++ ...erShellEditorServices.Test.Protocol.csproj | 109 +++++++ .../Properties/AssemblyInfo.cs | 42 +++ test/ServiceHost.Test/packages.config | 11 + test/ServiceHost.Test/project.json | 30 ++ 79 files changed, 854 insertions(+), 42 deletions(-) delete mode 100644 ServiceHost/.vscode/launch.json delete mode 100644 ServiceHost/.vscode/tasks.json create mode 100644 global.json rename {ServiceHost => src/ServiceHost}/LanguageServer/ClientCapabilities.cs (100%) rename {ServiceHost => src/ServiceHost}/LanguageServer/Completion.cs (100%) rename {ServiceHost => src/ServiceHost}/LanguageServer/Configuration.cs (100%) rename {ServiceHost => src/ServiceHost}/LanguageServer/Definition.cs (100%) rename {ServiceHost => src/ServiceHost}/LanguageServer/Diagnostics.cs (100%) rename {ServiceHost => src/ServiceHost}/LanguageServer/DocumentHighlight.cs (100%) rename {ServiceHost => src/ServiceHost}/LanguageServer/ExpandAliasRequest.cs (100%) rename {ServiceHost => src/ServiceHost}/LanguageServer/FindModuleRequest.cs (100%) rename {ServiceHost => src/ServiceHost}/LanguageServer/Hover.cs (100%) rename {ServiceHost => src/ServiceHost}/LanguageServer/Initialize.cs (100%) rename {ServiceHost => src/ServiceHost}/LanguageServer/InstallModuleRequest.cs (100%) rename {ServiceHost => src/ServiceHost}/LanguageServer/References.cs (100%) rename {ServiceHost => src/ServiceHost}/LanguageServer/ServerCapabilities.cs (100%) rename {ServiceHost => src/ServiceHost}/LanguageServer/ShowOnlineHelpRequest.cs (100%) rename {ServiceHost => src/ServiceHost}/LanguageServer/Shutdown.cs (100%) rename {ServiceHost => src/ServiceHost}/LanguageServer/SignatureHelp.cs (100%) rename {ServiceHost => src/ServiceHost}/LanguageServer/TextDocument.cs (100%) rename {ServiceHost => src/ServiceHost}/LanguageServer/WorkspaceSymbols.cs (100%) rename {ServiceHost => src/ServiceHost}/LanguageSupport/LanguageService.cs (100%) rename {ServiceHost => src/ServiceHost}/MessageProtocol/Channel/ChannelBase.cs (100%) rename {ServiceHost => src/ServiceHost}/MessageProtocol/Channel/StdioClientChannel.cs (100%) rename {ServiceHost => src/ServiceHost}/MessageProtocol/Channel/StdioServerChannel.cs (100%) rename {ServiceHost => src/ServiceHost}/MessageProtocol/Constants.cs (100%) rename {ServiceHost => src/ServiceHost}/MessageProtocol/EventContext.cs (100%) rename {ServiceHost => src/ServiceHost}/MessageProtocol/EventType.cs (100%) rename {ServiceHost => src/ServiceHost}/MessageProtocol/IMessageSender.cs (100%) rename {ServiceHost => src/ServiceHost}/MessageProtocol/IMessageSerializer.cs (100%) rename {ServiceHost => src/ServiceHost}/MessageProtocol/Message.cs (100%) rename {ServiceHost => src/ServiceHost}/MessageProtocol/MessageDispatcher.cs (100%) rename {ServiceHost => src/ServiceHost}/MessageProtocol/MessageParseException.cs (100%) rename {ServiceHost => src/ServiceHost}/MessageProtocol/MessageProtocolType.cs (100%) rename {ServiceHost => src/ServiceHost}/MessageProtocol/MessageReader.cs (100%) rename {ServiceHost => src/ServiceHost}/MessageProtocol/MessageWriter.cs (100%) rename {ServiceHost => src/ServiceHost}/MessageProtocol/ProtocolEndpoint.cs (100%) rename {ServiceHost => src/ServiceHost}/MessageProtocol/RequestContext.cs (100%) rename {ServiceHost => src/ServiceHost}/MessageProtocol/RequestType.cs (100%) rename {ServiceHost => src/ServiceHost}/MessageProtocol/Serializers/JsonRpcMessageSerializer.cs (100%) rename {ServiceHost => src/ServiceHost}/MessageProtocol/Serializers/V8MessageSerializer.cs (100%) rename {ServiceHost => src/ServiceHost}/Program.cs (100%) rename {ServiceHost => src/ServiceHost}/Properties/AssemblyInfo.cs (100%) rename {ServiceHost => src/ServiceHost}/Server/LanguageServer.cs (100%) rename {ServiceHost => src/ServiceHost}/Server/LanguageServerBase.cs (100%) rename {ServiceHost => src/ServiceHost}/Server/LanguageServerEditorOperations.cs (100%) rename {ServiceHost => src/ServiceHost}/Server/LanguageServerSettings.cs (100%) rename {ServiceHost => src/ServiceHost}/Session/EditorSession.cs (100%) rename {ServiceHost => src/ServiceHost}/Session/HostDetails.cs (100%) rename {ServiceHost => src/ServiceHost}/Session/OutputType.cs (100%) rename {ServiceHost => src/ServiceHost}/Session/OutputWrittenEventArgs.cs (100%) rename {ServiceHost => src/ServiceHost}/Session/ProfilePaths.cs (100%) rename {ServiceHost => src/ServiceHost}/Session/SqlToolsContext.cs (100%) rename {ServiceHost => src/ServiceHost}/Utility/AsyncContext.cs (100%) rename {ServiceHost => src/ServiceHost}/Utility/AsyncContextThread.cs (100%) rename {ServiceHost => src/ServiceHost}/Utility/AsyncLock.cs (100%) rename {ServiceHost => src/ServiceHost}/Utility/AsyncQueue.cs (100%) rename {ServiceHost => src/ServiceHost}/Utility/Extensions.cs (100%) rename {ServiceHost => src/ServiceHost}/Utility/Logger.cs (100%) rename {ServiceHost => src/ServiceHost}/Utility/ThreadSynchronizationContext.cs (100%) rename {ServiceHost => src/ServiceHost}/Utility/Validate.cs (100%) rename {ServiceHost => src/ServiceHost}/Workspace/BufferPosition.cs (100%) rename {ServiceHost => src/ServiceHost}/Workspace/BufferRange.cs (100%) rename {ServiceHost => src/ServiceHost}/Workspace/FileChange.cs (100%) rename {ServiceHost => src/ServiceHost}/Workspace/FilePosition.cs (100%) rename {ServiceHost => src/ServiceHost}/Workspace/ScriptFile.cs (100%) rename {ServiceHost => src/ServiceHost}/Workspace/ScriptFileMarker.cs (100%) rename {ServiceHost => src/ServiceHost}/Workspace/ScriptRegion.cs (100%) rename {ServiceHost => src/ServiceHost}/Workspace/Workspace.cs (100%) rename {ServiceHost => src/ServiceHost}/project.json (91%) create mode 100644 test/ServiceHost.Test/App.config create mode 100644 test/ServiceHost.Test/LanguageServer/JsonRpcMessageSerializerTests.cs create mode 100644 test/ServiceHost.Test/Message/MessageReaderWriterTests.cs create mode 100644 test/ServiceHost.Test/Message/TestMessageTypes.cs create mode 100644 test/ServiceHost.Test/PowerShellEditorServices.Test.Protocol.csproj create mode 100644 test/ServiceHost.Test/Properties/AssemblyInfo.cs create mode 100644 test/ServiceHost.Test/packages.config create mode 100644 test/ServiceHost.Test/project.json diff --git a/.gitignore b/.gitignore index d1fcfc4e..4c997e2b 100644 --- a/.gitignore +++ b/.gitignore @@ -1,3 +1,270 @@ -bin -obj -project.lock.json \ No newline at end of file +syntax: glob + +### VisualStudio ### + +# Project.json lock file +project.lock.json + +# Tool Runtime Dir +/[Tt]ools/ + +# User-specific files +*.suo +*.user +*.userosscache +*.sln.docstates + +# Build results +[Dd]ebug/ +[Dd]ebugPublic/ +[Rr]elease/ +[Rr]eleases/ +x64/ +x86/ +build/ +bld/ +[Bb]in/ +[Oo]bj/ +msbuild.log +msbuild.err +msbuild.wrn + + + +# Cross building rootfs +cross/rootfs/ + +# Visual Studio 2015 +.vs/ + +# Visual Studio 2015 Pre-CTP6 +*.sln.ide +*.ide/ + +# MSTest test Results +[Tt]est[Rr]esult*/ +[Bb]uild[Ll]og.* + +#NUNIT +*.VisualState.xml +TestResult.xml + +# Build Results of an ATL Project +[Dd]ebugPS/ +[Rr]eleasePS/ +dlldata.c + +*_i.c +*_p.c +*_i.h +*.ilk +*.meta +*.obj +*.pch +*.pdb +*.pgc +*.pgd +*.rsp +*.sbr +*.tlb +*.tli +*.tlh +*.tmp +*.tmp_proj +*.log +*.vspscc +*.vssscc +.builds +*.pidb +*.svclog +*.scc + +# Chutzpah Test files +_Chutzpah* + +# Visual C++ cache files +ipch/ +*.aps +*.ncb +*.opendb +*.opensdf +*.sdf +*.cachefile +*.VC.db + +# Visual Studio profiler +*.psess +*.vsp +*.vspx + +# TFS 2012 Local Workspace +$tf/ + +# Guidance Automation Toolkit +*.gpState + +# ReSharper is a .NET coding add-in +_ReSharper*/ +*.[Rr]e[Ss]harper +*.DotSettings.user + +# JustCode is a .NET coding addin-in +.JustCode + +# TeamCity is a build add-in +_TeamCity* + +# DotCover is a Code Coverage Tool +*.dotCover + +# NCrunch +_NCrunch_* +.*crunch*.local.xml + +# MightyMoose +*.mm.* +AutoTest.Net/ + +# Web workbench (sass) +.sass-cache/ + +# Installshield output folder +[Ee]xpress/ + +# DocProject is a documentation generator add-in +DocProject/buildhelp/ +DocProject/Help/*.HxT +DocProject/Help/*.HxC +DocProject/Help/*.hhc +DocProject/Help/*.hhk +DocProject/Help/*.hhp +DocProject/Help/Html2 +DocProject/Help/html + +# Click-Once directory +publish/ + +# Publish Web Output +*.[Pp]ublish.xml +*.azurePubxml +*.pubxml +*.publishproj + +# NuGet Packages +*.nuget.props +*.nuget.targets +*.nupkg +**/packages/* + +# NuGet package restore lockfiles +project.lock.json + +# Windows Azure Build Output +csx/ +*.build.csdef + +# Windows Store app package directory +AppPackages/ + +# Others +*.Cache +ClientBin/ +[Ss]tyle[Cc]op.* +~$* +*.dbmdl +*.dbproj.schemaview +*.pfx +*.publishsettings +node_modules/ +*.metaproj +*.metaproj.tmp + +# RIA/Silverlight projects +Generated_Code/ + +# Backup & report files from converting an old project file +# to a newer Visual Studio version. Backup files are not needed, +# because we have git ;-) +_UpgradeReport_Files/ +Backup*/ +UpgradeLog*.XML +UpgradeLog*.htm + +# SQL Server files +*.mdf +*.ldf + +# Business Intelligence projects +*.rdl.data +*.bim.layout +*.bim_*.settings + +# Microsoft Fakes +FakesAssemblies/ + +### MonoDevelop ### + +*.pidb +*.userprefs + +### Windows ### + +# Windows image file caches +Thumbs.db +ehthumbs.db + +# Folder config file +Desktop.ini + +# Recycle Bin used on file shares +$RECYCLE.BIN/ + +# Windows Installer files +*.cab +*.msi +*.msm +*.msp + +# Windows shortcuts +*.lnk + +### Linux ### + +*~ + +# KDE directory preferences +.directory + +### OSX ### + +.DS_Store +.AppleDouble +.LSOverride + +# Icon must end with two \r +Icon + +# Thumbnails +._* + +# Files that might appear on external disk +.Spotlight-V100 +.Trashes + +# Directories potentially created on remote AFP share +.AppleDB +.AppleDesktop +Network Trash Folder +Temporary Items +.apdisk + +# vim temporary files +[._]*.s[a-w][a-z] +[._]s[a-w][a-z] +*.un~ +Session.vim +.netrwhist +*~ + +# Visual Studio Code +.vscode/ diff --git a/ServiceHost/.vscode/launch.json b/ServiceHost/.vscode/launch.json deleted file mode 100644 index 18ebbb27..00000000 --- a/ServiceHost/.vscode/launch.json +++ /dev/null @@ -1,24 +0,0 @@ -{ - "version": "0.2.0", - "configurations": [ - { - "name": ".NET Core Launch (console)", - "type": "coreclr", - "request": "launch", - "preLaunchTask": "build", - "program": "${workspaceRoot}/bin/Debug/netcoreapp1.0/servicehost.dll", - "args": [], - "cwd": "${workspaceRoot}", - "externalConsole": true, - "requireExactSource": false, - "stopAtEntry": false - }, - { - "name": ".NET Core Attach", - "type": "coreclr", - "request": "attach", - "requireExactSource": false, - "processId": 17264 - } - ] -} \ No newline at end of file diff --git a/ServiceHost/.vscode/tasks.json b/ServiceHost/.vscode/tasks.json deleted file mode 100644 index 67d6eb75..00000000 --- a/ServiceHost/.vscode/tasks.json +++ /dev/null @@ -1,14 +0,0 @@ -{ - "version": "0.1.0", - "command": "dotnet", - "isShellCommand": true, - "args": [], - "tasks": [ - { - "taskName": "build", - "args": [], - "isBuildCommand": true, - "problemMatcher": "$msCompile" - } - ] -} \ No newline at end of file diff --git a/global.json b/global.json new file mode 100644 index 00000000..db6ba19b --- /dev/null +++ b/global.json @@ -0,0 +1,5 @@ +{ + "projects": [ "src", "test" ] +} + + diff --git a/ServiceHost/LanguageServer/ClientCapabilities.cs b/src/ServiceHost/LanguageServer/ClientCapabilities.cs similarity index 100% rename from ServiceHost/LanguageServer/ClientCapabilities.cs rename to src/ServiceHost/LanguageServer/ClientCapabilities.cs diff --git a/ServiceHost/LanguageServer/Completion.cs b/src/ServiceHost/LanguageServer/Completion.cs similarity index 100% rename from ServiceHost/LanguageServer/Completion.cs rename to src/ServiceHost/LanguageServer/Completion.cs diff --git a/ServiceHost/LanguageServer/Configuration.cs b/src/ServiceHost/LanguageServer/Configuration.cs similarity index 100% rename from ServiceHost/LanguageServer/Configuration.cs rename to src/ServiceHost/LanguageServer/Configuration.cs diff --git a/ServiceHost/LanguageServer/Definition.cs b/src/ServiceHost/LanguageServer/Definition.cs similarity index 100% rename from ServiceHost/LanguageServer/Definition.cs rename to src/ServiceHost/LanguageServer/Definition.cs diff --git a/ServiceHost/LanguageServer/Diagnostics.cs b/src/ServiceHost/LanguageServer/Diagnostics.cs similarity index 100% rename from ServiceHost/LanguageServer/Diagnostics.cs rename to src/ServiceHost/LanguageServer/Diagnostics.cs diff --git a/ServiceHost/LanguageServer/DocumentHighlight.cs b/src/ServiceHost/LanguageServer/DocumentHighlight.cs similarity index 100% rename from ServiceHost/LanguageServer/DocumentHighlight.cs rename to src/ServiceHost/LanguageServer/DocumentHighlight.cs diff --git a/ServiceHost/LanguageServer/ExpandAliasRequest.cs b/src/ServiceHost/LanguageServer/ExpandAliasRequest.cs similarity index 100% rename from ServiceHost/LanguageServer/ExpandAliasRequest.cs rename to src/ServiceHost/LanguageServer/ExpandAliasRequest.cs diff --git a/ServiceHost/LanguageServer/FindModuleRequest.cs b/src/ServiceHost/LanguageServer/FindModuleRequest.cs similarity index 100% rename from ServiceHost/LanguageServer/FindModuleRequest.cs rename to src/ServiceHost/LanguageServer/FindModuleRequest.cs diff --git a/ServiceHost/LanguageServer/Hover.cs b/src/ServiceHost/LanguageServer/Hover.cs similarity index 100% rename from ServiceHost/LanguageServer/Hover.cs rename to src/ServiceHost/LanguageServer/Hover.cs diff --git a/ServiceHost/LanguageServer/Initialize.cs b/src/ServiceHost/LanguageServer/Initialize.cs similarity index 100% rename from ServiceHost/LanguageServer/Initialize.cs rename to src/ServiceHost/LanguageServer/Initialize.cs diff --git a/ServiceHost/LanguageServer/InstallModuleRequest.cs b/src/ServiceHost/LanguageServer/InstallModuleRequest.cs similarity index 100% rename from ServiceHost/LanguageServer/InstallModuleRequest.cs rename to src/ServiceHost/LanguageServer/InstallModuleRequest.cs diff --git a/ServiceHost/LanguageServer/References.cs b/src/ServiceHost/LanguageServer/References.cs similarity index 100% rename from ServiceHost/LanguageServer/References.cs rename to src/ServiceHost/LanguageServer/References.cs diff --git a/ServiceHost/LanguageServer/ServerCapabilities.cs b/src/ServiceHost/LanguageServer/ServerCapabilities.cs similarity index 100% rename from ServiceHost/LanguageServer/ServerCapabilities.cs rename to src/ServiceHost/LanguageServer/ServerCapabilities.cs diff --git a/ServiceHost/LanguageServer/ShowOnlineHelpRequest.cs b/src/ServiceHost/LanguageServer/ShowOnlineHelpRequest.cs similarity index 100% rename from ServiceHost/LanguageServer/ShowOnlineHelpRequest.cs rename to src/ServiceHost/LanguageServer/ShowOnlineHelpRequest.cs diff --git a/ServiceHost/LanguageServer/Shutdown.cs b/src/ServiceHost/LanguageServer/Shutdown.cs similarity index 100% rename from ServiceHost/LanguageServer/Shutdown.cs rename to src/ServiceHost/LanguageServer/Shutdown.cs diff --git a/ServiceHost/LanguageServer/SignatureHelp.cs b/src/ServiceHost/LanguageServer/SignatureHelp.cs similarity index 100% rename from ServiceHost/LanguageServer/SignatureHelp.cs rename to src/ServiceHost/LanguageServer/SignatureHelp.cs diff --git a/ServiceHost/LanguageServer/TextDocument.cs b/src/ServiceHost/LanguageServer/TextDocument.cs similarity index 100% rename from ServiceHost/LanguageServer/TextDocument.cs rename to src/ServiceHost/LanguageServer/TextDocument.cs diff --git a/ServiceHost/LanguageServer/WorkspaceSymbols.cs b/src/ServiceHost/LanguageServer/WorkspaceSymbols.cs similarity index 100% rename from ServiceHost/LanguageServer/WorkspaceSymbols.cs rename to src/ServiceHost/LanguageServer/WorkspaceSymbols.cs diff --git a/ServiceHost/LanguageSupport/LanguageService.cs b/src/ServiceHost/LanguageSupport/LanguageService.cs similarity index 100% rename from ServiceHost/LanguageSupport/LanguageService.cs rename to src/ServiceHost/LanguageSupport/LanguageService.cs diff --git a/ServiceHost/MessageProtocol/Channel/ChannelBase.cs b/src/ServiceHost/MessageProtocol/Channel/ChannelBase.cs similarity index 100% rename from ServiceHost/MessageProtocol/Channel/ChannelBase.cs rename to src/ServiceHost/MessageProtocol/Channel/ChannelBase.cs diff --git a/ServiceHost/MessageProtocol/Channel/StdioClientChannel.cs b/src/ServiceHost/MessageProtocol/Channel/StdioClientChannel.cs similarity index 100% rename from ServiceHost/MessageProtocol/Channel/StdioClientChannel.cs rename to src/ServiceHost/MessageProtocol/Channel/StdioClientChannel.cs diff --git a/ServiceHost/MessageProtocol/Channel/StdioServerChannel.cs b/src/ServiceHost/MessageProtocol/Channel/StdioServerChannel.cs similarity index 100% rename from ServiceHost/MessageProtocol/Channel/StdioServerChannel.cs rename to src/ServiceHost/MessageProtocol/Channel/StdioServerChannel.cs diff --git a/ServiceHost/MessageProtocol/Constants.cs b/src/ServiceHost/MessageProtocol/Constants.cs similarity index 100% rename from ServiceHost/MessageProtocol/Constants.cs rename to src/ServiceHost/MessageProtocol/Constants.cs diff --git a/ServiceHost/MessageProtocol/EventContext.cs b/src/ServiceHost/MessageProtocol/EventContext.cs similarity index 100% rename from ServiceHost/MessageProtocol/EventContext.cs rename to src/ServiceHost/MessageProtocol/EventContext.cs diff --git a/ServiceHost/MessageProtocol/EventType.cs b/src/ServiceHost/MessageProtocol/EventType.cs similarity index 100% rename from ServiceHost/MessageProtocol/EventType.cs rename to src/ServiceHost/MessageProtocol/EventType.cs diff --git a/ServiceHost/MessageProtocol/IMessageSender.cs b/src/ServiceHost/MessageProtocol/IMessageSender.cs similarity index 100% rename from ServiceHost/MessageProtocol/IMessageSender.cs rename to src/ServiceHost/MessageProtocol/IMessageSender.cs diff --git a/ServiceHost/MessageProtocol/IMessageSerializer.cs b/src/ServiceHost/MessageProtocol/IMessageSerializer.cs similarity index 100% rename from ServiceHost/MessageProtocol/IMessageSerializer.cs rename to src/ServiceHost/MessageProtocol/IMessageSerializer.cs diff --git a/ServiceHost/MessageProtocol/Message.cs b/src/ServiceHost/MessageProtocol/Message.cs similarity index 100% rename from ServiceHost/MessageProtocol/Message.cs rename to src/ServiceHost/MessageProtocol/Message.cs diff --git a/ServiceHost/MessageProtocol/MessageDispatcher.cs b/src/ServiceHost/MessageProtocol/MessageDispatcher.cs similarity index 100% rename from ServiceHost/MessageProtocol/MessageDispatcher.cs rename to src/ServiceHost/MessageProtocol/MessageDispatcher.cs diff --git a/ServiceHost/MessageProtocol/MessageParseException.cs b/src/ServiceHost/MessageProtocol/MessageParseException.cs similarity index 100% rename from ServiceHost/MessageProtocol/MessageParseException.cs rename to src/ServiceHost/MessageProtocol/MessageParseException.cs diff --git a/ServiceHost/MessageProtocol/MessageProtocolType.cs b/src/ServiceHost/MessageProtocol/MessageProtocolType.cs similarity index 100% rename from ServiceHost/MessageProtocol/MessageProtocolType.cs rename to src/ServiceHost/MessageProtocol/MessageProtocolType.cs diff --git a/ServiceHost/MessageProtocol/MessageReader.cs b/src/ServiceHost/MessageProtocol/MessageReader.cs similarity index 100% rename from ServiceHost/MessageProtocol/MessageReader.cs rename to src/ServiceHost/MessageProtocol/MessageReader.cs diff --git a/ServiceHost/MessageProtocol/MessageWriter.cs b/src/ServiceHost/MessageProtocol/MessageWriter.cs similarity index 100% rename from ServiceHost/MessageProtocol/MessageWriter.cs rename to src/ServiceHost/MessageProtocol/MessageWriter.cs diff --git a/ServiceHost/MessageProtocol/ProtocolEndpoint.cs b/src/ServiceHost/MessageProtocol/ProtocolEndpoint.cs similarity index 100% rename from ServiceHost/MessageProtocol/ProtocolEndpoint.cs rename to src/ServiceHost/MessageProtocol/ProtocolEndpoint.cs diff --git a/ServiceHost/MessageProtocol/RequestContext.cs b/src/ServiceHost/MessageProtocol/RequestContext.cs similarity index 100% rename from ServiceHost/MessageProtocol/RequestContext.cs rename to src/ServiceHost/MessageProtocol/RequestContext.cs diff --git a/ServiceHost/MessageProtocol/RequestType.cs b/src/ServiceHost/MessageProtocol/RequestType.cs similarity index 100% rename from ServiceHost/MessageProtocol/RequestType.cs rename to src/ServiceHost/MessageProtocol/RequestType.cs diff --git a/ServiceHost/MessageProtocol/Serializers/JsonRpcMessageSerializer.cs b/src/ServiceHost/MessageProtocol/Serializers/JsonRpcMessageSerializer.cs similarity index 100% rename from ServiceHost/MessageProtocol/Serializers/JsonRpcMessageSerializer.cs rename to src/ServiceHost/MessageProtocol/Serializers/JsonRpcMessageSerializer.cs diff --git a/ServiceHost/MessageProtocol/Serializers/V8MessageSerializer.cs b/src/ServiceHost/MessageProtocol/Serializers/V8MessageSerializer.cs similarity index 100% rename from ServiceHost/MessageProtocol/Serializers/V8MessageSerializer.cs rename to src/ServiceHost/MessageProtocol/Serializers/V8MessageSerializer.cs diff --git a/ServiceHost/Program.cs b/src/ServiceHost/Program.cs similarity index 100% rename from ServiceHost/Program.cs rename to src/ServiceHost/Program.cs diff --git a/ServiceHost/Properties/AssemblyInfo.cs b/src/ServiceHost/Properties/AssemblyInfo.cs similarity index 100% rename from ServiceHost/Properties/AssemblyInfo.cs rename to src/ServiceHost/Properties/AssemblyInfo.cs diff --git a/ServiceHost/Server/LanguageServer.cs b/src/ServiceHost/Server/LanguageServer.cs similarity index 100% rename from ServiceHost/Server/LanguageServer.cs rename to src/ServiceHost/Server/LanguageServer.cs diff --git a/ServiceHost/Server/LanguageServerBase.cs b/src/ServiceHost/Server/LanguageServerBase.cs similarity index 100% rename from ServiceHost/Server/LanguageServerBase.cs rename to src/ServiceHost/Server/LanguageServerBase.cs diff --git a/ServiceHost/Server/LanguageServerEditorOperations.cs b/src/ServiceHost/Server/LanguageServerEditorOperations.cs similarity index 100% rename from ServiceHost/Server/LanguageServerEditorOperations.cs rename to src/ServiceHost/Server/LanguageServerEditorOperations.cs diff --git a/ServiceHost/Server/LanguageServerSettings.cs b/src/ServiceHost/Server/LanguageServerSettings.cs similarity index 100% rename from ServiceHost/Server/LanguageServerSettings.cs rename to src/ServiceHost/Server/LanguageServerSettings.cs diff --git a/ServiceHost/Session/EditorSession.cs b/src/ServiceHost/Session/EditorSession.cs similarity index 100% rename from ServiceHost/Session/EditorSession.cs rename to src/ServiceHost/Session/EditorSession.cs diff --git a/ServiceHost/Session/HostDetails.cs b/src/ServiceHost/Session/HostDetails.cs similarity index 100% rename from ServiceHost/Session/HostDetails.cs rename to src/ServiceHost/Session/HostDetails.cs diff --git a/ServiceHost/Session/OutputType.cs b/src/ServiceHost/Session/OutputType.cs similarity index 100% rename from ServiceHost/Session/OutputType.cs rename to src/ServiceHost/Session/OutputType.cs diff --git a/ServiceHost/Session/OutputWrittenEventArgs.cs b/src/ServiceHost/Session/OutputWrittenEventArgs.cs similarity index 100% rename from ServiceHost/Session/OutputWrittenEventArgs.cs rename to src/ServiceHost/Session/OutputWrittenEventArgs.cs diff --git a/ServiceHost/Session/ProfilePaths.cs b/src/ServiceHost/Session/ProfilePaths.cs similarity index 100% rename from ServiceHost/Session/ProfilePaths.cs rename to src/ServiceHost/Session/ProfilePaths.cs diff --git a/ServiceHost/Session/SqlToolsContext.cs b/src/ServiceHost/Session/SqlToolsContext.cs similarity index 100% rename from ServiceHost/Session/SqlToolsContext.cs rename to src/ServiceHost/Session/SqlToolsContext.cs diff --git a/ServiceHost/Utility/AsyncContext.cs b/src/ServiceHost/Utility/AsyncContext.cs similarity index 100% rename from ServiceHost/Utility/AsyncContext.cs rename to src/ServiceHost/Utility/AsyncContext.cs diff --git a/ServiceHost/Utility/AsyncContextThread.cs b/src/ServiceHost/Utility/AsyncContextThread.cs similarity index 100% rename from ServiceHost/Utility/AsyncContextThread.cs rename to src/ServiceHost/Utility/AsyncContextThread.cs diff --git a/ServiceHost/Utility/AsyncLock.cs b/src/ServiceHost/Utility/AsyncLock.cs similarity index 100% rename from ServiceHost/Utility/AsyncLock.cs rename to src/ServiceHost/Utility/AsyncLock.cs diff --git a/ServiceHost/Utility/AsyncQueue.cs b/src/ServiceHost/Utility/AsyncQueue.cs similarity index 100% rename from ServiceHost/Utility/AsyncQueue.cs rename to src/ServiceHost/Utility/AsyncQueue.cs diff --git a/ServiceHost/Utility/Extensions.cs b/src/ServiceHost/Utility/Extensions.cs similarity index 100% rename from ServiceHost/Utility/Extensions.cs rename to src/ServiceHost/Utility/Extensions.cs diff --git a/ServiceHost/Utility/Logger.cs b/src/ServiceHost/Utility/Logger.cs similarity index 100% rename from ServiceHost/Utility/Logger.cs rename to src/ServiceHost/Utility/Logger.cs diff --git a/ServiceHost/Utility/ThreadSynchronizationContext.cs b/src/ServiceHost/Utility/ThreadSynchronizationContext.cs similarity index 100% rename from ServiceHost/Utility/ThreadSynchronizationContext.cs rename to src/ServiceHost/Utility/ThreadSynchronizationContext.cs diff --git a/ServiceHost/Utility/Validate.cs b/src/ServiceHost/Utility/Validate.cs similarity index 100% rename from ServiceHost/Utility/Validate.cs rename to src/ServiceHost/Utility/Validate.cs diff --git a/ServiceHost/Workspace/BufferPosition.cs b/src/ServiceHost/Workspace/BufferPosition.cs similarity index 100% rename from ServiceHost/Workspace/BufferPosition.cs rename to src/ServiceHost/Workspace/BufferPosition.cs diff --git a/ServiceHost/Workspace/BufferRange.cs b/src/ServiceHost/Workspace/BufferRange.cs similarity index 100% rename from ServiceHost/Workspace/BufferRange.cs rename to src/ServiceHost/Workspace/BufferRange.cs diff --git a/ServiceHost/Workspace/FileChange.cs b/src/ServiceHost/Workspace/FileChange.cs similarity index 100% rename from ServiceHost/Workspace/FileChange.cs rename to src/ServiceHost/Workspace/FileChange.cs diff --git a/ServiceHost/Workspace/FilePosition.cs b/src/ServiceHost/Workspace/FilePosition.cs similarity index 100% rename from ServiceHost/Workspace/FilePosition.cs rename to src/ServiceHost/Workspace/FilePosition.cs diff --git a/ServiceHost/Workspace/ScriptFile.cs b/src/ServiceHost/Workspace/ScriptFile.cs similarity index 100% rename from ServiceHost/Workspace/ScriptFile.cs rename to src/ServiceHost/Workspace/ScriptFile.cs diff --git a/ServiceHost/Workspace/ScriptFileMarker.cs b/src/ServiceHost/Workspace/ScriptFileMarker.cs similarity index 100% rename from ServiceHost/Workspace/ScriptFileMarker.cs rename to src/ServiceHost/Workspace/ScriptFileMarker.cs diff --git a/ServiceHost/Workspace/ScriptRegion.cs b/src/ServiceHost/Workspace/ScriptRegion.cs similarity index 100% rename from ServiceHost/Workspace/ScriptRegion.cs rename to src/ServiceHost/Workspace/ScriptRegion.cs diff --git a/ServiceHost/Workspace/Workspace.cs b/src/ServiceHost/Workspace/Workspace.cs similarity index 100% rename from ServiceHost/Workspace/Workspace.cs rename to src/ServiceHost/Workspace/Workspace.cs diff --git a/ServiceHost/project.json b/src/ServiceHost/project.json similarity index 91% rename from ServiceHost/project.json rename to src/ServiceHost/project.json index 28565355..11340892 100644 --- a/ServiceHost/project.json +++ b/src/ServiceHost/project.json @@ -5,7 +5,7 @@ "emitEntryPoint": true }, "dependencies": { - "Newtonsoft.Json": "9.0.1", + "Newtonsoft.Json": "9.0.1" }, "frameworks": { "netcoreapp1.0": { diff --git a/test/ServiceHost.Test/App.config b/test/ServiceHost.Test/App.config new file mode 100644 index 00000000..570b96df --- /dev/null +++ b/test/ServiceHost.Test/App.config @@ -0,0 +1,9 @@ + + + + + + + + + \ No newline at end of file diff --git a/test/ServiceHost.Test/LanguageServer/JsonRpcMessageSerializerTests.cs b/test/ServiceHost.Test/LanguageServer/JsonRpcMessageSerializerTests.cs new file mode 100644 index 00000000..9ec341c5 --- /dev/null +++ b/test/ServiceHost.Test/LanguageServer/JsonRpcMessageSerializerTests.cs @@ -0,0 +1,144 @@ +// +// Copyright (c) Microsoft. All rights reserved. +// Licensed under the MIT license. See LICENSE file in the project root for full license information. +// + +using Microsoft.SqlTools.EditorServices.Protocol.MessageProtocol; +using Microsoft.SqlTools.EditorServices.Protocol.MessageProtocol.Serializers; +using Newtonsoft.Json.Linq; +using Xunit; + +namespace Microsoft.SqlTools.EditorServices.Test.Protocol.LanguageServer +{ + public class TestMessageContents + { + public const string SomeFieldValue = "Some value"; + public const int NumberValue = 42; + + public string SomeField { get; set; } + + public int Number { get; set; } + + public TestMessageContents() + { + this.SomeField = SomeFieldValue; + this.Number = NumberValue; + } + } + + public class JsonRpcMessageSerializerTests + { + private IMessageSerializer messageSerializer; + + private const string MessageId = "42"; + private const string MethodName = "testMethod"; + private static readonly JToken MessageContent = JToken.FromObject(new TestMessageContents()); + + public JsonRpcMessageSerializerTests() + { + this.messageSerializer = new JsonRpcMessageSerializer(); + } + + [Fact] + public void SerializesRequestMessages() + { + var messageObj = + this.messageSerializer.SerializeMessage( + Message.Request( + MessageId, + MethodName, + MessageContent)); + + AssertMessageFields( + messageObj, + checkId: true, + checkMethod: true, + checkParams: true); + } + + [Fact] + public void SerializesEventMessages() + { + var messageObj = + this.messageSerializer.SerializeMessage( + Message.Event( + MethodName, + MessageContent)); + + AssertMessageFields( + messageObj, + checkMethod: true, + checkParams: true); + } + + [Fact] + public void SerializesResponseMessages() + { + var messageObj = + this.messageSerializer.SerializeMessage( + Message.Response( + MessageId, + null, + MessageContent)); + + AssertMessageFields( + messageObj, + checkId: true, + checkResult: true); + } + + [Fact] + public void SerializesResponseWithErrorMessages() + { + var messageObj = + this.messageSerializer.SerializeMessage( + Message.ResponseError( + MessageId, + null, + MessageContent)); + + AssertMessageFields( + messageObj, + checkId: true, + checkError: true); + } + + private static void AssertMessageFields( + JObject messageObj, + bool checkId = false, + bool checkMethod = false, + bool checkParams = false, + bool checkResult = false, + bool checkError = false) + { + JToken token = null; + + Assert.True(messageObj.TryGetValue("jsonrpc", out token)); + Assert.Equal("2.0", token.ToString()); + + if (checkId) + { + Assert.True(messageObj.TryGetValue("id", out token)); + Assert.Equal(MessageId, token.ToString()); + } + + if (checkMethod) + { + Assert.True(messageObj.TryGetValue("method", out token)); + Assert.Equal(MethodName, token.ToString()); + } + + if (checkError) + { + // TODO + } + else + { + string contentField = checkParams ? "params" : "result"; + Assert.True(messageObj.TryGetValue(contentField, out token)); + Assert.True(JToken.DeepEquals(token, MessageContent)); + } + } + } +} + diff --git a/test/ServiceHost.Test/Message/MessageReaderWriterTests.cs b/test/ServiceHost.Test/Message/MessageReaderWriterTests.cs new file mode 100644 index 00000000..82e619f5 --- /dev/null +++ b/test/ServiceHost.Test/Message/MessageReaderWriterTests.cs @@ -0,0 +1,177 @@ +// +// Copyright (c) Microsoft. All rights reserved. +// Licensed under the MIT license. See LICENSE file in the project root for full license information. +// + +using Microsoft.SqlTools.EditorServices.Protocol.MessageProtocol; +using Microsoft.SqlTools.EditorServices.Protocol.MessageProtocol.Serializers; +using System; +using System.IO; +using System.Text; +using System.Threading.Tasks; +using Xunit; + +namespace Microsoft.SqlTools.EditorServices.Test.Protocol.MessageProtocol +{ + public class MessageReaderWriterTests + { + const string TestEventString = "{\"type\":\"event\",\"event\":\"testEvent\",\"body\":null}"; + const string TestEventFormatString = "{{\"event\":\"testEvent\",\"body\":{{\"someString\":\"{0}\"}},\"seq\":0,\"type\":\"event\"}}"; + readonly int ExpectedMessageByteCount = Encoding.UTF8.GetByteCount(TestEventString); + + private IMessageSerializer messageSerializer; + + public MessageReaderWriterTests() + { + this.messageSerializer = new V8MessageSerializer(); + } + + [Fact] + public async Task WritesMessage() + { + MemoryStream outputStream = new MemoryStream(); + + MessageWriter messageWriter = + new MessageWriter( + outputStream, + this.messageSerializer); + + // 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)); + outputStream.Seek(0, SeekOrigin.Begin); + + string expectedHeaderString = + string.Format( + Constants.ContentLengthFormatString, + ExpectedMessageByteCount); + + byte[] buffer = new byte[128]; + await outputStream.ReadAsync(buffer, 0, expectedHeaderString.Length); + + Assert.Equal( + expectedHeaderString, + Encoding.ASCII.GetString(buffer, 0, expectedHeaderString.Length)); + + // Read the message + await outputStream.ReadAsync(buffer, 0, ExpectedMessageByteCount); + + Assert.Equal( + TestEventString, + Encoding.UTF8.GetString(buffer, 0, ExpectedMessageByteCount)); + + outputStream.Dispose(); + } + + [Fact] + public void ReadsMessage() + { + MemoryStream inputStream = new MemoryStream(); + MessageReader messageReader = + new MessageReader( + inputStream, + this.messageSerializer); + + // Write a message to the stream + byte[] messageBuffer = this.GetMessageBytes(TestEventString); + inputStream.Write( + this.GetMessageBytes(TestEventString), + 0, + messageBuffer.Length); + + inputStream.Flush(); + inputStream.Seek(0, SeekOrigin.Begin); + + Message messageResult = messageReader.ReadMessage().Result; + Assert.Equal("testEvent", messageResult.Method); + + inputStream.Dispose(); + } + + [Fact] + public void ReadsManyBufferedMessages() + { + MemoryStream inputStream = new MemoryStream(); + MessageReader messageReader = + new MessageReader( + inputStream, + this.messageSerializer); + + // Get a message to use for writing to the stream + byte[] messageBuffer = this.GetMessageBytes(TestEventString); + + // How many messages of this size should we write to overflow the buffer? + int overflowMessageCount = + (int)Math.Ceiling( + (MessageReader.DefaultBufferSize * 1.5) / messageBuffer.Length); + + // Write the necessary number of messages to the stream + for (int i = 0; i < overflowMessageCount; i++) + { + inputStream.Write(messageBuffer, 0, messageBuffer.Length); + } + + inputStream.Flush(); + inputStream.Seek(0, SeekOrigin.Begin); + + // Read the written messages from the stream + for (int i = 0; i < overflowMessageCount; i++) + { + Message messageResult = messageReader.ReadMessage().Result; + Assert.Equal("testEvent", messageResult.Method); + } + + inputStream.Dispose(); + } + + [Fact] + public void ReaderResizesBufferForLargeMessages() + { + MemoryStream inputStream = new MemoryStream(); + MessageReader messageReader = + new MessageReader( + inputStream, + this.messageSerializer); + + // Get a message with content so large that the buffer will need + // to be resized to fit it all. + byte[] messageBuffer = + this.GetMessageBytes( + string.Format( + TestEventFormatString, + new String('X', (int)(MessageReader.DefaultBufferSize * 3)))); + + inputStream.Write(messageBuffer, 0, messageBuffer.Length); + inputStream.Flush(); + inputStream.Seek(0, SeekOrigin.Begin); + + Message messageResult = messageReader.ReadMessage().Result; + Assert.Equal("testEvent", messageResult.Method); + + inputStream.Dispose(); + } + + private byte[] GetMessageBytes(string messageString, Encoding encoding = null) + { + if (encoding == null) + { + encoding = Encoding.UTF8; + } + + byte[] messageBytes = Encoding.UTF8.GetBytes(messageString); + byte[] headerBytes = + Encoding.ASCII.GetBytes( + string.Format( + Constants.ContentLengthFormatString, + messageBytes.Length)); + + // Copy the bytes into a single buffer + byte[] finalBytes = new byte[headerBytes.Length + messageBytes.Length]; + Buffer.BlockCopy(headerBytes, 0, finalBytes, 0, headerBytes.Length); + Buffer.BlockCopy(messageBytes, 0, finalBytes, headerBytes.Length, messageBytes.Length); + + return finalBytes; + } + } +} + diff --git a/test/ServiceHost.Test/Message/TestMessageTypes.cs b/test/ServiceHost.Test/Message/TestMessageTypes.cs new file mode 100644 index 00000000..cc5981dc --- /dev/null +++ b/test/ServiceHost.Test/Message/TestMessageTypes.cs @@ -0,0 +1,56 @@ +// +// Copyright (c) Microsoft. All rights reserved. +// Licensed under the MIT license. See LICENSE file in the project root for full license information. +// + +using Microsoft.SqlTools.EditorServices.Protocol.MessageProtocol; +using System; +using System.Threading.Tasks; + +namespace Microsoft.SqlTools.EditorServices.Test.Protocol.MessageProtocol +{ + #region Request Types + + internal class TestRequest + { + public Task ProcessMessage( + EditorSession editorSession, + MessageWriter messageWriter) + { + return Task.FromResult(false); + } + } + + internal class TestRequestArguments + { + public string SomeString { get; set; } + } + + #endregion + + #region Response Types + + internal class TestResponse + { + } + + internal class TestResponseBody + { + public string SomeString { get; set; } + } + + #endregion + + #region Event Types + + internal class TestEvent + { + } + + internal class TestEventBody + { + public string SomeString { get; set; } + } + + #endregion +} diff --git a/test/ServiceHost.Test/PowerShellEditorServices.Test.Protocol.csproj b/test/ServiceHost.Test/PowerShellEditorServices.Test.Protocol.csproj new file mode 100644 index 00000000..54e20896 --- /dev/null +++ b/test/ServiceHost.Test/PowerShellEditorServices.Test.Protocol.csproj @@ -0,0 +1,109 @@ + + + + + + + Debug + AnyCPU + {E3A5CF5D-6E41-44AC-AE0A-4C227E4BACD4} + Library + Properties + Microsoft.SqlTools.EditorServices.Test.Protocol + Microsoft.SqlTools.EditorServices.Test.Protocol + v4.6.1 + 512 + 69e9ba79 + ..\..\ + true + + + + true + full + false + bin\Debug\ + DEBUG;TRACE + prompt + 4 + + + pdbonly + true + bin\Release\ + TRACE + prompt + 4 + + + + ..\..\packages\Newtonsoft.Json.8.0.2\lib\net45\Newtonsoft.Json.dll + True + + + + + + + + + + ..\..\packages\xunit.abstractions.2.0.0\lib\net35\xunit.abstractions.dll + True + + + ..\..\packages\xunit.assert.2.1.0\lib\portable-net45+win8+wp8+wpa81\xunit.assert.dll + True + + + ..\..\packages\xunit.extensibility.core.2.1.0\lib\portable-net45+win8+wp8+wpa81\xunit.core.dll + True + + + ..\..\packages\xunit.extensibility.execution.2.1.0\lib\net45\xunit.execution.desktop.dll + True + + + + + + + + + + + + + + + + + {f8a0946a-5d25-4651-8079-b8d5776916fb} + SqlToolsEditorServices.Protocol + + + {81e8cbcd-6319-49e7-9662-0475bd0791f4} + SqlToolsEditorServices + + + + + + + + + This project references NuGet package(s) that are missing on this computer. Enable NuGet Package Restore to download them. For more information, see http://go.microsoft.com/fwlink/?LinkID=322105. The missing file is {0}. + + + + + + + + \ No newline at end of file diff --git a/test/ServiceHost.Test/Properties/AssemblyInfo.cs b/test/ServiceHost.Test/Properties/AssemblyInfo.cs new file mode 100644 index 00000000..5cf54b90 --- /dev/null +++ b/test/ServiceHost.Test/Properties/AssemblyInfo.cs @@ -0,0 +1,42 @@ +// +// Copyright (c) Microsoft. All rights reserved. +// Licensed under the MIT license. See LICENSE file in the project root for full license information. +// + +using System.Reflection; +using System.Runtime.CompilerServices; +using System.Runtime.InteropServices; + +// General Information about an assembly is controlled through the following +// set of attributes. Change these attribute values to modify the information +// associated with an assembly. +[assembly: AssemblyTitle("SqlToolsEditorServices.Test.Transport.Stdio")] +[assembly: AssemblyDescription("")] +[assembly: AssemblyConfiguration("")] +[assembly: AssemblyCompany("")] +[assembly: AssemblyProduct("SqlToolsEditorServices.Test.Transport.Stdio")] +[assembly: AssemblyCopyright("Copyright � 2015")] +[assembly: AssemblyTrademark("")] +[assembly: AssemblyCulture("")] + +// Setting ComVisible to false makes the types in this assembly not visible +// to COM components. If you need to access a type in this assembly from +// COM, set the ComVisible attribute to true on that type. +[assembly: ComVisible(false)] + +// The following GUID is for the ID of the typelib if this project is exposed to COM +[assembly: Guid("07137FCA-76D0-4CE7-9764-C21DB7A57093")] + +// Version information for an assembly consists of the following four values: +// +// Major Version +// Minor Version +// Build Number +// Revision +// +// You can specify all the values or you can default the Build and Revision Numbers +// by using the '*' as shown below: +// [assembly: AssemblyVersion("1.0.*")] +[assembly: AssemblyVersion("1.0.0.0")] +[assembly: AssemblyFileVersion("1.0.0.0")] + diff --git a/test/ServiceHost.Test/packages.config b/test/ServiceHost.Test/packages.config new file mode 100644 index 00000000..d01e8969 --- /dev/null +++ b/test/ServiceHost.Test/packages.config @@ -0,0 +1,11 @@ + + + + + + + + + + + \ No newline at end of file diff --git a/test/ServiceHost.Test/project.json b/test/ServiceHost.Test/project.json new file mode 100644 index 00000000..b7f00724 --- /dev/null +++ b/test/ServiceHost.Test/project.json @@ -0,0 +1,30 @@ +{ + "version": "1.0.0-*", + "buildOptions": { + "debugType": "portable" + }, + "dependencies": { + "Newtonsoft.Json": "9.0.1", + "System.Runtime.Serialization.Primitives": "4.1.1", + "xunit": "2.1.0", + "dotnet-test-xunit": "1.0.0-rc2-192208-24", + "ServiceHost": { + "target": "project" + } + }, + "testRunner": "xunit", + "frameworks": { + "netcoreapp1.0": { + "dependencies": { + "Microsoft.NETCore.App": { + "type": "platform", + "version": "1.0.0" + } + }, + "imports": [ + "dotnet5.4", + "portable-net451+win8" + ] + } + } +} From 2a6a33fc11bcad28b6a1e760bf06dd9ff7b0744e Mon Sep 17 00:00:00 2001 From: benrr101 Date: Tue, 19 Jul 2016 14:56:44 -0700 Subject: [PATCH 5/6] Adding VS2015 support for ServiceHost project Creating the standard sln flies for the root of the sqltoolsservice project and adding xproj files for the individual projects. Has been confirmed to open and build with VS2015. xUnit tests will work, but only from Test Explorer (ie, ReSharper test runner doesn't work with dnx) Note: This may be subject to change as new standards for .NET Core project files are developed. See dotnet/roslyn-project-system#37 for more details. --- global.json | 5 ++- sqltoolsservice.sln | 40 ++++++++++++++++++++ src/ServiceHost/ServiceHost.xproj | 20 ++++++++++ test/ServiceHost.Test/ServiceHost.Test.xproj | 19 ++++++++++ 4 files changed, 83 insertions(+), 1 deletion(-) create mode 100644 sqltoolsservice.sln create mode 100644 src/ServiceHost/ServiceHost.xproj create mode 100644 test/ServiceHost.Test/ServiceHost.Test.xproj diff --git a/global.json b/global.json index db6ba19b..9ae78d22 100644 --- a/global.json +++ b/global.json @@ -1,5 +1,8 @@ { - "projects": [ "src", "test" ] + "projects": [ "src", "test" ], + "sdk": { + "version": "1.0.0-preview2-003121" + } } diff --git a/sqltoolsservice.sln b/sqltoolsservice.sln new file mode 100644 index 00000000..b993537f --- /dev/null +++ b/sqltoolsservice.sln @@ -0,0 +1,40 @@ +Microsoft Visual Studio Solution File, Format Version 12.00 +# Visual Studio 14 +VisualStudioVersion = 14.0.25420.1 +MinimumVisualStudioVersion = 10.0.40219.1 +Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "src", "src", "{2BBD7364-054F-4693-97CD-1C395E3E84A9}" +EndProject +Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "test", "test", "{AB9CA2B8-6F70-431C-8A1D-67479D8A7BE4}" +EndProject +Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "Solution Items", "Solution Items", "{32DC973E-9EEA-4694-B1C2-B031167AB945}" + ProjectSection(SolutionItems) = preProject + global.json = global.json + EndProjectSection +EndProject +Project("{8BB2217D-0F2D-49D1-97BC-3654ED321F3B}") = "ServiceHost", "src\ServiceHost\ServiceHost.xproj", "{0D61DC2B-DA66-441D-B9D0-F76C98F780F9}" +EndProject +Project("{8BB2217D-0F2D-49D1-97BC-3654ED321F3B}") = "ServiceHost.Test", "test\ServiceHost.Test\ServiceHost.Test.xproj", "{2D771D16-9D85-4053-9F79-E2034737DEEF}" +EndProject +Global + GlobalSection(SolutionConfigurationPlatforms) = preSolution + Debug|Any CPU = Debug|Any CPU + Release|Any CPU = Release|Any CPU + EndGlobalSection + GlobalSection(ProjectConfigurationPlatforms) = postSolution + {0D61DC2B-DA66-441D-B9D0-F76C98F780F9}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {0D61DC2B-DA66-441D-B9D0-F76C98F780F9}.Debug|Any CPU.Build.0 = Debug|Any CPU + {0D61DC2B-DA66-441D-B9D0-F76C98F780F9}.Release|Any CPU.ActiveCfg = Release|Any CPU + {0D61DC2B-DA66-441D-B9D0-F76C98F780F9}.Release|Any CPU.Build.0 = Release|Any CPU + {2D771D16-9D85-4053-9F79-E2034737DEEF}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {2D771D16-9D85-4053-9F79-E2034737DEEF}.Debug|Any CPU.Build.0 = Debug|Any CPU + {2D771D16-9D85-4053-9F79-E2034737DEEF}.Release|Any CPU.ActiveCfg = Release|Any CPU + {2D771D16-9D85-4053-9F79-E2034737DEEF}.Release|Any CPU.Build.0 = Release|Any CPU + EndGlobalSection + GlobalSection(SolutionProperties) = preSolution + HideSolutionNode = FALSE + EndGlobalSection + GlobalSection(NestedProjects) = preSolution + {0D61DC2B-DA66-441D-B9D0-F76C98F780F9} = {2BBD7364-054F-4693-97CD-1C395E3E84A9} + {2D771D16-9D85-4053-9F79-E2034737DEEF} = {AB9CA2B8-6F70-431C-8A1D-67479D8A7BE4} + EndGlobalSection +EndGlobal diff --git a/src/ServiceHost/ServiceHost.xproj b/src/ServiceHost/ServiceHost.xproj new file mode 100644 index 00000000..ac743bab --- /dev/null +++ b/src/ServiceHost/ServiceHost.xproj @@ -0,0 +1,20 @@ + + + + 14.0 + $(MSBuildExtensionsPath32)\Microsoft\VisualStudio\v$(VisualStudioVersion) + + + + {0D61DC2B-DA66-441D-B9D0-F76C98F780F9} + Microsoft.SqlTools.ServiceHost + .\obj + .\bin\ + v4.5.2 + + + + 2.0 + + + diff --git a/test/ServiceHost.Test/ServiceHost.Test.xproj b/test/ServiceHost.Test/ServiceHost.Test.xproj new file mode 100644 index 00000000..7e4a3242 --- /dev/null +++ b/test/ServiceHost.Test/ServiceHost.Test.xproj @@ -0,0 +1,19 @@ + + + + 14.0 + $(MSBuildExtensionsPath32)\Microsoft\VisualStudio\v$(VisualStudioVersion) + + + + 2d771d16-9d85-4053-9f79-e2034737deef + Microsoft.SqlTools.EditorServices.Test.Protocol + .\obj + .\bin\ + v4.5.2 + + + 2.0 + + + \ No newline at end of file From 5517d9da817a114faeccb23458fbc9b0d6c7f339 Mon Sep 17 00:00:00 2001 From: benrr101 Date: Tue, 19 Jul 2016 16:15:21 -0700 Subject: [PATCH 6/6] Removing dead csproj file --- ...erShellEditorServices.Test.Protocol.csproj | 109 ------------------ 1 file changed, 109 deletions(-) delete mode 100644 test/ServiceHost.Test/PowerShellEditorServices.Test.Protocol.csproj diff --git a/test/ServiceHost.Test/PowerShellEditorServices.Test.Protocol.csproj b/test/ServiceHost.Test/PowerShellEditorServices.Test.Protocol.csproj deleted file mode 100644 index 54e20896..00000000 --- a/test/ServiceHost.Test/PowerShellEditorServices.Test.Protocol.csproj +++ /dev/null @@ -1,109 +0,0 @@ - - - - - - - Debug - AnyCPU - {E3A5CF5D-6E41-44AC-AE0A-4C227E4BACD4} - Library - Properties - Microsoft.SqlTools.EditorServices.Test.Protocol - Microsoft.SqlTools.EditorServices.Test.Protocol - v4.6.1 - 512 - 69e9ba79 - ..\..\ - true - - - - true - full - false - bin\Debug\ - DEBUG;TRACE - prompt - 4 - - - pdbonly - true - bin\Release\ - TRACE - prompt - 4 - - - - ..\..\packages\Newtonsoft.Json.8.0.2\lib\net45\Newtonsoft.Json.dll - True - - - - - - - - - - ..\..\packages\xunit.abstractions.2.0.0\lib\net35\xunit.abstractions.dll - True - - - ..\..\packages\xunit.assert.2.1.0\lib\portable-net45+win8+wp8+wpa81\xunit.assert.dll - True - - - ..\..\packages\xunit.extensibility.core.2.1.0\lib\portable-net45+win8+wp8+wpa81\xunit.core.dll - True - - - ..\..\packages\xunit.extensibility.execution.2.1.0\lib\net45\xunit.execution.desktop.dll - True - - - - - - - - - - - - - - - - - {f8a0946a-5d25-4651-8079-b8d5776916fb} - SqlToolsEditorServices.Protocol - - - {81e8cbcd-6319-49e7-9662-0475bd0791f4} - SqlToolsEditorServices - - - - - - - - - This project references NuGet package(s) that are missing on this computer. Enable NuGet Package Restore to download them. For more information, see http://go.microsoft.com/fwlink/?LinkID=322105. The missing file is {0}. - - - - - - - - \ No newline at end of file