Compare commits

...

14 Commits

Author SHA1 Message Date
Victor GABORIT fc2db0d322 ajout d'une nouvelle branch pour corriger un problème de dépendance forte entre la partie WebService et EF ainsi que l'exclusion de la primary key dans la methode UpdateItem
1 year ago
Victor GABORIT 9073f29527 utilisation DeleteItem dans UserController et correction de bug car DeletItem renvoyait un objet non serializable qui provoquait une erreur 500 coté API 🐛
1 year ago
Victor GABORIT 91b2a5a082 merge de la branch genericite sur crud/security
1 year ago
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
Erwan MENAGER 515735dcb6 Implémentation des méthodes CRUD pour les 5 entités !
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>
<ProjectReference Include="..\ModelToEntity\ModelToEntity.csproj" />
<ProjectReference Include="..\Services\Services.csproj" />
</ItemGroup>

@ -10,26 +10,25 @@ namespace API.Controllers
[ApiController]
public class InquiriesController : Controller
{
private IDataService _inquiryDataService;
private IDataService<InquiryDTO> _dataService;
private readonly ILogger<UserController> _logger;
public InquiriesController(IDataService inquiryDataService)
private readonly ILogger<UsersController> _logger;
public InquiriesController(IDataService<InquiryDTO> dataService)
{
_inquiryDataService = inquiryDataService;
_dataService = _dataService;
}
[HttpGet("inquiries/{page}/{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)
{
_logger.LogError("[ERREUR] Aucune enquête trouvé.");
_logger.LogError("[ERREUR] Aucune enquête trouvée.");
return StatusCode(204);
}
_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}")]
@ -37,8 +36,8 @@ namespace API.Controllers
{
try
{
_logger.LogInformation("[INFORMATION] Enquête avec l'id {id} a été trouvé.", id);
return Ok(_inquiryDataService.GetInquiryById(id));
_logger.LogInformation("[INFORMATION] L'enquête avec l'id {id} a été trouvé.", id);
return Ok(_dataService.InquiryDataService.GetInquiryById(id));
}
catch (ArgumentException)
{
@ -52,8 +51,8 @@ namespace API.Controllers
{
try
{
_logger.LogInformation("[INFORMATION] Enquête avec le titre {title} a été trouvé.", title);
return Ok(_inquiryDataService.GetInquiryByTitle(title));
_logger.LogInformation("[INFORMATION] L'enquête avec le titre {title} a été trouvé.", title);
return Ok(_dataService.InquiryDataService.GetInquiryByTitle(title));
}
catch (ArgumentException)
{
@ -61,5 +60,55 @@ namespace API.Controllers
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,114 @@
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using Model.DTO;
using Services;
namespace API.Controllers
{
[Route("api/[controller]")]
[Authorize]
[ApiController]
public class LessonsController : Controller
{
private IDataService<LessonDTO> _dataService;
private readonly ILogger<UsersController> _logger;
public LessonsController(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();
}
}
}

@ -0,0 +1,117 @@
using DbContextLib;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Model.Business;
using Model.DTO;
using Services;
namespace API.Controllers
{
[Route("api/[controller]")]
[Authorize]
[ApiController]
public class ParagraphsController : Controller
{
private IDataService _paragraphDataService;
private readonly ILogger<ParagraphsController> _logger;
public ParagraphsController(IDataService paragraphDataService, ILogger<ParagraphsController> logger)
{
_paragraphDataService = paragraphDataService;
_logger = logger;
}
[HttpGet("paragraphs/{page}/{number}")]
public async Task<IActionResult> GetParagraphs(int page, int number)
{
var nbParagraph = (await _paragraphDataService.GetParagraphs(page, number)).ToList().Count();
if(nbParagraph == 0)
{
_logger.LogError("[ERREUR] Aucun paragraphe trouvé.");
return StatusCode(204);
}
_logger.LogInformation("[INFORMATION] {nb} Paragraphe(s) trouvé(s)", nbParagraph);
return Ok(_paragraphDataService.GetParagraphs(page, number));
}
[HttpGet("paragraph/id/{id}")]
public async Task<IActionResult> GetParagraphById(int id)
{
try
{
_logger.LogInformation("[INFORMATION] Le paragraphe avec l'id {id} a été trouvé.", id);
return Ok(_paragraphDataService.GetParagraphById(id));
} catch (ArgumentException)
{
_logger.LogError("[ERREUR] Aucun paragraphe trouvé avec l'id {id}.", id);
return NotFound();
}
}
[HttpGet("paragraph/title/{title}")]
public async Task<IActionResult> GetParagraphByTitle(string title)
{
try
{
_logger.LogInformation("[INFORMATION] Le paragraphe avec le titre {title} a été trouvé.", title);
return Ok(_paragraphDataService.GetUserByUsername(title));
}catch (ArgumentException)
{
_logger.LogError("[ERREUR] Aucun paragraphe trouvé avec le titre {title}.", title);
return NotFound();
}
}
[HttpDelete]
public async Task<IActionResult> DeleteParagraph(int id)
{
var success = await _paragraphDataService.DeleteParagraph(id);
if(success)
{
_logger.LogInformation("[INFORMATION] Le paragraphe avec l'id {id} a été supprimé.", id);
return Ok(_paragraphDataService.DeleteParagraph(id));
} else
{
_logger.LogError("[ERREUR] Aucun paragraphe trouvé avec l'id {id}.", id);
return NotFound();
}
}
[HttpPost]
public async Task<IActionResult> CreateParagraph([FromBody] ParagraphDTO dto)
{
if (dto.Title == null || dto.Content == null || dto.Info == null || dto.Query == null || dto.Comment == null)
{
return BadRequest();
}
_logger.LogInformation("[INFORMATION] Un paragraphe a été créé : title - {title}, content - {content}, info - {info}, query - {query}, comment - {comment}", dto.Title, dto.Content, dto.Info, dto.Query, dto.Comment);
return Created(nameof(GetParagraphs), _paragraphDataService.CreateParagraph(dto.Title, dto.Content, dto.Info, dto.Query, dto.Comment));
}
[HttpPut]
public async Task<IActionResult> UpdateParagraph(int id, [FromBody] ParagraphDTO paragraphDTO)
{
if(id != paragraphDTO.Id)
{
_logger.LogError("[ERREUR] Problème ID - La mise à jour du paragraphe avec l'id {id} a échouée.", id);
return BadRequest();
}
if(!ModelState.IsValid)
{
_logger.LogError("[ERREUR] Problème controlleur - La mise à jour du paragraphe avec l'id {id} a échouée.", id);
return BadRequest();
}
if(paragraphDTO != null)
{
_logger.LogInformation("[INFORMATION] La mise à jour du paragraphe avec l'id {id} a été effectuée", id);
return Ok(_paragraphDataService.UpdateParagraph(id, paragraphDTO));
}
_logger.LogError("[ERREUR] Aucun paragraphe trouvé avec l'id {id}.", id);
return NotFound();
}
}
}

@ -0,0 +1,117 @@
using DbContextLib;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Model.Business;
using Model.DTO;
using Services;
namespace API.Controllers
{
[Route("api/[controller]")]
[Authorize]
[ApiController]
public class SuccessesController : Controller
{
private IDataService _successDataService;
private readonly ILogger<SuccessesController> _logger;
public SuccessesController(IDataService successDataService, ILogger<SuccessesController> logger)
{
_successDataService = successDataService;
_logger = logger;
}
[HttpGet("successes/{page}/{number}")]
public async Task<IActionResult> GetSuccesses(int page, int number)
{
var nbUser = (await _successDataService.GetUsers(page, number)).ToList().Count();
if(nbUser == 0)
{
_logger.LogError("[ERREUR] Aucun utilisateur trouvé.");
return StatusCode(204);
}
_logger.LogInformation("[INFORMATION] {nb} Utilisateur(s) trouvé(s)", nbUser);
return Ok(_successDataService.GetUsers(page, number));
}
[HttpGet("success/user/{id}")]
public async Task<IActionResult> GetSuccessByUserId(int userId)
{
try
{
_logger.LogInformation("[INFORMATION] Le succès avec l'id de l'utilisateur {id} a été trouvé.", userId);
return Ok(_successDataService.GetSuccessByUserId(userId));
} catch (ArgumentException)
{
_logger.LogError("[ERREUR] Aucun utilisateur trouvé avec l'id de l'utilisateur {id}.", userId);
return NotFound();
}
}
[HttpGet("success/inquiry/{inquiryId}")]
public async Task<IActionResult> GetSuccessByInquiryId(int inquiryId)
{
try
{
_logger.LogInformation("[INFORMATION] Utilisateur avec l'id de l'enquête {inquiryId} a été trouvé.", inquiryId);
return Ok(_successDataService.GetSuccessByInquiryId(inquiryId));
}catch (ArgumentException)
{
_logger.LogError("[ERREUR] Aucun utilisateur trouvé avec l'id de l'enquête {inquiryId}.", inquiryId);
return NotFound();
}
}
[HttpDelete]
public async Task<IActionResult> DeleteSuccess(int id)
{
var success = await _successDataService.DeleteSuccess(id);
if(success)
{
_logger.LogInformation("[INFORMATION] Le succès avec l'id {id} a été supprimé.", id);
return Ok(_successDataService.DeleteSuccess(id));
} else
{
_logger.LogError("[ERREUR] Aucun succès trouvé avec l'id {id}.", id);
return NotFound();
}
}
[HttpPost]
public async Task<IActionResult> CreateSuccess([FromBody] SuccessDTO dto)
{
/*if (dto.UserId == null || dto.InquiryId == null)
{
return BadRequest();
}*/
_logger.LogInformation("[INFORMATION] Un succès a été créé : userId - {userId}, inquiryId - {inquiryId}, isFinished - {isFinished}", dto.UserId, dto.InquiryId, dto.IsFinished);
return Created(nameof(GetSuccesses), _successDataService.CreateSuccess(dto.UserId, dto.InquiryId, dto.IsFinished));
}
[HttpPut]
public async Task<IActionResult> UpdateSuccess(int id, [FromBody] SuccessDTO successDTO)
{
if(id != successDTO.UserId)
{
_logger.LogError("[ERREUR] Problème ID - La mise à jour du succès avec l'id de l'utilisateur {id} a échouée.", id);
return BadRequest();
}
if(!ModelState.IsValid)
{
_logger.LogError("[ERREUR] Problème controlleur - La mise à jour du succès avec l'id de l'utilisateur {id} a échouée.", id);
return BadRequest();
}
if(successDTO != null)
{
_logger.LogInformation("[INFORMATION] La mise à jour du succès avec l'id de l'utilisateur {id} a été effectuée", id);
return Ok(_successDataService.UpdateSuccess(id, successDTO));
}
_logger.LogError("[ERREUR] Aucun succès trouvé avec l'id de l'utilisateur {id}.", id);
return NotFound();
}
}
}

@ -1,9 +1,12 @@
using DbContextLib;
using Entities.SQLudeoDB;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Model;
using Model.Business;
using Model.DTO;
using Model.Mappers;
using Services;
namespace API.Controllers
@ -11,39 +14,38 @@ namespace API.Controllers
[Route("api/[controller]")]
[Authorize]
[ApiController]
public class UserController : Controller
public class UsersController : Controller
{
private IDataService _userDataService;
private IDataService<UserDTO?> _dataService;
private readonly ILogger<UserController> _logger;
public UserController(IDataService userDataService, ILogger<UserController> logger)
private readonly ILogger<UsersController> _logger;
public UsersController(IDataService<UserDTO?> dataService, ILogger<UsersController> logger)
{
_userDataService = userDataService;
_dataService = dataService;
_logger = logger;
}
[HttpGet("users/{page}/{number}")]
public IActionResult GetUsers(int page, int number)
public async Task<IActionResult> GetUsers(int page, int number)
{
var nbUser = _userDataService.GetUsers(page, number).Count();
var nbUser = (await _dataService.UserService.GetItems(page, number)).ToList().Count();
if(nbUser == 0)
{
_logger.LogError("[ERREUR] Aucun utilisateur trouvé.");
return StatusCode(204);
}
_logger.LogInformation("[INFORMATION] {nb} Utilisateur(s) trouvé(s)", nbUser);
return Ok(_userDataService.GetUsers(page, number));
return Ok(_dataService.UserService.GetItems(page, number));
}
[HttpGet("user/id/{id}")]
public IActionResult GetUserById(int id)
public async Task<IActionResult> GetUserById(int id)
{
try
{
_logger.LogInformation("[INFORMATION] Utilisateur avec l'id {id} a été trouvé.", id);
return Ok(_userDataService.GetUserById(id));
} catch (ArgumentException)
return Ok(_dataService.UserService.GetItems(1, 1, UserProperty.Id.ToString(),id));
} catch (KeyNotFoundException)
{
_logger.LogError("[ERREUR] Aucun utilisateur trouvé avec l'id {id}.", id);
return NotFound();
@ -51,12 +53,12 @@ namespace API.Controllers
}
[HttpGet("user/username/{username}")]
public IActionResult GetUserByUsername(string username)
public async Task<IActionResult> GetUserByUsername(string username)
{
try
{
_logger.LogInformation("[INFORMATION] Utilisateur avec l'username {username} a été trouvé.", username);
return Ok(_userDataService.GetUserByUsername(username));
return Ok(_dataService.UserService.GetItems(1, 1,UserProperty.Username.ToString(), username));
}catch (ArgumentException)
{
_logger.LogError("[ERREUR] Aucun utilisateur trouvé avec l'username {username}.", username);
@ -66,13 +68,13 @@ namespace API.Controllers
}
[HttpDelete]
public IActionResult DeleteUser(int id)
public async Task<IActionResult> DeleteUser(int id)
{
var success = _userDataService.DeleteUser(id);
var success = await _dataService.UserService.DeleteItem(id);
if(success)
{
_logger.LogInformation("[INFORMATION] L'utilisateur avec l'id {id} a été supprimé.", id);
return Ok(_userDataService.DeleteUser(id));
return Ok(_dataService.UserService.DeleteItem(id));
} else
{
_logger.LogError("[ERREUR] Aucun utilisateur trouvé avec l'id {id}.", id);
@ -82,19 +84,19 @@ namespace API.Controllers
}
[HttpPost]
public IActionResult CreateUser([FromBody]UserDTO dto)
public async Task<IActionResult> CreateUser([FromBody]UserDTO dto)
{
if (dto.Username == null || dto.Password == null || dto.Email == null)
{
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);
return Created(nameof(GetUsers), _userDataService.CreateUser(dto.Username, dto.Password, dto.Email, dto.IsAdmin));
return Created(nameof(GetUsers), _dataService.UserService.AddItem(dto));
}
[HttpPut]
public IActionResult UpdateUser(int id, [FromBody] UserDTO userDTO)
public async Task<IActionResult> UpdateUser(int id, [FromBody] UserDTO userDTO)
{
if(id != userDTO.Id)
{
@ -108,8 +110,8 @@ namespace API.Controllers
}
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.LogInformation("[INFORMATION] La mise à jour de l'utilisateur avec l'id {id} a été effectuée", id);
return Ok(_dataService.UserService.UpdateItem<UserDTO>(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.EntityFrameworkCore;
using Microsoft.OpenApi.Models;
using Model.DTO;
using Model.Business;
using ModelToEntity;
using Services;
using System.Data.Common;
using Microsoft.Extensions.Options;
var builder = WebApplication.CreateBuilder(args);
@ -13,7 +18,9 @@ builder.Services.AddControllers();
// Learn more about configuring Swagger/OpenAPI at https://aka.ms/aspnetcore/swashbuckle
builder.Services.AddEndpointsApiExplorer();
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<WebAPIDbContext>(options => options.UseInMemoryDatabase("appDb"));
builder.Services.AddIdentityApiEndpoints<IdentityUser>().AddEntityFrameworkStores<WebAPIDbContext>();

@ -3,19 +3,23 @@ Microsoft Visual Studio Solution File, Format Version 12.00
# Visual Studio Version 17
VisualStudioVersion = 17.8.34408.163
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
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
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
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
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
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
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
Global
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}.Release|Any CPU.ActiveCfg = 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
GlobalSection(SolutionProperties) = preSolution
HideSolutionNode = FALSE

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

@ -25,5 +25,14 @@ namespace Entities.SQLudeoDB
Database = database;
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 int Id { get; set; }
public string Titla { get; set; }
public string Title { get; set; }
public string LastPublisher { get; set; }
public DateOnly LastEdit { get; set; }
public LessonEntity() { }
public LessonEntity(int id, string titla, string lastPublisher, DateOnly lastEdit)
public LessonEntity(int id, string title, string lastPublisher, DateOnly lastEdit)
{
Id = id;
Titla = titla;
Title = title;
LastPublisher = lastPublisher;
LastEdit = lastEdit;
}
public LessonEntity(string titla, string lastPublisher, DateOnly lastEdit)
public LessonEntity(string title, string lastPublisher, DateOnly lastEdit)
{
Titla = titla;
Title = title;
LastPublisher = lastPublisher;
LastEdit = lastEdit;
}

@ -1,4 +1,5 @@
using System;
using Entities.SQLudeoDB;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
@ -8,5 +9,22 @@ namespace Model.Business
{
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;
}
}
}

@ -0,0 +1,38 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Model.Business
{
public class Paragraph
{
public int Id { get; }
public string Title { get; set; }
public string Content { get; set; }
public string Info { get; set; }
public string Query { get; set; }
public string Comment { get; set; }
public Paragraph() { }
public Paragraph(int id, string title, string content, string info, string query, string comment)
{
Id = id;
Title = title;
Content = content;
Info = info;
Query = query;
Comment = comment;
}
public Paragraph(string title, string content, string info, string query, string comment)
{
Title = title;
Content = content;
Info = info;
Query = query;
Comment = comment;
}
}
}

@ -0,0 +1,34 @@
using Entities.SQLudeoDB;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Model.Business
{
public class Success
{
public int UserId { get; set; }
public UserEntity User { get; set; }
public int InquiryId { get; set; }
public InquiryEntity Inquiry { get; set; }
public bool IsFinished { get; set; }
public Success() { }
public Success(int userId, int inquiryId, bool isFinished)
{
UserId = userId;
InquiryId = inquiryId;
IsFinished = isFinished;
}
public Success(UserEntity user, InquiryEntity inquiry, bool isFinished)
{
User = user;
Inquiry = inquiry;
IsFinished = isFinished;
}
}
}

@ -1,4 +1,5 @@
using System;
using Entities.SQLudeoDB;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
@ -8,5 +9,22 @@ namespace Model.DTO
{
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;
}
}
}

@ -0,0 +1,31 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Model.DTO
{
public class ParagraphDTO
{
public int Id { get; }
public string Title { get; set; }
public string Content { get; set; }
public string Info { get; set; }
public string Query { get; set; }
public string Comment { get; set; }
public ParagraphDTO() { }
public ParagraphDTO(int id, string title, string content, string info, string query, string comment)
{
Id = id;
Title = title;
Content = content;
Info = info;
Query = query;
Comment = comment;
}
}
}

@ -0,0 +1,28 @@
using Entities.SQLudeoDB;
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations.Schema;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Model.DTO
{
public class SuccessDTO
{
public int UserId { get; set; }
public UserEntity User { get; set; }
public int InquiryId { get; set; }
public InquiryEntity Inquiry { get; set; }
public bool IsFinished { get; set; }
public SuccessDTO() { }
public SuccessDTO(int userId, int inquiryId, bool isFinished)
{
UserId = userId;
InquiryId = inquiryId;
IsFinished = isFinished;
}
}
}

@ -1,17 +0,0 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.InteropServices.ObjectiveC;
using System.Text;
using System.Threading.Tasks;
namespace Model.Mappers
{
public interface IMapper
{
public Object FromEntityToModel(object o);
public Object FromModelToDTO(object o);
public Object FromDTOToModel(object o);
public Object FromModelToEntity(object o);
}
}

@ -1,4 +1,7 @@
using System;
using Entities.SQLudeoDB;
using Model.Business;
using Model.DTO;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
@ -6,26 +9,26 @@ using System.Threading.Tasks;
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,34 @@
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 Model.Mappers
{
public static class ParagraphMapper
{
public static Paragraph FromDTOToModel(this ParagraphDTO dto)
{
return new Paragraph(dto.Id, dto.Title, dto.Content, dto.Info, dto.Query, dto.Comment);
}
public static Paragraph FromEntityToModel(this ParagraphEntity entity)
{
return new Paragraph(entity.Id, entity.Title, entity.Content, entity.Info, entity.Query, entity.Comment);
}
public static ParagraphDTO FromModelToDTO(this Paragraph paragraph)
{
return new ParagraphDTO(paragraph.Id, paragraph.Title, paragraph.Content, paragraph.Info, paragraph.Query, paragraph.Comment);
}
public static ParagraphEntity FromModelToEntity(this Paragraph paragraph)
{
return new ParagraphEntity(paragraph.Id, paragraph.Title, paragraph.Content, paragraph.Info, paragraph.Query, paragraph.Comment);
}
}
}

@ -0,0 +1,29 @@
using Entities.SQLudeoDB;
using Model.Business;
using Model.DTO;
namespace Model.Mappers
{
public static class SuccessMapper
{
public static Success FromDTOToModel(this SuccessDTO dto)
{
return new Success(dto.UserId, dto.InquiryId, dto.IsFinished);
}
public static Success FromEntityToModel(this SuccessEntity entity)
{
return new Success(entity.UserId, entity.InquiryId, entity.IsFinished);
}
public static SuccessDTO FromModelToDTO(this Success success)
{
return new SuccessDTO(success.UserId, success.InquiryId, success.IsFinished);
}
public static SuccessEntity FromModelToEntity(this Success success)
{
return new SuccessEntity(success.UserId, success.InquiryId, success.IsFinished);
}
}
}

@ -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,195 @@
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<User?> AddItem(User? item)
{
using (var context = new UserDbContext())
{
return (await context.CreateItemAsync(item.FromModelToEntity())).FromEntityToModel() ;
}
}
public async Task<bool> DeleteItem(int id)
{
using(var context = new UserDbContext())
{
return await context.DeleteItemAsync<UserEntity>(id);
}
}
public async Task<User?> UpdateItem<TDto>(int? id, TDto? newItem) where TDto : class
{
using(var context = new UserDbContext())
{
return (await context.UpdateItemAsync<UserEntity, TDto>(id, newItem)).FromEntityToModel();
}
}
public async Task<IEnumerable<User?>> GetItems(int index, int count, string? orderingPropertyName = null, object? valueProperty = null)
{
using (var context = new UserDbContext())
{
return (await context.GetItemsWithFilter<UserEntity>(index, count, orderingPropertyName, valueProperty)).Select(item => item.FromEntityToModel());
}
}
}
}

@ -0,0 +1,107 @@
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 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;
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 });
}
}
}
return Task.FromResult<IEnumerable<T?>>(new List<T?> { default(T) });
}
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 +1,40 @@
using Model.Business;
using Entities.SQLudeoDB;
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 Task<IEnumerable<UserDTO>> GetUsers(int page, int number);
public Task<UserDTO> GetUserById(int id);
public Task<UserDTO> GetUserByUsername(string username);
public Task<bool> DeleteUser(int id);
public Task<UserDTO> UpdateUser(int id, UserDTO user);
public Task<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);
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);
public Task<IEnumerable<ParagraphDTO>> GetParagraphs(int page, int number);
public Task<ParagraphDTO> GetParagraphById(int id);
public Task<ParagraphDTO> GetParagraphByTitle(string title);
public Task<bool> DeleteParagraph(int id);
public Task<ParagraphDTO> UpdateParagraph(int id, ParagraphDTO paragraphDTO);
public Task<ParagraphDTO> CreateParagraph(string title, string content, string info, string query, string comment);
public Task<IEnumerable<UserDTO>> GetSuccesses(int page, int number);
public Task<UserDTO> GetSuccessByUserId(int id);
public Task<UserDTO> GetSuccessByInquiryId(int id);
public Task<bool> DeleteSuccess(int id);
public Task<UserDTO> UpdateSuccess(int id, SuccessDTO success);
public Task<UserDTO> CreateSuccess(int userId, int inquiryId, bool isFinished);
}
}

@ -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>
<ProjectReference Include="..\DbContextLib\DbContextLib.csproj" />
<ProjectReference Include="..\EntityFramework\Entities.csproj" />
<ProjectReference Include="..\ModelToEntity\ModelToEntity.csproj" />
<ProjectReference Include="..\Model\Model.csproj" />
<ProjectReference Include="..\Shared\Shared.csproj" />
</ItemGroup>
</Project>

@ -1,4 +1,4 @@
using DbContextLib;
using DbContextLib;
using Model.DTO;
using System;
using System.Collections.Generic;
@ -8,98 +8,142 @@ using System.Threading.Tasks;
using Model.Mappers;
using Model.Business;
using Microsoft.EntityFrameworkCore;
using Entities.SQLudeoDB;
using ModelToEntity;
namespace Services
{
public class UserDataService : IDataService
public class UserDataService : IUserDataService<UserDTO?>
{
private UserDbContext DbContext { get; set; }
public UserDataService(UserDbContext context)
private readonly IUserDataService<User> dataServiceEF;
public UserDataService(IUserDataService<User> dataServiceEF)
{
DbContext = context;
context.Database.EnsureCreated();
this.dataServiceEF = dataServiceEF;
}
public UserDTO GetUserById(int id)
public async Task<UserDTO?> GetUserById(int id)
{
var userEntity = DbContext.Users.FirstOrDefault(u => u.Id == id);
if (userEntity == null)
var user = await dataServiceEF.GetUserById(id);
return user.FromModelToDTO();
}
public async Task<UserDTO?> GetUserByUsername(string username)
{
var user = await dataServiceEF.GetUserByUsername(username);
return user.FromModelToDTO();
}
public async Task<IEnumerable<UserDTO?>> GetUsers(int page, int number)
{
throw new ArgumentException("Impossible de trouver l'utilisateur", nameof(id));
var users = await dataServiceEF.GetUsers(page, number);
return users.Select(u => u.FromModelToDTO());
}
return userEntity.FromEntityToModel().FromModelToDTO();
public async Task<bool> DeleteUser(int id)
{
var respons = await dataServiceEF.DeleteUser(id);
return respons;
}
public async Task<UserDTO?> UpdateUser(int id, UserDTO user)
{
var updatingUser = await dataServiceEF.UpdateUser(id, user);
return updatingUser.FromModelToDTO();
}
public async Task<UserDTO?> CreateUser(string username, string password, string email, bool isAdmin)
{
var newUserEntity = await dataServiceEF.CreateUser(username, password, email, isAdmin);
return newUserEntity.FromModelToDTO();
}
public UserDTO GetUserByUsername(string username)
public async Task<UserDTO?> AddItem(UserDTO? item)
{
var newItem = await dataServiceEF.AddItem(item.FromDTOToModel());
return newItem.FromModelToDTO();
}
public Task<bool> DeleteItem(int id)
{
var succes = dataServiceEF.DeleteItem(id);
return succes;
}
public async Task<UserDTO> UpdateItem<TDto>(int? id, TDto? newItem) where TDto : class
{
var item = await dataServiceEF.UpdateItem<TDto>(id, newItem);
return item.FromModelToDTO();
}
public async Task<IEnumerable<UserDTO?>> GetItems(int index, int count, string? orderingPropertyName = null, object? valueProperty = null)
{
try
{
var userEntity = DbContext.Users.FirstOrDefault(u => u.Username == username);
if (userEntity == null)
var items = await dataServiceEF.GetItems(index, count, orderingPropertyName, valueProperty);
return items.Select(item => item.FromModelToDTO());
}
catch (KeyNotFoundException ex)
{
throw new ArgumentException("Impossible de trouver l'utilisateur", nameof(username));
throw;
}
return userEntity.FromEntityToModel().FromModelToDTO();
}
public IEnumerable<UserDTO> GetUsers(int page, int number)
public Task<IEnumerable<ParagraphDTO>> GetParagraphs(int page, int number)
{
return DbContext.Users.Skip((page - 1) * number).Take(number).ToList().Select(u => u.FromEntityToModel().FromModelToDTO());
throw new NotImplementedException();
}
public bool DeleteUser(int id)
public Task<ParagraphDTO> GetParagraphById(int id)
{
var userEntity = DbContext.Users.FirstOrDefault(u => u.Id == id);
if (userEntity == null)
throw new NotImplementedException();
}
public Task<ParagraphDTO> GetParagraphByTitle(string title)
{
return false;
throw new NotImplementedException();
}
DbContext.Users.Remove(userEntity);
DbContext.SaveChangesAsync();
return true;
public Task<bool> DeleteParagraph(int id)
{
throw new NotImplementedException();
}
public UserDTO UpdateUser(int id, UserDTO user)
public Task<ParagraphDTO> UpdateParagraph(int id, ParagraphDTO paragraphDTO)
{
var updatingUser = DbContext.Users.FirstOrDefault(u => u.Id == id);
if (updatingUser == null)
throw new NotImplementedException();
}
public Task<ParagraphDTO> CreateParagraph(string title, string content, string info, string query, string comment)
{
throw new ArgumentException("Impossible de trouver l'utilisateur", nameof(id));
throw new NotImplementedException();
}
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 Task<IEnumerable<UserDTO>> GetSuccesses(int page, int number)
{
throw new NotImplementedException();
}
public UserDTO CreateUser(string username, string password, string email, bool isAdmin)
public Task<UserDTO> GetSuccessByUserId(int id)
{
var newUserEntity = new UserDTO
throw new NotImplementedException();
}
public Task<UserDTO> GetSuccessByInquiryId(int id)
{
Username = username,
Password = password,
Email = email,
IsAdmin = isAdmin
};
DbContext.Users.Add(newUserEntity.FromDTOToModel().FromModelToEntity());
DbContext.SaveChangesAsync();
return newUserEntity;
throw new NotImplementedException();
}
public IEnumerable<InquiryDTO> GetInquiries(int page, int number)
public Task<bool> DeleteSuccess(int id)
{
throw new NotImplementedException();
}
public InquiryDTO GetInquiryById(int id)
public Task<UserDTO> UpdateSuccess(int id, SuccessDTO success)
{
throw new NotImplementedException();
}
public InquiryDTO GetInquiryByTitle(string title)
public Task<UserDTO> CreateSuccess(int userId, int inquiryId, bool isFinished)
{
throw new NotImplementedException();
}

@ -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? 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 index, int count, string? orderingPropertyName = null, object? valueProperty = null);
}
}

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