Skip to content

feat: migrate .NET templates to System.Text.Json + add .NET 9.0 tests #1085

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

Open
wants to merge 6 commits into
base: master
Choose a base branch
from
Open
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
5 changes: 5 additions & 0 deletions src/SDK/Language/DotNet.php
Original file line number Diff line number Diff line change
Expand Up @@ -380,6 +380,11 @@ public function getFiles(): array
'destination' => '{{ spec.title | caseUcfirst }}/Converters/ValueClassConverter.cs',
'template' => 'dotnet/Package/Converters/ValueClassConverter.cs.twig',
],
[
'scope' => 'default',
'destination' => '{{ spec.title | caseUcfirst }}/Converters/ObjectToInferredTypesConverter.cs',
'template' => 'dotnet/Package/Converters/ObjectToInferredTypesConverter.cs.twig',
],
[
'scope' => 'default',
'destination' => '{{ spec.title | caseUcfirst }}/Extensions/Extensions.cs',
Expand Down
147 changes: 100 additions & 47 deletions templates/dotnet/Package/Client.cs.twig
Original file line number Diff line number Diff line change
@@ -1,14 +1,12 @@
using Newtonsoft.Json;
using Newtonsoft.Json.Converters;
using Newtonsoft.Json.Linq;
using Newtonsoft.Json.Serialization;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Text;
using System.Text.Json;
using System.Text.Json.Serialization;
using System.Threading.Tasks;
using {{ spec.title | caseUcfirst }}.Converters;
using {{ spec.title | caseUcfirst }}.Extensions;
Expand All @@ -29,26 +27,28 @@ namespace {{ spec.title | caseUcfirst }}

private static readonly int ChunkSize = 5 * 1024 * 1024;

public static JsonSerializerSettings DeserializerSettings { get; set; } = new JsonSerializerSettings
public static JsonSerializerOptions DeserializerOptions { get; set; } = new JsonSerializerOptions
{
MetadataPropertyHandling = MetadataPropertyHandling.Ignore,
NullValueHandling = NullValueHandling.Ignore,
ContractResolver = new CamelCasePropertyNamesContractResolver(),
Converters = new List<JsonConverter>
PropertyNamingPolicy = JsonNamingPolicy.CamelCase,
DefaultIgnoreCondition = JsonIgnoreCondition.WhenWritingNull,
PropertyNameCaseInsensitive = true,
Converters =
{
new StringEnumConverter(new CamelCaseNamingStrategy()),
new ValueClassConverter()
new JsonStringEnumConverter(JsonNamingPolicy.CamelCase),
new ValueClassConverter(),
new ObjectToInferredTypesConverter()
}
};

public static JsonSerializerSettings SerializerSettings { get; set; } = new JsonSerializerSettings
public static JsonSerializerOptions SerializerOptions { get; set; } = new JsonSerializerOptions
{
NullValueHandling = NullValueHandling.Ignore,
ContractResolver = new CamelCasePropertyNamesContractResolver(),
Converters = new List<JsonConverter>
PropertyNamingPolicy = JsonNamingPolicy.CamelCase,
DefaultIgnoreCondition = JsonIgnoreCondition.WhenWritingNull,
Converters =
{
new StringEnumConverter(new CamelCaseNamingStrategy()),
new ValueClassConverter()
new JsonStringEnumConverter(JsonNamingPolicy.CamelCase),
new ValueClassConverter(),
new ObjectToInferredTypesConverter()
}
};

Expand All @@ -69,7 +69,7 @@ namespace {{ spec.title | caseUcfirst }}
_headers = new Dictionary<string, string>()
{
{ "content-type", "application/json" },
{ "user-agent" , "{{spec.title | caseUcfirst}}{{ language.name | caseUcfirst }}SDK/{{ sdk.version }} (${Environment.OSVersion.Platform}; ${Environment.OSVersion.VersionString})"},
{ "user-agent" , $"{{spec.title | caseUcfirst}}{{ language.name | caseUcfirst }}SDK/{{ sdk.version }} ({Environment.OSVersion.Platform}; {Environment.OSVersion.VersionString})"},
{ "x-sdk-name", "{{ sdk.name }}" },
{ "x-sdk-platform", "{{ sdk.platform }}" },
{ "x-sdk-language", "{{ language.name | caseLower }}" },
Expand All @@ -86,8 +86,6 @@ namespace {{ spec.title | caseUcfirst }}
{
SetSelfSigned(true);
}

JsonConvert.DefaultSettings = () => DeserializerSettings;
}

public Client SetSelfSigned(bool selfSigned)
Expand Down Expand Up @@ -158,19 +156,23 @@ namespace {{ spec.title | caseUcfirst }}
{
if (parameter.Key == "file")
{
form.Add(((MultipartFormDataContent)parameters["file"]).First()!);
var fileContent = parameters["file"] as MultipartFormDataContent;
if (fileContent != null)
{
form.Add(fileContent.First()!);
}
}
else if (parameter.Value is IEnumerable<object> enumerable)
{
var list = new List<object>(enumerable);
for (int index = 0; index < list.Count; index++)
{
form.Add(new StringContent(list[index].ToString()!), $"{parameter.Key}[{index}]");
form.Add(new StringContent(list[index]?.ToString() ?? string.Empty), $"{parameter.Key}[{index}]");
}
}
else
{
form.Add(new StringContent(parameter.Value.ToString()!), parameter.Key);
form.Add(new StringContent(parameter.Value?.ToString() ?? string.Empty), parameter.Key);
}
}
request.Content = form;
Expand Down Expand Up @@ -243,16 +245,27 @@ namespace {{ spec.title | caseUcfirst }}
}

if (contentType.Contains("application/json")) {
message = JObject.Parse(text)["message"]!.ToString();
type = JObject.Parse(text)["type"]?.ToString() ?? string.Empty;
try
{
using var errorDoc = JsonDocument.Parse(text);
message = errorDoc.RootElement.GetProperty("message").GetString() ?? "";
if (errorDoc.RootElement.TryGetProperty("type", out var typeElement))
{
type = typeElement.GetString() ?? "";
}
}
catch
{
message = text;
}
} else {
message = text;
}

throw new {{spec.title | caseUcfirst}}Exception(message, code, type, text);
}

return response.Headers.Location.OriginalString;
return response.Headers.Location?.OriginalString ?? string.Empty;
}

public Task<Dictionary<string, object?>> Call(
Expand Down Expand Up @@ -298,8 +311,19 @@ namespace {{ spec.title | caseUcfirst }}
var type = "";

if (isJson) {
message = JObject.Parse(text)["message"]!.ToString();
type = JObject.Parse(text)["type"]?.ToString() ?? string.Empty;
try
{
using var errorDoc = JsonDocument.Parse(text);
message = errorDoc.RootElement.GetProperty("message").GetString() ?? "";
if (errorDoc.RootElement.TryGetProperty("type", out var typeElement))
{
type = typeElement.GetString() ?? "";
}
}
catch
{
message = text;
}
} else {
message = text;
}
Expand All @@ -311,13 +335,13 @@ namespace {{ spec.title | caseUcfirst }}
{
var responseString = await response.Content.ReadAsStringAsync();

var dict = JsonConvert.DeserializeObject<Dictionary<string, object>>(
var dict = JsonSerializer.Deserialize<Dictionary<string, object>>(
responseString,
DeserializerSettings);
DeserializerOptions);

if (convert != null)
if (convert != null && dict != null)
{
return convert(dict!);
return convert(dict);
}

return (dict as T)!;
Expand All @@ -337,7 +361,16 @@ namespace {{ spec.title | caseUcfirst }}
string? idParamName = null,
Action<UploadProgress>? onProgress = null) where T : class
{
if (string.IsNullOrEmpty(paramName))
throw new ArgumentException("Parameter name cannot be null or empty", nameof(paramName));

if (!parameters.ContainsKey(paramName))
throw new ArgumentException($"Parameter {paramName} not found", nameof(paramName));

var input = parameters[paramName] as InputFile;
if (input == null)
throw new ArgumentException($"Parameter {paramName} must be an InputFile", nameof(paramName));

var size = 0L;
switch(input.SourceType)
{
Expand All @@ -347,10 +380,16 @@ namespace {{ spec.title | caseUcfirst }}
size = info.Length;
break;
case "stream":
size = (input.Data as Stream).Length;
var stream = input.Data as Stream;
if (stream == null)
throw new InvalidOperationException("Stream data is null");
size = stream.Length;
break;
case "bytes":
size = ((byte[])input.Data).Length;
var bytes = input.Data as byte[];
if (bytes == null)
throw new InvalidOperationException("Byte array data is null");
size = bytes.Length;
break;
};

Expand All @@ -364,10 +403,16 @@ namespace {{ spec.title | caseUcfirst }}
{
case "path":
case "stream":
await (input.Data as Stream).ReadAsync(buffer, 0, (int)size);
var dataStream = input.Data as Stream;
if (dataStream == null)
throw new InvalidOperationException("Stream data is null");
await dataStream.ReadAsync(buffer, 0, (int)size);
break;
case "bytes":
buffer = (byte[])input.Data;
var dataBytes = input.Data as byte[];
if (dataBytes == null)
throw new InvalidOperationException("Byte array data is null");
buffer = dataBytes;
break;
}

Expand All @@ -393,14 +438,16 @@ namespace {{ spec.title | caseUcfirst }}
// Make a request to check if a file already exists
var current = await Call<Dictionary<string, object?>>(
method: "GET",
path: $"{path}/{parameters[idParamName]}",
path: $"{path}/{parameters[idParamName!]}",
new Dictionary<string, string> { { "content-type", "application/json" } },
parameters: new Dictionary<string, object?>()
);
var chunksUploaded = (long)current["chunksUploaded"];
offset = chunksUploaded * ChunkSize;
if (current.TryGetValue("chunksUploaded", out var chunksUploadedValue) && chunksUploadedValue != null)
{
offset = Convert.ToInt64(chunksUploadedValue) * ChunkSize;
}
}
catch (Exception ex)
catch
{
// ignored as it mostly means file not found
}
Expand All @@ -413,6 +460,8 @@ namespace {{ spec.title | caseUcfirst }}
case "path":
case "stream":
var stream = input.Data as Stream;
if (stream == null)
throw new InvalidOperationException("Stream data is null");
stream.Seek(offset, SeekOrigin.Begin);
await stream.ReadAsync(buffer, 0, ChunkSize);
break;
Expand Down Expand Up @@ -445,12 +494,12 @@ namespace {{ spec.title | caseUcfirst }}
var id = result.ContainsKey("$id")
? result["$id"]?.ToString() ?? string.Empty
: string.Empty;
var chunksTotal = result.ContainsKey("chunksTotal")
? (long)result["chunksTotal"]
: 0;
var chunksUploaded = result.ContainsKey("chunksUploaded")
? (long)result["chunksUploaded"]
: 0;
var chunksTotal = result.TryGetValue("chunksTotal", out var chunksTotalValue) && chunksTotalValue != null
? Convert.ToInt64(chunksTotalValue)
: 0L;
var chunksUploaded = result.TryGetValue("chunksUploaded", out var chunksUploadedValue) && chunksUploadedValue != null
? Convert.ToInt64(chunksUploadedValue)
: 0L;

headers["x-appwrite-id"] = id;

Expand All @@ -463,7 +512,11 @@ namespace {{ spec.title | caseUcfirst }}
chunksUploaded: chunksUploaded));
}

return converter(result);
// Convert to non-nullable dictionary for converter
var nonNullableResult = result.Where(kvp => kvp.Value != null)
.ToDictionary(kvp => kvp.Key, kvp => kvp.Value!);

return converter(nonNullableResult);
}
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,44 @@
using System;
using System.Collections.Generic;
using System.Text.Json;
using System.Text.Json.Serialization;

namespace {{ spec.title | caseUcfirst }}.Converters
{
public class ObjectToInferredTypesConverter : JsonConverter<object>
{
public override object Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options)
{
switch (reader.TokenType)
{
case JsonTokenType.True:
return true;
case JsonTokenType.False:
return false;
case JsonTokenType.Number:
if (reader.TryGetInt64(out long l))
{
return l;
}
return reader.GetDouble();
case JsonTokenType.String:
if (reader.TryGetDateTime(out DateTime datetime))
{
return datetime;
}
return reader.GetString()!;
case JsonTokenType.StartObject:
return JsonSerializer.Deserialize<Dictionary<string, object>>(ref reader, options)!;
case JsonTokenType.StartArray:
return JsonSerializer.Deserialize<object[]>(ref reader, options)!;
default:
return JsonDocument.ParseValue(ref reader).RootElement.Clone();
}
}

public override void Write(Utf8JsonWriter writer, object objectToWrite, JsonSerializerOptions options)
{
JsonSerializer.Serialize(writer, objectToWrite, objectToWrite.GetType(), options);
}
}
}
Loading