merge de la branch genericite sur crud/security

correctionLienWebServiceEF
Victor GABORIT 1 year ago
commit 91b2a5a082

@ -10,26 +10,25 @@ namespace API.Controllers
[ApiController] [ApiController]
public class InquiriesController : Controller public class InquiriesController : Controller
{ {
private IDataService _inquiryDataService; private IDataService<InquiryDTO> _dataService;
private readonly ILogger<UsersController> _logger; private readonly ILogger<UsersController> _logger;
public InquiriesController(IDataService<InquiryDTO> dataService)
public InquiriesController(IDataService inquiryDataService)
{ {
_inquiryDataService = inquiryDataService; _dataService = _dataService;
} }
[HttpGet("inquiries/{page}/{number}")] [HttpGet("inquiries/{page}/{number}")]
public IActionResult GetInquiries(int page, int number) public IActionResult GetInquiries(int page, int number)
{ {
var nbInquiry = _inquiryDataService.GetInquiries(page, number).Count(); var nbInquiry = _dataService.InquiryDataService.GetInquiries(page, number).Count();
if (nbInquiry == 0) if (nbInquiry == 0)
{ {
_logger.LogError("[ERREUR] Aucune enquête trouvée."); _logger.LogError("[ERREUR] Aucune enquête trouvée.");
return StatusCode(204); return StatusCode(204);
} }
_logger.LogInformation("[INFORMATION] {nb} Enquête(s) trouvée(s)", nbInquiry); _logger.LogInformation("[INFORMATION] {nb} Enquête(s) trouvée(s)", nbInquiry);
return Ok(_inquiryDataService.GetInquiries(page, number)); return Ok(_dataService.InquiryDataService.GetInquiries(page, number));
} }
[HttpGet("inquiry/id/{id}")] [HttpGet("inquiry/id/{id}")]
@ -38,7 +37,7 @@ namespace API.Controllers
try try
{ {
_logger.LogInformation("[INFORMATION] L'enquête avec l'id {id} a été trouvé.", id); _logger.LogInformation("[INFORMATION] L'enquête avec l'id {id} a été trouvé.", id);
return Ok(_inquiryDataService.GetInquiryById(id)); return Ok(_dataService.InquiryDataService.GetInquiryById(id));
} }
catch (ArgumentException) catch (ArgumentException)
{ {
@ -53,7 +52,7 @@ namespace API.Controllers
try try
{ {
_logger.LogInformation("[INFORMATION] L'enquête avec le titre {title} a été trouvé.", title); _logger.LogInformation("[INFORMATION] L'enquête avec le titre {title} a été trouvé.", title);
return Ok(_inquiryDataService.GetInquiryByTitle(title)); return Ok(_dataService.InquiryDataService.GetInquiryByTitle(title));
} }
catch (ArgumentException) catch (ArgumentException)
{ {
@ -65,11 +64,11 @@ namespace API.Controllers
[HttpDelete] [HttpDelete]
public IActionResult DeleteInquiry(int id) public IActionResult DeleteInquiry(int id)
{ {
var success = _inquiryDataService.DeleteInquiry(id); var success = _dataService.InquiryDataService.DeleteInquiry(id);
if (success) if (success)
{ {
_logger.LogInformation("[INFORMATION] L'enquête avec l'id {id} a été supprimé.", id); _logger.LogInformation("[INFORMATION] L'enquête avec l'id {id} a été supprimé.", id);
return Ok(_inquiryDataService.DeleteInquiry(id)); return Ok(_dataService.InquiryDataService.DeleteInquiry(id));
} }
else else
{ {
@ -87,7 +86,7 @@ namespace API.Controllers
return BadRequest(); return BadRequest();
} }
_logger.LogInformation("[INFORMATION] Une enquête a été créé : title - {title}, description - {description}, isUser - {isUser}, database - {database}, inquiryTable - {inquiryTable}", dto.Title, dto.Description, dto.IsUser, dto.Database, dto.InquiryTable); _logger.LogInformation("[INFORMATION] Une enquête a été créé : title - {title}, description - {description}, isUser - {isUser}, database - {database}, inquiryTable - {inquiryTable}", dto.Title, dto.Description, dto.IsUser, dto.Database, dto.InquiryTable);
return Created(nameof(GetInquiries), _inquiryDataService.CreateInquiry(dto.Title, dto.Description, dto.IsUser, dto.Database, dto.InquiryTable)); return Created(nameof(GetInquiries), _dataService.InquiryDataService.CreateInquiry(dto.Title, dto.Description, dto.IsUser, dto.Database, dto.InquiryTable));
} }
[HttpPut] [HttpPut]
@ -106,7 +105,7 @@ namespace API.Controllers
if (inquiryDTO != null) if (inquiryDTO != null)
{ {
_logger.LogInformation("[INFORMATION] La mise à jour de l'enquête avec l'id {id} a été effectuée", id); _logger.LogInformation("[INFORMATION] La mise à jour de l'enquête avec l'id {id} a été effectuée", id);
return Ok(_inquiryDataService.UpdateInquiry(id, inquiryDTO)); return Ok(_dataService.InquiryDataService.UpdateInquiry(id, inquiryDTO));
} }
_logger.LogError("[ERREUR] Aucune enquête trouvée avec l'id {id}.", id); _logger.LogError("[ERREUR] Aucune enquête trouvée avec l'id {id}.", id);
return NotFound(); return NotFound();

@ -10,26 +10,25 @@ namespace API.Controllers
[ApiController] [ApiController]
public class LessonsController : Controller public class LessonsController : Controller
{ {
private IDataService _lessonDataService; private IDataService<LessonDTO> _dataService;
private readonly ILogger<UsersController> _logger; private readonly ILogger<UsersController> _logger;
public LessonsController(IDataService<LessonDTO> dataService)
public LessonsController(IDataService lessonDataService)
{ {
_lessonDataService = lessonDataService; _dataService = dataService;
} }
[HttpGet("lessons/{page}/{number}")] [HttpGet("lessons/{page}/{number}")]
public IActionResult GetLessons(int page, int number) public IActionResult GetLessons(int page, int number)
{ {
var nbLesson = _lessonDataService.GetInquiries(page, number).Count(); var nbLesson = _dataService.LessonDataService.GetLessons(page, number).Count();
if (nbLesson == 0) if (nbLesson == 0)
{ {
_logger.LogError("[ERREUR] Aucune leçon trouvée."); _logger.LogError("[ERREUR] Aucune leçon trouvée.");
return StatusCode(204); return StatusCode(204);
} }
_logger.LogInformation("[INFORMATION] {nb} Leçon(s) trouvée(s)", nbLesson); _logger.LogInformation("[INFORMATION] {nb} Leçon(s) trouvée(s)", nbLesson);
return Ok(_lessonDataService.GetLessons(page, number)); return Ok(_dataService.LessonDataService.GetLessons(page, number));
} }
[HttpGet("lesson/id/{id}")] [HttpGet("lesson/id/{id}")]
@ -38,7 +37,7 @@ namespace API.Controllers
try try
{ {
_logger.LogInformation("[INFORMATION] La leçon avec l'id {id} a été trouvé.", id); _logger.LogInformation("[INFORMATION] La leçon avec l'id {id} a été trouvé.", id);
return Ok(_lessonDataService.GetLessonById(id)); return Ok(_dataService.LessonDataService.GetLessonById(id));
} }
catch (ArgumentException) catch (ArgumentException)
{ {
@ -53,7 +52,7 @@ namespace API.Controllers
try try
{ {
_logger.LogInformation("[INFORMATION] La leçon avec le titre {title} a été trouvé.", title); _logger.LogInformation("[INFORMATION] La leçon avec le titre {title} a été trouvé.", title);
return Ok(_lessonDataService.GetLessonByTitle(title)); return Ok(_dataService.LessonDataService.GetLessonByTitle(title));
} }
catch (ArgumentException) catch (ArgumentException)
{ {
@ -65,11 +64,11 @@ namespace API.Controllers
[HttpDelete] [HttpDelete]
public IActionResult DeleteLesson(int id) public IActionResult DeleteLesson(int id)
{ {
var success = _lessonDataService.DeleteLesson(id); var success = _dataService.LessonDataService.DeleteLesson(id);
if (success) if (success)
{ {
_logger.LogInformation("[INFORMATION] La leçon avec l'id {id} a été supprimé.", id); _logger.LogInformation("[INFORMATION] La leçon avec l'id {id} a été supprimé.", id);
return Ok(_lessonDataService.DeleteLesson(id)); return Ok(_dataService.LessonDataService.DeleteLesson(id));
} }
else else
{ {
@ -87,7 +86,7 @@ namespace API.Controllers
return BadRequest(); return BadRequest();
} }
_logger.LogInformation("[INFORMATION] Une leçon a été créé : title - {title}, lastPublisher - {publisher}, lastEdit - {lastEdit}", dto.Title, dto.LastPublisher, dto.LastEdit); _logger.LogInformation("[INFORMATION] Une leçon a été créé : title - {title}, lastPublisher - {publisher}, lastEdit - {lastEdit}", dto.Title, dto.LastPublisher, dto.LastEdit);
return Created(nameof(GetLessons), _lessonDataService.CreateLesson(dto.Title, dto.LastPublisher, dto.LastEdit)); return Created(nameof(GetLessons), _dataService.LessonDataService.CreateLesson(dto.Title, dto.LastPublisher, dto.LastEdit));
} }
[HttpPut] [HttpPut]
@ -106,7 +105,7 @@ namespace API.Controllers
if (lessonDTO != null) if (lessonDTO != null)
{ {
_logger.LogInformation("[INFORMATION] La mise à jour de la leçon avec l'id {id} a été effectuée", id); _logger.LogInformation("[INFORMATION] La mise à jour de la leçon avec l'id {id} a été effectuée", id);
return Ok(_lessonDataService.UpdateLesson(id, lessonDTO)); return Ok(_dataService.LessonDataService.UpdateLesson(id, lessonDTO));
} }
_logger.LogError("[ERREUR] Aucune leçon trouvée avec l'id {id}.", id); _logger.LogError("[ERREUR] Aucune leçon trouvée avec l'id {id}.", id);
return NotFound(); return NotFound();

@ -1,9 +1,12 @@
using DbContextLib; using DbContextLib;
using Entities.SQLudeoDB;
using Microsoft.AspNetCore.Authorization; using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Http; using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc; using Microsoft.AspNetCore.Mvc;
using Model;
using Model.Business; using Model.Business;
using Model.DTO; using Model.DTO;
using Model.Mappers;
using Services; using Services;
namespace API.Controllers namespace API.Controllers
@ -13,27 +16,26 @@ namespace API.Controllers
[ApiController] [ApiController]
public class UsersController : Controller public class UsersController : Controller
{ {
private IDataService _userDataService; private IDataService<UserDTO?> _dataService;
private readonly ILogger<UsersController> _logger; private readonly ILogger<UsersController> _logger;
public UsersController(IDataService<UserDTO?> dataService, ILogger<UsersController> logger)
public UsersController(IDataService userDataService, ILogger<UsersController> logger)
{ {
_userDataService = userDataService; _dataService = dataService;
_logger = logger; _logger = logger;
} }
[HttpGet("users/{page}/{number}")] [HttpGet("users/{page}/{number}")]
public async Task<IActionResult> GetUsers(int page, int number) public async Task<IActionResult> GetUsers(int page, int number)
{ {
var nbUser = (await _userDataService.GetUsers(page, number)).ToList().Count(); var nbUser = (await _dataService.UserService.GetUsers(page, number)).ToList().Count();
if(nbUser == 0) if(nbUser == 0)
{ {
_logger.LogError("[ERREUR] Aucun utilisateur trouvé."); _logger.LogError("[ERREUR] Aucun utilisateur trouvé.");
return StatusCode(204); return StatusCode(204);
} }
_logger.LogInformation("[INFORMATION] {nb} Utilisateur(s) trouvé(s)", nbUser); _logger.LogInformation("[INFORMATION] {nb} Utilisateur(s) trouvé(s)", nbUser);
return Ok(_userDataService.GetUsers(page, number)); return Ok(_dataService.UserService.GetItems<UserEntity>(page, number));
} }
[HttpGet("user/id/{id}")] [HttpGet("user/id/{id}")]
@ -42,7 +44,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(_userDataService.GetUserById(id)); return Ok(_dataService.UserService.GetItems<UserEntity>(1, 1, UserProperty.Id.ToString(),id));
} catch (ArgumentException) } catch (ArgumentException)
{ {
_logger.LogError("[ERREUR] Aucun utilisateur trouvé avec l'id {id}.", id); _logger.LogError("[ERREUR] Aucun utilisateur trouvé avec l'id {id}.", id);
@ -56,7 +58,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(_userDataService.GetUserByUsername(username)); return Ok(_dataService.UserService.GetItems<UserEntity>(1, 1,UserProperty.Username.ToString(), username));
}catch (ArgumentException) }catch (ArgumentException)
{ {
_logger.LogError("[ERREUR] Aucun utilisateur trouvé avec l'username {username}.", username); _logger.LogError("[ERREUR] Aucun utilisateur trouvé avec l'username {username}.", username);
@ -68,11 +70,11 @@ namespace API.Controllers
[HttpDelete] [HttpDelete]
public async Task<IActionResult> DeleteUser(int id) public async Task<IActionResult> DeleteUser(int id)
{ {
var success = await _userDataService.DeleteUser(id); var success = await _dataService.UserService.DeleteItem<UserEntity>(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(_userDataService.DeleteUser(id)); return Ok(_dataService.UserService.DeleteUser(id));
} else } else
{ {
_logger.LogError("[ERREUR] Aucun utilisateur trouvé avec l'id {id}.", id); _logger.LogError("[ERREUR] Aucun utilisateur trouvé avec l'id {id}.", id);
@ -88,9 +90,9 @@ namespace API.Controllers
{ {
return BadRequest(); return BadRequest();
} }
// return Ok(_userDataService.CreateUser(username, password, email, isAdmin));
_logger.LogInformation("[INFORMATION] Un utilisateur a été créé : username - {username}, password - {password}, email - {email}, isAdmin - {isAdmin}", dto.Username, dto.Password, dto.Email, dto.IsAdmin); _logger.LogInformation("[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), _userDataService.CreateUser(dto.Username, dto.Password, dto.Email, dto.IsAdmin)); return Created(nameof(GetUsers), _dataService.UserService.AddItem(dto.FromDTOToModel().FromModelToEntity()));
} }
[HttpPut] [HttpPut]
@ -109,7 +111,7 @@ namespace API.Controllers
if(userDTO != null) if(userDTO != null)
{ {
_logger.LogInformation("[INFORMATION] La mise à jour de l'utilisateur avec l'id {id} a été effectuée", id); _logger.LogInformation("[INFORMATION] La mise à jour de l'utilisateur avec l'id {id} a été effectuée", id);
return Ok(_userDataService.UpdateUser(id, userDTO)); return Ok(_dataService.UserService.UpdateItem<UserEntity, UserDTO>(id, userDTO));
} }
_logger.LogError("[ERREUR] Aucun utilisateur trouvé avec l'id {id}.", id); _logger.LogError("[ERREUR] Aucun utilisateur trouvé avec l'id {id}.", id);
return NotFound(); return NotFound();

@ -3,9 +3,12 @@ using DbContextLib;
using Microsoft.AspNetCore.Identity; using Microsoft.AspNetCore.Identity;
using Microsoft.EntityFrameworkCore; using Microsoft.EntityFrameworkCore;
using Microsoft.OpenApi.Models; using Microsoft.OpenApi.Models;
using Model.DTO;
using Model.Business;
using ModelToEntity; using ModelToEntity;
using Services; using Services;
using System.Data.Common; using System.Data.Common;
using Microsoft.Extensions.Options;
var builder = WebApplication.CreateBuilder(args); var builder = WebApplication.CreateBuilder(args);
@ -15,8 +18,9 @@ builder.Services.AddControllers();
// Learn more about configuring Swagger/OpenAPI at https://aka.ms/aspnetcore/swashbuckle // Learn more about configuring Swagger/OpenAPI at https://aka.ms/aspnetcore/swashbuckle
builder.Services.AddEndpointsApiExplorer(); builder.Services.AddEndpointsApiExplorer();
builder.Services.AddSwaggerGen(); builder.Services.AddSwaggerGen();
builder.Services.AddScoped<IDataService, UserDataService>(); builder.Services.AddScoped<IUserDataService<UserDTO>, UserDataService>();
builder.Services.AddScoped<IDataServiceEF, DbDataManager>(); builder.Services.AddScoped<IDataService<UserDTO?>, DataService>();
builder.Services.AddScoped<IUserDataService<User>, DbDataManager>();
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"));
builder.Services.AddIdentityApiEndpoints<IdentityUser>().AddEntityFrameworkStores<WebAPIDbContext>(); builder.Services.AddIdentityApiEndpoints<IdentityUser>().AddEntityFrameworkStores<WebAPIDbContext>();

@ -17,7 +17,9 @@ Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "DbContextLib", "DbContextLi
EndProject EndProject
Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "Services", "Services\Services.csproj", "{9BD3DCBA-AFD8-47FA-B07C-613B53E63968}" Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "Services", "Services\Services.csproj", "{9BD3DCBA-AFD8-47FA-B07C-613B53E63968}"
EndProject EndProject
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "ModelToEntity", "ModelToEntity\ModelToEntity.csproj", "{8F53CC62-94B3-4F9D-ABF1-F7307A6F27C0}" Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "ModelToEntity", "ModelToEntity\ModelToEntity.csproj", "{8F53CC62-94B3-4F9D-ABF1-F7307A6F27C0}"
EndProject
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Shared", "Shared\Shared.csproj", "{B28FD539-6FE4-4B13-9C1F-D88F4771CC69}"
EndProject EndProject
Global Global
GlobalSection(SolutionConfigurationPlatforms) = preSolution GlobalSection(SolutionConfigurationPlatforms) = preSolution
@ -57,6 +59,10 @@ Global
{8F53CC62-94B3-4F9D-ABF1-F7307A6F27C0}.Debug|Any CPU.Build.0 = Debug|Any CPU {8F53CC62-94B3-4F9D-ABF1-F7307A6F27C0}.Debug|Any CPU.Build.0 = Debug|Any CPU
{8F53CC62-94B3-4F9D-ABF1-F7307A6F27C0}.Release|Any CPU.ActiveCfg = Release|Any CPU {8F53CC62-94B3-4F9D-ABF1-F7307A6F27C0}.Release|Any CPU.ActiveCfg = Release|Any CPU
{8F53CC62-94B3-4F9D-ABF1-F7307A6F27C0}.Release|Any CPU.Build.0 = Release|Any CPU {8F53CC62-94B3-4F9D-ABF1-F7307A6F27C0}.Release|Any CPU.Build.0 = Release|Any CPU
{B28FD539-6FE4-4B13-9C1F-D88F4771CC69}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{B28FD539-6FE4-4B13-9C1F-D88F4771CC69}.Debug|Any CPU.Build.0 = Debug|Any CPU
{B28FD539-6FE4-4B13-9C1F-D88F4771CC69}.Release|Any CPU.ActiveCfg = Release|Any CPU
{B28FD539-6FE4-4B13-9C1F-D88F4771CC69}.Release|Any CPU.Build.0 = Release|Any CPU
EndGlobalSection EndGlobalSection
GlobalSection(SolutionProperties) = preSolution GlobalSection(SolutionProperties) = preSolution
HideSolutionNode = FALSE HideSolutionNode = FALSE

@ -25,7 +25,7 @@ namespace DbContextLib
{ {
if (!optionsBuilder.IsConfigured) if (!optionsBuilder.IsConfigured)
{ {
optionsBuilder.UseNpgsql("Host=localhost;Database=SQLuedo;Username=admin;Password=motdepasse"); optionsBuilder.UseNpgsql("Host=localhost;Database=SQLuedo;Username=admin;Password=motdepasse").EnableSensitiveDataLogging();
} }
base.OnConfiguring(optionsBuilder); base.OnConfiguring(optionsBuilder);
} }

@ -0,0 +1,18 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Model
{
public enum UserProperty
{
Id,
Username,
Password,
Email,
IsAdmin
}
}

@ -6,10 +6,13 @@ using DbContextLib;
using Model.Business; using Model.Business;
using Model; using Model;
using Model.Mappers; using Model.Mappers;
using System;
using Microsoft.AspNetCore.Identity;
using System.Runtime.InteropServices.ObjectiveC;
namespace ModelToEntity namespace ModelToEntity
{ {
public class DbDataManager : IDataServiceEF public class DbDataManager : IUserDataService<User?>
{ {
public async Task<User> GetUserById(int id) public async Task<User> GetUserById(int id)
{ {
@ -93,7 +96,7 @@ namespace ModelToEntity
IsAdmin = isAdmin IsAdmin = isAdmin
}; };
context.Users.Add(newUserEntity.FromDTOToModel().FromModelToEntity()); context.Users.Add(newUserEntity.FromDTOToModel().FromModelToEntity());
context.SaveChangesAsync(); context.SaveChanges();
return await Task.FromResult(newUserEntity.FromDTOToModel()); return await Task.FromResult(newUserEntity.FromDTOToModel());
} }
@ -157,6 +160,39 @@ namespace ModelToEntity
{ {
throw new NotImplementedException(); throw new NotImplementedException();
} }
public async Task<T?> AddItem<T>(T? item) where T : class
{
using (var context = new UserDbContext())
{
return await context.CreateItemAsync(item);
}
}
public async Task<bool> DeleteItem<T>(int id) where T : class
{
using(var context = new UserDbContext())
{
return await context.DeleteItemAsync<T>(id);
}
}
public async Task<T?> UpdateItem<T, TDto>(int? id, TDto? newItem)
where T : class
where TDto : class
{
using(var context = new UserDbContext())
{
return await context.UpdateItemAsync<T, TDto>(id, newItem);
}
} }
public async Task<IEnumerable<T?>> GetItems<T>(int index, int count, string? orderingPropertyName = null, object? valueProperty = null) where T : class
{
using (var context = new UserDbContext())
{
return await context.GetItemsWithFilter<T>(index, count, orderingPropertyName, valueProperty);
}
}
}
} }

@ -7,10 +7,98 @@ using System.Threading.Tasks;
using Entities; using Entities;
using Entities.SQLudeoDB; using Entities.SQLudeoDB;
using Model.Business; using Model.Business;
using System.Diagnostics;
using DbContextLib;
using Microsoft.EntityFrameworkCore;
using System.Linq.Expressions;
using Microsoft.EntityFrameworkCore.Metadata.Internal;
namespace ModelToEntity namespace ModelToEntity
{ {
static class Extension internal static class Extension
{ {
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?>(default(T));
}
context.Set<T>().Add(item);
context.SaveChangesAsync();
return Task.FromResult<T?>(item);
}
internal static async Task<bool> DeleteItemAsync<T>(this DbContext context, int? id) where T : class
{
if (id == null)
{
return false;
}
var entity = await context.Set<T>().FindAsync(id);
if (entity == null)
{
return false;
}
context.Set<T>().Remove(entity);
await context.SaveChangesAsync();
return 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 propertiesToUpdate = typeof(TDto).GetProperties()
.Where(p => p.CanRead && p.CanWrite);
foreach (var property in propertiesToUpdate)
{
var value = property.GetValue(dto);
typeof(T).GetProperty(property.Name)?.SetValue(entity, value);
}
context.Entry(entity).State = EntityState.Modified;
context.SaveChanges();
return Task.FromResult<T?>(entity);
}
internal static Task<IEnumerable<T?>> GetItemsWithFilter<T>(this DbContext context,
int index, int count, string? orderingPropertyName = null, object valueProperty = null) where T : class
{
IQueryable<T> query = context.Set<T>();
if (valueProperty != null && !string.IsNullOrEmpty(orderingPropertyName))
{
var prop = typeof(T).GetProperty(orderingPropertyName);
if (prop != null)
{
var idProp = typeof(T).GetProperty(orderingPropertyName);
if (idProp != null)
{
var parameter = Expression.Parameter(typeof(T), "entity");
var propertyAccess = Expression.Property(parameter, prop);
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 });
}
}
}
}
var items = query.Skip(index).Take(count).ToList();
return Task.FromResult<IEnumerable<T?>>(items);
}
} }
} }

@ -23,6 +23,7 @@
<ProjectReference Include="..\DbContextLib\DbContextLib.csproj" /> <ProjectReference Include="..\DbContextLib\DbContextLib.csproj" />
<ProjectReference Include="..\EntityFramework\Entities.csproj" /> <ProjectReference Include="..\EntityFramework\Entities.csproj" />
<ProjectReference Include="..\Model\Model.csproj" /> <ProjectReference Include="..\Model\Model.csproj" />
<ProjectReference Include="..\Shared\Shared.csproj" />
</ItemGroup> </ItemGroup>
</Project> </Project>

@ -0,0 +1,24 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Model.Business;
using Model.DTO;
using Shared;
namespace Services
{
public class DataService : IDataService<UserDTO>
{
public IUserDataService<UserDTO?> UserService { get; }
public DataService(IUserDataService<UserDTO?> userDataService)
{
UserService = userDataService;
}
public IInquiryDataService InquiryDataService { get; }
public ILessonDataService LessonDataService { get; }
}
}

@ -0,0 +1,12 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Services
{
public class LessonDataService
{
}
}

@ -24,6 +24,7 @@
<ProjectReference Include="..\EntityFramework\Entities.csproj" /> <ProjectReference Include="..\EntityFramework\Entities.csproj" />
<ProjectReference Include="..\ModelToEntity\ModelToEntity.csproj" /> <ProjectReference Include="..\ModelToEntity\ModelToEntity.csproj" />
<ProjectReference Include="..\Model\Model.csproj" /> <ProjectReference Include="..\Model\Model.csproj" />
<ProjectReference Include="..\Shared\Shared.csproj" />
</ItemGroup> </ItemGroup>
</Project> </Project>

@ -1,4 +1,4 @@
using DbContextLib; using DbContextLib;
using Model.DTO; using Model.DTO;
using System; using System;
using System.Collections.Generic; using System.Collections.Generic;
@ -13,28 +13,27 @@ using ModelToEntity;
namespace Services namespace Services
{ {
public class UserDataService : IDataService public class UserDataService : IUserDataService<UserDTO?>
{ {
private UserDbContext DbContext { get; set; } private readonly IUserDataService<User> dataServiceEF;
private readonly IDataServiceEF dataServiceEF; public UserDataService(IUserDataService<User> dataServiceEF)
public UserDataService(IDataServiceEF dataServiceEF)
{ {
this.dataServiceEF = dataServiceEF; this.dataServiceEF = dataServiceEF;
} }
public async Task<UserDTO> GetUserById(int id) public async Task<UserDTO?> GetUserById(int id)
{ {
var user = await dataServiceEF.GetUserById(id); var user = await dataServiceEF.GetUserById(id);
return user.FromModelToDTO(); return user.FromModelToDTO();
} }
public async Task<UserDTO> GetUserByUsername(string username) public async Task<UserDTO?> GetUserByUsername(string username)
{ {
var user = await dataServiceEF.GetUserByUsername(username); var user = await dataServiceEF.GetUserByUsername(username);
return user.FromModelToDTO(); return user.FromModelToDTO();
} }
public async Task<IEnumerable<UserDTO>> GetUsers(int page, int number) public async Task<IEnumerable<UserDTO?>> GetUsers(int page, int number)
{ {
var users = await dataServiceEF.GetUsers(page, number); var users = await dataServiceEF.GetUsers(page, number);
return users.Select(u => u.FromModelToDTO()); return users.Select(u => u.FromModelToDTO());
@ -46,74 +45,39 @@ namespace Services
return respons; return respons;
} }
public async Task<UserDTO> UpdateUser(int id, UserDTO user) public async Task<UserDTO?> UpdateUser(int id, UserDTO user)
{ {
var updatingUser = await dataServiceEF.UpdateUser(id, user); var updatingUser = await dataServiceEF.UpdateUser(id, user);
return updatingUser.FromModelToDTO(); return updatingUser.FromModelToDTO();
} }
public async Task<UserDTO> CreateUser(string username, string password, string email, bool isAdmin) public async Task<UserDTO?> CreateUser(string username, string password, string email, bool isAdmin)
{ {
var newUserEntity = await dataServiceEF.CreateUser(username, password, email, isAdmin); var newUserEntity = await dataServiceEF.CreateUser(username, password, email, isAdmin);
return newUserEntity.FromModelToDTO(); return newUserEntity.FromModelToDTO();
} }
public IEnumerable<InquiryDTO> GetInquiries(int page, int number) public async Task<T?> AddItem<T>(T? item) where T : class
{ {
throw new NotImplementedException(); var newItem = dataServiceEF.AddItem(item);
} return await newItem;
public InquiryDTO GetInquiryById(int id)
{
throw new NotImplementedException();
}
public InquiryDTO GetInquiryByTitle(string title)
{
throw new NotImplementedException();
}
public UserDTO CreateInquiry(string title, string description, bool isUser, InquiryTableEntity database, SolutionEntity inquiryTable)
{
throw new NotImplementedException();
} }
public bool DeleteInquiry(int id) public Task<bool> DeleteItem<T>(int id) where T : class
{ {
throw new NotImplementedException(); var succes = dataServiceEF.DeleteItem<T>(id);
return succes;
} }
public InquiryDTO UpdateInquiry(int id, InquiryDTO inquiry) public Task<T> UpdateItem<T, TDto>(int? id, TDto? newItem) where T : class where TDto : class
{ {
throw new NotImplementedException(); var item = dataServiceEF.UpdateItem<T, TDto>(id, newItem);
} return item;
public IEnumerable<InquiryDTO> GetLessons(int page, int number)
{
throw new NotImplementedException();
} }
public InquiryDTO GetLessonById(int id) public Task<IEnumerable<T?>> GetItems<T>(int index, int count, string? orderingPropertyName = null, object? valueProperty = null) where T : class
{ {
throw new NotImplementedException(); var items = dataServiceEF.GetItems<T>(index, count, orderingPropertyName, valueProperty);
} return items;
public InquiryDTO GetLessonByTitle(string title)
{
throw new NotImplementedException();
}
public bool DeleteLesson(int id)
{
throw new NotImplementedException();
}
public InquiryDTO UpdateLesson(int id, LessonDTO lesson)
{
throw new NotImplementedException();
}
public UserDTO CreateLesson(string title, string lastPublisher, DateOnly lastEdit)
{
throw new NotImplementedException();
} }
public Task<IEnumerable<ParagraphDTO>> GetParagraphs(int page, int number) public Task<IEnumerable<ParagraphDTO>> GetParagraphs(int page, int number)

@ -0,0 +1,13 @@
using Entities.SQLudeoDB;
using Model.Business;
using Model.DTO;
namespace Services
{
public interface IDataService<T> where T : class
{
IUserDataService<T?> UserService { get; }
IInquiryDataService InquiryDataService { get; }
ILessonDataService LessonDataService { get; }
}
}

@ -0,0 +1,10 @@
namespace Shared
{
public interface IGenericService<T> where T : class
{
public Task<T?> AddItem<T>(T? item) where T : class;
public Task<bool> DeleteItem<T>(int id) where T : class;
public Task<T> UpdateItem<T, TDto>(int? id, TDto? newItem) where T : class where TDto : class;
public Task<IEnumerable<T>> GetItems<T>(int index, int count, string? orderingPropertyName = null, object? valueProperty = null) where T : class;
}
}

@ -0,0 +1,21 @@
using Entities.SQLudeoDB;
using Model.DTO;
using Shared;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Services
{
public interface IInquiryDataService : IGenericService<InquiryDTO>
{
public IEnumerable<InquiryDTO> GetInquiries(int page, int number);
public InquiryDTO GetInquiryById(int id);
public InquiryDTO GetInquiryByTitle(string title);
public bool DeleteInquiry(int id);
public InquiryDTO UpdateInquiry(int id, InquiryDTO inquiry);
public UserDTO CreateInquiry(string title, string description, bool isUser, InquiryTableEntity database, SolutionEntity inquiryTable);
}
}

@ -0,0 +1,20 @@
using Model.DTO;
using Shared;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Services
{
public interface ILessonDataService : IGenericService<LessonDTO>
{
public IEnumerable<InquiryDTO> GetLessons(int page, int number);
public InquiryDTO GetLessonById(int id);
public InquiryDTO GetLessonByTitle(string title);
public bool DeleteLesson(int id);
public InquiryDTO UpdateLesson(int id, LessonDTO lesson);
public UserDTO CreateLesson(string title, string lastPublisher, DateOnly lastEdit);
}
}

@ -0,0 +1,23 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Services;
using Model.DTO;
using Shared;
using Model.Business;
namespace Services
{
public interface IUserDataService<T> : IGenericService<T?> where T : class
{
public Task<IEnumerable<T?>> GetUsers(int page, int number);
public Task<T?> GetUserById(int id);
public Task<T?> GetUserByUsername(string username);
public Task<bool> DeleteUser(int id);
public Task<T?> UpdateUser(int id, UserDTO user);
public Task<T?> CreateUser(string username, string password, string email, bool isAdmin);
}
}

@ -0,0 +1,13 @@
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<TargetFramework>net8.0</TargetFramework>
<ImplicitUsings>enable</ImplicitUsings>
<Nullable>enable</Nullable>
</PropertyGroup>
<ItemGroup>
<ProjectReference Include="..\Model\Model.csproj" />
</ItemGroup>
</Project>
Loading…
Cancel
Save