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

Refactor/32 migrate newtonsoftjson to systemtextjson #35

Merged
merged 10 commits into from
May 15, 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
24 changes: 4 additions & 20 deletions src/Eurofurence.App.Common/Compression/ZipHelper.cs
Original file line number Diff line number Diff line change
@@ -1,9 +1,5 @@
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.IO;
using System.IO.Compression;
using System.Text;
using System.IO.Compression;
using System.Text.Json;

namespace Eurofurence.App.Common.Compression
{
Expand All @@ -14,13 +10,7 @@ public static void AddAsJson(this ZipArchive archive, string entryName, object i
var entry = archive.CreateEntry(entryName, compressionLevel);
var stream = entry.Open();

var serializer = new JsonSerializer();

using (var streamWriter = new StreamWriter(stream, Encoding.UTF8))
using (var textWriter = new JsonTextWriter(streamWriter))
{
serializer.Serialize(textWriter, item);
}
JsonSerializer.Serialize(stream, item);
}

public static void AddAsBinary(this ZipArchive archive, string entryName, byte[] data, CompressionLevel compressionLevel = CompressionLevel.Optimal)
Expand All @@ -37,13 +27,7 @@ public static T ReadAsJson<T>(this ZipArchive archive, string entryName)
var entry = archive.GetEntry(entryName);
var stream = entry.Open();

var serializer = new JsonSerializer();

using (var streamReader = new StreamReader(stream, Encoding.UTF8))
using (var textReader = new JsonTextReader(streamReader))
{
return serializer.Deserialize<T>(textReader);
}
return JsonSerializer.Deserialize<T>(stream);
}

public static byte[] ReadAsBinary(this ZipArchive archive, string entryName)
Expand Down
3 changes: 0 additions & 3 deletions src/Eurofurence.App.Common/Eurofurence.App.Common.csproj
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,4 @@
<GenerateAssemblyCompanyAttribute>false</GenerateAssemblyCompanyAttribute>
<GenerateAssemblyProductAttribute>false</GenerateAssemblyProductAttribute>
</PropertyGroup>
<ItemGroup>
<PackageReference Include="Newtonsoft.Json" Version="13.0.3" />
</ItemGroup>
</Project>
Original file line number Diff line number Diff line change
@@ -1,32 +1,32 @@
using Newtonsoft.Json;
using System;
using System;
using System.Text.Json.Serialization;

namespace Eurofurence.App.Server.Services.Abstractions.Lassie
{
public class LostAndFoundResponse
{
[JsonProperty("id")]
[JsonPropertyName("id")]
public int Id { get; set; }

[JsonProperty("image")]
[JsonPropertyName("image")]
public string ImageUrl { get; set; }

[JsonProperty("title")]
[JsonPropertyName("title")]
public string Title { get; set; }

[JsonProperty("description")]
[JsonPropertyName("description")]
public string Description { get; set; }

[JsonProperty("status")]
[JsonPropertyName("status")]
public string Status { get; set; }

[JsonProperty("lost_timestamp")]
[JsonPropertyName("lost_timestamp")]
public DateTime? LostDateTimeLocal { get; set; }

[JsonProperty("found_timestamp")]
[JsonPropertyName("found_timestamp")]
public DateTime? FoundDateTimeLocal { get; set; }

[JsonProperty("return_timestamp")]
[JsonPropertyName("return_timestamp")]
public DateTime? ReturnDateTimeLocal { get; set; }
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,36 @@
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<TargetFramework>net8.0</TargetFramework>
<AssemblyName>Eurofurence.App.Server.Services</AssemblyName>
<PackageId>Eurofurence.App.Server.Services</PackageId>
<GenerateAssemblyConfigurationAttribute>false</GenerateAssemblyConfigurationAttribute>
<GenerateAssemblyCompanyAttribute>false</GenerateAssemblyCompanyAttribute>
<GenerateAssemblyProductAttribute>false</GenerateAssemblyProductAttribute>
</PropertyGroup>
<PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Debug|AnyCPU'">
<DefineConstants>TRACE;DEBUG;NETSTANDARD2_0</DefineConstants>
</PropertyGroup>
<ItemGroup>
<ProjectReference Include="..\Eurofurence.App.Domain.Model.MongoDb\Eurofurence.App.Domain.Model.MongoDb.csproj" />
<ProjectReference Include="..\Eurofurence.App.Domain.Model.MySql\Eurofurence.App.Domain.Model.MySql.csproj" />
<ProjectReference Include="..\Eurofurence.App.Domain.Model\Eurofurence.App.Domain.Model.csproj" />
</ItemGroup>
<ItemGroup>
<PackageReference Include="Autofac" Version="8.0.0" />
<PackageReference Include="CsvHelper" Version="30.1.0" />
<PackageReference Include="FirebaseAdmin" Version="2.4.0" />
<PackageReference Include="Microsoft.Extensions.Configuration.Binder" Version="8.0.1" />
<PackageReference Include="Microsoft.IdentityModel.Tokens" Version="7.3.0" />
<PackageReference Include="SixLabors.ImageSharp" Version="3.1.2" />
<PackageReference Include="SixLabors.ImageSharp.Drawing" Version="2.1.1" />
<PackageReference Include="System.IdentityModel.Tokens.Jwt" Version="7.3.0" />
<PackageReference Include="System.Linq.Async" Version="6.0.1" />
<PackageReference Include="Telegram.Bot" Version="19.0.0" />
<PackageReference Include="Microsoft.Extensions.Configuration" Version="8.0.0" />
<PackageReference Include="Microsoft.Extensions.Logging" Version="8.0.0" />
<PackageReference Include="Microsoft.Extensions.Logging.Abstractions" Version="8.0.0" />
</ItemGroup>
<ItemGroup>
<Folder Include="Properties\" />
</ItemGroup>
</Project>
29 changes: 17 additions & 12 deletions src/Eurofurence.App.Server.Services/Lassie/LassieApiClient.cs
Original file line number Diff line number Diff line change
@@ -1,23 +1,26 @@
using Eurofurence.App.Server.Services.Abstractions.Lassie;
using Newtonsoft.Json;
using System;
using Eurofurence.App.Server.Services.Abstractions.Lassie;
using System.Collections.Generic;
using System.Net.Http;
using System.Text.Json;
using System.Threading.Tasks;

namespace Eurofurence.App.Server.Services.Lassie
{
public class LassieApiClient : ILassieApiClient
{
private class DataResponseWrapper<T>
public class DataResponseWrapper<T>
{
public T[] Data { get; set; }
}

private LassieConfiguration _configuration;
private JsonSerializerOptions _serializerOptions;

public LassieApiClient(LassieConfiguration configuration)
public LassieApiClient(LassieConfiguration configuration, JsonSerializerOptions serializerOptions)
{
_configuration = configuration;
_serializerOptions = serializerOptions;
}

public async Task<LostAndFoundResponse[]> QueryLostAndFoundDbAsync(string command = "lostandfound")
Expand All @@ -29,16 +32,18 @@ public async Task<LostAndFoundResponse[]> QueryLostAndFoundDbAsync(string comman
new KeyValuePair<string, string>("command", command)
};

using (var client = new HttpClient())
{
var response = await client.PostAsync(_configuration.BaseApiUrl, new FormUrlEncodedContent(outgoingQuery));
var content = await response.Content.ReadAsStringAsync();
using var client = new HttpClient();
var response = await client.PostAsync(_configuration.BaseApiUrl, new FormUrlEncodedContent(outgoingQuery));
var content = await response.Content.ReadAsStringAsync();

var dataResponse = DeserializeLostAndFoundResponse(content);

var dataResponse = JsonConvert.DeserializeObject<DataResponseWrapper<LostAndFoundResponse>>(content,
new JsonSerializerSettings() { DateTimeZoneHandling = DateTimeZoneHandling.Local });
return dataResponse.Data ?? Array.Empty<LostAndFoundResponse>();
}

return dataResponse.Data ?? new LostAndFoundResponse[0];
}
public DataResponseWrapper<LostAndFoundResponse> DeserializeLostAndFoundResponse(string content)
{
return JsonSerializer.Deserialize<DataResponseWrapper<LostAndFoundResponse>>(content, _serializerOptions);
}
}
}
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text.Json;
using System.Threading.Tasks;
using Eurofurence.App.Common.ExtensionMethods;
using Eurofurence.App.Common.Results;
Expand All @@ -13,7 +14,6 @@
using FirebaseAdmin.Messaging;
using Google.Apis.Auth.OAuth2;
using Microsoft.EntityFrameworkCore;
using Newtonsoft.Json;

namespace Eurofurence.App.Server.Services.PushNotifications
{
Expand Down Expand Up @@ -206,7 +206,7 @@ public Task PushSyncRequestAsync()
// For Expo / React Native
{ "experienceId", _configuration.ExpoExperienceId },
{ "scopeKey", _configuration.ExpoScopeKey },
{ "body", JsonConvert.SerializeObject(new
{ "body", JsonSerializer.Serialize(new
{
@event = "Sync",
cid = _conventionSettings.ConventionIdentifier
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -7,8 +7,9 @@
using Eurofurence.App.Domain.Model.PushNotifications;
using Eurofurence.App.Infrastructure.EntityFramework;
using Eurofurence.App.Server.Services.Abstractions.PushNotifications;
using System.Text.Json;
using System.Text.Json.Nodes;
using Microsoft.EntityFrameworkCore;
using Newtonsoft.Json;

namespace Eurofurence.App.Server.Services.PushNotifications
{
Expand Down Expand Up @@ -42,7 +43,7 @@ public async Task PushAnnouncementNotificationAsync(AnnouncementRecord announcem

var recipients = GetAllRecipientsAsyncByTopic(_configuration.TargetTopic);

await SendRawAsync(recipients, JsonConvert.SerializeObject(message));
await SendRawAsync(recipients, JsonSerializer.Serialize(message));
}

public async Task SendToastAsync(string topic, string message)
Expand Down Expand Up @@ -165,7 +166,7 @@ private IQueryable<PushNotificationChannelRecord> GetAllRecipientsAsyncByUid(str

private Task SendRawAsync(IEnumerable<PushNotificationChannelRecord> recipients, object rawContent)
{
return SendRawAsync(recipients, JsonConvert.SerializeObject(rawContent));
return SendRawAsync(recipients, JsonSerializer.Serialize(rawContent));
}

private async Task SendRawAsync(IEnumerable<PushNotificationChannelRecord> recipients, string rawContent)
Expand Down Expand Up @@ -208,25 +209,23 @@ await _appDbContext.PushNotificationChannels.FirstOrDefaultAsync(entity =>

private async Task<string> GetWnsAccessTokenAsync()
{
using (var client = new HttpClient())
using var client = new HttpClient();
var payload = new FormUrlEncodedContent(new List<KeyValuePair<string, string>>
{
var payload = new FormUrlEncodedContent(new List<KeyValuePair<string, string>>
{
new KeyValuePair<string, string>("grant_type", "client_credentials"),
new KeyValuePair<string, string>("client_id", _configuration.ClientId),
new KeyValuePair<string, string>("client_secret", _configuration.ClientSecret),
new KeyValuePair<string, string>("scope", "notify.windows.com")
});
new KeyValuePair<string, string>("grant_type", "client_credentials"),
new KeyValuePair<string, string>("client_id", _configuration.ClientId),
new KeyValuePair<string, string>("client_secret", _configuration.ClientSecret),
new KeyValuePair<string, string>("scope", "notify.windows.com")
});

var response = await client.PostAsync("https://login.live.com/accesstoken.srf", payload);
response.EnsureSuccessStatusCode();
var response = await client.PostAsync("https://login.live.com/accesstoken.srf", payload);
response.EnsureSuccessStatusCode();

var content = await response.Content.ReadAsStringAsync();
var schema = new {token_type = "", access_token = "", expires_in = 0};
var node = JsonConvert.DeserializeAnonymousType(content, schema);
var content = await response.Content.ReadAsStringAsync();

return node.access_token;
}
var accessTokenNode = JsonNode.Parse(content)!;

return (string)accessTokenNode["access_token"] ?? "";
}
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -28,7 +28,6 @@
<PackageReference Include="Serilog.Sinks.File" Version="5.0.0" />
<PackageReference Include="Swashbuckle.AspNetCore" Version="6.6.1" />
<PackageReference Include="Microsoft.AspNetCore.Authentication.JwtBearer" Version="8.0.5" />
<PackageReference Include="Microsoft.AspNetCore.Mvc.NewtonsoftJson" Version="8.0.5" />
<PackageReference Include="Microsoft.AspNetCore.Mvc.Razor.RuntimeCompilation" Version="8.0.5" />
<PackageReference Include="Microsoft.Extensions.Configuration" Version="8.0.0" />
<PackageReference Include="Microsoft.Extensions.Configuration.FileExtensions" Version="8.0.0" />
Expand Down

This file was deleted.

21 changes: 21 additions & 0 deletions src/Eurofurence.App.Server.Web/Extensions/JsonDateTimeConverter.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
using System.Diagnostics;
using System.Text.Json;
using System.Text.Json.Serialization;
using System;

namespace Eurofurence.App.Server.Web.Extensions
{
public class JsonDateTimeConverter : JsonConverter<DateTime>
{
public override DateTime Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options)
{
Debug.Assert(typeToConvert == typeof(DateTime));
return DateTime.Parse(reader.GetString()!);
}

public override void Write(Utf8JsonWriter writer, DateTime value, JsonSerializerOptions options)
{
writer.WriteStringValue(value.ToString("yyyy'-'MM'-'dd'T'HH':'mm':'ss.fffK"));
}
}
}
Loading