Compare commits

...

10 Commits

Author SHA1 Message Date
Victor GABORIT e476fd6c82 ajout d'un option dans UserDbContext pour avoir plus de détaille sur les logs. Ajout de GetItems
1 year ago
Victor GABORIT a307f68fc3 correction du bug sur le renvoie d'un object non sérializable par la méthode UpdatItem qui provoquait une erreur 500 coté API
1 year ago
Victor GABORIT de66affddc ajout d'UpdateItem générique, la mise à jour se fait en base de donnée mais PUT renvoie un code de retour 500 car elle ne renvoie pas un object sérializable : à corriger
1 year ago
Victor GABORIT 7c2cc6f5ce ajout d'un méthode d'extension générique pour la suppression d'un item
1 year ago
Victor GABORIT 5f68add0fe ajout d'un methode d'extension générique pour ajouter Item
1 year ago
Victor GABORIT df34ec238a correction de bug quand on apelle les interface 🐛
1 year ago
Victor GABORIT d3154b9552 résolution d'érreur sur l'implémentation des différentes intefaces
1 year ago
Victor GABORIT 08e08687da ajout début de la génicité mais il y a des erreurs, pas encore corigées !!!!
1 year ago
Victor GABORIT 5f9899276a mise à jour de la structure avec ajout de service pour la partie EntityFramework et ajout de la class DbDataManager pour communiquer avec la BDD, changement des methode dans l'API qui sont maintenant en asynchrone. Changement du DbContextLib poureffectuer les migrations : ajout d'un constructeur et indication clé étrangère pour inquiryEntity
1 year ago
Erwan MENAGER 9bd3088aa2 Début implémentation CRUD dans des nouveaux controlleurs pour Inquiry et Lesson + Mappers + DTO et certains petits détails...
1 year ago

@ -24,6 +24,7 @@
</ItemGroup> </ItemGroup>
<ItemGroup> <ItemGroup>
<ProjectReference Include="..\ModelToEntity\ModelToEntity.csproj" />
<ProjectReference Include="..\Services\Services.csproj" /> <ProjectReference Include="..\Services\Services.csproj" />
</ItemGroup> </ItemGroup>

@ -1,65 +0,0 @@
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using Model.DTO;
using Services;
namespace API.Controllers
{
[Route("api/[controller]")]
[Authorize]
[ApiController]
public class InquiriesController : Controller
{
private IDataService _inquiryDataService;
private readonly ILogger<UserController> _logger;
public InquiriesController(IDataService inquiryDataService)
{
_inquiryDataService = inquiryDataService;
}
[HttpGet("inquiries/{page}/{number}")]
public IActionResult GetInquiries(int page, int number)
{
var nbInquiry = _inquiryDataService.GetInquiries(page, number).Count();
if (nbInquiry == 0)
{
_logger.LogError("[ERREUR] Aucune enquête trouvé.");
return StatusCode(204);
}
_logger.LogInformation("[INFORMATION] {nb} Enquête(s) trouvée(s)", nbInquiry);
return Ok(_inquiryDataService.GetInquiries(page, number));
}
[HttpGet("inquiry/id/{id}")]
public IActionResult GetInquiryById(int id)
{
try
{
_logger.LogInformation("[INFORMATION] Enquête avec l'id {id} a été trouvé.", id);
return Ok(_inquiryDataService.GetInquiryById(id));
}
catch (ArgumentException)
{
_logger.LogError("[ERREUR] Aucune enquête trouvée avec l'id {id}.", id);
return NotFound();
}
}
[HttpGet("inquiry/title/{title}")]
public IActionResult GetInquiryByTitle(string title)
{
try
{
_logger.LogInformation("[INFORMATION] Enquête avec le titre {title} a été trouvé.", title);
return Ok(_inquiryDataService.GetInquiryByTitle(title));
}
catch (ArgumentException)
{
_logger.LogError("[ERREUR] Aucune enquête trouvée avec le titre {title}.", title);
return NotFound();
}
}
}
}

@ -0,0 +1,115 @@
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using Model.DTO;
using Services;
namespace API.Controllers
{
[Route("api/[controller]")]
[Authorize]
[ApiController]
public class InquiryController : Controller
{
private IDataService<InquiryDTO> _dataService;
private readonly ILogger<UserController> _logger;
public InquiryController(IDataService<InquiryDTO> dataService)
{
_dataService = _dataService;
}
[HttpGet("inquiries/{page}/{number}")]
public IActionResult GetInquiries(int page, int number)
{
var nbInquiry = _dataService.InquiryDataService.GetInquiries(page, number).Count();
if (nbInquiry == 0)
{
_logger.LogError("[ERREUR] Aucune enquête trouvée.");
return StatusCode(204);
}
_logger.LogInformation("[INFORMATION] {nb} Enquête(s) trouvée(s)", nbInquiry);
return Ok(_dataService.InquiryDataService.GetInquiries(page, number));
}
[HttpGet("inquiry/id/{id}")]
public IActionResult GetInquiryById(int id)
{
try
{
_logger.LogInformation("[INFORMATION] L'enquête avec l'id {id} a été trouvé.", id);
return Ok(_dataService.InquiryDataService.GetInquiryById(id));
}
catch (ArgumentException)
{
_logger.LogError("[ERREUR] Aucune enquête trouvée avec l'id {id}.", id);
return NotFound();
}
}
[HttpGet("inquiry/title/{title}")]
public IActionResult GetInquiryByTitle(string title)
{
try
{
_logger.LogInformation("[INFORMATION] L'enquête avec le titre {title} a été trouvé.", title);
return Ok(_dataService.InquiryDataService.GetInquiryByTitle(title));
}
catch (ArgumentException)
{
_logger.LogError("[ERREUR] Aucune enquête trouvée avec le titre {title}.", title);
return NotFound();
}
}
[HttpDelete]
public IActionResult DeleteInquiry(int id)
{
var success = _dataService.InquiryDataService.DeleteInquiry(id);
if (success)
{
_logger.LogInformation("[INFORMATION] L'enquête avec l'id {id} a été supprimé.", id);
return Ok(_dataService.InquiryDataService.DeleteInquiry(id));
}
else
{
_logger.LogError("[ERREUR] Aucune enquête trouvée avec l'id {id}.", id);
return NotFound();
}
}
[HttpPost]
public IActionResult CreateInquiry([FromBody] InquiryDTO dto)
{
if (dto.Title == null || dto.Description == null || dto.Database == null || dto.InquiryTable == null)
{
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);
return Created(nameof(GetInquiries), _dataService.InquiryDataService.CreateInquiry(dto.Title, dto.Description, dto.IsUser, dto.Database, dto.InquiryTable));
}
[HttpPut]
public IActionResult UpdateInquiry(int id, [FromBody] InquiryDTO inquiryDTO)
{
if (id != inquiryDTO.Id)
{
_logger.LogError("[ERREUR] Problème ID - La mise à jour de l'enquête avec l'id {id} a échouée.", id);
return BadRequest();
}
if (!ModelState.IsValid)
{
_logger.LogError("[ERREUR] Problème controlleur - La mise à jour de l'enquête avec l'id {id} a échouée.", id);
return BadRequest();
}
if (inquiryDTO != null)
{
_logger.LogInformation("[INFORMATION] La mise à jour de l'enquête avec l'id {id} a été effectuée", id);
return Ok(_dataService.InquiryDataService.UpdateInquiry(id, inquiryDTO));
}
_logger.LogError("[ERREUR] Aucune enquête trouvée avec l'id {id}.", id);
return NotFound();
}
}
}

@ -0,0 +1,115 @@
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using Model.DTO;
using Services;
namespace API.Controllers
{
[Route("api/[controller]")]
[Authorize]
[ApiController]
public class LessonController : Controller
{
private IDataService<LessonDTO> _dataService;
private readonly ILogger<UserController> _logger;
public LessonController(IDataService<LessonDTO> dataService)
{
_dataService = dataService;
}
[HttpGet("lessons/{page}/{number}")]
public IActionResult GetLessons(int page, int number)
{
var nbLesson = _dataService.LessonDataService.GetLessons(page, number).Count();
if (nbLesson == 0)
{
_logger.LogError("[ERREUR] Aucune leçon trouvée.");
return StatusCode(204);
}
_logger.LogInformation("[INFORMATION] {nb} Leçon(s) trouvée(s)", nbLesson);
return Ok(_dataService.LessonDataService.GetLessons(page, number));
}
[HttpGet("lesson/id/{id}")]
public IActionResult GetLessonById(int id)
{
try
{
_logger.LogInformation("[INFORMATION] La leçon avec l'id {id} a été trouvé.", id);
return Ok(_dataService.LessonDataService.GetLessonById(id));
}
catch (ArgumentException)
{
_logger.LogError("[ERREUR] Aucune leçon trouvée avec l'id {id}.", id);
return NotFound();
}
}
[HttpGet("lesson/title/{title}")]
public IActionResult GetLessonByTitle(string title)
{
try
{
_logger.LogInformation("[INFORMATION] La leçon avec le titre {title} a été trouvé.", title);
return Ok(_dataService.LessonDataService.GetLessonByTitle(title));
}
catch (ArgumentException)
{
_logger.LogError("[ERREUR] Aucune leçon trouvée avec le titre {title}.", title);
return NotFound();
}
}
[HttpDelete]
public IActionResult DeleteLesson(int id)
{
var success = _dataService.LessonDataService.DeleteLesson(id);
if (success)
{
_logger.LogInformation("[INFORMATION] La leçon avec l'id {id} a été supprimé.", id);
return Ok(_dataService.LessonDataService.DeleteLesson(id));
}
else
{
_logger.LogError("[ERREUR] Aucune leçon trouvée avec l'id {id}.", id);
return NotFound();
}
}
[HttpPost]
public IActionResult CreateLesson([FromBody] LessonDTO dto)
{
if (dto.Title == null || dto.LastPublisher == null)
{
return BadRequest();
}
_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), _dataService.LessonDataService.CreateLesson(dto.Title, dto.LastPublisher, dto.LastEdit));
}
[HttpPut]
public IActionResult UpdateLesson(int id, [FromBody] LessonDTO lessonDTO)
{
if (id != lessonDTO.Id)
{
_logger.LogError("[ERREUR] Problème ID - La mise à jour de la leçon avec l'id {id} a échouée.", id);
return BadRequest();
}
if (!ModelState.IsValid)
{
_logger.LogError("[ERREUR] Problème controlleur - La mise à jour de la leçon avec l'id {id} a échouée.", id);
return BadRequest();
}
if (lessonDTO != null)
{
_logger.LogInformation("[INFORMATION] La mise à jour de la leçon avec l'id {id} a été effectuée", id);
return Ok(_dataService.LessonDataService.UpdateLesson(id, lessonDTO));
}
_logger.LogError("[ERREUR] Aucune leçon trouvée avec l'id {id}.", id);
return NotFound();
}
}
}

@ -1,118 +1,121 @@
using DbContextLib; using DbContextLib;
using Microsoft.AspNetCore.Authorization; using Entities.SQLudeoDB;
using Microsoft.AspNetCore.Http; using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc; using Microsoft.AspNetCore.Http;
using Model.Business; using Microsoft.AspNetCore.Mvc;
using Model.DTO; using Model;
using Services; using Model.Business;
using Model.DTO;
namespace API.Controllers using Model.Mappers;
{ using Services;
[Route("api/[controller]")]
[Authorize]
[ApiController]
public class UserController : Controller
{
private IDataService _userDataService;
private readonly ILogger<UserController> _logger; namespace API.Controllers
{
public UserController(IDataService userDataService, ILogger<UserController> logger) [Route("api/[controller]")]
{ [Authorize]
_userDataService = userDataService; [ApiController]
_logger = logger; public class UserController : Controller
} {
private IDataService<UserDTO?> _dataService;
[HttpGet("users/{page}/{number}")]
public IActionResult GetUsers(int page, int number) private readonly ILogger<UserController> _logger;
{
var nbUser = _userDataService.GetUsers(page, number).Count(); public UserController(IDataService<UserDTO?> dataService, ILogger<UserController> logger)
if(nbUser == 0) {
{ _dataService = dataService;
_logger.LogError("[ERREUR] Aucun utilisateur trouvé."); _logger = logger;
return StatusCode(204); }
}
_logger.LogInformation("[INFORMATION] {nb} Utilisateur(s) trouvé(s)", nbUser); [HttpGet("users/{page}/{number}")]
return Ok(_userDataService.GetUsers(page, number)); public async Task<IActionResult> GetUsers(int page, int number)
} {
var nbUser = (await _dataService.UserService.GetUsers(page, number)).ToList().Count();
[HttpGet("user/id/{id}")] if(nbUser == 0)
public IActionResult GetUserById(int id) {
{ _logger.LogError("[ERREUR] Aucun utilisateur trouvé.");
try return StatusCode(204);
{ }
_logger.LogInformation("[INFORMATION] Utilisateur avec l'id {id} a été trouvé.", id); _logger.LogInformation("[INFORMATION] {nb} Utilisateur(s) trouvé(s)", nbUser);
return Ok(_userDataService.GetUserById(id)); return Ok(_dataService.UserService.GetItems<UserEntity>(page, number));
} catch (ArgumentException) }
{
_logger.LogError("[ERREUR] Aucun utilisateur trouvé avec l'id {id}.", id); [HttpGet("user/id/{id}")]
return NotFound(); public async Task<IActionResult> GetUserById(int id)
} {
} try
{
[HttpGet("user/username/{username}")] _logger.LogInformation("[INFORMATION] Utilisateur avec l'id {id} a été trouvé.", id);
public IActionResult GetUserByUsername(string username) return Ok(_dataService.UserService.GetItems<UserEntity>(1, 1, UserProperty.Id.ToString(),id));
{ } catch (ArgumentException)
try {
{ _logger.LogError("[ERREUR] Aucun utilisateur trouvé avec l'id {id}.", id);
_logger.LogInformation("[INFORMATION] Utilisateur avec l'username {username} a été trouvé.", username); return NotFound();
return Ok(_userDataService.GetUserByUsername(username)); }
}catch (ArgumentException) }
{
_logger.LogError("[ERREUR] Aucun utilisateur trouvé avec l'username {username}.", username); [HttpGet("user/username/{username}")]
return NotFound(); public async Task<IActionResult> GetUserByUsername(string username)
} {
try
} {
_logger.LogInformation("[INFORMATION] Utilisateur avec l'username {username} a été trouvé.", username);
[HttpDelete] return Ok(_dataService.UserService.GetItems<UserEntity>(1, 1,UserProperty.Username.ToString(), username));
public IActionResult DeleteUser(int id) }catch (ArgumentException)
{ {
var success = _userDataService.DeleteUser(id); _logger.LogError("[ERREUR] Aucun utilisateur trouvé avec l'username {username}.", username);
if(success) return NotFound();
{ }
_logger.LogInformation("[INFORMATION] L'utilisateur avec l'id {id} a été supprimé.", id);
return Ok(_userDataService.DeleteUser(id)); }
} else
{ [HttpDelete]
_logger.LogError("[ERREUR] Aucun utilisateur trouvé avec l'id {id}.", id); public async Task<IActionResult> DeleteUser(int id)
return NotFound(); {
} var success = await _dataService.UserService.DeleteItem<UserEntity>(id);
if(success)
} {
_logger.LogInformation("[INFORMATION] L'utilisateur avec l'id {id} a été supprimé.", id);
[HttpPost] return Ok(_dataService.UserService.DeleteUser(id));
public IActionResult CreateUser([FromBody]UserDTO dto) } else
{ {
_logger.LogError("[ERREUR] Aucun utilisateur trouvé avec l'id {id}.", id);
return NotFound();
}
}
[HttpPost]
public async Task<IActionResult> CreateUser([FromBody]UserDTO dto)
{
if (dto.Username == null || dto.Password == null || dto.Email == null) if (dto.Username == null || dto.Password == null || dto.Email == null)
{ {
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]
public IActionResult UpdateUser(int id, [FromBody] UserDTO userDTO) public async Task<IActionResult> UpdateUser(int id, [FromBody] UserDTO userDTO)
{ {
if(id != userDTO.Id) if(id != userDTO.Id)
{
_logger.LogError("[ERREUR] Problème ID - La mise à jour de l'utilisateur avec l'id {id} a échouée.", id);
return BadRequest();
}
if(!ModelState.IsValid)
{
_logger.LogError("[ERREUR] Problème controlleur - La mise à jour de l'utilisateur avec l'id {id} a échouée.", id);
return BadRequest();
}
if(userDTO != null)
{ {
_logger.LogError("[ERREUR] Problème ID - La mise à jour de l'utilisateur avec l'id {id} a échouée.", id); _logger.LogInformation("[INFORMATION] La mise à jour de l'utilisateur avec l'id {id} a été effectuée", id);
return BadRequest(); return Ok(_dataService.UserService.UpdateItem<UserEntity, UserDTO>(id, userDTO));
} }
if(!ModelState.IsValid) _logger.LogError("[ERREUR] Aucun utilisateur trouvé avec l'id {id}.", id);
{ return NotFound();
_logger.LogError("[ERREUR] Problème controlleur - La mise à jour de l'utilisateur avec l'id {id} a échouée.", id); }
return BadRequest(); }
} }
if(userDTO != null)
{
_logger.LogInformation("[INFORMATION] La mise à jour de l'utilsiateur avec l'id {id} a été effectuée", id);
return Ok(_userDataService.UpdateUser(id, userDTO));
}
_logger.LogError("[ERREUR] Aucun utilisateur trouvé avec l'id {id}.", id);
return NotFound();
}
}
}

@ -3,7 +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 Services; using Services;
using System.Data.Common;
using Microsoft.Extensions.Options;
var builder = WebApplication.CreateBuilder(args); var builder = WebApplication.CreateBuilder(args);
@ -13,7 +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<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>();

@ -3,19 +3,23 @@ Microsoft Visual Studio Solution File, Format Version 12.00
# Visual Studio Version 17 # Visual Studio Version 17
VisualStudioVersion = 17.8.34408.163 VisualStudioVersion = 17.8.34408.163
MinimumVisualStudioVersion = 10.0.40219.1 MinimumVisualStudioVersion = 10.0.40219.1
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "API", "API\API.csproj", "{65F4AE69-E1CA-4B87-BDF0-946A37351BD1}" Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "API", "API\API.csproj", "{65F4AE69-E1CA-4B87-BDF0-946A37351BD1}"
EndProject EndProject
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Entities", "EntityFramework\Entities.csproj", "{6D079CDA-C000-4833-98A0-D07D153EA264}" Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "Entities", "EntityFramework\Entities.csproj", "{6D079CDA-C000-4833-98A0-D07D153EA264}"
EndProject EndProject
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Model", "Model\Model.csproj", "{ADCC427D-A3CD-431C-A90B-F9369C4584E8}" Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "Model", "Model\Model.csproj", "{ADCC427D-A3CD-431C-A90B-F9369C4584E8}"
EndProject EndProject
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "TestAPI", "TestAPI\TestAPI.csproj", "{17025B90-8B2A-49E9-97D3-1A84A208DF50}" Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "TestAPI", "TestAPI\TestAPI.csproj", "{17025B90-8B2A-49E9-97D3-1A84A208DF50}"
EndProject EndProject
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "TestEF", "TestEF\TestEF.csproj", "{54FAD8AF-7601-4C54-8406-D81476A8D7D7}" Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "TestEF", "TestEF\TestEF.csproj", "{54FAD8AF-7601-4C54-8406-D81476A8D7D7}"
EndProject EndProject
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "DbContextLib", "DbContextLib\DbContextLib.csproj", "{BDCB3BFD-B744-4BC0-BCFC-78E08600203A}" Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "DbContextLib", "DbContextLib\DbContextLib.csproj", "{BDCB3BFD-B744-4BC0-BCFC-78E08600203A}"
EndProject EndProject
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "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
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
@ -51,6 +55,14 @@ Global
{9BD3DCBA-AFD8-47FA-B07C-613B53E63968}.Debug|Any CPU.Build.0 = Debug|Any CPU {9BD3DCBA-AFD8-47FA-B07C-613B53E63968}.Debug|Any CPU.Build.0 = Debug|Any CPU
{9BD3DCBA-AFD8-47FA-B07C-613B53E63968}.Release|Any CPU.ActiveCfg = Release|Any CPU {9BD3DCBA-AFD8-47FA-B07C-613B53E63968}.Release|Any CPU.ActiveCfg = Release|Any CPU
{9BD3DCBA-AFD8-47FA-B07C-613B53E63968}.Release|Any CPU.Build.0 = Release|Any CPU {9BD3DCBA-AFD8-47FA-B07C-613B53E63968}.Release|Any CPU.Build.0 = Release|Any CPU
{8F53CC62-94B3-4F9D-ABF1-F7307A6F27C0}.Debug|Any CPU.ActiveCfg = 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.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

@ -20,11 +20,12 @@ namespace DbContextLib
public DbSet<SuccessEntity> Success { get; set; } public DbSet<SuccessEntity> Success { get; set; }
public DbSet<NotepadEntity> Notepad { get; set; } public DbSet<NotepadEntity> Notepad { 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)
{ {
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);
} }
@ -67,6 +68,7 @@ namespace DbContextLib
modelBuilder.Entity<ContentLessonEntity>().HasKey(c => c.LessonPartId); modelBuilder.Entity<ContentLessonEntity>().HasKey(c => c.LessonPartId);
modelBuilder.Entity<SuccessEntity>().HasKey(s => s.UserId); modelBuilder.Entity<SuccessEntity>().HasKey(s => s.UserId);
modelBuilder.Entity<SuccessEntity>().HasKey(s => s.InquiryId); modelBuilder.Entity<SuccessEntity>().HasKey(s => s.InquiryId);
modelBuilder.Entity<InquiryEntity>().HasKey(s => s.Id);
base.OnModelCreating(modelBuilder); base.OnModelCreating(modelBuilder);
} }
} }

@ -25,5 +25,14 @@ namespace Entities.SQLudeoDB
Database = database; Database = database;
InquiryTable = inquiryTable; InquiryTable = inquiryTable;
} }
public InquiryEntity(string title, string description, bool isUser, InquiryTableEntity database, SolutionEntity inquiryTable)
{
Title = title;
Description = description;
IsUser = isUser;
Database = database;
InquiryTable = inquiryTable;
}
} }
} }

@ -9,22 +9,22 @@ namespace Entities.SQLudeoDB
public class LessonEntity public class LessonEntity
{ {
public int Id { get; set; } public int Id { get; set; }
public string Titla { get; set; } public string Title { get; set; }
public string LastPublisher { get; set; } public string LastPublisher { get; set; }
public DateOnly LastEdit { get; set; } public DateOnly LastEdit { get; set; }
public LessonEntity() { } public LessonEntity() { }
public LessonEntity(int id, string titla, string lastPublisher, DateOnly lastEdit) public LessonEntity(int id, string title, string lastPublisher, DateOnly lastEdit)
{ {
Id = id; Id = id;
Titla = titla; Title = title;
LastPublisher = lastPublisher; LastPublisher = lastPublisher;
LastEdit = lastEdit; LastEdit = lastEdit;
} }
public LessonEntity(string titla, string lastPublisher, DateOnly lastEdit) public LessonEntity(string title, string lastPublisher, DateOnly lastEdit)
{ {
Titla = titla; Title = title;
LastPublisher = lastPublisher; LastPublisher = lastPublisher;
LastEdit = lastEdit; LastEdit = lastEdit;
} }

@ -1,4 +1,5 @@
using System; using Entities.SQLudeoDB;
using System;
using System.Collections.Generic; using System.Collections.Generic;
using System.Linq; using System.Linq;
using System.Text; using System.Text;
@ -8,5 +9,22 @@ namespace Model.Business
{ {
public class Inquiry public class Inquiry
{ {
public int Id { get; set; }
public string Title { get; set; }
public string Description { get; set; }
public bool IsUser { get; set; }
public InquiryTableEntity Database { get; set; }
public SolutionEntity InquiryTable { get; set; }
public Inquiry() { }
public Inquiry(int id, string title, string description, bool isUser, InquiryTableEntity database, SolutionEntity inquiryTable)
{
Id = id;
Title = title;
Description = description;
IsUser = isUser;
Database = database;
InquiryTable = inquiryTable;
}
} }
} }

@ -0,0 +1,26 @@
using Entities.SQLudeoDB;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Model.Business
{
public class Lesson
{
public int Id { get; set; }
public string Title { get; set; }
public string LastPublisher { get; set; }
public DateOnly LastEdit { get; set; }
public Lesson() { }
public Lesson(int id, string title, string lastPublisher, DateOnly lastEdit)
{
Id = id;
Title = title;
LastPublisher = lastPublisher;
LastEdit = lastEdit;
}
}
}

@ -1,4 +1,5 @@
using System; using Entities.SQLudeoDB;
using System;
using System.Collections.Generic; using System.Collections.Generic;
using System.Linq; using System.Linq;
using System.Text; using System.Text;
@ -8,5 +9,22 @@ namespace Model.DTO
{ {
public class InquiryDTO public class InquiryDTO
{ {
public int Id { get; set; }
public string Title { get; set; }
public string Description { get; set; }
public bool IsUser { get; set; }
public InquiryTableEntity Database { get; set; }
public SolutionEntity InquiryTable { get; set; }
public InquiryDTO() { }
public InquiryDTO(int id, string title, string description, bool isUser, InquiryTableEntity database, SolutionEntity inquiryTable)
{
Id = id;
Title = title;
Description = description;
IsUser = isUser;
Database = database;
InquiryTable = inquiryTable;
}
} }
} }

@ -0,0 +1,26 @@
using Entities.SQLudeoDB;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Model.DTO
{
public class LessonDTO
{
public int Id { get; set; }
public string Title { get; set; }
public string LastPublisher { get; set; }
public DateOnly LastEdit { get; set; }
public LessonDTO() { }
public LessonDTO(int id, string title, string lastPublisher, DateOnly lastEdit)
{
Id = id;
Title = title;
LastPublisher = lastPublisher;
LastEdit = lastEdit;
}
}
}

@ -1,4 +1,7 @@
using System; using Entities.SQLudeoDB;
using Model.Business;
using Model.DTO;
using System;
using System.Collections.Generic; using System.Collections.Generic;
using System.Linq; using System.Linq;
using System.Text; using System.Text;
@ -6,26 +9,26 @@ using System.Threading.Tasks;
namespace Model.Mappers namespace Model.Mappers
{ {
public class InquiryMapper public static class InquiryMapper
{ {
public object FromDTOToModel() public static Inquiry FromDTOToModel(this InquiryDTO dto)
{ {
throw new NotImplementedException(); return new Inquiry(dto.Id, dto.Title, dto.Description, dto.IsUser, dto.Database, dto.InquiryTable);
} }
public object FromEntityToModel() public static Inquiry FromEntityToModel(this InquiryEntity entity)
{ {
throw new NotImplementedException(); return new Inquiry(entity.Id, entity.Title, entity.Description, entity.IsUser, entity.Database, entity.InquiryTable);
} }
public object FromModelToDTO() public static InquiryDTO FromModelToDTO(this Inquiry inquiry)
{ {
throw new NotImplementedException(); return new InquiryDTO(inquiry.Id, inquiry.Title, inquiry.Description, inquiry.IsUser, inquiry.Database, inquiry.InquiryTable);
} }
public object FromModelToEntity() public static InquiryEntity FromModelToEntity(this Inquiry inquiry)
{ {
throw new NotImplementedException(); return new InquiryEntity(inquiry.Id, inquiry.Title, inquiry.Description, inquiry.IsUser, inquiry.Database, inquiry.InquiryTable);
} }
} }
} }

@ -0,0 +1,29 @@
using Entities.SQLudeoDB;
using Model.Business;
using Model.DTO;
namespace Model.Mappers
{
public static class LessonMapper
{
public static Lesson FromDTOToModel(this LessonDTO dto)
{
return new Lesson(dto.Id, dto.Title, dto.LastPublisher, dto.LastEdit);
}
public static Lesson FromEntityToModel(this LessonEntity entity)
{
return new Lesson(entity.Id, entity.Title, entity.LastPublisher, entity.LastEdit);
}
public static LessonDTO FromModelToDTO(this Lesson lesson)
{
return new LessonDTO(lesson.Id, lesson.Title, lesson.LastPublisher, lesson.LastEdit);
}
public static LessonEntity FromModelToEntity(this Lesson lesson)
{
return new LessonEntity(lesson.Id, lesson.Title, lesson.LastPublisher, lesson.LastEdit);
}
}
}

@ -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
}
}

@ -0,0 +1,198 @@
using Entities.SQLudeoDB;
using Microsoft.EntityFrameworkCore;
using Model.DTO;
using Services;
using DbContextLib;
using Model.Business;
using Model;
using Model.Mappers;
using System;
using Microsoft.AspNetCore.Identity;
using System.Runtime.InteropServices.ObjectiveC;
namespace ModelToEntity
{
public class DbDataManager : IUserDataService<User?>
{
public async Task<User> GetUserById(int id)
{
using(var context = new UserDbContext())
{
var userEntity = context.Users.FirstOrDefault(u => u.Id == id);
if(userEntity == null)
{
throw new ArgumentException("Impossible de trouver l'utilisateur", nameof(id));
}
return await Task.FromResult(userEntity.FromEntityToModel());
}
}
public async Task<User> GetUserByUsername(string username)
{
using (var context = new UserDbContext())
{
var userEntity = context.Users.FirstOrDefault(u => u.Username == username);
if (userEntity == null)
{
throw new ArgumentException("Impossible de trouver l'utilisateur", nameof(username));
}
return await Task.FromResult(userEntity.FromEntityToModel());
}
}
public async Task<IEnumerable<User>> GetUsers(int page, int number)
{
using (var context = new UserDbContext())
{
return await Task.FromResult(context.Users.Skip((page - 1) * number).Take(number).ToList().Select(u => u.FromEntityToModel()));
}
}
public Task<bool> DeleteUser(int id)
{
using (var context = new UserDbContext()) {
var userEntity = context.Users.FirstOrDefault(u => u.Id == id);
if (userEntity == null)
{
return Task.FromResult(false);
}
context.Users.Remove(userEntity);
context.SaveChangesAsync();
}
return Task.FromResult(true);
}
public async Task<User> UpdateUser(int id, UserDTO user)
{
using (var context = new UserDbContext())
{
var updatingUser = context.Users.FirstOrDefault(u => u.Id == id);
if (updatingUser == null)
{
throw new ArgumentException("Impossible de trouver l'utilisateur", nameof(id));
}
updatingUser.Username = user.Username;
updatingUser.Password = user.Password;
updatingUser.Email = user.Email;
updatingUser.IsAdmin = user.IsAdmin;
// Permet d'indiquer en Db que l'entité a été modifiée.
context.Entry(updatingUser).State = EntityState.Modified;
context.SaveChangesAsync();
return await Task.FromResult(updatingUser.FromEntityToModel());
}
}
public async Task<User> CreateUser(string username, string password, string email, bool isAdmin)
{
using (var context = new UserDbContext())
{
var newUserEntity = new UserDTO
{
Username = username,
Password = password,
Email = email,
IsAdmin = isAdmin
};
context.Users.Add(newUserEntity.FromDTOToModel().FromModelToEntity());
context.SaveChanges();
return await Task.FromResult(newUserEntity.FromDTOToModel());
}
}
public IEnumerable<InquiryDTO> GetInquiries(int page, int number)
{
throw new NotImplementedException();
}
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)
{
throw new NotImplementedException();
}
public InquiryDTO UpdateInquiry(int id, InquiryDTO inquiry)
{
throw new NotImplementedException();
}
public IEnumerable<InquiryDTO> GetLessons(int page, int number)
{
throw new NotImplementedException();
}
public InquiryDTO GetLessonById(int id)
{
throw new NotImplementedException();
}
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 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);
}
}
}
}

@ -0,0 +1,104 @@
using Microsoft.AspNetCore.Identity;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Entities;
using Entities.SQLudeoDB;
using Model.Business;
using System.Diagnostics;
using DbContextLib;
using Microsoft.EntityFrameworkCore;
using System.Linq.Expressions;
using Microsoft.EntityFrameworkCore.Metadata.Internal;
namespace ModelToEntity
{
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);
}
}
}

@ -0,0 +1,33 @@
using Entities.SQLudeoDB;
using Model.Business;
using Model.DTO;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Services
{
public interface IDataServiceEF
{
public Task<IEnumerable<User>> GetUsers(int page, int number);
public Task<User> GetUserById(int id);
public Task<User> GetUserByUsername(string username);
public Task<bool> DeleteUser(int id);
public Task<User> UpdateUser(int id, UserDTO user);
public Task<User> CreateUser(string username, string password, string email, bool isAdmin);
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);
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,29 @@
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<TargetFramework>net8.0</TargetFramework>
<ImplicitUsings>enable</ImplicitUsings>
<Nullable>enable</Nullable>
</PropertyGroup>
<ItemGroup>
<PackageReference Include="Microsoft.EntityFrameworkCore" Version="8.0.1" />
<PackageReference Include="Microsoft.EntityFrameworkCore.Design" Version="8.0.1">
<PrivateAssets>all</PrivateAssets>
<IncludeAssets>runtime; build; native; contentfiles; analyzers; buildtransitive</IncludeAssets>
</PackageReference>
<PackageReference Include="Microsoft.EntityFrameworkCore.Tools" Version="8.0.1">
<PrivateAssets>all</PrivateAssets>
<IncludeAssets>runtime; build; native; contentfiles; analyzers; buildtransitive</IncludeAssets>
</PackageReference>
<PackageReference Include="Npgsql.EntityFrameworkCore.PostgreSQL" Version="8.0.0" />
</ItemGroup>
<ItemGroup>
<ProjectReference Include="..\DbContextLib\DbContextLib.csproj" />
<ProjectReference Include="..\EntityFramework\Entities.csproj" />
<ProjectReference Include="..\Model\Model.csproj" />
<ProjectReference Include="..\Shared\Shared.csproj" />
</ItemGroup>
</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; }
}
}

@ -1,18 +0,0 @@
using Model.Business;
using Model.DTO;
namespace Services
{
public interface IDataService
{
public IEnumerable<UserDTO> GetUsers(int page, int number);
public UserDTO GetUserById(int id);
public UserDTO GetUserByUsername(string username);
public bool DeleteUser(int id);
public UserDTO UpdateUser(int id, UserDTO user);
public UserDTO CreateUser(string username, string password, string email, bool isAdmin);
public IEnumerable<InquiryDTO> GetInquiries(int page, int number);
public InquiryDTO GetInquiryById(int id);
public InquiryDTO GetInquiryByTitle(string title);
}
}

@ -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
{
}
}

@ -22,7 +22,9 @@
<ItemGroup> <ItemGroup>
<ProjectReference Include="..\DbContextLib\DbContextLib.csproj" /> <ProjectReference Include="..\DbContextLib\DbContextLib.csproj" />
<ProjectReference Include="..\EntityFramework\Entities.csproj" /> <ProjectReference Include="..\EntityFramework\Entities.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>

@ -8,100 +8,76 @@ using System.Threading.Tasks;
using Model.Mappers; using Model.Mappers;
using Model.Business; using Model.Business;
using Microsoft.EntityFrameworkCore; using Microsoft.EntityFrameworkCore;
using Entities.SQLudeoDB;
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;
public UserDataService(UserDbContext context) public UserDataService(IUserDataService<User> dataServiceEF)
{ {
DbContext = context; this.dataServiceEF = dataServiceEF;
context.Database.EnsureCreated();
} }
public UserDTO GetUserById(int id) public async Task<UserDTO?> GetUserById(int id)
{ {
var userEntity = DbContext.Users.FirstOrDefault(u => u.Id == id); var user = await dataServiceEF.GetUserById(id);
if (userEntity == null) return user.FromModelToDTO();
{
throw new ArgumentException("Impossible de trouver l'utilisateur", nameof(id));
}
return userEntity.FromEntityToModel().FromModelToDTO();
}
public UserDTO GetUserByUsername(string username)
{
var userEntity = DbContext.Users.FirstOrDefault(u => u.Username == username);
if (userEntity == null)
{
throw new ArgumentException("Impossible de trouver l'utilisateur", nameof(username));
}
return userEntity.FromEntityToModel().FromModelToDTO();
} }
public IEnumerable<UserDTO> GetUsers(int page, int number) public async Task<UserDTO?> GetUserByUsername(string username)
{ {
return DbContext.Users.Skip((page - 1) * number).Take(number).ToList().Select(u => u.FromEntityToModel().FromModelToDTO()); var user = await dataServiceEF.GetUserByUsername(username);
return user.FromModelToDTO();
} }
public bool DeleteUser(int id) public async Task<IEnumerable<UserDTO?>> GetUsers(int page, int number)
{ {
var userEntity = DbContext.Users.FirstOrDefault(u => u.Id == id); var users = await dataServiceEF.GetUsers(page, number);
if (userEntity == null) return users.Select(u => u.FromModelToDTO());
{
return false;
}
DbContext.Users.Remove(userEntity);
DbContext.SaveChangesAsync();
return true;
} }
public UserDTO UpdateUser(int id, UserDTO user) public async Task<bool> DeleteUser(int id)
{ {
var updatingUser = DbContext.Users.FirstOrDefault(u => u.Id == id); var respons = await dataServiceEF.DeleteUser(id);
if (updatingUser == null) return respons;
{
throw new ArgumentException("Impossible de trouver l'utilisateur", nameof(id));
}
updatingUser.Username = user.Username;
updatingUser.Password = user.Password;
updatingUser.Email = user.Email;
updatingUser.IsAdmin = user.IsAdmin;
// Permet d'indiquer en Db que l'entité a été modifiée.
DbContext.Entry(updatingUser).State = EntityState.Modified;
DbContext.SaveChangesAsync();
return updatingUser.FromEntityToModel().FromModelToDTO();
} }
public UserDTO CreateUser(string username, string password, string email, bool isAdmin) public async Task<UserDTO?> UpdateUser(int id, UserDTO user)
{ {
var newUserEntity = new UserDTO var updatingUser = await dataServiceEF.UpdateUser(id, user);
{ return updatingUser.FromModelToDTO();
Username = username,
Password = password,
Email = email,
IsAdmin = isAdmin
};
DbContext.Users.Add(newUserEntity.FromDTOToModel().FromModelToEntity());
DbContext.SaveChangesAsync();
return newUserEntity;
} }
public async Task<UserDTO?> CreateUser(string username, string password, string email, bool isAdmin)
public IEnumerable<InquiryDTO> GetInquiries(int page, int number)
{ {
throw new NotImplementedException(); var newUserEntity = await dataServiceEF.CreateUser(username, password, email, isAdmin);
return newUserEntity.FromModelToDTO();
}
public async Task<T?> AddItem<T>(T? item) where T : class
{
var newItem = dataServiceEF.AddItem(item);
return await newItem;
}
public Task<bool> DeleteItem<T>(int id) where T : class
{
var succes = dataServiceEF.DeleteItem<T>(id);
return succes;
} }
public InquiryDTO GetInquiryById(int id) 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 InquiryDTO GetInquiryByTitle(string title) 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;
} }
} }
} }

@ -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