Skip to content
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

Dot net 3 support #642

Merged
merged 2 commits into from
Apr 9, 2020
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
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,6 @@
import io.swagger.codegen.v3.CodegenModel;
import io.swagger.codegen.v3.CodegenOperation;
import io.swagger.codegen.v3.CodegenProperty;
import io.swagger.codegen.v3.ISchemaHandler;
import io.swagger.codegen.v3.generators.DefaultCodegenConfig;
import io.swagger.codegen.v3.generators.handlebars.csharp.CsharpHelper;
import io.swagger.codegen.v3.generators.handlebars.lambda.CamelCaseLambda;
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -2,15 +2,12 @@

import com.fasterxml.jackson.core.JsonProcessingException;
import com.samskivert.mustache.Mustache;
import io.swagger.codegen.v3.CodegenArgument;
import io.swagger.codegen.v3.CodegenConstants;
import io.swagger.codegen.v3.CodegenContent;
import io.swagger.codegen.v3.CodegenOperation;
import io.swagger.codegen.v3.CodegenSecurity;
import io.swagger.codegen.v3.CodegenType;
import io.swagger.codegen.v3.SupportingFile;
import io.swagger.codegen.v3.generators.handlebars.ExtensionHelper;
import io.swagger.codegen.v3.utils.URLPathUtil;
import io.swagger.v3.core.util.Json;
import io.swagger.v3.oas.models.OpenAPI;
import io.swagger.v3.oas.models.security.SecurityScheme;
Expand All @@ -19,11 +16,9 @@
import org.slf4j.LoggerFactory;

import java.io.File;
import java.net.URL;
import java.util.Arrays;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import java.util.stream.Collectors;

import static io.swagger.codegen.v3.generators.handlebars.ExtensionHelper.getBooleanValue;
Expand All @@ -35,7 +30,7 @@ public class AspNetCoreServerCodegen extends AbstractCSharpCodegen {
private static final String ASP_NET_CORE_VERSION_OPTION = "--aspnet-core-version";
private static final String INTERFACE_ONLY_OPTION = "--interface-only";
private static final String INTERFACE_CONTROLLER_OPTION = "--interface-controller";
private final String DEFAULT_ASP_NET_CORE_VERSION = "2.2";
private final String DEFAULT_ASP_NET_CORE_VERSION = "3.0";
private String aspNetCoreVersion;

@SuppressWarnings("hiding")
Expand Down Expand Up @@ -151,13 +146,30 @@ public void processOpts() {
supportingFiles.add(new SupportingFile("Program.mustache", packageFolder, "Program.cs"));
supportingFiles.add(new SupportingFile("Project.csproj.mustache", packageFolder, this.packageName + ".csproj"));
supportingFiles.add(new SupportingFile("Dockerfile.mustache", packageFolder, "Dockerfile"));
} else{
supportingFiles.add(new SupportingFile("Filters" + File.separator + "BasePathFilter.mustache", packageFolder + File.separator + "Filters", "BasePathFilter.cs"));
supportingFiles.add(new SupportingFile("Filters" + File.separator + "GeneratePathParamsValidationFilter.mustache", packageFolder + File.separator + "Filters", "GeneratePathParamsValidationFilter.cs"));
supportingFiles.add(new SupportingFile("Startup.mustache", packageFolder, "Startup.cs"));
} else if (aspNetCoreVersion.equals("2.1")) {
apiTemplateFiles.put("2.1/controller.mustache", ".cs");
addInterfaceControllerTemplate();

supportingFiles.add(new SupportingFile("2.1/Program.mustache", packageFolder, "Program.cs"));
supportingFiles.add(new SupportingFile("2.1/Project.csproj.mustache", packageFolder, this.packageName + ".csproj"));
supportingFiles.add(new SupportingFile("2.1/Dockerfile.mustache", packageFolder, "Dockerfile"));
supportingFiles.add(new SupportingFile("Filters" + File.separator + "BasePathFilter.mustache", packageFolder + File.separator + "Filters", "BasePathFilter.cs"));
supportingFiles.add(new SupportingFile("Filters" + File.separator + "GeneratePathParamsValidationFilter.mustache", packageFolder + File.separator + "Filters", "GeneratePathParamsValidationFilter.cs"));
supportingFiles.add(new SupportingFile("Startup.mustache", packageFolder, "Startup.cs"));
} else {
apiTemplateFiles.put("3.0/controller.mustache", ".cs");
addInterfaceControllerTemplate();

supportingFiles.add(new SupportingFile("3.0" + File.separator + "Filters" + File.separator + "BasePathFilter.mustache", packageFolder + File.separator + "Filters", "BasePathFilter.cs"));
supportingFiles.add(new SupportingFile("3.0" + File.separator + "Filters" + File.separator + "GeneratePathParamsValidationFilter.mustache", packageFolder + File.separator + "Filters", "GeneratePathParamsValidationFilter.cs"));

supportingFiles.add(new SupportingFile("3.0/Startup.mustache", packageFolder, "Startup.cs"));
supportingFiles.add(new SupportingFile("3.0/Program.mustache", packageFolder, "Program.cs"));
supportingFiles.add(new SupportingFile("3.0/Project.csproj.mustache", packageFolder, this.packageName + ".csproj"));
supportingFiles.add(new SupportingFile("3.0/Dockerfile.mustache", packageFolder, "Dockerfile"));
}

if (!additionalProperties.containsKey(CodegenConstants.API_PACKAGE)) {
Expand All @@ -178,15 +190,15 @@ public void processOpts() {
supportingFiles.add(new SupportingFile("gitignore", packageFolder, ".gitignore"));
supportingFiles.add(new SupportingFile("appsettings.json", packageFolder, "appsettings.json"));

supportingFiles.add(new SupportingFile("Startup.mustache", packageFolder, "Startup.cs"));
//supportingFiles.add(new SupportingFile("Startup.mustache", packageFolder, "Startup.cs"));

supportingFiles.add(new SupportingFile("validateModel.mustache", packageFolder + File.separator + "Attributes", "ValidateModelStateAttribute.cs"));
supportingFiles.add(new SupportingFile("web.config", packageFolder, "web.config"));

supportingFiles.add(new SupportingFile("Properties" + File.separator + "launchSettings.json", packageFolder + File.separator + "Properties", "launchSettings.json"));

supportingFiles.add(new SupportingFile("Filters" + File.separator + "BasePathFilter.mustache", packageFolder + File.separator + "Filters", "BasePathFilter.cs"));
supportingFiles.add(new SupportingFile("Filters" + File.separator + "GeneratePathParamsValidationFilter.mustache", packageFolder + File.separator + "Filters", "GeneratePathParamsValidationFilter.cs"));
// supportingFiles.add(new SupportingFile("Filters" + File.separator + "BasePathFilter.mustache", packageFolder + File.separator + "Filters", "BasePathFilter.cs"));
// supportingFiles.add(new SupportingFile("Filters" + File.separator + "GeneratePathParamsValidationFilter.mustache", packageFolder + File.separator + "Filters", "GeneratePathParamsValidationFilter.cs"));

supportingFiles.add(new SupportingFile("wwwroot" + File.separator + "README.md", packageFolder + File.separator + "wwwroot", "README.md"));
supportingFiles.add(new SupportingFile("wwwroot" + File.separator + "index.html", packageFolder + File.separator + "wwwroot", "index.html"));
Expand Down
2 changes: 1 addition & 1 deletion src/main/resources/arguments/aspnetcore.yaml
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
arguments:
- option: "--aspnet-core-version"
description: "aspnetcore version to use, current options are: 2.0, 2.1 and 2.2 (default)"
description: "aspnetcore version to use, current options are: 2.0, 2.1, 2.2 and 3.0 (default)"
type: "string"
- option: "--interface-only"
description: "creates interfaces controller only"
Expand Down
18 changes: 18 additions & 0 deletions src/main/resources/handlebars/aspnetcore/3.0/Dockerfile.mustache
Original file line number Diff line number Diff line change
@@ -0,0 +1,18 @@
FROM mcr.microsoft.com/dotnet/core/sdk:{{aspNetCoreVersion}} AS build-env
WORKDIR /app

ENV DOTNET_CLI_TELEMETRY_OPTOUT 1

# copy csproj and restore as distinct layers
COPY *.csproj ./
RUN dotnet restore

# copy everything else and build
COPY . ./
RUN dotnet publish -c Release -o out

# build runtime image
FROM mcr.microsoft.com/dotnet/core/aspnet:{{aspNetCoreVersion}}
WORKDIR /app
COPY --from=build-env /app/out .
ENTRYPOINT ["dotnet", "{{packageName}}.dll"]
Original file line number Diff line number Diff line change
@@ -0,0 +1,51 @@
using System.Linq;
using System.Text.RegularExpressions;
using Swashbuckle.AspNetCore.Swagger;
using Swashbuckle.AspNetCore.SwaggerGen;
using Microsoft.OpenApi.Models;

namespace {{packageName}}.Filters
{
/// <summary>
/// BasePath Document Filter sets BasePath property of Swagger and removes it from the individual URL paths
/// </summary>
public class BasePathFilter : IDocumentFilter
{
/// <summary>
/// Constructor
/// </summary>
/// <param name="basePath">BasePath to remove from Operations</param>
public BasePathFilter(string basePath)
{
BasePath = basePath;
}

/// <summary>
/// Gets the BasePath of the Swagger Doc
/// </summary>
/// <returns>The BasePath of the Swagger Doc</returns>
public string BasePath { get; }

/// <summary>
/// Apply the filter
/// </summary>
/// <param name="swaggerDoc">OpenApiDocument</param>
/// <param name="context">FilterContext</param>
public void Apply(OpenApiDocument swaggerDoc, DocumentFilterContext context)
{
swaggerDoc.Servers.Add(new OpenApiServer() { Url = this.BasePath });

var pathsToModify = swaggerDoc.Paths.Where(p => p.Key.StartsWith(this.BasePath)).ToList();

foreach (var path in pathsToModify)
{
if (path.Key.StartsWith(this.BasePath))
{
string newKey = Regex.Replace(path.Key, $"^{this.BasePath}", string.Empty);
swaggerDoc.Paths.Remove(path.Key);
swaggerDoc.Paths.Add(newKey, path.Value);
}
}
}
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,96 @@
using System.ComponentModel.DataAnnotations;
using System.Linq;
using Microsoft.AspNetCore.Mvc.Controllers;
using Microsoft.OpenApi.Models;
using Swashbuckle.AspNetCore.SwaggerGen;

namespace {{packageName}}.Filters
{
/// <summary>
/// Path Parameter Validation Rules Filter
/// </summary>
public class GeneratePathParamsValidationFilter : IOperationFilter
{
/// <summary>
/// Constructor
/// </summary>
/// <param name="operation">Operation</param>
/// <param name="context">OperationFilterContext</param>
public void Apply(OpenApiOperation operation, OperationFilterContext context)
{
var pars = context.ApiDescription.ParameterDescriptions;

foreach (var par in pars)
{
var swaggerParam = operation.Parameters.SingleOrDefault(p => p.Name == par.Name);

var attributes = ((ControllerParameterDescriptor)par.ParameterDescriptor).ParameterInfo.CustomAttributes;

if (attributes != null && attributes.Count() > 0 && swaggerParam != null)
{
// Required - [Required]
var requiredAttr = attributes.FirstOrDefault(p => p.AttributeType == typeof(RequiredAttribute));
if (requiredAttr != null)
{
swaggerParam.Required = true;
}

// Regex Pattern [RegularExpression]
var regexAttr = attributes.FirstOrDefault(p => p.AttributeType == typeof(RegularExpressionAttribute));
if (regexAttr != null)
{
string regex = (string)regexAttr.ConstructorArguments[0].Value;
if (swaggerParam is OpenApiParameter)
{
((OpenApiParameter)swaggerParam).Schema.Pattern = regex;
}
}

// String Length [StringLength]
int? minLenght = null, maxLength = null;
var stringLengthAttr = attributes.FirstOrDefault(p => p.AttributeType == typeof(StringLengthAttribute));
if (stringLengthAttr != null)
{
if (stringLengthAttr.NamedArguments.Count == 1)
{
minLenght = (int)stringLengthAttr.NamedArguments.Single(p => p.MemberName == "MinimumLength").TypedValue.Value;
}
maxLength = (int)stringLengthAttr.ConstructorArguments[0].Value;
}

var minLengthAttr = attributes.FirstOrDefault(p => p.AttributeType == typeof(MinLengthAttribute));
if (minLengthAttr != null)
{
minLenght = (int)minLengthAttr.ConstructorArguments[0].Value;
}

var maxLengthAttr = attributes.FirstOrDefault(p => p.AttributeType == typeof(MaxLengthAttribute));
if (maxLengthAttr != null)
{
maxLength = (int)maxLengthAttr.ConstructorArguments[0].Value;
}

if (swaggerParam is OpenApiParameter)
{
((OpenApiParameter)swaggerParam).Schema.MinLength = minLenght;
((OpenApiParameter)swaggerParam).Schema.MaxLength = maxLength;
}

// Range [Range]
var rangeAttr = attributes.FirstOrDefault(p => p.AttributeType == typeof(RangeAttribute));
if (rangeAttr != null)
{
int rangeMin = (int)rangeAttr.ConstructorArguments[0].Value;
int rangeMax = (int)rangeAttr.ConstructorArguments[1].Value;

if (swaggerParam is OpenApiParameter)
{
((OpenApiParameter)swaggerParam).Schema.Minimum = rangeMin;
((OpenApiParameter)swaggerParam).Schema.Maximum = rangeMax;
}
}
}
}
}
}
}
29 changes: 29 additions & 0 deletions src/main/resources/handlebars/aspnetcore/3.0/Program.mustache
Original file line number Diff line number Diff line change
@@ -0,0 +1,29 @@
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore;

namespace {{packageName}}
{
/// <summary>
/// Program
/// </summary>
public class Program
{
/// <summary>
/// Main
/// </summary>
/// <param name="args"></param>
public static void Main(string[] args)
{
CreateWebHostBuilder(args).Build().Run();
}

/// <summary>
/// Create the web host builder.
/// </summary>
/// <param name="args"></param>
/// <returns>IWebHostBuilder</returns>
public static IWebHostBuilder CreateWebHostBuilder(string[] args) =>
WebHost.CreateDefaultBuilder(args)
.UseStartup<Startup>();
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,20 @@
<Project Sdk="Microsoft.NET.Sdk.Web">
<PropertyGroup>
<Description>{{packageName}}</Description>
<Copyright>{{packageName}}</Copyright>
<TargetFramework>netcoreapp{{aspNetCoreVersion}}</TargetFramework>
<GenerateDocumentationFile>true</GenerateDocumentationFile>
<PreserveCompilationContext>true</PreserveCompilationContext>
<AssemblyName>{{packageName}}</AssemblyName>
<PackageId>{{packageName}}</PackageId>
</PropertyGroup>
<ItemGroup>
<PackageReference Include="Swashbuckle.AspNetCore" Version="5.0.0-rc4"/>
<PackageReference Include="Swashbuckle.AspNetCore.SwaggerGen" Version="5.0.0-rc4"/>
<PackageReference Include="Swashbuckle.AspNetCore.SwaggerUI" Version="5.0.0-rc4"/>
<PackageReference Include="Swashbuckle.AspNetCore.Annotations" Version="5.0.0-rc4" />
</ItemGroup>
<ItemGroup>
<DotNetCliToolReference Include="Microsoft.VisualStudio.Web.CodeGeneration.Tools" Version="2.0.4" />
</ItemGroup>
</Project>
Loading