Skip to content

Commit

Permalink
[Aspnetcore] Fix nullable warnings part 1 (#15555)
Browse files Browse the repository at this point in the history
* Fix nullable errors in attribute and filters

* Add missing samples
  • Loading branch information
JFCote committed May 18, 2023
1 parent c7d185d commit b7dc6ce
Show file tree
Hide file tree
Showing 101 changed files with 9,624 additions and 54 deletions.
7 changes: 5 additions & 2 deletions .github/workflows/samples-dotnet.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -15,8 +15,10 @@ on:
- 'samples/client/petstore/csharp-netcore/OpenAPIClient-generichost-netcore**/'
- 'samples/server/petstore/aspnetcore-6.0/**'
- 'samples/server/petstore/aspnetcore-6.0-pocoModels/**'
- 'samples/server/petstore/aspnetcore-6.0-project4Models/**'
- 'samples/server/petstore/aspnetcore-6.0-useSwashBuckle/**'
- 'samples/server/petstore/aspnetcore-6.0-useNewtonsoft/**'
- 'samples/server/petstore/aspnetcore-6.0-NewtonsoftFalse/**'
- 'samples/server/petstore/aspnetcore-6.0-nullableReferenceTypes/**'
jobs:
build:
name: Build .Net projects
Expand All @@ -35,7 +37,8 @@ jobs:
- samples/server/petstore/aspnetcore-6.0-pocoModels
- samples/server/petstore/aspnetcore-6.0-project4Models
- samples/server/petstore/aspnetcore-6.0-useSwashBuckle
- samples/server/petstore/aspnetcore-6.0-useNewtonsoft
- samples/server/petstore/aspnetcore-6.0-NewtonsoftFalse
- samples/server/petstore/aspnetcore-6.0-nullableReferenceTypes
steps:
- uses: actions/checkout@v3
- uses: actions/[email protected]
Expand Down
2 changes: 1 addition & 1 deletion bin/configs/aspnetcore-6.0-NewtonsoftFalse.yaml
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
generatorName: aspnetcore
outputDir: samples/server/petstore/aspnetcore-6.0-useNewtonsoft
outputDir: samples/server/petstore/aspnetcore-6.0-NewtonsoftFalse
inputSpec: modules/openapi-generator/src/test/resources/3_0/aspnetcore/petstore.yaml
templateDir: modules/openapi-generator/src/main/resources/aspnetcore/3.0
additionalProperties:
Expand Down
9 changes: 9 additions & 0 deletions bin/configs/aspnetcore-6.0-nullableReferenceTypes.yaml
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
generatorName: aspnetcore
outputDir: samples/server/petstore/aspnetcore-6.0-nullableReferenceTypes
inputSpec: modules/openapi-generator/src/test/resources/3_0/aspnetcore/petstore.yaml
templateDir: modules/openapi-generator/src/main/resources/aspnetcore/3.0
additionalProperties:
packageGuid: '{3C799344-F285-4669-8FD5-7ED9B795D5C5}'
aspnetCoreVersion: "6.0"
userSecretsGuid: 'cb87e868-8646-48ef-9bb6-344b537d0d37'
nullableReferenceTypes: true
Original file line number Diff line number Diff line change
Expand Up @@ -21,7 +21,7 @@ namespace {{packageName}}.Converters
/// <param name="context"></param>
/// <param name="sourceType"></param>
/// <returns></returns>
public override bool CanConvertFrom(ITypeDescriptorContext context, Type sourceType)
public override bool CanConvertFrom(ITypeDescriptorContext{{#nullableReferenceTypes}}?{{/nullableReferenceTypes}} context, Type sourceType)
{
return sourceType == typeof(string) || base.CanConvertFrom(context, sourceType);
}
Expand All @@ -33,15 +33,15 @@ namespace {{packageName}}.Converters
/// <param name="culture"></param>
/// <param name="value"></param>
/// <returns></returns>
public override object ConvertFrom(ITypeDescriptorContext context, CultureInfo culture, object value)
public override object{{#nullableReferenceTypes}}?{{/nullableReferenceTypes}} ConvertFrom(ITypeDescriptorContext{{#nullableReferenceTypes}}?{{/nullableReferenceTypes}} context, CultureInfo{{#nullableReferenceTypes}}?{{/nullableReferenceTypes}} culture, object value)
{
var s = value as string;
if (string.IsNullOrEmpty(s))
{
return null;
}

return {{#useNewtonsoft}}JsonConvert.DeserializeObject{{/useNewtonsoft}}{{^useNewtonsoft}}JsonSerializer.Deserialize{{/useNewtonsoft}}<T>(@"""" + value.ToString() + @"""");
return {{#useNewtonsoft}}JsonConvert.DeserializeObject{{/useNewtonsoft}}{{^useNewtonsoft}}JsonSerializer.Deserialize{{/useNewtonsoft}}<T>(@"""" + value + @"""");
}
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -19,13 +19,12 @@ namespace {{packageName}}.Attributes
public override void OnActionExecuting(ActionExecutingContext context)
{
// Per https://blog.markvincze.com/how-to-validate-action-parameters-with-dataannotation-attributes/
var descriptor = context.ActionDescriptor as ControllerActionDescriptor;
if (descriptor != null)
if (context.ActionDescriptor is ControllerActionDescriptor descriptor)
{
foreach (var parameter in descriptor.MethodInfo.GetParameters())
{
object args = null;
if (context.ActionArguments.ContainsKey(parameter.Name))
object{{#nullableReferenceTypes}}?{{/nullableReferenceTypes}} args = null;
if ({{#nullableReferenceTypes}}parameter.Name != null && {{/nullableReferenceTypes}}context.ActionArguments.ContainsKey(parameter.Name))
{
args = context.ActionArguments[parameter.Name];
}
Expand All @@ -40,17 +39,16 @@ namespace {{packageName}}.Attributes
}
}

private void ValidateAttributes(ParameterInfo parameter, object args, ModelStateDictionary modelState)
private void ValidateAttributes(ParameterInfo parameter, object{{#nullableReferenceTypes}}?{{/nullableReferenceTypes}} args, ModelStateDictionary modelState)
{
foreach (var attributeData in parameter.CustomAttributes)
{
var attributeInstance = parameter.GetCustomAttribute(attributeData.AttributeType);
var validationAttribute = attributeInstance as ValidationAttribute;
if (validationAttribute != null)
if (attributeInstance is ValidationAttribute validationAttribute)
{
var isValid = validationAttribute.IsValid(args);
if (!isValid)
if (!isValid{{#nullableReferenceTypes}} && parameter.Name != null{{/nullableReferenceTypes}})
{
modelState.AddModelError(parameter.Name, validationAttribute.FormatErrorMessage(parameter.Name));
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -19,8 +19,7 @@ public class ValidateModelStateAttribute : ActionFilterAttribute
public override void OnActionExecuting(ActionExecutingContext context)
{
// Per https://blog.markvincze.com/how-to-validate-action-parameters-with-dataannotation-attributes/
var descriptor = context.ActionDescriptor as ControllerActionDescriptor;
if (descriptor != null)
if (context.ActionDescriptor is ControllerActionDescriptor descriptor)
{
foreach (var parameter in descriptor.MethodInfo.GetParameters())
{
Expand All @@ -46,8 +45,7 @@ private void ValidateAttributes(ParameterInfo parameter, object args, ModelState
{
var attributeInstance = parameter.GetCustomAttribute(attributeData.AttributeType);

var validationAttribute = attributeInstance as ValidationAttribute;
if (validationAttribute != null)
if (attributeInstance is ValidationAttribute validationAttribute)
{
var isValid = validationAttribute.IsValid(args);
if (!isValid)
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -36,7 +36,7 @@ public override object ConvertFrom(ITypeDescriptorContext context, CultureInfo c
return null;
}

return JsonConvert.DeserializeObject<T>(@"""" + value.ToString() + @"""");
return JsonConvert.DeserializeObject<T>(@"""" + value + @"""");
}
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -19,8 +19,7 @@ public class ValidateModelStateAttribute : ActionFilterAttribute
public override void OnActionExecuting(ActionExecutingContext context)
{
// Per https://blog.markvincze.com/how-to-validate-action-parameters-with-dataannotation-attributes/
var descriptor = context.ActionDescriptor as ControllerActionDescriptor;
if (descriptor != null)
if (context.ActionDescriptor is ControllerActionDescriptor descriptor)
{
foreach (var parameter in descriptor.MethodInfo.GetParameters())
{
Expand All @@ -46,8 +45,7 @@ private void ValidateAttributes(ParameterInfo parameter, object args, ModelState
{
var attributeInstance = parameter.GetCustomAttribute(attributeData.AttributeType);

var validationAttribute = attributeInstance as ValidationAttribute;
if (validationAttribute != null)
if (attributeInstance is ValidationAttribute validationAttribute)
{
var isValid = validationAttribute.IsValid(args);
if (!isValid)
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -36,7 +36,7 @@ public override object ConvertFrom(ITypeDescriptorContext context, CultureInfo c
return null;
}

return JsonConvert.DeserializeObject<T>(@"""" + value.ToString() + @"""");
return JsonConvert.DeserializeObject<T>(@"""" + value + @"""");
}
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -19,8 +19,7 @@ public class ValidateModelStateAttribute : ActionFilterAttribute
public override void OnActionExecuting(ActionExecutingContext context)
{
// Per https://blog.markvincze.com/how-to-validate-action-parameters-with-dataannotation-attributes/
var descriptor = context.ActionDescriptor as ControllerActionDescriptor;
if (descriptor != null)
if (context.ActionDescriptor is ControllerActionDescriptor descriptor)
{
foreach (var parameter in descriptor.MethodInfo.GetParameters())
{
Expand All @@ -46,8 +45,7 @@ private void ValidateAttributes(ParameterInfo parameter, object args, ModelState
{
var attributeInstance = parameter.GetCustomAttribute(attributeData.AttributeType);

var validationAttribute = attributeInstance as ValidationAttribute;
if (validationAttribute != null)
if (attributeInstance is ValidationAttribute validationAttribute)
{
var isValid = validationAttribute.IsValid(args);
if (!isValid)
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -36,7 +36,7 @@ public override object ConvertFrom(ITypeDescriptorContext context, CultureInfo c
return null;
}

return JsonConvert.DeserializeObject<T>(@"""" + value.ToString() + @"""");
return JsonConvert.DeserializeObject<T>(@"""" + value + @"""");
}
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,23 @@
# OpenAPI Generator Ignore
# Generated by openapi-generator https://github.com/openapitools/openapi-generator

# Use this file to prevent files from being overwritten by the generator.
# The patterns follow closely to .gitignore or .dockerignore.

# As an example, the C# client generator defines ApiClient.cs.
# You can make changes and tell OpenAPI Generator to ignore just this file by uncommenting the following line:
#ApiClient.cs

# You can match any string of characters against a directory, file or extension with a single asterisk (*):
#foo/*/qux
# The above matches foo/bar/qux and foo/baz/qux, but not foo/bar/baz/qux

# You can recursively match patterns against a directory, file or extension with a double asterisk (**):
#foo/**/qux
# This matches foo/bar/qux, foo/baz/qux, and foo/bar/baz/qux

# You can also negate patterns with an exclamation (!).
# For example, you can ignore all files in a docs folder with the file extension .md:
#docs/*.md
# Then explicitly reverse the ignore rule for a single file:
#!docs/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,38 @@
.openapi-generator-ignore
Org.OpenAPITools.sln
README.md
build.bat
build.sh
src/Org.OpenAPITools/.gitignore
src/Org.OpenAPITools/Attributes/ValidateModelStateAttribute.cs
src/Org.OpenAPITools/Authentication/ApiAuthentication.cs
src/Org.OpenAPITools/Controllers/FakeApi.cs
src/Org.OpenAPITools/Controllers/PetApi.cs
src/Org.OpenAPITools/Controllers/StoreApi.cs
src/Org.OpenAPITools/Controllers/UserApi.cs
src/Org.OpenAPITools/Converters/CustomEnumConverter.cs
src/Org.OpenAPITools/Dockerfile
src/Org.OpenAPITools/Filters/BasePathFilter.cs
src/Org.OpenAPITools/Filters/GeneratePathParamsValidationFilter.cs
src/Org.OpenAPITools/Formatters/InputFormatterStream.cs
src/Org.OpenAPITools/Models/Animal.cs
src/Org.OpenAPITools/Models/ApiResponse.cs
src/Org.OpenAPITools/Models/Cat.cs
src/Org.OpenAPITools/Models/CatAllOf.cs
src/Org.OpenAPITools/Models/Category.cs
src/Org.OpenAPITools/Models/Dog.cs
src/Org.OpenAPITools/Models/DogAllOf.cs
src/Org.OpenAPITools/Models/Order.cs
src/Org.OpenAPITools/Models/Pet.cs
src/Org.OpenAPITools/Models/Tag.cs
src/Org.OpenAPITools/Models/User.cs
src/Org.OpenAPITools/OpenApi/TypeExtensions.cs
src/Org.OpenAPITools/Org.OpenAPITools.csproj
src/Org.OpenAPITools/Program.cs
src/Org.OpenAPITools/Properties/launchSettings.json
src/Org.OpenAPITools/Startup.cs
src/Org.OpenAPITools/appsettings.Development.json
src/Org.OpenAPITools/appsettings.json
src/Org.OpenAPITools/wwwroot/README.md
src/Org.OpenAPITools/wwwroot/index.html
src/Org.OpenAPITools/wwwroot/openapi-original.json
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
7.0.0-SNAPSHOT
Original file line number Diff line number Diff line change
@@ -0,0 +1,22 @@

Microsoft Visual Studio Solution File, Format Version 12.00
# Visual Studio 15
VisualStudioVersion = 15.0.27428.2043
MinimumVisualStudioVersion = 10.0.40219.1
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Org.OpenAPITools", "src\Org.OpenAPITools\Org.OpenAPITools.csproj", "{3C799344-F285-4669-8FD5-7ED9B795D5C5}"
EndProject
Global
GlobalSection(SolutionConfigurationPlatforms) = preSolution
Debug|Any CPU = Debug|Any CPU
Release|Any CPU = Release|Any CPU
EndGlobalSection
GlobalSection(ProjectConfigurationPlatforms) = postSolution
{3C799344-F285-4669-8FD5-7ED9B795D5C5}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{3C799344-F285-4669-8FD5-7ED9B795D5C5}.Debug|Any CPU.Build.0 = Debug|Any CPU
{3C799344-F285-4669-8FD5-7ED9B795D5C5}.Release|Any CPU.ActiveCfg = Release|Any CPU
{3C799344-F285-4669-8FD5-7ED9B795D5C5}.Release|Any CPU.Build.0 = Release|Any CPU
EndGlobalSection
GlobalSection(SolutionProperties) = preSolution
HideSolutionNode = FALSE
EndGlobalSection
EndGlobal
50 changes: 50 additions & 0 deletions samples/server/petstore/aspnetcore-6.0-NewtonsoftFalse/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,50 @@
# Org.OpenAPITools - ASP.NET Core 6.0 Server

This is a sample server Petstore server. For this sample, you can use the api key `special-key` to test the authorization filters.

## Upgrade NuGet Packages

NuGet packages get frequently updated.

To upgrade this solution to the latest version of all NuGet packages, use the dotnet-outdated tool.


Install dotnet-outdated tool:

```
dotnet tool install --global dotnet-outdated-tool
```

Upgrade only to new minor versions of packages

```
dotnet outdated --upgrade --version-lock Major
```

Upgrade to all new versions of packages (more likely to include breaking API changes)

```
dotnet outdated --upgrade
```


## Run

Linux/OS X:

```
sh build.sh
```

Windows:

```
build.bat
```
## Run in Docker

```
cd src/Org.OpenAPITools
docker build -t org.openapitools .
docker run -p 5000:8080 org.openapitools
```
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
:: Generated by: https://openapi-generator.tech
::

@echo off

dotnet restore src\Org.OpenAPITools
dotnet build src\Org.OpenAPITools
echo Now, run the following to start the project: dotnet run -p src\Org.OpenAPITools\Org.OpenAPITools.csproj --launch-profile web.
echo.
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
#!/usr/bin/env bash
#
# Generated by: https://openapi-generator.tech
#

dotnet restore src/Org.OpenAPITools/ && \
dotnet build src/Org.OpenAPITools/ && \
echo "Now, run the following to start the project: dotnet run -p src/Org.OpenAPITools/Org.OpenAPITools.csproj --launch-profile web"
Loading

0 comments on commit b7dc6ce

Please sign in to comment.