Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Update Newtonsoft.Json dependency to 13.0.1 #687

Merged
merged 5 commits into from
Aug 16, 2021
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 2 additions & 2 deletions Directory.Build.props
Original file line number Diff line number Diff line change
Expand Up @@ -29,8 +29,8 @@
<PackageReference Include="Microsoft.CodeAnalysis.NetAnalyzers" Version="5.0.3" PrivateAssets="all" />
<PackageReference Include="Microsoft.NETFramework.ReferenceAssemblies" Version="1.0.2" PrivateAssets="all" />
<PackageReference Include="Microsoft.SourceLink.GitHub" Version="1.0.0" PrivateAssets="all" />
<PackageReference Include="Nerdbank.GitVersioning" Version="3.4.220" PrivateAssets="all" />
<PackageReference Include="Microsoft.Net.Compilers.Toolset" Version="3.10.0" PrivateAssets="all" />
<PackageReference Include="Nerdbank.GitVersioning" Version="3.4.231" PrivateAssets="all" />
<PackageReference Include="Microsoft.Net.Compilers.Toolset" Version="3.11.0" PrivateAssets="all" />
<PackageReference Include="StyleCop.Analyzers" Version="1.2.0-beta.312" PrivateAssets="all" />
</ItemGroup>

Expand Down
2 changes: 1 addition & 1 deletion global.json
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
{
"sdk": {
"version": "5.0.202",
"version": "5.0.400",
"rollForward": "patch",
"allowPrerelease": false
}
Expand Down
4 changes: 4 additions & 0 deletions src/StreamJsonRpc/AwaitExtensions.cs
Original file line number Diff line number Diff line change
Expand Up @@ -20,7 +20,9 @@ internal static class AwaitExtensions
/// <returns>The value to await on.</returns>
internal static SynchronizationContextAwaiter GetAwaiter(this SynchronizationContext synchronizationContext)
{
#pragma warning disable VSTHRD110 // Observe result of async calls
Requires.NotNull(synchronizationContext, nameof(synchronizationContext));
#pragma warning restore VSTHRD110 // Observe result of async calls
return new SynchronizationContextAwaiter(synchronizationContext);
}

Expand All @@ -42,7 +44,9 @@ internal struct SynchronizationContextAwaiter : INotifyCompletion
/// <param name="synchronizationContext">The <see cref="SynchronizationContext"/> to switch the caller's context to.</param>
internal SynchronizationContextAwaiter(SynchronizationContext synchronizationContext)
{
#pragma warning disable VSTHRD110 // Observe result of async calls
Requires.NotNull(synchronizationContext, nameof(synchronizationContext));
#pragma warning restore VSTHRD110 // Observe result of async calls
this.synchronizationContext = synchronizationContext;
}

Expand Down
47 changes: 24 additions & 23 deletions src/StreamJsonRpc/JsonMessageFormatter.cs
Original file line number Diff line number Diff line change
Expand Up @@ -402,14 +402,14 @@ public JsonRpcMessage Deserialize(JToken json)
return
json["method"] != null ? this.ReadRequest(json) :
json["error"]?.Type == JTokenType.Null ? this.ReadResult(json) :
json["error"]?.Type != JTokenType.Null ? (JsonRpcMessage)this.ReadError(json) :
json["error"] is { Type: not JTokenType.Null } ? this.ReadError(json) :
throw this.CreateProtocolNonComplianceException(json);
case 2:
this.VerifyProtocolCompliance(json.Value<string>("jsonrpc") == "2.0", json, $"\"jsonrpc\" property must be set to \"2.0\", or set {nameof(this.ProtocolVersion)} to 1.0 mode.");
return
json["method"] != null ? this.ReadRequest(json) :
json["result"] != null ? this.ReadResult(json) :
json["error"] != null ? (JsonRpcMessage)this.ReadError(json) :
json["error"] != null ? this.ReadError(json) :
throw this.CreateProtocolNonComplianceException(json);
default:
throw Assumes.NotReachable();
Expand Down Expand Up @@ -649,7 +649,7 @@ private JToken TokenizeUserData(Type? declaredType, object? value)
{
using var jsonWriter = new JTokenWriter();
converter.WriteJson(jsonWriter, value, this.JsonSerializer);
return jsonWriter.Token;
return jsonWriter.Token!;
}

return JToken.FromObject(value, this.JsonSerializer);
Expand Down Expand Up @@ -679,14 +679,14 @@ private JsonRpcRequest ReadRequest(JToken json)

// We leave arguments as JTokens at this point, so that we can try deserializing them
// to more precise .NET types as required by the method we're invoking.
JToken args = json["params"];
JToken? args = json["params"];
object? arguments =
args is JObject argsObject ? PartiallyParseNamedArguments(argsObject) :
args is JArray argsArray ? (object)PartiallyParsePositionalArguments(argsArray) :
null;

// If method is $/progress, get the progress instance from the dictionary and call Report
string method = json.Value<string>("method");
string? method = json.Value<string>("method");

if (this.formatterProgressTracker != null && string.Equals(method, MessageFormatterProgressTracker.ProgressRequestSpecialMethod, StringComparison.Ordinal))
{
Expand All @@ -703,7 +703,7 @@ private JsonRpcRequest ReadRequest(JToken json)
null;

MessageFormatterProgressTracker.ProgressParamInformation? progressInfo = null;
if (this.formatterProgressTracker.TryGetProgressObject(progressId.Value<long>(), out progressInfo))
if (progressId is object && this.formatterProgressTracker.TryGetProgressObject(progressId.Value<long>(), out progressInfo))
{
object? typedValue = value?.ToObject(progressInfo.ValueType, this.JsonSerializer);
progressInfo.InvokeReport(typedValue);
Expand Down Expand Up @@ -732,7 +732,7 @@ private JsonRpcResult ReadResult(JToken json)
Requires.NotNull(json, nameof(json));

RequestId id = this.ExtractRequestId(json);
JToken result = json["result"];
JToken? result = json["result"];

return new JsonRpcResult(this.JsonSerializer)
{
Expand All @@ -746,7 +746,8 @@ private JsonRpcError ReadError(JToken json)
Requires.NotNull(json, nameof(json));

RequestId id = this.ExtractRequestId(json);
JToken error = json["error"];
JToken? error = json["error"];
Assumes.NotNull(error); // callers should have verified this already.

return new JsonRpcError
{
Expand All @@ -762,7 +763,7 @@ private JsonRpcError ReadError(JToken json)

private RequestId ExtractRequestId(JToken json)
{
JToken idToken = json["id"];
JToken? idToken = json["id"];
if (idToken == null)
{
throw this.CreateProtocolNonComplianceException(json, "\"id\" property missing.");
Expand Down Expand Up @@ -843,7 +844,7 @@ public override bool TryGetArgumentByNameOrIndex(string? name, int position, Typ
this.formatter.deserializingMessageWithId = this.RequestId;
try
{
value = token?.ToObject(typeHint, this.formatter.JsonSerializer);
value = token?.ToObject(typeHint!, this.formatter.JsonSerializer); // Null typeHint is allowed (https://github.com/JamesNK/Newtonsoft.Json/pull/2562)
}
finally
{
Expand Down Expand Up @@ -890,7 +891,7 @@ public override T GetResult<T>()

try
{
return result.ToObject<T>(this.jsonSerializer);
return result.ToObject<T>(this.jsonSerializer)!;
}
catch (Exception exception)
{
Expand Down Expand Up @@ -949,7 +950,7 @@ internal JsonArrayPool(ArrayPool<T> arrayPool)

public T[] Rent(int minimumLength) => this.arrayPool.Rent(minimumLength);

public void Return(T[] array) => this.arrayPool.Return(array);
public void Return(T[]? array) => this.arrayPool.Return(array);
}

/// <summary>
Expand All @@ -971,9 +972,9 @@ public override object ReadJson(JsonReader reader, Type objectType, object? exis
throw new NotSupportedException();
}

public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer)
public override void WriteJson(JsonWriter writer, object? value, JsonSerializer serializer)
{
long progressId = this.formatter.FormatterProgressTracker.GetTokenForProgress(value);
long progressId = this.formatter.FormatterProgressTracker.GetTokenForProgress(value!);
writer.WriteValue(progressId);
}
}
Expand Down Expand Up @@ -1050,7 +1051,7 @@ internal AsyncEnumerableConsumerConverter(JsonMessageFormatter jsonMessageFormat
}
}

public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer)
public override void WriteJson(JsonWriter writer, object? value, JsonSerializer serializer)
{
throw new NotSupportedException();
}
Expand All @@ -1060,7 +1061,7 @@ private IAsyncEnumerable<T> ReadJson<T>(JsonReader reader, JsonSerializer serial
#pragma warning restore VSTHRD200 // Use "Async" suffix in names of methods that return an awaitable type.
{
JToken enumJToken = JToken.Load(reader);
JToken handle = enumJToken[MessageFormatterEnumerableTracker.TokenPropertyName];
JToken? handle = enumJToken[MessageFormatterEnumerableTracker.TokenPropertyName];
IReadOnlyList<T>? prefetchedItems = enumJToken[MessageFormatterEnumerableTracker.ValuesPropertyName]?.ToObject<IReadOnlyList<T>>(serializer);

return this.formatter.EnumerableTracker.CreateEnumerableProxy(handle, prefetchedItems);
Expand Down Expand Up @@ -1088,9 +1089,9 @@ internal AsyncEnumerableGeneratorConverter(JsonMessageFormatter jsonMessageForma
throw new NotSupportedException();
}

public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer)
public override void WriteJson(JsonWriter writer, object? value, JsonSerializer serializer)
{
Type? iface = TrackerHelpers<IAsyncEnumerable<int>>.FindInterfaceImplementedBy(value.GetType());
Type? iface = TrackerHelpers<IAsyncEnumerable<int>>.FindInterfaceImplementedBy(value!.GetType());
Assumes.NotNull(iface);
MethodInfo genericMethod = WriteJsonOpenGenericMethod.MakeGenericMethod(iface.GenericTypeArguments[0]);
try
Expand Down Expand Up @@ -1284,9 +1285,9 @@ internal JsonConverterFormatter(JsonSerializer serializer)
this.serializer = serializer;
}

public object Convert(object value, Type type) => ((JToken)value).ToObject(type, this.serializer);
public object? Convert(object value, Type type) => ((JToken)value).ToObject(type, this.serializer);

public object Convert(object value, TypeCode typeCode)
public object? Convert(object value, TypeCode typeCode)
{
return typeCode switch
{
Expand Down Expand Up @@ -1317,7 +1318,7 @@ public object Convert(object value, TypeCode typeCode)

public float ToSingle(object value) => ((JToken)value).ToObject<float>(this.serializer);

public string ToString(object value) => ((JToken)value).ToObject<string>(this.serializer);
public string? ToString(object value) => ((JToken)value).ToObject<string>(this.serializer);

public ushort ToUInt16(object value) => ((JToken)value).ToObject<ushort>(this.serializer);

Expand Down Expand Up @@ -1358,7 +1359,7 @@ internal ExceptionConverter(JsonMessageFormatter formatter)

if (reader.TokenType == JsonToken.PropertyName)
{
string name = (string)reader.Value;
string name = (string)reader.Value!;
if (!reader.Read())
{
throw new EndOfStreamException();
Expand Down Expand Up @@ -1419,7 +1420,7 @@ public override JsonContract ResolveContract(Type type)
continue;
}

if (this.formatter.TryGetImplicitlyMarshaledJsonConverter(property.PropertyType, out RpcMarshalableImplicitConverter? converter))
if (property.PropertyType is object && this.formatter.TryGetImplicitlyMarshaledJsonConverter(property.PropertyType, out RpcMarshalableImplicitConverter? converter))
{
property.Converter = converter;
}
Expand Down
2 changes: 2 additions & 0 deletions src/StreamJsonRpc/JsonRpcExtensions.cs
Original file line number Diff line number Diff line change
Expand Up @@ -160,7 +160,9 @@ internal static (IReadOnlyList<T> Elements, bool Finished) TearOffPrefetchedElem
return (enumerable as RpcEnumerable<T>)?.TearOffPrefetchedElements() ?? (Array.Empty<T>(), false);
}

#pragma warning disable VSTHRD200 // Use "Async" suffix for async methods
private static RpcEnumerable<T> GetRpcEnumerable<T>(IAsyncEnumerable<T> enumerable) => enumerable as RpcEnumerable<T> ?? new RpcEnumerable<T>(enumerable);
#pragma warning restore VSTHRD200 // Use "Async" suffix for async methods

#pragma warning disable CA1001 // Types that own disposable fields should be disposable
private class RpcEnumerable<T> : IAsyncEnumerable<T>, IRpcEnumerable
Expand Down
4 changes: 2 additions & 2 deletions src/StreamJsonRpc/RequestIdJsonConverter.cs
Original file line number Diff line number Diff line change
Expand Up @@ -14,8 +14,8 @@ public override RequestId ReadJson(JsonReader reader, Type objectType, RequestId
{
switch (reader.TokenType)
{
case JsonToken.Integer: return new RequestId(reader.Value is int i ? i : (long)reader.Value);
case JsonToken.String: return new RequestId((string)reader.Value);
case JsonToken.Integer: return new RequestId(reader.Value is int i ? i : (long)reader.Value!);
case JsonToken.String: return new RequestId((string?)reader.Value);
case JsonToken.Null: return RequestId.Null;
default: throw new JsonSerializationException("Unexpected token type for request ID: " + reader.TokenType);
}
Expand Down
8 changes: 4 additions & 4 deletions src/StreamJsonRpc/StreamJsonRpc.csproj
Original file line number Diff line number Diff line change
Expand Up @@ -15,12 +15,12 @@
</EmbeddedResource>
</ItemGroup>
<ItemGroup>
<PackageReference Include="MessagePack" Version="2.2.85" />
<PackageReference Include="MessagePackAnalyzer" Version="2.2.85" PrivateAssets="all" />
<PackageReference Include="Microsoft.VisualStudio.Threading" Version="16.9.60" />
<PackageReference Include="MessagePack" Version="2.2.113" />
<PackageReference Include="MessagePackAnalyzer" Version="2.2.113" PrivateAssets="all" />
<PackageReference Include="Microsoft.VisualStudio.Threading" Version="16.10.56" />
<PackageReference Include="Microsoft.Bcl.AsyncInterfaces" Version="5.0.0" PrivateAssets="compile" />
<PackageReference Include="Nerdbank.Streams" Version="2.7.74" />
<PackageReference Include="Newtonsoft.Json" Version="12.0.2" />
<PackageReference Include="Newtonsoft.Json" Version="13.0.1" />
<PackageReference Include="Microsoft.CodeAnalysis.PublicApiAnalyzers" Version="3.3.2" PrivateAssets="all" />
<PackageReference Include="Nullable" Version="1.3.0" PrivateAssets="all" />
<PackageReference Include="System.Collections.Immutable" Version="5.0.0" />
Expand Down
4 changes: 2 additions & 2 deletions test/StreamJsonRpc.Tests/AsyncEnumerableTests.cs
Original file line number Diff line number Diff line change
Expand Up @@ -785,12 +785,12 @@ protected class UnserializableType

protected class ThrowingJsonConverter<T> : JsonConverter<T>
{
public override T ReadJson(JsonReader reader, Type objectType, T existingValue, bool hasExistingValue, JsonSerializer serializer)
public override T ReadJson(JsonReader reader, Type objectType, T? existingValue, bool hasExistingValue, JsonSerializer serializer)
{
throw new Exception();
}

public override void WriteJson(JsonWriter writer, T value, JsonSerializer serializer)
public override void WriteJson(JsonWriter writer, T? value, JsonSerializer serializer)
{
throw new Exception();
}
Expand Down
8 changes: 4 additions & 4 deletions test/StreamJsonRpc.Tests/JsonMessageFormatterTests.cs
Original file line number Diff line number Diff line change
Expand Up @@ -165,8 +165,8 @@ public void ErrorResponseOmitsNullDataField()
var formatter = new JsonMessageFormatter();
JToken jtoken = formatter.Serialize(new JsonRpcError { RequestId = new RequestId(1), Error = new JsonRpcError.ErrorDetail { Code = JsonRpcErrorCode.InternalError, Message = "some error" } });
this.Logger.WriteLine(jtoken.ToString(Formatting.Indented));
Assert.Equal((int)JsonRpcErrorCode.InternalError, jtoken["error"]["code"]);
Assert.Null(jtoken["error"]["data"]); // we're testing for an undefined field -- not a field with a null value.
Assert.Equal((int)JsonRpcErrorCode.InternalError, jtoken["error"]!["code"]);
Assert.Null(jtoken["error"]!["data"]); // we're testing for an undefined field -- not a field with a null value.
}

[Fact]
Expand All @@ -175,8 +175,8 @@ public void ErrorResponseIncludesNonNullDataField()
var formatter = new JsonMessageFormatter();
JToken jtoken = formatter.Serialize(new JsonRpcError { RequestId = new RequestId(1), Error = new JsonRpcError.ErrorDetail { Code = JsonRpcErrorCode.InternalError, Message = "some error", Data = new { more = "info" } } });
this.Logger.WriteLine(jtoken.ToString(Formatting.Indented));
Assert.Equal((int)JsonRpcErrorCode.InternalError, jtoken["error"]["code"]);
Assert.Equal("info", jtoken["error"]["data"].Value<string>("more"));
Assert.Equal((int)JsonRpcErrorCode.InternalError, jtoken["error"]!["code"]);
Assert.Equal("info", jtoken["error"]!["data"]!.Value<string>("more"));
}

[Fact]
Expand Down
4 changes: 2 additions & 2 deletions test/StreamJsonRpc.Tests/JsonRpcClient10InteropTests.cs
Original file line number Diff line number Diff line change
Expand Up @@ -34,8 +34,8 @@ public async Task ClientRecognizesResultWithNullError()
// Receive the request at the server side and sanity check its contents.
JToken request = await this.ReceiveAsync();
Assert.Equal("test", request.Value<string>("method"));
Assert.Single((JArray)request["params"]);
Assert.Equal("arg1", request["params"][0].Value<string>());
Assert.Single((JArray?)request["params"]);
Assert.Equal("arg1", request["params"]?[0]?.Value<string>());
Assert.NotNull(request["id"]);

const string expectedResult = "some result";
Expand Down
Loading