From 98ce833b7c1eb1f225de55abe7233032caad2ca1 Mon Sep 17 00:00:00 2001 From: "victor.gaborit" Date: Thu, 14 Mar 2024 17:09:48 +0100 Subject: [PATCH] =?UTF-8?q?ajout=20des=20methodes=20d'extensions=20mais=20?= =?UTF-8?q?elles=20ne=20sont=20pas=20encore=20utilis=C3=A9es?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- API_SQLuedo/API/Controllers/UserController.cs | 20 ++-- API_SQLuedo/API/Program.cs | 21 +++- API_SQLuedo/API/Service/UserDataServiceAPI.cs | 22 +++++ API_SQLuedo/DbContextLib/UserDbContext.cs | 1 + API_SQLuedo/DbDataManager/Extensions.cs | 96 +++++++++++++++++++ .../DbDataManager/Service/UserDataService.cs | 26 +++++ API_SQLuedo/Shared/DataService.cs | 34 +++++++ API_SQLuedo/Shared/IGenericDataService.cs | 17 ++++ API_SQLuedo/Shared/IUserService.cs | 2 +- API_SQLuedo/Shared/IdataService.cs | 19 ++++ API_SQLuedo/Shared/UserDataService.cs | 20 ++++ .../StubbedContextLib/StubbedContext.cs | 1 + 12 files changed, 263 insertions(+), 16 deletions(-) create mode 100644 API_SQLuedo/DbDataManager/Extensions.cs create mode 100644 API_SQLuedo/Shared/DataService.cs create mode 100644 API_SQLuedo/Shared/IGenericDataService.cs create mode 100644 API_SQLuedo/Shared/IdataService.cs diff --git a/API_SQLuedo/API/Controllers/UserController.cs b/API_SQLuedo/API/Controllers/UserController.cs index a6114f5..77e8cb1 100644 --- a/API_SQLuedo/API/Controllers/UserController.cs +++ b/API_SQLuedo/API/Controllers/UserController.cs @@ -11,15 +11,15 @@ namespace API.Controllers [Authorize] [ApiVersion("1.0")] [ApiController] - public class UsersController(ILogger logger, IUserDataService userService) : ControllerBase + public class UsersController(ILogger logger, IdataService dataService) : ControllerBase { [HttpGet("users/{page}/{number}")] [ProducesResponseType(typeof(UserDTO), 200)] [ProducesResponseType(typeof(string), 204)] - public IActionResult GetUsers(int page, int number, UserOrderCriteria orderCriteria) + public async Task GetUsers(int page, int number, UserOrderCriteria orderCriteria) { - var users = userService.GetUsers(page, number, orderCriteria).ToList(); - if (users.Count == 0) + var users = (await dataService.userService.GetItems(page, number, orderCriteria)).ToList(); + if (users.Count() == 0) { logger.LogError("[ERREUR] Aucun utilisateur trouvé."); return StatusCode(204); @@ -37,7 +37,7 @@ namespace API.Controllers try { logger.LogInformation("[INFORMATION] Utilisateur avec l'id {id} a été trouvé.", id); - return Ok(userService.GetUserById(id)); + return Ok(dataService.userService.GetUserById(id)); } catch (ArgumentException) { @@ -54,7 +54,7 @@ namespace API.Controllers try { logger.LogInformation("[INFORMATION] Utilisateur avec l'username {username} a été trouvé.", username); - return Ok(userService.GetUserByUsername(username)); + return Ok(dataService.userService.GetUserByUsername(username)); } catch (ArgumentException) { @@ -68,11 +68,11 @@ namespace API.Controllers [ProducesResponseType(typeof(string), 404)] public IActionResult DeleteUser(int id) { - var success = userService.DeleteUser(id); + var success = dataService.userService.DeleteUser(id); if (success) { logger.LogInformation("[INFORMATION] L'utilisateur avec l'id {id} a été supprimé.", id); - return Ok(userService.DeleteUser(id)); + return Ok(dataService.userService.DeleteUser(id)); } else { @@ -96,7 +96,7 @@ namespace API.Controllers "[INFORMATION] Un utilisateur a été créé : username - {username}, password - {password}, email - {email}, isAdmin - {isAdmin}", dto.Username, dto.Password, dto.Email, dto.IsAdmin); return Created(nameof(GetUsers), - userService.CreateUser(dto.Username, dto.Password, dto.Email, dto.IsAdmin)); + dataService.userService.CreateUser(dto.Username, dto.Password, dto.Email, dto.IsAdmin)); } [HttpPut("user/{id}")] @@ -122,7 +122,7 @@ namespace API.Controllers { logger.LogInformation("[INFORMATION] La mise à jour de l'utilsiateur avec l'id {id} a été effectuée", id); - return Ok(userService.UpdateUser(id, userDto)); + return Ok(dataService.userService.UpdateUser(id, userDto)); } logger.LogError("[ERREUR] Aucun utilisateur trouvé avec l'id {id}.", id); diff --git a/API_SQLuedo/API/Program.cs b/API_SQLuedo/API/Program.cs index 338e26c..2916e69 100644 --- a/API_SQLuedo/API/Program.cs +++ b/API_SQLuedo/API/Program.cs @@ -21,20 +21,31 @@ builder.Services.AddControllers(); builder.Services.AddEndpointsApiExplorer(); builder.Services.AddSwaggerGen(); -builder.Services.AddScoped, DbDataManager.Service.UserDataService>(); +//builder.Services.AddScoped, DbDataManager.Service.UserDataService>(); +//builder.Services.AddScoped(); builder.Services.AddScoped, Shared.UserDataService>(); +builder.Services.AddScoped, DataService>(); +//builder.Services.AddScoped, Shared.UserDataService>(); -builder.Services.AddScoped, DbDataManager.Service.InquiryDataService>(); +//builder.Services.AddScoped, DbDataManager.Service.InquiryDataService>(); +//builder.Services.AddScoped(); builder.Services.AddScoped, Shared.InquiryDataService>(); +//builder.Services.AddScoped, Shared.InquiryDataService>(); -builder.Services.AddScoped, DbDataManager.Service.ParagraphDataService>(); +//builder.Services.AddScoped, DbDataManager.Service.ParagraphDataService>(); +//builder.Services.AddScoped(); builder.Services.AddScoped, Shared.ParagraphDataService>(); +//builder.Services.AddScoped, Shared.ParagraphDataService>(); -builder.Services.AddScoped, DbDataManager.Service.SuccessDataService>(); +//builder.Services.AddScoped, DbDataManager.Service.SuccessDataService>(); +//builder.Services.AddScoped(); builder.Services.AddScoped, Shared.SuccessDataService>(); +//builder.Services.AddScoped, Shared.SuccessDataService>(); -builder.Services.AddScoped, DbDataManager.Service.LessonDataService>(); +//builder.Services.AddScoped, DbDataManager.Service.LessonDataService>(); +//builder.Services.AddScoped(); builder.Services.AddScoped, Shared.LessonDataService>(); +//builder.Services.AddScoped, Shared.LessonDataService>(); builder.Services.AddDbContext(); builder.Services.AddDbContext(options => options.UseInMemoryDatabase("appDb")); diff --git a/API_SQLuedo/API/Service/UserDataServiceAPI.cs b/API_SQLuedo/API/Service/UserDataServiceAPI.cs index c1d4997..93e366b 100644 --- a/API_SQLuedo/API/Service/UserDataServiceAPI.cs +++ b/API_SQLuedo/API/Service/UserDataServiceAPI.cs @@ -1,6 +1,7 @@ using Entities; using Model.OrderCriteria; using Shared; +using static System.Runtime.InteropServices.JavaScript.JSType; namespace API.Service; @@ -23,4 +24,25 @@ public class UserDataServiceApi(IUserService userService) : IUserSer public UserEntity CreateUser(string username, string password, string email, bool isAdmin) => userService.CreateUser(username, password, email, isAdmin); + + public Task AddItem(UserEntity? item) + { + throw new NotImplementedException(); + } + + public Task DeleteItem(int id) + { + throw new NotImplementedException(); + } + + public Task UpdateItem(int? id, TDto? newItem) where TDto : class + { + throw new NotImplementedException(); + } + + public async Task> GetItems(int page, int count, object orderCriteria, string? filter = null, object? valueFilter = null) + { + var usersEntities = await userService.GetItems(page, count, orderCriteria, filter, valueFilter); + return usersEntities.Select(e => e).ToList(); + } } \ No newline at end of file diff --git a/API_SQLuedo/DbContextLib/UserDbContext.cs b/API_SQLuedo/DbContextLib/UserDbContext.cs index 0bcf02a..e799386 100644 --- a/API_SQLuedo/DbContextLib/UserDbContext.cs +++ b/API_SQLuedo/DbContextLib/UserDbContext.cs @@ -18,6 +18,7 @@ namespace DbContextLib public DbSet Successes { get; set; } public DbSet Notepads { get; set; } public UserDbContext(DbContextOptions options) : base(options) { } + public UserDbContext() : base() { } protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder) { if (!optionsBuilder.IsConfigured) diff --git a/API_SQLuedo/DbDataManager/Extensions.cs b/API_SQLuedo/DbDataManager/Extensions.cs new file mode 100644 index 0000000..5f01cbf --- /dev/null +++ b/API_SQLuedo/DbDataManager/Extensions.cs @@ -0,0 +1,96 @@ +using Microsoft.EntityFrameworkCore; +using System; +using System.Collections.Generic; +using System.Linq; +using System.Linq.Expressions; +using System.Text; +using System.Threading.Tasks; + +namespace ModelToEntities +{ + internal static class Extensions + { + internal static Task CreateItemAsync(this DbContext context, T? item) where T : class + { + if (item == null || context.Set().Contains(item)) + { + return Task.FromResult(null); + } + + context.Set().Add(item); + context.SaveChangesAsync(); + + return Task.FromResult(item); + } + internal static Task DeleteItemAsync(this DbContext context, int? id) where T : class + { + if (id == null) + { + return Task.FromResult(false); + } + + var entity = context.Set().Find(id); + if (entity == null) + { + return Task.FromResult(false); + } + + context.Set().Remove(entity); + context.SaveChanges(); + + return Task.FromResult(true); + } + internal static Task UpdateItemAsync(this DbContext context, int? id, TDto dto) + where T : class + where TDto : class + { + var entity = context.Set().Find(id); + if (entity == null) + { + throw new ArgumentException("Impossible de trouver l'entité", nameof(id)); + } + var primaryKey = context.Model.FindEntityType(typeof(T)).FindPrimaryKey(); + var primaryKeyPropertyName = primaryKey.Properties.Select(x => x.Name).Single(); + + var propertiesToUpdate = typeof(TDto).GetProperties() + .Where(p => p.CanRead && p.CanWrite && p.Name != primaryKeyPropertyName); + + foreach (var property in propertiesToUpdate) + { + var value = property.GetValue(dto); + typeof(T).GetProperty(property.Name)?.SetValue(entity, value); + } + + context.Entry(entity).State = EntityState.Modified; // Permet d'indiquer en Db que l'entité a été modifiée. + context.SaveChanges(); + + return Task.FromResult(entity); + } + internal static Task> GetItemsWithFilter(this DbContext context, + int page, int count, object orderCriteria, string? filter = null, object? valueProperty = null) where T : class + { + IQueryable query = context.Set(); + + if (valueProperty != null && !string.IsNullOrEmpty(filter)) + { + var idProp = typeof(T).GetProperty(filter); + if (idProp != null) + { + var parameter = Expression.Parameter(typeof(T), "entity"); + var propertyAccess = Expression.Property(parameter, idProp); + var constant = Expression.Constant(valueProperty); + var equality = Expression.Equal(propertyAccess, constant); + var lambda = Expression.Lambda>(equality, parameter); + var filteredEntity = context.Set().FirstOrDefault(lambda); + if (filteredEntity != null) + { + return Task.FromResult>(new List { filteredEntity }); + } + } + return Task.FromResult>(null); + } + var items = query.Skip((page - 1) * count).Take(count).ToList().Select(u => u); + return Task.FromResult>(items); + } + } +} diff --git a/API_SQLuedo/DbDataManager/Service/UserDataService.cs b/API_SQLuedo/DbDataManager/Service/UserDataService.cs index b4de650..d9d9ae6 100644 --- a/API_SQLuedo/DbDataManager/Service/UserDataService.cs +++ b/API_SQLuedo/DbDataManager/Service/UserDataService.cs @@ -2,6 +2,7 @@ using Entities; using Microsoft.EntityFrameworkCore; using Model.OrderCriteria; +using ModelToEntities; using Shared; namespace DbDataManager.Service; @@ -89,4 +90,29 @@ public class UserDataService : IUserService DbContext.SaveChangesAsync(); return newUserEntity; } + + public Task AddItem(UserEntity? item) + { + throw new NotImplementedException(); + } + + public Task DeleteItem(int id) + { + throw new NotImplementedException(); + } + + public Task UpdateItem(int? id, TDto? newItem) where TDto : class + { + throw new NotImplementedException(); + } + + public async Task> GetItems(int page, int count, object orderCriteria, string? filter = null, object? valueFilter = null) + { + var user = (await DbContext.GetItemsWithFilter(page, count, orderCriteria, filter, valueFilter)); + if(user == null) + { + throw new ArgumentNullException("il n'y a pas de donnée"); + } + return user; + } } \ No newline at end of file diff --git a/API_SQLuedo/Shared/DataService.cs b/API_SQLuedo/Shared/DataService.cs new file mode 100644 index 0000000..3f8c439 --- /dev/null +++ b/API_SQLuedo/Shared/DataService.cs @@ -0,0 +1,34 @@ +using DbContextLib; +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace Shared +{ + public class DataService : IdataService where TUser : class + { + private UserDbContext _dbContext; + public DataService(UserDbContext userDbContext, IUserService userService, ILessonService lessonService, IInquiryService inquiryService, IParagraphService paragrapheService, ISuccessService sucessService) + { + this._dbContext = userDbContext; + + this.inquiryService = inquiryService; + this.lessonService = lessonService; + this.paragraphService = paragrapheService; + this.successDataService = sucessService; + this.userService = userService; + //this.userService = new UserDataService(userDbContext); + } + public IUserService userService { get; } + + public IInquiryService inquiryService { get; } + + public ILessonService lessonService { get; } + + public IParagraphService paragraphService { get; } + + public ISuccessService successDataService { get; } +} +} diff --git a/API_SQLuedo/Shared/IGenericDataService.cs b/API_SQLuedo/Shared/IGenericDataService.cs new file mode 100644 index 0000000..334892a --- /dev/null +++ b/API_SQLuedo/Shared/IGenericDataService.cs @@ -0,0 +1,17 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace Shared +{ + public interface IGenericDataService where T : class + { + public Task AddItem(T? item); + public Task DeleteItem(int id); + public Task UpdateItem(int? id, TDto? newItem) where TDto : class; + public Task> GetItems(int page, int count, object orderCriteria, string? filter = null, object? valueFilter = null); + + } +} diff --git a/API_SQLuedo/Shared/IUserService.cs b/API_SQLuedo/Shared/IUserService.cs index d1d458a..719becf 100644 --- a/API_SQLuedo/Shared/IUserService.cs +++ b/API_SQLuedo/Shared/IUserService.cs @@ -2,7 +2,7 @@ namespace Shared { - public interface IUserService + public interface IUserService : IGenericDataService where TUser : class { public IEnumerable GetUsers(int page, int number, UserOrderCriteria orderCriteria); public TUser GetUserById(int id); diff --git a/API_SQLuedo/Shared/IdataService.cs b/API_SQLuedo/Shared/IdataService.cs new file mode 100644 index 0000000..4198305 --- /dev/null +++ b/API_SQLuedo/Shared/IdataService.cs @@ -0,0 +1,19 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace Shared +{ + public interface IdataService where TUser : class + { + IUserService userService { get; } + IInquiryService inquiryService { get; } + ILessonService lessonService { get; } + IParagraphService paragraphService { get; } + ISuccessService successDataService { get; } + + + } +} diff --git a/API_SQLuedo/Shared/UserDataService.cs b/API_SQLuedo/Shared/UserDataService.cs index a90b809..21702d1 100644 --- a/API_SQLuedo/Shared/UserDataService.cs +++ b/API_SQLuedo/Shared/UserDataService.cs @@ -117,5 +117,25 @@ namespace Shared return newUserEntity; } + + public Task AddItem(UserDTO? item) + { + throw new NotImplementedException(); + } + + public Task DeleteItem(int id) + { + throw new NotImplementedException(); + } + + public Task UpdateItem(int? id, TDto? newItem) where TDto : class + { + throw new NotImplementedException(); + } + + public Task> GetItems(int page, int count, object orderCriteria, string? filter = null, object? valueFilter = null) + { + throw new NotImplementedException(); + } } } diff --git a/API_SQLuedo/StubbedContextLib/StubbedContext.cs b/API_SQLuedo/StubbedContextLib/StubbedContext.cs index e87f12f..541bc48 100644 --- a/API_SQLuedo/StubbedContextLib/StubbedContext.cs +++ b/API_SQLuedo/StubbedContextLib/StubbedContext.cs @@ -12,6 +12,7 @@ public class StubbedContext : UserDbContext public StubbedContext(DbContextOptions options) : base(options) { } + public StubbedContext() : base() { } protected override void OnModelCreating(ModelBuilder modelBuilder) {