Skip to content

Commit 46f8a67

Browse files
authored
[csharp] Move nullable reference types switch to abstract (#9661)
* moved switch to abstract * build samples * added nullable option to csproj * removed unused method * added switch back to aspnetcore * build samples
1 parent f1ee1cb commit 46f8a67

File tree

9 files changed

+36
-25
lines changed

9 files changed

+36
-25
lines changed

docs/generators/aspnetcore.md

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -19,7 +19,7 @@ These options may be applied as additional-properties (cli) or configOptions (pl
1919
|licenseUrl|The URL of the license| |http://localhost|
2020
|modelClassModifier|Model Class Modifier can be nothing or partial| |partial|
2121
|newtonsoftVersion|Version for Microsoft.AspNetCore.Mvc.NewtonsoftJson for ASP.NET Core 3.0+| |3.0.0|
22-
|nullableReferenceTypes|Annotate Project with <Nullable>annotations</Nullable> and use ? annotation on all nullable attributes. Only supported on C# 8 / ASP.NET Core 3.0 or newer.| |false|
22+
|nullableReferenceTypes|Use nullable annotations in the project. Only supported on C# 8 / ASP.NET Core 3.0 or newer.| |false|
2323
|operationIsAsync|Set methods to async or sync (default).| |false|
2424
|operationModifier|Operation Modifier can be virtual or abstract|<dl><dt>**virtual**</dt><dd>Keep method virtual</dd><dt>**abstract**</dt><dd>Make method abstract</dd></dl>|virtual|
2525
|operationResultTask|Set methods result to Task&lt;&gt;.| |false|

docs/generators/csharp-netcore.md

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -17,6 +17,7 @@ These options may be applied as additional-properties (cli) or configOptions (pl
1717
|modelPropertyNaming|Naming convention for the property: 'camelCase', 'PascalCase', 'snake_case' and 'original', which keeps the original name| |PascalCase|
1818
|netCoreProjectFile|Use the new format (.NET Core) for .NET project files (.csproj).| |false|
1919
|nonPublicApi|Generates code with reduced access modifiers; allows embedding elsewhere without exposing non-public API calls to consumers.| |false|
20+
|nullableReferenceTypes|Use nullable annotations in the project. Only supported on C# 8 / ASP.NET Core 3.0 or newer.| |false|
2021
|optionalAssemblyInfo|Generate AssemblyInfo.cs.| |true|
2122
|optionalEmitDefaultValues|Set DataMember's EmitDefaultValue.| |false|
2223
|optionalMethodArgument|C# Optional method argument, e.g. void square(int x=10) (.net 4.0+ only).| |true|

modules/openapi-generator/src/main/java/org/openapitools/codegen/CodegenConstants.java

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -211,6 +211,9 @@ public class CodegenConstants {
211211
public static final String DOTNET_FRAMEWORK = "targetFramework";
212212
public static final String DOTNET_FRAMEWORK_DESC = "The target .NET framework version. To target multiple frameworks, use `;` as the separator, e.g. `netstandard2.1;netcoreapp3.0`";
213213

214+
public static final String NULLABLE_REFERENCE_TYPES = "nullableReferenceTypes";
215+
public static final String NULLABLE_REFERENCE_TYPES_DESC = "Use nullable annotations in the project. Only supported on C# 8 / ASP.NET Core 3.0 or newer.";
216+
214217
public static final String TEMPLATING_ENGINE = "templatingEngine";
215218
public static final String TEMPLATING_ENGINE_DESC = "The templating engine plugin to use: \"mustache\" (default) or \"handlebars\" (beta)";
216219

modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/AbstractCSharpCodegen.java

Lines changed: 14 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -47,6 +47,7 @@ public abstract class AbstractCSharpCodegen extends DefaultCodegen implements Co
4747
protected boolean useCollection = false;
4848
protected boolean returnICollection = false;
4949
protected boolean netCoreProjectFileFlag = false;
50+
protected boolean nullReferenceTypesFlag = false;
5051

5152
protected String modelPropertyNaming = CodegenConstants.MODEL_PROPERTY_NAMING_TYPE.PascalCase.name();
5253

@@ -356,6 +357,12 @@ public void processOpts() {
356357
additionalProperties.put(CodegenConstants.NETCORE_PROJECT_FILE, netCoreProjectFileFlag);
357358
}
358359

360+
if (additionalProperties.containsKey(CodegenConstants.NULLABLE_REFERENCE_TYPES)) {
361+
setNullableReferenceTypes(convertPropertyToBooleanAndWriteBack(CodegenConstants.NULLABLE_REFERENCE_TYPES));
362+
} else {
363+
additionalProperties.put(CodegenConstants.NULLABLE_REFERENCE_TYPES, nullReferenceTypesFlag);
364+
}
365+
359366
if (additionalProperties.containsKey(CodegenConstants.INTERFACE_PREFIX)) {
360367
String useInterfacePrefix = additionalProperties.get(CodegenConstants.INTERFACE_PREFIX).toString();
361368
if ("false".equals(useInterfacePrefix.toLowerCase(Locale.ROOT))) {
@@ -1112,6 +1119,13 @@ public String getInterfacePrefix() {
11121119
return interfacePrefix;
11131120
}
11141121

1122+
public void setNullableReferenceTypes(final Boolean nullReferenceTypesFlag){
1123+
this.nullReferenceTypesFlag = nullReferenceTypesFlag;
1124+
if (nullReferenceTypesFlag == true){
1125+
this.nullableType.add("string");
1126+
}
1127+
}
1128+
11151129
public void setInterfacePrefix(final String interfacePrefix) {
11161130
this.interfacePrefix = interfacePrefix;
11171131
}

modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/AspNetCoreServerCodegen.java

Lines changed: 5 additions & 23 deletions
Original file line numberDiff line numberDiff line change
@@ -60,7 +60,6 @@ public class AspNetCoreServerCodegen extends AbstractCSharpCodegen {
6060
public static final String USE_NEWTONSOFT = "useNewtonsoft";
6161
public static final String USE_DEFAULT_ROUTING = "useDefaultRouting";
6262
public static final String NEWTONSOFT_VERSION = "newtonsoftVersion";
63-
public static final String NULLABLE_REFERENCE_TYPES = "nullableReferenceTypes";
6463

6564
private String packageGuid = "{" + randomUUID().toString().toUpperCase(Locale.ROOT) + "}";
6665
private String userSecretsGuid = randomUUID().toString();
@@ -85,7 +84,6 @@ public class AspNetCoreServerCodegen extends AbstractCSharpCodegen {
8584
private boolean useFrameworkReference = false;
8685
private boolean useNewtonsoft = true;
8786
private boolean useDefaultRouting = true;
88-
private boolean nullableReferenceTypes = false;
8987
private String newtonsoftVersion = "3.0.0";
9088

9189
public AspNetCoreServerCodegen() {
@@ -211,6 +209,10 @@ public AspNetCoreServerCodegen() {
211209
cliOptions.add(swashbuckleVersion);
212210

213211
// CLI Switches
212+
addSwitch(CodegenConstants.NULLABLE_REFERENCE_TYPES,
213+
CodegenConstants.NULLABLE_REFERENCE_TYPES_DESC,
214+
this.nullReferenceTypesFlag);
215+
214216
addSwitch(CodegenConstants.SORT_PARAMS_BY_REQUIRED_FLAG,
215217
CodegenConstants.SORT_PARAMS_BY_REQUIRED_FLAG_DESC,
216218
sortParamsByRequiredFlag);
@@ -251,11 +253,6 @@ public AspNetCoreServerCodegen() {
251253
"Use default routing for the ASP.NET Core version.",
252254
useDefaultRouting);
253255

254-
addSwitch(NULLABLE_REFERENCE_TYPES,
255-
"Annotate Project with <Nullable>annotations</Nullable> and use ? annotation on all nullable attributes. " +
256-
"Only supported on C# 8 / ASP.NET Core 3.0 or newer.",
257-
nullableReferenceTypes);
258-
259256
addOption(CodegenConstants.ENUM_NAME_SUFFIX,
260257
CodegenConstants.ENUM_NAME_SUFFIX_DESC,
261258
enumNameSuffix);
@@ -373,7 +370,6 @@ public void processOpts() {
373370
setIsFramework();
374371
setUseNewtonsoft();
375372
setUseEndpointRouting();
376-
setNullableReferenceTypes();
377373

378374
supportingFiles.add(new SupportingFile("build.sh.mustache", "", "build.sh"));
379375
supportingFiles.add(new SupportingFile("build.bat.mustache", "", "build.bat"));
@@ -528,7 +524,7 @@ public String toRegularExpression(String pattern) {
528524
@Override
529525
public String getNullableType(Schema p, String type) {
530526
if (languageSpecificPrimitives.contains(type)) {
531-
if (isSupportNullable() && ModelUtils.isNullable(p) && (nullableType.contains(type) || nullableReferenceTypes)) {
527+
if (isSupportNullable() && ModelUtils.isNullable(p) && (nullableType.contains(type) || nullReferenceTypesFlag)) {
532528
return type + "?";
533529
} else {
534530
return type;
@@ -657,20 +653,6 @@ private void setUseSwashbuckle() {
657653
}
658654
}
659655

660-
private void setNullableReferenceTypes() {
661-
if (additionalProperties.containsKey(NULLABLE_REFERENCE_TYPES)) {
662-
if (aspnetCoreVersion.getOptValue().startsWith("2.")) {
663-
LOGGER.warn("Nullable annotation are not supported in ASP.NET core version 2. Setting {} to false",
664-
NULLABLE_REFERENCE_TYPES);
665-
additionalProperties.put(NULLABLE_REFERENCE_TYPES, false);
666-
} else {
667-
nullableReferenceTypes = convertPropertyToBooleanAndWriteBack(NULLABLE_REFERENCE_TYPES);
668-
}
669-
} else {
670-
additionalProperties.put(NULLABLE_REFERENCE_TYPES, nullableReferenceTypes);
671-
}
672-
}
673-
674656
private void setOperationIsAsync() {
675657
if (isLibrary) {
676658
operationIsAsync = false;

modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/CSharpNetCoreClientCodegen.java

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -230,6 +230,10 @@ public CSharpNetCoreClientCodegen() {
230230
cliOptions.add(modelPropertyNaming.defaultValue("PascalCase"));
231231

232232
// CLI Switches
233+
addSwitch(CodegenConstants.NULLABLE_REFERENCE_TYPES,
234+
CodegenConstants.NULLABLE_REFERENCE_TYPES_DESC,
235+
this.nullReferenceTypesFlag);
236+
233237
addSwitch(CodegenConstants.HIDE_GENERATION_TIMESTAMP,
234238
CodegenConstants.HIDE_GENERATION_TIMESTAMP_DESC,
235239
this.hideGenerationTimestamp);

modules/openapi-generator/src/main/resources/csharp-netcore/netcore_project.mustache

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -19,6 +19,9 @@
1919
<RepositoryType>git</RepositoryType>{{#releaseNote}}
2020
<PackageReleaseNotes>{{releaseNote}}</PackageReleaseNotes>{{/releaseNote}}{{#packageTags}}
2121
<PackageTags>{{{packageTags}}}</PackageTags>{{/packageTags}}
22+
{{#nullableReferenceTypes}}
23+
<Nullable>annotations</Nullable>
24+
{{/nullableReferenceTypes}}
2225
</PropertyGroup>
2326

2427
<ItemGroup>

modules/openapi-generator/src/main/resources/csharp/netcore_project.mustache

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -15,6 +15,9 @@
1515
<GenerateBindingRedirectsOutputType>true</GenerateBindingRedirectsOutputType>
1616
<RootNamespace>{{packageName}}</RootNamespace>
1717
<Version>{{packageVersion}}</Version>
18+
{{#nullableReferenceTypes}}
19+
<Nullable>annotations</Nullable>
20+
{{/nullableReferenceTypes}}
1821
</PropertyGroup>
1922

2023
<ItemGroup>

modules/openapi-generator/src/test/java/org/openapitools/codegen/csharp/CSharpModelTest.java

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -21,6 +21,7 @@
2121
import io.swagger.v3.oas.models.OpenAPI;
2222
import io.swagger.v3.oas.models.media.*;
2323
import io.swagger.v3.parser.util.SchemaTypeUtil;
24+
import org.openapitools.codegen.CodegenConstants;
2425
import org.openapitools.codegen.CodegenModel;
2526
import org.openapitools.codegen.CodegenProperty;
2627
import org.openapitools.codegen.DefaultCodegen;
@@ -335,7 +336,7 @@ public void nullablePropertyWithNullableReferenceTypesTest() {
335336
.addProperties("subObject", new Schema().addProperties("name", new StringSchema()).nullable(true))
336337
.addRequiredItem("id");
337338
final DefaultCodegen codegen = new AspNetCoreServerCodegen();
338-
codegen.additionalProperties().put(AspNetCoreServerCodegen.NULLABLE_REFERENCE_TYPES, true);
339+
codegen.additionalProperties().put(CodegenConstants.NULLABLE_REFERENCE_TYPES, true);
339340
codegen.processOpts();
340341
OpenAPI openAPI = TestUtils.createOpenAPIWithOneSchema("sample", model);
341342
codegen.setOpenAPI(openAPI);

0 commit comments

Comments
 (0)