Skip to content

Commit 4aa4021

Browse files
committed
Implement source generation context
1 parent 980fca4 commit 4aa4021

File tree

8 files changed

+71
-65
lines changed

8 files changed

+71
-65
lines changed
Original file line numberDiff line numberDiff line change
@@ -1,11 +1,11 @@
1-
using System.Text.Json;
1+
using System.Text.Json;
22

33
namespace ImeSense.Launchers.Belarus.Core.Helpers;
44

55
public static class FileDataHelper {
66
public static async Task<T?> LoadDataAsync<T>(string filePath) {
77
await using var fileStream = new FileStream(filePath, FileMode.Open, FileAccess.Read,
88
FileShare.Read, 4096, FileOptions.Asynchronous);
9-
return await JsonSerializer.DeserializeAsync<T>(fileStream);
9+
return (T?) await JsonSerializer.DeserializeAsync(fileStream, typeof(T), SourceGenerationContext.Default);
1010
}
1111
}
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,4 @@
1-
using System.Text.Encodings.Web;
1+
using System.Text.Encodings.Web;
22
using System.Text.Json;
33
using System.Text.Unicode;
44

@@ -9,11 +9,6 @@ public static async Task WriteReleaseAsync<T>(T obj, string path) {
99
await using var fileStream = new FileStream(path, FileMode.Create);
1010
await using var writer = new StreamWriter(fileStream);
1111

12-
var options = new JsonSerializerOptions {
13-
AllowTrailingCommas = true,
14-
Encoder = JavaScriptEncoder.Create(UnicodeRanges.All),
15-
WriteIndented = true
16-
};
17-
await JsonSerializer.SerializeAsync(fileStream, obj, options);
12+
await JsonSerializer.SerializeAsync(fileStream, obj, typeof(T), SourceGenerationContext.Default);
1813
}
1914
}

src/ImeSense.Launchers.Belarus.Core/Helpers/SerializationHelper.cs

+2-2
Original file line numberDiff line numberDiff line change
@@ -1,11 +1,11 @@
1-
using System.Text.Json;
1+
using System.Text.Json;
22

33
namespace ImeSense.Launchers.Belarus.Core.Helpers;
44

55
public static class SerializationHelper {
66
public static async Task<MemoryStream> SerializeToStreamAsync<T>(T? obj) {
77
var stream = new MemoryStream();
8-
await JsonSerializer.SerializeAsync(stream, obj);
8+
await JsonSerializer.SerializeAsync(stream, obj, typeof(T), SourceGenerationContext.Default);
99
stream.Position = 0;
1010
return stream;
1111
}

src/ImeSense.Launchers.Belarus.Core/Manager/UserManager.cs

+4-10
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,4 @@
1-
using System.Text.Encodings.Web;
21
using System.Text.Json;
3-
using System.Text.Unicode;
42

53
using ImeSense.Launchers.Belarus.Core.Models;
64
using ImeSense.Launchers.Belarus.Core.Storage;
@@ -29,8 +27,9 @@ private void Load() {
2927
}
3028

3129
try {
32-
var json = File.ReadAllText(PathStorage.LauncherSetting);
33-
var user = JsonSerializer.Deserialize<UserSettings>(json)!;
30+
using var json = File.OpenRead(PathStorage.LauncherSetting);
31+
var user = JsonSerializer.Deserialize(json, SourceGenerationContext.Default.UserSettings)!;
32+
3433
if (!_startGameValidator.IsValidIpAddressOrUrl(user.IpAddress)) {
3534
user.IpAddress = string.Empty;
3635
}
@@ -63,12 +62,7 @@ public void Save() {
6362
FileMode.Create);
6463
using var writer = new StreamWriter(fileStream);
6564

66-
var options = new JsonSerializerOptions {
67-
AllowTrailingCommas = true,
68-
Encoder = JavaScriptEncoder.Create(UnicodeRanges.All),
69-
WriteIndented = true
70-
};
71-
var json = JsonSerializer.Serialize(UserSettings, options);
65+
var json = JsonSerializer.Serialize(UserSettings, typeof(UserSettings), SourceGenerationContext.Default);
7266
writer.Write(json);
7367
}
7468
}

src/ImeSense.Launchers.Belarus.Core/Services/GitHubApiService.cs

+28-28
Original file line numberDiff line numberDiff line change
@@ -19,30 +19,30 @@ public GitHubApiService(ILogger<GitHubApiService>? logger, HttpClient httpClient
1919
_launcherStorage = launcherStorage;
2020
}
2121

22-
public async IAsyncEnumerable<T?> DownloadJsonArrayAsync<T>(string filename,
23-
Uri? uriRepository = null) where T : class
24-
{
25-
if (uriRepository == null) {
26-
if (_httpClient.BaseAddress == null) {
27-
throw new NullReferenceException("No base address for HttpClient");
28-
}
29-
uriRepository = _httpClient.BaseAddress;
30-
}
31-
32-
GitHubRelease? release;
33-
if (_launcherStorage == null) {
34-
release = await GetLastReleaseAsync();
35-
} else {
36-
release = _launcherStorage.GitHubRelease;
37-
}
38-
39-
var asset = release?.Assets?.FirstOrDefault(n => n.Name.Equals(filename));
40-
await using var assetStream = await _httpClient.GetStreamAsync(asset?.BrowserDownloadUrl);
41-
var contents = JsonSerializer.DeserializeAsyncEnumerable<T>(assetStream);
42-
await foreach (var content in contents) {
43-
yield return content;
44-
}
45-
}
22+
//public async IAsyncEnumerable<T?> DownloadJsonArrayAsync<T>(string filename,
23+
// Uri? uriRepository = null) where T : class
24+
//{
25+
// if (uriRepository == null) {
26+
// if (_httpClient.BaseAddress == null) {
27+
// throw new NullReferenceException("No base address for HttpClient");
28+
// }
29+
// uriRepository = _httpClient.BaseAddress;
30+
// }
31+
32+
// GitHubRelease? release;
33+
// if (_launcherStorage == null) {
34+
// release = await GetLastReleaseAsync();
35+
// } else {
36+
// release = _launcherStorage.GitHubRelease;
37+
// }
38+
39+
// var asset = release?.Assets?.FirstOrDefault(n => n.Name.Equals(filename));
40+
// await using var assetStream = await _httpClient.GetStreamAsync(asset?.BrowserDownloadUrl);
41+
// var contents = JsonSerializer.DeserializeAsyncEnumerable<T>(assetStream);
42+
// await foreach (var content in contents) {
43+
// yield return content;
44+
// }
45+
//}
4646

4747
/// <summary>
4848
/// Downloads a JSON file from a GitHub release and deserializes it into the specified object type
@@ -68,7 +68,7 @@ public GitHubApiService(ILogger<GitHubApiService>? logger, HttpClient httpClient
6868
// Find the asset with the specified filename
6969
var asset = release?.Assets?.FirstOrDefault(n => n.Name.Equals(filename));
7070
// Download the asset
71-
return await _httpClient.GetFromJsonAsync<T>(asset?.BrowserDownloadUrl);
71+
return await _httpClient.GetFromJsonAsync(asset?.BrowserDownloadUrl, typeof(T), SourceGenerationContext.Default) as T;
7272
}
7373

7474
public async Task<GitHubRelease?> GetLastReleaseAsync(Uri? uriRepository = null) {
@@ -79,7 +79,7 @@ public GitHubApiService(ILogger<GitHubApiService>? logger, HttpClient httpClient
7979
uriRepository = _httpClient.BaseAddress;
8080
}
8181

82-
return await _httpClient.GetFromJsonAsync<GitHubRelease>(new Uri(uriRepository, "releases/latest"));
82+
return await _httpClient.GetFromJsonAsync(new Uri(uriRepository, "releases/latest"), SourceGenerationContext.Default.GitHubRelease);
8383
}
8484

8585
public async Task<GitHubRelease?> GetReleaseAsync(string tag, Uri? uriRepository = null) {
@@ -90,7 +90,7 @@ public GitHubApiService(ILogger<GitHubApiService>? logger, HttpClient httpClient
9090
uriRepository = _httpClient.BaseAddress;
9191
}
9292

93-
var json = await _httpClient.GetFromJsonAsync<IList<GitHubRelease>>(new Uri(uriRepository, $"releases"));
93+
var json = await _httpClient.GetFromJsonAsync(new Uri(uriRepository, $"releases"), SourceGenerationContext.Default.GitHubReleaseArray);
9494
return json?.FirstOrDefault(t => t.TagName.Equals(tag));
9595
}
9696

@@ -103,7 +103,7 @@ public GitHubApiService(ILogger<GitHubApiService>? logger, HttpClient httpClient
103103
}
104104

105105
await using var tagsStream = await _httpClient.GetStreamAsync(new Uri(uriRepository, "tags"));
106-
var tags = JsonSerializer.Deserialize<IEnumerable<Tag>>(tagsStream);
106+
var tags = JsonSerializer.Deserialize(tagsStream, SourceGenerationContext.Default.IEnumerableTag);
107107

108108
if (tags is not null) {
109109
return tags;

src/ImeSense.Launchers.Belarus.Core/Services/IGitStorageApiService.cs

+1-1
Original file line numberDiff line numberDiff line change
@@ -3,7 +3,7 @@
33
namespace ImeSense.Launchers.Belarus.Core.Services;
44

55
public interface IGitStorageApiService {
6-
IAsyncEnumerable<T?> DownloadJsonArrayAsync<T>(string filename, Uri? uriRepository = null) where T : class;
6+
//IAsyncEnumerable<T?> DownloadJsonArrayAsync<T>(string filename, Uri? uriRepository = null) where T : class;
77
Task<T?> DownloadJsonAsync<T>(string filename, Uri? uriRepository = null) where T : class;
88
Task<GitHubRelease?> GetLastReleaseAsync(Uri? uriRepository = null);
99
Task<IEnumerable<Tag?>?> GetTagsAsync(Uri? uriRepository = null);
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,25 @@
1+
using System.Text.Json.Serialization;
2+
3+
using ImeSense.Launchers.Belarus.Core.Models;
4+
5+
namespace ImeSense.Launchers.Belarus.Core;
6+
7+
[JsonSourceGenerationOptions(WriteIndented = true, AllowTrailingCommas = true)]
8+
[JsonSerializable(typeof(Asset))]
9+
[JsonSerializable(typeof(Commit))]
10+
[JsonSerializable(typeof(GameResource))]
11+
[JsonSerializable(typeof(GameResource[]))]
12+
[JsonSerializable(typeof(GitHubRelease))]
13+
[JsonSerializable(typeof(GitHubRelease[]))]
14+
[JsonSerializable(typeof(Locale))]
15+
[JsonSerializable(typeof(NewsContent))]
16+
[JsonSerializable(typeof(IEnumerable<NewsContent>))]
17+
[JsonSerializable(typeof(IEnumerable<LangNewsContent>))]
18+
[JsonSerializable(typeof(Tag))]
19+
[JsonSerializable(typeof(IEnumerable<Tag>))]
20+
[JsonSerializable(typeof(UserSettings))]
21+
[JsonSerializable(typeof(WebResource))]
22+
[JsonSerializable(typeof(WebResource[]))]
23+
[JsonSerializable(typeof(IEnumerable<WebResource>))]
24+
public partial class SourceGenerationContext : JsonSerializerContext {
25+
}

src/ImeSense.Launchers.Belarus.CryptoHasher/Program.cs

+7-15
Original file line numberDiff line numberDiff line change
@@ -1,22 +1,19 @@
11
using System.Diagnostics;
2-
using System.Text.Encodings.Web;
32
using System.Text.Json;
4-
using System.Text.Unicode;
53

64
using ImeSense.Launchers.Belarus.Core.FileHashVerification;
75
using ImeSense.Launchers.Belarus.Core.Logger;
86
using ImeSense.Launchers.Belarus.Core.Models;
97
using ImeSense.Launchers.Belarus.Core.Storage;
8+
using ImeSense.Launchers.Belarus.Core;
109

1110
using Microsoft.Extensions.Logging;
1211

1312
using Serilog;
1413

1514
using static ImeSense.Launchers.Belarus.Core.Storage.DirectoryStorage;
1615

17-
IEnumerable<string> GetDirectories() {
18-
return new[] { Binaries, Resources, Patches };
19-
}
16+
IEnumerable<string> GetDirectories() => [Binaries, Resources, Patches];
2017

2118
var pathLog = Path.Combine(UserLogs, "CryptoHasherReport.log");
2219
using var factory = LoggerFactory.Create(builder => builder.AddSerilog(LogManager.CreateLoggerConsole(pathLog, true)));
@@ -41,21 +38,16 @@ IEnumerable<string> GetDirectories() {
4138

4239
var gameResources = await Task.WhenAll(gameResourceTasks);
4340
stopwatch.Stop();
44-
logger.LogInformation($"Hash calculation time: {stopwatch.ElapsedMilliseconds}");
41+
logger.LogInformation("Hash calculation time: {time}", stopwatch.ElapsedMilliseconds);
4542

46-
var options = new JsonSerializerOptions {
47-
AllowTrailingCommas = true,
48-
Encoder = JavaScriptEncoder.Create(UnicodeRanges.All),
49-
WriteIndented = true
50-
};
5143
await using var fs = new FileStream(FileNameStorage.HashResources, FileMode.OpenOrCreate);
52-
await JsonSerializer.SerializeAsync(fs, gameResources, options);
44+
await JsonSerializer.SerializeAsync(fs, gameResources, SourceGenerationContext.Default.GameResourceArray);
5345
fs.Close();
5446

55-
logger.LogInformation(File.ReadAllText(FileNameStorage.HashResources));
47+
logger.LogInformation("{json}", File.ReadAllText(FileNameStorage.HashResources));
5648
} catch (Exception ex) {
57-
logger.LogInformation(ex.Message);
58-
logger.LogInformation(ex.StackTrace);
49+
logger.LogInformation("{Message}", ex.Message);
50+
logger.LogInformation("{StackTrace}", ex.StackTrace);
5951

6052
Console.ReadLine();
6153
}

0 commit comments

Comments
 (0)