From 58f6e2ab0e36f434f0fc5be8bbb797d008b1f8b7 Mon Sep 17 00:00:00 2001 From: dave Date: Fri, 15 Mar 2024 19:08:53 +0100 Subject: [PATCH] GOOOOOOO --- src/HeartTrackAPI/AppBootstrap.cs | 234 ------------------------------ src/HeartTrackAPI/Program.cs | 162 ++++++++++++++++++++- 2 files changed, 154 insertions(+), 242 deletions(-) diff --git a/src/HeartTrackAPI/AppBootstrap.cs b/src/HeartTrackAPI/AppBootstrap.cs index ae5caeb..b0a9d5b 100644 --- a/src/HeartTrackAPI/AppBootstrap.cs +++ b/src/HeartTrackAPI/AppBootstrap.cs @@ -19,237 +19,3 @@ using Swashbuckle.AspNetCore.SwaggerGen; namespace HeartTrackAPI; -public class AppBootstrap(IConfiguration configuration) -{ - private IConfiguration Configuration { get; } = configuration; - - public void ConfigureServices(IServiceCollection services) - { - services.AddControllers(); - services.AddEndpointsApiExplorer(); - AddSwagger(services); - // include Xml comment - // addsecurityRequiment - // securityDef - AddHeartTrackContextServices(services); - AddModelService(services); - AddIdentityServices(services); - AddApiVersioning(services); - - services.AddHealthChecks(); - - } - - private void AddHeartTrackContextServices(IServiceCollection services) - { - string connectionString; - - switch (Environment.GetEnvironmentVariable("TYPE")) - { - case "BDD": - var HOST = System.Environment.GetEnvironmentVariable("HOST"); - var PORT = System.Environment.GetEnvironmentVariable("PORTDB"); - var DATABASE = System.Environment.GetEnvironmentVariable("DATABASE"); - var USERNAME = System.Environment.GetEnvironmentVariable("USERNAME"); - var PASSWORD = System.Environment.GetEnvironmentVariable("PASSWORD"); - - connectionString = $"Server={HOST};port={PORT};database={DATABASE};user={USERNAME};password={PASSWORD}"; - Console.WriteLine("========RUNNING USING THE MYSQL SERVER=============="); - Console.WriteLine(connectionString); - Console.WriteLine(connectionString); - Console.WriteLine("======================"); - // with auth when it was working was'nt here - services.AddDbContext(options => options.UseInMemoryDatabase("AuthDb")); - services.AddDbContext(options => - options.UseMySql($"{connectionString}", new MySqlServerVersion(new Version(10, 11, 1))) - , ServiceLifetime.Singleton); - break; - default: - Console.WriteLine("====== RUNNING USING THE IN SQLLITE DATABASE ======"); - connectionString = Configuration.GetConnectionString("HeartTrackAuthConnection"); - if (!string.IsNullOrWhiteSpace(connectionString)) - { - services.AddDbContext(options => options.UseInMemoryDatabase("AuthDb")); - Console.WriteLine(connectionString); - Console.WriteLine("======================"); - //options => options.UseSqlite(connectionString) - //services.AddDbContext(); - testDir(); - services.AddDbContext(options => - options.UseSqlite($"Data Source=uca_HeartTrack.db"), ServiceLifetime.Singleton); - - } - else - { - services.AddDbContext(options => options.UseInMemoryDatabase("AuthDb")); - services.AddDbContext(options => options.UseInMemoryDatabase("HeartTrackDb")); - } - break; - - } - -/* - services.AddSingleton>(provider => - { - var connection = new SqliteConnection("DataSource=:memory:"); - connection.Open(); - - var options = new DbContextOptionsBuilder() - .UseSqlite(connection) - .Options; - - return options; - });*/ - } - - public void testDir() - { - var dirPath = @"/"; - - // Créez une instance de DirectoryInfo - DirectoryInfo d = new DirectoryInfo(dirPath); - - // Obtenez les fichiers et les dossiers - FileInfo[] Files = d.GetFiles(); // Obtenez la liste des fichiers - DirectoryInfo[] Directories = d.GetDirectories(); // Obtenez la liste des dossiers - - // Affichez les fichiers - Console.WriteLine("Fichiers:"); - foreach(FileInfo file in Files ) - { - Console.WriteLine($"{file.Name}"); - } - - // Affichez les dossiers - Console.WriteLine("\nDossiers:"); - foreach(DirectoryInfo dir in Directories) - { - Console.WriteLine($"{dir.Name}"); - } - } - - private void AddModelService(IServiceCollection services) - { - //services.AddSingleton(provider => new DbDataManager(provider.GetService())); - //services.AddSingleton(); - services.AddSingleton(provider => new DbDataManager(provider.GetRequiredService())); - - //services.AddTransient(); - } - - private void AddIdentityServices(IServiceCollection services) - { -// services.AddTransient, EmailSender>(); - services.AddAuthorization(); - - services.AddIdentityApiEndpoints() - .AddEntityFrameworkStores(); - //services.AddIdentity() - // .AddEntityFrameworkStores().AddDefaultTokenProviders(); - } - - private void AddApiVersioning(IServiceCollection services) - { - - services.AddApiVersioning(opt => - { - opt.ReportApiVersions = true; - opt.AssumeDefaultVersionWhenUnspecified = true; - opt.DefaultApiVersion = new Microsoft.AspNetCore.Mvc.ApiVersion(1, 0); -// options.ApiVersionReader = new HeaderApiVersionReader("api-version"); - - opt.ApiVersionReader = ApiVersionReader.Combine(new UrlSegmentApiVersionReader(), - new HeaderApiVersionReader("x-api-version"), - new MediaTypeApiVersionReader("x-api-version")); - }); - - } - private void AddSwagger(IServiceCollection services) - { - services.AddSwaggerGen(options => - { - options.OperationFilter(); - - var xmlFile = $"{Assembly.GetExecutingAssembly().GetName().Name}.xml"; - var xmlPath = Path.Combine(AppContext.BaseDirectory, xmlFile); - options.IncludeXmlComments(xmlPath); - - options.AddSecurityDefinition("Bearer", new OpenApiSecurityScheme - { - Description = - "JWT Authorization header using the Bearer scheme. Example: \"Authorization: Bearer {token}\"", - Name = "Authorization", - In = ParameterLocation.Header, - Type = SecuritySchemeType.ApiKey - }); - var scheme = new OpenApiSecurityRequirement - { - { - new OpenApiSecurityScheme - { - Reference = new OpenApiReference - { - Type = ReferenceType.SecurityScheme, - Id = "Bearer" - }, - Scheme = "oauth2", - Name = "Bearer", - In = ParameterLocation.Header, - }, - new List() - } - }; - options.AddSecurityRequirement(scheme); - }); - services.AddTransient, SwaggerOptions>(); - services.AddSwaggerGen(options => - { - options.OperationFilter(); - }); - /* services.AddSwaggerGen(options => - { - options.SwaggerDoc("v1", new OpenApiInfo { Title = "HeartTrackAPI", Version = "v1" }); - options.SwaggerDoc("v2", new OpenApiInfo { Title = "HeartTrackAPI", Version = "v2" }); - });*/ - - services.AddVersionedApiExplorer(setup => - { - setup.GroupNameFormat = "'v'VVV"; - setup.SubstituteApiVersionInUrl = true; - }); - - } - - public void Configure(WebApplication app, IWebHostEnvironment env) - { - app.UseHttpsRedirection(); - app.MapIdentityApi(); - - app.MapControllers(); - app.UseAuthorization(); - - app.MapHealthChecks("/health"); - - // Configure the HTTP request pipeline. - if (true) - { - var apiVersionDescriptionProvider = app.Services.GetRequiredService(); - app.UseSwagger(); - app.UseSwaggerUI(); - app.MapSwagger(); - app.UseSwaggerUI(options => - { - foreach (var description in apiVersionDescriptionProvider.ApiVersionDescriptions) - - //foreach (var description in apiVersionDescriptionProvider) - { - options.SwaggerEndpoint($"/swagger/{description.GroupName}/swagger.json", - description.GroupName.ToUpperInvariant()); - } - }); - - } - - - } -} diff --git a/src/HeartTrackAPI/Program.cs b/src/HeartTrackAPI/Program.cs index 5fcc883..bc3f19e 100644 --- a/src/HeartTrackAPI/Program.cs +++ b/src/HeartTrackAPI/Program.cs @@ -1,24 +1,170 @@ +using System.Reflection; using DbContextLib; +using DbContextLib.Identity; using HeartTrackAPI; +using HeartTrackAPI.Utils; +using Microsoft.AspNetCore.Identity; +using Microsoft.AspNetCore.Mvc.ApiExplorer; +using Microsoft.AspNetCore.Mvc.Versioning; +using Microsoft.EntityFrameworkCore; +using Microsoft.Extensions.Options; +using Microsoft.OpenApi.Models; +using Model.Manager; +using Model2Entities; +using Swashbuckle.AspNetCore.SwaggerGen; var builder = WebApplication.CreateBuilder(args); builder.Logging.AddConsole(); -builder.WebHost.ConfigureKestrel(serverOptions => +builder.WebHost.ConfigureKestrel(serverOptions => { serverOptions.Limits.MaxRequestBodySize = long.MaxValue; }); + + +builder.Services.AddControllers(); +builder.Services.AddEndpointsApiExplorer(); +builder.Services.AddSwaggerGen(options => +{ + options.OperationFilter(); + + var xmlFile = $"{Assembly.GetExecutingAssembly().GetName().Name}.xml"; + var xmlPath = Path.Combine(AppContext.BaseDirectory, xmlFile); + options.IncludeXmlComments(xmlPath); + + options.AddSecurityDefinition("Bearer", new OpenApiSecurityScheme + { + Description = + "JWT Authorization header using the Bearer scheme. Example: \"Authorization: Bearer {token}\"", + Name = "Authorization", + In = ParameterLocation.Header, + Type = SecuritySchemeType.ApiKey + }); + var scheme = new OpenApiSecurityRequirement + { + { + new OpenApiSecurityScheme + { + Reference = new OpenApiReference + { + Type = ReferenceType.SecurityScheme, + Id = "Bearer" + }, + Scheme = "oauth2", + Name = "Bearer", + In = ParameterLocation.Header, + }, + new List() + } + }; + options.AddSecurityRequirement(scheme); +}); +builder.Services.AddTransient, SwaggerOptions>(); +builder.Services.AddSwaggerGen(options => { options.OperationFilter(); }); +/* services.AddSwaggerGen(options => + { + options.SwaggerDoc("v1", new OpenApiInfo { Title = "HeartTrackAPI", Version = "v1" }); + options.SwaggerDoc("v2", new OpenApiInfo { Title = "HeartTrackAPI", Version = "v2" }); + });*/ + +builder.Services.AddVersionedApiExplorer(setup => { - serverOptions.Limits.MaxRequestBodySize = long.MaxValue; + setup.GroupNameFormat = "'v'VVV"; + setup.SubstituteApiVersionInUrl = true; }); -var init = new AppBootstrap(builder.Configuration); +string connectionString; + +switch (Environment.GetEnvironmentVariable("TYPE")) +{ + case "BDD": + var HOST = System.Environment.GetEnvironmentVariable("HOST"); + var PORT = System.Environment.GetEnvironmentVariable("PORTDB"); + var DATABASE = System.Environment.GetEnvironmentVariable("DATABASE"); + var USERNAME = System.Environment.GetEnvironmentVariable("USERNAME"); + var PASSWORD = System.Environment.GetEnvironmentVariable("PASSWORD"); + + connectionString = $"Server={HOST};port={PORT};database={DATABASE};user={USERNAME};password={PASSWORD}"; + Console.WriteLine("========RUNNING USING THE MYSQL SERVER=============="); + Console.WriteLine(connectionString); + Console.WriteLine(connectionString); + Console.WriteLine("======================"); + // with auth when it was working was'nt here + builder.Services.AddDbContext(options => options.UseInMemoryDatabase("AuthDb")); + builder.Services.AddDbContext(options => + options.UseMySql($"{connectionString}", new MySqlServerVersion(new Version(10, 11, 1))) + , ServiceLifetime.Singleton); + break; + default: + Console.WriteLine("====== RUNNING USING THE IN SQLLITE DATABASE ======"); + connectionString = builder.Configuration.GetConnectionString("HeartTrackAuthConnection"); + if (!string.IsNullOrWhiteSpace(connectionString)) + { + builder.Services.AddDbContext(options => options.UseInMemoryDatabase("AuthDb")); + Console.WriteLine(connectionString); + Console.WriteLine("======================"); + //options => options.UseSqlite(connectionString) + //services.AddDbContext(); + builder.Services.AddDbContext(options => + options.UseSqlite(connectionString), ServiceLifetime.Singleton); + } + else + { + builder.Services.AddDbContext(options => options.UseInMemoryDatabase("AuthDb")); + builder.Services.AddDbContext(options => options.UseInMemoryDatabase("HeartTrackDb")); + } + + break; +} + +builder.Services.AddSingleton(provider => + new DbDataManager(provider.GetRequiredService())); +builder.Services.AddAuthorization(); + +builder.Services.AddIdentityApiEndpoints() + .AddEntityFrameworkStores(); + +builder.Services.AddApiVersioning(opt => +{ + opt.ReportApiVersions = true; + opt.AssumeDefaultVersionWhenUnspecified = true; + opt.DefaultApiVersion = new Microsoft.AspNetCore.Mvc.ApiVersion(1, 0); +// options.ApiVersionReader = new HeaderApiVersionReader("api-version"); + + opt.ApiVersionReader = ApiVersionReader.Combine(new UrlSegmentApiVersionReader(), + new HeaderApiVersionReader("x-api-version"), + new MediaTypeApiVersionReader("x-api-version")); +}); + +builder.Services.AddHealthChecks(); -init.ConfigureServices(builder.Services); var app = builder.Build(); -init.Configure(app, app.Environment); -init.testDir(); +app.UseHttpsRedirection(); +app.MapIdentityApi(); + +app.MapControllers(); +app.UseAuthorization(); + +app.MapHealthChecks("/health"); + +// Configure the HTTP request pipeline. +if (true) +{ + var apiVersionDescriptionProvider = app.Services.GetRequiredService(); + app.UseSwagger(); + app.UseSwaggerUI(); + app.MapSwagger(); + app.UseSwaggerUI(options => + { + foreach (var description in apiVersionDescriptionProvider.ApiVersionDescriptions) + + //foreach (var description in apiVersionDescriptionProvider) + { + options.SwaggerEndpoint($"/swagger/{description.GroupName}/swagger.json", + description.GroupName.ToUpperInvariant()); + } + }); +} -app.Services.GetService().Database.EnsureCreated(); -init.testDir(); +app.Services.GetService()!.Database.EnsureCreated(); app.Run(); \ No newline at end of file