Update SQL Server spec and add Steeltoe 3.0 tests

This commit is contained in:
Chris Cheetham 2020-08-17 12:09:30 -04:00
Родитель 049260c218
Коммит 4d1c5f8af1
27 изменённых файлов: 1391 добавлений и 96 удалений

Просмотреть файл

@ -28,6 +28,6 @@ namespace Steeltoe.Initializr.TemplateEngine.Models
public string Tags { get; set; }
public DotnetFramework DotnetFramework { get; set; }
public string DotnetFramework { get; set; }
}
}

Просмотреть файл

@ -1,33 +0,0 @@
// Copyright 2020 the original author or authors.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// https://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
using System;
namespace Steeltoe.Initializr.TemplateEngine.Services
{
public enum DotnetFramework
{
NetCoreApp21,
NetCoreApp31,
}
public static class DotNetFrameworkParser
{
public static DotnetFramework Parse(string s)
{
return Enum.Parse<DotnetFramework>(s.Replace(".", string.Empty), true);
}
}
}

Просмотреть файл

@ -26,7 +26,7 @@ namespace Steeltoe.Initializr.TemplateEngine.Services
List<TemplateViewModel> GetAvailableTemplates();
List<ProjectDependency> GetDependencies(DotnetFramework framework, string template);
List<ProjectDependency> GetDependencies(string framework, string template);
void ClearCache();
}

Просмотреть файл

@ -174,11 +174,10 @@ namespace Steeltoe.Initializr.TemplateEngine.Services.Mustache
private void LoadConfig(string templatePath)
{
var frameworkNames = new[] {"netcoreapp2.1", "netcoreapp3.1"};
foreach (var frameworkName in frameworkNames)
var frameworks = new[] {"netcoreapp2.1", "netcoreapp3.1"};
foreach (var framework in frameworks)
{
var framework = DotNetFrameworkParser.Parse(frameworkName);
var path = Path.Join(templatePath, "2.4", frameworkName);
var path = Path.Join(templatePath, "2.4", framework);
foreach (var dir in new DirectoryInfo(path).EnumerateDirectories())
{
var template = dir.Name;

Просмотреть файл

@ -34,8 +34,8 @@ namespace Steeltoe.Initializr.TemplateEngine.Services.Mustache
/// </summary>
public class MustacheTemplateService : ITemplateService
{
private const string DefaultTemplateName = "Steeltoe-WebApi";
private const DotnetFramework DefaultVersion = DotnetFramework.NetCoreApp21;
private const string DefaultTemplate = "Steeltoe-WebApi";
private const string DefaultFramework = "netcoreapp2.1";
private Dictionary<string, string> FriendlyNames { get; set; }
@ -67,9 +67,8 @@ namespace Steeltoe.Initializr.TemplateEngine.Services.Mustache
public async Task<List<KeyValuePair<string, string>>> GenerateProjectFiles(GeneratorModel model)
{
var framework = DotNetFrameworkParser.Parse(model.TargetFramework);
var template = string.IsNullOrEmpty(model.Template) ? DefaultTemplateName : model.Template;
var templateKey = new TemplateKey(framework, template);
var template = string.IsNullOrEmpty(model.Template) ? DefaultTemplate : model.Template;
var templateKey = new TemplateKey(model.TargetFramework, template);
if (!_mustacheConfig.GetTemplateKeys().Contains(templateKey))
{
throw new InvalidDataException($"Template with Name[{template}] and Framework[{model.TargetFramework}] doesn't exist");
@ -117,9 +116,9 @@ namespace Steeltoe.Initializr.TemplateEngine.Services.Mustache
.ToList();
}
public List<ProjectDependency> GetDependencies(DotnetFramework framework, string shortName)
public List<ProjectDependency> GetDependencies(string framework, string shortName)
{
shortName = string.IsNullOrEmpty(shortName) ? DefaultTemplateName : shortName;
shortName = string.IsNullOrEmpty(shortName) ? DefaultTemplate : shortName;
var list = GetAvailableTemplates();
var selectedTemplate = list.FirstOrDefault(x => x.ShortName == shortName);

Просмотреть файл

@ -20,9 +20,9 @@ namespace Steeltoe.Initializr.TemplateEngine.Services.Mustache
{
public string Template { get; }
public DotnetFramework Framework { get; }
public string Framework { get; }
public TemplateKey(DotnetFramework framework, string template)
public TemplateKey(string framework, string template)
{
Framework = framework;
Template = template;

Просмотреть файл

@ -74,7 +74,7 @@ Get project:
private string GetDependencies()
{
var result = new StringBuilder();
var dependencies = _templateService.GetDependencies(DotnetFramework.NetCoreApp31, string.Empty);
var dependencies = _templateService.GetDependencies("netcoreapp3.1", string.Empty);
var fieldWidths = new int[] { 40, 100 };
result.Append("\nDependencies: \n");

Просмотреть файл

@ -57,7 +57,7 @@ namespace Steeltoe.Initializr.WebApp.Controllers
[FromQuery(Name = "dotNetTemplate")] string template,
[FromQuery(Name = "dotNetFramework")] string framework = "netcoreapp3.1")
{
return Ok(_sttemplateService.GetDependencies(DotNetFrameworkParser.Parse(framework), template));
return Ok(_sttemplateService.GetDependencies(framework, template));
}
[Route("templates")]

Просмотреть файл

@ -35,48 +35,50 @@
{
"Name": "MongoDB",
"DefaultValue": false,
"Description": "Steeltoe: Add MongoDB connnectors"
"Description": "Steeltoe: Add MongoDB connectors"
},
{
"Name": "MySql",
"DefaultValue": "false",
"Description": "Steeltoe: Add MySql connnectors"
"Description": "Steeltoe: Add MySql connectors"
},
{
"Name": "MySqlEFCore",
"DefaultValue": false,
"Description": "Steeltoe: Add MySQL EFCore connnectors"
"Description": "Steeltoe: Add MySQL EFCore connectors",
"friendlyName": "MySql EFCore"
},
{
"Name": "OAuthConnector",
"DefaultValue": false,
"Description": "Steeltoe: Add OAuth connnectors"
"Description": "Steeltoe: Add OAuth connectors"
},
{
"Name": "Postgres",
"DefaultValue": false,
"Description": "Steeltoe: Add Postgres connnectors"
"Description": "Steeltoe: Add Postgres connectors"
},
{
"Name": "PostgresEFCore",
"DefaultValue": false,
"Description": "Steeltoe: Add PostgresEFCore connnectors"
"Description": "Steeltoe: Add Postgres EFCore connectors",
"friendlyName": "Postgres EFCore"
},
{
"Name": "RabbitMQ",
"DefaultValue": false,
"Description": "Steeltoe: Add RabbitMQ connnectors"
"Description": "Steeltoe: Add RabbitMQ connectors"
},
{
"Name": "Redis",
"DefaultValue": false,
"Description": "Steeltoe: Add Redis connnectors"
"Description": "Steeltoe: Add Redis connectors"
},
{
"Name": "SQLServer",
"Name": "SQLServerEFCore",
"DefaultValue": false,
"Description": "Steeltoe: Add Microsoft SQL Server connnectors",
"friendlyName": "SQL Server"
"Description": "Steeltoe: Add Microsoft SQL Server connectors",
"friendlyName": "SQL Server EFCore"
},
{
"Name": "ConfigServer",

Просмотреть файл

@ -35,48 +35,50 @@
{
"Name": "MongoDB",
"DefaultValue": false,
"Description": "Steeltoe: Add MongoDB connnectors"
"Description": "Steeltoe: Add MongoDB connectors"
},
{
"Name": "MySql",
"DefaultValue": "false",
"Description": "Steeltoe: Add MySql connnectors"
"Description": "Steeltoe: Add MySql connectors"
},
{
"Name": "MySqlEFCore",
"DefaultValue": false,
"Description": "Steeltoe: Add MySQL EFCore connnectors"
"Description": "Steeltoe: Add MySQL EFCore connectors",
"friendlyName": "MySql EFCore"
},
{
"Name": "OAuthConnector",
"DefaultValue": false,
"Description": "Steeltoe: Add OAuth connnectors"
"Description": "Steeltoe: Add OAuth connectors"
},
{
"Name": "Postgres",
"DefaultValue": false,
"Description": "Steeltoe: Add Postgres connnectors"
"Description": "Steeltoe: Add Postgres connectors"
},
{
"Name": "PostgresEFCore",
"DefaultValue": false,
"Description": "Steeltoe: Add PostgresEFCore connnectors"
"Description": "Steeltoe: Add Postgres EFCore connectors",
"friendlyName": "Postgres EFCore"
},
{
"Name": "RabbitMQ",
"DefaultValue": false,
"Description": "Steeltoe: Add RabbitMQ connnectors"
"Description": "Steeltoe: Add RabbitMQ connectors"
},
{
"Name": "Redis",
"DefaultValue": false,
"Description": "Steeltoe: Add Redis connnectors"
"Description": "Steeltoe: Add Redis connectors"
},
{
"Name": "SQLServer",
"Name": "SQLServerEFCore",
"DefaultValue": false,
"Description": "Steeltoe: Add Microsoft SQL Server connnectors",
"friendlyName": "SQL Server"
"Description": "Steeltoe: Add Microsoft SQL Server connectors",
"friendlyName": "SQL Server EFCore"
},
{
"Name": "ProjectNameSpace",

Просмотреть файл

@ -0,0 +1,232 @@
## Ignore Visual Studio temporary files, build results, and
## files generated by popular Visual Studio add-ons.
# User-specific files
*.suo
*.user
*.userosscache
*.sln.docstates
# User-specific files (MonoDevelop/Xamarin Studio)
*.userprefs
# Build results
[Dd]ebug/
[Dd]ebugPublic/
[Rr]elease/
[Rr]eleases/
x64/
x86/
build/
bld/
bin/
Bin/
obj/
Obj/
# Visual Studio 2015 cache/options directory
.vs/
/wwwroot/dist/
# MSTest test Results
[Tt]est[Rr]esult*/
[Bb]uild[Ll]og.*
# NUNIT
*.VisualState.xml
TestResult.xml
# Build Results of an ATL Project
[Dd]ebugPS/
[Rr]eleasePS/
dlldata.c
*_i.c
*_p.c
*_i.h
*.ilk
*.meta
*.obj
*.pch
*.pdb
*.pgc
*.pgd
*.rsp
*.sbr
*.tlb
*.tli
*.tlh
*.tmp
*.tmp_proj
*.log
*.vspscc
*.vssscc
.builds
*.pidb
*.svclog
*.scc
# Chutzpah Test files
_Chutzpah*
# Visual C++ cache files
ipch/
*.aps
*.ncb
*.opendb
*.opensdf
*.sdf
*.cachefile
# Visual Studio profiler
*.psess
*.vsp
*.vspx
*.sap
# TFS 2012 Local Workspace
$tf/
# Guidance Automation Toolkit
*.gpState
# ReSharper is a .NET coding add-in
_ReSharper*/
*.[Rr]e[Ss]harper
*.DotSettings.user
# JustCode is a .NET coding add-in
.JustCode
# TeamCity is a build add-in
_TeamCity*
# DotCover is a Code Coverage Tool
*.dotCover
# NCrunch
_NCrunch_*
.*crunch*.local.xml
nCrunchTemp_*
# MightyMoose
*.mm.*
AutoTest.Net/
# Web workbench (sass)
.sass-cache/
# Installshield output folder
[Ee]xpress/
# DocProject is a documentation generator add-in
DocProject/buildhelp/
DocProject/Help/*.HxT
DocProject/Help/*.HxC
DocProject/Help/*.hhc
DocProject/Help/*.hhk
DocProject/Help/*.hhp
DocProject/Help/Html2
DocProject/Help/html
# Click-Once directory
publish/
# Publish Web Output
*.[Pp]ublish.xml
*.azurePubxml
# TODO: Comment the next line if you want to checkin your web deploy settings
# but database connection strings (with potential passwords) will be unencrypted
*.pubxml
*.publishproj
# NuGet Packages
*.nupkg
# The packages folder can be ignored because of Package Restore
**/packages/*
# except build/, which is used as an MSBuild target.
!**/packages/build/
# Uncomment if necessary however generally it will be regenerated when needed
#!**/packages/repositories.config
# Microsoft Azure Build Output
csx/
*.build.csdef
# Microsoft Azure Emulator
ecf/
rcf/
# Microsoft Azure ApplicationInsights config file
ApplicationInsights.config
# Windows Store app package directory
AppPackages/
BundleArtifacts/
# Visual Studio cache files
# files ending in .cache can be ignored
*.[Cc]ache
# but keep track of directories ending in .cache
!*.[Cc]ache/
# Others
ClientBin/
~$*
*~
*.dbmdl
*.dbproj.schemaview
*.pfx
*.publishsettings
orleans.codegen.cs
/node_modules
# RIA/Silverlight projects
Generated_Code/
# Backup & report files from converting an old project file
# to a newer Visual Studio version. Backup files are not needed,
# because we have git ;-)
_UpgradeReport_Files/
Backup*/
UpgradeLog*.XML
UpgradeLog*.htm
# SQL Server files
*.mdf
*.ldf
# Business Intelligence projects
*.rdl.data
*.bim.layout
*.bim_*.settings
# Microsoft Fakes
FakesAssemblies/
# GhostDoc plugin setting file
*.GhostDoc.xml
# Node.js Tools for Visual Studio
.ntvs_analysis.dat
# Visual Studio 6 build log
*.plg
# Visual Studio 6 workspace options file
*.opt
# Visual Studio LightSwitch build output
**/*.HTMLClient/GeneratedArtifacts
**/*.DesktopClient/GeneratedArtifacts
**/*.DesktopClient/ModelManifest.xml
**/*.Server/GeneratedArtifacts
**/*.Server/ModelManifest.xml
_Pvt_Extensions
# Paket dependency manager
.paket/paket.exe
# FAKE - F# Make
.fake/

Просмотреть файл

@ -0,0 +1,331 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.Extensions.Logging;
{{#Auth}}
using Microsoft.AspNetCore.Authorization;
{{/Auth}}
using Microsoft.AspNetCore.Mvc;
{{#SQLServer}}
using System.Data.SqlClient;
using System.Data;
{{/SQLServer}}
{{#MySql}}
using MySql.Data.MySqlClient;
using System.Data;
{{/MySql}}
{{#Postgres}}
using Npgsql;
using System.Data;
{{/Postgres}}
{{#MongoDB}}
using MongoDB.Driver;
using System.Data;
{{/MongoDB}}
{{#Redis}}
using Microsoft.Extensions.Caching.Distributed;
{{/Redis}}
{{#RabbitMQ}}
using RabbitMQ.Client;
using RabbitMQ.Client.Events;
using System.Text;
using System.Threading;
{{/RabbitMQ}}
{{#AnyConfigSource}}
using Microsoft.Extensions.Configuration;
{{/AnyConfigSource}}
{{#CloudFoundry}}
using Steeltoe.Extensions.Configuration.CloudFoundry;
using Microsoft.Extensions.Options;
{{/CloudFoundry}}
namespace {{ProjectNameSpace}}.Controllers
{
{{#Auth}}
[Authorize]
{{/Auth}}
[Route("api/[controller]")]
[ApiController]
public class ValuesController : ControllerBase
{
{{^MoreThanOneValuesControllerWithArgs }}
{{#SQLServer}}
private readonly SqlConnection _dbConnection;
public ValuesController([FromServices] SqlConnection dbConnection)
{
_dbConnection = dbConnection;
}
// GET api/values
[HttpGet]
public ActionResult<IEnumerable<string>> Get()
{
List<string> tables = new List<string>();
_dbConnection.Open();
DataTable dt = _dbConnection.GetSchema("Tables");
_dbConnection.Close();
foreach (DataRow row in dt.Rows)
{
string tablename = (string)row[2];
tables.Add(tablename);
}
return tables;
}
{{/SQLServer}}
{{#MySql}}
private readonly MySqlConnection _dbConnection;
public ValuesController([FromServices] MySqlConnection dbConnection)
{
_dbConnection = dbConnection;
}
// GET api/values
[HttpGet]
public ActionResult<IEnumerable<string>> Get()
{
List<string> tables = new List<string>();
_dbConnection.Open();
DataTable dt = _dbConnection.GetSchema("Tables");
_dbConnection.Close();
foreach (DataRow row in dt.Rows)
{
string tablename = (string)row[2];
tables.Add(tablename);
}
return tables;
}
{{/MySql}}
{{#Postgres}}
private readonly NpgsqlConnection _dbConnection;
public ValuesController([FromServices] NpgsqlConnection dbConnection)
{
_dbConnection = dbConnection;
}
// GET api/values
[HttpGet]
public ActionResult<IEnumerable<string>> Get()
{
List<string> tables = new List<string>();
_dbConnection.Open();
DataTable dt = _dbConnection.GetSchema("Databases");
_dbConnection.Close();
foreach (DataRow row in dt.Rows)
{
string tablename = (string)row[2];
tables.Add(tablename);
}
return tables;
}
{{/Postgres}}
{{#MongoDB}}
private readonly IMongoClient _mongoClient;
private readonly MongoUrl _mongoUrl;
public ValuesController(IMongoClient mongoClient, MongoUrl mongoUrl)
{
_mongoClient = mongoClient;
_mongoUrl = mongoUrl;
}
// GET api/values
[HttpGet]
public ActionResult<IEnumerable<string>> Get()
{
return _mongoClient.ListDatabaseNames().ToList();
}
{{/MongoDB}}
{{#Redis}}
private readonly IDistributedCache _cache;
public ValuesController(IDistributedCache cache)
{
_cache = cache;
}
// GET api/values
[HttpGet]
public async Task<IEnumerable<string>> Get()
{
await _cache.SetStringAsync("MyValue1", "123");
await _cache.SetStringAsync("MyValue2", "456");
string myval1 = await _cache.GetStringAsync("MyValue1");
string myval2 = await _cache.GetStringAsync("MyValue2");
return new string[]{ myval1, myval2};
}
{{/Redis}}
{{#RabbitMQ}}
private readonly ILogger _logger;
private readonly ConnectionFactory _factory;
private const string queueName = "my-queue";
public ValuesController(ILogger<ValuesController> logger, [FromServices] ConnectionFactory factory)
{
_logger = logger;
_factory = factory;
}
// GET api/values
[HttpGet]
public ActionResult<string> Get()
{
using (var connection = _factory.CreateConnection())
using (var channel = connection.CreateModel())
{
//the queue
channel.QueueDeclare(queue: queueName,
durable: false,
exclusive: false,
autoDelete: false,
arguments: null);
// consumer
var consumer = new EventingBasicConsumer(channel);
consumer.Received += (model, ea) =>
{
string msg = Encoding.UTF8.GetString(ea.Body);
_logger.LogInformation("Received message: " + msg);
};
channel.BasicConsume(queue: queueName,
autoAck: true,
consumer: consumer);
// publisher
int i = 0;
while (i<5) { //write a message every second, for 5 seconds
var body = Encoding.UTF8.GetBytes($"Message {++i}");
channel.BasicPublish(exchange: "",
routingKey: queueName,
basicProperties: null,
body: body);
Thread.Sleep(1000);
}
}
return "Wrote 5 message to the info log. Have a look!";
}
{{/RabbitMQ}}
{{#ConfigServer}}
private readonly IConfiguration _config;
public ValuesController(IConfiguration config)
{
_config = config;
}
// GET api/values
[HttpGet]
public ActionResult<IEnumerable<string>> Get()
{
var val1 = _config["Value1"];
var val2 = _config["Value2"];
return new string[] { val1, val2 };
}
{{/ConfigServer}}
{{#PlaceholderConfig}}
private readonly IConfiguration _config;
public ValuesController(IConfiguration config)
{
_config = config;
}
// GET api/values
[HttpGet]
public ActionResult<IEnumerable<string>> Get()
{
var val1 = _config["ResolvedPlaceholderFromEnvVariables"];
var val2 = _config["UnresolvedPlaceholder"];
var val3 = _config["ResolvedPlaceholderFromJson"];
return new string[] { val1, val2, val3 };
}
{{/PlaceholderConfig}}
{{#RandomValueConfig}}
private readonly IConfiguration _config;
public ValuesController(IConfiguration config)
{
_config = config;
}
// GET api/values
[HttpGet]
public ActionResult<IEnumerable<string>> Get()
{
var val1 = _config["random:int"];
var val2 = _config["random:uuid"];
var val3 = _config["random:string"];
return new string[] { val1, val2, val3 };
}
{{/RandomValueConfig}}
{{#CircuitBreaker}}
// GET api/values
[HttpGet]
public async Task<IEnumerable<string>> Get()
{
MyCircuitBreakerCommand cb = new MyCircuitBreakerCommand("ThisIsMyBreaker");
cb.IsFallbackUserDefined = true;
string a = await cb.ExecuteAsync();
return new string[] { a };
}
{{/CircuitBreaker}}
{{#CloudFoundry}}
private readonly ILogger _logger;
private CloudFoundryApplicationOptions _appOptions { get; set; }
private CloudFoundryServicesOptions _serviceOptions { get; set; }
public ValuesController(ILogger<ValuesController> logger, IOptions<CloudFoundryApplicationOptions> appOptions, IOptions<CloudFoundryServicesOptions> serviceOptions)
{
_logger = logger;
_appOptions = appOptions.Value;
_serviceOptions = serviceOptions.Value;
}
// GET api/values
[HttpGet]
public ActionResult<IEnumerable<string>> Get()
{
string appName = _appOptions.ApplicationName;
string appInstance = _appOptions.ApplicationId;
/*_serviceOptions.Services["user-provided"]
.First(q => q.Name.Equals("xxxxxxx"))
.Credentials["xxxxxxx"].Value*/
return new string[] { appInstance, appName };
}
{{/CloudFoundry}}
{{/MoreThanOneValuesControllerWithArgs}}
{{#MoreThanOneValuesControllerWithArgs}}
[HttpGet]
public ActionResult<string> Get()
{
return "value";
}
{{/MoreThanOneValuesControllerWithArgs}}
{{^ValuesControllerWithArgs}}
[HttpGet]
public ActionResult<string> Get()
{
return "value";
}
{{/ValuesControllerWithArgs}}
// GET api/values/5
[HttpGet("{id}")]
public ActionResult<string> Get(int id)
{
return "value";
}
// POST api/values
[HttpPost]
public void Post([FromBody] string value)
{
}
// PUT api/values/5
[HttpPut("{id}")]
public void Put(int id, [FromBody] string value)
{
}
// DELETE api/values/5
[HttpDelete("{id}")]
public void Delete(int id)
{
}
}
}

Просмотреть файл

@ -0,0 +1,18 @@
FROM mcr.microsoft.com/dotnet/core/aspnet:3.1 AS base
WORKDIR /app
EXPOSE 80
FROM mcr.microsoft.com/dotnet/core/sdk:3.1 AS build
WORKDIR /src
COPY ["{{ProjectNameSpace}}.csproj", "."]
RUN dotnet restore "{{ProjectNameSpace}}.csproj"
COPY . .
RUN dotnet build "{{ProjectNameSpace}}.csproj" -c Release -o /app
FROM build AS publish
RUN dotnet publish "{{ProjectNameSpace}}.csproj" -c Release -o /app
FROM base AS final
WORKDIR /app
COPY --from=publish /app .
ENTRYPOINT ["dotnet", "{{ProjectNameSpace}}.dll"]

Просмотреть файл

@ -0,0 +1,11 @@
using System;
namespace {{ProjectNameSpace}}
{
public class ErrorViewModel
{
public string RequestId { get; set; }
public bool ShowRequestId => !string.IsNullOrEmpty(RequestId);
}
}

Просмотреть файл

@ -0,0 +1,31 @@
using Microsoft.AspNetCore.Hosting;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
namespace {{ProjectNameSpace}}
{
public static class InitializeContext
{
public static IWebHost InitializeDbContexts(this IWebHost host)
{
using (var scope = host.Services.CreateScope())
{
var services = scope.ServiceProvider;
try
{
SampleData.InitializeMyContexts(services);
}
catch (Exception ex)
{
var logger = services.GetRequiredService<ILogger<WebHostBuilder>>();
logger.LogError(ex, "An error occurred seeding the DB.");
}
}
return host;
}
}
}

Просмотреть файл

@ -0,0 +1,45 @@
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.DependencyInjection;
using System;
using System.Linq;
namespace {{ProjectNameSpace}}
{
public class SampleData
{
internal static void InitializeMyContexts(IServiceProvider serviceProvider)
{
if (serviceProvider == null)
{
throw new ArgumentNullException("serviceProvider");
}
using (var serviceScope = serviceProvider.GetRequiredService<IServiceScopeFactory>().CreateScope())
{
var db = serviceScope.ServiceProvider.GetService<TestContext>();
db.Database.EnsureCreated();
}
InitializeContext(serviceProvider);
}
private static void InitializeContext(IServiceProvider serviceProvider)
{
using (var serviceScope = serviceProvider.GetRequiredService<IServiceScopeFactory>().CreateScope())
{
var db = serviceScope.ServiceProvider.GetService<TestContext>();
if (db.TestData.Any())
{
return;
}
AddData<TestData>(db, new TestData() { Id = 1, Data = "Test Data 1 - TestContext " });
AddData<TestData>(db, new TestData() { Id = 2, Data = "Test Data 2 - TestContext " });
db.SaveChanges();
}
}
private static void AddData<TData>(DbContext db, object item) where TData: class
{
db.Entry(item).State = EntityState.Added;
}
}
}

Просмотреть файл

@ -0,0 +1,25 @@
using Microsoft.EntityFrameworkCore;
using System.ComponentModel.DataAnnotations;
using System.ComponentModel.DataAnnotations.Schema;
namespace {{ProjectNameSpace}}
{
public class TestContext : DbContext
{
public TestContext(DbContextOptions options) : base(options)
{
}
public DbSet<TestData> TestData { get; set; }
}
public class TestData
{
[Key]
[DatabaseGenerated(DatabaseGeneratedOption.None)]
public int Id { get; set; }
public string Data { get; set; }
}
}

Просмотреть файл

@ -0,0 +1,26 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Steeltoe.CircuitBreaker.Hystrix;
namespace {{ProjectNameSpace}}
{
public class MyCircuitBreakerCommand : HystrixCommand<string>
{
private string _name;
public MyCircuitBreakerCommand(string name): base(HystrixCommandGroupKeyDefault.AsKey("MyCircuitBreakerGroup"))
{
_name = name;
IsFallbackUserDefined = true;
}
protected override async Task<string> RunAsync()
{
return await Task.FromResult("Hello " + _name);
}
protected override async Task<string> RunFallbackAsync()
{
return await Task.FromResult("Hello " + _name + " via fallback");
}
}
}

Просмотреть файл

@ -0,0 +1,68 @@
using Microsoft.AspNetCore;
using Microsoft.AspNetCore.Hosting;
{{#AzureSpringCloud}}
using Microsoft.Azure.SpringCloud.Client;
{{/AzureSpringCloud}}
{{#ActuatorsOrDynamicLogger}}
using Steeltoe.Extensions.Logging.DynamicSerilog;
{{/ActuatorsOrDynamicLogger}}
{{#CloudFoundry}}
{{^ConfigServer}}
using Steeltoe.Common.Hosting;
using Steeltoe.Extensions.Configuration.CloudFoundry;
{{/ConfigServer}}
{{/CloudFoundry}}
{{#ConfigServer}}
using Steeltoe.Extensions.Configuration.ConfigServer;
{{/ConfigServer}}
{{#PlaceholderConfig}}
using Steeltoe.Extensions.Configuration.Placeholder;
{{/PlaceholderConfig}}
{{#RandomValueConfig}}
using Steeltoe.Extensions.Configuration.RandomValue;
{{/ RandomValueConfig}}
namespace {{ProjectNameSpace}}
{
public class Program
{
public static void Main(string[] args)
{
CreateWebHostBuilder(args)
.Build()
{{#AnyEFCore}}
.InitializeDbContexts()
{{/AnyEFCore}}
.Run();
}
public static IWebHostBuilder CreateWebHostBuilder(string[] args)
{
var builder = WebHost.CreateDefaultBuilder(args)
.UseDefaultServiceProvider(configure => configure.ValidateScopes = false)
{{#CloudFoundry}}
.UseCloudHosting() //Enable listening on a Env provided port
{{^ConfigServer}}
.AddCloudFoundryConfiguration() //Add cloudfoundry environment variables as a configuration source
{{/ConfigServer}}
{{/CloudFoundry}}
{{#ConfigServer}}
.AddConfigServer()
{{/ConfigServer}}
{{#PlaceholderConfig}}
.AddPlaceholderResolver()
{{/PlaceholderConfig}}
{{#RandomValueConfig}}
.ConfigureAppConfiguration((b) => b.AddRandomValueSource())
{{/RandomValueConfig}}
{{#AzureSpringCloud}}
.UseAzureSpringCloudService()
{{/AzureSpringCloud}}
{{#ActuatorsOrDynamicLogger}}
.ConfigureLogging((context, builder) => builder.AddSerilogDynamicConsole())
{{/ActuatorsOrDynamicLogger}}
.UseStartup<Startup>();
return builder;
}
}
}

Просмотреть файл

@ -0,0 +1,46 @@
{
"$schema": "http://json.schemastore.org/launchsettings.json",
"iisSettings": {
{{#WindowsAuth}}
"windowsAuthentication": true,
"anonymousAuthentication": false,
{{/WindowsAuth}}
{{^WindowsAuth}}
"windowsAuthentication": false,
"anonymousAuthentication": true,
{{/WindowsAuth}}
"iisExpress": {
"applicationUrl": "http://localhost:8080",
{{#RequiresHttps}}
"sslPort": 44300
{{/RequiresHttps}}
{{^RequiresHttps}}
"sslPort": 0
{{/RequiresHttps}}
}
},
"profiles": {
"IIS Express": {
"commandName": "IISExpress",
"launchBrowser": true,
"launchUrl": "api/values",
"environmentVariables": {
"ASPNETCORE_ENVIRONMENT": "Development"
}
},
"{{ProjectNameSpace}}": {
"commandName": "Project",
"launchBrowser": true,
"launchUrl": "api/values",
{{#RequiresHttps}}
"applicationUrl": "https://localhost:5001;http://localhost:5000",
{{/RequiresHttps}}
{{^RequiresHttps}}
"applicationUrl": "http://localhost:5000",
{{/RequiresHttps}}
"environmentVariables": {
"ASPNETCORE_ENVIRONMENT": "Development"
}
}
}
}

Просмотреть файл

@ -0,0 +1,100 @@
<Project Sdk="Microsoft.NET.Sdk.Web">
<PropertyGroup>
<TargetFramework>{{TargetFrameworkVersion}}</TargetFramework>
{{#Auth}}
<UserSecretsId >{{UserSecretsId}}</UserSecretsId>
{{/Auth}}
{{#ExcludeLaunchSettings}}
<NoDefaultLaunchSettingsFile>True</NoDefaultLaunchSettingsFile>
{{/ExcludeLaunchSettings}}
<AspNetCoreHostingModel>InProcess</AspNetCoreHostingModel>
</PropertyGroup>
<ItemGroup >
{{#OrganizationalAuth}}
<PackageReference Include="Microsoft.AspNetCore.Authentication.AzureAD.UI" Version="{{AspNetCoreVersion}}" />
{{/OrganizationalAuth}}
{{#IndividualB2CAuth}}
<PackageReference Include="Microsoft.AspNetCore.Authentication.AzureADB2C.UI" Version="{{AspNetCoreVersion}}}" />
{{/IndividualB2CAuth}}
{{#RequiresHttps}}
<PackageReference Include="Microsoft.AspNetCore.HttpsPolicy" Version="{{AspNetCoreVersion}}" />
{{/RequiresHttps}}
{{#AnyEFCore}}
<PackageReference Include="Microsoft.EntityFrameworkCore" Version="{{AspNetCoreVersion}}" />
{{/AnyEFCore}}
{{#MongoDB}}
<PackageReference Include="MongoDB.Driver" Version="{{MongoDBVersion}}" />
{{/MongoDB}}
{{#MySql}}
<PackageReference Include="MySql.Data" Version="{{MySqlVersion}}" />
{{/MySql}}
{{#Postgres}}
<PackageReference Include="Npgsql" Version="{{NpgSqlVersion}}" />
{{/Postgres}}
{{#CircuitBreaker}}
<PackageReference Include="Steeltoe.CircuitBreaker.HystrixCore" Version="{{SteeltoeVersion}}" />
{{/CircuitBreaker}}
{{#CloudFoundry}}
<PackageReference Include="Steeltoe.Common.Hosting" Version="{{SteeltoeVersion}}" />
{{/CloudFoundry}}
{{#AnyConnector}}
<PackageReference Include="Steeltoe.Connector.ConnectorCore" Version="{{SteeltoeVersion}}"/>
<PackageReference Include="Steeltoe.Connector.CloudFoundry" Version="{{SteeltoeVersion}}"/>
{{/AnyConnector}}
{{#AnyEFCore}}
<PackageReference Include="Steeltoe.Connector.EFCore" Version="{{SteeltoeVersion}}" />
{{/AnyEFCore}}
{{#SQLServer}}
<PackageReference Include="Steeltoe.Connector.EFCore" Version="{{SteeltoeVersion}}" />
{{/SQLServer}}
{{#Discovery}}
<PackageReference Include="Steeltoe.Discovery.ClientCore" Version="{{SteeltoeVersion}}"/>
{{/Discovery}}
{{#CloudFoundry}}
<PackageReference Include="Steeltoe.Extensions.Configuration.CloudFoundryCore" Version="{{SteeltoeVersion}}" />
{{/CloudFoundry}}
{{#PlaceholderConfig}}
<PackageReference Include="Steeltoe.Extensions.Configuration.PlaceholderCore" Version="{{SteeltoeVersion}}" />
{{/PlaceholderConfig}}
{{#ActuatorsOrCloudFoundry}}
<PackageReference Include="Steeltoe.Extensions.Logging.DynamicSerilogCore" Version="{{SteeltoeVersion}}" />
{{/ActuatorsOrCloudFoundry}}
{{#DynamicLogger}}
<PackageReference Include="Steeltoe.Extensions.Logging.DynamicSerilogCore" Version="{{SteeltoeVersion}}" />
{{/DynamicLogger}}
{{#ActuatorsOrCloudFoundry}}
<PackageReference Include="Steeltoe.Management.CloudFoundryCore" Version="{{SteeltoeVersion}}" />
{{/ActuatorsOrCloudFoundry}}
{{#ConfigServer}}
<PackageReference Include="Steeltoe.Extensions.Configuration.ConfigServerCore" Version="{{SteeltoeVersion}}" />
{{/ConfigServer}}
{{#RandomValueConfig}}
<PackageReference Include="Steeltoe.Extensions.Configuration.RandomValueBase" Version="{{SteeltoeVersion}}" />
{{/RandomValueConfig}}
{{#AzureSpringCloud}}
<PackageReference Include="Microsoft.Azure.SpringCloud.Client" Version="1.0.0-alpha.1" />
{{/AzureSpringCloud}}
<PackageReference Include="Newtonsoft.Json" Version="12.0.2" />
{{#Redis}}
<PackageReference Include="Microsoft.Extensions.Caching.StackExchangeRedis" Version="3.1.0" />
{{/Redis}}
{{#PostgresEFCore}}
<PackageReference Include="Npgsql.EntityFrameworkCore.PostgreSQL" Version="3.1.0" />
{{/PostgresEFCore}}
{{#RabbitMQ}}
<PackageReference Include="RabbitMQ.Client" Version="{{RabbitMQVersion}}" />
{{/RabbitMQ}}
</ItemGroup>
{{#CircuitBreaker}}
<ItemGroup Condition="'$(BUILD)' == ''">
<PackageReference Include="Steeltoe.CircuitBreaker.Hystrix.MetricsStreamCore" Version="{{SteeltoeVersion}}" />
<PackageReference Include="RabbitMQ.Client" Version="{{RabbitMQVersion}}" />
</ItemGroup>
<ItemGroup Condition="'$(BUILD)' == 'LOCAL'">
<PackageReference Include="Steeltoe.CircuitBreaker.Hystrix.MetricsEventsCore" Version="{{SteeltoeVersion}}" />
<PackageReference Include="System.Threading.ThreadPool" Version="4.3.0" />
</ItemGroup>
{{/CircuitBreaker}}
</Project>

Просмотреть файл

@ -0,0 +1,149 @@
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
{{#MongoDB}}
using Steeltoe.Connector.MongoDb;
{{/MongoDB}}
{{#MySqlOrMySqlEFCore}}
using Steeltoe.Connector.MySql;
{{/MySqlOrMySqlEFCore}}
{{#MySqlEFCore}}
using Steeltoe.Connector.MySql.EFCore;
{{/MySqlEFCore}}
{{#OAuthConnector}}
using Steeltoe.Connector.OAuth;
{{/OAuthConnector}}
{{#Postgres}}
using Steeltoe.Connector.PostgreSql;
{{/Postgres}}
{{#PostgresEFCore}}
using Steeltoe.Connector.PostgreSql.EFCore;
{{/PostgresEFCore}}
{{#RabbitMQ}}
using Steeltoe.Connector.RabbitMQ;
{{/RabbitMQ}}
{{#Redis}}
using Steeltoe.Connector.Redis;
{{/Redis}}
{{#SQLServer}}
using Steeltoe.Connector.SqlServer.EFCore;
{{/SQLServer}}
{{#Discovery}}
using Steeltoe.Discovery.Client;
{{/Discovery}}
{{#Actuators}}
using Steeltoe.Management.CloudFoundry;
{{/Actuators}}
{{#RequiresHttps}}
using Microsoft.AspNetCore.HttpsPolicy;
{{/RequiresHttps}}
{{#Auth}}
using Microsoft.AspNetCore.Authentication;
{{/Auth}}
{{#OrganizationalAuth}}
using Microsoft.AspNetCore.Authentication.AzureAD.UI;
{{/OrganizationalAuth}}
{{#IndividualB2CAuth}}
using Microsoft.AspNetCore.Authentication.AzureADB2C.UI;
{{/IndividualB2CAuth}}
{{#CircuitBreaker}}
using Steeltoe.CircuitBreaker.Hystrix;
{{/CircuitBreaker}}
namespace {{ProjectNameSpace}}
{
public class Startup
{
public Startup(IConfiguration configuration)
{
Configuration = configuration;
}
public IConfiguration Configuration { get; }
// This method gets called by the runtime. Use this method to add services to the container.
public void ConfigureServices(IServiceCollection services)
{
{{#OrganizationalAuth}}
services.AddAuthentication(AzureADDefaults.BearerAuthenticationScheme)
.AddAzureADBearer(options => Configuration.Bind("AzureAd", options));
{{/OrganizationalAuth}}
{{#IndividualB2CAuth}}
services.AddAuthentication(AzureADB2CDefaults.BearerAuthenticationScheme)
.AddAzureADB2CBearer(options => Configuration.Bind("AzureAdB2C", options));
{{/IndividualB2CAuth}}
{{#MySql}}
services.AddMySqlConnection(Configuration);
{{/MySql}}
{{#Actuators}}
{{#CloudFoundry}}
services.ConfigureCloudFoundryOptions(Configuration, MediaTypeVersion.V2, ActuatorContext.ActuatorAndCloudFoundry);
{{/CloudFoundry}}
{{^CloudFoundry}}
services.AddCloudFoundryActuators(Configuration);
{{/CloudFoundry}}
{{/Actuators}}
{{#Discovery}}
services.AddDiscoveryClient(Configuration);
{{/ Discovery}}
{{#Postgres}}
services.AddPostgresConnection(Configuration);
{{/Postgres}}
{{#RabbitMQ}}
services.AddRabbitMQConnection(Configuration);
{{/RabbitMQ}}
{{#Redis}}
// Add the Redis distributed cache.
// We are using the Steeltoe Redis Connector to pickup the CloudFoundry
// Redis Service binding and use it to configure the underlying RedisCache
// This adds a IDistributedCache to the container
services.AddDistributedRedisCache(Configuration);
// This works like the above, but adds a IConnectionMultiplexer to the container
// services.AddRedisConnectionMultiplexer(Configuration);
{{/Redis}}
{{#MongoDB}}
services.AddMongoClient(Configuration);
{{/MongoDB}}
{{#OAuthConnector}}
services.AddOAuthServiceOptions(Configuration);
{{/OAuthConnector}}
{{#PostgresEFCore}}
// Add Context and use Postgres as provider ... provider will be configured from VCAP_ info
// services.AddDbContext<MyDbContext>(options => options.UseNpgsql(Configuration));
{{/PostgresEFCore}}
services.AddControllers();
}
// This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
}
{{#RequiresHttps}}
else
{
// The default HSTS value is 30 days. You may want to change this for production scenarios, see https://aka.ms/aspnetcore-hsts.
app.UseHsts();
}
app.UseHttpsRedirection();
{{/RequiresHttps}}
{{#Auth}}
app.UseAuthentication();
{{/Auth}}
{{#Discovery}}
app.UseDiscoveryClient();
{{/Discovery}}
app.UseRouting();
app.UseEndpoints(endpoints =>
{
endpoints.MapControllers();
});
}
}
}

Просмотреть файл

@ -0,0 +1,6 @@
<?xml version="1.0" encoding="utf-8" ?>
<configuration>
<runtime>
<gcServer enabled="true"/>
</runtime>
</configuration>

Просмотреть файл

@ -0,0 +1,14 @@
{
{{#PlaceholderConfig}}
"ResolvedPlaceholderFromEnvVariables": "${PATH?NotFound}",
"UnresolvedPlaceholder": "${SomKeyNotFound?NotFound}",
"ResolvedPlaceholderFromJson": "${Logging:LogLevel:System?${Loggin:LogLevel:Default}}",
{{/PlaceholderConfig}}
"Logging": {
"LogLevel": {
"Default": "Debug",
"System": "Information",
"Microsoft": "Information"
}
}
}

Просмотреть файл

@ -0,0 +1,226 @@
{
"Params": [
{
"Name": "Actuators",
"DefaultValue": false,
"Description": "Steeltoe: Add management endpoints for your application"
},
{
"Name": "Auth",
"DefaultValue": false,
"Description": "Add Authentication"
},
{
"Name": "CircuitBreaker",
"DefaultValue": false,
"Description": "Steeltoe: Add Circuit Breakers",
"FriendlyName": "Circuit Breakers"
},
{
"Name": "CloudFoundry",
"DefaultValue": false,
"Description": "Steeltoe: Target CloudFoundry Hosting",
"FriendlyName": "Cloud Foundry"
},
{
"Name": "Discovery",
"DefaultValue": false,
"Description": "Steeltoe: Add Discovery Client"
},
{
"Name": "DynamicLogger",
"DefaultValue": false,
"Description": "Steeltoe: Add Dynamic Logger"
},
{
"Name": "AzureSpringCloud",
"DefaultValue": false,
"Description": "Steeltoe: Target Microsoft Azure Spring Cloud Hosting",
"FriendlyName": "Microsoft Azure Spring Cloud"
},
{
"Name": "MongoDB",
"DefaultValue": false,
"Description": "Steeltoe: Add MongoDB connnectors"
},
{
"Name": "MySql",
"DefaultValue": "false",
"Description": "Steeltoe: Add MySql connnectors"
},
{
"Name": "MySqlEFCore",
"DefaultValue": false,
"Description": "Steeltoe: Add MySQL EFCore connnectors"
},
{
"Name": "OAuthConnector",
"DefaultValue": false,
"Description": "Steeltoe: Add OAuth connnectors"
},
{
"Name": "Postgres",
"DefaultValue": false,
"Description": "Steeltoe: Add Postgres connnectors"
},
{
"Name": "PostgresEFCore",
"DefaultValue": false,
"Description": "Steeltoe: Add PostgresEFCore connnectors"
},
{
"Name": "RabbitMQ",
"DefaultValue": false,
"Description": "Steeltoe: Add RabbitMQ connnectors"
},
{
"Name": "Redis",
"DefaultValue": false,
"Description": "Steeltoe: Add Redis connnectors"
},
{
"Name": "SQLServer",
"DefaultValue": false,
"Description": "Steeltoe: Add Microsoft SQL Server connnectors",
"friendlyName": "SQL Server"
},
{
"Name": "ProjectNameSpace",
"DefaultValue": "SteeltoeExample",
"Description": "Change the namespace "
},
{
"Name": "ConfigServer",
"DefaultValue": false,
"Description": "Steeltoe: Add ConfigServer Configuration Source",
"friendlyName": "Config Server"
},
{
"Name": "PlaceholderConfig",
"DefaultValue": false,
"Description": "Steeltoe: Add Placeholder Configuration Source",
"friendlyName": "Placeholder Configuration Source"
},
{
"Name": "RandomValueConfig",
"DefaultValue": false,
"Description": "Steeltoe: Add RandomValue Configuration Source",
"friendlyName": "RandomValue Configuration Source"
},
{
"Name": "Dockerfile",
"DefaultValue": false,
"Description": "Steeltoe: Add Dockerfile",
"friendlyName": "Dockerfile"
}
],
"CalculatedParams": [
{
"Name": "ActuatorsOrCloudFoundry",
"Expression": "Actuators,CloudFoundry",
"ExpressionType": "Any"
},
{
"Name": "AnyEFCore",
"Expression": "PostgresEFCore,MySqlEFCore",
"ExpressionType": "Any"
},
{
"Name": "MySqlOrMySqlEFCore",
"Expression": "MySql,MySqlEFCore",
"ExpressionType": "Any"
},
{
"Name": "ActuatorsOrDynamicLogger",
"Expression": "Actuators,DynamicLogger",
"ExpressionType": "Any"
},
{
"Name": "ValuesControllerWithArgs",
"Expression": "SQLServer,MySql,Postgres,MongoDB,RabbitMQ,Redis,ConfigServer,PlaceholderConfig,RandomValueConfig,CircuitBreaker,CloudFoundry",
"ExpressionType": "Any"
},
{
"Name": "MoreThanOneValuesControllerWithArgs",
"Expression": "SQLServer,MySql,Postgres,MongoDB,RabbitMQ,Redis,ConfigServer,PlaceholderConfig,RandomValueConfig,CircuitBreaker,CloudFoundry",
"ExpressionType": "MoreThanOne"
},
{
"Name": "AnyConfigSource",
"Expression": "ConfigServer,PlaceholderConfig,RandomValueConfig",
"ExpressionType": "Any"
},
{
"Name": "AnyConnector",
"Expression": "MySql,Postgres,Redis,MongoDB,RabbitMQ,OAuthConnector",
"ExpressionType": "Any"
},
{
"Name": "AspNetCoreVersion",
"Expression": "TargetFrameworkVersion,netcoreapp3.1=3.1.0,default=3.1.0",
"ExpressionType": "Case"
}
],
"ConditionalInclusions": [
{
"Name": "AnyEFCore",
"InclusionExpression": "Models/**"
},
{
"Name": "CircuitBreaker",
"InclusionExpression": "MyCircuitBreakerCommand.cs"
},
{
"Name": "Dockerfile",
"InclusionExpression": "Dockerfile"
}
],
"Versions": [
{
"Name": "SteeltoeVersion",
"DefaultValue": "2.4.4",
"Description": "Target the appropriate Steeltoe version",
"choices": [
{
"choice": "2.4.4",
"Description": "Target Steeltoe version 2.4.4"
},
{
"choice": "3.0.0-rc1",
"Description": "Target Steeltoe version 3.0.0-rc1"
}
]
},
{
"Name": "TargetFrameworkVersion",
"DefaultValue": "netcoreapp3.1",
"Description": "Target the appropriate Dotnet framework version",
"choices": [
{
"Choice": "netcoreapp3.1",
"Description": "Target Dotnet framework version 3.1"
}
]
},
{
"Name": "MySqlVersion",
"DefaultValue": "8.0.16"
},
{
"Name": "NpgSqlVersion",
"DefaultValue": "4.1.2"
},
{
"Name": "MongoDBVersion",
"DefaultValue": "2.8.1"
},
{
"Name": "RabbitMQVersion",
"DefaultValue": "5.1.0"
}
]
}

Просмотреть файл

@ -42,7 +42,7 @@ namespace Steeltoe.Initializr.TemplateEngine.Test.IntegrationTests
[Fact]
public void Scratch()
{
var argsList = GetArgs(typeof(MustacheTemplateService), DotnetFramework.NetCoreApp31, "Steeltoe-WebApi");
var argsList = GetArgs(typeof(MustacheTemplateService), "netcoreapp3.1", "Steeltoe-WebApi");
foreach (var args in argsList)
{
_testOutputHelper.WriteLine($"dotnet {args[1]}, template {args[2]}, dependency {args[3]}");
@ -50,27 +50,27 @@ namespace Steeltoe.Initializr.TemplateEngine.Test.IntegrationTests
}
[Theory]
[MemberData(nameof(GetArgs), typeof(MustacheTemplateService), DotnetFramework.NetCoreApp21, "Steeltoe-WebApi")]
public async Task Steeltoe24Dotnet21(ITemplateService service, DotnetFramework dotNet, string template, string dependency)
[MemberData(nameof(GetArgs), typeof(MustacheTemplateService), "netcoreapp2.1", "Steeltoe-WebApi")]
public async Task Steeltoe24Dotnet21(ITemplateService service, string framework, string template, string dependency)
{
await GenerateAndBuildProject(service, dotNet, template, dependency);
await GenerateAndBuildProject(service, framework, template, dependency);
}
[Theory]
[MemberData(nameof(GetArgs), typeof(MustacheTemplateService), DotnetFramework.NetCoreApp31, "Steeltoe-WebApi")]
public async Task Steeltoe24Dotnet31(ITemplateService service, DotnetFramework dotNet,
[MemberData(nameof(GetArgs), typeof(MustacheTemplateService), "netcoreapp3.1", "Steeltoe-WebApi")]
public async Task Steeltoe24Dotnet31(ITemplateService service, string framework,
string template, string dependency)
{
await GenerateAndBuildProject(service, dotNet, template, dependency);
await GenerateAndBuildProject(service, framework, template, dependency);
}
[Theory]
[MemberData(nameof(GetArgs), typeof(MustacheTemplateService), DotnetFramework.NetCoreApp31, "Steeltoe-WebApi")]
public async Task Steeltoe30Dotnet31(ITemplateService service, DotnetFramework dotNet,
string template, string dependency)
{
await GenerateAndBuildProject(service, dotNet, template, dependency);
}
// [Theory]
// [MemberData(nameof(GetArgs), typeof(MustacheTemplateService), "netcoreapp3.1", "Steeltoe-WebApi")]
// public async Task Steeltoe30Dotnet31(ITemplateService service, string framework,
// string template, string dependency)
// {
// await GenerateAndBuildProject(service, framework, template, dependency);
// }
// TODO: test Steeltoe 3
@ -78,19 +78,19 @@ namespace Steeltoe.Initializr.TemplateEngine.Test.IntegrationTests
private async Task GenerateAndBuildProject(
ITemplateService service,
DotnetFramework dotNet,
string framework,
string template,
string dependency,
string steeltoe = "2.4.4")
{
_testOutputHelper.WriteLine(
$"Generating and Building: Steeltoe {steeltoe}, DotNet {dotNet}, Template {template}, dependency {dependency}");
$"Generating and Building: Steeltoe {steeltoe}, Framework {framework}, Template {template}, dependency {dependency}");
var archive = await service.GenerateProjectArchiveAsync(new GeneratorModel()
{
Dependencies = dependency,
Template = template,
ProjectName = "Foo.Bar",
TargetFramework = dotNet == DotnetFramework.NetCoreApp21 ? "netcoreapp2.1" : "netcoreapp3.1",
TargetFramework = framework,
SteeltoeVersion = steeltoe,
});
@ -114,12 +114,12 @@ namespace Steeltoe.Initializr.TemplateEngine.Test.IntegrationTests
$"Error compiling {dependency}. \n {output}");
}
public static IEnumerable<object[]> GetArgs(Type templateServiceType, DotnetFramework dotNet, string template)
public static IEnumerable<object[]> GetArgs(Type templateServiceType, string framework, string template)
{
var service = BuildTemplateService(templateServiceType);
var deps = service.GetDependencies(dotNet, template).Select(dep => dep.ShortName.ToLower());
return from dep in deps select new object[] {service, dotNet, template, dep};
var deps = service.GetDependencies(framework, template).Select(dep => dep.ShortName.ToLower());
return from dep in deps select new object[] {service, framework, template, dep};
}
static ITemplateService BuildTemplateService(Type type)

Просмотреть файл

@ -39,8 +39,7 @@ namespace Steeltoe.Initializr.TemplateEngine.Test
[ClassData(typeof(AllImplementationsAndTemplates))]
public void GetDependencies(ITemplateService templateService, string templateName, string framework)
{
var frameworkEnum = Enum.Parse<DotnetFramework>(framework.Replace(".", ""), true);
var deps = templateService.GetDependencies(frameworkEnum, templateName);
var deps = templateService.GetDependencies(framework, templateName);
Assert.NotNull(deps);
Assert.NotEmpty(deps);
@ -51,8 +50,7 @@ namespace Steeltoe.Initializr.TemplateEngine.Test
[ClassData(typeof(AllImplementationsAndTemplates))]
public void GetDependencies_WithFriendlyNames(ITemplateService templateService, string templateName, string framework)
{
var frameworkEnum = Enum.Parse<DotnetFramework>(framework.Replace(".", ""), true);
var deps = templateService.GetDependencies(frameworkEnum, templateName);
var deps = templateService.GetDependencies(framework, templateName);
Assert.NotNull(deps);
Assert.NotEmpty(deps);