diff --git a/Directory.Packages.props b/Directory.Packages.props index 935d2db68f5..ff2c1bc4ee8 100644 --- a/Directory.Packages.props +++ b/Directory.Packages.props @@ -6,9 +6,9 @@ --> <_MicrosoftWebToolsPackageVersion>17.9.67-preview-0001 - <_MicrosoftVisualStudioShellPackagesVersion>17.10.39563 - <_MicrosoftVisualStudioPackagesVersion>17.10.151 - <_VisualStudioLanguageServerProtocolVersion>17.11.1-preview + <_MicrosoftVisualStudioShellPackagesVersion>17.11.39721 + <_MicrosoftVisualStudioPackagesVersion>17.11.191 + <_VisualStudioLanguageServerProtocolVersion>17.12.1-preview <_MicrosoftExtensionsPackageVersion>8.0.0 <_BasicReferenceAssembliesVersion>1.7.2 <_BenchmarkDotNetPackageVersion>0.13.5.2136 @@ -26,7 +26,7 @@ - + @@ -70,7 +70,7 @@ - + @@ -86,14 +86,14 @@ - + - + @@ -105,7 +105,7 @@ - + diff --git a/NuGet.config b/NuGet.config index c7e40df931c..95636d05192 100644 --- a/NuGet.config +++ b/NuGet.config @@ -84,6 +84,7 @@ + diff --git a/azure-pipelines.yml b/azure-pipelines.yml index 1c1bc779eee..cabca65cbf3 100644 --- a/azure-pipelines.yml +++ b/azure-pipelines.yml @@ -222,6 +222,11 @@ stages: displayName: Restore, Build and Test condition: succeeded() + - publish: artifacts/log/$(_BuildConfig) + artifact: $(Agent.Os)_$(Agent.JobName) Attempt $(System.JobAttempt) Logs + displayName: Publish Build Artifacts + condition: always() + - publish: artifacts/TestResults/$(_BuildConfig) artifact: $(Agent.Os)_$(Agent.JobName) Attempt $(System.JobAttempt) TestResults displayName: Publish Test Results @@ -263,6 +268,11 @@ stages: displayName: Restore, Build and Test condition: succeeded() + - publish: artifacts/log/$(_BuildConfig) + artifact: $(Agent.Os)_$(Agent.JobName) Attempt $(System.JobAttempt) Logs + displayName: Publish Build Artifacts + condition: always() + - publish: artifacts/TestResults/$(_BuildConfig)/ artifact: $(Agent.Os)_$(Agent.JobName) Attempt $(System.JobAttempt) TestResults displayName: Publish Test Results diff --git a/src/Razor/benchmarks/Microsoft.AspNetCore.Razor.Microbenchmarks/Serialization/CompletionListSerializationBenchmark.cs b/src/Razor/benchmarks/Microsoft.AspNetCore.Razor.Microbenchmarks/Serialization/CompletionListSerializationBenchmark.cs index 811f9e7d574..2c9ecda9bf9 100644 --- a/src/Razor/benchmarks/Microsoft.AspNetCore.Razor.Microbenchmarks/Serialization/CompletionListSerializationBenchmark.cs +++ b/src/Razor/benchmarks/Microsoft.AspNetCore.Razor.Microbenchmarks/Serialization/CompletionListSerializationBenchmark.cs @@ -2,7 +2,7 @@ // Licensed under the MIT license. See License.txt in the project root for license information. using System.IO; -using System.Text; +using System.Text.Json; using BenchmarkDotNet.Attributes; using Microsoft.AspNetCore.Razor.Language; using Microsoft.AspNetCore.Razor.LanguageServer; @@ -11,7 +11,6 @@ using Microsoft.CodeAnalysis.Razor.Completion; using Microsoft.CodeAnalysis.Razor.Workspaces; using Microsoft.VisualStudio.LanguageServer.Protocol; -using Newtonsoft.Json; namespace Microsoft.AspNetCore.Razor.Microbenchmarks.Serialization; @@ -19,7 +18,6 @@ public class CompletionListSerializationBenchmark { private readonly byte[] _completionListBuffer; - private readonly JsonSerializer _serializer; private readonly CompletionList _completionList; public CompletionListSerializationBenchmark() @@ -29,8 +27,6 @@ public CompletionListSerializationBenchmark() var optionsMonitor = new RazorLSPOptionsMonitor(configurationService, RazorLSPOptions.Default); var tagHelperCompletionProvider = new TagHelperCompletionProvider(completionService, optionsMonitor); - _serializer = JsonSerializer.Create(); - var documentContent = "<"; var queryIndex = 1; _completionList = GenerateCompletionList(documentContent, queryIndex, tagHelperCompletionProvider); @@ -43,17 +39,15 @@ public void ComponentElement_CompletionList_Serialization_RoundTrip() // Serialize back to json. MemoryStream originalStream; using (originalStream = new MemoryStream()) - using (var writer = new StreamWriter(originalStream, Encoding.UTF8, bufferSize: 4096)) { - _serializer.Serialize(writer, _completionList); + JsonSerializer.Serialize(originalStream, _completionList); } CompletionList deserializedCompletions; var stream = new MemoryStream(originalStream.GetBuffer()); using (stream) - using (var reader = new JsonTextReader(new StreamReader(stream))) { - deserializedCompletions = _serializer.Deserialize(reader).AssumeNotNull(); + deserializedCompletions = JsonSerializer.Deserialize(stream).AssumeNotNull(); } } @@ -61,8 +55,7 @@ public void ComponentElement_CompletionList_Serialization_RoundTrip() public void ComponentElement_CompletionList_Serialization() { using var stream = new MemoryStream(); - using var writer = new StreamWriter(stream, Encoding.UTF8, bufferSize: 4096); - _serializer.Serialize(writer, _completionList); + JsonSerializer.Serialize(stream, _completionList); } [Benchmark(Description = "Component Completion List Deserialization")] @@ -70,9 +63,8 @@ public void ComponentElement_CompletionList_Deserialization() { // Deserialize from json file. using var stream = new MemoryStream(_completionListBuffer); - using var reader = new JsonTextReader(new StreamReader(stream)); CompletionList deserializedCompletions; - deserializedCompletions = _serializer.Deserialize(reader).AssumeNotNull(); + deserializedCompletions = JsonSerializer.Deserialize(stream).AssumeNotNull(); } private CompletionList GenerateCompletionList(string documentContent, int queryIndex, TagHelperCompletionProvider componentCompletionProvider) @@ -111,8 +103,7 @@ private CompletionList GenerateCompletionList(string documentContent, int queryI private byte[] GenerateBuffer(CompletionList completionList) { using var stream = new MemoryStream(); - using var writer = new StreamWriter(stream, Encoding.UTF8, bufferSize: 4096); - _serializer.Serialize(writer, completionList); + JsonSerializer.Serialize(stream, completionList); var buffer = stream.GetBuffer(); return buffer; diff --git a/src/Razor/src/Microsoft.AspNetCore.Razor.LanguageServer/CodeActions/BaseDelegatedCodeActionResolver.cs b/src/Razor/src/Microsoft.AspNetCore.Razor.LanguageServer/CodeActions/BaseDelegatedCodeActionResolver.cs index 25fdfb871f9..341c8ca5ae1 100644 --- a/src/Razor/src/Microsoft.AspNetCore.Razor.LanguageServer/CodeActions/BaseDelegatedCodeActionResolver.cs +++ b/src/Razor/src/Microsoft.AspNetCore.Razor.LanguageServer/CodeActions/BaseDelegatedCodeActionResolver.cs @@ -12,14 +12,9 @@ namespace Microsoft.AspNetCore.Razor.LanguageServer.CodeActions; -internal abstract class BaseDelegatedCodeActionResolver : ICodeActionResolver +internal abstract class BaseDelegatedCodeActionResolver(IClientConnection clientConnection) : ICodeActionResolver { - protected readonly IClientConnection ClientConnection; - - public BaseDelegatedCodeActionResolver(IClientConnection clientConnection) - { - ClientConnection = clientConnection ?? throw new ArgumentNullException(nameof(clientConnection)); - } + protected readonly IClientConnection ClientConnection = clientConnection; public abstract string Action { get; } diff --git a/src/Razor/src/Microsoft.AspNetCore.Razor.LanguageServer/CodeActions/CSharp/DefaultCSharpCodeActionProvider.cs b/src/Razor/src/Microsoft.AspNetCore.Razor.LanguageServer/CodeActions/CSharp/DefaultCSharpCodeActionProvider.cs index 89425322fa2..fb8dafb245f 100644 --- a/src/Razor/src/Microsoft.AspNetCore.Razor.LanguageServer/CodeActions/CSharp/DefaultCSharpCodeActionProvider.cs +++ b/src/Razor/src/Microsoft.AspNetCore.Razor.LanguageServer/CodeActions/CSharp/DefaultCSharpCodeActionProvider.cs @@ -4,6 +4,7 @@ using System; using System.Collections.Generic; using System.Linq; +using System.Text.Json; using System.Threading; using System.Threading.Tasks; using Microsoft.AspNetCore.Razor.Language; @@ -12,15 +13,14 @@ using Microsoft.AspNetCore.Razor.Threading; using Microsoft.CodeAnalysis.ExternalAccess.Razor; using Microsoft.CodeAnalysis.Razor.Workspaces; -using Newtonsoft.Json.Linq; namespace Microsoft.AspNetCore.Razor.LanguageServer.CodeActions; -internal sealed class DefaultCSharpCodeActionProvider : ICSharpCodeActionProvider +internal sealed class DefaultCSharpCodeActionProvider(LanguageServerFeatureOptions languageServerFeatureOptions) : ICSharpCodeActionProvider { // Internal for testing - internal static readonly HashSet SupportedDefaultCodeActionNames = new HashSet() - { + internal static readonly HashSet SupportedDefaultCodeActionNames = + [ RazorPredefinedCodeRefactoringProviderNames.GenerateEqualsAndGetHashCodeFromMembers, RazorPredefinedCodeRefactoringProviderNames.AddAwait, RazorPredefinedCodeRefactoringProviderNames.AddDebuggerDisplay, @@ -39,39 +39,24 @@ internal sealed class DefaultCSharpCodeActionProvider : ICSharpCodeActionProvide RazorPredefinedCodeFixProviderNames.ImplementAbstractClass, RazorPredefinedCodeFixProviderNames.ImplementInterface, RazorPredefinedCodeFixProviderNames.RemoveUnusedVariable, - }; + ]; // We don't support any code actions in implicit expressions at the moment, but rather than simply returning early // I thought it best to create an allow list, empty, so that we can easily add them later if we identify any big // hitters that we want to enable. // The one example commented out here should not be taken as an opinion as to what that allow list should look like. - internal static readonly HashSet SupportedImplicitExpressionCodeActionNames = new HashSet() - { + internal static readonly HashSet SupportedImplicitExpressionCodeActionNames = + [ // RazorPredefinedCodeFixProviderNames.RemoveUnusedVariable, - }; - - private readonly LanguageServerFeatureOptions _languageServerFeatureOptions; + ]; - public DefaultCSharpCodeActionProvider(LanguageServerFeatureOptions languageServerFeatureOptions) - { - _languageServerFeatureOptions = languageServerFeatureOptions; - } + private readonly LanguageServerFeatureOptions _languageServerFeatureOptions = languageServerFeatureOptions; public Task?> ProvideAsync( RazorCodeActionContext context, IEnumerable codeActions, CancellationToken cancellationToken) { - if (context is null) - { - throw new ArgumentNullException(nameof(context)); - } - - if (codeActions is null) - { - throw new ArgumentNullException(nameof(codeActions)); - } - // Used to identify if this is VSCode which doesn't support // code action resolve. if (!context.SupportsCodeActionResolve) @@ -93,24 +78,14 @@ public DefaultCSharpCodeActionProvider(LanguageServerFeatureOptions languageServ { var isOnAllowList = codeAction.Name is not null && allowList.Contains(codeAction.Name); - if (_languageServerFeatureOptions.ShowAllCSharpCodeActions && codeAction.Data is not null) + // If this code action isn't on the allow list, it might have been handled by another provider, which means + // it will already have been wrapped, so we have to check not to double-wrap it. + if (_languageServerFeatureOptions.ShowAllCSharpCodeActions && + CanDeserializeTo(codeAction.Data)) { - // If this code action isn't on the allow list, it might have been handled by another provider, which means - // it will already have been wrapped, so we have to check not to double-wrap it. Unfortunately there isn't a - // good way to do this, but to try and deserialize some Json. Since this only needs to happen if the feature - // flag is on, any perf hit here isn't going to affect real users. - try - { - if (((JToken)codeAction.Data).ToObject() is not null) - { - // This code action has already been wrapped by something else, so skip it here, or it could - // be marked as experimental when its not, and more importantly would be duplicated in the list. - continue; - } - } - catch - { - } + // This code action has already been wrapped by something else, so skip it here, or it could + // be marked as experimental when its not, and more importantly would be duplicated in the list. + continue; } if (_languageServerFeatureOptions.ShowAllCSharpCodeActions || isOnAllowList) @@ -120,5 +95,23 @@ public DefaultCSharpCodeActionProvider(LanguageServerFeatureOptions languageServ } return Task.FromResult?>(results); + + static bool CanDeserializeTo(object? data) + { + // We don't care about errors here, and there is no TryDeserialize method, so we can just brute force this. + // Since this only happens if the feature flag is on, which is internal only and intended only for users of + // this repo, any perf hit here isn't going to affect real users. + try + { + if (data is JsonElement element && + element.Deserialize() is not null) + { + return true; + } + } + catch { } + + return false; + } } } diff --git a/src/Razor/src/Microsoft.AspNetCore.Razor.LanguageServer/CodeActions/CodeActionEndpoint.cs b/src/Razor/src/Microsoft.AspNetCore.Razor.LanguageServer/CodeActions/CodeActionEndpoint.cs index 01ba4955bc1..fe4609a615f 100644 --- a/src/Razor/src/Microsoft.AspNetCore.Razor.LanguageServer/CodeActions/CodeActionEndpoint.cs +++ b/src/Razor/src/Microsoft.AspNetCore.Razor.LanguageServer/CodeActions/CodeActionEndpoint.cs @@ -6,6 +6,7 @@ using System.Collections.Immutable; using System.Linq; using System.Reflection; +using System.Text.Json; using System.Threading; using System.Threading.Tasks; using Microsoft.AspNetCore.Razor.Language; @@ -22,7 +23,6 @@ using Microsoft.CodeAnalysis.Razor.Protocol.CodeActions; using Microsoft.CodeAnalysis.Razor.Workspaces; using Microsoft.VisualStudio.LanguageServer.Protocol; -using Newtonsoft.Json.Linq; using StreamJsonRpc; namespace Microsoft.AspNetCore.Razor.LanguageServer.CodeActions; @@ -215,9 +215,9 @@ private RazorVSInternalCodeAction[] ExtractCSharpCodeActionNamesFromData(RazorVS foreach (var codeAction in codeActions) { - // Note: we may see a perf benefit from using a JsonConverter - var tags = ((JToken?)codeAction.Data)?["CustomTags"]?.ToObject(); - if (tags is null || tags.Length == 0) + if (codeAction.Data is not JsonElement jsonData || + !jsonData.TryGetProperty("CustomTags", out var value) || + value.Deserialize() is not [..] tags) { continue; } diff --git a/src/Razor/src/Microsoft.AspNetCore.Razor.LanguageServer/CodeActions/CodeActionResolveEndpoint.cs b/src/Razor/src/Microsoft.AspNetCore.Razor.LanguageServer/CodeActions/CodeActionResolveEndpoint.cs index f1687da4c57..3892f546301 100644 --- a/src/Razor/src/Microsoft.AspNetCore.Razor.LanguageServer/CodeActions/CodeActionResolveEndpoint.cs +++ b/src/Razor/src/Microsoft.AspNetCore.Razor.LanguageServer/CodeActions/CodeActionResolveEndpoint.cs @@ -5,6 +5,7 @@ using System.Collections.Generic; using System.Collections.Immutable; using System.Diagnostics; +using System.Text.Json; using System.Threading; using System.Threading.Tasks; using Microsoft.AspNetCore.Razor.LanguageServer.CodeActions.Models; @@ -12,7 +13,6 @@ using Microsoft.AspNetCore.Razor.PooledObjects; using Microsoft.CodeAnalysis.Razor.Logging; using Microsoft.VisualStudio.LanguageServer.Protocol; -using Newtonsoft.Json.Linq; namespace Microsoft.AspNetCore.Razor.LanguageServer.CodeActions; @@ -66,13 +66,13 @@ public async Task HandleRequestAsync(CodeAction request, RazorReques throw new ArgumentNullException(nameof(request)); } - if (request.Data is not JObject paramsObj) + if (request.Data is not JsonElement paramsObj) { _logger.LogError($"Invalid CodeAction Received '{request.Title}'."); return request; } - var resolutionParams = paramsObj.ToObject(); + var resolutionParams = paramsObj.Deserialize(); if (resolutionParams is null) { @@ -87,7 +87,7 @@ public async Task HandleRequestAsync(CodeAction request, RazorReques // as it does not support Command.Edit based code actions anymore. if (resolutionParams.Action == LanguageServerConstants.CodeActions.EditBasedCodeActionCommand) { - request.Edit = (resolutionParams.Data as JObject)?.ToObject(); + request.Edit = (resolutionParams.Data as JsonElement?)?.Deserialize(); return request; } @@ -128,7 +128,7 @@ internal async Task ResolveRazorCodeActionAsync( return codeAction; } - if (resolutionParams.Data is not JObject data) + if (resolutionParams.Data is not JsonElement data) { return codeAction; } @@ -148,20 +148,20 @@ internal Task ResolveHtmlCodeActionAsync(CodeAction codeAction, Razo private async Task ResolveDelegatedCodeActionAsync(ImmutableDictionary resolvers, CodeAction codeAction, RazorCodeActionResolutionParams resolutionParams, CancellationToken cancellationToken) { - if (resolutionParams.Data is not JObject csharpParamsObj) + if (resolutionParams.Data is not JsonElement csharpParamsObj) { _logger.LogError($"Invalid CodeAction Received."); Debug.Fail($"Invalid CSharp CodeAction Received."); return codeAction; } - var csharpParams = csharpParamsObj.ToObject(); + var csharpParams = csharpParamsObj.Deserialize(); if (csharpParams is null) { throw new ArgumentOutOfRangeException($"Data was not convertible to {nameof(CodeActionResolveParams)}"); } - codeAction.Data = csharpParams.Data as JToken; + codeAction.Data = csharpParams.Data; if (!resolvers.TryGetValue(resolutionParams.Action, out var resolver)) { diff --git a/src/Razor/src/Microsoft.AspNetCore.Razor.LanguageServer/CodeActions/Models/AddUsingsCodeActionParams.cs b/src/Razor/src/Microsoft.AspNetCore.Razor.LanguageServer/CodeActions/Models/AddUsingsCodeActionParams.cs index 80d52b62da5..9c9fe60a538 100644 --- a/src/Razor/src/Microsoft.AspNetCore.Razor.LanguageServer/CodeActions/Models/AddUsingsCodeActionParams.cs +++ b/src/Razor/src/Microsoft.AspNetCore.Razor.LanguageServer/CodeActions/Models/AddUsingsCodeActionParams.cs @@ -2,13 +2,17 @@ // Licensed under the MIT license. See License.txt in the project root for license information. using System; +using System.Text.Json.Serialization; using Microsoft.VisualStudio.LanguageServer.Protocol; namespace Microsoft.AspNetCore.Razor.LanguageServer.CodeActions.Models; internal sealed class AddUsingsCodeActionParams { + [JsonPropertyName("uri")] public required Uri Uri { get; set; } + [JsonPropertyName("namespace")] public required string Namespace { get; set; } + [JsonPropertyName("additionalEdit")] public TextDocumentEdit? AdditionalEdit { get; set; } } diff --git a/src/Razor/src/Microsoft.AspNetCore.Razor.LanguageServer/CodeActions/Models/CodeActionExtensions.cs b/src/Razor/src/Microsoft.AspNetCore.Razor.LanguageServer/CodeActions/Models/CodeActionExtensions.cs index 62f2e601ee9..47af3510f70 100644 --- a/src/Razor/src/Microsoft.AspNetCore.Razor.LanguageServer/CodeActions/Models/CodeActionExtensions.cs +++ b/src/Razor/src/Microsoft.AspNetCore.Razor.LanguageServer/CodeActions/Models/CodeActionExtensions.cs @@ -3,8 +3,9 @@ using System; using System.Linq; +using System.Text.Json; +using System.Text.Json.Nodes; using Microsoft.VisualStudio.LanguageServer.Protocol; -using Newtonsoft.Json.Linq; namespace Microsoft.AspNetCore.Razor.LanguageServer.CodeActions.Models; @@ -26,19 +27,19 @@ public static SumType AsVSCodeCommandOrCodeAction(this VSIn razorCodeAction = new VSInternalCodeAction() { Title = razorCodeAction.Title, - Data = JToken.FromObject(resolutionParams), + Data = JsonSerializer.SerializeToElement(resolutionParams), TelemetryId = razorCodeAction.TelemetryId, }; } - var serializedParams = JToken.FromObject(razorCodeAction.Data); - var arguments = new JArray(serializedParams); + var serializedParams = JsonSerializer.SerializeToNode(razorCodeAction.Data).AssumeNotNull(); + var arguments = new JsonArray(serializedParams); return new Command { Title = razorCodeAction.Title ?? string.Empty, CommandIdentifier = LanguageServerConstants.RazorCodeActionRunnerCommand, - Arguments = arguments.ToArray(), + Arguments = arguments.ToArray()! }; } @@ -71,7 +72,7 @@ public static RazorVSInternalCodeAction WrapResolvableCodeAction( Language = language, Data = resolveParams }; - razorCodeAction.Data = JToken.FromObject(resolutionParams); + razorCodeAction.Data = JsonSerializer.SerializeToElement(resolutionParams); if (!isOnAllowList) { @@ -108,7 +109,7 @@ private static VSInternalCodeAction WrapResolvableCodeAction( Language = language, Data = resolveParams }; - razorCodeAction.Data = JToken.FromObject(resolutionParams); + razorCodeAction.Data = JsonSerializer.SerializeToElement(resolutionParams); if (!isOnAllowList) { diff --git a/src/Razor/src/Microsoft.AspNetCore.Razor.LanguageServer/CodeActions/Models/CodeActionResolveParams.cs b/src/Razor/src/Microsoft.AspNetCore.Razor.LanguageServer/CodeActions/Models/CodeActionResolveParams.cs index 41cb4ca080a..927b8a9ecf5 100644 --- a/src/Razor/src/Microsoft.AspNetCore.Razor.LanguageServer/CodeActions/Models/CodeActionResolveParams.cs +++ b/src/Razor/src/Microsoft.AspNetCore.Razor.LanguageServer/CodeActions/Models/CodeActionResolveParams.cs @@ -1,14 +1,17 @@ // Copyright (c) .NET Foundation. All rights reserved. // Licensed under the MIT license. See License.txt in the project root for license information. +using System.Text.Json.Serialization; using Microsoft.VisualStudio.LanguageServer.Protocol; namespace Microsoft.AspNetCore.Razor.LanguageServer.CodeActions.Models; internal sealed class CodeActionResolveParams { + [JsonPropertyName("data")] public object? Data { get; set; } // Need to use the VS type so that project context info, if present, is maintained + [JsonPropertyName("razorFileIdentifier")] public required VSTextDocumentIdentifier RazorFileIdentifier { get; set; } } diff --git a/src/Razor/src/Microsoft.AspNetCore.Razor.LanguageServer/CodeActions/Models/CreateComponentCodeActionParams.cs b/src/Razor/src/Microsoft.AspNetCore.Razor.LanguageServer/CodeActions/Models/CreateComponentCodeActionParams.cs index a97d0e18877..13e2ea5095c 100644 --- a/src/Razor/src/Microsoft.AspNetCore.Razor.LanguageServer/CodeActions/Models/CreateComponentCodeActionParams.cs +++ b/src/Razor/src/Microsoft.AspNetCore.Razor.LanguageServer/CodeActions/Models/CreateComponentCodeActionParams.cs @@ -2,11 +2,14 @@ // Licensed under the MIT license. See License.txt in the project root for license information. using System; +using System.Text.Json.Serialization; namespace Microsoft.AspNetCore.Razor.LanguageServer.CodeActions.Models; internal sealed class CreateComponentCodeActionParams { + [JsonPropertyName("uri")] public required Uri Uri { get; set; } + [JsonPropertyName("path")] public required string Path { get; set; } } diff --git a/src/Razor/src/Microsoft.AspNetCore.Razor.LanguageServer/CodeActions/Models/ExtractToCodeBehindCodeActionParams.cs b/src/Razor/src/Microsoft.AspNetCore.Razor.LanguageServer/CodeActions/Models/ExtractToCodeBehindCodeActionParams.cs index 316a4dc88c3..cf744ef110b 100644 --- a/src/Razor/src/Microsoft.AspNetCore.Razor.LanguageServer/CodeActions/Models/ExtractToCodeBehindCodeActionParams.cs +++ b/src/Razor/src/Microsoft.AspNetCore.Razor.LanguageServer/CodeActions/Models/ExtractToCodeBehindCodeActionParams.cs @@ -2,15 +2,27 @@ // Licensed under the MIT license. See License.txt in the project root for license information. using System; +using System.Text.Json.Serialization; namespace Microsoft.AspNetCore.Razor.LanguageServer.CodeActions.Models; internal sealed class ExtractToCodeBehindCodeActionParams { + [JsonPropertyName("uri")] public required Uri Uri { get; set; } + + [JsonPropertyName("extractStart")] public int ExtractStart { get; set; } + + [JsonPropertyName("extractEnd")] public int ExtractEnd { get; set; } + + [JsonPropertyName("removeStart")] public int RemoveStart { get; set; } + + [JsonPropertyName("removeEnd")] public int RemoveEnd { get; set; } + + [JsonPropertyName("namespace")] public required string Namespace { get; set; } } diff --git a/src/Razor/src/Microsoft.AspNetCore.Razor.LanguageServer/CodeActions/Models/GenerateMethodCodeActionParams.cs b/src/Razor/src/Microsoft.AspNetCore.Razor.LanguageServer/CodeActions/Models/GenerateMethodCodeActionParams.cs index ab385bcc88b..e5a6c0020cc 100644 --- a/src/Razor/src/Microsoft.AspNetCore.Razor.LanguageServer/CodeActions/Models/GenerateMethodCodeActionParams.cs +++ b/src/Razor/src/Microsoft.AspNetCore.Razor.LanguageServer/CodeActions/Models/GenerateMethodCodeActionParams.cs @@ -2,13 +2,21 @@ // Licensed under the MIT license. See License.txt in the project root for license information. using System; +using System.Text.Json.Serialization; namespace Microsoft.AspNetCore.Razor.LanguageServer.CodeActions.Models; internal class GenerateMethodCodeActionParams { + [JsonPropertyName("uri")] public required Uri Uri { get; set; } + + [JsonPropertyName("methodName")] public required string MethodName { get; set; } + + [JsonPropertyName("eventName")] public required string EventName { get; set; } + + [JsonPropertyName("isAsync")] public required bool IsAsync { get; set; } } diff --git a/src/Razor/src/Microsoft.AspNetCore.Razor.LanguageServer/CodeActions/Models/RazorCodeActionResolutionParams.cs b/src/Razor/src/Microsoft.AspNetCore.Razor.LanguageServer/CodeActions/Models/RazorCodeActionResolutionParams.cs index a312180758b..5d47f9828db 100644 --- a/src/Razor/src/Microsoft.AspNetCore.Razor.LanguageServer/CodeActions/Models/RazorCodeActionResolutionParams.cs +++ b/src/Razor/src/Microsoft.AspNetCore.Razor.LanguageServer/CodeActions/Models/RazorCodeActionResolutionParams.cs @@ -1,19 +1,19 @@ // Copyright (c) .NET Foundation. All rights reserved. // Licensed under the MIT license. See License.txt in the project root for license information. -using Newtonsoft.Json; +using System.Text.Json; +using System.Text.Json.Serialization; namespace Microsoft.AspNetCore.Razor.LanguageServer.CodeActions.Models; -[JsonObject] internal class RazorCodeActionResolutionParams { - [JsonProperty(PropertyName = "action", Required = Required.Always)] + [JsonPropertyName("action")] public required string Action { get; set; } - [JsonProperty(PropertyName = "language", Required = Required.Always)] + [JsonPropertyName("language")] public required string Language { get; set; } - [JsonProperty(PropertyName = "data", Required = Required.Always)] + [JsonPropertyName("data")] public required object Data { get; set; } } diff --git a/src/Razor/src/Microsoft.AspNetCore.Razor.LanguageServer/CodeActions/Razor/AddUsingsCodeActionResolver.cs b/src/Razor/src/Microsoft.AspNetCore.Razor.LanguageServer/CodeActions/Razor/AddUsingsCodeActionResolver.cs index 3fb397f010c..f679b1566a5 100644 --- a/src/Razor/src/Microsoft.AspNetCore.Razor.LanguageServer/CodeActions/Razor/AddUsingsCodeActionResolver.cs +++ b/src/Razor/src/Microsoft.AspNetCore.Razor.LanguageServer/CodeActions/Razor/AddUsingsCodeActionResolver.cs @@ -4,6 +4,7 @@ using System; using System.Collections.Generic; using System.Linq; +using System.Text.Json; using System.Threading; using System.Threading.Tasks; using Microsoft.AspNetCore.Mvc.Razor.Extensions; @@ -17,7 +18,6 @@ using Microsoft.CodeAnalysis.Razor.ProjectSystem; using Microsoft.CodeAnalysis.Razor.Workspaces; using Microsoft.VisualStudio.LanguageServer.Protocol; -using Newtonsoft.Json.Linq; namespace Microsoft.AspNetCore.Razor.LanguageServer.CodeActions; @@ -32,14 +32,9 @@ public AddUsingsCodeActionResolver(IDocumentContextFactory documentContextFactor public string Action => LanguageServerConstants.CodeActions.AddUsing; - public async Task ResolveAsync(JObject data, CancellationToken cancellationToken) + public async Task ResolveAsync(JsonElement data, CancellationToken cancellationToken) { - if (data is null) - { - return null; - } - - var actionParams = data.ToObject(); + var actionParams = data.Deserialize(); if (actionParams is null) { return null; diff --git a/src/Razor/src/Microsoft.AspNetCore.Razor.LanguageServer/CodeActions/Razor/CreateComponentCodeActionResolver.cs b/src/Razor/src/Microsoft.AspNetCore.Razor.LanguageServer/CodeActions/Razor/CreateComponentCodeActionResolver.cs index a69358b3a76..0780869ae28 100644 --- a/src/Razor/src/Microsoft.AspNetCore.Razor.LanguageServer/CodeActions/Razor/CreateComponentCodeActionResolver.cs +++ b/src/Razor/src/Microsoft.AspNetCore.Razor.LanguageServer/CodeActions/Razor/CreateComponentCodeActionResolver.cs @@ -4,6 +4,7 @@ using System; using System.Collections.Generic; using System.Linq; +using System.Text.Json; using System.Threading; using System.Threading.Tasks; using Microsoft.AspNetCore.Razor.Language; @@ -13,7 +14,6 @@ using Microsoft.CodeAnalysis.Razor.ProjectSystem; using Microsoft.CodeAnalysis.Razor.Workspaces; using Microsoft.VisualStudio.LanguageServer.Protocol; -using Newtonsoft.Json.Linq; namespace Microsoft.AspNetCore.Razor.LanguageServer.CodeActions; @@ -30,14 +30,9 @@ public CreateComponentCodeActionResolver(IDocumentContextFactory documentContext public string Action => LanguageServerConstants.CodeActions.CreateComponentFromTag; - public async Task ResolveAsync(JObject data, CancellationToken cancellationToken) + public async Task ResolveAsync(JsonElement data, CancellationToken cancellationToken) { - if (data is null) - { - return null; - } - - var actionParams = data.ToObject(); + var actionParams = data.Deserialize(); if (actionParams is null) { return null; diff --git a/src/Razor/src/Microsoft.AspNetCore.Razor.LanguageServer/CodeActions/Razor/ExtractToCodeBehindCodeActionResolver.cs b/src/Razor/src/Microsoft.AspNetCore.Razor.LanguageServer/CodeActions/Razor/ExtractToCodeBehindCodeActionResolver.cs index 4bd8554f543..ae27499675c 100644 --- a/src/Razor/src/Microsoft.AspNetCore.Razor.LanguageServer/CodeActions/Razor/ExtractToCodeBehindCodeActionResolver.cs +++ b/src/Razor/src/Microsoft.AspNetCore.Razor.LanguageServer/CodeActions/Razor/ExtractToCodeBehindCodeActionResolver.cs @@ -4,6 +4,7 @@ using System; using System.Globalization; using System.IO; +using System.Text.Json; using System.Threading; using System.Threading.Tasks; using Microsoft.AspNetCore.Razor.Language; @@ -21,7 +22,6 @@ using Microsoft.CodeAnalysis.Razor.Protocol.CodeActions; using Microsoft.CodeAnalysis.Razor.Workspaces; using Microsoft.VisualStudio.LanguageServer.Protocol; -using Newtonsoft.Json.Linq; namespace Microsoft.AspNetCore.Razor.LanguageServer.CodeActions; @@ -45,14 +45,9 @@ public ExtractToCodeBehindCodeActionResolver( public string Action => LanguageServerConstants.CodeActions.ExtractToCodeBehindAction; - public async Task ResolveAsync(JObject data, CancellationToken cancellationToken) + public async Task ResolveAsync(JsonElement data, CancellationToken cancellationToken) { - if (data is null) - { - return null; - } - - var actionParams = data.ToObject(); + var actionParams = data.Deserialize(); if (actionParams is null) { return null; diff --git a/src/Razor/src/Microsoft.AspNetCore.Razor.LanguageServer/CodeActions/Razor/GenerateMethodCodeActionResolver.cs b/src/Razor/src/Microsoft.AspNetCore.Razor.LanguageServer/CodeActions/Razor/GenerateMethodCodeActionResolver.cs index 20e130b4f10..6cf869bf21b 100644 --- a/src/Razor/src/Microsoft.AspNetCore.Razor.LanguageServer/CodeActions/Razor/GenerateMethodCodeActionResolver.cs +++ b/src/Razor/src/Microsoft.AspNetCore.Razor.LanguageServer/CodeActions/Razor/GenerateMethodCodeActionResolver.cs @@ -5,6 +5,7 @@ using System.Diagnostics; using System.IO; using System.Linq; +using System.Text.Json; using System.Threading; using System.Threading.Tasks; using Microsoft.AspNetCore.Razor.Language; @@ -20,7 +21,6 @@ using Microsoft.CodeAnalysis.Razor.ProjectSystem; using Microsoft.CodeAnalysis.Razor.Protocol; using Microsoft.VisualStudio.LanguageServer.Protocol; -using Newtonsoft.Json.Linq; using CSharpSyntaxFactory = Microsoft.CodeAnalysis.CSharp.SyntaxFactory; namespace Microsoft.AspNetCore.Razor.LanguageServer.CodeActions.Razor; @@ -59,14 +59,9 @@ public GenerateMethodCodeActionResolver( _razorFormattingService = razorFormattingService; } - public async Task ResolveAsync(JObject data, CancellationToken cancellationToken) + public async Task ResolveAsync(JsonElement data, CancellationToken cancellationToken) { - if (data is null) - { - return null; - } - - var actionParams = data.ToObject(); + var actionParams = data.Deserialize(); if (actionParams is null) { return null; diff --git a/src/Razor/src/Microsoft.AspNetCore.Razor.LanguageServer/CodeActions/Razor/IRazorCodeActionResolver.cs b/src/Razor/src/Microsoft.AspNetCore.Razor.LanguageServer/CodeActions/Razor/IRazorCodeActionResolver.cs index d86224daa4b..60b58952eea 100644 --- a/src/Razor/src/Microsoft.AspNetCore.Razor.LanguageServer/CodeActions/Razor/IRazorCodeActionResolver.cs +++ b/src/Razor/src/Microsoft.AspNetCore.Razor.LanguageServer/CodeActions/Razor/IRazorCodeActionResolver.cs @@ -1,14 +1,14 @@ // Copyright (c) .NET Foundation. All rights reserved. // Licensed under the MIT license. See License.txt in the project root for license information. +using System.Text.Json; using System.Threading; using System.Threading.Tasks; using Microsoft.VisualStudio.LanguageServer.Protocol; -using Newtonsoft.Json.Linq; namespace Microsoft.AspNetCore.Razor.LanguageServer.CodeActions; internal interface IRazorCodeActionResolver : ICodeActionResolver { - Task ResolveAsync(JObject data, CancellationToken cancellationToken); + Task ResolveAsync(JsonElement data, CancellationToken cancellationToken); } diff --git a/src/Razor/src/Microsoft.AspNetCore.Razor.LanguageServer/CodeActions/Razor/RazorCodeActionFactory.cs b/src/Razor/src/Microsoft.AspNetCore.Razor.LanguageServer/CodeActions/Razor/RazorCodeActionFactory.cs index e444c5a2dee..832f3c2a351 100644 --- a/src/Razor/src/Microsoft.AspNetCore.Razor.LanguageServer/CodeActions/Razor/RazorCodeActionFactory.cs +++ b/src/Razor/src/Microsoft.AspNetCore.Razor.LanguageServer/CodeActions/Razor/RazorCodeActionFactory.cs @@ -2,9 +2,9 @@ // Licensed under the MIT license. See License.txt in the project root for license information. using System; +using System.Text.Json; using Microsoft.AspNetCore.Razor.LanguageServer.CodeActions.Models; using Microsoft.VisualStudio.LanguageServer.Protocol; -using Newtonsoft.Json.Linq; namespace Microsoft.AspNetCore.Razor.LanguageServer.CodeActions.Razor; @@ -20,7 +20,7 @@ internal static class RazorCodeActionFactory public static RazorVSInternalCodeAction CreateAddComponentUsing(string @namespace, string? newTagName, RazorCodeActionResolutionParams resolutionParams) { var title = $"@using {@namespace}"; - var data = JToken.FromObject(resolutionParams); + var data = JsonSerializer.SerializeToElement(resolutionParams); var codeAction = new RazorVSInternalCodeAction { Title = newTagName is null ? title : $"{newTagName} - {title}", @@ -44,7 +44,7 @@ public static RazorVSInternalCodeAction CreateFullyQualifyComponent(string fully public static RazorVSInternalCodeAction CreateComponentFromTag(RazorCodeActionResolutionParams resolutionParams) { var title = SR.Create_Component_FromTag_Title; - var data = JToken.FromObject(resolutionParams); + var data = JsonSerializer.SerializeToElement(resolutionParams); var codeAction = new RazorVSInternalCodeAction() { Title = title, @@ -57,7 +57,7 @@ public static RazorVSInternalCodeAction CreateComponentFromTag(RazorCodeActionRe public static RazorVSInternalCodeAction CreateExtractToCodeBehind(RazorCodeActionResolutionParams resolutionParams) { var title = SR.ExtractTo_CodeBehind_Title; - var data = JToken.FromObject(resolutionParams); + var data = JsonSerializer.SerializeToElement(resolutionParams); var codeAction = new RazorVSInternalCodeAction() { Title = title, @@ -84,7 +84,7 @@ public static RazorVSInternalCodeAction CreateGenerateMethod(Uri uri, string met }; var title = SR.FormatGenerate_Event_Handler_Title(methodName); - var data = JToken.FromObject(resolutionParams); + var data = JsonSerializer.SerializeToElement(resolutionParams); var codeAction = new RazorVSInternalCodeAction() { Title = title, @@ -111,7 +111,7 @@ public static RazorVSInternalCodeAction CreateAsyncGenerateMethod(Uri uri, strin }; var title = SR.FormatGenerate_Async_Event_Handler_Title(methodName); - var data = JToken.FromObject(resolutionParams); + var data = JsonSerializer.SerializeToElement(resolutionParams); var codeAction = new RazorVSInternalCodeAction() { Title = title, diff --git a/src/Razor/src/Microsoft.AspNetCore.Razor.LanguageServer/Completion/CompletionListMerger.cs b/src/Razor/src/Microsoft.AspNetCore.Razor.LanguageServer/Completion/CompletionListMerger.cs index 04131c02b46..5f4bb5ac7d9 100644 --- a/src/Razor/src/Microsoft.AspNetCore.Razor.LanguageServer/Completion/CompletionListMerger.cs +++ b/src/Razor/src/Microsoft.AspNetCore.Razor.LanguageServer/Completion/CompletionListMerger.cs @@ -79,7 +79,7 @@ internal static class CompletionListMerger return new MergedCompletionListData(data1, data2); } - public static bool TrySplit(object? data, [NotNullWhen(true)] out IReadOnlyList? splitData) + public static bool TrySplit(object? data, [NotNullWhen(true)] out IReadOnlyList? splitData) { if (data is null) { @@ -87,7 +87,7 @@ public static bool TrySplit(object? data, [NotNullWhen(true)] out IReadOnlyList< return false; } - var collector = new List(); + var collector = new List(); Split(data, collector); if (collector.Count == 0) @@ -100,7 +100,7 @@ public static bool TrySplit(object? data, [NotNullWhen(true)] out IReadOnlyList< return true; } - private static void Split(object data, List collector) + private static void Split(object data, List collector) { if (data is MergedCompletionListData mergedData) { @@ -117,7 +117,7 @@ private static void Split(object data, List collector) TrySplitJObject(data, collector); } - private static void TrySplitJsonElement(object data, List collector) + private static void TrySplitJsonElement(object data, List collector) { if (data is not JsonElement jsonElement) { @@ -141,22 +141,22 @@ private static void TrySplitJsonElement(object data, List collector) } else { - collector.Add((JObject)JsonHelpers.TryConvertFromJsonElement(jsonElement).AssumeNotNull()); + collector.Add(jsonElement); } } - private static void TrySplitJObject(object data, List collector) + private static void TrySplitJObject(object data, List collector) { - if (data is not JObject jobject) + if (data is not JObject jObject) { return; } - if ((jobject.ContainsKey(Data1Key) || jobject.ContainsKey(Data1Key.ToLowerInvariant())) && - (jobject.ContainsKey(Data2Key) || jobject.ContainsKey(Data2Key.ToLowerInvariant()))) + if ((jObject.ContainsKey(Data1Key) || jObject.ContainsKey(Data1Key.ToLowerInvariant())) && + (jObject.ContainsKey(Data2Key) || jObject.ContainsKey(Data2Key.ToLowerInvariant()))) { // Merged data - var mergedCompletionListData = jobject.ToObject(); + var mergedCompletionListData = jObject.ToObject(); if (mergedCompletionListData is null) { @@ -170,7 +170,7 @@ private static void TrySplitJObject(object data, List collector) else { // Normal, non-merged data - collector.Add(jobject); + collector.Add(JsonDocument.Parse(jObject.ToString()).RootElement); } } diff --git a/src/Razor/src/Microsoft.AspNetCore.Razor.LanguageServer/Completion/VSInternalCompletionItemExtensions.cs b/src/Razor/src/Microsoft.AspNetCore.Razor.LanguageServer/Completion/VSInternalCompletionItemExtensions.cs index a1a843708e0..540d01a3280 100644 --- a/src/Razor/src/Microsoft.AspNetCore.Razor.LanguageServer/Completion/VSInternalCompletionItemExtensions.cs +++ b/src/Razor/src/Microsoft.AspNetCore.Razor.LanguageServer/Completion/VSInternalCompletionItemExtensions.cs @@ -33,13 +33,10 @@ public static bool TryGetCompletionListResultIds(this VSInternalCompletionItem c for (var i = 0; i < splitData.Count; i++) { var data = splitData[i]; - if (data.ContainsKey(ResultIdKey)) + if (data.TryGetProperty(ResultIdKey, out var resultIdElement) && + resultIdElement.TryGetInt32(out var resultId)) { - var resultId = data[ResultIdKey]?.ToObject(); - if (resultId is not null) - { - ids.Add(resultId.Value); - } + ids.Add(resultId); } } diff --git a/src/Razor/src/Microsoft.AspNetCore.Razor.LanguageServer/Completion/VSInternalCompletionListExtensions.cs b/src/Razor/src/Microsoft.AspNetCore.Razor.LanguageServer/Completion/VSInternalCompletionListExtensions.cs index 44e204767e4..94a502eb190 100644 --- a/src/Razor/src/Microsoft.AspNetCore.Razor.LanguageServer/Completion/VSInternalCompletionListExtensions.cs +++ b/src/Razor/src/Microsoft.AspNetCore.Razor.LanguageServer/Completion/VSInternalCompletionListExtensions.cs @@ -3,8 +3,9 @@ using System; using System.Linq; +using System.Text.Json; +using System.Text.Json.Nodes; using Microsoft.VisualStudio.LanguageServer.Protocol; -using Newtonsoft.Json.Linq; namespace Microsoft.AspNetCore.Razor.LanguageServer.Completion; @@ -18,15 +19,10 @@ public static void SetResultId( int resultId, VSInternalCompletionSetting? completionSetting) { - if (completionList is null) - { - throw new ArgumentNullException(nameof(completionList)); - } - - var data = new JObject() + var data = JsonSerializer.SerializeToElement(new JsonObject() { [ResultIdKey] = resultId, - }; + }); if (completionSetting?.CompletionList?.Data == true) { diff --git a/src/Razor/src/Microsoft.AspNetCore.Razor.LanguageServer/DefaultRazorConfigurationService.cs b/src/Razor/src/Microsoft.AspNetCore.Razor.LanguageServer/DefaultRazorConfigurationService.cs index 1f263bb6fca..6010dde3ebd 100644 --- a/src/Razor/src/Microsoft.AspNetCore.Razor.LanguageServer/DefaultRazorConfigurationService.cs +++ b/src/Razor/src/Microsoft.AspNetCore.Razor.LanguageServer/DefaultRazorConfigurationService.cs @@ -2,14 +2,15 @@ // Licensed under the MIT license. See License.txt in the project root for license information. using System; +using System.Runtime.CompilerServices; +using System.Text.Json; +using System.Text.Json.Nodes; using System.Threading; using System.Threading.Tasks; using Microsoft.AspNetCore.Razor.LanguageServer.Hosting; using Microsoft.CodeAnalysis.Razor.Logging; using Microsoft.CodeAnalysis.Razor.Settings; using Microsoft.VisualStudio.LanguageServer.Protocol; -using Newtonsoft.Json; -using Newtonsoft.Json.Linq; namespace Microsoft.AspNetCore.Razor.LanguageServer; @@ -40,7 +41,7 @@ public DefaultRazorConfigurationService(IClientConnection clientConnection, ILog { var request = GenerateConfigParams(); - var result = await _clientConnection.SendRequestAsync(Methods.WorkspaceConfigurationName, request, cancellationToken).ConfigureAwait(false); + var result = await _clientConnection.SendRequestAsync(Methods.WorkspaceConfigurationName, request, cancellationToken).ConfigureAwait(false); // LSP spec indicates result should be the same length as the number of ConfigurationItems we pass in. if (result?.Length != request.Items.Length || result[0] is null) @@ -84,7 +85,7 @@ private static ConfigurationParams GenerateConfigParams() } // Internal for testing - internal RazorLSPOptions BuildOptions(JObject[] result) + internal RazorLSPOptions BuildOptions(JsonObject[] result) { // VS Code will send back settings in the first two elements, VS will send back settings in the 3rd // so we can effectively detect which IDE we're in. @@ -107,7 +108,7 @@ internal RazorLSPOptions BuildOptions(JObject[] result) } private void ExtractVSCodeOptions( - JObject[] result, + JsonObject[] result, out bool enableFormatting, out bool autoClosingTags, out bool commitElementsWithSpace, @@ -123,48 +124,44 @@ private void ExtractVSCodeOptions( // this matches VS Code's html servers commit behaviour commitElementsWithSpace = false; - if (razor != null) + if (razor.TryGetPropertyValue("format", out var parsedFormatNode) && + parsedFormatNode?.AsObject() is { } parsedFormat) { - if (razor.TryGetValue("format", out var parsedFormat)) + if (parsedFormat.TryGetPropertyValue("enable", out var parsedEnableFormatting) && + parsedEnableFormatting is not null) { - if (parsedFormat is JObject jObject) - { - if (jObject.TryGetValue("enable", out var parsedEnableFormatting)) - { - enableFormatting = GetObjectOrDefault(parsedEnableFormatting, enableFormatting); - } - - if (jObject.TryGetValue("codeBlockBraceOnNextLine", out var parsedCodeBlockBraceOnNextLine)) - { - codeBlockBraceOnNextLine = GetObjectOrDefault(parsedCodeBlockBraceOnNextLine, codeBlockBraceOnNextLine); - } - } + enableFormatting = GetObjectOrDefault(parsedEnableFormatting, enableFormatting); } - if (razor.TryGetValue("completion", out var parsedCompletion)) + if (parsedFormat.TryGetPropertyValue("codeBlockBraceOnNextLine", out var parsedCodeBlockBraceOnNextLine) && + parsedCodeBlockBraceOnNextLine is not null) { - if (parsedCompletion is JObject jObject && - jObject.TryGetValue("commitElementsWithSpace", out var parsedCommitElementsWithSpace)) - { - commitElementsWithSpace = GetObjectOrDefault(parsedCommitElementsWithSpace, commitElementsWithSpace); - } + codeBlockBraceOnNextLine = GetObjectOrDefault(parsedCodeBlockBraceOnNextLine, codeBlockBraceOnNextLine); } } - if (html != null) + if (razor.TryGetPropertyValue("completion", out var parsedCompletionNode) && + parsedCompletionNode?.AsObject() is { } parsedCompletion) { - if (html.TryGetValue("autoClosingTags", out var parsedAutoClosingTags)) + if (parsedCompletion.TryGetPropertyValue("commitElementsWithSpace", out var parsedCommitElementsWithSpace) && + parsedCommitElementsWithSpace is not null) { - autoClosingTags = GetObjectOrDefault(parsedAutoClosingTags, autoClosingTags); + commitElementsWithSpace = GetObjectOrDefault(parsedCommitElementsWithSpace, commitElementsWithSpace); } } + + if (html.TryGetPropertyValue("autoClosingTags", out var parsedAutoClosingTags) && + parsedAutoClosingTags is not null) + { + autoClosingTags = GetObjectOrDefault(parsedAutoClosingTags, autoClosingTags); + } } - private ClientSettings ExtractVSOptions(JObject[] result) + private ClientSettings ExtractVSOptions(JsonObject[] result) { try { - var settings = result[2]?.ToObject(); + var settings = result[2].Deserialize(); if (settings is null) { return ClientSettings.Default; @@ -188,23 +185,23 @@ private ClientSettings ExtractVSOptions(JObject[] result) return settings; } - catch (JsonReaderException) + catch (Exception) { return ClientSettings.Default; } } - private T GetObjectOrDefault(JToken token, T defaultValue) + private T GetObjectOrDefault(JsonNode token, T defaultValue, [CallerArgumentExpression(nameof(defaultValue))] string? expression = null) { try { - // JToken.ToObject could potentially throw here if the user provides malformed options. + // GetValue could potentially throw here if the user provides malformed options. // If this occurs, catch the exception and return the default value. - return token.ToObject() ?? defaultValue; + return token.GetValue() ?? defaultValue; } catch (Exception ex) { - _logger.LogError(ex, $"Malformed option: Token {token} cannot be converted to type {typeof(T)}."); + _logger.LogError(ex, $"Malformed option: Token {token} cannot be converted to type {typeof(T)} for {expression}."); return defaultValue; } } diff --git a/src/Razor/src/Microsoft.AspNetCore.Razor.LanguageServer/GeneratedDocumentPublisher.cs b/src/Razor/src/Microsoft.AspNetCore.Razor.LanguageServer/GeneratedDocumentPublisher.cs index 3789f77ffc5..2c75f6b6dc5 100644 --- a/src/Razor/src/Microsoft.AspNetCore.Razor.LanguageServer/GeneratedDocumentPublisher.cs +++ b/src/Razor/src/Microsoft.AspNetCore.Razor.LanguageServer/GeneratedDocumentPublisher.cs @@ -4,6 +4,7 @@ using System; using System.Collections.Generic; using System.Diagnostics; +using System.Linq; using System.Threading; using Microsoft.AspNetCore.Razor.LanguageServer.Hosting; using Microsoft.AspNetCore.Razor.PooledObjects; @@ -95,7 +96,7 @@ public void PublishCSharp(ProjectKey projectKey, string filePath, SourceText sou { HostDocumentFilePath = filePath, ProjectKeyId = projectKey.Id, - Changes = textChanges, + Changes = textChanges.Select(t => t.ToRazorTextChange()).ToArray(), HostDocumentVersion = hostDocumentVersion, PreviousWasEmpty = previouslyPublishedData.SourceText.Length == 0 }; @@ -138,7 +139,7 @@ public void PublishHtml(ProjectKey projectKey, string filePath, SourceText sourc { HostDocumentFilePath = filePath, ProjectKeyId = projectKey.Id, - Changes = textChanges, + Changes = textChanges.Select(t => t.ToRazorTextChange()).ToArray(), HostDocumentVersion = hostDocumentVersion, PreviousWasEmpty = previouslyPublishedData.SourceText.Length == 0 }; diff --git a/src/Razor/src/Microsoft.AspNetCore.Razor.LanguageServer/Hosting/RazorLanguageServerCapability.cs b/src/Razor/src/Microsoft.AspNetCore.Razor.LanguageServer/Hosting/RazorLanguageServerCapability.cs index 0ddb2e761f9..0eac8fb6c58 100644 --- a/src/Razor/src/Microsoft.AspNetCore.Razor.LanguageServer/Hosting/RazorLanguageServerCapability.cs +++ b/src/Razor/src/Microsoft.AspNetCore.Razor.LanguageServer/Hosting/RazorLanguageServerCapability.cs @@ -3,8 +3,8 @@ using System.Collections.Generic; using System.Diagnostics.CodeAnalysis; +using System.Text.Json; using Microsoft.VisualStudio.LanguageServer.Protocol; -using Newtonsoft.Json.Linq; namespace Microsoft.AspNetCore.Razor.LanguageServer.Hosting; @@ -30,33 +30,27 @@ public void ApplyCapabilities(VSInternalServerCapabilities serverCapabilities, V dict["razor"] = s_default; } - public static bool TryGet(JToken token, [NotNullWhen(true)] out RazorLanguageServerCapability? razorCapability) + public static bool TryGet(JsonElement token, [NotNullWhen(true)] out RazorLanguageServerCapability? razorCapability) { - if (token is not JObject jobject) + if (token.ValueKind != JsonValueKind.Object) { razorCapability = null; return false; } - if (!jobject.TryGetValue("experimental", out var experimentalCapabilitiesToken)) + if (!token.TryGetProperty("experimental", out var experimentalCapabilities)) { razorCapability = null; return false; } - if (experimentalCapabilitiesToken is not JObject experimentalCapabilities) + if (!experimentalCapabilities.TryGetProperty(RazorCapabilityKey, out var razorCapabilityToken)) { razorCapability = null; return false; } - if (!experimentalCapabilities.TryGetValue(RazorCapabilityKey, out var razorCapabilityToken)) - { - razorCapability = null; - return false; - } - - razorCapability = razorCapabilityToken.ToObject(); + razorCapability = razorCapabilityToken.Deserialize(); return razorCapability is not null; } } diff --git a/src/Razor/src/Microsoft.AspNetCore.Razor.LanguageServer/Hosting/RazorLanguageServerHost.cs b/src/Razor/src/Microsoft.AspNetCore.Razor.LanguageServer/Hosting/RazorLanguageServerHost.cs index 447448d0396..56e9cb461b9 100644 --- a/src/Razor/src/Microsoft.AspNetCore.Razor.LanguageServer/Hosting/RazorLanguageServerHost.cs +++ b/src/Razor/src/Microsoft.AspNetCore.Razor.LanguageServer/Hosting/RazorLanguageServerHost.cs @@ -4,6 +4,7 @@ using System; using System.Diagnostics; using System.IO; +using System.Text.Json; using System.Threading.Tasks; using Microsoft.AspNetCore.Razor.Telemetry; using Microsoft.CodeAnalysis.Razor.Logging; @@ -11,8 +12,6 @@ using Microsoft.CodeAnalysis.Razor.Workspaces; using Microsoft.Extensions.DependencyInjection; using Microsoft.VisualStudio.LanguageServer.Protocol; -using Newtonsoft.Json; -using Newtonsoft.Json.Serialization; using StreamJsonRpc; namespace Microsoft.AspNetCore.Razor.LanguageServer.Hosting; @@ -74,18 +73,19 @@ public static RazorLanguageServerHost Create( return host; } - private static (JsonRpc, JsonSerializer) CreateJsonRpc(Stream input, Stream output) + private static (JsonRpc, JsonSerializerOptions) CreateJsonRpc(Stream input, Stream output) { - var messageFormatter = new JsonMessageFormatter(); - messageFormatter.JsonSerializer.AddVSInternalExtensionConverters(); - messageFormatter.JsonSerializer.ContractResolver = new CamelCasePropertyNamesContractResolver(); + var messageFormatter = new SystemTextJsonFormatter(); + + // In its infinite wisdom, the LSP client has a public method that takes Newtonsoft.Json types, but an internal method that takes System.Text.Json types. + typeof(VSInternalExtensionUtilities).GetMethod("AddVSInternalExtensionConverters", System.Reflection.BindingFlags.Static | System.Reflection.BindingFlags.NonPublic)!.Invoke(null, [messageFormatter.JsonSerializerOptions]); var jsonRpc = new JsonRpc(new HeaderDelimitedMessageHandler(output, input, messageFormatter)); // Get more information about exceptions that occur during RPC method invocations. jsonRpc.ExceptionStrategy = ExceptionProcessing.ISerializable; - return (jsonRpc, messageFormatter.JsonSerializer); + return (jsonRpc, messageFormatter.JsonSerializerOptions); } public Task WaitForExitAsync() diff --git a/src/Razor/src/Microsoft.AspNetCore.Razor.LanguageServer/InlayHints/InlayHintService.cs b/src/Razor/src/Microsoft.AspNetCore.Razor.LanguageServer/InlayHints/InlayHintService.cs index 8bb6cc50156..7a1143d1a60 100644 --- a/src/Razor/src/Microsoft.AspNetCore.Razor.LanguageServer/InlayHints/InlayHintService.cs +++ b/src/Razor/src/Microsoft.AspNetCore.Razor.LanguageServer/InlayHints/InlayHintService.cs @@ -2,6 +2,8 @@ // Licensed under the MIT license. See License.txt in the project root for license information. using System.Diagnostics; +using System.Text.Json; +using System.Text.Json.Nodes; using System.Threading; using System.Threading.Tasks; using Microsoft.AspNetCore.Razor.Language; @@ -14,7 +16,6 @@ using Microsoft.CodeAnalysis.Razor.Workspaces; using Microsoft.CodeAnalysis.Razor.Workspaces.InlayHints; using Microsoft.VisualStudio.LanguageServer.Protocol; -using Newtonsoft.Json.Linq; namespace Microsoft.AspNetCore.Razor.LanguageServer.InlayHints; @@ -93,10 +94,11 @@ internal sealed class InlayHintService(IRazorDocumentMappingService documentMapp public async Task ResolveInlayHintAsync(IClientConnection clientConnection, InlayHint inlayHint, CancellationToken cancellationToken) { var inlayHintWrapper = inlayHint.Data as RazorInlayHintWrapper; + if (inlayHintWrapper is null && - inlayHint.Data is JObject dataObj) + inlayHint.Data is JsonElement dataElement) { - inlayHintWrapper = dataObj.ToObject(); + inlayHintWrapper = dataElement.Deserialize(); } if (inlayHintWrapper is null) diff --git a/src/Razor/src/Microsoft.AspNetCore.Razor.LanguageServer/InlayHints/RazorInlayHintWrapper.cs b/src/Razor/src/Microsoft.AspNetCore.Razor.LanguageServer/InlayHints/RazorInlayHintWrapper.cs index 02e0b6a722f..8d21b84e325 100644 --- a/src/Razor/src/Microsoft.AspNetCore.Razor.LanguageServer/InlayHints/RazorInlayHintWrapper.cs +++ b/src/Razor/src/Microsoft.AspNetCore.Razor.LanguageServer/InlayHints/RazorInlayHintWrapper.cs @@ -1,6 +1,7 @@ // Copyright (c) .NET Foundation. All rights reserved. // Licensed under the MIT license. See License.txt in the project root for license information. +using System.Text.Json.Serialization; using Microsoft.CodeAnalysis.Razor.Protocol; using Microsoft.VisualStudio.LanguageServer.Protocol; @@ -8,7 +9,10 @@ namespace Microsoft.CodeAnalysis.Razor.Workspaces.InlayHints; internal class RazorInlayHintWrapper { + [JsonPropertyName("textDocument")] public required TextDocumentIdentifierAndVersion TextDocument { get; set; } + [JsonPropertyName("originalData")] public required object? OriginalData { get; set; } + [JsonPropertyName("originalPosition")] public required Position OriginalPosition { get; set; } } diff --git a/src/Razor/src/Microsoft.AspNetCore.Razor.LanguageServer/Mapping/RazorLanguageQueryParams.cs b/src/Razor/src/Microsoft.AspNetCore.Razor.LanguageServer/Mapping/RazorLanguageQueryParams.cs index d7bf0cbd41e..87b292a0911 100644 --- a/src/Razor/src/Microsoft.AspNetCore.Razor.LanguageServer/Mapping/RazorLanguageQueryParams.cs +++ b/src/Razor/src/Microsoft.AspNetCore.Razor.LanguageServer/Mapping/RazorLanguageQueryParams.cs @@ -3,16 +3,16 @@ using System; using System.Runtime.Serialization; +using System.Text.Json.Serialization; using Microsoft.VisualStudio.LanguageServer.Protocol; namespace Microsoft.AspNetCore.Razor.LanguageServer.Mapping; -[DataContract] internal class RazorLanguageQueryParams { - [DataMember(Name = "uri")] + [JsonPropertyName("uri")] public required Uri Uri { get; set; } - [DataMember(Name = "position")] + [JsonPropertyName("position")] public required Position Position { get; set; } } diff --git a/src/Razor/src/Microsoft.AspNetCore.Razor.LanguageServer/Mapping/RazorLanguageQueryResponse.cs b/src/Razor/src/Microsoft.AspNetCore.Razor.LanguageServer/Mapping/RazorLanguageQueryResponse.cs index 41ac1952caf..584ff8e63d9 100644 --- a/src/Razor/src/Microsoft.AspNetCore.Razor.LanguageServer/Mapping/RazorLanguageQueryResponse.cs +++ b/src/Razor/src/Microsoft.AspNetCore.Razor.LanguageServer/Mapping/RazorLanguageQueryResponse.cs @@ -1,24 +1,23 @@ // Copyright (c) .NET Foundation. All rights reserved. // Licensed under the MIT license. See License.txt in the project root for license information. -using System.Runtime.Serialization; +using System.Text.Json.Serialization; using Microsoft.CodeAnalysis.Razor.Protocol; using Microsoft.VisualStudio.LanguageServer.Protocol; namespace Microsoft.AspNetCore.Razor.LanguageServer.Mapping; -[DataContract] internal class RazorLanguageQueryResponse { - [DataMember(Name = "kind")] + [JsonPropertyName("kind")] public RazorLanguageKind Kind { get; set; } - [DataMember(Name = "positionIndex")] + [JsonPropertyName("positionIndex")] public int PositionIndex { get; set; } - [DataMember(Name = "position")] + [JsonPropertyName("position")] public required Position Position { get; set; } - [DataMember(Name = "hostDocumentVersion")] + [JsonPropertyName("hostDocumentVersion")] public int? HostDocumentVersion { get; set; } } diff --git a/src/Razor/src/Microsoft.AspNetCore.Razor.LanguageServer/RazorLanguageServer.cs b/src/Razor/src/Microsoft.AspNetCore.Razor.LanguageServer/RazorLanguageServer.cs index 1e23ce5ba13..17c412bd72b 100644 --- a/src/Razor/src/Microsoft.AspNetCore.Razor.LanguageServer/RazorLanguageServer.cs +++ b/src/Razor/src/Microsoft.AspNetCore.Razor.LanguageServer/RazorLanguageServer.cs @@ -2,6 +2,7 @@ // Licensed under the MIT license. See License.txt in the project root for license information. using System; +using System.Text.Json; using Microsoft.AspNetCore.Razor.LanguageServer.AutoInsert; using Microsoft.AspNetCore.Razor.LanguageServer.ColorPresentation; using Microsoft.AspNetCore.Razor.LanguageServer.Debugging; @@ -32,12 +33,11 @@ using Microsoft.CommonLanguageServerProtocol.Framework; using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.DependencyInjection.Extensions; -using Newtonsoft.Json; using StreamJsonRpc; namespace Microsoft.AspNetCore.Razor.LanguageServer; -internal partial class RazorLanguageServer : NewtonsoftLanguageServer, IDisposable +internal partial class RazorLanguageServer : SystemTextJsonLanguageServer, IDisposable { private readonly JsonRpc _jsonRpc; private readonly ILoggerFactory _loggerFactory; @@ -52,14 +52,14 @@ internal partial class RazorLanguageServer : NewtonsoftLanguageServer? configureServices, RazorLSPOptions? lspOptions, ILspServerActivationTracker? lspServerActivationTracker, ITelemetryReporter telemetryReporter) - : base(jsonRpc, serializer, CreateILspLogger(loggerFactory, telemetryReporter)) + : base(jsonRpc, options, CreateILspLogger(loggerFactory, telemetryReporter)) { _jsonRpc = jsonRpc; _loggerFactory = loggerFactory; diff --git a/src/Razor/src/Microsoft.AspNetCore.Razor.LanguageServer/UpdateBufferRequest.cs b/src/Razor/src/Microsoft.AspNetCore.Razor.LanguageServer/UpdateBufferRequest.cs deleted file mode 100644 index 5ba1ea6465b..00000000000 --- a/src/Razor/src/Microsoft.AspNetCore.Razor.LanguageServer/UpdateBufferRequest.cs +++ /dev/null @@ -1,20 +0,0 @@ -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT license. See License.txt in the project root for license information. - -using System.Collections.Generic; -using Microsoft.CodeAnalysis.Text; - -namespace Microsoft.AspNetCore.Razor.LanguageServer; - -internal class UpdateBufferRequest -{ - public int? HostDocumentVersion { get; set; } - - public string? ProjectKeyId { get; set; } - - public required string HostDocumentFilePath { get; set; } - - public required IReadOnlyList Changes { get; set; } - - public bool PreviousWasEmpty { get; set; } -} diff --git a/src/Razor/src/Microsoft.AspNetCore.Razor.LanguageServer/WrapWithTag/WrapWithTagParams.cs b/src/Razor/src/Microsoft.AspNetCore.Razor.LanguageServer/WrapWithTag/WrapWithTagParams.cs index cd0cf1d415a..65892849b52 100644 --- a/src/Razor/src/Microsoft.AspNetCore.Razor.LanguageServer/WrapWithTag/WrapWithTagParams.cs +++ b/src/Razor/src/Microsoft.AspNetCore.Razor.LanguageServer/WrapWithTag/WrapWithTagParams.cs @@ -1,6 +1,7 @@ // Copyright (c) .NET Foundation. All rights reserved. // Licensed under the MIT license. See License.txt in the project root for license information. +using System.Text.Json.Serialization; using Microsoft.VisualStudio.LanguageServer.Protocol; using Newtonsoft.Json; @@ -14,25 +15,25 @@ internal class WrapWithTagParams /// /// Gets or sets the identifier for the text document to be operate on. /// - [JsonProperty("_vs_textDocument")] + [JsonPropertyName("_vs_textDocument")] public TextDocumentIdentifier TextDocument { get; set; } /// /// Gets or sets the selection range to be wrapped. /// - [JsonProperty("_vs_range")] + [JsonPropertyName("_vs_range")] public Range? Range { get; set; } /// /// Gets or sets the wrapping tag name. /// - [JsonProperty("_vs_tagName")] + [JsonPropertyName("_vs_tagName")] public string? TagName { get; set; } /// /// Gets or sets the formatting options. /// - [JsonProperty("_vs_options")] + [JsonPropertyName("_vs_options")] public FormattingOptions? Options { get; set; } public WrapWithTagParams(TextDocumentIdentifier textDocument) @@ -51,6 +52,6 @@ public DelegatedWrapWithTagParams(VersionedTextDocumentIdentifier identifier, Wr Options = parameters.Options; } - [JsonProperty("_vs_textDocument")] + [JsonPropertyName("_vs_textDocument")] public new VersionedTextDocumentIdentifier TextDocument { get; set; } } diff --git a/src/Razor/src/Microsoft.AspNetCore.Razor.LanguageServer/WrapWithTag/WrapWithTagResponse.cs b/src/Razor/src/Microsoft.AspNetCore.Razor.LanguageServer/WrapWithTag/WrapWithTagResponse.cs index ae3a240be03..1f580332c7d 100644 --- a/src/Razor/src/Microsoft.AspNetCore.Razor.LanguageServer/WrapWithTag/WrapWithTagResponse.cs +++ b/src/Razor/src/Microsoft.AspNetCore.Razor.LanguageServer/WrapWithTag/WrapWithTagResponse.cs @@ -1,8 +1,8 @@ // Copyright (c) .NET Foundation. All rights reserved. // Licensed under the MIT license. See License.txt in the project root for license information. +using System.Text.Json.Serialization; using Microsoft.VisualStudio.LanguageServer.Protocol; -using Newtonsoft.Json; namespace Microsoft.AspNetCore.Razor.LanguageServer.WrapWithTag; @@ -14,12 +14,12 @@ internal class WrapWithTagResponse /// /// Gets or sets the range of the wrapping tag. /// - [JsonProperty("_vs_tagRange")] + [JsonPropertyName("_vs_tagRange")] public Range? TagRange { get; set; } /// /// Gets or sets the text edits. /// - [JsonProperty("_vs_textEdits")] + [JsonPropertyName("_vs_textEdits")] public TextEdit[]? TextEdits { get; set; } } diff --git a/src/Razor/src/Microsoft.CodeAnalysis.Razor.Workspaces/Extensions/TextChangeExtensions.cs b/src/Razor/src/Microsoft.CodeAnalysis.Razor.Workspaces/Extensions/TextChangeExtensions.cs index a2606290782..e0479829ef1 100644 --- a/src/Razor/src/Microsoft.CodeAnalysis.Razor.Workspaces/Extensions/TextChangeExtensions.cs +++ b/src/Razor/src/Microsoft.CodeAnalysis.Razor.Workspaces/Extensions/TextChangeExtensions.cs @@ -2,6 +2,7 @@ // Licensed under the MIT license. See License.txt in the project root for license information. using System; +using Microsoft.CodeAnalysis.Razor.Protocol; using Microsoft.CodeAnalysis.Text; using Microsoft.VisualStudio.LanguageServer.Protocol; @@ -26,4 +27,17 @@ public static TextEdit ToTextEdit(this TextChange textChange, SourceText sourceT Range = range }; } + + public static RazorTextChange ToRazorTextChange(this TextChange textChange) + { + return new RazorTextChange() + { + Span = new RazorTextSpan() + { + Start = textChange.Span.Start, + Length = textChange.Span.Length, + }, + NewText = textChange.NewText + }; + } } diff --git a/src/Razor/src/Microsoft.CodeAnalysis.Razor.Workspaces/Protocol/CodeActions/DelegatedCodeActionParams.cs b/src/Razor/src/Microsoft.CodeAnalysis.Razor.Workspaces/Protocol/CodeActions/DelegatedCodeActionParams.cs index cd48169b78f..6f5ad59ef17 100644 --- a/src/Razor/src/Microsoft.CodeAnalysis.Razor.Workspaces/Protocol/CodeActions/DelegatedCodeActionParams.cs +++ b/src/Razor/src/Microsoft.CodeAnalysis.Razor.Workspaces/Protocol/CodeActions/DelegatedCodeActionParams.cs @@ -2,22 +2,21 @@ // Licensed under the MIT license. See License.txt in the project root for license information. using System; -using System.Runtime.Serialization; +using System.Text.Json.Serialization; namespace Microsoft.CodeAnalysis.Razor.Protocol.CodeActions; -[DataContract] internal class DelegatedCodeActionParams { - [DataMember(Name = "hostDocumentVersion")] + [JsonPropertyName("hostDocumentVersion")] public int HostDocumentVersion { get; set; } - [DataMember(Name = "codeActionParams")] + [JsonPropertyName("codeActionParams")] public required VSCodeActionParams CodeActionParams { get; set; } - [DataMember(Name = "languageKind")] + [JsonPropertyName("languageKind")] public RazorLanguageKind LanguageKind { get; set; } - [DataMember(Name = "correlationId")] + [JsonPropertyName("correlationId")] public Guid CorrelationId { get; set; } } diff --git a/src/Razor/src/Microsoft.CodeAnalysis.Razor.Workspaces/Protocol/CodeActions/RazorResolveCodeActionParams.cs b/src/Razor/src/Microsoft.CodeAnalysis.Razor.Workspaces/Protocol/CodeActions/RazorResolveCodeActionParams.cs index d7cffa13cea..4ecf43d0505 100644 --- a/src/Razor/src/Microsoft.CodeAnalysis.Razor.Workspaces/Protocol/CodeActions/RazorResolveCodeActionParams.cs +++ b/src/Razor/src/Microsoft.CodeAnalysis.Razor.Workspaces/Protocol/CodeActions/RazorResolveCodeActionParams.cs @@ -1,8 +1,13 @@ // Copyright (c) .NET Foundation. All rights reserved. // Licensed under the MIT license. See License.txt in the project root for license information. +using System.Text.Json.Serialization; using Microsoft.VisualStudio.LanguageServer.Protocol; namespace Microsoft.CodeAnalysis.Razor.Protocol.CodeActions; -internal record RazorResolveCodeActionParams(TextDocumentIdentifier Identifier, int HostDocumentVersion, RazorLanguageKind LanguageKind, CodeAction CodeAction); +internal record RazorResolveCodeActionParams( + [property: JsonPropertyName("identifier")] TextDocumentIdentifier Identifier, + [property: JsonPropertyName("hostDocumentVersion")] int HostDocumentVersion, + [property: JsonPropertyName("languageKind")] RazorLanguageKind LanguageKind, + [property: JsonPropertyName("codeAction")] CodeAction CodeAction); diff --git a/src/Razor/src/Microsoft.CodeAnalysis.Razor.Workspaces/Protocol/ColorPresentation/ColorPresentation.cs b/src/Razor/src/Microsoft.CodeAnalysis.Razor.Workspaces/Protocol/ColorPresentation/ColorPresentation.cs index fe27a6cafaa..d8f678ac6bc 100644 --- a/src/Razor/src/Microsoft.CodeAnalysis.Razor.Workspaces/Protocol/ColorPresentation/ColorPresentation.cs +++ b/src/Razor/src/Microsoft.CodeAnalysis.Razor.Workspaces/Protocol/ColorPresentation/ColorPresentation.cs @@ -3,21 +3,20 @@ #nullable disable -using System.Runtime.Serialization; +using System.Text.Json.Serialization; using Microsoft.VisualStudio.LanguageServer.Protocol; namespace Microsoft.CodeAnalysis.Razor.Protocol.ColorPresentation; // VS doesn't support textDocument/colorPresentation but VSCode does. This class is a workaround until VS adds support. -[DataContract] internal sealed class ColorPresentation { - [DataMember(Name = "label")] + [JsonPropertyName("label")] public string Label { get; set; } - [DataMember(Name = "textEdit")] + [JsonPropertyName("textEdit")] public TextEdit TextEdit { get; set; } - [DataMember(Name = "additionalTextEdits")] + [JsonPropertyName("additionalTextEdits")] public TextEdit[] AdditionalTextEdits { get; set; } } diff --git a/src/Razor/src/Microsoft.CodeAnalysis.Razor.Workspaces/Protocol/ColorPresentation/ColorPresentationParams.cs b/src/Razor/src/Microsoft.CodeAnalysis.Razor.Workspaces/Protocol/ColorPresentation/ColorPresentationParams.cs index 830e5e061a5..e56dfddec45 100644 --- a/src/Razor/src/Microsoft.CodeAnalysis.Razor.Workspaces/Protocol/ColorPresentation/ColorPresentationParams.cs +++ b/src/Razor/src/Microsoft.CodeAnalysis.Razor.Workspaces/Protocol/ColorPresentation/ColorPresentationParams.cs @@ -3,21 +3,20 @@ #nullable disable -using System.Runtime.Serialization; +using System.Text.Json.Serialization; using Microsoft.VisualStudio.LanguageServer.Protocol; namespace Microsoft.CodeAnalysis.Razor.Protocol.ColorPresentation; // VS doesn't support textDocument/colorPresentation but VSCode does. This class is a workaround until VS adds support. -[DataContract] internal class ColorPresentationParams { - [DataMember(Name = "textDocument")] + [JsonPropertyName("textDocument")] public TextDocumentIdentifier TextDocument { get; set; } - [DataMember(Name = "color")] + [JsonPropertyName("color")] public Color Color { get; set; } - [DataMember(Name = "range")] + [JsonPropertyName("range")] public Range Range { get; set; } } diff --git a/src/Razor/src/Microsoft.CodeAnalysis.Razor.Workspaces/Protocol/ColorPresentation/DelegatedColorPresentationParams.cs b/src/Razor/src/Microsoft.CodeAnalysis.Razor.Workspaces/Protocol/ColorPresentation/DelegatedColorPresentationParams.cs index 0bf0698c1df..988fa08eb03 100644 --- a/src/Razor/src/Microsoft.CodeAnalysis.Razor.Workspaces/Protocol/ColorPresentation/DelegatedColorPresentationParams.cs +++ b/src/Razor/src/Microsoft.CodeAnalysis.Razor.Workspaces/Protocol/ColorPresentation/DelegatedColorPresentationParams.cs @@ -1,13 +1,12 @@ // Copyright (c) .NET Foundation. All rights reserved. // Licensed under the MIT license. See License.txt in the project root for license information. -using System.Runtime.Serialization; +using System.Text.Json.Serialization; namespace Microsoft.CodeAnalysis.Razor.Protocol.ColorPresentation; -[DataContract] internal class DelegatedColorPresentationParams : ColorPresentationParams { - [DataMember(Name = "_vs_requiredHostDocumentVersion")] + [JsonPropertyName("_vs_requiredHostDocumentVersion")] public int RequiredHostDocumentVersion { get; set; } } diff --git a/src/Razor/src/Microsoft.CodeAnalysis.Razor.Workspaces/Protocol/ColorPresentation/DelegatedDocumentColorParams.cs b/src/Razor/src/Microsoft.CodeAnalysis.Razor.Workspaces/Protocol/ColorPresentation/DelegatedDocumentColorParams.cs index f8f04a01a43..89729afc428 100644 --- a/src/Razor/src/Microsoft.CodeAnalysis.Razor.Workspaces/Protocol/ColorPresentation/DelegatedDocumentColorParams.cs +++ b/src/Razor/src/Microsoft.CodeAnalysis.Razor.Workspaces/Protocol/ColorPresentation/DelegatedDocumentColorParams.cs @@ -1,14 +1,13 @@ // Copyright (c) .NET Foundation. All rights reserved. // Licensed under the MIT license. See License.txt in the project root for license information. -using System.Runtime.Serialization; +using System.Text.Json.Serialization; using Microsoft.VisualStudio.LanguageServer.Protocol; namespace Microsoft.CodeAnalysis.Razor.Protocol.ColorPresentation; -[DataContract] internal class DelegatedDocumentColorParams : DocumentColorParams { - [DataMember(Name = "_razor_hostDocumentVersion")] + [JsonPropertyName("_razor_hostDocumentVersion")] public int HostDocumentVersion { get; set; } } diff --git a/src/Razor/src/Microsoft.CodeAnalysis.Razor.Workspaces/Protocol/Completion/RazorInlineCompletionRequest.cs b/src/Razor/src/Microsoft.CodeAnalysis.Razor.Workspaces/Protocol/Completion/RazorInlineCompletionRequest.cs index 9a5df90d199..2c4a0a6b689 100644 --- a/src/Razor/src/Microsoft.CodeAnalysis.Razor.Workspaces/Protocol/Completion/RazorInlineCompletionRequest.cs +++ b/src/Razor/src/Microsoft.CodeAnalysis.Razor.Workspaces/Protocol/Completion/RazorInlineCompletionRequest.cs @@ -1,15 +1,13 @@ // Copyright (c) .NET Foundation. All rights reserved. // Licensed under the MIT license. See License.txt in the project root for license information. -using System.Runtime.Serialization; +using System.Text.Json.Serialization; using Microsoft.VisualStudio.LanguageServer.Protocol; -using Newtonsoft.Json; namespace Microsoft.CodeAnalysis.Razor.Protocol.Completion; internal class RazorInlineCompletionRequest : VSInternalInlineCompletionRequest { - [DataMember(Name = "razorLanguageKind")] - [JsonProperty(Required = Required.Always)] + [JsonPropertyName("razorLanguageKind")] public RazorLanguageKind Kind { get; set; } } diff --git a/src/Razor/src/Microsoft.CodeAnalysis.Razor.Workspaces/Protocol/Debugging/RazorBreakpointSpanParams.cs b/src/Razor/src/Microsoft.CodeAnalysis.Razor.Workspaces/Protocol/Debugging/RazorBreakpointSpanParams.cs index 67aaeca40f4..f486bc6230f 100644 --- a/src/Razor/src/Microsoft.CodeAnalysis.Razor.Workspaces/Protocol/Debugging/RazorBreakpointSpanParams.cs +++ b/src/Razor/src/Microsoft.CodeAnalysis.Razor.Workspaces/Protocol/Debugging/RazorBreakpointSpanParams.cs @@ -2,13 +2,16 @@ // Licensed under the MIT license. See License.txt in the project root for license information. using System; +using System.Text.Json.Serialization; using Microsoft.VisualStudio.LanguageServer.Protocol; namespace Microsoft.CodeAnalysis.Razor.Protocol.Debugging; internal class RazorBreakpointSpanParams { + [JsonPropertyName("uri")] public required Uri Uri { get; init; } + [JsonPropertyName("position")] public required Position Position { get; init; } } diff --git a/src/Razor/src/Microsoft.CodeAnalysis.Razor.Workspaces/Protocol/Debugging/RazorBreakpointSpanResponse.cs b/src/Razor/src/Microsoft.CodeAnalysis.Razor.Workspaces/Protocol/Debugging/RazorBreakpointSpanResponse.cs index adc972c0ddf..cfafecfbd05 100644 --- a/src/Razor/src/Microsoft.CodeAnalysis.Razor.Workspaces/Protocol/Debugging/RazorBreakpointSpanResponse.cs +++ b/src/Razor/src/Microsoft.CodeAnalysis.Razor.Workspaces/Protocol/Debugging/RazorBreakpointSpanResponse.cs @@ -1,9 +1,12 @@ // Copyright (c) .NET Foundation. All rights reserved. // Licensed under the MIT license. See License.txt in the project root for license information. +using System.Text.Json.Serialization; + namespace Microsoft.CodeAnalysis.Razor.Protocol.Debugging; internal class RazorBreakpointSpanResponse { + [JsonPropertyName("range")] public required Range Range { get; init; } } diff --git a/src/Razor/src/Microsoft.CodeAnalysis.Razor.Workspaces/Protocol/Debugging/RazorProximityExpressionsParams.cs b/src/Razor/src/Microsoft.CodeAnalysis.Razor.Workspaces/Protocol/Debugging/RazorProximityExpressionsParams.cs index 0b9cafd289f..d56edee55b7 100644 --- a/src/Razor/src/Microsoft.CodeAnalysis.Razor.Workspaces/Protocol/Debugging/RazorProximityExpressionsParams.cs +++ b/src/Razor/src/Microsoft.CodeAnalysis.Razor.Workspaces/Protocol/Debugging/RazorProximityExpressionsParams.cs @@ -2,13 +2,16 @@ // Licensed under the MIT license. See License.txt in the project root for license information. using System; +using System.Text.Json.Serialization; using Microsoft.VisualStudio.LanguageServer.Protocol; namespace Microsoft.CodeAnalysis.Razor.Protocol.Debugging; internal class RazorProximityExpressionsParams { + [JsonPropertyName("uri")] public required Uri Uri { get; init; } + [JsonPropertyName("position")] public required Position Position { get; init; } } diff --git a/src/Razor/src/Microsoft.CodeAnalysis.Razor.Workspaces/Protocol/Debugging/RazorProximityExpressionsResponse.cs b/src/Razor/src/Microsoft.CodeAnalysis.Razor.Workspaces/Protocol/Debugging/RazorProximityExpressionsResponse.cs index 7e62e82b764..87d61b7c568 100644 --- a/src/Razor/src/Microsoft.CodeAnalysis.Razor.Workspaces/Protocol/Debugging/RazorProximityExpressionsResponse.cs +++ b/src/Razor/src/Microsoft.CodeAnalysis.Razor.Workspaces/Protocol/Debugging/RazorProximityExpressionsResponse.cs @@ -2,10 +2,12 @@ // Licensed under the MIT license. See License.txt in the project root for license information. using System.Collections.Generic; +using System.Text.Json.Serialization; namespace Microsoft.CodeAnalysis.Razor.Protocol.Debugging; internal class RazorProximityExpressionsResponse { + [JsonPropertyName("expressions")] public required IReadOnlyList Expressions { get; init; } } diff --git a/src/Razor/src/Microsoft.CodeAnalysis.Razor.Workspaces/Protocol/DelegatedTypes.cs b/src/Razor/src/Microsoft.CodeAnalysis.Razor.Workspaces/Protocol/DelegatedTypes.cs index 66cbb62e91f..ff1b67da580 100644 --- a/src/Razor/src/Microsoft.CodeAnalysis.Razor.Workspaces/Protocol/DelegatedTypes.cs +++ b/src/Razor/src/Microsoft.CodeAnalysis.Razor.Workspaces/Protocol/DelegatedTypes.cs @@ -2,6 +2,7 @@ // Licensed under the MIT license. See License.txt in the project root for license information. using System; +using System.Text.Json.Serialization; // A file for delegated record types to be put. Each individually // should be a plain record. If more logic is needed than record @@ -12,77 +13,77 @@ namespace Microsoft.CodeAnalysis.Razor.Protocol; using Microsoft.VisualStudio.LanguageServer.Protocol; internal record DelegatedSpellCheckParams( - TextDocumentIdentifierAndVersion Identifier); + [property: JsonPropertyName("identifier")] TextDocumentIdentifierAndVersion Identifier); internal record DelegatedDiagnosticParams( - TextDocumentIdentifierAndVersion Identifier, - Guid CorrelationId); + [property: JsonPropertyName("identifier")] TextDocumentIdentifierAndVersion Identifier, + [property: JsonPropertyName("correlationId")] Guid CorrelationId); internal record DelegatedPositionParams( - TextDocumentIdentifierAndVersion Identifier, - Position ProjectedPosition, - RazorLanguageKind ProjectedKind) : IDelegatedParams; + [property: JsonPropertyName("identifier")] TextDocumentIdentifierAndVersion Identifier, + [property: JsonPropertyName("projectedPosition")] Position ProjectedPosition, + [property: JsonPropertyName("projectedKind")] RazorLanguageKind ProjectedKind) : IDelegatedParams; internal record DelegatedInlayHintParams( - TextDocumentIdentifierAndVersion Identifier, - Range ProjectedRange, - RazorLanguageKind ProjectedKind) : IDelegatedParams; + [property: JsonPropertyName("identifier")] TextDocumentIdentifierAndVersion Identifier, + [property: JsonPropertyName("projectedRange")] Range ProjectedRange, + [property: JsonPropertyName("projectedKind")] RazorLanguageKind ProjectedKind) : IDelegatedParams; internal record DelegatedInlayHintResolveParams( - TextDocumentIdentifierAndVersion Identifier, - InlayHint InlayHint, - RazorLanguageKind ProjectedKind) : IDelegatedParams; + [property: JsonPropertyName("identifier")] TextDocumentIdentifierAndVersion Identifier, + [property: JsonPropertyName("inlayHint")] InlayHint InlayHint, + [property: JsonPropertyName("projectedKind")] RazorLanguageKind ProjectedKind) : IDelegatedParams; internal record DelegatedValidateBreakpointRangeParams( - TextDocumentIdentifierAndVersion Identifier, - Range ProjectedRange, - RazorLanguageKind ProjectedKind) : IDelegatedParams; + [property: JsonPropertyName("identifier")] TextDocumentIdentifierAndVersion Identifier, + [property: JsonPropertyName("projectedRange")] Range ProjectedRange, + [property: JsonPropertyName("projectedKind")] RazorLanguageKind ProjectedKind) : IDelegatedParams; internal record DelegatedOnAutoInsertParams( - TextDocumentIdentifierAndVersion Identifier, - Position ProjectedPosition, - RazorLanguageKind ProjectedKind, - string Character, - FormattingOptions Options) : IDelegatedParams; + [property: JsonPropertyName("identifier")] TextDocumentIdentifierAndVersion Identifier, + [property: JsonPropertyName("projectedPosition")] Position ProjectedPosition, + [property: JsonPropertyName("projectedKind")] RazorLanguageKind ProjectedKind, + [property: JsonPropertyName("character")] string Character, + [property: JsonPropertyName("options")] FormattingOptions Options) : IDelegatedParams; internal record DelegatedRenameParams( - TextDocumentIdentifierAndVersion Identifier, - Position ProjectedPosition, - RazorLanguageKind ProjectedKind, - string NewName) : IDelegatedParams; + [property: JsonPropertyName("identifier")] TextDocumentIdentifierAndVersion Identifier, + [property: JsonPropertyName("projectedPosition")] Position ProjectedPosition, + [property: JsonPropertyName("projectedKind")] RazorLanguageKind ProjectedKind, + [property: JsonPropertyName("newName")] string NewName) : IDelegatedParams; internal record DelegatedCompletionParams( - TextDocumentIdentifierAndVersion Identifier, - Position ProjectedPosition, - RazorLanguageKind ProjectedKind, - VSInternalCompletionContext Context, - TextEdit? ProvisionalTextEdit, - bool ShouldIncludeSnippets, - Guid CorrelationId) : IDelegatedParams; + [property: JsonPropertyName("identifier")] TextDocumentIdentifierAndVersion Identifier, + [property: JsonPropertyName("projectedPosition")] Position ProjectedPosition, + [property: JsonPropertyName("projectedKind")] RazorLanguageKind ProjectedKind, + [property: JsonPropertyName("context")] VSInternalCompletionContext Context, + [property: JsonPropertyName("provisionalTextEdit")] TextEdit? ProvisionalTextEdit, + [property: JsonPropertyName("shouldIncludeSnippets")] bool ShouldIncludeSnippets, + [property: JsonPropertyName("correlationId")] Guid CorrelationId) : IDelegatedParams; internal record DelegatedMapCodeParams( - TextDocumentIdentifierAndVersion Identifier, - RazorLanguageKind ProjectedKind, - Guid MapCodeCorrelationId, - string[] Contents, - Location[][] FocusLocations) : IDelegatedParams; + [property: JsonPropertyName("identifier")] TextDocumentIdentifierAndVersion Identifier, + [property: JsonPropertyName("projectedKind")] RazorLanguageKind ProjectedKind, + [property: JsonPropertyName("mapCodeCorrelationId")] Guid MapCodeCorrelationId, + [property: JsonPropertyName("contents")] string[] Contents, + [property: JsonPropertyName("focusLocations")] Location[][] FocusLocations) : IDelegatedParams; internal record DelegatedCompletionResolutionContext( - DelegatedCompletionParams OriginalRequestParams, - object? OriginalCompletionListData); + [property: JsonPropertyName("originalRequestParams")] DelegatedCompletionParams OriginalRequestParams, + [property: JsonPropertyName("originalCompletionListData")] object? OriginalCompletionListData); internal record DelegatedCompletionItemResolveParams( - TextDocumentIdentifierAndVersion Identifier, - VSInternalCompletionItem CompletionItem, - RazorLanguageKind OriginatingKind); + [property: JsonPropertyName("identifier")] TextDocumentIdentifierAndVersion Identifier, + [property: JsonPropertyName("completionItem")] VSInternalCompletionItem CompletionItem, + [property: JsonPropertyName("originatingKind")] RazorLanguageKind OriginatingKind); internal record DelegatedProjectContextsParams( - Uri Uri); + [property: JsonPropertyName("uri")] Uri Uri); internal record DelegatedDocumentSymbolParams( - TextDocumentIdentifierAndVersion Identifier); + [property: JsonPropertyName("identifier")] TextDocumentIdentifierAndVersion Identifier); internal record DelegatedSimplifyMethodParams( - TextDocumentIdentifierAndVersion Identifier, - bool RequiresVirtualDocument, - TextEdit TextEdit); + [property: JsonPropertyName("identifier")] TextDocumentIdentifierAndVersion Identifier, + [property: JsonPropertyName("requiresVirtualDocument")] bool RequiresVirtualDocument, + [property: JsonPropertyName("textEdit")] TextEdit TextEdit); diff --git a/src/Razor/src/Microsoft.CodeAnalysis.Razor.Workspaces/Protocol/Diagnostics/RazorPullDiagnosticResponse.cs b/src/Razor/src/Microsoft.CodeAnalysis.Razor.Workspaces/Protocol/Diagnostics/RazorPullDiagnosticResponse.cs index 1041397a4fc..91ee4523003 100644 --- a/src/Razor/src/Microsoft.CodeAnalysis.Razor.Workspaces/Protocol/Diagnostics/RazorPullDiagnosticResponse.cs +++ b/src/Razor/src/Microsoft.CodeAnalysis.Razor.Workspaces/Protocol/Diagnostics/RazorPullDiagnosticResponse.cs @@ -1,8 +1,11 @@ // Copyright (c) .NET Foundation. All rights reserved. // Licensed under the MIT license. See License.txt in the project root for license information. +using System.Text.Json.Serialization; using Microsoft.VisualStudio.LanguageServer.Protocol; namespace Microsoft.CodeAnalysis.Razor.Protocol.Diagnostics; -internal record RazorPullDiagnosticResponse(VSInternalDiagnosticReport[] CSharpDiagnostics, VSInternalDiagnosticReport[] HtmlDiagnostics); +internal record RazorPullDiagnosticResponse( + [property: JsonPropertyName("csharpDiagnostics")] VSInternalDiagnosticReport[] CSharpDiagnostics, + [property: JsonPropertyName("htmlDiagnostics")] VSInternalDiagnosticReport[] HtmlDiagnostics); diff --git a/src/Razor/src/Microsoft.CodeAnalysis.Razor.Workspaces/Protocol/DocumentMapping/RazorMapToDocumentRangesParams.cs b/src/Razor/src/Microsoft.CodeAnalysis.Razor.Workspaces/Protocol/DocumentMapping/RazorMapToDocumentRangesParams.cs index c85320bf96a..6118b3227be 100644 --- a/src/Razor/src/Microsoft.CodeAnalysis.Razor.Workspaces/Protocol/DocumentMapping/RazorMapToDocumentRangesParams.cs +++ b/src/Razor/src/Microsoft.CodeAnalysis.Razor.Workspaces/Protocol/DocumentMapping/RazorMapToDocumentRangesParams.cs @@ -2,23 +2,22 @@ // Licensed under the MIT license. See License.txt in the project root for license information. using System; -using System.Runtime.Serialization; +using System.Text.Json.Serialization; using Microsoft.CodeAnalysis.Razor.DocumentMapping; namespace Microsoft.CodeAnalysis.Razor.Protocol.DocumentMapping; -[DataContract] internal class RazorMapToDocumentRangesParams { - [DataMember(Name = "kind")] + [JsonPropertyName("kind")] public RazorLanguageKind Kind { get; init; } - [DataMember(Name = "razorDocumentUri")] + [JsonPropertyName("razorDocumentUri")] public required Uri RazorDocumentUri { get; init; } - [DataMember(Name = "projectedRanges")] + [JsonPropertyName("projectedRanges")] public required Range[] ProjectedRanges { get; init; } - [DataMember(Name = "mappingBehavior")] + [JsonPropertyName("mappingBehavior")] public MappingBehavior MappingBehavior { get; init; } } diff --git a/src/Razor/src/Microsoft.CodeAnalysis.Razor.Workspaces/Protocol/DocumentMapping/RazorMapToDocumentRangesResponse.cs b/src/Razor/src/Microsoft.CodeAnalysis.Razor.Workspaces/Protocol/DocumentMapping/RazorMapToDocumentRangesResponse.cs index ec4427d9942..8692fa83020 100644 --- a/src/Razor/src/Microsoft.CodeAnalysis.Razor.Workspaces/Protocol/DocumentMapping/RazorMapToDocumentRangesResponse.cs +++ b/src/Razor/src/Microsoft.CodeAnalysis.Razor.Workspaces/Protocol/DocumentMapping/RazorMapToDocumentRangesResponse.cs @@ -1,16 +1,15 @@ // Copyright (c) .NET Foundation. All rights reserved. // Licensed under the MIT license. See License.txt in the project root for license information. -using System.Runtime.Serialization; +using System.Text.Json.Serialization; namespace Microsoft.CodeAnalysis.Razor.Protocol.DocumentMapping; -[DataContract] internal class RazorMapToDocumentRangesResponse { - [DataMember(Name = "ranges")] + [JsonPropertyName("ranges")] public required Range[] Ranges { get; init; } - [DataMember(Name = "hostDocumentVersion")] + [JsonPropertyName("hostDocumentVersion")] public int? HostDocumentVersion { get; init; } } diff --git a/src/Razor/src/Microsoft.CodeAnalysis.Razor.Workspaces/Protocol/DocumentPresentation/RazorTextPresentationParams.cs b/src/Razor/src/Microsoft.CodeAnalysis.Razor.Workspaces/Protocol/DocumentPresentation/RazorTextPresentationParams.cs index 493050aa1db..97f8cd23860 100644 --- a/src/Razor/src/Microsoft.CodeAnalysis.Razor.Workspaces/Protocol/DocumentPresentation/RazorTextPresentationParams.cs +++ b/src/Razor/src/Microsoft.CodeAnalysis.Razor.Workspaces/Protocol/DocumentPresentation/RazorTextPresentationParams.cs @@ -1,7 +1,7 @@ // Copyright (c) .NET Foundation. All rights reserved. // Licensed under the MIT license. See License.txt in the project root for license information. -using System.Runtime.Serialization; +using System.Text.Json.Serialization; namespace Microsoft.CodeAnalysis.Razor.Protocol.DocumentPresentation; @@ -11,9 +11,9 @@ namespace Microsoft.CodeAnalysis.Razor.Protocol.DocumentPresentation; /// internal class RazorTextPresentationParams : TextPresentationParams, IRazorPresentationParams { - [DataMember] + [JsonPropertyName("kind")] public RazorLanguageKind Kind { get; set; } - [DataMember] + [JsonPropertyName("hostDocumentVersion")] public int HostDocumentVersion { get; set; } } diff --git a/src/Razor/src/Microsoft.CodeAnalysis.Razor.Workspaces/Protocol/DocumentPresentation/RazorUriPresentationParams.cs b/src/Razor/src/Microsoft.CodeAnalysis.Razor.Workspaces/Protocol/DocumentPresentation/RazorUriPresentationParams.cs index 282aee39758..f324c00ef9a 100644 --- a/src/Razor/src/Microsoft.CodeAnalysis.Razor.Workspaces/Protocol/DocumentPresentation/RazorUriPresentationParams.cs +++ b/src/Razor/src/Microsoft.CodeAnalysis.Razor.Workspaces/Protocol/DocumentPresentation/RazorUriPresentationParams.cs @@ -1,7 +1,7 @@ // Copyright (c) .NET Foundation. All rights reserved. // Licensed under the MIT license. See License.txt in the project root for license information. -using System.Runtime.Serialization; +using System.Text.Json.Serialization; namespace Microsoft.CodeAnalysis.Razor.Protocol.DocumentPresentation; @@ -11,9 +11,9 @@ namespace Microsoft.CodeAnalysis.Razor.Protocol.DocumentPresentation; /// internal class RazorUriPresentationParams : UriPresentationParams, IRazorPresentationParams { - [DataMember] + [JsonPropertyName("kind")] public RazorLanguageKind Kind { get; set; } - [DataMember] + [JsonPropertyName("hostDocumentVersion")] public int HostDocumentVersion { get; set; } } diff --git a/src/Razor/src/Microsoft.CodeAnalysis.Razor.Workspaces/Protocol/Folding/RazorFoldingRangeRequestParam.cs b/src/Razor/src/Microsoft.CodeAnalysis.Razor.Workspaces/Protocol/Folding/RazorFoldingRangeRequestParam.cs index 863e6ecec0b..90b07fe6ad2 100644 --- a/src/Razor/src/Microsoft.CodeAnalysis.Razor.Workspaces/Protocol/Folding/RazorFoldingRangeRequestParam.cs +++ b/src/Razor/src/Microsoft.CodeAnalysis.Razor.Workspaces/Protocol/Folding/RazorFoldingRangeRequestParam.cs @@ -1,13 +1,13 @@ // Copyright (c) .NET Foundation. All rights reserved. // Licensed under the MIT license. See License.txt in the project root for license information. -using System.Runtime.Serialization; +using System.Text.Json.Serialization; using Microsoft.VisualStudio.LanguageServer.Protocol; namespace Microsoft.CodeAnalysis.Razor.Protocol.Folding; internal class RazorFoldingRangeRequestParam : FoldingRangeParams { - [DataMember(Name = "hostDocumentVersion")] + [JsonPropertyName("hostDocumentVersion")] public int HostDocumentVersion { get; init; } } diff --git a/src/Razor/src/Microsoft.CodeAnalysis.Razor.Workspaces/Protocol/Folding/RazorFoldingRangeResponse.cs b/src/Razor/src/Microsoft.CodeAnalysis.Razor.Workspaces/Protocol/Folding/RazorFoldingRangeResponse.cs index 638308d1c7c..b08e8a162c7 100644 --- a/src/Razor/src/Microsoft.CodeAnalysis.Razor.Workspaces/Protocol/Folding/RazorFoldingRangeResponse.cs +++ b/src/Razor/src/Microsoft.CodeAnalysis.Razor.Workspaces/Protocol/Folding/RazorFoldingRangeResponse.cs @@ -2,11 +2,14 @@ // Licensed under the MIT license. See License.txt in the project root for license information. using System.Collections.Immutable; +using System.Text.Json.Serialization; using Microsoft.VisualStudio.LanguageServer.Protocol; namespace Microsoft.CodeAnalysis.Razor.Protocol.Folding; -internal sealed record RazorFoldingRangeResponse(ImmutableArray HtmlRanges, ImmutableArray CSharpRanges) +internal sealed record RazorFoldingRangeResponse( + [property: JsonPropertyName("htmlRanges")] ImmutableArray HtmlRanges, + [property: JsonPropertyName("csharpRanges")] ImmutableArray CSharpRanges) { public static readonly RazorFoldingRangeResponse Empty = new(ImmutableArray.Empty, ImmutableArray.Empty); } diff --git a/src/Razor/src/Microsoft.CodeAnalysis.Razor.Workspaces/Protocol/Formatting/RazorDocumentFormattingParams.cs b/src/Razor/src/Microsoft.CodeAnalysis.Razor.Workspaces/Protocol/Formatting/RazorDocumentFormattingParams.cs index 680e434c255..c4a4f7cceb3 100644 --- a/src/Razor/src/Microsoft.CodeAnalysis.Razor.Workspaces/Protocol/Formatting/RazorDocumentFormattingParams.cs +++ b/src/Razor/src/Microsoft.CodeAnalysis.Razor.Workspaces/Protocol/Formatting/RazorDocumentFormattingParams.cs @@ -1,14 +1,13 @@ // Copyright (c) .NET Foundation. All rights reserved. // Licensed under the MIT license. See License.txt in the project root for license information. -using System.Runtime.Serialization; +using System.Text.Json.Serialization; using Microsoft.VisualStudio.LanguageServer.Protocol; namespace Microsoft.CodeAnalysis.Razor.Protocol.Formatting; -[DataContract] internal class RazorDocumentFormattingParams : DocumentFormattingParams { - [DataMember(Name = "hostDocumentVersion")] + [JsonPropertyName("hostDocumentVersion")] public int HostDocumentVersion { get; set; } } diff --git a/src/Razor/src/Microsoft.CodeAnalysis.Razor.Workspaces/Protocol/Formatting/RazorDocumentFormattingResponse.cs b/src/Razor/src/Microsoft.CodeAnalysis.Razor.Workspaces/Protocol/Formatting/RazorDocumentFormattingResponse.cs index 4c6e6347c6c..b9cb31f7344 100644 --- a/src/Razor/src/Microsoft.CodeAnalysis.Razor.Workspaces/Protocol/Formatting/RazorDocumentFormattingResponse.cs +++ b/src/Razor/src/Microsoft.CodeAnalysis.Razor.Workspaces/Protocol/Formatting/RazorDocumentFormattingResponse.cs @@ -1,11 +1,13 @@ // Copyright (c) .NET Foundation. All rights reserved. // Licensed under the MIT license. See License.txt in the project root for license information. +using System.Text.Json.Serialization; using Microsoft.VisualStudio.LanguageServer.Protocol; namespace Microsoft.CodeAnalysis.Razor.Protocol.Formatting; internal class RazorDocumentFormattingResponse { + [JsonPropertyName("edits")] public TextEdit[]? Edits { get; set; } } diff --git a/src/Razor/src/Microsoft.CodeAnalysis.Razor.Workspaces/Protocol/Formatting/RazorDocumentOnTypeFormattingParams.cs b/src/Razor/src/Microsoft.CodeAnalysis.Razor.Workspaces/Protocol/Formatting/RazorDocumentOnTypeFormattingParams.cs index a97366be186..818c49d9197 100644 --- a/src/Razor/src/Microsoft.CodeAnalysis.Razor.Workspaces/Protocol/Formatting/RazorDocumentOnTypeFormattingParams.cs +++ b/src/Razor/src/Microsoft.CodeAnalysis.Razor.Workspaces/Protocol/Formatting/RazorDocumentOnTypeFormattingParams.cs @@ -1,14 +1,13 @@ // Copyright (c) .NET Foundation. All rights reserved. // Licensed under the MIT license. See License.txt in the project root for license information. -using System.Runtime.Serialization; +using System.Text.Json.Serialization; using Microsoft.VisualStudio.LanguageServer.Protocol; namespace Microsoft.CodeAnalysis.Razor.Protocol.Formatting; -[DataContract] internal class RazorDocumentOnTypeFormattingParams : DocumentOnTypeFormattingParams { - [DataMember(Name = "hostDocumentVersion")] + [JsonPropertyName("hostDocumentVersion")] public int HostDocumentVersion { get; init; } } diff --git a/src/Razor/src/Microsoft.CodeAnalysis.Razor.Workspaces/Protocol/JsonHelpers.cs b/src/Razor/src/Microsoft.CodeAnalysis.Razor.Workspaces/Protocol/JsonHelpers.cs index e3a8b319739..6bca8850e25 100644 --- a/src/Razor/src/Microsoft.CodeAnalysis.Razor.Workspaces/Protocol/JsonHelpers.cs +++ b/src/Razor/src/Microsoft.CodeAnalysis.Razor.Workspaces/Protocol/JsonHelpers.cs @@ -8,32 +8,31 @@ namespace Microsoft.CodeAnalysis.Razor.Protocol; internal static class JsonHelpers { - private const string s_convertedFlag = "__convertedFromJsonElement"; + private const string s_convertedFlag = "__convertedFromJObject"; /// - /// Normalizes data from JsonElement to JObject as thats what we expect to process + /// Normalizes data from JObject to JsonElement as thats what we expect to process /// - internal static object? TryConvertFromJsonElement(object? data) + internal static object? TryConvertFromJObject(object? data) { - if (data is JsonElement element) + if (data is JObject jObject) { - var jObject = JObject.Parse(element.GetRawText()); jObject[s_convertedFlag] = true; - return jObject; + return JsonDocument.Parse(jObject.ToString()).RootElement; } return data; } /// - /// Converts from JObject back to JsonElement, but only if the original conversion was done with + /// Converts from JObject back to JsonElement, but only if the original conversion was done with /// - internal static object? TryConvertBackToJsonElement(object? data) + internal static object? TryConvertBackToJObject(object? data) { - if (data is JObject jObject && - jObject.ContainsKey(s_convertedFlag)) + if (data is JsonElement jsonElement && + jsonElement.TryGetProperty(s_convertedFlag, out _)) { - return JsonDocument.Parse(jObject.ToString()).RootElement; + data = JObject.Parse(jsonElement.ToString()); } return data; diff --git a/src/Razor/src/Microsoft.CodeAnalysis.Razor.Workspaces/Protocol/RazorTextChange.cs b/src/Razor/src/Microsoft.CodeAnalysis.Razor.Workspaces/Protocol/RazorTextChange.cs new file mode 100644 index 00000000000..6774d811ed1 --- /dev/null +++ b/src/Razor/src/Microsoft.CodeAnalysis.Razor.Workspaces/Protocol/RazorTextChange.cs @@ -0,0 +1,19 @@ +// Copyright (c) .NET Foundation. All rights reserved. +// Licensed under the MIT license. See License.txt in the project root for license information. + +using System.Text.Json.Serialization; + +namespace Microsoft.CodeAnalysis.Razor.Protocol; + +/// +/// A representation of a Roslyn TextChange that can be serialized with System.Text.Json. Also needs to match +/// https://github.com/dotnet/vscode-csharp/blob/main/src/razor/src/rpc/serverTextChange.ts for VS Code. +/// +internal sealed record RazorTextChange +{ + [JsonPropertyName("span")] + public required RazorTextSpan Span { get; set; } + + [JsonPropertyName("newText")] + public string? NewText { get; set; } +} diff --git a/src/Razor/src/Microsoft.CodeAnalysis.Razor.Workspaces/Protocol/RazorTextSpan.cs b/src/Razor/src/Microsoft.CodeAnalysis.Razor.Workspaces/Protocol/RazorTextSpan.cs new file mode 100644 index 00000000000..afe209d1a99 --- /dev/null +++ b/src/Razor/src/Microsoft.CodeAnalysis.Razor.Workspaces/Protocol/RazorTextSpan.cs @@ -0,0 +1,19 @@ +// Copyright (c) .NET Foundation. All rights reserved. +// Licensed under the MIT license. See License.txt in the project root for license information. + +using System.Text.Json.Serialization; + +namespace Microsoft.CodeAnalysis.Razor.Protocol; + +/// +/// A representation of a Roslyn TextSpan that can be serialized with System.Text.Json. Also needs to match +/// https://github.com/dotnet/vscode-csharp/blob/main/src/razor/src/rpc/serverTextSpan.ts for VS Code. +/// +internal sealed record RazorTextSpan +{ + [JsonPropertyName("start")] + public int Start { get; set; } + + [JsonPropertyName("length")] + public int Length { get; set; } +} diff --git a/src/Razor/src/Microsoft.CodeAnalysis.Razor.Workspaces/Protocol/SemanticTokens/ProvideSemanticTokensRangesParams.cs b/src/Razor/src/Microsoft.CodeAnalysis.Razor.Workspaces/Protocol/SemanticTokens/ProvideSemanticTokensRangesParams.cs index e579bf31f56..814842e39c5 100644 --- a/src/Razor/src/Microsoft.CodeAnalysis.Razor.Workspaces/Protocol/SemanticTokens/ProvideSemanticTokensRangesParams.cs +++ b/src/Razor/src/Microsoft.CodeAnalysis.Razor.Workspaces/Protocol/SemanticTokens/ProvideSemanticTokensRangesParams.cs @@ -2,20 +2,20 @@ // Licensed under the MIT license. See License.txt in the project root for license information. using System; -using System.Runtime.Serialization; +using System.Text.Json.Serialization; using Microsoft.VisualStudio.LanguageServer.Protocol; namespace Microsoft.CodeAnalysis.Razor.Workspaces.Protocol.SemanticTokens; internal class ProvideSemanticTokensRangesParams : SemanticTokensParams { - [DataMember(Name = "requiredHostDocumentVersion", IsRequired = true)] + [JsonPropertyName("requiredHostDocumentVersion")] public long RequiredHostDocumentVersion { get; } - [DataMember(Name = "ranges", IsRequired = true)] + [JsonPropertyName("ranges")] public Range[] Ranges { get; } - [DataMember(Name = "correlationId", IsRequired = true)] + [JsonPropertyName("correlationId")] public Guid CorrelationId { get; } public ProvideSemanticTokensRangesParams(TextDocumentIdentifier textDocument, long requiredHostDocumentVersion, Range[] ranges, Guid correlationId) diff --git a/src/Razor/src/Microsoft.CodeAnalysis.Razor.Workspaces/Protocol/SemanticTokens/ProvideSemanticTokensResponse.cs b/src/Razor/src/Microsoft.CodeAnalysis.Razor.Workspaces/Protocol/SemanticTokens/ProvideSemanticTokensResponse.cs index 883dc1fd613..a8928a587fe 100644 --- a/src/Razor/src/Microsoft.CodeAnalysis.Razor.Workspaces/Protocol/SemanticTokens/ProvideSemanticTokensResponse.cs +++ b/src/Razor/src/Microsoft.CodeAnalysis.Razor.Workspaces/Protocol/SemanticTokens/ProvideSemanticTokensResponse.cs @@ -1,6 +1,8 @@ // Copyright (c) .NET Foundation. All rights reserved. // Licensed under the MIT license. See License.txt in the project root for license information. +using System.Text.Json.Serialization; + namespace Microsoft.CodeAnalysis.Razor.Workspaces.Protocol.SemanticTokens; /// @@ -14,7 +16,9 @@ public ProvideSemanticTokensResponse(int[]? tokens, long hostDocumentSyncVersion HostDocumentSyncVersion = hostDocumentSyncVersion; } + [JsonPropertyName("tokens")] public int[]? Tokens { get; } + [JsonPropertyName("hostDocumentSyncVersion")] public long HostDocumentSyncVersion { get; } } diff --git a/src/Razor/src/Microsoft.CodeAnalysis.Razor.Workspaces/Protocol/SemanticTokens/SemanticTokensRangesParams.cs b/src/Razor/src/Microsoft.CodeAnalysis.Razor.Workspaces/Protocol/SemanticTokens/SemanticTokensRangesParams.cs index c185b35cef1..10864b93015 100644 --- a/src/Razor/src/Microsoft.CodeAnalysis.Razor.Workspaces/Protocol/SemanticTokens/SemanticTokensRangesParams.cs +++ b/src/Razor/src/Microsoft.CodeAnalysis.Razor.Workspaces/Protocol/SemanticTokens/SemanticTokensRangesParams.cs @@ -1,14 +1,13 @@ // Copyright (c) .NET Foundation. All rights reserved. // Licensed under the MIT license. See License.txt in the project root for license information. -using System.Runtime.Serialization; +using System.Text.Json.Serialization; using Microsoft.VisualStudio.LanguageServer.Protocol; namespace Microsoft.CodeAnalysis.Razor.Workspaces.Protocol.SemanticTokens; -[DataContract] internal class SemanticTokensRangesParams : SemanticTokensParams { - [DataMember(Name = "ranges")] + [JsonPropertyName("ranges")] public required Range[] Ranges { get; set; } } diff --git a/src/Razor/src/Microsoft.CodeAnalysis.Razor.Workspaces/Protocol/TextDocumentIdentifierAndVersion.cs b/src/Razor/src/Microsoft.CodeAnalysis.Razor.Workspaces/Protocol/TextDocumentIdentifierAndVersion.cs index 5c18234be8a..90156f1ab1d 100644 --- a/src/Razor/src/Microsoft.CodeAnalysis.Razor.Workspaces/Protocol/TextDocumentIdentifierAndVersion.cs +++ b/src/Razor/src/Microsoft.CodeAnalysis.Razor.Workspaces/Protocol/TextDocumentIdentifierAndVersion.cs @@ -1,6 +1,7 @@ // Copyright (c) .NET Foundation. All rights reserved. // Licensed under the MIT license. See License.txt in the project root for license information. +using System.Text.Json.Serialization; using Microsoft.VisualStudio.LanguageServer.Protocol; namespace Microsoft.CodeAnalysis.Razor.Protocol; @@ -11,4 +12,6 @@ namespace Microsoft.CodeAnalysis.Razor.Protocol; /// and deserializing that class, if the is a /// it will lose the project context information. /// -internal record class TextDocumentIdentifierAndVersion(TextDocumentIdentifier TextDocumentIdentifier, int Version); +internal record class TextDocumentIdentifierAndVersion( + [property:JsonPropertyName("textDocumentIdentifier")] TextDocumentIdentifier TextDocumentIdentifier, + [property:JsonPropertyName("version")] int Version); diff --git a/src/Razor/src/Microsoft.CodeAnalysis.Razor.Workspaces/Protocol/UpdateBufferRequest.cs b/src/Razor/src/Microsoft.CodeAnalysis.Razor.Workspaces/Protocol/UpdateBufferRequest.cs new file mode 100644 index 00000000000..912fa684e31 --- /dev/null +++ b/src/Razor/src/Microsoft.CodeAnalysis.Razor.Workspaces/Protocol/UpdateBufferRequest.cs @@ -0,0 +1,24 @@ +// Copyright (c) .NET Foundation. All rights reserved. +// Licensed under the MIT license. See License.txt in the project root for license information. + +using System.Text.Json.Serialization; + +namespace Microsoft.CodeAnalysis.Razor.Protocol; + +internal sealed class UpdateBufferRequest +{ + [JsonPropertyName("hostDocumentVersion")] + public int? HostDocumentVersion { get; set; } + + [JsonPropertyName("projectKeyId")] + public string? ProjectKeyId { get; set; } + + [JsonPropertyName("hostDocumentFilePath")] + public string? HostDocumentFilePath { get; set; } + + [JsonPropertyName("changes")] + public required RazorTextChange[] Changes { get; set; } + + [JsonPropertyName("previousWasEmpty")] + public bool PreviousWasEmpty { get; set; } +} diff --git a/src/Razor/src/Microsoft.CodeAnalysis.Razor.Workspaces/Serialization/RazorUriJsonConverter.cs b/src/Razor/src/Microsoft.CodeAnalysis.Razor.Workspaces/Serialization/RazorUriJsonConverter.cs deleted file mode 100644 index e9794b5d778..00000000000 --- a/src/Razor/src/Microsoft.CodeAnalysis.Razor.Workspaces/Serialization/RazorUriJsonConverter.cs +++ /dev/null @@ -1,26 +0,0 @@ -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT license. See License.txt in the project root for license information. - -using System; -using Microsoft.VisualStudio.LanguageServer.Protocol; - -namespace Microsoft.CodeAnalysis.Razor.Workspaces.Serialization; - -/// -/// To workaround https://github.com/JamesNK/Newtonsoft.Json/issues/2128 we need to provide a Uri converter. -/// The LSP client has one, but it is not hooked up automatically and doesn't implement CanConvert, but we can -/// just do that on their behalf. -/// -internal class RazorUriJsonConverter : DocumentUriConverter -{ - public static readonly RazorUriJsonConverter Instance = new RazorUriJsonConverter(); - - private RazorUriJsonConverter() - { - } - - public override bool CanConvert(Type objectType) - { - return typeof(Uri).IsAssignableFrom(objectType); - } -} diff --git a/src/Razor/src/Microsoft.VisualStudio.LanguageServer.ContainedLanguage/DefaultFallbackCapabilitiesFilterResolver.cs b/src/Razor/src/Microsoft.VisualStudio.LanguageServer.ContainedLanguage/DefaultFallbackCapabilitiesFilterResolver.cs deleted file mode 100644 index 15b1525665e..00000000000 --- a/src/Razor/src/Microsoft.VisualStudio.LanguageServer.ContainedLanguage/DefaultFallbackCapabilitiesFilterResolver.cs +++ /dev/null @@ -1,288 +0,0 @@ -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT license. See License.txt in the project root for license information. - -using System; -using System.ComponentModel.Composition; -using Microsoft.VisualStudio.LanguageServer.Protocol; -using Newtonsoft.Json.Linq; - -namespace Microsoft.VisualStudio.LanguageServer.ContainedLanguage; - -[Export(typeof(FallbackCapabilitiesFilterResolver))] -internal class DefaultFallbackCapabilitiesFilterResolver : FallbackCapabilitiesFilterResolver -{ - public override Func Resolve(string lspRequestMethodName) - { - if (lspRequestMethodName is null) - { - throw new ArgumentNullException(nameof(lspRequestMethodName)); - } - - return lspRequestMethodName switch - { - // Standard LSP capabilities - Methods.TextDocumentImplementationName => CheckImplementationCapabilities, - Methods.TextDocumentTypeDefinitionName => CheckTypeDefinitionCapabilities, - Methods.TextDocumentReferencesName => CheckFindAllReferencesCapabilities, - Methods.TextDocumentRenameName => CheckRenameCapabilities, - Methods.TextDocumentSignatureHelpName => CheckSignatureHelpCapabilities, - Methods.TextDocumentWillSaveName => CheckWillSaveCapabilities, - Methods.TextDocumentWillSaveWaitUntilName => CheckWillSaveWaitUntilCapabilities, - Methods.TextDocumentRangeFormattingName => CheckRangeFormattingCapabilities, - Methods.WorkspaceSymbolName => CheckWorkspaceSymbolCapabilities, - Methods.TextDocumentOnTypeFormattingName => CheckOnTypeFormattingCapabilities, - Methods.TextDocumentFormattingName => CheckFormattingCapabilities, - Methods.TextDocumentHoverName => CheckHoverCapabilities, - Methods.TextDocumentCodeActionName => CheckCodeActionCapabilities, - Methods.TextDocumentCodeLensName => CheckCodeLensCapabilities, - Methods.TextDocumentCompletionName => CheckCompletionCapabilities, - Methods.TextDocumentCompletionResolveName => CheckCompletionResolveCapabilities, - Methods.TextDocumentDefinitionName => CheckDefinitionCapabilities, - Methods.TextDocumentDocumentHighlightName => CheckHighlightCapabilities, - "textDocument/semanticTokens" or Methods.TextDocumentSemanticTokensFullName or Methods.TextDocumentSemanticTokensFullDeltaName or Methods.TextDocumentSemanticTokensRangeName => CheckSemanticTokensCapabilities, - Methods.TextDocumentLinkedEditingRangeName => CheckLinkedEditingRangeCapabilities, - Methods.CodeActionResolveName => CheckCodeActionResolveCapabilities, - Methods.TextDocumentDocumentColorName => CheckDocumentColorCapabilities, - // VS LSP Expansion capabilities - VSMethods.GetProjectContextsName => CheckProjectContextsCapabilities, - VSInternalMethods.DocumentReferencesName => CheckMSReferencesCapabilities, - VSInternalMethods.OnAutoInsertName => CheckOnAutoInsertCapabilities, - VSInternalMethods.DocumentPullDiagnosticName or VSInternalMethods.WorkspacePullDiagnosticName => CheckPullDiagnosticCapabilities, - VSInternalMethods.TextDocumentTextPresentationName => CheckTextPresentationCapabilities, - VSInternalMethods.TextDocumentUriPresentationName => CheckUriPresentationCapabilities, - _ => FallbackCheckCapabilties, - }; - } - - private bool CheckDocumentColorCapabilities(JToken token) - { - var serverCapabilities = token.ToObject(); - - return serverCapabilities?.DocumentColorProvider?.Match( - boolValue => boolValue, - options => options is not null) ?? false; - } - - private static bool CheckSemanticTokensCapabilities(JToken token) - { - var serverCapabilities = token.ToObject(); - - return serverCapabilities?.SemanticTokensOptions is not null; - } - - private static bool CheckImplementationCapabilities(JToken token) - { - var serverCapabilities = token.ToObject(); - - return serverCapabilities?.ImplementationProvider?.Match( - boolValue => boolValue, - options => options is not null) ?? false; - } - - private bool CheckTypeDefinitionCapabilities(JToken token) - { - var serverCapabilities = token.ToObject(); - - return serverCapabilities?.TypeDefinitionProvider?.Match( - boolValue => boolValue, - options => options is not null) ?? false; - } - - private static bool CheckFindAllReferencesCapabilities(JToken token) - { - var serverCapabilities = token.ToObject(); - - return serverCapabilities?.ReferencesProvider?.Match( - boolValue => boolValue, - options => options is not null) ?? false; - } - - private static bool CheckRenameCapabilities(JToken token) - { - var serverCapabilities = token.ToObject(); - - return serverCapabilities?.RenameProvider?.Match( - boolValue => boolValue, - options => options is not null) ?? false; - } - - private static bool CheckSignatureHelpCapabilities(JToken token) - { - var serverCapabilities = token.ToObject(); - - return serverCapabilities?.SignatureHelpProvider is not null; - } - - private static bool CheckWillSaveCapabilities(JToken token) - { - var serverCapabilities = token.ToObject(); - - return serverCapabilities?.TextDocumentSync?.WillSave == true; - } - - private static bool CheckWillSaveWaitUntilCapabilities(JToken token) - { - var serverCapabilities = token.ToObject(); - - return serverCapabilities?.TextDocumentSync?.WillSaveWaitUntil == true; - } - - private static bool CheckRangeFormattingCapabilities(JToken token) - { - var serverCapabilities = token.ToObject(); - - return serverCapabilities?.DocumentRangeFormattingProvider?.Match( - boolValue => boolValue, - options => options is not null) ?? false; - } - - private static bool CheckWorkspaceSymbolCapabilities(JToken token) - { - var serverCapabilities = token.ToObject(); - - return serverCapabilities?.WorkspaceSymbolProvider?.Match( - boolValue => boolValue, - options => options is not null) ?? false; - } - - private static bool CheckOnTypeFormattingCapabilities(JToken token) - { - var serverCapabilities = token.ToObject(); - - return serverCapabilities?.DocumentOnTypeFormattingProvider is not null; - } - - private static bool CheckFormattingCapabilities(JToken token) - { - var serverCapabilities = token.ToObject(); - - return serverCapabilities?.DocumentFormattingProvider?.Match( - boolValue => boolValue, - options => options is not null) ?? false; - } - - private static bool CheckHoverCapabilities(JToken token) - { - var serverCapabilities = token.ToObject(); - - return serverCapabilities?.HoverProvider?.Match( - boolValue => boolValue, - options => options is not null) ?? false; - } - - private static bool CheckCodeActionCapabilities(JToken token) - { - var serverCapabilities = token.ToObject(); - - return serverCapabilities?.CodeActionProvider?.Match( - boolValue => boolValue, - options => options is not null) ?? false; - } - - private static bool CheckCodeLensCapabilities(JToken token) - { - var serverCapabilities = token.ToObject(); - - return serverCapabilities?.CodeLensProvider is not null; - } - - private static bool CheckCompletionCapabilities(JToken token) - { - var serverCapabilities = token.ToObject(); - - return serverCapabilities?.CompletionProvider is not null; - } - - private static bool CheckCompletionResolveCapabilities(JToken token) - { - var serverCapabilities = token.ToObject(); - - return serverCapabilities?.CompletionProvider?.ResolveProvider == true; - } - - private static bool CheckDefinitionCapabilities(JToken token) - { - var serverCapabilities = token.ToObject(); - - return serverCapabilities?.DefinitionProvider?.Match( - boolValue => boolValue, - options => options is not null) ?? false; - } - - private static bool CheckHighlightCapabilities(JToken token) - { - var serverCapabilities = token.ToObject(); - - return serverCapabilities?.DocumentHighlightProvider?.Match( - boolValue => boolValue, - options => options is not null) ?? false; - } - - private static bool CheckMSReferencesCapabilities(JToken token) - { - var serverCapabilities = token.ToObject(); - - return serverCapabilities?.MSReferencesProvider == true; - } - - private static bool CheckProjectContextsCapabilities(JToken token) - { - var serverCapabilities = token.ToObject(); - - return serverCapabilities?.ProjectContextProvider == true; - } - - private static bool CheckCodeActionResolveCapabilities(JToken token) - { - var serverCapabilities = token.ToObject(); - - var resolvesCodeActions = serverCapabilities?.CodeActionProvider?.Match( - boolValue => false, - options => options.ResolveProvider) ?? false; - - return resolvesCodeActions; - } - - private static bool CheckOnAutoInsertCapabilities(JToken token) - { - var serverCapabilities = token.ToObject(); - - return serverCapabilities?.OnAutoInsertProvider is not null; - } - - private static bool CheckTextPresentationCapabilities(JToken token) - { - var serverCapabilities = token.ToObject(); - - return serverCapabilities?.TextPresentationProvider == true; - } - private static bool CheckUriPresentationCapabilities(JToken token) - { - var serverCapabilities = token.ToObject(); - - return serverCapabilities?.UriPresentationProvider == true; - } - - private static bool CheckLinkedEditingRangeCapabilities(JToken token) - { - var serverCapabilities = token.ToObject(); - - return serverCapabilities?.LinkedEditingRangeProvider?.Match( - boolValue => boolValue, - options => options is not null) ?? false; - } - - private static bool CheckPullDiagnosticCapabilities(JToken token) - { - var serverCapabilities = token.ToObject(); - - return serverCapabilities?.SupportsDiagnosticRequests == true; - } - - private bool FallbackCheckCapabilties(JToken token) - { - // Fallback is to assume present - - return true; - } -} diff --git a/src/Razor/src/Microsoft.VisualStudio.LanguageServer.ContainedLanguage/DefaultLSPRequestInvoker.cs b/src/Razor/src/Microsoft.VisualStudio.LanguageServer.ContainedLanguage/DefaultLSPRequestInvoker.cs index e65a311c0b2..57d2748e1bd 100644 --- a/src/Razor/src/Microsoft.VisualStudio.LanguageServer.ContainedLanguage/DefaultLSPRequestInvoker.cs +++ b/src/Razor/src/Microsoft.VisualStudio.LanguageServer.ContainedLanguage/DefaultLSPRequestInvoker.cs @@ -9,9 +9,7 @@ using System.Threading.Tasks; using Microsoft.AspNetCore.Razor.PooledObjects; using Microsoft.VisualStudio.LanguageServer.Client; -using Microsoft.VisualStudio.LanguageServer.Protocol; using Microsoft.VisualStudio.Text; -using Newtonsoft.Json; using Newtonsoft.Json.Linq; namespace Microsoft.VisualStudio.LanguageServer.ContainedLanguage; @@ -21,30 +19,16 @@ namespace Microsoft.VisualStudio.LanguageServer.ContainedLanguage; internal class DefaultLSPRequestInvoker : LSPRequestInvoker { private readonly ILanguageServiceBroker2 _languageServiceBroker; - private readonly FallbackCapabilitiesFilterResolver _fallbackCapabilitiesFilterResolver; - private readonly JsonSerializer _serializer; [ImportingConstructor] - public DefaultLSPRequestInvoker( - ILanguageServiceBroker2 languageServiceBroker, - FallbackCapabilitiesFilterResolver fallbackCapabilitiesFilterResolver) + public DefaultLSPRequestInvoker(ILanguageServiceBroker2 languageServiceBroker) { if (languageServiceBroker is null) { throw new ArgumentNullException(nameof(languageServiceBroker)); } - if (fallbackCapabilitiesFilterResolver is null) - { - throw new ArgumentNullException(nameof(fallbackCapabilitiesFilterResolver)); - } - _languageServiceBroker = languageServiceBroker; - _fallbackCapabilitiesFilterResolver = fallbackCapabilitiesFilterResolver; - - // We need these converters so we don't lose information as part of the deserialization. - _serializer = new JsonSerializer(); - _serializer.AddVSInternalExtensionConverters(); } [Obsolete] @@ -59,22 +43,11 @@ public override Task>> ReinvokeRequestOnMulti return RequestMultipleServerCoreAsync(method, parameters, cancellationToken); } - public override Task> ReinvokeRequestOnServerAsync( + public async override Task> ReinvokeRequestOnServerAsync( string method, string languageServerName, TIn parameters, CancellationToken cancellationToken) - { - var capabilitiesFilter = _fallbackCapabilitiesFilterResolver.Resolve(method); - return ReinvokeRequestOnServerAsync(method, languageServerName, capabilitiesFilter, parameters, cancellationToken); - } - - public override async Task> ReinvokeRequestOnServerAsync( - string method, - string languageServerName, - Func capabilitiesFilter, - TIn parameters, - CancellationToken cancellationToken) { if (string.IsNullOrEmpty(method)) { @@ -90,19 +63,18 @@ public override async Task> ReinvokeRequestOnServerAsync< return result; } - public override Task?> ReinvokeRequestOnServerAsync(ITextBuffer textBuffer, string method, string languageServerName, TIn parameters, CancellationToken cancellationToken) - { - var capabilitiesFilter = _fallbackCapabilitiesFilterResolver.Resolve(method); - return ReinvokeRequestOnServerAsync(textBuffer, method, languageServerName, capabilitiesFilter, parameters, cancellationToken); - } - - public override async Task?> ReinvokeRequestOnServerAsync( - ITextBuffer textBuffer, + [Obsolete] + public override Task> ReinvokeRequestOnServerAsync( string method, string languageServerName, Func capabilitiesFilter, TIn parameters, CancellationToken cancellationToken) + { + return ReinvokeRequestOnServerAsync(method, languageServerName, parameters, cancellationToken); + } + + public override async Task?> ReinvokeRequestOnServerAsync(ITextBuffer textBuffer, string method, string languageServerName, TIn parameters, CancellationToken cancellationToken) { var response = await _languageServiceBroker.RequestAsync( new DocumentRequest() @@ -123,6 +95,18 @@ public override async Task> ReinvokeRequestOnServerAsync< return reinvocationResponse; } + [Obsolete] + public override Task?> ReinvokeRequestOnServerAsync( + ITextBuffer textBuffer, + string method, + string languageServerName, + Func capabilitiesFilter, + TIn parameters, + CancellationToken cancellationToken) + { + return ReinvokeRequestOnServerAsync(textBuffer, method, languageServerName, parameters, cancellationToken); + } + private async Task>> RequestMultipleServerCoreAsync(string method, TIn parameters, CancellationToken cancellationToken) where TIn : notnull { @@ -145,20 +129,20 @@ private async Task>> RequestMultipleServerCor return responses.ToArray(); } + [Obsolete("New callers should use a method that doesn't have a capabilities filter")] public override IAsyncEnumerable> ReinvokeRequestOnMultipleServersAsync( ITextBuffer textBuffer, string method, + Func capabilitiesFilter, TIn parameters, CancellationToken cancellationToken) { - var capabilitiesFilter = _fallbackCapabilitiesFilterResolver.Resolve(method); - return ReinvokeRequestOnMultipleServersAsync(textBuffer, method, capabilitiesFilter, parameters, cancellationToken); + return ReinvokeRequestOnMultipleServersAsync(textBuffer, method, parameters, cancellationToken); } public override async IAsyncEnumerable> ReinvokeRequestOnMultipleServersAsync( ITextBuffer textBuffer, string method, - Func capabilitiesFilter, TIn parameters, [EnumeratorCancellation] CancellationToken cancellationToken) { diff --git a/src/Razor/src/Microsoft.VisualStudio.LanguageServer.ContainedLanguage/FallbackCapabilitiesFilterResolver.cs b/src/Razor/src/Microsoft.VisualStudio.LanguageServer.ContainedLanguage/FallbackCapabilitiesFilterResolver.cs deleted file mode 100644 index a82e39f8a3e..00000000000 --- a/src/Razor/src/Microsoft.VisualStudio.LanguageServer.ContainedLanguage/FallbackCapabilitiesFilterResolver.cs +++ /dev/null @@ -1,12 +0,0 @@ -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT license. See License.txt in the project root for license information. - -using System; -using Newtonsoft.Json.Linq; - -namespace Microsoft.VisualStudio.LanguageServer.ContainedLanguage; - -internal abstract class FallbackCapabilitiesFilterResolver -{ - public abstract Func Resolve(string lspRequestMethodName); -} diff --git a/src/Razor/src/Microsoft.VisualStudio.LanguageServer.ContainedLanguage/InternalAPI.Unshipped.txt b/src/Razor/src/Microsoft.VisualStudio.LanguageServer.ContainedLanguage/InternalAPI.Unshipped.txt index f84890fe7c1..36eda715446 100644 --- a/src/Razor/src/Microsoft.VisualStudio.LanguageServer.ContainedLanguage/InternalAPI.Unshipped.txt +++ b/src/Razor/src/Microsoft.VisualStudio.LanguageServer.ContainedLanguage/InternalAPI.Unshipped.txt @@ -1,6 +1,7 @@ #nullable enable Microsoft.VisualStudio.LanguageServer.ContainedLanguage.DefaultLSPDocumentSynchronizer.SynchronizedResult.Deconstruct(out bool Synchronized, out TVirtualDocumentSnapshot? VirtualSnapshot) -> void Microsoft.VisualStudio.LanguageServer.ContainedLanguage.DefaultLSPDocumentSynchronizer.TryReturnPossiblyFutureSnapshot(int requiredHostDocumentVersion, System.Uri! hostDocumentUri, System.Uri? specificVirtualDocumentUri) -> Microsoft.VisualStudio.LanguageServer.ContainedLanguage.DefaultLSPDocumentSynchronizer.SynchronizedResult? +Microsoft.VisualStudio.LanguageServer.ContainedLanguage.DefaultLSPRequestInvoker.DefaultLSPRequestInvoker(Microsoft.VisualStudio.LanguageServer.Client.ILanguageServiceBroker2! languageServiceBroker) -> void Microsoft.VisualStudio.LanguageServer.ContainedLanguage.LSPDocumentSnapshot.TryGetAllVirtualDocumentsAsArray(out System.Collections.Immutable.ImmutableArray virtualDocuments) -> bool Microsoft.VisualStudio.LanguageServer.ContainedLanguage.MessageInterception.DefaultInterceptorManager.DefaultInterceptorManager(System.Collections.Generic.IEnumerable!>! lazyInterceptors, System.Collections.Generic.IEnumerable!>! lazyGenericInterceptors) -> void override Microsoft.VisualStudio.LanguageServer.ContainedLanguage.DefaultLSPDocument.SetVirtualDocuments(System.Collections.Generic.IReadOnlyList! virtualDocuments) -> void diff --git a/src/Razor/src/Microsoft.VisualStudio.LanguageServer.ContainedLanguage/LSPRequestInvoker.cs b/src/Razor/src/Microsoft.VisualStudio.LanguageServer.ContainedLanguage/LSPRequestInvoker.cs index 4d66216ece4..8ab4630d744 100644 --- a/src/Razor/src/Microsoft.VisualStudio.LanguageServer.ContainedLanguage/LSPRequestInvoker.cs +++ b/src/Razor/src/Microsoft.VisualStudio.LanguageServer.ContainedLanguage/LSPRequestInvoker.cs @@ -42,6 +42,7 @@ public abstract Task> ReinvokeRequestOnServerAsync /// /// When operating on a document the overload should be used, since it guarantees ordering. + [Obsolete("Use the overload that doesn't take a capability filter")] public abstract Task> ReinvokeRequestOnServerAsync( string method, string languageServerName, @@ -58,6 +59,7 @@ public abstract Task> ReinvokeRequestOnServerAsync?> ReinvokeRequestOnServerAsync( ITextBuffer textBuffer, string method, @@ -114,6 +116,7 @@ public abstract IAsyncEnumerable> ReinvokeRequestOnMu CancellationToken cancellationToken) where TIn : notnull; + [Obsolete("New callers should use a method that doesn't have a capabilities filter")] public abstract IAsyncEnumerable> ReinvokeRequestOnMultipleServersAsync( ITextBuffer textBuffer, string method, diff --git a/src/Razor/src/Microsoft.VisualStudio.LanguageServices.Razor/LanguageClient/Cohost/CohostSemanticTokensRangeEndpoint.cs b/src/Razor/src/Microsoft.VisualStudio.LanguageServices.Razor/LanguageClient/Cohost/CohostSemanticTokensRangeEndpoint.cs index d7b676cffe9..d59809ccb74 100644 --- a/src/Razor/src/Microsoft.VisualStudio.LanguageServices.Razor/LanguageClient/Cohost/CohostSemanticTokensRangeEndpoint.cs +++ b/src/Razor/src/Microsoft.VisualStudio.LanguageServices.Razor/LanguageClient/Cohost/CohostSemanticTokensRangeEndpoint.cs @@ -3,6 +3,7 @@ using System; using System.Composition; +using System.Text.Json; using System.Threading; using System.Threading.Tasks; using Microsoft.AspNetCore.Razor; @@ -16,7 +17,6 @@ using Microsoft.VisualStudio.LanguageServer.Protocol; using Microsoft.VisualStudio.Razor.LanguageClient.Extensions; using Microsoft.VisualStudio.Razor.Settings; -using Newtonsoft.Json; namespace Microsoft.VisualStudio.Razor.LanguageClient.Cohost; @@ -49,7 +49,7 @@ internal sealed class CohostSemanticTokensRangeEndpoint( if (clientCapabilities.TextDocument?.SemanticTokens?.DynamicRegistration == true) { var semanticTokensRefreshQueue = requestContext.GetRequiredService(); - var clientCapabilitiesString = JsonConvert.SerializeObject(clientCapabilities); + var clientCapabilitiesString = JsonSerializer.Serialize(clientCapabilities); semanticTokensRefreshQueue.Initialize(clientCapabilitiesString); return new Registration() diff --git a/src/Razor/src/Microsoft.VisualStudio.LanguageServices.Razor/LanguageClient/Cohost/RazorCohostDynamicRegistrationService.cs b/src/Razor/src/Microsoft.VisualStudio.LanguageServices.Razor/LanguageClient/Cohost/RazorCohostDynamicRegistrationService.cs index 8c6e8068e68..5eab1db55f7 100644 --- a/src/Razor/src/Microsoft.VisualStudio.LanguageServices.Razor/LanguageClient/Cohost/RazorCohostDynamicRegistrationService.cs +++ b/src/Razor/src/Microsoft.VisualStudio.LanguageServices.Razor/LanguageClient/Cohost/RazorCohostDynamicRegistrationService.cs @@ -4,13 +4,13 @@ using System; using System.Collections.Generic; using System.Composition; +using System.Text.Json; using System.Threading; using System.Threading.Tasks; using Microsoft.AspNetCore.Razor.PooledObjects; using Microsoft.CodeAnalysis.ExternalAccess.Razor.Cohost; using Microsoft.CodeAnalysis.Razor.Workspaces; using Microsoft.VisualStudio.LanguageServer.Protocol; -using Newtonsoft.Json; namespace Microsoft.VisualStudio.Razor.LanguageClient.Cohost; @@ -44,7 +44,7 @@ public async Task RegisterAsync(string clientCapabilitiesString, RazorCohostRequ // TODO: Should we delay everything below this line until a Razor file is opened? - var clientCapabilities = JsonConvert.DeserializeObject(clientCapabilitiesString) ?? new(); + var clientCapabilities = JsonSerializer.Deserialize(clientCapabilitiesString) ?? new(); _lazyRazorCohostClientCapabilitiesService.Value.SetCapabilities(clientCapabilities); diff --git a/src/Razor/src/Microsoft.VisualStudio.LanguageServices.Razor/LanguageClient/Debugging/DefaultLSPBreakpointSpanProvider.cs b/src/Razor/src/Microsoft.VisualStudio.LanguageServices.Razor/LanguageClient/Debugging/DefaultLSPBreakpointSpanProvider.cs index 365fce8a898..89c8291df75 100644 --- a/src/Razor/src/Microsoft.VisualStudio.LanguageServices.Razor/LanguageClient/Debugging/DefaultLSPBreakpointSpanProvider.cs +++ b/src/Razor/src/Microsoft.VisualStudio.LanguageServices.Razor/LanguageClient/Debugging/DefaultLSPBreakpointSpanProvider.cs @@ -5,13 +5,11 @@ using System.ComponentModel.Composition; using System.Threading; using System.Threading.Tasks; -using Microsoft.AspNetCore.Razor.LanguageServer.Hosting; using Microsoft.CodeAnalysis.Razor.Logging; using Microsoft.CodeAnalysis.Razor.Protocol; using Microsoft.CodeAnalysis.Razor.Protocol.Debugging; using Microsoft.VisualStudio.LanguageServer.ContainedLanguage; using Microsoft.VisualStudio.LanguageServer.Protocol; -using Newtonsoft.Json.Linq; namespace Microsoft.VisualStudio.Razor.LanguageClient.Debugging; @@ -52,7 +50,6 @@ public DefaultLSPBreakpointSpanProvider( documentSnapshot.Snapshot.TextBuffer, LanguageServerConstants.RazorBreakpointSpanEndpoint, RazorLSPConstants.RazorLanguageServerName, - CheckRazorBreakpointSpanCapability, languageQueryParams, cancellationToken).ConfigureAwait(false); @@ -65,14 +62,4 @@ public DefaultLSPBreakpointSpanProvider( return languageResponse.Range; } - - private static bool CheckRazorBreakpointSpanCapability(JToken token) - { - if (!RazorLanguageServerCapability.TryGet(token, out var razorCapability)) - { - return false; - } - - return razorCapability.BreakpointSpan; - } } diff --git a/src/Razor/src/Microsoft.VisualStudio.LanguageServices.Razor/LanguageClient/Debugging/DefaultLSPProximityExpressionsProvider.cs b/src/Razor/src/Microsoft.VisualStudio.LanguageServices.Razor/LanguageClient/Debugging/DefaultLSPProximityExpressionsProvider.cs index b88757baec5..1452ca9f165 100644 --- a/src/Razor/src/Microsoft.VisualStudio.LanguageServices.Razor/LanguageClient/Debugging/DefaultLSPProximityExpressionsProvider.cs +++ b/src/Razor/src/Microsoft.VisualStudio.LanguageServices.Razor/LanguageClient/Debugging/DefaultLSPProximityExpressionsProvider.cs @@ -6,13 +6,11 @@ using System.ComponentModel.Composition; using System.Threading; using System.Threading.Tasks; -using Microsoft.AspNetCore.Razor.LanguageServer.Hosting; using Microsoft.CodeAnalysis.Razor.Logging; using Microsoft.CodeAnalysis.Razor.Protocol; using Microsoft.CodeAnalysis.Razor.Protocol.Debugging; using Microsoft.VisualStudio.LanguageServer.ContainedLanguage; using Microsoft.VisualStudio.LanguageServer.Protocol; -using Newtonsoft.Json.Linq; namespace Microsoft.VisualStudio.Razor.LanguageClient.Debugging; @@ -54,7 +52,6 @@ public DefaultLSPProximityExpressionsProvider( documentSnapshot.Snapshot.TextBuffer, LanguageServerConstants.RazorProximityExpressionsEndpoint, RazorLSPConstants.RazorLanguageServerName, - CheckRazorProximityExpressionsCapability, proximityExpressionsParams, cancellationToken).ConfigureAwait(false); @@ -67,14 +64,4 @@ public DefaultLSPProximityExpressionsProvider( return languageResponse.Expressions; } - - private static bool CheckRazorProximityExpressionsCapability(JToken token) - { - if (!RazorLanguageServerCapability.TryGet(token, out var razorCapability)) - { - return false; - } - - return razorCapability.ProximityExpressions; - } } diff --git a/src/Razor/src/Microsoft.VisualStudio.LanguageServices.Razor/LanguageClient/DocumentMapping/DefaultLSPDocumentMappingProvider.cs b/src/Razor/src/Microsoft.VisualStudio.LanguageServices.Razor/LanguageClient/DocumentMapping/DefaultLSPDocumentMappingProvider.cs index 243676250f8..2ace7bbf3a4 100644 --- a/src/Razor/src/Microsoft.VisualStudio.LanguageServices.Razor/LanguageClient/DocumentMapping/DefaultLSPDocumentMappingProvider.cs +++ b/src/Razor/src/Microsoft.VisualStudio.LanguageServices.Razor/LanguageClient/DocumentMapping/DefaultLSPDocumentMappingProvider.cs @@ -5,12 +5,10 @@ using System.ComponentModel.Composition; using System.Threading; using System.Threading.Tasks; -using Microsoft.AspNetCore.Razor.LanguageServer.Hosting; using Microsoft.CodeAnalysis.Razor.DocumentMapping; using Microsoft.CodeAnalysis.Razor.Protocol; using Microsoft.CodeAnalysis.Razor.Protocol.DocumentMapping; using Microsoft.VisualStudio.LanguageServer.ContainedLanguage; -using Newtonsoft.Json.Linq; namespace Microsoft.VisualStudio.Razor.LanguageClient.DocumentMapping; @@ -76,20 +74,9 @@ public DefaultLSPDocumentMappingProvider( documentSnapshot.Snapshot.TextBuffer, LanguageServerConstants.RazorMapToDocumentRangesEndpoint, RazorLSPConstants.RazorLanguageServerName, - CheckRazorRangeMappingCapability, mapToDocumentRangeParams, cancellationToken).ConfigureAwait(false); return documentMappingResponse?.Response; } - - private static bool CheckRazorRangeMappingCapability(JToken token) - { - if (!RazorLanguageServerCapability.TryGet(token, out var razorCapability)) - { - return false; - } - - return razorCapability.RangeMapping; - } } diff --git a/src/Razor/src/Microsoft.VisualStudio.LanguageServices.Razor/LanguageClient/Endpoints/RazorCustomMessageTarget_CodeActions.cs b/src/Razor/src/Microsoft.VisualStudio.LanguageServices.Razor/LanguageClient/Endpoints/RazorCustomMessageTarget_CodeActions.cs index 0471d843d0d..60384baa0af 100644 --- a/src/Razor/src/Microsoft.VisualStudio.LanguageServices.Razor/LanguageClient/Endpoints/RazorCustomMessageTarget_CodeActions.cs +++ b/src/Razor/src/Microsoft.VisualStudio.LanguageServices.Razor/LanguageClient/Endpoints/RazorCustomMessageTarget_CodeActions.cs @@ -11,7 +11,6 @@ using Microsoft.VisualStudio.LanguageServer.ContainedLanguage; using Microsoft.VisualStudio.LanguageServer.Protocol; using Microsoft.VisualStudio.Threading; -using Newtonsoft.Json.Linq; using StreamJsonRpc; namespace Microsoft.VisualStudio.Razor.LanguageClient.Endpoints; @@ -66,7 +65,6 @@ internal partial class RazorCustomMessageTarget var requests = _requestInvoker.ReinvokeRequestOnMultipleServersAsync>( textBuffer, lspMethodName, - SupportsCodeActionResolve, codeActionParams.CodeActionParams, cancellationToken).ConfigureAwait(false); @@ -82,7 +80,7 @@ internal partial class RazorCustomMessageTarget { foreach (var codeAction in response.Response) { - codeAction.Data = JsonHelpers.TryConvertFromJsonElement(codeAction.Data); + codeAction.Data = JsonHelpers.TryConvertFromJObject(codeAction.Data); codeActions.Add(codeAction); } } @@ -130,12 +128,11 @@ internal partial class RazorCustomMessageTarget var textBuffer = virtualDocumentSnapshot.Snapshot.TextBuffer; var codeAction = resolveCodeActionParams.CodeAction; - codeAction.Data = JsonHelpers.TryConvertBackToJsonElement(codeAction.Data); + codeAction.Data = JsonHelpers.TryConvertBackToJObject(codeAction.Data); var requests = _requestInvoker.ReinvokeRequestOnMultipleServersAsync( textBuffer, Methods.CodeActionResolveName, - SupportsCodeActionResolve, codeAction, cancellationToken).ConfigureAwait(false); @@ -145,7 +142,7 @@ internal partial class RazorCustomMessageTarget { // Only take the first response from a resolution var resolved = response.Response; - resolved.Data = JsonHelpers.TryConvertFromJsonElement(resolved.Data); + resolved.Data = JsonHelpers.TryConvertFromJObject(resolved.Data); return resolved; } @@ -153,15 +150,4 @@ internal partial class RazorCustomMessageTarget return null; } - - private static bool SupportsCodeActionResolve(JToken token) - { - var serverCapabilities = token.ToObject(); - - var (providesCodeActions, resolvesCodeActions) = serverCapabilities?.CodeActionProvider?.Match( - boolValue => (boolValue, false), - options => (true, options.ResolveProvider)) ?? (false, false); - - return providesCodeActions && resolvesCodeActions; - } } diff --git a/src/Razor/src/Microsoft.VisualStudio.LanguageServices.Razor/LanguageClient/Endpoints/RazorCustomMessageTarget_Completion.cs b/src/Razor/src/Microsoft.VisualStudio.LanguageServices.Razor/LanguageClient/Endpoints/RazorCustomMessageTarget_Completion.cs index db82f4b3aa6..fe14b8f494b 100644 --- a/src/Razor/src/Microsoft.VisualStudio.LanguageServices.Razor/LanguageClient/Endpoints/RazorCustomMessageTarget_Completion.cs +++ b/src/Razor/src/Microsoft.VisualStudio.LanguageServices.Razor/LanguageClient/Endpoints/RazorCustomMessageTarget_Completion.cs @@ -155,7 +155,7 @@ internal partial class RazorCustomMessageTarget AddSnippetCompletions(request, ref builder.AsRef()); completionList.Items = builder.ToArray(); - completionList.Data = JsonHelpers.TryConvertFromJsonElement(completionList.Data); + completionList.Data = JsonHelpers.TryConvertFromJObject(completionList.Data); ConvertJsonElementToJObject(completionList); return completionList; @@ -175,7 +175,7 @@ private void ConvertJsonElementToJObject(VSInternalCompletionList completionList { foreach (var item in completionList.Items) { - item.Data = JsonHelpers.TryConvertFromJsonElement(item.Data); + item.Data = JsonHelpers.TryConvertFromJObject(item.Data); } } @@ -298,7 +298,7 @@ private void UpdateVirtualDocument( var completionResolveParams = request.CompletionItem; - completionResolveParams.Data = JsonHelpers.TryConvertBackToJsonElement(completionResolveParams.Data); + completionResolveParams.Data = JsonHelpers.TryConvertBackToJObject(completionResolveParams.Data); var textBuffer = virtualDocumentSnapshot.Snapshot.TextBuffer; var response = await _requestInvoker.ReinvokeRequestOnServerAsync( @@ -311,7 +311,7 @@ private void UpdateVirtualDocument( var item = response?.Response; if (item is not null) { - item.Data = JsonHelpers.TryConvertFromJsonElement(item.Data); + item.Data = JsonHelpers.TryConvertFromJObject(item.Data); } return item; @@ -333,7 +333,7 @@ private void AddSnippetCompletions(DelegatedCompletionParams request, ref Pooled // Temporary fix: snippets are broken in CSharp. We're investigating // but this is very disruptive. This quick fix unblocks things. - // TODO: Add an option to enable this. + // TODO: Add an option to enable this. if (request.ProjectedKind != RazorLanguageKind.Html) { return; diff --git a/src/Razor/src/Microsoft.VisualStudio.LanguageServices.Razor/LanguageClient/Endpoints/RazorCustomMessageTarget_DocumentColor.cs b/src/Razor/src/Microsoft.VisualStudio.LanguageServices.Razor/LanguageClient/Endpoints/RazorCustomMessageTarget_DocumentColor.cs index 6982a880ed8..c43276e66bf 100644 --- a/src/Razor/src/Microsoft.VisualStudio.LanguageServices.Razor/LanguageClient/Endpoints/RazorCustomMessageTarget_DocumentColor.cs +++ b/src/Razor/src/Microsoft.VisualStudio.LanguageServices.Razor/LanguageClient/Endpoints/RazorCustomMessageTarget_DocumentColor.cs @@ -9,7 +9,6 @@ using Microsoft.CodeAnalysis.Razor.Protocol.ColorPresentation; using Microsoft.VisualStudio.LanguageServer.Protocol; using Microsoft.VisualStudio.Threading; -using Newtonsoft.Json.Linq; using StreamJsonRpc; namespace Microsoft.VisualStudio.Razor.LanguageClient.Endpoints; @@ -36,7 +35,6 @@ internal partial class RazorCustomMessageTarget var requests = _requestInvoker.ReinvokeRequestOnMultipleServersAsync( htmlTextBuffer, Methods.DocumentColorRequest.Name, - SupportsDocumentColor, documentColorParams, cancellationToken).ConfigureAwait(false); @@ -86,15 +84,4 @@ public async Task> ProvideHtmlColorPresentation return colorPresentation; } - - private static bool SupportsDocumentColor(JToken token) - { - var serverCapabilities = token.ToObject(); - - var supportsDocumentColor = serverCapabilities?.DocumentColorProvider?.Match( - boolValue => boolValue, - options => options != null) ?? false; - - return supportsDocumentColor; - } } diff --git a/src/Razor/src/Microsoft.VisualStudio.LanguageServices.Razor/LanguageClient/Endpoints/RazorCustomMessageTarget_FoldingRange.cs b/src/Razor/src/Microsoft.VisualStudio.LanguageServices.Razor/LanguageClient/Endpoints/RazorCustomMessageTarget_FoldingRange.cs index 58bfec4ca2f..a33e9ff4c83 100644 --- a/src/Razor/src/Microsoft.VisualStudio.LanguageServices.Razor/LanguageClient/Endpoints/RazorCustomMessageTarget_FoldingRange.cs +++ b/src/Razor/src/Microsoft.VisualStudio.LanguageServices.Razor/LanguageClient/Endpoints/RazorCustomMessageTarget_FoldingRange.cs @@ -11,7 +11,6 @@ using Microsoft.CodeAnalysis.Razor.Workspaces; using Microsoft.VisualStudio.LanguageServer.Protocol; using Microsoft.VisualStudio.Razor.LanguageClient.Extensions; -using Newtonsoft.Json.Linq; using StreamJsonRpc; namespace Microsoft.VisualStudio.Razor.LanguageClient.Endpoints; @@ -54,7 +53,6 @@ internal partial class RazorCustomMessageTarget csharpSnapshot.Snapshot.TextBuffer, Methods.TextDocumentFoldingRange.Name, RazorLSPConstants.RazorCSharpLanguageServerName, - SupportsFoldingRange, csharpRequestParams, cancellationToken).ConfigureAwait(false); @@ -90,7 +88,6 @@ internal partial class RazorCustomMessageTarget htmlDocument.Snapshot.TextBuffer, Methods.TextDocumentFoldingRange.Name, RazorLSPConstants.HtmlLanguageServerName, - SupportsFoldingRange, htmlRequestParams, cancellationToken).ConfigureAwait(false); @@ -126,15 +123,4 @@ internal partial class RazorCustomMessageTarget return new(htmlRanges.ToImmutableArray(), csharpRanges.ToImmutableArray()); } - - private static bool SupportsFoldingRange(JToken token) - { - var serverCapabilities = token.ToObject(); - - var supportsFoldingRange = serverCapabilities?.FoldingRangeProvider?.Match( - boolValue => boolValue, - options => options is not null) ?? false; - - return supportsFoldingRange; - } } diff --git a/src/Razor/src/Microsoft.VisualStudio.LanguageServices.Razor/LanguageClient/Endpoints/RazorCustomMessageTarget_FormatNewFile.cs b/src/Razor/src/Microsoft.VisualStudio.LanguageServices.Razor/LanguageClient/Endpoints/RazorCustomMessageTarget_FormatNewFile.cs index ae0e8cf41ae..82f049a1fb9 100644 --- a/src/Razor/src/Microsoft.VisualStudio.LanguageServices.Razor/LanguageClient/Endpoints/RazorCustomMessageTarget_FormatNewFile.cs +++ b/src/Razor/src/Microsoft.VisualStudio.LanguageServices.Razor/LanguageClient/Endpoints/RazorCustomMessageTarget_FormatNewFile.cs @@ -5,8 +5,6 @@ using System.Threading.Tasks; using Microsoft.CodeAnalysis.Razor.Protocol; using Microsoft.CodeAnalysis.Razor.Protocol.CodeActions; -using Microsoft.VisualStudio.LanguageServer.Protocol; -using Newtonsoft.Json.Linq; using StreamJsonRpc; namespace Microsoft.VisualStudio.Razor.LanguageClient.Endpoints; @@ -20,19 +18,9 @@ internal partial class RazorCustomMessageTarget var response = await _requestInvoker.ReinvokeRequestOnServerAsync( RazorLSPConstants.RoslynFormatNewFileEndpointName, RazorLSPConstants.RazorCSharpLanguageServerName, - SupportsFormatNewFile, request, cancellationToken).ConfigureAwait(false); return response.Result; } - - private static bool SupportsFormatNewFile(JToken token) - { - var serverCapabilities = token.ToObject(); - - return serverCapabilities?.Experimental is JObject experimental - && experimental.TryGetValue(RazorLSPConstants.RoslynFormatNewFileEndpointName, out var supportsFormatNewFile) - && supportsFormatNewFile.ToObject(); - } } diff --git a/src/Razor/src/Microsoft.VisualStudio.LanguageServices.Razor/LanguageClient/Endpoints/RazorCustomMessageTarget_MapCode.cs b/src/Razor/src/Microsoft.VisualStudio.LanguageServices.Razor/LanguageClient/Endpoints/RazorCustomMessageTarget_MapCode.cs index 98979877700..bf8e5a895ee 100644 --- a/src/Razor/src/Microsoft.VisualStudio.LanguageServices.Razor/LanguageClient/Endpoints/RazorCustomMessageTarget_MapCode.cs +++ b/src/Razor/src/Microsoft.VisualStudio.LanguageServices.Razor/LanguageClient/Endpoints/RazorCustomMessageTarget_MapCode.cs @@ -6,7 +6,6 @@ using Microsoft.CodeAnalysis.Razor.Protocol; using Microsoft.VisualStudio.LanguageServer.Protocol; using Microsoft.VisualStudio.Razor.LanguageClient.Extensions; -using Newtonsoft.Json.Linq; using StreamJsonRpc; namespace Microsoft.VisualStudio.Razor.LanguageClient.Endpoints; @@ -47,7 +46,6 @@ internal partial class RazorCustomMessageTarget textBuffer, lspMethodName, languageServerName, - SupportsMapCode, mapCodeParams, cancellationToken).ConfigureAwait(false); @@ -80,11 +78,4 @@ private void ConvertCSharpFocusLocationUris(Location[][] focusLocations) } } } - - private static bool SupportsMapCode(JToken token) - { - var serverCapabilities = token.ToObject(); - - return serverCapabilities?.MapCodeProvider ?? false; - } } diff --git a/src/Razor/src/Microsoft.VisualStudio.LanguageServices.Razor/LanguageClient/Endpoints/RazorCustomMessageTarget_SemanticTokens.cs b/src/Razor/src/Microsoft.VisualStudio.LanguageServices.Razor/LanguageClient/Endpoints/RazorCustomMessageTarget_SemanticTokens.cs index 784c77b732e..1d895280ad4 100644 --- a/src/Razor/src/Microsoft.VisualStudio.LanguageServices.Razor/LanguageClient/Endpoints/RazorCustomMessageTarget_SemanticTokens.cs +++ b/src/Razor/src/Microsoft.VisualStudio.LanguageServices.Razor/LanguageClient/Endpoints/RazorCustomMessageTarget_SemanticTokens.cs @@ -10,7 +10,6 @@ using Microsoft.CodeAnalysis.Razor.Protocol; using Microsoft.CodeAnalysis.Razor.Workspaces.Protocol.SemanticTokens; using Microsoft.VisualStudio.LanguageServer.Protocol; -using Newtonsoft.Json.Linq; using StreamJsonRpc; namespace Microsoft.VisualStudio.Razor.LanguageClient.Endpoints; @@ -28,7 +27,6 @@ internal partial class RazorCustomMessageTarget return ProvideSemanticTokensAsync( semanticTokensParams: inputParams, lspMethodName: Methods.TextDocumentSemanticTokensRangeName, - capabilitiesFilter: _ => true, requestParams: new SemanticTokensRangeParams { TextDocument = inputParams.TextDocument, @@ -45,7 +43,6 @@ internal partial class RazorCustomMessageTarget return ProvideSemanticTokensAsync( semanticTokensParams: inputParams, lspMethodName: RazorLSPConstants.RoslynSemanticTokenRangesEndpointName, - capabilitiesFilter: SupportsPreciseRanges, requestParams: new SemanticTokensRangesParams() { TextDocument = inputParams.TextDocument, @@ -57,7 +54,6 @@ internal partial class RazorCustomMessageTarget private async Task ProvideSemanticTokensAsync( ProvideSemanticTokensRangesParams semanticTokensParams, string lspMethodName, - Func capabilitiesFilter, SemanticTokensParams requestParams, CancellationToken cancellationToken) { @@ -123,7 +119,6 @@ internal partial class RazorCustomMessageTarget textBuffer, lspMethodName, languageServerName, - capabilitiesFilter, requestParams, cancellationToken).ConfigureAwait(false); @@ -140,13 +135,4 @@ internal partial class RazorCustomMessageTarget _logger.LogDebug($"Made one semantic token requests to Roslyn for {semanticTokensParams.Ranges.Length} ranges"); return new ProvideSemanticTokensResponse(response.Data, semanticTokensParams.RequiredHostDocumentVersion); } - - private static bool SupportsPreciseRanges(JToken token) - { - var serverCapabilities = token.ToObject(); - - return serverCapabilities?.Experimental is JObject experimental - && experimental.TryGetValue(RazorLSPConstants.RoslynSemanticTokenRangesEndpointName, out var supportsPreciseRanges) - && supportsPreciseRanges.ToObject(); - } } diff --git a/src/Razor/src/Microsoft.VisualStudio.LanguageServices.Razor/LanguageClient/Endpoints/RazorCustomMessageTarget_SimplifyMethod.cs b/src/Razor/src/Microsoft.VisualStudio.LanguageServices.Razor/LanguageClient/Endpoints/RazorCustomMessageTarget_SimplifyMethod.cs index b39724d978c..f1ac1f0567e 100644 --- a/src/Razor/src/Microsoft.VisualStudio.LanguageServices.Razor/LanguageClient/Endpoints/RazorCustomMessageTarget_SimplifyMethod.cs +++ b/src/Razor/src/Microsoft.VisualStudio.LanguageServices.Razor/LanguageClient/Endpoints/RazorCustomMessageTarget_SimplifyMethod.cs @@ -7,7 +7,6 @@ using Microsoft.CodeAnalysis.Razor.Protocol.CodeActions; using Microsoft.VisualStudio.LanguageServer.Protocol; using Microsoft.VisualStudio.Razor.LanguageClient.Extensions; -using Newtonsoft.Json.Linq; using StreamJsonRpc; namespace Microsoft.VisualStudio.Razor.LanguageClient.Endpoints; @@ -41,19 +40,9 @@ internal partial class RazorCustomMessageTarget var response = await _requestInvoker.ReinvokeRequestOnServerAsync( RazorLSPConstants.RoslynSimplifyMethodEndpointName, RazorLSPConstants.RazorCSharpLanguageServerName, - SupportsSimplifyMethod, simplifyTypeNamesParams, cancellationToken).ConfigureAwait(false); return response.Result; } - - private static bool SupportsSimplifyMethod(JToken token) - { - var serverCapabilities = token.ToObject(); - - return serverCapabilities?.Experimental is JObject experimental - && experimental.TryGetValue(RazorLSPConstants.RoslynSimplifyMethodEndpointName, out var supportsSimplifyMethod) - && supportsSimplifyMethod.ToObject(); - } } diff --git a/src/Razor/src/Microsoft.VisualStudio.LanguageServices.Razor/LanguageClient/Endpoints/RazorCustomMessageTarget_SpellCheck.cs b/src/Razor/src/Microsoft.VisualStudio.LanguageServices.Razor/LanguageClient/Endpoints/RazorCustomMessageTarget_SpellCheck.cs index 61ed7a1a6b5..ba4b1a825fc 100644 --- a/src/Razor/src/Microsoft.VisualStudio.LanguageServices.Razor/LanguageClient/Endpoints/RazorCustomMessageTarget_SpellCheck.cs +++ b/src/Razor/src/Microsoft.VisualStudio.LanguageServices.Razor/LanguageClient/Endpoints/RazorCustomMessageTarget_SpellCheck.cs @@ -7,7 +7,6 @@ using Microsoft.CodeAnalysis.Razor.Protocol; using Microsoft.VisualStudio.LanguageServer.Protocol; using Microsoft.VisualStudio.Razor.LanguageClient.Extensions; -using Newtonsoft.Json.Linq; using StreamJsonRpc; namespace Microsoft.VisualStudio.Razor.LanguageClient.Endpoints; @@ -36,17 +35,9 @@ public async Task SpellCheckAsync(Delegat virtualDocument.Snapshot.TextBuffer, VSInternalMethods.TextDocumentSpellCheckableRangesName, RazorLSPConstants.RazorCSharpLanguageServerName, - SupportsSpellCheck, spellCheckParams, cancellationToken).ConfigureAwait(false); return response?.Response ?? Array.Empty(); } - - private static bool SupportsSpellCheck(JToken token) - { - var serverCapabilities = token.ToObject(); - - return serverCapabilities?.SpellCheckingProvider ?? false; - } } diff --git a/src/Razor/src/Microsoft.VisualStudio.LanguageServices.Razor/LanguageClient/Endpoints/RazorCustomMessageTarget_UpdateCSharpBuffer.cs b/src/Razor/src/Microsoft.VisualStudio.LanguageServices.Razor/LanguageClient/Endpoints/RazorCustomMessageTarget_UpdateCSharpBuffer.cs index 6e75cb4ddf9..9ebc750ea31 100644 --- a/src/Razor/src/Microsoft.VisualStudio.LanguageServices.Razor/LanguageClient/Endpoints/RazorCustomMessageTarget_UpdateCSharpBuffer.cs +++ b/src/Razor/src/Microsoft.VisualStudio.LanguageServices.Razor/LanguageClient/Endpoints/RazorCustomMessageTarget_UpdateCSharpBuffer.cs @@ -9,7 +9,6 @@ using Microsoft.AspNetCore.Razor.ProjectSystem; using Microsoft.CodeAnalysis.Razor.Logging; using Microsoft.CodeAnalysis.Razor.Protocol; -using Microsoft.VisualStudio.Razor.LanguageClient.Extensions; using StreamJsonRpc; namespace Microsoft.VisualStudio.Razor.LanguageClient.Endpoints; diff --git a/src/Razor/src/Microsoft.VisualStudio.LanguageServices.Razor/LanguageClient/Endpoints/RazorCustomMessageTarget_UpdateHtmlBuffer.cs b/src/Razor/src/Microsoft.VisualStudio.LanguageServices.Razor/LanguageClient/Endpoints/RazorCustomMessageTarget_UpdateHtmlBuffer.cs index bec621eaf08..0bf10cdcdb6 100644 --- a/src/Razor/src/Microsoft.VisualStudio.LanguageServices.Razor/LanguageClient/Endpoints/RazorCustomMessageTarget_UpdateHtmlBuffer.cs +++ b/src/Razor/src/Microsoft.VisualStudio.LanguageServices.Razor/LanguageClient/Endpoints/RazorCustomMessageTarget_UpdateHtmlBuffer.cs @@ -6,7 +6,6 @@ using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis.Razor.Protocol; -using Microsoft.VisualStudio.Razor.LanguageClient.Extensions; using StreamJsonRpc; namespace Microsoft.VisualStudio.Razor.LanguageClient.Endpoints; diff --git a/src/Razor/src/Microsoft.VisualStudio.LanguageServices.Razor/LanguageClient/Endpoints/UpdateBufferRequest.cs b/src/Razor/src/Microsoft.VisualStudio.LanguageServices.Razor/LanguageClient/Endpoints/UpdateBufferRequest.cs deleted file mode 100644 index 9defb928b38..00000000000 --- a/src/Razor/src/Microsoft.VisualStudio.LanguageServices.Razor/LanguageClient/Endpoints/UpdateBufferRequest.cs +++ /dev/null @@ -1,20 +0,0 @@ -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT license. See License.txt in the project root for license information. - -using System.Collections.Generic; -using Microsoft.CodeAnalysis.Text; - -namespace Microsoft.VisualStudio.Razor.LanguageClient.Endpoints; - -internal class UpdateBufferRequest -{ - public int? HostDocumentVersion { get; init; } - - public string? ProjectKeyId { get; init; } - - public string? HostDocumentFilePath { get; init; } - - public required IReadOnlyList Changes { get; init; } - - public bool PreviousWasEmpty { get; set; } -} diff --git a/src/Razor/src/Microsoft.VisualStudio.LanguageServices.Razor/LanguageClient/Extensions/TextChangeExtensions.cs b/src/Razor/src/Microsoft.VisualStudio.LanguageServices.Razor/LanguageClient/Extensions/TextChangeExtensions.cs index fff495f7b89..ed35fe35e5a 100644 --- a/src/Razor/src/Microsoft.VisualStudio.LanguageServices.Razor/LanguageClient/Extensions/TextChangeExtensions.cs +++ b/src/Razor/src/Microsoft.VisualStudio.LanguageServices.Razor/LanguageClient/Extensions/TextChangeExtensions.cs @@ -1,14 +1,13 @@ // Copyright (c) .NET Foundation. All rights reserved. // Licensed under the MIT license. See License.txt in the project root for license information. -using Microsoft.CodeAnalysis.Text; using Microsoft.VisualStudio.LanguageServer.ContainedLanguage; using Microsoft.VisualStudio.Text; -namespace Microsoft.VisualStudio.Razor.LanguageClient.Extensions; +namespace Microsoft.CodeAnalysis.Razor.Protocol; internal static class TextChangeExtensions { - public static ITextChange ToVisualStudioTextChange(this TextChange roslynTextChange) => - new VisualStudioTextChange(roslynTextChange.Span.Start, roslynTextChange.Span.Length, roslynTextChange.NewText!); + public static ITextChange ToVisualStudioTextChange(this RazorTextChange razorTextChange) + => new VisualStudioTextChange(razorTextChange.Span.Start, razorTextChange.Span.Length, razorTextChange.NewText!); } diff --git a/src/Razor/src/Microsoft.VisualStudio.LanguageServices.Razor/LanguageClient/RazorLanguageServerClient.cs b/src/Razor/src/Microsoft.VisualStudio.LanguageServices.Razor/LanguageClient/RazorLanguageServerClient.cs index 355cc455e94..2bf2206fe25 100644 --- a/src/Razor/src/Microsoft.VisualStudio.LanguageServices.Razor/LanguageClient/RazorLanguageServerClient.cs +++ b/src/Razor/src/Microsoft.VisualStudio.LanguageServices.Razor/LanguageClient/RazorLanguageServerClient.cs @@ -42,7 +42,7 @@ internal class RazorLanguageServerClient( IClientSettingsManager clientSettingsManager, ILspServerActivationTracker lspServerActivationTracker, VisualStudioHostServicesProvider vsHostServicesProvider) - : ILanguageClient, ILanguageClientCustomMessage2, ILanguageClientPriority + : ILanguageClient, ILanguageClientCustomMessage2, ILanguageClientPriority, IPropertyOwner { private readonly ILanguageClientBroker _languageClientBroker = languageClientBroker; private readonly ILanguageServiceBroker2 _languageServiceBroker = languageServiceBroker; @@ -84,6 +84,16 @@ public event AsyncEventHandler? StopAsync public bool ShowNotificationOnInitializeFailed => true; + public PropertyCollection Properties { get; } = CreateStjPropertyCollection(); + + private static PropertyCollection CreateStjPropertyCollection() + { + // Opt in to System.Text.Json serialization on the client + var collection = new PropertyCollection(); + collection.AddProperty("lsp-serialization", "stj"); + return collection; + } + public async Task ActivateAsync(CancellationToken token) { // Swap to background thread, nothing below needs to be done on the UI thread. diff --git a/src/Razor/src/Microsoft.VisualStudio.LanguageServices.Razor/LanguageClient/WorkspaceConfigurationChangedListener.cs b/src/Razor/src/Microsoft.VisualStudio.LanguageServices.Razor/LanguageClient/WorkspaceConfigurationChangedListener.cs index 9962e1b8058..a2ec0e79fdc 100644 --- a/src/Razor/src/Microsoft.VisualStudio.LanguageServices.Razor/LanguageClient/WorkspaceConfigurationChangedListener.cs +++ b/src/Razor/src/Microsoft.VisualStudio.LanguageServices.Razor/LanguageClient/WorkspaceConfigurationChangedListener.cs @@ -4,11 +4,9 @@ using System.ComponentModel.Composition; using System.Threading; using System.Threading.Tasks; -using Microsoft.AspNetCore.Razor.LanguageServer.Hosting; using Microsoft.VisualStudio.LanguageServer.ContainedLanguage; using Microsoft.VisualStudio.LanguageServer.Protocol; using Microsoft.VisualStudio.Razor.Settings; -using Newtonsoft.Json.Linq; namespace Microsoft.VisualStudio.Razor.LanguageClient; @@ -39,21 +37,10 @@ private async Task OnClientSettingsChangedAsync() await _requestInvoker.ReinvokeRequestOnServerAsync( Methods.WorkspaceDidChangeConfigurationName, RazorLSPConstants.RazorLanguageServerName, - CheckRazorServerCapability, new DidChangeConfigurationParams(), CancellationToken.None); } - private static bool CheckRazorServerCapability(JToken token) - { - // We're talking cross-language servers here. Given the workspace/didChangeConfiguration is a normal LSP message this will only fail - // if the Razor language server is not running. Typically this would be OK from a platform perspective; however VS will explode if - // there's not a corresponding language server to accept the message. To protect ourselves from this scenario we can utilize capabilities - // and just lookup generic Razor language server specific capabilities. If they exist we can succeed. - var isRazorLanguageServer = RazorLanguageServerCapability.TryGet(token, out _); - return isRazorLanguageServer; - } - private class Unit { } diff --git a/src/Razor/src/Microsoft.VisualStudio.LanguageServices.Razor/LanguageClient/WrapWithTag/VSInternalWrapWithTagParams.cs b/src/Razor/src/Microsoft.VisualStudio.LanguageServices.Razor/LanguageClient/WrapWithTag/VSInternalWrapWithTagParams.cs index 864094c30a4..b9b4d7ff394 100644 --- a/src/Razor/src/Microsoft.VisualStudio.LanguageServices.Razor/LanguageClient/WrapWithTag/VSInternalWrapWithTagParams.cs +++ b/src/Razor/src/Microsoft.VisualStudio.LanguageServices.Razor/LanguageClient/WrapWithTag/VSInternalWrapWithTagParams.cs @@ -2,6 +2,7 @@ // Licensed under the MIT license. See License.txt in the project root for license information. using System.Runtime.Serialization; +using System.Text.Json.Serialization; using Microsoft.VisualStudio.LanguageServer.Protocol; namespace Microsoft.VisualStudio.Razor.LanguageClient.WrapWithTag; @@ -28,6 +29,7 @@ public VSInternalWrapWithTagParams(Range range, /// Gets or sets the identifier for the text document to be operate on. /// [DataMember(Name = "_vs_textDocument")] + [JsonPropertyName("_vs_textDocument")] public VersionedTextDocumentIdentifier TextDocument { get; @@ -38,6 +40,7 @@ public VersionedTextDocumentIdentifier TextDocument /// Gets or sets the selection range to be wrapped. /// [DataMember(Name = "_vs_range")] + [JsonPropertyName("_vs_range")] public Range Range { get; @@ -48,6 +51,7 @@ public Range Range /// Gets or sets the wrapping tag name. /// [DataMember(Name = "_vs_tagName")] + [JsonPropertyName("_vs_tagName")] public string TagName { get; @@ -58,6 +62,7 @@ public string TagName /// Gets or sets the formatting options. /// [DataMember(Name = "_vs_options")] + [JsonPropertyName("_vs_options")] public FormattingOptions Options { get; diff --git a/src/Razor/src/Microsoft.VisualStudio.LanguageServices.Razor/LanguageClient/WrapWithTag/VSInternalWrapWithTagResponse.cs b/src/Razor/src/Microsoft.VisualStudio.LanguageServices.Razor/LanguageClient/WrapWithTag/VSInternalWrapWithTagResponse.cs index f4ef0651375..35316bc2909 100644 --- a/src/Razor/src/Microsoft.VisualStudio.LanguageServices.Razor/LanguageClient/WrapWithTag/VSInternalWrapWithTagResponse.cs +++ b/src/Razor/src/Microsoft.VisualStudio.LanguageServices.Razor/LanguageClient/WrapWithTag/VSInternalWrapWithTagResponse.cs @@ -2,6 +2,7 @@ // Licensed under the MIT license. See License.txt in the project root for license information. using System.Runtime.Serialization; +using System.Text.Json.Serialization; using Microsoft.VisualStudio.LanguageServer.Protocol; namespace Microsoft.VisualStudio.Razor.LanguageClient.WrapWithTag; @@ -23,12 +24,14 @@ public VSInternalWrapWithTagResponse(Range tagRange, TextEdit[] textEdits) /// Gets or sets the range of the wrapping tag. /// [DataMember(Name = "_vs_tagRange")] + [JsonPropertyName("_vs_tagRange")] public Range TagRange { get; } /// /// Gets or sets the text edits. /// [DataMember(Name = "_vs_textEdits")] + [JsonPropertyName("_vs_textEdits")] public TextEdit[] TextEdits { get; diff --git a/src/Razor/src/Microsoft.VisualStudio.LanguageServices.Razor/Snippets/SnippetInfo.cs b/src/Razor/src/Microsoft.VisualStudio.LanguageServices.Razor/Snippets/SnippetInfo.cs index a573dab3301..57f70ffa2a3 100644 --- a/src/Razor/src/Microsoft.VisualStudio.LanguageServices.Razor/Snippets/SnippetInfo.cs +++ b/src/Razor/src/Microsoft.VisualStudio.LanguageServices.Razor/Snippets/SnippetInfo.cs @@ -3,8 +3,8 @@ using System; using System.Diagnostics.CodeAnalysis; -using Newtonsoft.Json; -using Newtonsoft.Json.Linq; +using System.Text.Json; +using System.Text.Json.Serialization; namespace Microsoft.VisualStudio.Razor.Snippets; @@ -40,7 +40,7 @@ public SnippetInfo( => _parsedXmlSnippet.Value; } -internal record SnippetCompletionData([property: JsonProperty(SnippetCompletionData.PropertyName)] string Path) +internal record SnippetCompletionData([property: JsonPropertyName(SnippetCompletionData.PropertyName)] string Path) { private const string PropertyName = "__razor_snippet_path"; @@ -48,12 +48,12 @@ internal static bool TryParse(object? data, [NotNullWhen(true)] out SnippetCompl { snippetCompletionData = data as SnippetCompletionData; - if (data is JObject jObject && - jObject.Property(PropertyName) is not null) + if (data is JsonElement jElement && + jElement.TryGetProperty(PropertyName, out _)) { try { - snippetCompletionData = jObject.ToObject(); + snippetCompletionData = jElement.Deserialize(); } catch { } } diff --git a/src/Razor/src/Microsoft.VisualStudio.RazorExtension/RazorPackage.cs b/src/Razor/src/Microsoft.VisualStudio.RazorExtension/RazorPackage.cs index 2134a9bec8a..81a89fb79fa 100644 --- a/src/Razor/src/Microsoft.VisualStudio.RazorExtension/RazorPackage.cs +++ b/src/Razor/src/Microsoft.VisualStudio.RazorExtension/RazorPackage.cs @@ -128,8 +128,11 @@ private void ShowToolWindow(object sender, EventArgs e) // Initialize command handlers in the window if (!window.CommandHandlersInitialized) { - var mcs = (IMenuCommandService)GetService(typeof(IMenuCommandService)); - window.InitializeCommands(mcs, GuidSyntaxVisualizerMenuCmdSet); + var mcs = (IMenuCommandService?)GetService(typeof(IMenuCommandService)); + if (mcs is not null) + { + window.InitializeCommands(mcs, GuidSyntaxVisualizerMenuCmdSet); + } } ErrorHandler.ThrowOnFailure(windowFrame.Show()); diff --git a/src/Razor/test/Microsoft.AspNetCore.Razor.LanguageServer.Test/CodeActions/AddUsingsCodeActionResolverTest.cs b/src/Razor/test/Microsoft.AspNetCore.Razor.LanguageServer.Test/CodeActions/AddUsingsCodeActionResolverTest.cs index 01c420a9ea8..5a1a0a6d6ee 100644 --- a/src/Razor/test/Microsoft.AspNetCore.Razor.LanguageServer.Test/CodeActions/AddUsingsCodeActionResolverTest.cs +++ b/src/Razor/test/Microsoft.AspNetCore.Razor.LanguageServer.Test/CodeActions/AddUsingsCodeActionResolverTest.cs @@ -3,6 +3,7 @@ using System; using System.Linq; +using System.Text.Json; using System.Threading.Tasks; using Microsoft.AspNetCore.Mvc.Razor.Extensions; using Microsoft.AspNetCore.Razor.Language; @@ -10,7 +11,6 @@ using Microsoft.AspNetCore.Razor.Test.Common.LanguageServer; using Microsoft.CodeAnalysis.Razor.ProjectSystem; using Microsoft.CodeAnalysis.Razor.Workspaces; -using Newtonsoft.Json.Linq; using Xunit; using Xunit.Abstractions; @@ -25,7 +25,7 @@ public async Task Handle_MissingFile() { // Arrange var resolver = new AddUsingsCodeActionResolver(_emptyDocumentContextFactory); - var data = JObject.FromObject(new AddUsingsCodeActionParams() + var data = JsonSerializer.SerializeToElement(new AddUsingsCodeActionParams() { Uri = new Uri("c:/Test.razor"), Namespace = "System", @@ -48,7 +48,7 @@ public async Task Handle_Unsupported() codeDocument.SetUnsupported(); var resolver = new AddUsingsCodeActionResolver(CreateDocumentContextFactory(documentPath, codeDocument)); - var data = JObject.FromObject(new AddUsingsCodeActionParams() + var data = JsonSerializer.SerializeToElement(new AddUsingsCodeActionParams() { Uri = documentPath, Namespace = "System", @@ -75,7 +75,7 @@ public async Task Handle_AddOneUsingToEmpty() Uri = documentPath, Namespace = "System", }; - var data = JObject.FromObject(actionParams); + var data = JsonSerializer.SerializeToElement(actionParams); // Act var workspaceEdit = await resolver.ResolveAsync(data, default); @@ -113,7 +113,7 @@ public async Task Handle_AddOneUsingToComponentPageDirective() Uri = documentPath, Namespace = "System", }; - var data = JObject.FromObject(actionParams); + var data = JsonSerializer.SerializeToElement(actionParams); // Act var workspaceEdit = await resolver.ResolveAsync(data, default); @@ -158,7 +158,7 @@ @model IndexModel Uri = documentPath, Namespace = "System", }; - var data = JObject.FromObject(actionParams); + var data = JsonSerializer.SerializeToElement(actionParams); // Act var workspaceEdit = await resolver.ResolveAsync(data, default); @@ -197,7 +197,7 @@ public async Task Handle_AddOneUsingToHTML() Uri = documentPath, Namespace = "System", }; - var data = JObject.FromObject(actionParams); + var data = JsonSerializer.SerializeToElement(actionParams); // Act var workspaceEdit = await resolver.ResolveAsync(data, default); @@ -234,7 +234,7 @@ @namespace Testing Uri = documentPath, Namespace = "System", }; - var data = JObject.FromObject(actionParams); + var data = JsonSerializer.SerializeToElement(actionParams); // Act var workspaceEdit = await resolver.ResolveAsync(data, default); @@ -272,7 +272,7 @@ @namespace Testing Uri = documentPath, Namespace = "System", }; - var data = JObject.FromObject(actionParams); + var data = JsonSerializer.SerializeToElement(actionParams); // Act var workspaceEdit = await resolver.ResolveAsync(data, default); @@ -306,7 +306,7 @@ public async Task Handle_AddOneUsingToUsings() Uri = documentPath, Namespace = "System.Linq", }; - var data = JObject.FromObject(actionParams); + var data = JsonSerializer.SerializeToElement(actionParams); // Act var workspaceEdit = await resolver.ResolveAsync(data, default); @@ -344,7 +344,7 @@ @using System.Linq Uri = documentPath, Namespace = "Microsoft.AspNetCore.Razor.Language", }; - var data = JObject.FromObject(actionParams); + var data = JsonSerializer.SerializeToElement(actionParams); // Act var workspaceEdit = await resolver.ResolveAsync(data, default); diff --git a/src/Razor/test/Microsoft.AspNetCore.Razor.LanguageServer.Test/CodeActions/CSharp/DefaultCSharpCodeActionResolverTest.cs b/src/Razor/test/Microsoft.AspNetCore.Razor.LanguageServer.Test/CodeActions/CSharp/DefaultCSharpCodeActionResolverTest.cs index 28a5e7a190f..254bdf1b91c 100644 --- a/src/Razor/test/Microsoft.AspNetCore.Razor.LanguageServer.Test/CodeActions/CSharp/DefaultCSharpCodeActionResolverTest.cs +++ b/src/Razor/test/Microsoft.AspNetCore.Razor.LanguageServer.Test/CodeActions/CSharp/DefaultCSharpCodeActionResolverTest.cs @@ -3,6 +3,8 @@ using System; using System.Linq; +using System.Text.Json; +using System.Text.Json.Nodes; using System.Threading; using System.Threading.Tasks; using Microsoft.AspNetCore.Mvc.Razor.Extensions; @@ -17,7 +19,6 @@ using Microsoft.CodeAnalysis.Razor.Workspaces; using Microsoft.VisualStudio.LanguageServer.Protocol; using Moq; -using Newtonsoft.Json.Linq; using Xunit; using Xunit.Abstractions; @@ -28,7 +29,7 @@ public class DefaultCSharpCodeActionResolverTest(ITestOutputHelper testOutput) : private static readonly CodeAction s_defaultResolvedCodeAction = new() { Title = "ResolvedCodeAction", - Data = JToken.FromObject(new object()), + Data = JsonSerializer.SerializeToElement(new object()), Edit = new WorkspaceEdit() { DocumentChanges = new TextDocumentEdit[] { @@ -85,7 +86,7 @@ public async Task ResolveAsync_NoDocumentChanges_ReturnsOriginalCodeAction() var resolvedCodeAction = new CodeAction() { Title = "ResolvedCodeAction", - Data = JToken.FromObject(new object()), + Data = JsonSerializer.SerializeToElement(new object()), Edit = new WorkspaceEdit() { DocumentChanges = null @@ -110,7 +111,7 @@ public async Task ResolveAsync_MultipleDocumentChanges_ReturnsOriginalCodeAction var resolvedCodeAction = new CodeAction() { Title = "ResolvedCodeAction", - Data = JToken.FromObject(new object()), + Data = JsonSerializer.SerializeToElement(new object()), Edit = new WorkspaceEdit() { DocumentChanges = new TextDocumentEdit[] { @@ -154,7 +155,7 @@ public async Task ResolveAsync_NonTextDocumentEdit_ReturnsOriginalCodeAction() var resolvedCodeAction = new CodeAction() { Title = "ResolvedCodeAction", - Data = JToken.FromObject(new object()), + Data = JsonSerializer.SerializeToElement(new object()), Edit = new WorkspaceEdit() { DocumentChanges = new SumType[] { @@ -190,7 +191,7 @@ private static void CreateCodeActionResolver( codeActionParams = new CodeActionResolveParams() { - Data = new JObject(), + Data = new JsonElement(), RazorFileIdentifier = new VSTextDocumentIdentifier { Uri = documentUri diff --git a/src/Razor/test/Microsoft.AspNetCore.Razor.LanguageServer.Test/CodeActions/CSharp/TypeAccessibilityCodeActionProviderTest.cs b/src/Razor/test/Microsoft.AspNetCore.Razor.LanguageServer.Test/CodeActions/CSharp/TypeAccessibilityCodeActionProviderTest.cs index f2b1a366606..292c08cd818 100644 --- a/src/Razor/test/Microsoft.AspNetCore.Razor.LanguageServer.Test/CodeActions/CSharp/TypeAccessibilityCodeActionProviderTest.cs +++ b/src/Razor/test/Microsoft.AspNetCore.Razor.LanguageServer.Test/CodeActions/CSharp/TypeAccessibilityCodeActionProviderTest.cs @@ -3,6 +3,7 @@ using System; using System.Collections.Immutable; +using System.Text.Json; using System.Threading; using System.Threading.Tasks; using Microsoft.AspNetCore.Mvc.Razor.Extensions; @@ -18,7 +19,6 @@ using Microsoft.CodeAnalysis.Text; using Microsoft.VisualStudio.LanguageServer.Protocol; using Moq; -using Newtonsoft.Json.Linq; using Xunit; using Xunit.Abstractions; @@ -225,7 +225,7 @@ public async Task Handle_ValidDiagnostic_ValidCodeAction_VSCode_ReturnsCodeActio Assert.Equal("@using System.IO", r.Title); Assert.Null(r.Edit); Assert.NotNull(r.Data); - var resolutionParams = ((JObject)r.Data).ToObject(); + var resolutionParams = ((JsonElement)r.Data).Deserialize(); Assert.NotNull(resolutionParams); Assert.Equal(LanguageServerConstants.CodeActions.AddUsing, resolutionParams.Action); }, @@ -284,7 +284,7 @@ public async Task Handle_CodeActionInSingleLineDirective_VS_ReturnsOnlyUsingCode Assert.Equal("@using System.IO", r.Title); Assert.Null(r.Edit); Assert.NotNull(r.Data); - var resolutionParams = ((JObject)r.Data).ToObject(); + var resolutionParams = ((JsonElement)r.Data).Deserialize(); Assert.NotNull(resolutionParams); Assert.Equal(LanguageServerConstants.CodeActions.Default, resolutionParams.Action); } @@ -336,7 +336,7 @@ public async Task Handle_ValidCodeAction_VS_ReturnsCodeActions() Assert.Equal("@using System.IO", r.Title); Assert.Null(r.Edit); Assert.NotNull(r.Data); - var resolutionParams = ((JObject)r.Data).ToObject(); + var resolutionParams = ((JsonElement)r.Data).Deserialize(); Assert.NotNull(resolutionParams); Assert.Equal(LanguageServerConstants.CodeActions.Default, resolutionParams.Action); }, @@ -414,7 +414,7 @@ public async Task Handle_ValidDiagnostic_MultipleValidCodeActions_VSCode_Returns Assert.Equal("@using SuperSpecialNamespace", r.Title); Assert.Null(r.Edit); Assert.NotNull(r.Data); - var resolutionParams = ((JObject)r.Data).ToObject(); + var resolutionParams = ((JsonElement)r.Data).Deserialize(); Assert.NotNull(resolutionParams); Assert.Equal(LanguageServerConstants.CodeActions.AddUsing, resolutionParams.Action); }, @@ -423,7 +423,7 @@ public async Task Handle_ValidDiagnostic_MultipleValidCodeActions_VSCode_Returns Assert.Equal("@using System.IO", r.Title); Assert.Null(r.Edit); Assert.NotNull(r.Data); - var resolutionParams = ((JObject)r.Data).ToObject(); + var resolutionParams = ((JsonElement)r.Data).Deserialize(); Assert.NotNull(resolutionParams); Assert.Equal(LanguageServerConstants.CodeActions.AddUsing, resolutionParams.Action); }, diff --git a/src/Razor/test/Microsoft.AspNetCore.Razor.LanguageServer.Test/CodeActions/CodeActionEndpointTest.cs b/src/Razor/test/Microsoft.AspNetCore.Razor.LanguageServer.Test/CodeActions/CodeActionEndpointTest.cs index 870ad3c7dbb..41ecfb5c476 100644 --- a/src/Razor/test/Microsoft.AspNetCore.Razor.LanguageServer.Test/CodeActions/CodeActionEndpointTest.cs +++ b/src/Razor/test/Microsoft.AspNetCore.Razor.LanguageServer.Test/CodeActions/CodeActionEndpointTest.cs @@ -4,6 +4,8 @@ using System; using System.Collections.Generic; using System.Linq; +using System.Text.Json; +using System.Text.Json.Nodes; using System.Threading; using System.Threading.Tasks; using Microsoft.AspNetCore.Razor.Language; @@ -18,7 +20,6 @@ using Microsoft.CodeAnalysis.Text; using Microsoft.VisualStudio.LanguageServer.Protocol; using Moq; -using Newtonsoft.Json.Linq; using Xunit; using Xunit.Abstractions; @@ -587,8 +588,8 @@ public async Task Handle_MultipleMixedProvider_SupportsCodeActionResolveFalse() { Assert.True(c.TryGetFirst(out var command1)); var command = Assert.IsType(command1); - var codeActionParamsToken = (JToken)command.Arguments!.First(); - var codeActionParams = codeActionParamsToken.ToObject(); + var codeActionParamsToken = (JsonObject)command.Arguments!.First(); + var codeActionParams = codeActionParamsToken.Deserialize(); Assert.NotNull(codeActionParams); Assert.Equal(LanguageServerConstants.CodeActions.EditBasedCodeActionCommand, codeActionParams.Action); }, @@ -847,7 +848,7 @@ private class MockRazorCommandProvider : IRazorCodeActionProvider return Task.FromResult?>(new List() { new RazorVSInternalCodeAction() { Title = "SomeTitle", - Data = JToken.FromObject(new AddUsingsCodeActionParams() + Data = JsonSerializer.SerializeToElement(new AddUsingsCodeActionParams() { Namespace="Test", Uri = new Uri("C:/path/to/Page.razor") @@ -921,7 +922,7 @@ delegatedCodeActionParams.CodeActionParams is not VSCodeActionParams codeActionP { new RazorVSInternalCodeAction() { - Data = JToken.FromObject(new { CustomTags = new object[] { "CodeActionName" } }), + Data = JsonSerializer.SerializeToElement(new { CustomTags = new object[] { "CodeActionName" } }), Diagnostics = diagnostics.ToArray() } }; diff --git a/src/Razor/test/Microsoft.AspNetCore.Razor.LanguageServer.Test/CodeActions/CodeActionResolutionEndpointTest.cs b/src/Razor/test/Microsoft.AspNetCore.Razor.LanguageServer.Test/CodeActions/CodeActionResolutionEndpointTest.cs index a831b2a11f2..e84c93d22e0 100644 --- a/src/Razor/test/Microsoft.AspNetCore.Razor.LanguageServer.Test/CodeActions/CodeActionResolutionEndpointTest.cs +++ b/src/Razor/test/Microsoft.AspNetCore.Razor.LanguageServer.Test/CodeActions/CodeActionResolutionEndpointTest.cs @@ -2,6 +2,7 @@ // Licensed under the MIT license. See License.txt in the project root for license information. using System; +using System.Text.Json; using System.Threading; using System.Threading.Tasks; using Microsoft.AspNetCore.Razor.LanguageServer.CodeActions.Models; @@ -11,7 +12,6 @@ using Microsoft.CodeAnalysis.Razor.Protocol; using Microsoft.VisualStudio.LanguageServer.Protocol; using Moq; -using Newtonsoft.Json.Linq; using Xunit; using Xunit.Abstractions; @@ -43,7 +43,7 @@ public async Task Handle_Valid_RazorCodeAction_WithResolver() var request = new CodeAction() { Title = "Valid request", - Data = JToken.FromObject(requestParams) + Data = JsonSerializer.SerializeToElement(requestParams) }; var requestContext = CreateRazorRequestContext(documentContext: null); @@ -69,7 +69,7 @@ public async Task Handle_Valid_CSharpCodeAction_WithResolver() { Action = "Test", Language = LanguageServerConstants.CodeActions.Languages.CSharp, - Data = JObject.FromObject(new CodeActionResolveParams() + Data = JsonSerializer.SerializeToElement(new CodeActionResolveParams() { RazorFileIdentifier = new VSTextDocumentIdentifier { @@ -80,7 +80,7 @@ public async Task Handle_Valid_CSharpCodeAction_WithResolver() var request = new CodeAction() { Title = "Valid request", - Data = JToken.FromObject(requestParams) + Data = JsonSerializer.SerializeToElement(requestParams) }; var requestContext = CreateRazorRequestContext(documentContext: null); @@ -108,7 +108,7 @@ public async Task Handle_Valid_CSharpCodeAction_WithMultipleLanguageResolvers() { Action = "TestCSharp", Language = LanguageServerConstants.CodeActions.Languages.CSharp, - Data = JObject.FromObject(new CodeActionResolveParams() + Data = JsonSerializer.SerializeToElement(new CodeActionResolveParams() { RazorFileIdentifier = new VSTextDocumentIdentifier { @@ -119,7 +119,7 @@ public async Task Handle_Valid_CSharpCodeAction_WithMultipleLanguageResolvers() var request = new CodeAction() { Title = "Valid request", - Data = JToken.FromObject(requestParams) + Data = JsonSerializer.SerializeToElement(requestParams) }; var requestContext = CreateRazorRequestContext(documentContext: null); @@ -152,7 +152,7 @@ public async Task Handle_Valid_RazorCodeAction_WithoutResolver() var request = new CodeAction() { Title = "Valid request", - Data = JToken.FromObject(requestParams) + Data = JsonSerializer.SerializeToElement(requestParams) }; var requestContext = CreateRazorRequestContext(documentContext: null); @@ -181,7 +181,7 @@ public async Task Handle_Valid_CSharpCodeAction_WithoutResolver() { Action = "Test", Language = LanguageServerConstants.CodeActions.Languages.CSharp, - Data = JObject.FromObject(new CodeActionResolveParams() + Data = JsonSerializer.SerializeToElement(new CodeActionResolveParams() { RazorFileIdentifier = new VSTextDocumentIdentifier { @@ -192,7 +192,7 @@ public async Task Handle_Valid_CSharpCodeAction_WithoutResolver() var request = new CodeAction() { Title = "Valid request", - Data = JToken.FromObject(requestParams) + Data = JsonSerializer.SerializeToElement(requestParams) }; var requestContext = CreateRazorRequestContext(documentContext: null); @@ -232,7 +232,7 @@ public async Task Handle_Valid_RazorCodeAction_WithCSharpResolver_ResolvesNull() var request = new CodeAction() { Title = "Valid request", - Data = JToken.FromObject(requestParams) + Data = JsonSerializer.SerializeToElement(requestParams) }; var requestContext = CreateRazorRequestContext(documentContext: null); @@ -263,7 +263,7 @@ public async Task Handle_Valid_CSharpCodeAction_WithRazorResolver_ResolvesNull() { Action = "Test", Language = LanguageServerConstants.CodeActions.Languages.CSharp, - Data = JObject.FromObject(new CodeActionResolveParams() + Data = JsonSerializer.SerializeToElement(new CodeActionResolveParams() { RazorFileIdentifier = new VSTextDocumentIdentifier { @@ -274,7 +274,7 @@ public async Task Handle_Valid_CSharpCodeAction_WithRazorResolver_ResolvesNull() var request = new CodeAction() { Title = "Valid request", - Data = JToken.FromObject(requestParams) + Data = JsonSerializer.SerializeToElement(requestParams) }; var requestContext = CreateRazorRequestContext(documentContext: null); @@ -307,7 +307,7 @@ public async Task ResolveRazorCodeAction_ResolveMultipleRazorProviders_FirstMatc { Action = "A", Language = LanguageServerConstants.CodeActions.Languages.Razor, - Data = JToken.FromObject(new AddUsingsCodeActionParams() + Data = JsonSerializer.SerializeToElement(new AddUsingsCodeActionParams() { Namespace = "Test", Uri = new Uri("C:/path/to/Page.razor") @@ -338,7 +338,7 @@ public async Task ResolveRazorCodeAction_ResolveMultipleRazorProviders_SecondMat { Action = "B", Language = LanguageServerConstants.CodeActions.Languages.Razor, - Data = JToken.FromObject(new AddUsingsCodeActionParams() + Data = JsonSerializer.SerializeToElement(new AddUsingsCodeActionParams() { Namespace = "Test", Uri = new Uri("C:/path/to/Page.razor") @@ -369,7 +369,7 @@ public async Task ResolveCSharpCodeAction_ResolveMultipleCSharpProviders_FirstMa { Action = "A", Language = LanguageServerConstants.CodeActions.Languages.CSharp, - Data = JObject.FromObject(new CodeActionResolveParams() + Data = JsonSerializer.SerializeToElement(new CodeActionResolveParams() { RazorFileIdentifier = new VSTextDocumentIdentifier { @@ -402,7 +402,7 @@ public async Task ResolveCSharpCodeAction_ResolveMultipleCSharpProviders_SecondM { Action = "B", Language = LanguageServerConstants.CodeActions.Languages.Razor, - Data = JObject.FromObject(new CodeActionResolveParams() + Data = JsonSerializer.SerializeToElement(new CodeActionResolveParams() { RazorFileIdentifier = new VSTextDocumentIdentifier { @@ -438,7 +438,7 @@ public async Task ResolveCSharpCodeAction_ResolveMultipleLanguageProviders() { Action = "D", Language = LanguageServerConstants.CodeActions.Languages.CSharp, - Data = JObject.FromObject(new CodeActionResolveParams() + Data = JsonSerializer.SerializeToElement(new CodeActionResolveParams() { RazorFileIdentifier = new VSTextDocumentIdentifier { @@ -469,13 +469,13 @@ public async Task Handle_ResolveEditBasedCodeActionCommand() { Action = LanguageServerConstants.CodeActions.EditBasedCodeActionCommand, Language = LanguageServerConstants.CodeActions.Languages.Razor, - Data = JToken.FromObject(new WorkspaceEdit()) + Data = JsonSerializer.SerializeToElement(new WorkspaceEdit()) }; var request = new CodeAction() { Title = "Valid request", - Data = JToken.FromObject(requestParams) + Data = JsonSerializer.SerializeToElement(requestParams) }; var requestContext = CreateRazorRequestContext(documentContext: null); @@ -495,7 +495,7 @@ internal MockRazorCodeActionResolver(string action) Action = action; } - public Task ResolveAsync(JObject data, CancellationToken cancellationToken) + public Task ResolveAsync(JsonElement data, CancellationToken cancellationToken) { return Task.FromResult(new WorkspaceEdit()); } @@ -510,7 +510,7 @@ internal MockRazorNullCodeActionResolver(string action) Action = action; } - public Task ResolveAsync(JObject data, CancellationToken cancellationToken) + public Task ResolveAsync(JsonElement data, CancellationToken cancellationToken) { return SpecializedTasks.Null(); } diff --git a/src/Razor/test/Microsoft.AspNetCore.Razor.LanguageServer.Test/CodeActions/Html/DefaultHtmlCodeActionProviderTest.cs b/src/Razor/test/Microsoft.AspNetCore.Razor.LanguageServer.Test/CodeActions/Html/DefaultHtmlCodeActionProviderTest.cs index 52946f14798..e507f91b974 100644 --- a/src/Razor/test/Microsoft.AspNetCore.Razor.LanguageServer.Test/CodeActions/Html/DefaultHtmlCodeActionProviderTest.cs +++ b/src/Razor/test/Microsoft.AspNetCore.Razor.LanguageServer.Test/CodeActions/Html/DefaultHtmlCodeActionProviderTest.cs @@ -3,6 +3,7 @@ using System; using System.Collections.Immutable; +using System.Text.Json; using System.Threading; using System.Threading.Tasks; using Microsoft.AspNetCore.Razor.Language; @@ -16,7 +17,6 @@ using Microsoft.CodeAnalysis.Text; using Microsoft.VisualStudio.LanguageServer.Protocol; using Moq; -using Newtonsoft.Json.Linq; using Xunit; using Xunit.Abstractions; @@ -55,7 +55,7 @@ public async Task ProvideAsync_WrapsResolvableCodeActions() Assert.NotNull(providedCodeActions); var action = Assert.Single(providedCodeActions); Assert.Equal("Test", action.Name); - Assert.Equal("Html", ((JObject)action.Data!)["language"]!.ToString()); + Assert.Equal("Html", ((JsonElement)action.Data!).GetProperty("language").GetString()); } [Fact] diff --git a/src/Razor/test/Microsoft.AspNetCore.Razor.LanguageServer.Test/CodeActions/Html/DefaultHtmlCodeActionResolverTest.cs b/src/Razor/test/Microsoft.AspNetCore.Razor.LanguageServer.Test/CodeActions/Html/DefaultHtmlCodeActionResolverTest.cs index a95e8a3e73b..28e7aab6e3d 100644 --- a/src/Razor/test/Microsoft.AspNetCore.Razor.LanguageServer.Test/CodeActions/Html/DefaultHtmlCodeActionResolverTest.cs +++ b/src/Razor/test/Microsoft.AspNetCore.Razor.LanguageServer.Test/CodeActions/Html/DefaultHtmlCodeActionResolverTest.cs @@ -2,6 +2,8 @@ // Licensed under the MIT license. See License.txt in the project root for license information. using System; +using System.Text.Json; +using System.Text.Json.Nodes; using System.Threading; using System.Threading.Tasks; using Microsoft.AspNetCore.Razor.LanguageServer.CodeActions.Models; @@ -15,7 +17,6 @@ using Microsoft.CodeAnalysis.Testing; using Microsoft.VisualStudio.LanguageServer.Protocol; using Moq; -using Newtonsoft.Json.Linq; using Xunit; using Xunit.Abstractions; @@ -83,7 +84,7 @@ public async Task ResolveAsync_RemapsAndFixesEdits() var codeActionParams = new CodeActionResolveParams() { - Data = new JObject(), + Data = new JsonElement(), RazorFileIdentifier = new VSTextDocumentIdentifier { Uri = new Uri(documentPath) diff --git a/src/Razor/test/Microsoft.AspNetCore.Razor.LanguageServer.Test/CodeActions/Razor/CreateComponentCodeActionResolverTest.cs b/src/Razor/test/Microsoft.AspNetCore.Razor.LanguageServer.Test/CodeActions/Razor/CreateComponentCodeActionResolverTest.cs index a8e8e7d658e..f8477ef3335 100644 --- a/src/Razor/test/Microsoft.AspNetCore.Razor.LanguageServer.Test/CodeActions/Razor/CreateComponentCodeActionResolverTest.cs +++ b/src/Razor/test/Microsoft.AspNetCore.Razor.LanguageServer.Test/CodeActions/Razor/CreateComponentCodeActionResolverTest.cs @@ -3,6 +3,7 @@ using System; using System.Linq; +using System.Text.Json; using System.Threading.Tasks; using Microsoft.AspNetCore.Razor.Language; using Microsoft.AspNetCore.Razor.LanguageServer.CodeActions.Models; @@ -11,7 +12,6 @@ using Microsoft.CodeAnalysis; using Microsoft.CodeAnalysis.Razor.ProjectSystem; using Microsoft.CodeAnalysis.Razor.Workspaces; -using Newtonsoft.Json.Linq; using Xunit; using Xunit.Abstractions; @@ -26,7 +26,7 @@ public async Task Handle_MissingFile() { // Arrange var resolver = new CreateComponentCodeActionResolver(_emptyDocumentContextFactory, TestLanguageServerFeatureOptions.Instance); - var data = JObject.FromObject(new CreateComponentCodeActionParams() + var data = JsonSerializer.SerializeToElement(new CreateComponentCodeActionParams() { Uri = new Uri("c:/Test.razor"), Path = "c:/Another.razor", @@ -49,7 +49,7 @@ public async Task Handle_Unsupported() codeDocument.SetUnsupported(); var resolver = new CreateComponentCodeActionResolver(CreateDocumentContextFactory(documentPath, codeDocument), TestLanguageServerFeatureOptions.Instance); - var data = JObject.FromObject(new CreateComponentCodeActionParams() + var data = JsonSerializer.SerializeToElement(new CreateComponentCodeActionParams() { Uri = documentPath, Path = "c:/Another.razor", @@ -72,7 +72,7 @@ public async Task Handle_InvalidFileKind() codeDocument.SetFileKind(FileKinds.Legacy); var resolver = new CreateComponentCodeActionResolver(CreateDocumentContextFactory(documentPath, codeDocument), TestLanguageServerFeatureOptions.Instance); - var data = JObject.FromObject(new CreateComponentCodeActionParams() + var data = JsonSerializer.SerializeToElement(new CreateComponentCodeActionParams() { Uri = documentPath, Path = "c:/Another.razor", @@ -99,7 +99,7 @@ public async Task Handle_CreateComponent() Uri = documentPath, Path = "c:/Another.razor", }; - var data = JObject.FromObject(actionParams); + var data = JsonSerializer.SerializeToElement(actionParams); // Act var workspaceEdit = await resolver.ResolveAsync(data, default); @@ -130,7 +130,7 @@ @namespace Another.Namespace Uri = documentPath, Path = "c:/Another.razor", }; - var data = JObject.FromObject(actionParams); + var data = JsonSerializer.SerializeToElement(actionParams); // Act var workspaceEdit = await resolver.ResolveAsync(data, default); diff --git a/src/Razor/test/Microsoft.AspNetCore.Razor.LanguageServer.Test/CodeActions/Razor/ExtractToCodeBehindCodeActionProviderTest.cs b/src/Razor/test/Microsoft.AspNetCore.Razor.LanguageServer.Test/CodeActions/Razor/ExtractToCodeBehindCodeActionProviderTest.cs index 8077b01189d..524fb6746f2 100644 --- a/src/Razor/test/Microsoft.AspNetCore.Razor.LanguageServer.Test/CodeActions/Razor/ExtractToCodeBehindCodeActionProviderTest.cs +++ b/src/Razor/test/Microsoft.AspNetCore.Razor.LanguageServer.Test/CodeActions/Razor/ExtractToCodeBehindCodeActionProviderTest.cs @@ -4,6 +4,7 @@ using System; using System.Collections.Immutable; using System.Linq; +using System.Text.Json; using System.Threading.Tasks; using Microsoft.AspNetCore.Razor.Language; using Microsoft.AspNetCore.Razor.Language.Components; @@ -17,7 +18,6 @@ using Microsoft.CodeAnalysis.Text; using Microsoft.VisualStudio.LanguageServer.Protocol; using Moq; -using Newtonsoft.Json.Linq; using Xunit; using Xunit.Abstractions; @@ -221,9 +221,9 @@ public async Task Handle_InCodeDirective_SupportsFileCreationTrue_ReturnsResult( // Assert Assert.NotNull(commandOrCodeActionContainer); var codeAction = Assert.Single(commandOrCodeActionContainer); - var razorCodeActionResolutionParams = ((JObject)codeAction.Data!).ToObject(); + var razorCodeActionResolutionParams = ((JsonElement)codeAction.Data!).Deserialize(); Assert.NotNull(razorCodeActionResolutionParams); - var actionParams = ((JObject)razorCodeActionResolutionParams.Data).ToObject(); + var actionParams = ((JsonElement)razorCodeActionResolutionParams.Data).Deserialize(); Assert.NotNull(actionParams); Assert.Equal(removeSpan, TextSpan.FromBounds(actionParams.RemoveStart, actionParams.RemoveEnd)); @@ -265,9 +265,9 @@ public async Task Handle_AtEndOfCodeDirectiveWithNoSpace_ReturnsResult() // Assert Assert.NotNull(commandOrCodeActionContainer); var codeAction = Assert.Single(commandOrCodeActionContainer); - var razorCodeActionResolutionParams = ((JObject)codeAction.Data!).ToObject(); + var razorCodeActionResolutionParams = ((JsonElement)codeAction.Data!).Deserialize(); Assert.NotNull(razorCodeActionResolutionParams); - var actionParams = ((JObject)razorCodeActionResolutionParams.Data).ToObject(); + var actionParams = ((JsonElement)razorCodeActionResolutionParams.Data).Deserialize(); Assert.NotNull(actionParams); Assert.Equal(removeSpan, TextSpan.FromBounds(actionParams.RemoveStart, actionParams.RemoveEnd)); @@ -339,9 +339,9 @@ public async Task Handle_InFunctionsDirective_SupportsFileCreationTrue_ReturnsRe // Assert Assert.NotNull(commandOrCodeActionContainer); var codeAction = Assert.Single(commandOrCodeActionContainer); - var razorCodeActionResolutionParams = ((JObject)codeAction.Data!).ToObject(); + var razorCodeActionResolutionParams = ((JsonElement)codeAction.Data!).Deserialize(); Assert.NotNull(razorCodeActionResolutionParams); - var actionParams = ((JObject)razorCodeActionResolutionParams.Data).ToObject(); + var actionParams = ((JsonElement)razorCodeActionResolutionParams.Data).Deserialize(); Assert.NotNull(actionParams); Assert.Equal(removeSpan, TextSpan.FromBounds(actionParams.RemoveStart, actionParams.RemoveEnd)); diff --git a/src/Razor/test/Microsoft.AspNetCore.Razor.LanguageServer.Test/CodeActions/Razor/ExtractToCodeBehindCodeActionResolverTest.cs b/src/Razor/test/Microsoft.AspNetCore.Razor.LanguageServer.Test/CodeActions/Razor/ExtractToCodeBehindCodeActionResolverTest.cs index 30c20b2ac87..0c2156c1071 100644 --- a/src/Razor/test/Microsoft.AspNetCore.Razor.LanguageServer.Test/CodeActions/Razor/ExtractToCodeBehindCodeActionResolverTest.cs +++ b/src/Razor/test/Microsoft.AspNetCore.Razor.LanguageServer.Test/CodeActions/Razor/ExtractToCodeBehindCodeActionResolverTest.cs @@ -4,6 +4,7 @@ using System; using System.Collections.Generic; using System.Linq; +using System.Text.Json; using System.Threading.Tasks; using Microsoft.AspNetCore.Razor.Language; using Microsoft.AspNetCore.Razor.LanguageServer.CodeActions.Models; @@ -14,7 +15,6 @@ using Microsoft.CodeAnalysis.Razor.ProjectSystem; using Microsoft.CodeAnalysis.Razor.Protocol; using Microsoft.CodeAnalysis.Razor.Workspaces; -using Newtonsoft.Json.Linq; using Roslyn.Test.Utilities; using Xunit; using Xunit.Abstractions; @@ -41,7 +41,7 @@ public async Task Handle_MissingFile() { // Arrange var resolver = new ExtractToCodeBehindCodeActionResolver(_emptyDocumentContextFactory, TestLanguageServerFeatureOptions.Instance, _languageServer); - var data = JObject.FromObject(new ExtractToCodeBehindCodeActionParams() + var data = JsonSerializer.SerializeToElement(new ExtractToCodeBehindCodeActionParams() { Uri = new Uri("c:/Test.razor"), RemoveStart = 14, @@ -71,7 +71,7 @@ public async Task Handle_Unsupported() codeDocument.SetUnsupported(); var resolver = new ExtractToCodeBehindCodeActionResolver(CreateDocumentContextFactory(documentPath, codeDocument), TestLanguageServerFeatureOptions.Instance, _languageServer); - var data = JObject.FromObject(CreateExtractToCodeBehindCodeActionParams(new Uri("c:/Test.razor"), contents, "@code", "Test")); + var data = JsonSerializer.SerializeToElement(CreateExtractToCodeBehindCodeActionParams(new Uri("c:/Test.razor"), contents, "@code", "Test")); // Act var workspaceEdit = await resolver.ResolveAsync(data, default); @@ -93,7 +93,7 @@ public async Task Handle_InvalidFileKind() codeDocument.SetFileKind(FileKinds.Legacy); var resolver = new ExtractToCodeBehindCodeActionResolver(CreateDocumentContextFactory(documentPath, codeDocument), TestLanguageServerFeatureOptions.Instance, _languageServer); - var data = JObject.FromObject(CreateExtractToCodeBehindCodeActionParams(new Uri("c:/Test.razor"), contents, "@code", "Test")); + var data = JsonSerializer.SerializeToElement(CreateExtractToCodeBehindCodeActionParams(new Uri("c:/Test.razor"), contents, "@code", "Test")); // Act var workspaceEdit = await resolver.ResolveAsync(data, default); @@ -119,7 +119,7 @@ public async Task Handle_ExtractCodeBlock() var resolver = new ExtractToCodeBehindCodeActionResolver(CreateDocumentContextFactory(documentPath, codeDocument), TestLanguageServerFeatureOptions.Instance, _languageServer); var actionParams = CreateExtractToCodeBehindCodeActionParams(documentPath, contents, "@code", @namespace); - var data = JObject.FromObject(actionParams); + var data = JsonSerializer.SerializeToElement(actionParams); // Act var workspaceEdit = await resolver.ResolveAsync(data, default); @@ -181,7 +181,7 @@ public async Task Handle_ExtractCodeBlock2() var resolver = new ExtractToCodeBehindCodeActionResolver(CreateDocumentContextFactory(documentPath, codeDocument), TestLanguageServerFeatureOptions.Instance, _languageServer); var actionParams = CreateExtractToCodeBehindCodeActionParams(documentPath, contents, "@code", @namespace); - var data = JObject.FromObject(actionParams); + var data = JsonSerializer.SerializeToElement(actionParams); // Act var workspaceEdit = await resolver.ResolveAsync(data, default); @@ -251,7 +251,7 @@ private void M() var resolver = new ExtractToCodeBehindCodeActionResolver(CreateDocumentContextFactory(documentPath, codeDocument), TestLanguageServerFeatureOptions.Instance, _languageServer); var actionParams = CreateExtractToCodeBehindCodeActionParams(documentPath, contents, "@code", @namespace); - var data = JObject.FromObject(actionParams); + var data = JsonSerializer.SerializeToElement(actionParams); // Act var workspaceEdit = await resolver.ResolveAsync(data, default); @@ -331,7 +331,7 @@ private void M() var resolver = new ExtractToCodeBehindCodeActionResolver(CreateDocumentContextFactory(documentPath, codeDocument), TestLanguageServerFeatureOptions.Instance, _languageServer); var actionParams = CreateExtractToCodeBehindCodeActionParams(documentPath, contents, "@code", @namespace); - var data = JObject.FromObject(actionParams); + var data = JsonSerializer.SerializeToElement(actionParams); // Act var workspaceEdit = await resolver.ResolveAsync(data, default); @@ -413,7 +413,7 @@ private void M() var resolver = new ExtractToCodeBehindCodeActionResolver(CreateDocumentContextFactory(documentPath, codeDocument), TestLanguageServerFeatureOptions.Instance, _languageServer); var actionParams = CreateExtractToCodeBehindCodeActionParams(documentPath, contents, "@code", @namespace); - var data = JObject.FromObject(actionParams); + var data = JsonSerializer.SerializeToElement(actionParams); // Act var workspaceEdit = await resolver.ResolveAsync(data, default); @@ -483,7 +483,7 @@ public async Task Handle_ExtractFunctionsBlock() var resolver = new ExtractToCodeBehindCodeActionResolver(CreateDocumentContextFactory(documentPath, codeDocument), TestLanguageServerFeatureOptions.Instance, _languageServer); var actionParams = CreateExtractToCodeBehindCodeActionParams(documentPath, contents, "@functions", @namespace); - var data = JObject.FromObject(actionParams); + var data = JsonSerializer.SerializeToElement(actionParams); // Act var workspaceEdit = await resolver.ResolveAsync(data, default); @@ -545,7 +545,7 @@ @using System.Diagnostics var resolver = new ExtractToCodeBehindCodeActionResolver(CreateDocumentContextFactory(documentPath, codeDocument), TestLanguageServerFeatureOptions.Instance, _languageServer); var actionParams = CreateExtractToCodeBehindCodeActionParams(documentPath, contents, "@code", @namespace); - var data = JObject.FromObject(actionParams); + var data = JsonSerializer.SerializeToElement(actionParams); // Act var workspaceEdit = await resolver.ResolveAsync(data, default); @@ -609,7 +609,7 @@ public async Task Handle_ExtractCodeBlockWithDirectives() var resolver = new ExtractToCodeBehindCodeActionResolver(CreateDocumentContextFactory(documentPath, codeDocument), TestLanguageServerFeatureOptions.Instance, _languageServer); var actionParams = CreateExtractToCodeBehindCodeActionParams(documentPath, contents, "@code", @namespace); - var data = JObject.FromObject(actionParams); + var data = JsonSerializer.SerializeToElement(actionParams); // Act var workspaceEdit = await resolver.ResolveAsync(data, default); @@ -677,7 +677,7 @@ public async Task Handle_ExtractCodeBlock_CallsRoslyn() var resolver = new ExtractToCodeBehindCodeActionResolver(CreateDocumentContextFactory(documentPath, codeDocument), TestLanguageServerFeatureOptions.Instance, languageServer); var actionParams = CreateExtractToCodeBehindCodeActionParams(documentPath, contents, "@code", @namespace); - var data = JObject.FromObject(actionParams); + var data = JsonSerializer.SerializeToElement(actionParams); // Act var workspaceEdit = await resolver.ResolveAsync(data, default); diff --git a/src/Razor/test/Microsoft.AspNetCore.Razor.LanguageServer.Test/Completion/RazorCompletionListProviderTest.cs b/src/Razor/test/Microsoft.AspNetCore.Razor.LanguageServer.Test/Completion/RazorCompletionListProviderTest.cs index e21f59116c0..cd809b718d3 100644 --- a/src/Razor/test/Microsoft.AspNetCore.Razor.LanguageServer.Test/Completion/RazorCompletionListProviderTest.cs +++ b/src/Razor/test/Microsoft.AspNetCore.Razor.LanguageServer.Test/Completion/RazorCompletionListProviderTest.cs @@ -6,6 +6,7 @@ using System.Collections.Generic; using System.Collections.Immutable; using System.Linq; +using System.Text.Json; using System.Threading.Tasks; using Microsoft.AspNetCore.Razor.Language; using Microsoft.AspNetCore.Razor.Language.Components; @@ -15,7 +16,6 @@ using Microsoft.CodeAnalysis.Razor.Tooltip; using Microsoft.CodeAnalysis.Testing; using Microsoft.VisualStudio.LanguageServer.Protocol; -using Newtonsoft.Json; using Xunit; using Xunit.Abstractions; using static Microsoft.AspNetCore.Razor.Language.CommonMetadata; @@ -153,7 +153,7 @@ public void TryConvert_Directive_SerializationDoesNotThrow() RazorCompletionListProvider.TryConvert(completionItem, _clientCapabilities, out var converted); // Act & Assert - JsonConvert.SerializeObject(converted); + JsonSerializer.Serialize(converted); } [Fact] @@ -164,7 +164,7 @@ public void TryConvert_DirectiveAttributeTransition_SerializationDoesNotThrow() RazorCompletionListProvider.TryConvert(completionItem, _clientCapabilities, out var converted); // Act & Assert - JsonConvert.SerializeObject(converted); + JsonSerializer.Serialize(converted); } [Fact] @@ -216,7 +216,7 @@ public void TryConvert_MarkupTransition_SerializationDoesNotThrow() RazorCompletionListProvider.TryConvert(completionItem, _clientCapabilities, out var converted); // Act & Assert - JsonConvert.SerializeObject(converted); + JsonSerializer.Serialize(converted); } [Fact] diff --git a/src/Razor/test/Microsoft.AspNetCore.Razor.LanguageServer.Test/Completion/RazorCompletionResolveEndpointTest.cs b/src/Razor/test/Microsoft.AspNetCore.Razor.LanguageServer.Test/Completion/RazorCompletionResolveEndpointTest.cs index 932edc5b4d8..8586d5b9635 100644 --- a/src/Razor/test/Microsoft.AspNetCore.Razor.LanguageServer.Test/Completion/RazorCompletionResolveEndpointTest.cs +++ b/src/Razor/test/Microsoft.AspNetCore.Razor.LanguageServer.Test/Completion/RazorCompletionResolveEndpointTest.cs @@ -4,14 +4,13 @@ #nullable disable using System; -using System.IO; +using System.Text.Json; using System.Linq; using System.Threading; using System.Threading.Tasks; using Microsoft.AspNetCore.Razor.LanguageServer.Test; using Microsoft.AspNetCore.Razor.Test.Common.LanguageServer; using Microsoft.VisualStudio.LanguageServer.Protocol; -using Newtonsoft.Json; using Xunit; using Xunit.Abstractions; @@ -149,11 +148,8 @@ public async Task Handle_MergedCompletionListFindsProperCompletionList_Resolves( private VSInternalCompletionItem ConvertToBridgedItem(CompletionItem completionItem) { - using var textWriter = new StringWriter(); - ProtocolSerializer.Instance.Serialize(textWriter, completionItem); - var stringBuilder = textWriter.GetStringBuilder(); - using var jsonReader = new JsonTextReader(new StringReader(stringBuilder.ToString())); - var bridgedItem = ProtocolSerializer.Instance.Deserialize(jsonReader); + var serialized = JsonSerializer.Serialize(completionItem, SerializerOptions); + var bridgedItem = JsonSerializer.Deserialize(serialized, SerializerOptions); return bridgedItem; } diff --git a/src/Razor/test/Microsoft.AspNetCore.Razor.LanguageServer.Test/DefaultRazorConfigurationServiceTest.cs b/src/Razor/test/Microsoft.AspNetCore.Razor.LanguageServer.Test/DefaultRazorConfigurationServiceTest.cs index c8820a8259a..29048394810 100644 --- a/src/Razor/test/Microsoft.AspNetCore.Razor.LanguageServer.Test/DefaultRazorConfigurationServiceTest.cs +++ b/src/Razor/test/Microsoft.AspNetCore.Razor.LanguageServer.Test/DefaultRazorConfigurationServiceTest.cs @@ -3,13 +3,13 @@ #nullable disable +using System.Text.Json.Nodes; using System.Threading; using System.Threading.Tasks; using Microsoft.AspNetCore.Razor.LanguageServer.Hosting; using Microsoft.AspNetCore.Razor.Test.Common.LanguageServer; using Microsoft.VisualStudio.LanguageServer.Protocol; using Moq; -using Newtonsoft.Json.Linq; using Xunit; using Xunit.Abstractions; @@ -28,8 +28,8 @@ public async Task GetLatestOptionsAsync_ReturnsExpectedOptions() { "format": { - "enable": "false", - "codeBlockBraceOnNextLine": "true" + "enable": false, + "codeBlockBraceOnNextLine": true } } @@ -38,8 +38,8 @@ public async Task GetLatestOptionsAsync_ReturnsExpectedOptions() var htmlJsonString = """ { - "format": "true", - "autoClosingTags": "false" + "format": true, + "autoClosingTags": false } """; @@ -50,7 +50,7 @@ public async Task GetLatestOptionsAsync_ReturnsExpectedOptions() """; - var result = new JObject[] { JObject.Parse(razorJsonString), JObject.Parse(htmlJsonString), JObject.Parse(vsEditorJsonString) }; + var result = new JsonObject[] { JsonNode.Parse(razorJsonString).AsObject(), JsonNode.Parse(htmlJsonString).AsObject(), JsonNode.Parse(vsEditorJsonString).AsObject() }; var languageServer = GetLanguageServer(result); var configurationService = new DefaultRazorConfigurationService(languageServer, LoggerFactory); @@ -65,7 +65,7 @@ public async Task GetLatestOptionsAsync_ReturnsExpectedOptions() public async Task GetLatestOptionsAsync_EmptyResponse_ReturnsNull() { // Arrange - var languageServer = GetLanguageServer(result: null); + var languageServer = GetLanguageServer(result: null); var configurationService = new DefaultRazorConfigurationService(languageServer, LoggerFactory); // Act @@ -79,7 +79,7 @@ public async Task GetLatestOptionsAsync_EmptyResponse_ReturnsNull() public async Task GetLatestOptionsAsync_ClientRequestThrows_ReturnsNull() { // Arrange - var languageServer = GetLanguageServer(result: null, shouldThrow: true); + var languageServer = GetLanguageServer(result: null, shouldThrow: true); var configurationService = new DefaultRazorConfigurationService(languageServer, LoggerFactory); // Act @@ -98,16 +98,16 @@ public void BuildOptions_VSCodeOptionsOnly_ReturnsExpected() var razorJsonString = """ { "format": { - "enable": "false", - "codeBlockBraceOnNextLine": "true" + "enable": false, + "codeBlockBraceOnNextLine": true } } """; var htmlJsonString = """ { - "format": "true", - "autoClosingTags": "false" + "format": true, + "autoClosingTags": false } """; @@ -117,7 +117,7 @@ public void BuildOptions_VSCodeOptionsOnly_ReturnsExpected() """; // Act - var result = new JObject[] { JObject.Parse(razorJsonString), JObject.Parse(htmlJsonString), JObject.Parse(vsEditorJsonString) }; + var result = new JsonObject[] { JsonNode.Parse(razorJsonString).AsObject(), JsonNode.Parse(htmlJsonString).AsObject(), JsonNode.Parse(vsEditorJsonString).AsObject() }; var languageServer = GetLanguageServer(result); var configurationService = new DefaultRazorConfigurationService(languageServer, LoggerFactory); var options = configurationService.BuildOptions(result); @@ -146,19 +146,19 @@ public void BuildOptions_VSOptionsOnly_ReturnsExpected() { "ClientSpaceSettings": { "IndentSize": 8, - "IndentWithTabs": "true" + "IndentWithTabs": true }, "AdvancedSettings": { - "FormatOnType": "false", - "AutoClosingTags": "false", - "AutoInsertAttributeQuotes": "false", - "CommitElementsWithSpace": "false" + "FormatOnType": false, + "AutoClosingTags": false, + "AutoInsertAttributeQuotes": false, + "CommitElementsWithSpace": false } } """; // Act - var result = new JObject[] { JObject.Parse(razorJsonString), JObject.Parse(htmlJsonString), JObject.Parse(vsEditorJsonString) }; + var result = new JsonObject[] { JsonNode.Parse(razorJsonString).AsObject(), JsonNode.Parse(htmlJsonString).AsObject(), JsonNode.Parse(vsEditorJsonString).AsObject() }; var languageServer = GetLanguageServer(result); var configurationService = new DefaultRazorConfigurationService(languageServer, LoggerFactory); var options = configurationService.BuildOptions(result); @@ -184,7 +184,7 @@ public void BuildOptions_MalformedOptions() ".Trim(); var htmlJsonString = @" { - ""format"": """", + ""format"": """" } ".Trim(); var vsEditorJsonString = @" @@ -197,7 +197,7 @@ public void BuildOptions_MalformedOptions() ".Trim(); // Act - var result = new JObject[] { JObject.Parse(razorJsonString), JObject.Parse(htmlJsonString), JObject.Parse(vsEditorJsonString) }; + var result = new JsonObject[] { JsonNode.Parse(razorJsonString).AsObject(), JsonNode.Parse(htmlJsonString).AsObject(), JsonNode.Parse(vsEditorJsonString).AsObject() }; var languageServer = GetLanguageServer(result); var configurationService = new DefaultRazorConfigurationService(languageServer, LoggerFactory); var options = configurationService.BuildOptions(result); @@ -213,7 +213,7 @@ public void BuildOptions_NullOptions() var expectedOptions = RazorLSPOptions.Default; // Act - var result = new JObject[] { null, null, null }; + var result = new JsonObject[] { null, null, null }; var languageServer = GetLanguageServer(result); var configurationService = new DefaultRazorConfigurationService(languageServer, LoggerFactory); var options = configurationService.BuildOptions(result); diff --git a/src/Razor/test/Microsoft.AspNetCore.Razor.LanguageServer.Test/Definition/DefinitionEndpointDelegationTest.cs b/src/Razor/test/Microsoft.AspNetCore.Razor.LanguageServer.Test/Definition/DefinitionEndpointDelegationTest.cs index 80ab00ce291..550b7671f2d 100644 --- a/src/Razor/test/Microsoft.AspNetCore.Razor.LanguageServer.Test/Definition/DefinitionEndpointDelegationTest.cs +++ b/src/Razor/test/Microsoft.AspNetCore.Razor.LanguageServer.Test/Definition/DefinitionEndpointDelegationTest.cs @@ -3,6 +3,8 @@ using System; using System.Collections.Generic; +using System.IO; +using System.Linq; using System.Threading.Tasks; using Microsoft.AspNetCore.Razor.Language; using Microsoft.CodeAnalysis.Razor.ProjectSystem; @@ -88,12 +90,11 @@ public async Task Handle_SingleServer_CSharp_MetadataReference() Assert.EndsWith("String.cs", location.Uri.ToString()); // Note: The location is in a generated C# "metadata-as-source" file, which has a different - // number of using directives in .NET Framework vs. .NET Core. So, the line numbers are different. -#if NETFRAMEWORK - Assert.Equal(24, location.Range.Start.Line); -#else - Assert.Equal(21, location.Range.Start.Line); -#endif + // number of using directives in .NET Framework vs. .NET Core, so rather than relying on line + // numbers we do some vague notion of actual navigation and test the actual source line that + // the user would see. + var line = File.ReadLines(location.Uri.LocalPath).ElementAt(location.Range.Start.Line); + Assert.Contains("public sealed class String", line); } [Theory] diff --git a/src/Razor/test/Microsoft.AspNetCore.Razor.LanguageServer.Test/GeneratedDocumentPublisherTest.cs b/src/Razor/test/Microsoft.AspNetCore.Razor.LanguageServer.Test/GeneratedDocumentPublisherTest.cs index 4115b7905bb..89da1223b80 100644 --- a/src/Razor/test/Microsoft.AspNetCore.Razor.LanguageServer.Test/GeneratedDocumentPublisherTest.cs +++ b/src/Razor/test/Microsoft.AspNetCore.Razor.LanguageServer.Test/GeneratedDocumentPublisherTest.cs @@ -8,6 +8,7 @@ using Microsoft.AspNetCore.Razor.Test.Common.ProjectSystem; using Microsoft.AspNetCore.Razor.Test.Common.Workspaces; using Microsoft.CodeAnalysis.Razor.ProjectSystem; +using Microsoft.CodeAnalysis.Razor.Workspaces; using Microsoft.CodeAnalysis.Text; using Xunit; using Xunit.Abstractions; @@ -96,7 +97,7 @@ public void PublishCSharp_SecondTime_PublishesSourceTextDifferences() var updateRequest = _serverClient.UpdateRequests.Last(); Assert.Equal("/path/to/file.razor", updateRequest.HostDocumentFilePath); var textChange = Assert.Single(updateRequest.Changes); - Assert.Equal(change, textChange); + Assert.Equal(change.ToRazorTextChange(), textChange); Assert.Equal(124, updateRequest.HostDocumentVersion); } @@ -120,7 +121,7 @@ public void PublishHtml_SecondTime_PublishesSourceTextDifferences() var updateRequest = _serverClient.UpdateRequests.Last(); Assert.Equal("/path/to/file.razor", updateRequest.HostDocumentFilePath); var textChange = Assert.Single(updateRequest.Changes); - Assert.Equal(change, textChange); + Assert.Equal(change.ToRazorTextChange(), textChange); Assert.Equal(124, updateRequest.HostDocumentVersion); } diff --git a/src/Razor/test/Microsoft.AspNetCore.Razor.LanguageServer.Test/ProtocolSerializer.cs b/src/Razor/test/Microsoft.AspNetCore.Razor.LanguageServer.Test/ProtocolSerializer.cs deleted file mode 100644 index 5be7f54eb80..00000000000 --- a/src/Razor/test/Microsoft.AspNetCore.Razor.LanguageServer.Test/ProtocolSerializer.cs +++ /dev/null @@ -1,21 +0,0 @@ -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT license. See License.txt in the project root for license information. - -using Microsoft.VisualStudio.LanguageServer.Protocol; -using Newtonsoft.Json; - -namespace Microsoft.AspNetCore.Razor.LanguageServer.Test; - -internal static class ProtocolSerializer -{ - public static JsonSerializer Instance { get; } = CreateSerializer(); - - private static JsonSerializer CreateSerializer() - { - var serializer = new JsonSerializer(); - serializer.AddVSInternalExtensionConverters(); - serializer.AddVSExtensionConverters(); - - return serializer; - } -} diff --git a/src/Razor/test/Microsoft.AspNetCore.Razor.LanguageServer.Test/Serialization/PlatformAgnosticClientCapabilitiesJsonConverterTest.cs b/src/Razor/test/Microsoft.AspNetCore.Razor.LanguageServer.Test/Serialization/PlatformAgnosticClientCapabilitiesJsonConverterTest.cs index 62217a425df..8d2f84072f0 100644 --- a/src/Razor/test/Microsoft.AspNetCore.Razor.LanguageServer.Test/Serialization/PlatformAgnosticClientCapabilitiesJsonConverterTest.cs +++ b/src/Razor/test/Microsoft.AspNetCore.Razor.LanguageServer.Test/Serialization/PlatformAgnosticClientCapabilitiesJsonConverterTest.cs @@ -3,10 +3,9 @@ #nullable disable -using System.IO; using System.Linq; +using System.Text.Json; using Microsoft.VisualStudio.LanguageServer.Protocol; -using Newtonsoft.Json; using Xunit; namespace Microsoft.AspNetCore.Razor.LanguageServer.Serialization; @@ -76,10 +75,9 @@ public void ReadJson_ReadsValues() } } }"; - var stringReader = new StringReader(rawJson); // Act - var capabilities = JsonSerializer.CreateDefault().Deserialize(new JsonTextReader(stringReader)); + var capabilities = JsonSerializer.Deserialize(rawJson); // Assert Assert.True(capabilities.Workspace.ApplyEdit); diff --git a/src/Razor/test/Microsoft.AspNetCore.Razor.LanguageServer.Test/TestClient.cs b/src/Razor/test/Microsoft.AspNetCore.Razor.LanguageServer.Test/TestClient.cs index ab474d70847..c99ebf5cd55 100644 --- a/src/Razor/test/Microsoft.AspNetCore.Razor.LanguageServer.Test/TestClient.cs +++ b/src/Razor/test/Microsoft.AspNetCore.Razor.LanguageServer.Test/TestClient.cs @@ -6,8 +6,8 @@ using System.Threading; using System.Threading.Tasks; using Microsoft.AspNetCore.Razor.LanguageServer.Hosting; +using Microsoft.CodeAnalysis.Razor.Protocol; using Microsoft.VisualStudio.LanguageServer.Protocol; -using Newtonsoft.Json.Linq; namespace Microsoft.AspNetCore.Razor.LanguageServer; @@ -32,11 +32,6 @@ public object GetService(Type serviceType) throw new NotImplementedException(); } - public bool TryGetRequest(long id, out string method, out TaskCompletionSource pendingTask) - { - throw new NotImplementedException(); - } - public Task SendNotificationAsync(string methodName, CancellationToken cancellationToken) { _requests.Add(new RequestPair(methodName, Params: null)); diff --git a/src/Razor/test/Microsoft.AspNetCore.Razor.Test.Common.Tooling/LanguageServer/CSharpTestLspServer.cs b/src/Razor/test/Microsoft.AspNetCore.Razor.Test.Common.Tooling/LanguageServer/CSharpTestLspServer.cs index 80002fcb73c..2b20c842cf4 100644 --- a/src/Razor/test/Microsoft.AspNetCore.Razor.Test.Common.Tooling/LanguageServer/CSharpTestLspServer.cs +++ b/src/Razor/test/Microsoft.AspNetCore.Razor.Test.Common.Tooling/LanguageServer/CSharpTestLspServer.cs @@ -27,7 +27,7 @@ public sealed class CSharpTestLspServer : IAsyncDisposable private readonly JsonRpc _clientRpc; private readonly JsonRpc _serverRpc; - private readonly JsonMessageFormatter _clientMessageFormatter; + private readonly SystemTextJsonFormatter _clientMessageFormatter; private readonly SystemTextJsonFormatter _serverMessageFormatter; private readonly HeaderDelimitedMessageHandler _clientMessageHandler; private readonly HeaderDelimitedMessageHandler _serverMessageHandler; @@ -54,7 +54,7 @@ private CSharpTestLspServer( ExceptionStrategy = ExceptionProcessing.ISerializable, }; - _clientMessageFormatter = CreateNewtonsoftMessageFormatter(); + _clientMessageFormatter = CreateSystemTextJsonMessageFormatter(languageServerFactory); _clientMessageHandler = new HeaderDelimitedMessageHandler(clientStream, clientStream, _clientMessageFormatter); _clientRpc = new JsonRpc(_clientMessageHandler) { @@ -82,14 +82,6 @@ static SystemTextJsonFormatter CreateSystemTextJsonMessageFormatter(AbstractRazo return messageFormatter; } - static JsonMessageFormatter CreateNewtonsoftMessageFormatter() - { - var messageFormatter = new JsonMessageFormatter(); - VSInternalExtensionUtilities.AddVSInternalExtensionConverters(messageFormatter.JsonSerializer); - - return messageFormatter; - } - static IRazorLanguageServerTarget CreateLanguageServer( JsonRpc serverRpc, JsonSerializerOptions options, diff --git a/src/Razor/test/Microsoft.AspNetCore.Razor.Test.Common.Tooling/LanguageServer/LanguageServerTestBase.cs b/src/Razor/test/Microsoft.AspNetCore.Razor.Test.Common.Tooling/LanguageServer/LanguageServerTestBase.cs index f8566ecb6af..b8a4e215aad 100644 --- a/src/Razor/test/Microsoft.AspNetCore.Razor.Test.Common.Tooling/LanguageServer/LanguageServerTestBase.cs +++ b/src/Razor/test/Microsoft.AspNetCore.Razor.Test.Common.Tooling/LanguageServer/LanguageServerTestBase.cs @@ -4,6 +4,7 @@ using System; using System.Collections.Generic; using System.Collections.Immutable; +using System.Text.Json; using System.Threading; using System.Threading.Tasks; using Microsoft.AspNetCore.Mvc.Razor.Extensions; @@ -22,18 +23,29 @@ using Microsoft.CodeAnalysis.Razor.Workspaces; using Microsoft.CodeAnalysis.Text; using Microsoft.CommonLanguageServerProtocol.Framework; +using Microsoft.VisualStudio.LanguageServer.Protocol; using Moq; using Xunit.Abstractions; namespace Microsoft.AspNetCore.Razor.Test.Common.LanguageServer; -public abstract class LanguageServerTestBase(ITestOutputHelper testOutput) : ToolingTestBase(testOutput) +public abstract class LanguageServerTestBase : ToolingTestBase { - private ThrowingRazorSpanMappingService? _spanMappingService; - private LSPFilePathService? _filePathService; + private protected IRazorSpanMappingService SpanMappingService { get; } + private protected IFilePathService FilePathService { get; } + private protected JsonSerializerOptions SerializerOptions { get; } - private protected IRazorSpanMappingService SpanMappingService => _spanMappingService ??= new(); - private protected IFilePathService FilePathService => _filePathService ??= new(TestLanguageServerFeatureOptions.Instance); + protected LanguageServerTestBase(ITestOutputHelper testOutput) + : base(testOutput) + { + SpanMappingService = new ThrowingRazorSpanMappingService(); + + SerializerOptions = new JsonSerializerOptions(); + // In its infinite wisdom, the LSP client has a public method that takes Newtonsoft.Json types, but an internal method that takes System.Text.Json types. + typeof(VSInternalExtensionUtilities).GetMethod("AddVSInternalExtensionConverters", System.Reflection.BindingFlags.Static | System.Reflection.BindingFlags.NonPublic)!.Invoke(null, [SerializerOptions]); + + FilePathService = new LSPFilePathService(TestLanguageServerFeatureOptions.Instance); + } private protected TestProjectSnapshotManager CreateProjectSnapshotManager() => CreateProjectSnapshotManager(ProjectEngineFactories.DefaultProvider); diff --git a/src/Razor/test/Microsoft.VisualStudio.LanguageServer.ContainedLanguage.Test/DefaultFallbackCapabilitiesFilterResolverTest.cs b/src/Razor/test/Microsoft.VisualStudio.LanguageServer.ContainedLanguage.Test/DefaultFallbackCapabilitiesFilterResolverTest.cs deleted file mode 100644 index ecd4ff346a7..00000000000 --- a/src/Razor/test/Microsoft.VisualStudio.LanguageServer.ContainedLanguage.Test/DefaultFallbackCapabilitiesFilterResolverTest.cs +++ /dev/null @@ -1,813 +0,0 @@ -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the MIT license. See License.txt in the project root for license information. - -#nullable disable - -using Microsoft.AspNetCore.Razor.Test.Common; -using Microsoft.VisualStudio.LanguageServer.Protocol; -using Newtonsoft.Json.Linq; -using Xunit; -using Xunit.Abstractions; - -namespace Microsoft.VisualStudio.LanguageServer.ContainedLanguage; - -public class DefaultFallbackCapabilitiesFilterResolverTest : ToolingTestBase -{ - private static readonly DefaultFallbackCapabilitiesFilterResolver s_resolver = new(); - - public DefaultFallbackCapabilitiesFilterResolverTest(ITestOutputHelper testOutput) - : base(testOutput) - { - } - - [Fact] - public void Resolve_Implementation_ReturnsTrue() - { - // Arrange - var methodName = Methods.TextDocumentImplementationName; - var capabilities = new ServerCapabilities() - { - ImplementationProvider = true, - }; - var jobjectCapabilities = JObject.FromObject(capabilities); - var filter = s_resolver.Resolve(methodName); - - // Act - var result = filter(jobjectCapabilities); - - // Assert - Assert.True(result); - } - - [Fact] - public void Resolve_ImplementationOptions_ReturnsTrue() - { - // Arrange - var methodName = Methods.TextDocumentImplementationName; - var capabilities = new ServerCapabilities() - { - ImplementationProvider = new ImplementationOptions(), - }; - var jobjectCapabilities = JObject.FromObject(capabilities); - var filter = s_resolver.Resolve(methodName); - - // Act - var result = filter(jobjectCapabilities); - - // Assert - Assert.True(result); - } - - [Fact] - public void Resolve_TypeDefinition_ReturnsTrue() - { - // Arrange - var methodName = Methods.TextDocumentTypeDefinitionName; - var capabilities = new ServerCapabilities() - { - TypeDefinitionProvider = true, - }; - var jobjectCapabilities = JObject.FromObject(capabilities); - var filter = s_resolver.Resolve(methodName); - - // Act - var result = filter(jobjectCapabilities); - - // Assert - Assert.True(result); - } - - [Fact] - public void Resolve_TypeDefinitionOptions_ReturnsTrue() - { - // Arrange - var methodName = Methods.TextDocumentTypeDefinitionName; - var capabilities = new ServerCapabilities() - { - TypeDefinitionProvider = new TypeDefinitionOptions(), - }; - var jobjectCapabilities = JObject.FromObject(capabilities); - var filter = s_resolver.Resolve(methodName); - - // Act - var result = filter(jobjectCapabilities); - - // Assert - Assert.True(result); - } - - [Fact] - public void Resolve_Reference_ReturnsTrue() - { - // Arrange - var methodName = Methods.TextDocumentReferencesName; - var capabilities = new ServerCapabilities() - { - ReferencesProvider = true, - }; - var jobjectCapabilities = JObject.FromObject(capabilities); - var filter = s_resolver.Resolve(methodName); - - // Act - var result = filter(jobjectCapabilities); - - // Assert - Assert.True(result); - } - - [Fact] - public void Resolve_ReferenceOptions_ReturnsTrue() - { - // Arrange - var methodName = Methods.TextDocumentReferencesName; - var capabilities = new ServerCapabilities() - { - ReferencesProvider = new ReferenceOptions(), - }; - var jobjectCapabilities = JObject.FromObject(capabilities); - var filter = s_resolver.Resolve(methodName); - - // Act - var result = filter(jobjectCapabilities); - - // Assert - Assert.True(result); - } - - [Fact] - public void Resolve_Rename_ReturnsTrue() - { - // Arrange - var methodName = Methods.TextDocumentRenameName; - var capabilities = new ServerCapabilities() - { - RenameProvider = true, - }; - var jobjectCapabilities = JObject.FromObject(capabilities); - var filter = s_resolver.Resolve(methodName); - - // Act - var result = filter(jobjectCapabilities); - - // Assert - Assert.True(result); - } - - [Fact] - public void Resolve_RenameOptions_ReturnsTrue() - { - // Arrange - var methodName = Methods.TextDocumentRenameName; - var capabilities = new ServerCapabilities() - { - RenameProvider = new RenameOptions(), - }; - var jobjectCapabilities = JObject.FromObject(capabilities); - var filter = s_resolver.Resolve(methodName); - - // Act - var result = filter(jobjectCapabilities); - - // Assert - Assert.True(result); - } - - [Fact] - public void Resolve_SignatureHelp_ReturnsTrue() - { - // Arrange - var methodName = Methods.TextDocumentSignatureHelpName; - var capabilities = new ServerCapabilities() - { - SignatureHelpProvider = new SignatureHelpOptions(), - }; - var jobjectCapabilities = JObject.FromObject(capabilities); - var filter = s_resolver.Resolve(methodName); - - // Act - var result = filter(jobjectCapabilities); - - // Assert - Assert.True(result); - } - - [Fact] - public void Resolve_WillSave_ReturnsTrue() - { - // Arrange - var methodName = Methods.TextDocumentWillSaveName; - var capabilities = new ServerCapabilities() - { - TextDocumentSync = new TextDocumentSyncOptions() - { - WillSave = true, - }, - }; - var jobjectCapabilities = JObject.FromObject(capabilities); - var filter = s_resolver.Resolve(methodName); - - // Act - var result = filter(jobjectCapabilities); - - // Assert - Assert.True(result); - } - - [Fact] - public void Resolve_WillSaveWaitUntil_ReturnsTrue() - { - // Arrange - var methodName = Methods.TextDocumentWillSaveWaitUntilName; - var capabilities = new ServerCapabilities() - { - TextDocumentSync = new TextDocumentSyncOptions() - { - WillSaveWaitUntil = true, - }, - }; - var jobjectCapabilities = JObject.FromObject(capabilities); - var filter = s_resolver.Resolve(methodName); - - // Act - var result = filter(jobjectCapabilities); - - // Assert - Assert.True(result); - } - - [Fact] - public void Resolve_RangeFormatting_ReturnsTrue() - { - // Arrange - var methodName = Methods.TextDocumentRangeFormattingName; - var capabilities = new ServerCapabilities() - { - DocumentRangeFormattingProvider = true, - }; - var jobjectCapabilities = JObject.FromObject(capabilities); - var filter = s_resolver.Resolve(methodName); - - // Act - var result = filter(jobjectCapabilities); - - // Assert - Assert.True(result); - } - - [Fact] - public void Resolve_RangeFormattingOptions_ReturnsTrue() - { - // Arrange - var methodName = Methods.TextDocumentRangeFormattingName; - var capabilities = new ServerCapabilities() - { - DocumentRangeFormattingProvider = new DocumentRangeFormattingOptions(), - }; - var jobjectCapabilities = JObject.FromObject(capabilities); - var filter = s_resolver.Resolve(methodName); - - // Act - var result = filter(jobjectCapabilities); - - // Assert - Assert.True(result); - } - - [Fact] - public void Resolve_WorkspaceSymbol_ReturnsTrue() - { - // Arrange - var methodName = Methods.WorkspaceSymbolName; - var capabilities = new ServerCapabilities() - { - WorkspaceSymbolProvider = true, - }; - var jobjectCapabilities = JObject.FromObject(capabilities); - var filter = s_resolver.Resolve(methodName); - - // Act - var result = filter(jobjectCapabilities); - - // Assert - Assert.True(result); - } - - [Fact] - public void Resolve_WorkspaceSymbolOptions_ReturnsTrue() - { - // Arrange - var methodName = Methods.WorkspaceSymbolName; - var capabilities = new ServerCapabilities() - { - WorkspaceSymbolProvider = new WorkspaceSymbolOptions(), - }; - var jobjectCapabilities = JObject.FromObject(capabilities); - var filter = s_resolver.Resolve(methodName); - - // Act - var result = filter(jobjectCapabilities); - - // Assert - Assert.True(result); - } - - [Fact] - public void Resolve_OnTypeFormatting_ReturnsTrue() - { - // Arrange - var methodName = Methods.TextDocumentOnTypeFormattingName; - var capabilities = new ServerCapabilities() - { - DocumentOnTypeFormattingProvider = new DocumentOnTypeFormattingOptions(), - }; - var jobjectCapabilities = JObject.FromObject(capabilities); - var filter = s_resolver.Resolve(methodName); - - // Act - var result = filter(jobjectCapabilities); - - // Assert - Assert.True(result); - } - - [Fact] - public void Resolve_Formatting_ReturnsTrue() - { - // Arrange - var methodName = Methods.TextDocumentFormattingName; - var capabilities = new ServerCapabilities() - { - DocumentFormattingProvider = true, - }; - var jobjectCapabilities = JObject.FromObject(capabilities); - var filter = s_resolver.Resolve(methodName); - - // Act - var result = filter(jobjectCapabilities); - - // Assert - Assert.True(result); - } - - [Fact] - public void Resolve_FormattingOptions_ReturnsTrue() - { - // Arrange - var methodName = Methods.TextDocumentFormattingName; - var capabilities = new ServerCapabilities() - { - DocumentFormattingProvider = new DocumentFormattingOptions(), - }; - var jobjectCapabilities = JObject.FromObject(capabilities); - var filter = s_resolver.Resolve(methodName); - - // Act - var result = filter(jobjectCapabilities); - - // Assert - Assert.True(result); - } - - [Fact] - public void Resolve_Hover_ReturnsTrue() - { - // Arrange - var methodName = Methods.TextDocumentHoverName; - var capabilities = new ServerCapabilities() - { - HoverProvider = true, - }; - var jobjectCapabilities = JObject.FromObject(capabilities); - var filter = s_resolver.Resolve(methodName); - - // Act - var result = filter(jobjectCapabilities); - - // Assert - Assert.True(result); - } - - [Fact] - public void Resolve_HoverOptions_ReturnsTrue() - { - // Arrange - var methodName = Methods.TextDocumentHoverName; - var capabilities = new ServerCapabilities() - { - HoverProvider = new HoverOptions(), - }; - var jobjectCapabilities = JObject.FromObject(capabilities); - var filter = s_resolver.Resolve(methodName); - - // Act - var result = filter(jobjectCapabilities); - - // Assert - Assert.True(result); - } - - [Fact] - public void Resolve_CodeAction_ReturnsTrue() - { - // Arrange - var methodName = Methods.TextDocumentCodeActionName; - var capabilities = new ServerCapabilities() - { - CodeActionProvider = true, - }; - var jobjectCapabilities = JObject.FromObject(capabilities); - var filter = s_resolver.Resolve(methodName); - - // Act - var result = filter(jobjectCapabilities); - - // Assert - Assert.True(result); - } - - [Fact] - public void Resolve_CodeActionOptions_ReturnsTrue() - { - // Arrange - var methodName = Methods.TextDocumentCodeActionName; - var capabilities = new ServerCapabilities() - { - CodeActionProvider = new CodeActionOptions(), - }; - var jobjectCapabilities = JObject.FromObject(capabilities); - var filter = s_resolver.Resolve(methodName); - - // Act - var result = filter(jobjectCapabilities); - - // Assert - Assert.True(result); - } - - [Fact] - public void Resolve_CodeLens_ReturnsTrue() - { - // Arrange - var methodName = Methods.CodeLensResolveName; - var capabilities = new ServerCapabilities() - { - CodeLensProvider = new CodeLensOptions(), - }; - var jobjectCapabilities = JObject.FromObject(capabilities); - var filter = s_resolver.Resolve(methodName); - - // Act - var result = filter(jobjectCapabilities); - - // Assert - Assert.True(result); - } - - [Fact] - public void Resolve_DocumentColor_ReturnsTrue() - { - // Arrange - var methodName = Methods.TextDocumentDocumentColorName; - var capabilities = new ServerCapabilities() - { - DocumentColorProvider = true, - }; - var jobjectCapabilities = JObject.FromObject(capabilities); - var filter = s_resolver.Resolve(methodName); - - // Act - var result = filter(jobjectCapabilities); - - // Assert - Assert.True(result); - } - - [Fact] - public void Resolve_DocumentColorOptions_ReturnsTrue() - { - // Arrange - var methodName = Methods.TextDocumentDocumentColorName; - var capabilities = new ServerCapabilities() - { - DocumentColorProvider = new DocumentColorOptions(), - }; - var jobjectCapabilities = JObject.FromObject(capabilities); - var filter = s_resolver.Resolve(methodName); - - // Act - var result = filter(jobjectCapabilities); - - // Assert - Assert.True(result); - } - - [Fact] - public void Resolve_Completion_ReturnsTrue() - { - // Arrange - var methodName = Methods.TextDocumentCompletionName; - var capabilities = new ServerCapabilities() - { - CompletionProvider = new CompletionOptions(), - }; - var jobjectCapabilities = JObject.FromObject(capabilities); - var filter = s_resolver.Resolve(methodName); - - // Act - var result = filter(jobjectCapabilities); - - // Assert - Assert.True(result); - } - - [Fact] - public void Resolve_CompletionResolve_ReturnsTrue() - { - // Arrange - var methodName = Methods.TextDocumentCompletionResolveName; - var capabilities = new ServerCapabilities() - { - CompletionProvider = new CompletionOptions() - { - ResolveProvider = true, - }, - }; - var jobjectCapabilities = JObject.FromObject(capabilities); - var filter = s_resolver.Resolve(methodName); - - // Act - var result = filter(jobjectCapabilities); - - // Assert - Assert.True(result); - } - - [Fact] - public void Resolve_Definition_ReturnsTrue() - { - // Arrange - var methodName = Methods.TextDocumentDefinitionName; - var capabilities = new ServerCapabilities() - { - DefinitionProvider = true, - }; - var jobjectCapabilities = JObject.FromObject(capabilities); - var filter = s_resolver.Resolve(methodName); - - // Act - var result = filter(jobjectCapabilities); - - // Assert - Assert.True(result); - } - - [Fact] - public void Resolve_DefinitionOptions_ReturnsTrue() - { - // Arrange - var methodName = Methods.TextDocumentDefinitionName; - var capabilities = new ServerCapabilities() - { - DefinitionProvider = new DefinitionOptions(), - }; - var jobjectCapabilities = JObject.FromObject(capabilities); - var filter = s_resolver.Resolve(methodName); - - // Act - var result = filter(jobjectCapabilities); - - // Assert - Assert.True(result); - } - - [Fact] - public void Resolve_Highlight_ReturnsTrue() - { - // Arrange - var methodName = Methods.TextDocumentDocumentHighlightName; - var capabilities = new ServerCapabilities() - { - DocumentHighlightProvider = true, - }; - var jobjectCapabilities = JObject.FromObject(capabilities); - var filter = s_resolver.Resolve(methodName); - - // Act - var result = filter(jobjectCapabilities); - - // Assert - Assert.True(result); - } - - [Fact] - public void Resolve_HighlightOptions_ReturnsTrue() - { - // Arrange - var methodName = Methods.TextDocumentDocumentHighlightName; - var capabilities = new ServerCapabilities() - { - DocumentHighlightProvider = new DocumentHighlightOptions(), - }; - var jobjectCapabilities = JObject.FromObject(capabilities); - var filter = s_resolver.Resolve(methodName); - - // Act - var result = filter(jobjectCapabilities); - - // Assert - Assert.True(result); - } - - [Fact] - public void Resolve_MSReference_ReturnsTrue() - { - // Arrange - var methodName = VSInternalMethods.DocumentReferencesName; - var capabilities = new VSInternalServerCapabilities() - { - MSReferencesProvider = true, - }; - var jobjectCapabilities = JObject.FromObject(capabilities); - var filter = s_resolver.Resolve(methodName); - - // Act - var result = filter(jobjectCapabilities); - - // Assert - Assert.True(result); - } - - [Fact] - public void Resolve_ProjectContext_ReturnsTrue() - { - // Arrange - var methodName = VSMethods.GetProjectContextsName; - var capabilities = new VSServerCapabilities() - { - ProjectContextProvider = true, - }; - var jobjectCapabilities = JObject.FromObject(capabilities); - var filter = s_resolver.Resolve(methodName); - - // Act - var result = filter(jobjectCapabilities); - - // Assert - Assert.True(result); - } - - [Fact] - public void Resolve_CodeActionResolve_ReturnsTrue() - { - // Arrange - var methodName = Methods.CodeActionResolveName; - var capabilities = new ServerCapabilities() - { - CodeActionProvider = new CodeActionOptions() - { - ResolveProvider = true, - }, - }; - var jobjectCapabilities = JObject.FromObject(capabilities); - var filter = s_resolver.Resolve(methodName); - - // Act - var result = filter(jobjectCapabilities); - - // Assert - Assert.True(result); - } - - [Fact] - public void Resolve_OnAutoInsert_ReturnsTrue() - { - // Arrange - var methodName = VSInternalMethods.OnAutoInsertName; - var capabilities = new VSInternalServerCapabilities() - { - OnAutoInsertProvider = new VSInternalDocumentOnAutoInsertOptions(), - }; - var jobjectCapabilities = JObject.FromObject(capabilities); - var filter = s_resolver.Resolve(methodName); - - // Act - var result = filter(jobjectCapabilities); - - // Assert - Assert.True(result); - } - - [Fact] - public void Resolve_PullDiagnostics_ReturnsTrue() - { - // Arrange - var methodName = VSInternalMethods.DocumentPullDiagnosticName; - var capabilities = new VSInternalServerCapabilities() - { - SupportsDiagnosticRequests = true, - }; - var jobjectCapabilities = JObject.FromObject(capabilities); - var filter = s_resolver.Resolve(methodName); - - // Act - var result = filter(jobjectCapabilities); - - // Assert - Assert.True(result); - } - - [Fact] - public void Resolve_ProjectContexts_ReturnsTrue() - { - // Arrange - var methodName = VSMethods.GetProjectContextsName; - var capabilities = new VSInternalServerCapabilities() - { - ProjectContextProvider = true - }; - - var jobjectCapabilities = JObject.FromObject(capabilities); - var filter = s_resolver.Resolve(methodName); - - // Act - var result = filter(jobjectCapabilities); - - // Assert - Assert.True(result); - } - - [Fact] - public void Resolve_DocumentSymbol_ReturnsTrue() - { - // Arrange - var methodName = Methods.TextDocumentDocumentSymbolName; - var capabilities = new ServerCapabilities() - { - DocumentSymbolProvider = true - }; - - var jobjectCapabilities = JObject.FromObject(capabilities); - var filter = s_resolver.Resolve(methodName); - - // Act - var result = filter(jobjectCapabilities); - - // Assert - Assert.True(result); - } - - [Theory] - [InlineData(Methods.TextDocumentImplementationName)] - [InlineData(Methods.TextDocumentTypeDefinitionName)] - [InlineData(Methods.TextDocumentReferencesName)] - [InlineData(Methods.TextDocumentRenameName)] - [InlineData(Methods.TextDocumentSignatureHelpName)] - [InlineData(Methods.TextDocumentWillSaveName)] - [InlineData(Methods.TextDocumentWillSaveWaitUntilName)] - [InlineData(Methods.TextDocumentRangeFormattingName)] - [InlineData(Methods.WorkspaceSymbolName)] - [InlineData(Methods.TextDocumentOnTypeFormattingName)] - [InlineData(Methods.TextDocumentFormattingName)] - [InlineData(Methods.TextDocumentHoverName)] - [InlineData(Methods.TextDocumentCodeActionName)] - [InlineData(Methods.TextDocumentCodeLensName)] - [InlineData(Methods.TextDocumentDocumentColorName)] - [InlineData(Methods.TextDocumentCompletionName)] - [InlineData(Methods.TextDocumentCompletionResolveName)] - [InlineData(Methods.TextDocumentDefinitionName)] - [InlineData(Methods.TextDocumentDocumentHighlightName)] - [InlineData(Methods.CodeActionResolveName)] - [InlineData(VSInternalMethods.DocumentReferencesName)] - [InlineData(VSInternalMethods.OnAutoInsertName)] - [InlineData(VSInternalMethods.DocumentPullDiagnosticName)] - [InlineData(VSInternalMethods.WorkspacePullDiagnosticName)] - public void Resolve_NotPresent_ReturnsFalse(string methodName) - { - // Arrange - var emptyCapabilities = new VSServerCapabilities(); - var jobjectCapabilities = JObject.FromObject(emptyCapabilities); - var filter = s_resolver.Resolve(methodName); - - // Act - var result = filter(jobjectCapabilities); - - // Assert - Assert.False(result); - } - - [Fact] - public void Resolve_UnknownMethod_ReturnsTrue() - { - // Arrange - var methodName = "razor/languageQuery"; - var emptyCapabilities = new VSServerCapabilities(); - var jobjectCapabilities = JObject.FromObject(emptyCapabilities); - var filter = s_resolver.Resolve(methodName); - - // Act - var result = filter(jobjectCapabilities); - - // Assert - Assert.True(result); - } -} diff --git a/src/Razor/test/Microsoft.VisualStudio.LanguageServices.Razor.Test/LanguageClient/DefaultLSPRequestInvokerTest.cs b/src/Razor/test/Microsoft.VisualStudio.LanguageServices.Razor.Test/LanguageClient/DefaultLSPRequestInvokerTest.cs index 8b506b0fae6..22e91532d80 100644 --- a/src/Razor/test/Microsoft.VisualStudio.LanguageServices.Razor.Test/LanguageClient/DefaultLSPRequestInvokerTest.cs +++ b/src/Razor/test/Microsoft.VisualStudio.LanguageServices.Razor.Test/LanguageClient/DefaultLSPRequestInvokerTest.cs @@ -15,16 +15,8 @@ namespace Microsoft.VisualStudio.Razor.LanguageClient; -public class DefaultLSPRequestInvokerTest : ToolingTestBase +public class DefaultLSPRequestInvokerTest(ITestOutputHelper testOutput) : ToolingTestBase(testOutput) { - private readonly FallbackCapabilitiesFilterResolver _capabilitiesResolver; - - public DefaultLSPRequestInvokerTest(ITestOutputHelper testOutput) - : base(testOutput) - { - _capabilitiesResolver = new DefaultFallbackCapabilitiesFilterResolver(); - } - [Fact] public async Task ReinvokeRequestOnServerAsync_InvokesRazorLanguageClient() { @@ -36,7 +28,7 @@ public async Task ReinvokeRequestOnServerAsync_InvokesRazorLanguageClient() called = true; Assert.Equal(expectedMethod, method); }); - var requestInvoker = new DefaultLSPRequestInvoker(broker, _capabilitiesResolver); + var requestInvoker = new DefaultLSPRequestInvoker(broker); // Act await requestInvoker.ReinvokeRequestOnServerAsync( @@ -57,7 +49,7 @@ public async Task ReinvokeRequestOnServerAsync_InvokesHtmlLanguageClient() called = true; Assert.Equal(expectedMethod, method); }); - var requestInvoker = new DefaultLSPRequestInvoker(broker, _capabilitiesResolver); + var requestInvoker = new DefaultLSPRequestInvoker(broker); // Act await requestInvoker.ReinvokeRequestOnServerAsync( @@ -78,7 +70,7 @@ public async Task ReinvokeRequestOnServerAsync_InvokesCSharpLanguageClient() called = true; Assert.Equal(expectedMethod, method); }); - var requestInvoker = new DefaultLSPRequestInvoker(broker, _capabilitiesResolver); + var requestInvoker = new DefaultLSPRequestInvoker(broker); // Act await requestInvoker.ReinvokeRequestOnServerAsync( @@ -99,7 +91,7 @@ public async Task CustomRequestServerAsync_InvokesRazorLanguageClient() called = true; Assert.Equal(expectedMethod, method); }); - var requestInvoker = new DefaultLSPRequestInvoker(broker, _capabilitiesResolver); + var requestInvoker = new DefaultLSPRequestInvoker(broker); // Act await requestInvoker.ReinvokeRequestOnServerAsync( @@ -120,7 +112,7 @@ public async Task CustomRequestServerAsync_InvokesHtmlLanguageClient() called = true; Assert.Equal(expectedMethod, method); }); - var requestInvoker = new DefaultLSPRequestInvoker(broker, _capabilitiesResolver); + var requestInvoker = new DefaultLSPRequestInvoker(broker); // Act await requestInvoker.ReinvokeRequestOnServerAsync( @@ -141,7 +133,7 @@ public async Task CustomRequestServerAsync_InvokesCSharpLanguageClient() called = true; Assert.Equal(expectedMethod, method); }); - var requestInvoker = new DefaultLSPRequestInvoker(broker, _capabilitiesResolver); + var requestInvoker = new DefaultLSPRequestInvoker(broker); // Act await requestInvoker.ReinvokeRequestOnServerAsync( diff --git a/src/Razor/test/Microsoft.VisualStudio.LanguageServices.Razor.Test/LanguageClient/DocumentMapping/DefaultLSPDocumentMappingProviderTest.cs b/src/Razor/test/Microsoft.VisualStudio.LanguageServices.Razor.Test/LanguageClient/DocumentMapping/DefaultLSPDocumentMappingProviderTest.cs index 9bff59b2086..79adf17c94f 100644 --- a/src/Razor/test/Microsoft.VisualStudio.LanguageServices.Razor.Test/LanguageClient/DocumentMapping/DefaultLSPDocumentMappingProviderTest.cs +++ b/src/Razor/test/Microsoft.VisualStudio.LanguageServices.Razor.Test/LanguageClient/DocumentMapping/DefaultLSPDocumentMappingProviderTest.cs @@ -14,7 +14,6 @@ using Microsoft.VisualStudio.LanguageServer.Protocol; using Microsoft.VisualStudio.Text; using Moq; -using Newtonsoft.Json.Linq; using Xunit; using Xunit.Abstractions; @@ -63,7 +62,6 @@ public async Task RazorMapToDocumentRangeAsync_InvokesLanguageServer() It.IsAny(), LanguageServerConstants.RazorMapToDocumentRangesEndpoint, RazorLSPConstants.RazorLanguageServerName, - It.IsAny>(), It.IsAny(), It.IsAny())) .ReturnsAsync(new ReinvocationResponse("TestLanguageClient", response)); diff --git a/src/Razor/test/Microsoft.VisualStudio.LanguageServices.Razor.Test/LanguageClient/RazorCustomMessageTargetTest.cs b/src/Razor/test/Microsoft.VisualStudio.LanguageServices.Razor.Test/LanguageClient/RazorCustomMessageTargetTest.cs index 0d60f3dd68f..5fafd0e5df1 100644 --- a/src/Razor/test/Microsoft.VisualStudio.LanguageServices.Razor.Test/LanguageClient/RazorCustomMessageTargetTest.cs +++ b/src/Razor/test/Microsoft.VisualStudio.LanguageServices.Razor.Test/LanguageClient/RazorCustomMessageTargetTest.cs @@ -26,7 +26,6 @@ using Microsoft.VisualStudio.Text; using Microsoft.VisualStudio.Threading; using Moq; -using Newtonsoft.Json.Linq; using Xunit; using Xunit.Abstractions; @@ -116,7 +115,7 @@ public async Task UpdateCSharpBuffer_UpdatesDocument() { HostDocumentFilePath = "C:/path/to/file.razor", HostDocumentVersion = 1337, - Changes = Array.Empty(), + Changes = [], }; // Act @@ -170,7 +169,7 @@ public async Task UpdateCSharpBuffer_UpdatesCorrectDocument() ProjectKeyId = projectKey2.Id, HostDocumentFilePath = "C:/path/to/file.razor", HostDocumentVersion = 1337, - Changes = Array.Empty(), + Changes = [], }; // Act @@ -262,7 +261,6 @@ async IAsyncEnumerable> .Setup(invoker => invoker.ReinvokeRequestOnMultipleServersAsync>( _textBuffer, Methods.TextDocumentCodeActionName, - It.IsAny>(), It.IsAny(), It.IsAny())) .Returns(expectedResults); @@ -345,7 +343,6 @@ async IAsyncEnumerable> GetExpectedRe .Setup(invoker => invoker.ReinvokeRequestOnMultipleServersAsync( It.IsAny(), Methods.CodeActionResolveName, - It.IsAny>(), It.IsAny(), It.IsAny())) .Returns(expectedResponses); @@ -512,7 +509,6 @@ public async Task ProvideSemanticTokensAsync_ContainsRange_ReturnsSemanticTokens _textBuffer, It.IsAny(), RazorLSPConstants.RazorCSharpLanguageServerName, - It.IsAny>(), It.IsAny(), It.IsAny())) .ReturnsAsync(new ReinvocationResponse("languageClient", expectedCSharpResults)); @@ -591,7 +587,6 @@ public async Task ProvideSemanticTokensAsync_EmptyRange_ReturnsNoSemanticTokens( _textBuffer, It.IsAny(), RazorLSPConstants.RazorCSharpLanguageServerName, - It.IsAny>(), It.IsAny(), It.IsAny())) .ReturnsAsync(new ReinvocationResponse("languageClient", expectedCSharpResults)); diff --git a/src/Razor/test/Microsoft.VisualStudio.LanguageServices.Razor.Test/LanguageClient/TestLSPRequestInvoker.cs b/src/Razor/test/Microsoft.VisualStudio.LanguageServices.Razor.Test/LanguageClient/TestLSPRequestInvoker.cs index 09dc4118c64..27bb265f77d 100644 --- a/src/Razor/test/Microsoft.VisualStudio.LanguageServices.Razor.Test/LanguageClient/TestLSPRequestInvoker.cs +++ b/src/Razor/test/Microsoft.VisualStudio.LanguageServices.Razor.Test/LanguageClient/TestLSPRequestInvoker.cs @@ -60,6 +60,7 @@ public override IAsyncEnumerable> ReinvokeRequestOnMu throw new NotImplementedException(); } + [Obsolete] public override IAsyncEnumerable> ReinvokeRequestOnMultipleServersAsync( ITextBuffer textBuffer, string method, @@ -79,6 +80,7 @@ public override Task> ReinvokeRequestOnServerAsync> ReinvokeRequestOnServerAsync( string method, string languageServerName, @@ -105,6 +107,7 @@ public async override Task> ReinvokeRequestOnServerAs return default; } + [Obsolete] public override Task> ReinvokeRequestOnServerAsync( ITextBuffer textBuffer, string method,