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
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -34,16 +34,19 @@

public class AspNetCoreServerCodegen extends AbstractCSharpCodegen {

public static final String USE_SWASHBUCKLE = "useSwashbuckle";

private String packageGuid = "{" + randomUUID().toString().toUpperCase() + "}";

@SuppressWarnings("hiding")
protected Logger LOGGER = LoggerFactory.getLogger(AspNetCoreServerCodegen.class);

private boolean useSwashbuckle = true;

public AspNetCoreServerCodegen() {
super();

setSourceFolder("src");
outputFolder = "generated-code" + File.separator + this.getName();
outputFolder = "generated-code" + File.separator + getName();

modelTemplateFiles.put("model.mustache", ".cs");
apiTemplateFiles.put("controller.mustache", ".cs");
Expand All @@ -59,11 +62,11 @@ public AspNetCoreServerCodegen() {
// CLI options
addOption(CodegenConstants.PACKAGE_NAME,
"C# package name (convention: Title.Case).",
this.packageName);
packageName);

addOption(CodegenConstants.PACKAGE_VERSION,
"C# package version.",
this.packageVersion);
packageVersion);

addOption(CodegenConstants.OPTIONAL_PROJECT_GUID,
CodegenConstants.OPTIONAL_PROJECT_GUID_DESC,
Expand All @@ -76,19 +79,23 @@ public AspNetCoreServerCodegen() {
// CLI Switches
addSwitch(CodegenConstants.SORT_PARAMS_BY_REQUIRED_FLAG,
CodegenConstants.SORT_PARAMS_BY_REQUIRED_FLAG_DESC,
this.sortParamsByRequiredFlag);
sortParamsByRequiredFlag);

addSwitch(CodegenConstants.USE_DATETIME_OFFSET,
CodegenConstants.USE_DATETIME_OFFSET_DESC,
this.useDateTimeOffsetFlag);
useDateTimeOffsetFlag);

addSwitch(CodegenConstants.USE_COLLECTION,
CodegenConstants.USE_COLLECTION_DESC,
this.useCollection);
useCollection);

addSwitch(CodegenConstants.RETURN_ICOLLECTION,
CodegenConstants.RETURN_ICOLLECTION_DESC,
this.returnICollection);
returnICollection);

addSwitch(USE_SWASHBUCKLE,
"Uses the Swashbuckle.AspNetCore NuGet package for documentation.",
useSwashbuckle);
}

@Override
Expand All @@ -115,7 +122,13 @@ public void processOpts() {
}
additionalProperties.put("packageGuid", packageGuid);

additionalProperties.put("dockerTag", this.packageName.toLowerCase());
if (additionalProperties.containsKey(USE_SWASHBUCKLE)) {
useSwashbuckle = convertPropertyToBooleanAndWriteBack(USE_SWASHBUCKLE);
} else {
additionalProperties.put(USE_SWASHBUCKLE, useSwashbuckle);
}

additionalProperties.put("dockerTag", packageName.toLowerCase());

apiPackage = packageName + ".Controllers";
modelPackage = packageName + ".Models";
Expand All @@ -125,7 +138,7 @@ public void processOpts() {
supportingFiles.add(new SupportingFile("build.sh.mustache", "", "build.sh"));
supportingFiles.add(new SupportingFile("build.bat.mustache", "", "build.bat"));
supportingFiles.add(new SupportingFile("README.mustache", "", "README.md"));
supportingFiles.add(new SupportingFile("Solution.mustache", "", this.packageName + ".sln"));
supportingFiles.add(new SupportingFile("Solution.mustache", "", packageName + ".sln"));
supportingFiles.add(new SupportingFile("Dockerfile.mustache", packageFolder, "Dockerfile"));
supportingFiles.add(new SupportingFile("gitignore", packageFolder, ".gitignore"));
supportingFiles.add(new SupportingFile("appsettings.json", packageFolder, "appsettings.json"));
Expand All @@ -135,12 +148,14 @@ public void processOpts() {
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("Project.csproj.mustache", packageFolder, this.packageName + ".csproj"));
supportingFiles.add(new SupportingFile("Project.csproj.mustache", packageFolder, packageName + ".csproj"));

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"));
if (useSwashbuckle) {
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 All @@ -149,19 +164,6 @@ public void processOpts() {
supportingFiles.add(new SupportingFile("wwwroot" + File.separator + "openapi-original.mustache", packageFolder + File.separator + "wwwroot", "openapi-original.json"));
}

@Override
public void setSourceFolder(final String sourceFolder) {
if (sourceFolder == null) {
LOGGER.warn("No sourceFolder specified, using default");
this.sourceFolder = "src" + File.separator + this.packageName;
} else if (!sourceFolder.equals("src") && !sourceFolder.startsWith("src")) {
LOGGER.warn("ASP.NET Core requires source code exists under src. Adjusting.");
this.sourceFolder = "src" + File.separator + sourceFolder;
} else {
this.sourceFolder = sourceFolder;
}
}

public void setPackageGuid(String packageGuid) {
this.packageGuid = packageGuid;
}
Expand All @@ -176,14 +178,12 @@ public String modelFileFolder() {
return outputFolder + File.separator + sourceFolder + File.separator + packageName + File.separator + "Models";
}


@Override
public Map<String, Object> postProcessSupportingFileData(Map<String, Object> objs) {
generateJSONSpecFile(objs);
return super.postProcessSupportingFileData(objs);
}


@Override
protected void processOperation(CodegenOperation operation) {
super.processOperation(operation);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -32,15 +32,15 @@ namespace {{packageName}}.Filters
/// <param name="context">FilterContext</param>
public void Apply(SwaggerDocument swaggerDoc, DocumentFilterContext context)
{
swaggerDoc.BasePath = this.BasePath;
swaggerDoc.BasePath = BasePath;

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

foreach (var path in pathsToModify)
{
if (path.Key.StartsWith(this.BasePath))
if (path.Key.StartsWith(BasePath))
{
string newKey = Regex.Replace(path.Key, $"^{this.BasePath}", string.Empty);
string newKey = Regex.Replace(path.Key, $"^{BasePath}", string.Empty);
swaggerDoc.Paths.Remove(path.Key);
swaggerDoc.Paths.Add(newKey, path.Value);
}
Expand Down
Original file line number Diff line number Diff line change
@@ -1,10 +1,4 @@
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore;

namespace {{packageName}}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -9,8 +9,8 @@
<PackageId>{{packageName}}</PackageId>
</PropertyGroup>
<ItemGroup>
<PackageReference Include="Microsoft.AspNetCore.All" Version="2.0.7" />
<PackageReference Include="Swashbuckle.AspNetCore" Version="2.4.0" />
<PackageReference Include="Microsoft.AspNetCore.All" Version="2.0.7" />{{#useSwashbuckle}}
<PackageReference Include="Swashbuckle.AspNetCore" Version="2.4.0" />{{/useSwashbuckle}}
<PackageReference Include="Newtonsoft.Json" Version="11.0.2" />
<PackageReference Include="Microsoft.EntityFrameworkCore" Version="2.0.2" />
</ItemGroup>
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -21,7 +21,7 @@ build.bat
## Run in Docker

```
cd src/{{packageName}}
cd {{sourceFolder}}/{{packageName}}
docker build -t {{dockerTag}} .
docker run -p 5000:5000 {{dockerTag}}
```
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@ 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}") = "{{packageName}}", "src\{{packageName}}\{{packageName}}.csproj", "{{packageGuid}}"
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "{{packageName}}", "{{sourceFolder}}\{{packageName}}\{{packageName}}.csproj", "{{packageGuid}}"
EndProject
Global
GlobalSection(SolutionConfigurationPlatforms) = preSolution
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -5,12 +5,11 @@ using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging;
using Newtonsoft.Json.Converters;
using Newtonsoft.Json.Serialization;
using Newtonsoft.Json.Serialization;{{#useSwashbuckle}}
using Swashbuckle.AspNetCore.Swagger;
using Swashbuckle.AspNetCore.SwaggerGen;
using {{packageName}}.Filters;
using {{packageName}}.Filters;{{/useSwashbuckle}}

namespace {{packageName}}
{
Expand All @@ -20,8 +19,7 @@ namespace {{packageName}}
public class Startup
{
private readonly IHostingEnvironment _hostingEnv;

private IConfiguration Configuration { get; }
private readonly IConfiguration _configuration;

/// <summary>
/// Constructor
Expand All @@ -31,7 +29,7 @@ namespace {{packageName}}
public Startup(IHostingEnvironment env, IConfiguration configuration)
{
_hostingEnv = env;
Configuration = configuration;
_configuration = configuration;
}

/// <summary>
Expand All @@ -46,10 +44,11 @@ namespace {{packageName}}
.AddJsonOptions(opts =>
{
opts.SerializerSettings.ContractResolver = new CamelCasePropertyNamesContractResolver();
opts.SerializerSettings.Converters.Add(new StringEnumConverter {
opts.SerializerSettings.Converters.Add(new StringEnumConverter
{
CamelCaseText = true
});
});
});{{#useSwashbuckle}}

services
.AddSwaggerGen(c =>
Expand Down Expand Up @@ -78,21 +77,19 @@ namespace {{packageName}}
// Include DataAnnotation attributes on Controller Action parameters as Swagger validation rules (e.g required, pattern, ..)
// Use [ValidateModelState] on Actions to actually validate it in C# as well!
c.OperationFilter<GeneratePathParamsValidationFilter>();
});
});{{/useSwashbuckle}}
}

/// <summary>
/// This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
/// </summary>
/// <param name="app"></param>
/// <param name="env"></param>
/// <param name="loggerFactory"></param>
public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory)
public void Configure(IApplicationBuilder app)
{
app
.UseMvc()
.UseDefaultFiles()
.UseStaticFiles()
.UseStaticFiles(){{#useSwashbuckle}}
.UseSwagger(c =>
{
c.RouteTemplate = "swagger/{documentName}/openapi.json";
Expand All @@ -104,9 +101,9 @@ namespace {{packageName}}

//TODO: Or alternatively use the original Swagger contract that's included in the static files
// c.SwaggerEndpoint("/openapi-original.json", "{{#appName}}{{{appName}}}{{/appName}}{{^appName}}{{packageName}}{{/appName}} Original");
});
}){{/useSwashbuckle}};

if (env.IsDevelopment())
if (_hostingEnv.IsDevelopment())
{
app.UseDeveloperExceptionPage();
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@

@echo off

dotnet restore src\{{packageName}}
dotnet build src\{{packageName}}
echo Now, run the following to start the project: dotnet run -p src\{{packageName}}\{{packageName}}.csproj --launch-profile web.
dotnet restore {{sourceFolder}}\{{packageName}}
dotnet build {{sourceFolder}}\{{packageName}}
echo Now, run the following to start the project: dotnet run -p {{sourceFolder}}\{{packageName}}\{{packageName}}.csproj --launch-profile web.
echo.
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,6 @@
# Generated by: https://openapi-generator.tech
#

dotnet restore src/{{packageName}}/ && \
dotnet build src/{{packageName}}/ && \
echo "Now, run the following to start the project: dotnet run -p src/{{packageName}}/{{packageName}}.csproj --launch-profile web"
dotnet restore {{sourceFolder}}/{{packageName}}/ && \
dotnet build {{sourceFolder}}/{{packageName}}/ && \
echo "Now, run the following to start the project: dotnet run -p {{sourceFolder}}/{{packageName}}/{{packageName}}.csproj --launch-profile web"
Original file line number Diff line number Diff line change
@@ -1,15 +1,8 @@
{{>partial_header}}
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.WebUtilities;
using Microsoft.Extensions.Logging;
using Microsoft.Extensions.Primitives;
using Swashbuckle.AspNetCore.SwaggerGen;
using Microsoft.AspNetCore.Mvc;{{#useSwashbuckle}}
using Swashbuckle.AspNetCore.SwaggerGen;{{/useSwashbuckle}}
using Newtonsoft.Json;
using System.ComponentModel.DataAnnotations;
using {{packageName}}.Attributes;
Expand All @@ -25,15 +18,15 @@ namespace {{packageName}}.Controllers
{ {{#operation}}
/// <summary>
/// {{#summary}}{{summary}}{{/summary}}
/// </summary>
{{#notes}}/// <remarks>{{notes}}</remarks>{{/notes}}{{#allParams}}
/// </summary>{{#notes}}
/// <remarks>{{notes}}</remarks>{{/notes}}{{#allParams}}
/// <param name="{{paramName}}">{{description}}</param>{{/allParams}}{{#responses}}
/// <response code="{{code}}">{{message}}</response>{{/responses}}
[{{httpMethod}}]
[Route("{{{basePathWithoutHost}}}{{{path}}}")]
[ValidateModelState]
[ValidateModelState]{{#useSwashbuckle}}
[SwaggerOperation("{{operationId}}")]{{#responses}}{{#dataType}}
[SwaggerResponse(statusCode: {{code}}, type: typeof({{&dataType}}), description: "{{message}}")]{{/dataType}}{{^dataType}}{{/dataType}}{{/responses}}
[SwaggerResponse(statusCode: {{code}}, type: typeof({{&dataType}}), description: "{{message}}")]{{/dataType}}{{^dataType}}{{/dataType}}{{/responses}}{{/useSwashbuckle}}
public virtual IActionResult {{operationId}}({{#allParams}}{{>pathParam}}{{>queryParam}}{{>bodyParam}}{{>formParam}}{{>headerParam}}{{#hasMore}}, {{/hasMore}}{{/allParams}})
{ {{#responses}}
{{#dataType}}
Expand Down
Original file line number Diff line number Diff line change
@@ -1,11 +1,8 @@
{{>partial_header}}
using System;
using System.Linq;
using System.IO;
using System.Text;
using System.Collections;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.ComponentModel.DataAnnotations;
using System.Runtime.Serialization;
using Newtonsoft.Json;
Expand Down
Loading