ajout des methodes d'extensions mais elles ne sont pas encore utilisées
continuous-integration/drone/push Build is failing Details

MethodeExtensions
Victor GABORIT 1 year ago
parent 73b603e21c
commit 98ce833b7c

@ -11,15 +11,15 @@ namespace API.Controllers
[Authorize] [Authorize]
[ApiVersion("1.0")] [ApiVersion("1.0")]
[ApiController] [ApiController]
public class UsersController(ILogger<UsersController> logger, IUserDataService userService) : ControllerBase public class UsersController(ILogger<UsersController> logger, IdataService<UserDTO, LessonDTO, InquiryDTO, ParagraphDTO, SuccessDTO> dataService) : ControllerBase
{ {
[HttpGet("users/{page}/{number}")] [HttpGet("users/{page}/{number}")]
[ProducesResponseType(typeof(UserDTO), 200)] [ProducesResponseType(typeof(UserDTO), 200)]
[ProducesResponseType(typeof(string), 204)] [ProducesResponseType(typeof(string), 204)]
public IActionResult GetUsers(int page, int number, UserOrderCriteria orderCriteria) public async Task<IActionResult> GetUsers(int page, int number, UserOrderCriteria orderCriteria)
{ {
var users = userService.GetUsers(page, number, orderCriteria).ToList(); var users = (await dataService.userService.GetItems(page, number, orderCriteria)).ToList();
if (users.Count == 0) if (users.Count() == 0)
{ {
logger.LogError("[ERREUR] Aucun utilisateur trouvé."); logger.LogError("[ERREUR] Aucun utilisateur trouvé.");
return StatusCode(204); return StatusCode(204);
@ -37,7 +37,7 @@ namespace API.Controllers
try try
{ {
logger.LogInformation("[INFORMATION] Utilisateur avec l'id {id} a été trouvé.", id); 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) catch (ArgumentException)
{ {
@ -54,7 +54,7 @@ namespace API.Controllers
try try
{ {
logger.LogInformation("[INFORMATION] Utilisateur avec l'username {username} a été trouvé.", username); 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) catch (ArgumentException)
{ {
@ -68,11 +68,11 @@ namespace API.Controllers
[ProducesResponseType(typeof(string), 404)] [ProducesResponseType(typeof(string), 404)]
public IActionResult DeleteUser(int id) public IActionResult DeleteUser(int id)
{ {
var success = userService.DeleteUser(id); var success = dataService.userService.DeleteUser(id);
if (success) if (success)
{ {
logger.LogInformation("[INFORMATION] L'utilisateur avec l'id {id} a été supprimé.", id); 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 else
{ {
@ -96,7 +96,7 @@ namespace API.Controllers
"[INFORMATION] Un utilisateur a été créé : username - {username}, password - {password}, email - {email}, isAdmin - {isAdmin}", "[INFORMATION] Un utilisateur a été créé : username - {username}, password - {password}, email - {email}, isAdmin - {isAdmin}",
dto.Username, dto.Password, dto.Email, dto.IsAdmin); dto.Username, dto.Password, dto.Email, dto.IsAdmin);
return Created(nameof(GetUsers), 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}")] [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", logger.LogInformation("[INFORMATION] La mise à jour de l'utilsiateur avec l'id {id} a été effectuée",
id); 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); logger.LogError("[ERREUR] Aucun utilisateur trouvé avec l'id {id}.", id);

@ -21,20 +21,31 @@ builder.Services.AddControllers();
builder.Services.AddEndpointsApiExplorer(); builder.Services.AddEndpointsApiExplorer();
builder.Services.AddSwaggerGen(); builder.Services.AddSwaggerGen();
builder.Services.AddScoped<IUserService<UserEntity>, DbDataManager.Service.UserDataService>(); //builder.Services.AddScoped<IUserService<UserEntity>, DbDataManager.Service.UserDataService>();
//builder.Services.AddScoped<IUserDataService, Shared.UserDataService>();
builder.Services.AddScoped<IUserService<UserDTO>, Shared.UserDataService>(); builder.Services.AddScoped<IUserService<UserDTO>, Shared.UserDataService>();
builder.Services.AddScoped<IdataService<UserDTO, LessonDTO, InquiryDTO, ParagraphDTO, SuccessDTO>, DataService<UserDTO, LessonDTO, InquiryDTO, ParagraphDTO, SuccessDTO>>();
//builder.Services.AddScoped<IUserService<UserDTO>, Shared.UserDataService>();
builder.Services.AddScoped<IInquiryService<InquiryEntity>, DbDataManager.Service.InquiryDataService>(); //builder.Services.AddScoped<IInquiryService<InquiryEntity>, DbDataManager.Service.InquiryDataService>();
//builder.Services.AddScoped<IInquiryDataService, Shared.InquiryDataService>();
builder.Services.AddScoped<IInquiryService<InquiryDTO>, Shared.InquiryDataService>(); builder.Services.AddScoped<IInquiryService<InquiryDTO>, Shared.InquiryDataService>();
//builder.Services.AddScoped<IInquiryService<InquiryDTO>, Shared.InquiryDataService>();
builder.Services.AddScoped<IParagraphService<ParagraphEntity>, DbDataManager.Service.ParagraphDataService>(); //builder.Services.AddScoped<IParagraphService<ParagraphEntity>, DbDataManager.Service.ParagraphDataService>();
//builder.Services.AddScoped<IParagraphDataService, Shared.ParagraphDataService>();
builder.Services.AddScoped<IParagraphService<ParagraphDTO>, Shared.ParagraphDataService>(); builder.Services.AddScoped<IParagraphService<ParagraphDTO>, Shared.ParagraphDataService>();
//builder.Services.AddScoped<IParagraphService<ParagraphDTO>, Shared.ParagraphDataService>();
builder.Services.AddScoped<ISuccessService<SuccessEntity>, DbDataManager.Service.SuccessDataService>(); //builder.Services.AddScoped<ISuccessService<SuccessEntity>, DbDataManager.Service.SuccessDataService>();
//builder.Services.AddScoped<ISuccessDataService, Shared.SuccessDataService>();
builder.Services.AddScoped<ISuccessService<SuccessDTO>, Shared.SuccessDataService>(); builder.Services.AddScoped<ISuccessService<SuccessDTO>, Shared.SuccessDataService>();
//builder.Services.AddScoped<ISuccessService<SuccessDTO>, Shared.SuccessDataService>();
builder.Services.AddScoped<ILessonService<LessonEntity>, DbDataManager.Service.LessonDataService>(); //builder.Services.AddScoped<ILessonService<LessonEntity>, DbDataManager.Service.LessonDataService>();
//builder.Services.AddScoped<ILessonDataService, Shared.LessonDataService>();
builder.Services.AddScoped<ILessonService<LessonDTO>, Shared.LessonDataService>(); builder.Services.AddScoped<ILessonService<LessonDTO>, Shared.LessonDataService>();
//builder.Services.AddScoped<ILessonService<LessonDTO>, Shared.LessonDataService>();
builder.Services.AddDbContext<DbContext, UserDbContext>(); builder.Services.AddDbContext<DbContext, UserDbContext>();
builder.Services.AddDbContext<WebAPIDbContext>(options => options.UseInMemoryDatabase("appDb")); builder.Services.AddDbContext<WebAPIDbContext>(options => options.UseInMemoryDatabase("appDb"));

@ -1,6 +1,7 @@
using Entities; using Entities;
using Model.OrderCriteria; using Model.OrderCriteria;
using Shared; using Shared;
using static System.Runtime.InteropServices.JavaScript.JSType;
namespace API.Service; namespace API.Service;
@ -23,4 +24,25 @@ public class UserDataServiceApi(IUserService<UserEntity> userService) : IUserSer
public UserEntity CreateUser(string username, string password, string email, bool isAdmin) => public UserEntity CreateUser(string username, string password, string email, bool isAdmin) =>
userService.CreateUser(username, password, email, isAdmin); userService.CreateUser(username, password, email, isAdmin);
public Task<UserEntity?> AddItem(UserEntity? item)
{
throw new NotImplementedException();
}
public Task<bool> DeleteItem(int id)
{
throw new NotImplementedException();
}
public Task<UserEntity> UpdateItem<TDto>(int? id, TDto? newItem) where TDto : class
{
throw new NotImplementedException();
}
public async Task<IEnumerable<UserEntity>> 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();
}
} }

@ -18,6 +18,7 @@ namespace DbContextLib
public DbSet<SuccessEntity> Successes { get; set; } public DbSet<SuccessEntity> Successes { get; set; }
public DbSet<NotepadEntity> Notepads { get; set; } public DbSet<NotepadEntity> Notepads { get; set; }
public UserDbContext(DbContextOptions<UserDbContext> options) : base(options) { } public UserDbContext(DbContextOptions<UserDbContext> options) : base(options) { }
public UserDbContext() : base() { }
protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder) protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
{ {
if (!optionsBuilder.IsConfigured) if (!optionsBuilder.IsConfigured)

@ -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<T?> CreateItemAsync<T>(this DbContext context, T? item) where T : class
{
if (item == null || context.Set<T>().Contains(item))
{
return Task.FromResult<T?>(null);
}
context.Set<T>().Add(item);
context.SaveChangesAsync();
return Task.FromResult<T?>(item);
}
internal static Task<bool> DeleteItemAsync<T>(this DbContext context, int? id) where T : class
{
if (id == null)
{
return Task.FromResult(false);
}
var entity = context.Set<T>().Find(id);
if (entity == null)
{
return Task.FromResult(false);
}
context.Set<T>().Remove(entity);
context.SaveChanges();
return Task.FromResult(true);
}
internal static Task<T?> UpdateItemAsync<T, TDto>(this DbContext context, int? id, TDto dto)
where T : class
where TDto : class
{
var entity = context.Set<T>().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<T?>(entity);
}
internal static Task<IEnumerable<T?>> GetItemsWithFilter<T>(this DbContext context,
int page, int count, object orderCriteria, string? filter = null, object? valueProperty = null) where T : class
{
IQueryable<T> query = context.Set<T>();
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<Func<T, bool>>(equality, parameter);
var filteredEntity = context.Set<T>().FirstOrDefault(lambda);
if (filteredEntity != null)
{
return Task.FromResult<IEnumerable<T?>>(new List<T?> { filteredEntity });
}
}
return Task.FromResult<IEnumerable<T?>>(null);
}
var items = query.Skip((page - 1) * count).Take(count).ToList().Select(u => u);
return Task.FromResult<IEnumerable<T?>>(items);
}
}
}

@ -2,6 +2,7 @@
using Entities; using Entities;
using Microsoft.EntityFrameworkCore; using Microsoft.EntityFrameworkCore;
using Model.OrderCriteria; using Model.OrderCriteria;
using ModelToEntities;
using Shared; using Shared;
namespace DbDataManager.Service; namespace DbDataManager.Service;
@ -89,4 +90,29 @@ public class UserDataService : IUserService<UserEntity>
DbContext.SaveChangesAsync(); DbContext.SaveChangesAsync();
return newUserEntity; return newUserEntity;
} }
public Task<UserEntity?> AddItem(UserEntity? item)
{
throw new NotImplementedException();
}
public Task<bool> DeleteItem(int id)
{
throw new NotImplementedException();
}
public Task<UserEntity> UpdateItem<TDto>(int? id, TDto? newItem) where TDto : class
{
throw new NotImplementedException();
}
public async Task<IEnumerable<UserEntity>> GetItems(int page, int count, object orderCriteria, string? filter = null, object? valueFilter = null)
{
var user = (await DbContext.GetItemsWithFilter<UserEntity>(page, count, orderCriteria, filter, valueFilter));
if(user == null)
{
throw new ArgumentNullException("il n'y a pas de donnée");
}
return user;
}
} }

@ -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<TUser, Tlesson, TInquiry, TParagraphe, TSucesss> : IdataService<TUser, Tlesson, TInquiry, TParagraphe, TSucesss> where TUser : class
{
private UserDbContext _dbContext;
public DataService(UserDbContext userDbContext, IUserService<TUser> userService, ILessonService<Tlesson> lessonService, IInquiryService<TInquiry> inquiryService, IParagraphService<TParagraphe> paragrapheService, ISuccessService<TSucesss> 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<TUser> userService { get; }
public IInquiryService<TInquiry> inquiryService { get; }
public ILessonService<Tlesson> lessonService { get; }
public IParagraphService<TParagraphe> paragraphService { get; }
public ISuccessService<TSucesss> successDataService { get; }
}
}

@ -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<T> where T : class
{
public Task<T?> AddItem(T? item);
public Task<bool> DeleteItem(int id);
public Task<T> UpdateItem<TDto>(int? id, TDto? newItem) where TDto : class;
public Task<IEnumerable<T>> GetItems(int page, int count, object orderCriteria, string? filter = null, object? valueFilter = null);
}
}

@ -2,7 +2,7 @@
namespace Shared namespace Shared
{ {
public interface IUserService<TUser> public interface IUserService<TUser> : IGenericDataService<TUser> where TUser : class
{ {
public IEnumerable<TUser> GetUsers(int page, int number, UserOrderCriteria orderCriteria); public IEnumerable<TUser> GetUsers(int page, int number, UserOrderCriteria orderCriteria);
public TUser GetUserById(int id); public TUser GetUserById(int id);

@ -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<TUser, Tlesson, TInquiry, TParagraphe, TSucesss> where TUser : class
{
IUserService<TUser> userService { get; }
IInquiryService<TInquiry> inquiryService { get; }
ILessonService<Tlesson> lessonService { get; }
IParagraphService<TParagraphe> paragraphService { get; }
ISuccessService<TSucesss> successDataService { get; }
}
}

@ -117,5 +117,25 @@ namespace Shared
return newUserEntity; return newUserEntity;
} }
public Task<UserDTO?> AddItem(UserDTO? item)
{
throw new NotImplementedException();
}
public Task<bool> DeleteItem(int id)
{
throw new NotImplementedException();
}
public Task<UserDTO> UpdateItem<TDto>(int? id, TDto? newItem) where TDto : class
{
throw new NotImplementedException();
}
public Task<IEnumerable<UserDTO>> GetItems(int page, int count, object orderCriteria, string? filter = null, object? valueFilter = null)
{
throw new NotImplementedException();
}
} }
} }

@ -12,6 +12,7 @@ public class StubbedContext : UserDbContext
public StubbedContext(DbContextOptions<UserDbContext> options) : base(options) public StubbedContext(DbContextOptions<UserDbContext> options) : base(options)
{ {
} }
public StubbedContext() : base() { }
protected override void OnModelCreating(ModelBuilder modelBuilder) protected override void OnModelCreating(ModelBuilder modelBuilder)
{ {

Loading…
Cancel
Save