Skip to content
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
The table of contents is too big for display.
Diff view
Diff view
  •  
  •  
  •  
2 changes: 1 addition & 1 deletion docs/generators/csharp.md
Original file line number Diff line number Diff line change
Expand Up @@ -52,7 +52,7 @@ These options may be applied as additional-properties (cli) or configOptions (pl
|useDateTimeOffset|Use DateTimeOffset to model date-time properties| |false|
|useIntForTimeout|Use int for Timeout (fall back to v7.9.0 templates). This option (for restsharp only) will be deprecated so please migrated to TimeSpan instead.| |false|
|useOneOfDiscriminatorLookup|Use the discriminator's mapping in oneOf to speed up the model lookup. IMPORTANT: Validation (e.g. one and only one match in oneOf's schemas) will be skipped.| |false|
|useSourceGeneration|Use source generation where available (only `generichost` library supports this option).| |false|
|useSourceGeneration|Use a shared source-generated JSON serialization context (only `generichost` library supports this option).| |false|
|useVirtualForHooks|Generate code that exposes public virtual hooks on ApiClient to customize low-level HTTP requests (only `restsharp`. `httpclient` libraries support this option).| |false|
|validatable|Generates self-validatable models.| |true|
|zeroBasedEnums|Enumerations with string values will start from 0 when true, 1 when false. If not set, enumerations with string values will start from 0 if the first value is 'unknown', case insensitive.| |null|
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -61,6 +61,7 @@ public class CSharpClientCodegen extends AbstractCSharpCodegen {
protected static final String MCS_NET_VERSION_KEY = "x-mcs-sdk";
protected static final String SUPPORTS_UWP = "supportsUWP";
protected static final String SUPPORTS_RETRY = "supportsRetry";
private static final String X_JSON_SERIALIZABLE_TYPES = "x-json-serializable-types";

protected static final String NET_STANDARD = "netStandard";

Expand Down Expand Up @@ -365,7 +366,7 @@ public CSharpClientCodegen() {
this.equatable);

addSwitch("useSourceGeneration",
"Use source generation where available (only `generichost` library supports this option).",
"Use a shared source-generated JSON serialization context (only `generichost` library supports this option).",
this.getUseSourceGeneration());

addSwitch(CodegenConstants.USE_VIRTUAL_FOR_HOOKS,
Expand Down Expand Up @@ -1168,6 +1169,9 @@ public void addGenericHostSupportingFiles(final String clientPackageDir, final S
supportingFiles.add(new SupportingFile("ApiResponse`1.mustache", clientPackageDir, "ApiResponse`1.cs"));
supportingFiles.add(new SupportingFile("ClientUtils.mustache", clientPackageDir, "ClientUtils.cs"));
supportingFiles.add(new SupportingFile("HostConfiguration.mustache", clientPackageDir, "HostConfiguration.cs"));
if (useSourceGeneration) {
supportingFiles.add(new SupportingFile("SourceGenerationContext.mustache", clientPackageDir, "OpenApiSerializationContext.cs"));
}
supportingFiles.add(new SupportingFile("ApiFactory.mustache", clientPackageDir, "ApiFactory.cs"));
supportingFiles.add(new SupportingFile("DateTimeFormatHelper.mustache", clientPackageDir, "DateTimeFormatHelper.cs"));
supportingFiles.add(new SupportingFile("ApiResponseEventArgs`1.mustache", clientPackageDir, "ApiResponseEventArgs.cs"));
Expand Down Expand Up @@ -1720,6 +1724,106 @@ protected void patchVendorExtensionNullableValueType(CodegenParameter parameter)
}
}

@Override
public Map<String, ModelsMap> postProcessAllModels(Map<String, ModelsMap> objs) {
Map<String, ModelsMap> processed = super.postProcessAllModels(objs);
if (!GENERICHOST.equals(getLibrary()) || !useSourceGeneration) {
return processed;
}

List<CodegenModel> models = processed.values().stream()
.flatMap(modelsMap -> modelsMap.getModels().stream())
.map(ModelMap::getModel)
.sorted(Comparator.comparing(model -> model.classname))
.collect(Collectors.toList());
Set<String> typeInfoPropertyNames = models.stream()
.map(model -> model.classname.replace("@", ""))
.collect(Collectors.toCollection(HashSet::new));
Set<String> serializableTypeNames = new HashSet<>();

for (CodegenModel model : models) {
List<Map<String, String>> serializableTypes = new ArrayList<>();

for (CodegenProperty property : model.vars) {
if (property.isEnum && !property.isContainer && property.complexType == null) {
addSerializableEnumTypes(model, property, property, serializableTypes,
serializableTypeNames, typeInfoPropertyNames);
}
if (property.items != null && property.items.isEnum
&& !property.items.isContainer && property.items.complexType == null) {
addSerializableEnumTypes(model, property, property.items, serializableTypes,
serializableTypeNames, typeInfoPropertyNames);
}
}

model.vendorExtensions.put(X_JSON_SERIALIZABLE_TYPES, serializableTypes);
}

return processed;
}

private void addSerializableEnumTypes(CodegenModel model,
CodegenProperty declaringProperty,
CodegenProperty enumProperty,
List<Map<String, String>> serializableTypes,
Set<String> serializableTypeNames,
Set<String> typeInfoPropertyNames) {
if (isEmpty(enumProperty.datatypeWithEnum)) {
return;
}

String enumName = model.classname.replace("@", "") + enumProperty.datatypeWithEnum.replace("@", "");
String enumType = "global::" + packageName + "." + modelPackage() + "."
+ model.classname + "." + enumProperty.datatypeWithEnum;
addSerializableType(enumType, enumName, serializableTypes, serializableTypeNames, typeInfoPropertyNames);

String nullableEnumType = "global::System.Nullable<" + enumType + ">";
addSerializableType(nullableEnumType, "Nullable" + enumName,
serializableTypes, serializableTypeNames, typeInfoPropertyNames);

if (!declaringProperty.required) {
String optionalEnumType = "global::" + packageName + "." + clientPackage
+ ".Option<" + nullableEnumType + ">";
addSerializableType(optionalEnumType, "OptionNullable" + enumName,
serializableTypes, serializableTypeNames, typeInfoPropertyNames);
}

if (declaringProperty.isContainer) {
String containerName = model.classname.replace("@", "")
+ declaringProperty.name.replace("@", "") + "Collection";
addSerializableType(declaringProperty.datatypeWithEnum, containerName,
serializableTypes, serializableTypeNames, typeInfoPropertyNames);

if (!declaringProperty.required) {
String optionalContainerType = "global::" + packageName + "." + clientPackage
+ ".Option<" + declaringProperty.datatypeWithEnum + ">";
addSerializableType(optionalContainerType, "Option" + containerName,
serializableTypes, serializableTypeNames, typeInfoPropertyNames);
}
}
}

private void addSerializableType(String dataType,
String basePropertyName,
List<Map<String, String>> serializableTypes,
Set<String> serializableTypeNames,
Set<String> typeInfoPropertyNames) {
if (!serializableTypeNames.add(dataType)) {
return;
}

String propertyName = basePropertyName;
int suffix = 2;
while (!typeInfoPropertyNames.add(propertyName)) {
propertyName = basePropertyName + suffix++;
}

Map<String, String> serializableType = new LinkedHashMap<>();
serializableType.put("dataType", dataType);
serializableType.put("typeInfoPropertyName", propertyName);
serializableTypes.add(serializableType);
}

@Override
public ModelsMap postProcessModels(ModelsMap objs) {
objs = super.postProcessModels(objs);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,9 @@ using System.Collections.Generic;
using System.Security.Cryptography;
using {{packageName}}.{{clientPackage}};
using {{packageName}}.{{apiPackage}};
{{#useSourceGeneration}}
using {{packageName}}.{{modelPackage}};
{{/useSourceGeneration}}
using {{packageName}}.Extensions;
using Xunit;

Expand Down Expand Up @@ -160,6 +163,24 @@ namespace {{packageName}}.Test.{{apiPackage}}
})
.Build();

{{#useSourceGeneration}}
/// <summary>
/// Test that the shared source-generation context contains every generated model contract.
/// </summary>
[Fact]
public void SourceGenerationContextContainsAllModelContracts()
{
{{#models}}
{{#model}}
{{#vendorExtensions.x-json-serializable-types}}
Assert.NotNull(OpenApiSerializationContext.Default.GetTypeInfo(typeof({{{dataType}}})));
{{/vendorExtensions.x-json-serializable-types}}
Assert.NotNull(OpenApiSerializationContext.Default.GetTypeInfo(typeof(global::{{packageName}}.{{modelPackage}}.{{classname}})));
{{/model}}
{{/models}}
}

{{/useSourceGeneration}}
/// <summary>
/// Test dependency injection when using the configure method
/// </summary>
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -55,21 +55,10 @@ namespace {{packageName}}.{{clientPackage}}
{{#models}}
{{#-first}}
_jsonOptions.TypeInfoResolver = System.Text.Json.Serialization.Metadata.JsonTypeInfoResolver.Combine(
{{/-first}}
{{/models}}
{{#lambda.joinLinesWithComma}}
{{#models}}
{{#model}}
new {{datatypeWithEnum}}{{^datatypeWithEnum}}{{classname}}{{/datatypeWithEnum}}SerializationContext(){{#-last}},{{/-last}}
{{/model}}
{{/models}}
{{/lambda.joinLinesWithComma}}
{{#models}}
{{#-last}}

new OpenApiSerializationContext(),
new System.Text.Json.Serialization.Metadata.DefaultJsonTypeInfoResolver()
);
{{/-last}}
{{/-first}}
{{/models}}

{{/useSourceGeneration}}
Expand Down
Original file line number Diff line number Diff line change
@@ -1,9 +1,41 @@
{{#useSourceGeneration}}
{{>partial_header}}
{{#nrt}}
#nullable enable

{{/nrt}}
using System.Text.Json.Serialization;
using System.Collections.Generic;
{{#models}}
{{#-first}}
using {{packageName}}.{{modelPackage}};
Comment thread
devhl-labs marked this conversation as resolved.
Resolved
{{/-first}}
{{/models}}

{{#models}}
{{#-first}}
namespace {{packageName}}.{{clientPackage}}
{
/// <summary>
/// The {{classname}}SerializationContext
/// The JSON serialization context for the generated OpenAPI models.
/// </summary>
[JsonSourceGenerationOptions(WriteIndented = true, GenerationMode = JsonSourceGenerationMode.Metadata | JsonSourceGenerationMode.Serialization)]
[JsonSerializable(typeof({{classname}}))]
{{>visibility}} partial class {{classname}}SerializationContext : JsonSerializerContext { }
{{/useSourceGeneration}}
{{/-first}}
{{/models}}
{{#models}}
{{#model}}
{{#vendorExtensions.x-json-serializable-types}}
[JsonSerializable(typeof({{{dataType}}}), TypeInfoPropertyName = "{{typeInfoPropertyName}}")]
{{/vendorExtensions.x-json-serializable-types}}
{{/model}}
{{/models}}
{{#models}}
{{#model}}
[JsonSerializable(typeof(global::{{packageName}}.{{modelPackage}}.{{classname}}))]
{{/model}}
{{/models}}
{{#models}}
{{#-last}}
{{>visibility}} partial class OpenApiSerializationContext : JsonSerializerContext { }
}
{{/-last}}
{{/models}}
Original file line number Diff line number Diff line change
Expand Up @@ -25,9 +25,6 @@ using System.ComponentModel.DataAnnotations;
using OpenAPIClientUtils = {{packageName}}.Client.ClientUtils;
{{/useCompareNetObjects}}
{{#useGenericHost}}
{{#useSourceGeneration}}
using System.Text.Json.Serialization.Metadata;
{{/useSourceGeneration}}
using {{packageName}}.{{clientPackage}};
{{/useGenericHost}}
{{#models}}
Expand All @@ -47,7 +44,6 @@ namespace {{packageName}}.{{modelPackage}}
{{>JsonConverter}}

{{/isEnum}}
{{>SourceGenerationContext}}

{{/model}}
{{/lambda.trimTrailingWithNewLine}}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -122,6 +122,59 @@ public void testGenericHostInjectedDateFormatOverridesProperty() throws IOExcept
".CreatedAtOption.Value!.Value.ToString(CreatedAtFormat, global::System.Globalization.CultureInfo.InvariantCulture)");
}

@Test
public void testGenericHostUsesSingleSourceGenerationContextWithUniqueInnerEnumNames() throws IOException {
OpenAPI openAPI = new OpenAPI().components(new Components()
.addSchemas("Asset", new ObjectSchema()
.addProperty("image", new Schema<>().$ref("#/components/schemas/ImageAsset"))
.addProperty("document", new Schema<>().$ref("#/components/schemas/DocumentAsset")))
.addSchemas("ImageAsset", new ObjectSchema()
.addProperty("type", new StringSchema()._enum(List.of("image"))))
.addSchemas("DocumentAsset", new ObjectSchema()
.addProperty("type", new StringSchema()._enum(List.of("document")))));

File output = Files.createTempDirectory("test").toFile().getCanonicalFile();
output.deleteOnExit();
DefaultGenerator generator = new DefaultGenerator();
ClientOptInput input = new ClientOptInput().openAPI(openAPI);
CSharpClientCodegen codegen = new CSharpClientCodegen();
codegen.setLibrary("generichost");
codegen.setOutputDir(output.getAbsolutePath());
codegen.additionalProperties().put("targetFramework", "net10.0");
codegen.additionalProperties().put("useSourceGeneration", true);
input.config(codegen);

Map<String, File> files = generator.opts(input).generate().stream()
.collect(Collectors.toMap(File::getPath, Function.identity()));
File context = files.get(Paths.get(output.getAbsolutePath(),
"src", "Org.OpenAPITools", "Client", "OpenApiSerializationContext.cs").toString());
assertNotNull(context);
assertFileContains(context.toPath(),
"[JsonSerializable(typeof(global::Org.OpenAPITools.Model.DocumentAsset.TypeEnum), TypeInfoPropertyName = \"DocumentAssetTypeEnum\")]",
"[JsonSerializable(typeof(global::System.Nullable<global::Org.OpenAPITools.Model.DocumentAsset.TypeEnum>), TypeInfoPropertyName = \"NullableDocumentAssetTypeEnum\")]",
"[JsonSerializable(typeof(global::Org.OpenAPITools.Client.Option<global::System.Nullable<global::Org.OpenAPITools.Model.DocumentAsset.TypeEnum>>), TypeInfoPropertyName = \"OptionNullableDocumentAssetTypeEnum\")]",
"[JsonSerializable(typeof(global::Org.OpenAPITools.Model.ImageAsset.TypeEnum), TypeInfoPropertyName = \"ImageAssetTypeEnum\")]",
"[JsonSerializable(typeof(global::System.Nullable<global::Org.OpenAPITools.Model.ImageAsset.TypeEnum>), TypeInfoPropertyName = \"NullableImageAssetTypeEnum\")]",
"[JsonSerializable(typeof(global::Org.OpenAPITools.Client.Option<global::System.Nullable<global::Org.OpenAPITools.Model.ImageAsset.TypeEnum>>), TypeInfoPropertyName = \"OptionNullableImageAssetTypeEnum\")]",
"[JsonSerializable(typeof(global::Org.OpenAPITools.Model.Asset))]",
"[JsonSerializable(typeof(global::Org.OpenAPITools.Model.DocumentAsset))]",
"[JsonSerializable(typeof(global::Org.OpenAPITools.Model.ImageAsset))]",
"public partial class OpenApiSerializationContext : JsonSerializerContext");

File hostConfiguration = files.get(Paths.get(output.getAbsolutePath(),
"src", "Org.OpenAPITools", "Client", "HostConfiguration.cs").toString());
assertNotNull(hostConfiguration);
assertFileContains(hostConfiguration.toPath(), "new OpenApiSerializationContext()");
assertFileNotContains(hostConfiguration.toPath(),
"AssetSerializationContext",
"DocumentAssetSerializationContext",
"ImageAssetSerializationContext");

assertFileNotContains(getGeneratedModel(files, output, "Asset").toPath(), "JsonSerializerContext");
assertFileNotContains(getGeneratedModel(files, output, "DocumentAsset").toPath(), "JsonSerializerContext");
assertFileNotContains(getGeneratedModel(files, output, "ImageAsset").toPath(), "JsonSerializerContext");
}

@Test
public void testGenericHostWritesUnsetAndNullInnerStringEnums() throws IOException {
OpenAPI openAPI = new OpenAPI().components(new Components().addSchemas("Pet",
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -144,6 +144,7 @@ src/Org.OpenAPITools/Client/HttpSigningConfiguration.cs
src/Org.OpenAPITools/Client/HttpSigningToken.cs
src/Org.OpenAPITools/Client/JsonSerializerOptionsProvider.cs
src/Org.OpenAPITools/Client/OAuthToken.cs
src/Org.OpenAPITools/Client/OpenApiSerializationContext.cs
src/Org.OpenAPITools/Client/Option.cs
src/Org.OpenAPITools/Client/RateLimitProvider`1.cs
src/Org.OpenAPITools/Client/TokenBase.cs
Expand Down
Loading
Loading