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

fix: serialization of primitives present in additionalData #468

Merged
merged 3 commits into from
Nov 13, 2024
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
6 changes: 6 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,12 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0

## [Unreleased]

## [1.15.1] - 2024-11-13

### Added

- Fixes serialization collections of primitives present in additional data. [microsoftgraph/msgraph-sdk-dotnet#2729](https://github.com/microsoftgraph/msgraph-sdk-dotnet/issues/2729)

## [1.15.0] - 2024-11-13

### Added
Expand Down
2 changes: 1 addition & 1 deletion Directory.Build.props
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
<Project>
<!-- Common default project properties for ALL projects-->
<PropertyGroup>
<VersionPrefix>1.15.0</VersionPrefix>
<VersionPrefix>1.15.1</VersionPrefix>
<VersionSuffix></VersionSuffix>
<!-- This is overidden in test projects by setting to true-->
<IsTestProject>false</IsTestProject>
Expand Down
12 changes: 7 additions & 5 deletions src/serialization/json/JsonSerializationWriter.cs
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
// ------------------------------------------------------------------------------
// ------------------------------------------------------------------------------
// Copyright (c) Microsoft Corporation. All Rights Reserved. Licensed under the MIT License. See License in the project root for license information.
// ------------------------------------------------------------------------------

Expand All @@ -23,7 +23,7 @@
/// <summary>
/// The <see cref="ISerializationWriter"/> implementation for json content types.
/// </summary>
public class JsonSerializationWriter : ISerializationWriter, IDisposable

Check warning on line 26 in src/serialization/json/JsonSerializationWriter.cs

View workflow job for this annotation

GitHub Actions / Build

Fix this implementation of 'IDisposable' to conform to the dispose pattern. (https://rules.sonarsource.com/csharp/RSPEC-3881)

Check warning on line 26 in src/serialization/json/JsonSerializationWriter.cs

View workflow job for this annotation

GitHub Actions / Build

'ISerializationWriter' implements 'IDisposable' so 'IDisposable' can be removed from the inheritance list. (https://rules.sonarsource.com/csharp/RSPEC-1939)
{
private readonly MemoryStream _stream = new MemoryStream();
private readonly KiotaJsonSerializationContext _kiotaJsonSerializationContext;
Expand Down Expand Up @@ -273,7 +273,7 @@
/// <param name="key">The key of the json node</param>
/// <param name="value">The enumeration value</param>
#if NET5_0_OR_GREATER
public void WriteEnumValue<[DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicFields)] T>(string? key, T? value) where T : struct, Enum

Check warning on line 276 in src/serialization/json/JsonSerializationWriter.cs

View workflow job for this annotation

GitHub Actions / Build

Refactor this method to reduce its Cognitive Complexity from 19 to the 15 allowed. (https://rules.sonarsource.com/csharp/RSPEC-3776)
#else
public void WriteEnumValue<T>(string? key, T? value) where T : struct, Enum
#endif
Expand Down Expand Up @@ -311,7 +311,9 @@
/// </summary>
/// <param name="key">The key of the json node</param>
/// <param name="values">The primitive collection</param>
public void WriteCollectionOfPrimitiveValues<T>(string? key, IEnumerable<T>? values)
public void WriteCollectionOfPrimitiveValues<T>(string? key, IEnumerable<T>? values) => WriteCollectionOfPrimitiveValuesInternal(key, values);

private void WriteCollectionOfPrimitiveValuesInternal(string? key, IEnumerable? values)
{
if(values != null)
{ //empty array is meaningful
Expand Down Expand Up @@ -374,7 +376,7 @@
private void WriteDictionaryValue<T>(string? key, T values) where T : IDictionary
#endif
{
if(values != null)

Check warning on line 379 in src/serialization/json/JsonSerializationWriter.cs

View workflow job for this annotation

GitHub Actions / Build

Use a comparison to 'default(T)' instead or add a constraint to 'T' so that it can't be a value type. (https://rules.sonarsource.com/csharp/RSPEC-2955)
{
if(!string.IsNullOrEmpty(key))
writer.WritePropertyName(key!);
Expand Down Expand Up @@ -412,16 +414,16 @@
/// <param name="key">The key of the json node</param>
/// <param name="value">The object instance to write</param>
/// <param name="additionalValuesToMerge">The additional values to merge to the main value when serializing an intersection wrapper.</param>
public void WriteObjectValue<T>(string? key, T? value, params IParsable?[] additionalValuesToMerge) where T : IParsable

Check warning on line 417 in src/serialization/json/JsonSerializationWriter.cs

View workflow job for this annotation

GitHub Actions / Build

Refactor this method to reduce its Cognitive Complexity from 24 to the 15 allowed. (https://rules.sonarsource.com/csharp/RSPEC-3776)
{
var filteredAdditionalValuesToMerge = (IParsable[])Array.FindAll(additionalValuesToMerge, static x => x is not null);
if(value != null || filteredAdditionalValuesToMerge.Length > 0)

Check warning on line 420 in src/serialization/json/JsonSerializationWriter.cs

View workflow job for this annotation

GitHub Actions / Build

Use a comparison to 'default(T)' instead or add a constraint to 'T' so that it can't be a value type. (https://rules.sonarsource.com/csharp/RSPEC-2955)
{
// until interface exposes WriteUntypedValue()
var serializingUntypedNode = value is UntypedNode;
if(!serializingUntypedNode && !string.IsNullOrEmpty(key))
writer.WritePropertyName(key!);
if(value != null)

Check warning on line 426 in src/serialization/json/JsonSerializationWriter.cs

View workflow job for this annotation

GitHub Actions / Build

Use a comparison to 'default(T)' instead or add a constraint to 'T' so that it can't be a value type. (https://rules.sonarsource.com/csharp/RSPEC-2955)
OnBeforeObjectSerialization?.Invoke(value);

if(serializingUntypedNode)
Expand All @@ -436,7 +438,7 @@
var serializingScalarValue = value is IComposedTypeWrapper;
if(!serializingScalarValue)
writer.WriteStartObject();
if(value != null)

Check warning on line 441 in src/serialization/json/JsonSerializationWriter.cs

View workflow job for this annotation

GitHub Actions / Build

Use a comparison to 'default(T)' instead or add a constraint to 'T' so that it can't be a value type. (https://rules.sonarsource.com/csharp/RSPEC-2955)
{
OnStartObjectSerialization?.Invoke(value, this);
value.Serialize(this);
Expand All @@ -451,7 +453,7 @@
if(!serializingScalarValue)
writer.WriteEndObject();
}
if(value != null) OnAfterObjectSerialization?.Invoke(value);

Check warning on line 456 in src/serialization/json/JsonSerializationWriter.cs

View workflow job for this annotation

GitHub Actions / Build

Use a comparison to 'default(T)' instead or add a constraint to 'T' so that it can't be a value type. (https://rules.sonarsource.com/csharp/RSPEC-2955)
}
}

Expand All @@ -477,7 +479,7 @@
if(!string.IsNullOrEmpty(key))
writer.WritePropertyName(key!);
writer.WriteStartObject();
if(value == null)

Check warning on line 482 in src/serialization/json/JsonSerializationWriter.cs

View workflow job for this annotation

GitHub Actions / Build

Use a comparison to 'default(T)' instead or add a constraint to 'T' so that it can't be a value type. (https://rules.sonarsource.com/csharp/RSPEC-2955)
writer.WriteNullValue();
else
foreach(var oProp in value.GetType().GetProperties())
Expand Down Expand Up @@ -525,9 +527,6 @@
case TimeSpan timeSpan:
WriteTimeSpanValue(key, timeSpan);
break;
case IEnumerable<object> coll:
WriteCollectionOfPrimitiveValues(key, coll);
break;
case UntypedNode node:
WriteUntypedValue(key, node);
break;
Expand All @@ -551,6 +550,9 @@
case IDictionary dictionary:
WriteDictionaryValue(key, dictionary);
break;
case IEnumerable coll:
WriteCollectionOfPrimitiveValuesInternal(key, coll);
break;
case object o:
WriteNonParsableObjectValue(key, o);
break;
Expand Down
34 changes: 33 additions & 1 deletion tests/serialization/json/JsonSerializationWriterTests.cs
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
using System;
using System;
using System.Collections.Generic;
using System.Globalization;
using System.IO;
Expand Down Expand Up @@ -40,6 +40,7 @@ public void WritesSampleObjectValue()
{"createdDateTime", DateTimeOffset.MinValue}, // write date value
{"weightInKgs", 51.80m}, // write weigth
{"businessPhones", new List<string>() {"+1 412 555 0109"}}, // write collection of primitives value
{"dates",new List<DateTimeOffset> { DateTimeOffset.MaxValue , DateTimeOffset.MinValue }},
{"endDateTime", new DateTime(2023,03,14,0,0,0,DateTimeKind.Utc) }, // ensure the DateTime doesn't crash
{"manager", new TestEntity{Id = "48d31887-5fad-4d73-a9f5-3c356e68a038"}}, // write nested object value
{"anonymousObject", new {Value1 = true, Value2 = "", Value3 = new List<string>{ "Value3.1", "Value3.2"}}}, // write nested object value
Expand Down Expand Up @@ -69,6 +70,7 @@ public void WritesSampleObjectValue()
"\"createdDateTime\":\"0001-01-01T00:00:00+00:00\"," +
"\"weightInKgs\":51.80," +
"\"businessPhones\":[\"\\u002B1 412 555 0109\"]," +
"\"dates\":[\"9999-12-31T23:59:59.9999999+00:00\",\"0001-01-01T00:00:00+00:00\"]," +
"\"endDateTime\":\"2023-03-14T00:00:00+00:00\"," +
"\"manager\":{\"id\":\"48d31887-5fad-4d73-a9f5-3c356e68a038\"}," +
"\"anonymousObject\":{\"Value1\":true,\"Value2\":\"\",\"Value3\":[\"Value3.1\",\"Value3.2\"]}," +
Expand Down Expand Up @@ -292,6 +294,36 @@ public void ForwardsOptionsToWriterFromSerializationContext()
Assert.Equal(expectedString, serializedJsonString.Replace("\r", string.Empty)); // string is indented and not escaped
}

[Fact]
public void WritesPrimitiveCollectionsInAdditionalData()
{
// Arrange
var dates = new List<DateTimeOffset>
{
DateTimeOffset.MaxValue, DateTimeOffset.MinValue
};
var testEntity = new TestEntity
{
Id = "testId",
AdditionalData = new Dictionary<string, object>()
{
{"dates", dates}
}
};
using var jsonSerializerWriter = new JsonSerializationWriter();
// Act
jsonSerializerWriter.WriteObjectValue(string.Empty, testEntity);
var serializedStream = jsonSerializerWriter.GetSerializedContent();
using var reader = new StreamReader(serializedStream, Encoding.UTF8);
var serializedJsonString = reader.ReadToEnd();

// Assert
Assert.Contains("\"id\":\"testId\"", serializedJsonString);
Assert.Contains("\"dates\":[\"", serializedJsonString);
Assert.Contains(JsonSerializer.Serialize(DateTimeOffset.MinValue), serializedJsonString);
Assert.Contains(JsonSerializer.Serialize(DateTimeOffset.MaxValue), serializedJsonString);
}

[Fact]
public void UsesDefaultOptionsToWriterFromSerializationContext()
{
Expand Down
Loading