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

@ -1,93 +0,0 @@
kind: pipeline
type: docker
name: API_SQLuedo
trigger:
event:
- push
steps:
- name: build
image: mcr.microsoft.com/dotnet/sdk:8.0
commands:
- cd API_SQLuedo/
- dotnet restore API_SQLuedo.sln
- dotnet build API_SQLuedo.sln -c Release --no-restore
- name: tests
image: mcr.microsoft.com/dotnet/sdk:8.0
commands:
- cd API_SQLuedo/
- dotnet restore API_SQLuedo.sln
- dotnet test API_SQLuedo.sln -c Release --no-build --no-restore
depends_on: [build]
- name: code-inspection
image: hub.codefirst.iut.uca.fr/marc.chevaldonne/codefirst-dronesonarplugin-dotnet8
secrets: [SECRET_SONAR_LOGIN]
environment:
sonar_host: https://codefirst.iut.uca.fr/sonar/
sonar_token:
from_secret: SECRET_SONAR_LOGIN
project_key: API_SQLuedo
coverage_exclusions: "**/Test*/**,**/*Context*/**,**/Program.cs,**/Migrations/**"
commands:
- cd API_SQLuedo/
- dotnet restore API_SQLuedo.sln
- dotnet sonarscanner begin /k:$${project_key} /d:sonar.host.url=$${sonar_host} /d:sonar.coverageReportPaths="coveragereport/SonarQube.xml" /d:sonar.coverage.exclusions=$${coverage_exclusions} /d:sonar.login=$${sonar_token}
- dotnet build API_SQLuedo.sln -c Release --no-restore
- dotnet test API_SQLuedo.sln --logger trx --no-restore /p:CollectCoverage=true /p:CoverletOutputFormat=cobertura --collect "XPlat Code Coverage"
- reportgenerator -reports:"**/coverage.cobertura.xml" -reporttypes:SonarQube -targetdir:"coveragereport"
- dotnet publish API_SQLuedo.sln -c Release --no-restore -o CI_PROJECT_DIR/build/release
- dotnet sonarscanner end /d:sonar.login=$${sonar_token}
depends_on: [build]
- name: deploy-sqluedo-db
image: hub.codefirst.iut.uca.fr/thomas.bellembois/codefirst-dockerproxy-clientdrone:latest
environment:
IMAGENAME: postgres:16.2
CONTAINERNAME: sqluedo-db
COMMAND: create
OVERWRITE: true
PRIVATE: true
CODEFIRST_CLIENTDRONE_ENV_POSTGRES_USER:
from_secret: db_username
CODEFIRST_CLIENTDRONE_ENV_POSTGRES_PASSWORD:
from_secret: db_password
CODEFIRST_CLIENTDRONE_ENV_POSTGRES_DB:
from_secret: db_database
ADMINS: erwanmenager,maximesapountzis,johnnyratton,victorgaborit,clementchieu
depends_on: [tests]
# Build and push API image
- name: api-image-build-and-push
image: plugins/docker
settings:
dockerfile: API_SQLuedo/API/Dockerfile
context: API_SQLuedo/
registry: hub.codefirst.iut.uca.fr
repo: hub.codefirst.iut.uca.fr/johnny.ratton/api_sqluedo
mirror: https://proxy.iut.uca.fr:8443
username:
from_secret: secret_registry_username
password:
from_secret: secret_registry_password
# Deploy API
- name: deploy-api-from-image
image: hub.codefirst.iut.uca.fr/thomas.bellembois/codefirst-dockerproxy-clientdrone:latest
environment:
IMAGENAME: hub.codefirst.iut.uca.fr/johnny.ratton/api_sqluedo:latest
CONTAINERNAME: sqluedo-api
COMMAND: create
OVERWRITE: true
CODEFIRST_CLIENTDRONE_ENV_DB_HOST:
from_secret: db_host
CODEFIRST_CLIENTDRONE_ENV_DB_USER:
from_secret: db_username
CODEFIRST_CLIENTDRONE_ENV_DB_PASSWORD:
from_secret: db_password
CODEFIRST_CLIENTDRONE_ENV_DB_DATABASE:
from_secret: db_database
ADMINS: erwanmenager,maximesapountzis,johnnyratton,victorgaborit,clementchieu
depends_on: [ api-image-build-and-push, deploy-sqluedo-db ]

3
.gitignore vendored

@ -492,7 +492,8 @@ fabric.properties
.idea/caches/build_file_checksums.ser
# Fichier db
# Migrations et fichiers db
**/Migrations/**
*.db
/**/.idea/

@ -1,30 +0,0 @@
**/.classpath
**/.dockerignore
**/.env
**/.git
**/.gitignore
**/.project
**/.settings
**/.toolstarget
**/.vs
**/.vscode
**/*.*proj.user
**/*.dbmdl
**/*.jfm
**/azds.yaml
**/bin
**/charts
**/docker-compose*
**/Dockerfile*
**/node_modules
**/npm-debug.log
**/obj
**/secrets.dev.yaml
**/values.dev.yaml
LICENSE
README.md
!**/.gitignore
!.git/HEAD
!.git/config
!.git/packed-refs
!.git/refs/heads/**

@ -8,30 +8,24 @@
</PropertyGroup>
<ItemGroup>
<PackageReference Include="Asp.Versioning.Mvc" Version="8.0.0" />
<PackageReference Include="Asp.Versioning.Mvc.ApiExplorer" Version="8.0.0" />
<PackageReference Include="Microsoft.AspNetCore.Identity.EntityFrameworkCore" Version="8.0.2" />
<PackageReference Include="Microsoft.EntityFrameworkCore" Version="8.0.2" />
<PackageReference Include="Microsoft.EntityFrameworkCore.Design" Version="8.0.2">
<PackageReference Include="Microsoft.AspNetCore.Identity.EntityFrameworkCore" Version="8.0.1" />
<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.InMemory" Version="8.0.2" />
<PackageReference Include="Microsoft.EntityFrameworkCore.Tools" Version="8.0.2">
<PackageReference Include="Microsoft.EntityFrameworkCore.InMemory" Version="8.0.1" />
<PackageReference Include="Microsoft.EntityFrameworkCore.Tools" Version="8.0.1">
<PrivateAssets>all</PrivateAssets>
<IncludeAssets>runtime; build; native; contentfiles; analyzers; buildtransitive</IncludeAssets>
</PackageReference>
<PackageReference Include="Newtonsoft.Json" Version="13.0.3" />
<PackageReference Include="Npgsql.EntityFrameworkCore.PostgreSQL" Version="8.0.0" />
<PackageReference Include="Swashbuckle.AspNetCore" Version="6.5.0" />
<PackageReference Include="Swashbuckle.AspNetCore" Version="6.4.0" />
</ItemGroup>
<ItemGroup>
<ProjectReference Include="..\DbContextLib\DbContextLib.csproj" />
<ProjectReference Include="..\Dto\Dto.csproj" />
<ProjectReference Include="..\DbDataManager\DbDataManager.csproj" />
<ProjectReference Include="..\Shared\Shared.csproj" />
<ProjectReference Include="..\StubbedContextLib\StubbedContextLib.csproj" />
<ProjectReference Include="..\ModelToEntity\ModelToEntity.csproj" />
<ProjectReference Include="..\Services\Services.csproj" />
</ItemGroup>
</Project>

@ -1,94 +0,0 @@
using Asp.Versioning;
using Dto;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using Model.OrderCriteria;
using Shared;
namespace API.Controllers;
[Route("api/v{version:apiVersion}/[controller]")]
[Authorize]
[ApiVersion("1.0")]
[ApiController]
public class BlackListController(ILogger<UsersController> logger, IBlackListService<BlackListDto> blackListService)
: ControllerBase
{
[HttpGet("user/ban/{page:int}/{number:int}")]
[ProducesResponseType(typeof(IEnumerable<BlackListDto>), 200)]
[ProducesResponseType(typeof(string), 204)]
public IActionResult GetBannedUsers(int page, int number, BlackListOdrerCriteria orderCriteria)
{
var users = blackListService.GetBannedUsers(page, number, orderCriteria).ToList();
if (users.Count == 0)
{
logger.LogError("[ERREUR] Aucun email banni trouvé.");
return StatusCode(204);
}
logger.LogInformation("[INFORMATION] {nb} Email(s) banni(s) trouvé(s)", users.Count);
return Ok(users);
}
[HttpGet("user/ban/number")]
[ProducesResponseType(typeof(UserDto), 200)]
[ProducesResponseType(typeof(string), 204)]
public IActionResult GetNumberOfBannedUsers()
{
var nb = blackListService.GetNumberOfBannedUsers();
logger.LogInformation("[INFORMATION] {nb} Email(s) banni(s) trouvé(s)", nb);
return Ok(new KeyValuePair<string,int>("number",nb));
}
[HttpPost("user/ban")]
[ProducesResponseType(typeof(UserDto), 200)]
[ProducesResponseType(typeof(string), 404)]
public IActionResult GetUserBannedByEmail([FromBody] string email)
{
var res = blackListService.GetUserBannedByEmail(email);
if (res != null)
{
logger.LogInformation("[INFORMATION] Utilisateur banni avec l'email {email} a été trouvé.", email);
return Ok(res);
}
logger.LogError("[ERREUR] Aucun utilisateur banni trouvé avec l'email {email}.", email);
return NotFound("Utilisateur non trouvé !");
}
[HttpDelete("user/ban/{username:alpha}")]
[ProducesResponseType(typeof(UserDto), 200)]
[ProducesResponseType(typeof(string), 404)]
public IActionResult BanUser(string username)
{
var success = blackListService.BanUser(username);
if (success)
{
logger.LogInformation("[INFORMATION] L'utilisateur avec le pseudo {username} a été banni pour 2 ans.", username);
return Ok(new KeyValuePair<string,bool>("success", true));
}
else
{
logger.LogError("[ERREUR] Aucun utilisateur trouvé avec le pseudo {username}.", username);
return NotFound();
}
}
[HttpPost("user/unban")]
[ProducesResponseType(typeof(UserDto), 200)]
[ProducesResponseType(typeof(string), 404)]
public IActionResult UnbanUser([FromBody] string email)
{
var success = blackListService.UnbanUser(email);
if (success)
{
logger.LogInformation("[INFORMATION] L'utilisateur avec l'email {email} a été débanni.", email);
return Ok(new KeyValuePair<string,bool>("success", true));
}
else
{
logger.LogError("[ERREUR] Aucun utilisateur banni trouvé avec l'email {email}.", email);
return NotFound();
}
}
}

@ -1,149 +0,0 @@
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using Dto;
using Model.OrderCriteria;
using Shared;
using Asp.Versioning;
namespace API.Controllers;
[Route("api/v{version:apiVersion}/[controller]")]
[Authorize]
[ApiVersion("1.0")]
[ApiController]
public class InquiriesController : Controller
{
private readonly IInquiryService<InquiryDto> _inquiryDataService;
private readonly ILogger<InquiriesController> _logger;
public InquiriesController(IInquiryService<InquiryDto> inquiryDataService, ILogger<InquiriesController> logger)
{
_inquiryDataService = inquiryDataService;
_logger = logger;
}
[HttpGet("inquiries/{page:int}/{number:int}/{orderCriteria}")]
[ProducesResponseType(typeof(InquiryDto), 200)]
[ProducesResponseType(typeof(string), 204)]
public IActionResult GetInquiries(int page, int number, InquiryOrderCriteria orderCriteria)
{
var nbInquiry = _inquiryDataService.GetInquiries(page, number, orderCriteria).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(_inquiryDataService.GetInquiries(page, number, orderCriteria));
}
[HttpGet("inquiry/{id:int}")]
[ProducesResponseType(typeof(InquiryDto), 200)]
[ProducesResponseType(typeof(string), 404)]
public IActionResult GetInquiryById(int id)
{
try
{
_logger.LogInformation("[INFORMATION] L'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:alpha}")]
[ProducesResponseType(typeof(InquiryDto), 200)]
[ProducesResponseType(typeof(string), 404)]
public IActionResult GetInquiryByTitle(string title)
{
try
{
_logger.LogInformation("[INFORMATION] L'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();
}
}
[HttpDelete("inquiry/{id:int}")]
[ProducesResponseType(typeof(InquiryDto), 200)]
[ProducesResponseType(typeof(string), 404)]
public IActionResult DeleteInquiry(int id)
{
var success = _inquiryDataService.DeleteInquiry(id);
if (success)
{
_logger.LogInformation("[INFORMATION] L'enquête avec l'id {id} a été supprimé.", id);
return Ok(_inquiryDataService.DeleteInquiry(id));
}
else
{
_logger.LogError("[ERREUR] Aucune enquête trouvée avec l'id {id}.", id);
return NotFound();
}
}
[HttpPost]
[ProducesResponseType(typeof(InquiryDto), 201)]
[ProducesResponseType(typeof(string), 400)]
public IActionResult CreateInquiry([FromBody] InquiryDto dto)
{
if (dto.Title == null || dto.Description == null)
{
return BadRequest();
}
_logger.LogInformation(
"[INFORMATION] Une enquête a été créé : title - {title}, description - {description}, isUser - {isUser}",
dto.Title, dto.Description, dto.IsUser);
return Created(nameof(GetInquiries),
_inquiryDataService.CreateInquiry(dto.Title, dto.Description, dto.IsUser));
}
[HttpPut("inquiry/{id:int}")]
[ProducesResponseType(typeof(InquiryDto), 200)]
[ProducesResponseType(typeof(string), 400)]
[ProducesResponseType(typeof(string), 404)]
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(_inquiryDataService.UpdateInquiry(id, InquiryDto));
}
_logger.LogError("[ERREUR] Aucune enquête trouvée avec l'id {id}.", id);
return NotFound();
}
[HttpGet("inquiries/number")]
[ProducesResponseType(typeof(InquiryDto), 200)]
[ProducesResponseType(typeof(string), 204)]
public IActionResult GetNumberOfInquiries()
{
var nbInquiry = _inquiryDataService.GetNumberOfInquiries();
_logger.LogInformation("[INFORMATION] {nb} Enquête(s) trouvée(s)", nbInquiry);
return Ok(new KeyValuePair<string, int>("nbInquiries", nbInquiry));
}
}

@ -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();
}
}
}

@ -1,42 +0,0 @@
using Asp.Versioning;
using Dto;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Http.HttpResults;
using Microsoft.AspNetCore.Mvc;
using Shared;
namespace API.Controllers;
[Route("api/v{version:apiVersion}/[controller]")]
[Authorize]
[ApiVersion("1.0")]
[ApiController]
public class InquiryTableController : Controller
{
private readonly IInquiryTableService<InquiryTableDto> _inquiryTableService;
private readonly ILogger<InquiryTableController> _logger;
public InquiryTableController(IInquiryTableService<InquiryTableDto> inquiryTableService, ILogger<InquiryTableController> logger)
{
_inquiryTableService = inquiryTableService;
_logger = logger;
}
[HttpGet("database/{id:int}")]
[ProducesResponseType(typeof(string), 200)]
[ProducesResponseType(typeof(string), 404)]
public IActionResult GetDatabaseNameByInquiryById(int id)
{
try
{
_logger.LogInformation("[INFORMATION] La base de données pour l'enquête avec l'id {id} a été trouvé.", id);
return Ok(_inquiryTableService.GetDatabaseNameByInquiryId(id));
}
catch (ArgumentException)
{
_logger.LogError("[ERREUR] Aucune base de données trouvée pour l'enquête 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,172 +0,0 @@
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using Dto;
using Model.OrderCriteria;
using Shared;
using Asp.Versioning;
namespace API.Controllers;
[Route("api/v{version:apiVersion}/[controller]")]
[Authorize]
[ApiVersion("1.0")]
[ApiController]
public class LessonsController : Controller
{
private readonly ILessonService<LessonDto> _lessonDataService;
private readonly ILogger<LessonsController> _logger;
public LessonsController(ILessonService<LessonDto> lessonDataService, ILogger<LessonsController> logger)
{
_lessonDataService = lessonDataService;
_logger = logger;
}
[HttpGet("lessons/{page:int}/{number:int}/{orderCriteria}")]
[ProducesResponseType(typeof(LessonDto), 200)]
[ProducesResponseType(typeof(string), 204)]
public IActionResult GetLessons(int page, int number, LessonOrderCriteria orderCriteria)
{
var nbLesson = _lessonDataService.GetLessons(page, number, orderCriteria).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(_lessonDataService.GetLessons(page, number, orderCriteria));
}
[HttpGet("lessons/number")]
[ProducesResponseType(typeof(LessonDto), 200)]
[ProducesResponseType(typeof(string), 204)]
public IActionResult GetNumberOfLessons()
{
var nbLesson = _lessonDataService.GetNumberOfLessons();
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(new KeyValuePair<string,int>("nbLessons", nbLesson));
}
[HttpGet("lesson/{id:int}")]
[ProducesResponseType(typeof(LessonDto), 200)]
[ProducesResponseType(typeof(string), 404)]
public IActionResult GetLessonById(int id)
{
try
{
_logger.LogInformation("[INFORMATION] La leçon avec l'id {id} a été trouvé.", id);
return Ok(_lessonDataService.GetLessonById(id));
}
catch (ArgumentException)
{
_logger.LogError("[ERREUR] Aucune leçon trouvée avec l'id {id}.", id);
return NotFound();
}
}
[HttpGet("lesson/{title:alpha}")]
[ProducesResponseType(typeof(LessonDto), 200)]
[ProducesResponseType(typeof(string), 404)]
public IActionResult GetLessonByTitle(string title)
{
try
{
_logger.LogInformation("[INFORMATION] La leçon avec le titre {title} a été trouvé.", title);
return Ok(_lessonDataService.GetLessonByTitle(title));
}
catch (ArgumentException)
{
_logger.LogError("[ERREUR] Aucune leçon trouvée avec le titre {title}.", title);
return NotFound();
}
}
[HttpDelete("lesson/{id:int}")]
[ProducesResponseType(typeof(LessonDto), 200)]
[ProducesResponseType(typeof(string), 404)]
public IActionResult DeleteLesson(int id)
{
var success = _lessonDataService.DeleteLesson(id);
if (success)
{
_logger.LogInformation("[INFORMATION] La leçon avec l'id {id} a été supprimé.", id);
return Ok(_lessonDataService.DeleteLesson(id));
}
else
{
_logger.LogError("[ERREUR] Aucune leçon trouvée avec l'id {id}.", id);
return NotFound();
}
}
[HttpPost]
[ProducesResponseType(typeof(LessonDto), 201)]
[ProducesResponseType(typeof(string), 400)]
[ProducesResponseType(typeof(string), 500)]
public IActionResult CreateLesson([FromBody] LessonDto dto)
{
if (dto.Title == null || dto.LastPublisher == null)
{
return BadRequest();
}
try
{
var createdLesson = _lessonDataService.CreateLesson(dto.Id, dto.Title, dto.LastPublisher,
dto.LastEdit ?? DateOnly.FromDateTime(DateTime.Now));
if (createdLesson != null)
{
_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), createdLesson);
}
else
{
return StatusCode(500);
}
}
catch (ArgumentException e)
{
_logger.LogError("[ERREUR] " + e.Message);
return Created();
}
}
[HttpPut("lesson/{id:int}")]
[ProducesResponseType(typeof(LessonDto), 200)]
[ProducesResponseType(typeof(string), 400)]
[ProducesResponseType(typeof(string), 404)]
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(_lessonDataService.UpdateLesson(id, LessonDto));
}
_logger.LogError("[ERREUR] Aucune leçon trouvée avec l'id {id}.", id);
return NotFound();
}
}

@ -1,97 +0,0 @@
using Asp.Versioning;
using Dto;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using Shared;
namespace API.Controllers;
[Route("api/v{version:apiVersion}/[controller]")]
[Authorize]
[ApiVersion("1.0")]
[ApiController]
public class NotepadController : Controller
{
private readonly INotepadService<NotepadDto> _notepadDataService;
private readonly ILogger<NotepadController> _logger;
public NotepadController(INotepadService<NotepadDto> notepadService, ILogger<NotepadController> logger)
{
_notepadDataService = notepadService;
_logger = logger;
}
[HttpGet("notepad/{userId:int}/{inquiryId:int}")]
[ProducesResponseType(typeof(NotepadDto), 200)]
[ProducesResponseType(typeof(void), 404)]
public IActionResult GetNotepadByUserAndInquiryById(int userId, int inquiryId)
{
try
{
_logger.LogInformation(
"[INFORMATION] Le bloc-notes de l'utilisateur avec l'id {id} et l'enquête avec l'id {idInquiry} a été trouvé.",
userId, inquiryId);
return Ok(_notepadDataService.GetNotepadFromUserAndInquiryId(userId,inquiryId));
}
catch (ArgumentException)
{
_logger.LogError(
"[ERREUR] Aucun bloc-notes trouvé pour l'utilisateur avec l'id {id} et l'enquête avec l'id {inquiryId}.",
userId, inquiryId);
return NotFound();
}
}
[HttpPost("notepad")]
[ProducesResponseType(typeof(void), 200)]
[ProducesResponseType(typeof(void), 404)]
public IActionResult SetNotepadByUserAndInquiryById([FromBody] NotepadDto notepad)
{
try
{
if (notepad.InquiryId < 0 || notepad.UserId < 0 || notepad.Notes == null)
{
return BadRequest();
}
_notepadDataService.SetNotepadFromUserAndInquiryId(notepad.UserId, notepad.InquiryId, notepad.Notes);
_logger.LogInformation(
"[INFORMATION] Le bloc-notes de l'utilisateur avec l'id {id} et l'enquête avec l'id {idInquiry} a été créé.",
notepad.UserId, notepad.InquiryId);
return Ok();
}
catch (ArgumentException)
{
_logger.LogError(
"[ERREUR] Aucun bloc-notes n'a pu être créé pour l'utilisateur avec l'id {id} et l'enquête avec l'id {inquiryId}.",
notepad.UserId, notepad.InquiryId);
return NotFound();
}
}
[HttpPut("notepad")]
[ProducesResponseType(typeof(void), 203)]
[ProducesResponseType(typeof(void), 404)]
public IActionResult UpdateNotepadByUserAndInquiryById([FromBody] NotepadDto notepad)
{
try
{
if (notepad.InquiryId < 0 || notepad.UserId < 0 || notepad.Notes == null)
{
return BadRequest();
}
_notepadDataService.UpdateNotepadFromUserAndInquiryId(notepad.UserId, notepad.InquiryId, notepad.Notes);
_logger.LogInformation(
"[INFORMATION] Le bloc-notes de l'utilisateur avec l'id {id} et l'enquête avec l'id {idInquiry} a été mis à jour.",
notepad.UserId, notepad.InquiryId);
return Ok();
}
catch (ArgumentException)
{
_logger.LogError(
"[ERREUR] Aucun bloc-notes n'a pu être mis à jour pour l'utilisateur avec l'id {id} et l'enquête avec l'id {inquiryId}.",
notepad.UserId, notepad.InquiryId);
return NotFound();
}
}
}

@ -1,160 +0,0 @@
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using Dto;
using Model.OrderCriteria;
using Shared;
using Asp.Versioning;
namespace API.Controllers;
[Route("api/v{version:apiVersion}/[controller]")]
[Authorize]
[ApiVersion("1.0")]
[ApiController]
public class ParagraphsController : Controller
{
private readonly IParagraphService<ParagraphDto> _paragraphDataService;
private readonly ILogger<ParagraphsController> _logger;
public ParagraphsController(IParagraphService<ParagraphDto> paragraphDataService,
ILogger<ParagraphsController> logger)
{
_paragraphDataService = paragraphDataService;
_logger = logger;
}
[HttpGet("paragraphs/{page:int}/{number:int}/{orderCriteria}")]
[ProducesResponseType(typeof(ParagraphDto), 200)]
[ProducesResponseType(typeof(string), 204)]
public IActionResult GetParagraphs(int page, int number, ParagraphOrderCriteria orderCriteria)
{
var nbParagraph = _paragraphDataService.GetParagraphs(page, number, orderCriteria).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, orderCriteria));
}
[HttpGet("paragraphs/lesson/{id:int}")]
[ProducesResponseType(typeof(IEnumerable<ParagraphDto>), 200)]
[ProducesResponseType(typeof(string), 204)]
public IActionResult GetParagraphsByLessonId(int id)
{
var paragraphs = _paragraphDataService.GetParagraphsByLessonId(id);
if (paragraphs.Count() == 0)
{
_logger.LogError("[ERREUR] Aucun paragraphe trouvé.");
return StatusCode(204);
}
_logger.LogInformation("[INFORMATION] {nb} Paragraphe(s) trouvé(s)", paragraphs.Count());
return Ok(paragraphs);
}
[HttpGet("paragraph/{id:int}")]
[ProducesResponseType(typeof(ParagraphDto), 200)]
[ProducesResponseType(typeof(string), 404)]
public 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:alpha}")]
[ProducesResponseType(typeof(ParagraphDto), 200)]
[ProducesResponseType(typeof(string), 404)]
public IActionResult GetParagraphByTitle(string title)
{
try
{
_logger.LogInformation("[INFORMATION] Le paragraphe avec le titre {title} a été trouvé.", title);
return Ok(_paragraphDataService.GetParagraphByTitle(title));
}
catch (ArgumentException)
{
_logger.LogError("[ERREUR] Aucun paragraphe trouvé avec le titre {title}.", title);
return NotFound();
}
}
[HttpDelete("paragraph/{id:int}")]
[ProducesResponseType(typeof(ParagraphDto), 200)]
[ProducesResponseType(typeof(string), 404)]
public IActionResult DeleteParagraph(int id)
{
var success = _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]
[ProducesResponseType(typeof(ParagraphDto), 201)]
[ProducesResponseType(typeof(string), 400)]
public IActionResult CreateParagraph([FromBody] ParagraphDto dto)
{
if (dto.ContentTitle == null || dto.ContentContent == null || 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.ContentTitle, dto.ContentContent, dto.Title, dto.Content,
dto.Info, dto.Query, dto.Comment,
dto.LessonId));
}
[HttpPut("paragraph/{id:int}")]
[ProducesResponseType(typeof(ParagraphDto), 200)]
[ProducesResponseType(typeof(string), 400)]
[ProducesResponseType(typeof(string), 404)]
public 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();
}
}

@ -1,65 +0,0 @@
using Dto;
using Asp.Versioning;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using Shared;
using Model.OrderCriteria;
namespace API.Controllers
{
[Route("api/v{version:apiVersion}/[controller]")]
[Authorize]
[ApiVersion("1.0")]
[ApiController]
public class QueryController(ILogger<QueryController> logger, IQueryService<QueryDto> queryService) : ControllerBase
{
[HttpPost("{database}/execute")]
[ProducesResponseType(typeof(QueryDto), 200)]
[ProducesResponseType(typeof(string), 204)]
public IActionResult ExecuteQuery([FromBody]string query, string database)
{
var queryResult = queryService.ExecuteQuery(query, database);
if (queryResult == null)
{
logger.LogError("[ERREUR] La requête n'a rien renvoyé.");
return StatusCode(204);
}
logger.LogInformation("[INFORMATION] La requête a renvoyé : {result} ", queryResult);
return Content(queryResult.Result, "application/json");
}
[HttpGet("{database}/Tables")]
[ProducesResponseType(typeof(QueryDto), 200)]
[ProducesResponseType(typeof(string), 204)]
public IActionResult GetTables(string database)
{
var queryResult = queryService.GetTables(database);
if (queryResult == null)
{
logger.LogError("[ERREUR] La requête n'a rien renvoyé.");
return StatusCode(204);
}
logger.LogInformation("[INFORMATION] La requête a renvoyé : {result} ", queryResult);
return Content(queryResult.Result, "application/json");
}
[HttpGet("{database}/{table}/Columns")]
[ProducesResponseType(typeof(QueryDto), 200)]
[ProducesResponseType(typeof(string), 204)]
public IActionResult GetColumns(string database,string table)
{
var queryResult = queryService.GetColumns(database,table);
if (queryResult == null)
{
logger.LogError("[ERREUR] La requête n'a rien renvoyé.");
return StatusCode(204);
}
logger.LogInformation("[INFORMATION] La requête a renvoyé : {result} ", queryResult);
return Content(queryResult.Result, "application/json");
}
}
}

@ -1,43 +0,0 @@
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using Dto;
using Model.OrderCriteria;
using Shared;
using Asp.Versioning;
namespace API.Controllers
{
[Route("api/v{version:apiVersion}/[controller]")]
[Authorize]
[ApiVersion("1.0")]
[ApiController]
public class SolutionController : Controller
{
private readonly ISolutionService<SolutionDto> _solutionDataService;
private readonly ILogger<SolutionController> _logger;
public SolutionController(ISolutionService<SolutionDto> solutionDataService, ILogger<SolutionController> logger)
{
_solutionDataService = solutionDataService;
_logger = logger;
}
[HttpGet("solution/{id:int}")]
[ProducesResponseType(typeof(SolutionDto), 200)]
[ProducesResponseType(typeof(string), 404)]
public IActionResult GetSolutionByInquiryById(int id)
{
try
{
_logger.LogInformation("[INFORMATION] L'enquête avec l'id {id} a été trouvé.", id);
return Ok(_solutionDataService.GetSolutionByInquiryId(id));
}
catch (ArgumentException)
{
_logger.LogError("[ERREUR] Aucune enquête trouvée avec l'id {id}.", id);
return NotFound();
}
}
}
}

@ -1,206 +0,0 @@
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using Dto;
using Model.OrderCriteria;
using Shared;
using Asp.Versioning;
namespace API.Controllers;
[Route("api/v{version:apiVersion}/[controller]")]
[Authorize]
[ApiVersion("1.0")]
[ApiController]
public class SuccessesController : Controller
{
private readonly ISuccessService<SuccessDto> _successDataService;
private readonly ILogger<SuccessesController> _logger;
public SuccessesController(ISuccessService<SuccessDto> successDataService, ILogger<SuccessesController> logger)
{
_successDataService = successDataService;
_logger = logger;
}
[HttpGet("successes/{page:int}/{number:int}/{orderCriteria}")]
[ProducesResponseType(typeof(SuccessDto), 200)]
[ProducesResponseType(typeof(string), 204)]
[ProducesResponseType(typeof(string), 400)]
public IActionResult GetSuccesses(int page, int number, SuccessOrderCriteria orderCriteria)
{
if (page < 1 || number < 1)
{
_logger.LogError("[ERREUR] La page ou le nombre de succès est inférieur à 1.");
return BadRequest("La page ou le nombre de succès est inférieur à 1.");
}
var nbUser = _successDataService.GetSuccesses(page, number, orderCriteria).ToList().Count;
if (nbUser == 0)
{
_logger.LogError("[ERREUR] Aucun Succès trouvé.");
return StatusCode(204);
}
_logger.LogInformation("[INFORMATION] {nb} Succès(s) trouvé(s)", nbUser);
return Ok(_successDataService.GetSuccesses(page, number, orderCriteria));
}
[HttpGet("success/user/{id:int}")]
[ProducesResponseType(typeof(SuccessDto), 200)]
[ProducesResponseType(typeof(string), 404)]
public IActionResult GetSuccessByUserId(int id)
{
if (id < 1)
{
_logger.LogError("[ERREUR] L'id de l'utilisateur est inférieur à 1.");
return BadRequest("L'id de l'utilisateur est inférieur à 1.");
}
try
{
_logger.LogInformation("[INFORMATION] Le succès avec l'id de l'utilisateur {id} a été trouvé.", id);
return Ok(_successDataService.GetSuccessesByUserId(id));
}
catch (ArgumentException)
{
_logger.LogError("[ERREUR] Aucun utilisateur trouvé avec l'id de l'utilisateur {id}.", id);
return NotFound("Aucun utilisateur trouvé avec l'id de l'utilisateur.");
}
}
[HttpGet("success/inquiry/{id:int}")]
[ProducesResponseType(typeof(SuccessDto), 200)]
[ProducesResponseType(typeof(string), 404)]
public IActionResult GetSuccessByInquiryId(int id)
{
if (id < 1)
{
_logger.LogError("[ERREUR] L'id de l'enquête doit être inférieur à 1.");
return BadRequest("L'id de l'enquête doit être inférieur à 1.");
}
try
{
_logger.LogInformation("[INFORMATION] Utilisateur avec l'id de l'enquête {inquiryId} a été trouvé.",
id);
return Ok(_successDataService.GetSuccessesByInquiryId(id));
}
catch (ArgumentException)
{
_logger.LogError("[ERREUR] Aucun utilisateur trouvé avec l'id de l'enquête {inquiryId}.", id);
return NotFound("Aucune enquête trouvée avec l'id de l'enquête.");
}
}
[HttpDelete("success/{idUser:int}/{idInquiry:int}")]
[ProducesResponseType(typeof(SuccessDto), 200)]
[ProducesResponseType(typeof(string), 404)]
public IActionResult DeleteSuccess(int idUser, int idInquiry)
{
if (idUser < 1 || idInquiry < 1)
{
_logger.LogInformation("[INFORMATION] L'id de l'utilisateur ou de l'enquête doit être supérieur à 1.");
return BadRequest("L'id de l'utilisateur ou de l'enquête doit être supérieur à 1.");
}
var success = _successDataService.DeleteSuccess(idUser, idInquiry);
if (success)
{
_logger.LogInformation("[INFORMATION] Le succès avec l'id {id} a été supprimé.", idUser);
return Ok(success);
}
else
{
_logger.LogError("[ERREUR] Aucun succès trouvé avec l'id {id}.", idUser);
return NotFound();
}
}
[HttpPost]
[ProducesResponseType(typeof(SuccessDto), 201)]
[ProducesResponseType(typeof(string), 409)]
[ProducesResponseType(typeof(string), 404)]
[ProducesResponseType(typeof(string), 400)]
public IActionResult CreateSuccess([FromBody] SuccessDto dto)
{
if (dto.UserId < 1 || dto.InquiryId < 1)
{
_logger.LogError("[ERREUR] L'id de l'utilisateur ou de l'enquête doit être supérieur à 1.");
return BadRequest("L'id de l'utilisateur ou de l'enquête doit être supérieur à 1.");
}
try
{
var s = _successDataService.CreateSuccess(dto.UserId, dto.InquiryId, dto.IsFinished);
_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), s);
}
catch (Exception e)
{
return HandleError(e);
}
}
[HttpPut("success/{idUser:int}/{idInquiry:int}")]
[ProducesResponseType(typeof(SuccessDto), 200)]
[ProducesResponseType(typeof(string), 400)]
[ProducesResponseType(typeof(string), 404)]
public IActionResult UpdateSuccess(int idUser, int idInquiry, [FromBody] SuccessDto successDto)
{
if (idUser < 1 || idInquiry < 1)
{
_logger.LogError("[ERREUR] L'id de l'utilisateur ou de l'enquête doit être supérieur à 1.");
return BadRequest("L'id de l'utilisateur ou de l'enquête doit être supérieur à 1.");
}
if (idUser != successDto.UserId || idInquiry != successDto.InquiryId)
{
_logger.LogError(
"[ERREUR] Problème ID - La mise à jour du succès avec l'id de l'utilisateur {id} a échouée.",
idUser);
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.",
idUser);
return BadRequest();
}
try
{
var s = _successDataService.UpdateSuccess(idUser, idInquiry, successDto);
_logger.LogInformation(
"[INFORMATION] La mise à jour du succès avec l'id de l'utilisateur {id} a été effectuée", idUser);
return Ok(s);
}
catch (Exception e)
{
return HandleError(e);
}
}
private IActionResult HandleError(Exception e)
{
switch (e.Message)
{
case { } msg when msg.Contains("userId"):
_logger.LogError("[ERREUR] Impossible de trouver l'utilisateur pour la manipulation du succès");
return NotFound("Impossible de trouver l'utilisateur pour la manipulation du succès");
case { } msg when msg.Contains("inquiryId"):
_logger.LogError("[ERREUR] Impossible de trouver l'enquête pour la manipulation du succès");
return NotFound("Impossible de trouver l'enquête pour la manipulation du succès");
case { } msg when msg.Contains("success"):
_logger.LogError("[ERREUR] Impossible de manipuler le succès car il n'existe pas");
return Conflict("Impossible de manipuler le succès car il n'existe pas");
default:
_logger.LogError("[ERREUR] Erreur inattendue, impossible de manipuler le succès");
return BadRequest("Erreur inattendue, impossible de manipuler le succès");
}
}
}

@ -1,234 +1,120 @@
using Dto;
using Asp.Versioning;
using DbContextLib;
using Entities.SQLudeoDB;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Shared;
using Model.OrderCriteria;
using Model;
using Model.Business;
using Model.DTO;
using Model.Mappers;
using Services;
namespace API.Controllers;
[Route("api/v{version:apiVersion}/[controller]")]
[Authorize]
[ApiVersion("1.0")]
[ApiController]
public class UsersController(ILogger<UsersController> logger, IUserService<UserDto> userService) : ControllerBase
namespace API.Controllers
{
[HttpGet("users/{page:int}/{number:int}")]
[ProducesResponseType(typeof(UserDto), 200)]
[ProducesResponseType(typeof(string), 204)]
public IActionResult GetUsers(int page, int number, UserOrderCriteria orderCriteria)
[Route("api/[controller]")]
[Authorize]
[ApiController]
public class UserController : Controller
{
var users = userService.GetUsers(page, number, orderCriteria).ToList();
if (users.Count == 0)
{
logger.LogError("[ERREUR] Aucun utilisateur trouvé.");
return StatusCode(204);
}
private IDataService<UserDTO?> _dataService;
logger.LogInformation("[INFORMATION] {nb} Utilisateur(s) trouvé(s)", users.Count);
return Ok(users);
}
private readonly ILogger<UserController> _logger;
[HttpGet("users/not-admin/{page:int}/{number:int}")]
[ProducesResponseType(typeof(UserDto), 200)]
[ProducesResponseType(typeof(string), 204)]
public IActionResult GetNotAdminUsers(int page, int number, UserOrderCriteria orderCriteria)
{
var users = userService.GetNotAdminUsers(page, number, orderCriteria).ToList();
if (users.Count == 0)
public UserController(IDataService<UserDTO?> dataService, ILogger<UserController> logger)
{
logger.LogError("[ERREUR] Aucun utilisateur trouvé.");
return StatusCode(204);
_dataService = dataService;
_logger = logger;
}
logger.LogInformation("[INFORMATION] {nb} Utilisateur(s) trouvé(s)", users.Count);
return Ok(users);
}
[HttpGet("users/number")]
[ProducesResponseType(typeof(UserDto), 200)]
[ProducesResponseType(typeof(string), 204)]
public IActionResult GetNumberOfUsers()
{
var users = userService.GetNumberOfUsers();
if (users == 0)
[HttpGet("users/{page}/{number}")]
public async Task<IActionResult> GetUsers(int page, int number)
{
logger.LogError("[ERREUR] Aucun utilisateur trouvé.");
return StatusCode(204);
var nbUser = (await _dataService.UserService.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(_dataService.UserService.GetItems<UserEntity>(page, number));
}
logger.LogInformation("[INFORMATION] {users} Utilisateur(s) trouvé(s)", users);
return Ok(new KeyValuePair<string, int>("nbUsers", users));
}
[HttpGet("user/{id:int}")]
[ProducesResponseType(typeof(UserDto), 200)]
[ProducesResponseType(typeof(string), 404)]
public IActionResult GetUserById(int id)
{
try
{
logger.LogInformation("[INFORMATION] Utilisateur avec l'id {id} a été trouvé.", id);
return Ok(userService.GetUserById(id));
}
catch (ArgumentException)
[HttpGet("user/id/{id}")]
public async Task<IActionResult> GetUserById(int id)
{
logger.LogError("[ERREUR] Aucun utilisateur trouvé avec l'id {id}.", id);
return NotFound();
try
{
_logger.LogInformation("[INFORMATION] Utilisateur avec l'id {id} a été trouvé.", id);
return Ok(_dataService.UserService.GetItems<UserEntity>(1, 1, UserProperty.Id.ToString(),id));
} catch (ArgumentException)
{
_logger.LogError("[ERREUR] Aucun utilisateur trouvé avec l'id {id}.", id);
return NotFound();
}
}
}
[HttpGet("user/{username:alpha}")]
[ProducesResponseType(typeof(UserDto), 200)]
[ProducesResponseType(typeof(string), 404)]
public IActionResult GetUserByUsername(string username)
{
try
[HttpGet("user/username/{username}")]
public async Task<IActionResult> GetUserByUsername(string username)
{
logger.LogInformation("[INFORMATION] Utilisateur avec l'username {username} a été trouvé.", username);
return Ok(userService.GetUserByUsername(username));
}
catch (ArgumentException)
{
logger.LogError("[ERREUR] Aucun utilisateur trouvé avec l'username {username}.", username);
return NotFound("Utilisateur non trouvé !");
}
}
try
{
_logger.LogInformation("[INFORMATION] Utilisateur avec l'username {username} a été trouvé.", username);
return Ok(_dataService.UserService.GetItems<UserEntity>(1, 1,UserProperty.Username.ToString(), username));
}catch (ArgumentException)
{
_logger.LogError("[ERREUR] Aucun utilisateur trouvé avec l'username {username}.", username);
return NotFound();
}
[HttpGet("user/email/{email}")]
[ProducesResponseType(typeof(UserDto), 200)]
[ProducesResponseType(typeof(string), 404)]
public IActionResult GetByEmail(string email)
{
try
{
logger.LogInformation("[INFORMATION] Utilisateur avec l'username {email} a été trouvé.", email);
return Ok(userService.GetUserByEmail(email));
}
catch (ArgumentException)
{
logger.LogError("[ERREUR] Aucun utilisateur trouvé avec l'username {email}.", email);
return NotFound();
}
}
[HttpDelete("user/{id:int}")]
[ProducesResponseType(typeof(UserDto), 200)]
[ProducesResponseType(typeof(string), 404)]
public IActionResult DeleteUser(int id)
{
var success = userService.DeleteUser(id);
if (success)
[HttpDelete]
public async Task<IActionResult> DeleteUser(int id)
{
logger.LogInformation("[INFORMATION] L'utilisateur avec l'id {id} a été supprimé.", id);
return Ok();
}
else
{
logger.LogError("[ERREUR] Aucun utilisateur trouvé avec l'id {id}.", id);
return NotFound();
}
}
[HttpDelete("user/username/{username:alpha}")]
[ProducesResponseType(typeof(UserDto), 200)]
[ProducesResponseType(typeof(string), 404)]
public IActionResult DeleteUserByUsername(string username)
{
var success = userService.DeleteUserByUsername(username);
if (success)
{
logger.LogInformation("[INFORMATION] L'utilisateur avec le pseudo {username} a été supprimé.",
username);
return Ok();
}
else
{
logger.LogError("[ERREUR] Aucun utilisateur trouvé avec le pseudo {username}.", username);
return NotFound();
}
}
[HttpPost]
[ProducesResponseType(typeof(UserDto), 201)]
[ProducesResponseType(typeof(string), 400)]
[ProducesResponseType(typeof(string), 409)]
[ProducesResponseType(typeof(string), 410)]
public IActionResult CreateUser([FromBody] UserDto dto)
{
if (dto.Username == null || dto.Password == null || dto.Email == null)
{
return BadRequest();
}
if (userService.IsEmailTaken(dto.Email))
{
return StatusCode(409, "Email déjà utilisé");
}
var success = await _dataService.UserService.DeleteItem<UserEntity>(id);
if(success)
{
_logger.LogInformation("[INFORMATION] L'utilisateur avec l'id {id} a été supprimé.", id);
return Ok(_dataService.UserService.DeleteUser(id));
} else
{
_logger.LogError("[ERREUR] Aucun utilisateur trouvé avec l'id {id}.", id);
return NotFound();
}
if (userService.IsUsernameTaken(dto.Username))
{
return StatusCode(410, "Username déjà utilisé");
}
// return Ok(userService.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),
userService.CreateUser(dto.Username, dto.Password, dto.Email, dto.IsAdmin));
}
[HttpPut("user/{id:int}")]
[ProducesResponseType(typeof(UserDto), 200)]
[ProducesResponseType(typeof(string), 400)]
[ProducesResponseType(typeof(string), 404)]
[ProducesResponseType(typeof(string), 409)]
public IActionResult UpdateUser(int id, [FromBody] UserDto userDto)
{
if (id != userDto.Id)
[HttpPost]
public async Task<IActionResult> CreateUser([FromBody]UserDTO dto)
{
logger.LogError("[ERREUR] Problème ID - La mise à jour de l'utilisateur avec l'id {id} a échouée.", id);
return BadRequest();
}
if (dto.Username == null || dto.Password == null || dto.Email == null)
{
return BadRequest();
}
if (!ModelState.IsValid)
{
logger.LogError(
"[ERREUR] Problème controller - La mise à jour de l'utilisateur avec l'id {id} a échouée.", id);
return BadRequest();
_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), _dataService.UserService.AddItem(dto.FromDTOToModel().FromModelToEntity()));
}
if (userDto.Username == userService.GetUserById(id).Username && !userService.IsEmailTaken(userDto.Email)
|| (userDto.Email == userService.GetUserById(id).Email &&
!userService.IsUsernameTaken(userDto.Username))
|| (!userService.IsEmailTaken(userDto.Email) && !userService.IsUsernameTaken(userDto.Username)))
{
logger.LogInformation("[INFORMATION] La mise à jour de l'utilisateur avec l'id {id} a été effectuée",
id);
return Ok(userService.UpdateUser(id, userDto));
}
logger.LogError("[ERREUR] Email ou nom d'utilisateur déjà utilisé");
return StatusCode(409, "Email ou nom d'utilisateur déjà utilisé");
}
[HttpPut("user/promote/{id:int}")]
[ProducesResponseType(typeof(UserDto), 200)]
[ProducesResponseType(typeof(string), 404)]
public IActionResult PromoteUser(int id)
{
var userPromoted = userService.GetUserById(id);
if (userPromoted != null)
{
userPromoted = userService.PromoteUser(id);
logger.LogInformation("[INFORMATION] La promotion de l'utilisateur avec l'id {id} a été effectuée");
return Ok(userPromoted);
}
else
[HttpPut]
public async Task<IActionResult> UpdateUser(int id, [FromBody] UserDTO userDTO)
{
logger.LogInformation("[INFORMATION] La promotion de l'utilisateur avec l'id {id} à échouée",
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.LogInformation("[INFORMATION] La mise à jour de l'utilisateur avec l'id {id} a été effectuée", id);
return Ok(_dataService.UserService.UpdateItem<UserEntity, UserDTO>(id, userDTO));
}
_logger.LogError("[ERREUR] Aucun utilisateur trouvé avec l'id {id}.", id);
return NotFound();
}
}

@ -1,31 +0,0 @@
FROM mcr.microsoft.com/dotnet/aspnet:8.0 AS base
USER app
WORKDIR /app
EXPOSE 80
FROM mcr.microsoft.com/dotnet/sdk:8.0 AS build
ARG BUILD_CONFIGURATION=Release
WORKDIR /src
COPY ["API/API.csproj", "API/"]
COPY ["DbContextLib/DbContextLib.csproj", "DbContextLib/"]
COPY ["EntityFramework/Entities.csproj", "EntityFramework/"]
COPY ["Dto/Dto.csproj", "Dto/"]
COPY ["DbDataManager/DbDataManager.csproj", "DbDataManager/"]
COPY ["Model/Model.csproj", "Model/"]
COPY ["Shared/Shared.csproj", "Shared/"]
COPY ["StubbedContextLib/StubbedContextLib.csproj", "StubbedContextLib/"]
RUN dotnet restore "./API/./API.csproj"
COPY . .
WORKDIR "/src/API"
RUN dotnet build "./API.csproj" -c $BUILD_CONFIGURATION -o /app/build
FROM build AS publish
ARG BUILD_CONFIGURATION=Release
RUN dotnet publish "./API.csproj" -c $BUILD_CONFIGURATION -o /app/publish /p:UseAppHost=false
FROM base AS final
WORKDIR /app
COPY --from=publish /app/publish .
ENV ASPNETCORE_HTTP_PORTS=80
ENV DOTNET_HOSTBUILDER__RELOADCONFIGONCHANGE=false
ENTRYPOINT ["dotnet", "API.dll"]

@ -1,93 +1,30 @@
using API;
using API.Service;
using Asp.Versioning;
using DbContextLib;
using DbDataManager.Service;
using Dto;
using Entities;
using Microsoft.AspNetCore.Identity;
using Microsoft.EntityFrameworkCore;
using Microsoft.OpenApi.Models;
using Model;
using Shared;
using StubbedContextLib;
using Model.DTO;
using Model.Business;
using ModelToEntity;
using Services;
using System.Data.Common;
using Microsoft.Extensions.Options;
var builder = WebApplication.CreateBuilder(args);
// Add services to the container.
builder.Services.AddControllers();
builder.Services.AddControllers();
// Learn more about configuring Swagger/OpenAPI at https://aka.ms/aspnetcore/swashbuckle
builder.Services.AddEndpointsApiExplorer();
builder.Services.AddSwaggerGen();
builder.Services.AddScoped<IQueryService<QueryDto>, QueryDataServiceApi>();
builder.Services.AddScoped<IUserService<UserEntity>, UserDataService>();
builder.Services.AddScoped<IUserService<UserDto>, UserDataServiceApi>();
builder.Services.AddScoped<IBlackListService<BlackListEntity>, BlackListDataService>();
builder.Services.AddScoped<IBlackListService<BlackListDto>, BlackListDataServiceAPI>();
builder.Services.AddScoped<IInquiryService<InquiryEntity>, InquiryDataService>();
builder.Services.AddScoped<IInquiryService<InquiryDto>, InquiryDataServiceApi>();
builder.Services.AddScoped<ISolutionService<SolutionEntity>, SolutionDataService>();
builder.Services.AddScoped<ISolutionService<SolutionDto>, SolutionDataServiceAPI>();
builder.Services.AddScoped<IInquiryTableService<InquiryTableEntity>, InquiryTableDataService>();
builder.Services.AddScoped<IInquiryTableService<InquiryTableDto>, InquiryTableDataServiceAPI>();
builder.Services.AddScoped<IParagraphService<ParagraphEntity>, ParagraphDataService>();
builder.Services.AddScoped<IParagraphService<ParagraphDto>, ParagraphDataServiceApi>();
builder.Services.AddScoped<ISuccessService<SuccessEntity>, SuccessDataService>();
builder.Services.AddScoped<ISuccessService<SuccessDto>, SuccessDataServiceApi>();
builder.Services.AddScoped<ILessonService<LessonEntity>, LessonDataService>();
builder.Services.AddScoped<ILessonService<LessonDto>, LessonDataServiceApi>();
builder.Services.AddScoped<INotepadService<NotepadEntity>, NotepadDataService>();
builder.Services.AddScoped<INotepadService<NotepadDto>, NotepadDataServiceAPI>();
builder.Services.AddDbContext<DbContext,UserDbContext>((serviceProvider, options) =>
{
if (builder.Environment.IsProduction())
{
Console.WriteLine("I am in production mode");
var address = Environment.GetEnvironmentVariable("DB_HOST", EnvironmentVariableTarget.Process)
?? throw new ArgumentException("Missing DB_HOST environment variable");
var database = Environment.GetEnvironmentVariable("DB_DATABASE", EnvironmentVariableTarget.Process)
?? throw new ArgumentException("Missing DB_DATABASE environment variable");
var user = Environment.GetEnvironmentVariable("DB_USER", EnvironmentVariableTarget.Process)
?? throw new ArgumentException("Missing DB_USER environment variable");
var password = Environment.GetEnvironmentVariable("DB_PASSWORD", EnvironmentVariableTarget.Process)
?? throw new ArgumentException("Missing DB_PASSWORD environment variable");
var coString = $"Host={address};Database={database};Username={user};Password={password}";
options.UseNpgsql(coString);
}
else
{
Console.WriteLine("I am in development mode");
options.UseNpgsql("Host=localhost;Database=SQLuedo;Username=admin;Password=motdepasse");
}
});
builder.Services.AddIdentityApiEndpoints<IdentityUser>().AddEntityFrameworkStores<UserDbContext>();
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>();
builder.Services.AddAuthorization();
builder.Services.AddApiVersioning(o =>
{
o.AssumeDefaultVersionWhenUnspecified = true;
o.DefaultApiVersion = new ApiVersion(1);
o.ReportApiVersions = true;
}).AddApiExplorer(
options =>
{
options.GroupNameFormat = "'v'VVV";
options.SubstituteApiVersionInUrl = true;
});
//builder.Services.AddIdentityApiEndpoints<IdentityUser>()
// .AddEntityFrameworkStores<UserDbContext>();
builder.Services.AddSwaggerGen(option =>
@ -109,75 +46,24 @@ builder.Services.AddSwaggerGen(option =>
{
Reference = new OpenApiReference
{
Type = ReferenceType.SecurityScheme,
Id = "Bearer"
Type=ReferenceType.SecurityScheme,
Id="Bearer"
}
},
new string[] { }
new string[]{}
}
});
});
builder.Services.AddCors(options =>
{
options.AddPolicy("AllowSpecificOrigin",
builder =>
{
builder.WithOrigins("https://localhost:7171")
.AllowAnyMethod()
.AllowAnyHeader();
});
});
var configuration = new ConfigurationBuilder()
.SetBasePath(Directory.GetCurrentDirectory())
.AddJsonFile("appsettings.json", optional: false, reloadOnChange: true)
.Build();
builder.Services.AddSingleton(configuration);
var app = builder.Build();
app.UseCors("AllowSpecificOrigin");
// Création de l'utilisateur admin pour la base de données Identity
using (var scope = app.Services.CreateScope())
// Configure the HTTP request pipeline.
if (app.Environment.IsDevelopment())
{
var services = scope.ServiceProvider;
// Création base de données via les migrations
await using var dbContext = services.GetRequiredService<UserDbContext>();
//await dbContext.Database.MigrateAsync();
var userManager = services.GetRequiredService<UserManager<IdentityUser>>();
try
{
var user = new IdentityUser { UserName = "admin@example.com", Email = "admin@example.com" };
var result = await userManager.CreateAsync(user, "Mdp_1234");
if (result.Succeeded)
{
Console.WriteLine("Utilisateur admin créé avec succès.");
}
else
{
foreach (var error in result.Errors)
{
Console.WriteLine($"Erreur lors de la création de l'utilisateur : {error.Description}");
}
}
}
catch (Exception ex)
{
var logger = services.GetRequiredService<ILogger<Program>>();
logger.LogError(ex, "Une erreur s'est produite lors de la création de l'utilisateur.");
}
app.UseSwagger();
app.UseSwaggerUI();
}
app.UseSwagger();
app.UseSwaggerUI();
app.UseHttpsRedirection();
app.UseAuthorization();

@ -16,10 +16,7 @@
"launchUrl": "swagger",
"applicationUrl": "http://localhost:5015",
"environmentVariables": {
"DB_HOST": "localhost",
"DB_DATABASE": "SQLuedo",
"DB_USER": "admin",
"DB_PASSWORD" : "motdepasse"
"ASPNETCORE_ENVIRONMENT": "Development"
}
},
"https": {
@ -27,23 +24,17 @@
"dotnetRunMessages": true,
"launchBrowser": true,
"launchUrl": "swagger",
"applicationUrl": "https://localhost:8081;http://localhost:5015",
"applicationUrl": "https://localhost:7259;http://localhost:5015",
"environmentVariables": {
"DB_HOST": "localhost",
"DB_DATABASE": "SQLuedo",
"DB_USER": "admin",
"DB_PASSWORD" : "motdepasse"
"ASPNETCORE_ENVIRONMENT": "Development"
}
},
"IIS Express": {
"commandName": "IISExpress",
"launchBrowser": true,
"launchUrl": "containers/johnnyratton-sqluedo-api",
"launchUrl": "swagger",
"environmentVariables": {
"DB_HOST": "localhost",
"DB_DATABASE": "SQLuedo",
"DB_USER": "admin",
"DB_PASSWORD" : "motdepasse"
"ASPNETCORE_ENVIRONMENT": "Development"
}
}
}

@ -1,27 +0,0 @@
using Dto;
using Entities;
using Model.OrderCriteria;
using Shared;
using Shared.Mapper;
namespace API.Service;
public class BlackListDataServiceAPI (IBlackListService<BlackListEntity> userService) : IBlackListService<BlackListDto>
{
public IEnumerable<BlackListDto> GetBannedUsers(int page, int number, BlackListOdrerCriteria orderCriteria) =>
userService.GetBannedUsers(page, number, orderCriteria).Select(b => b.FromEntityToDto());
public int GetNumberOfBannedUsers() => userService.GetNumberOfBannedUsers();
public BlackListDto? GetUserBannedByEmail(string email)
{
var res = userService.GetUserBannedByEmail(email);
if (res == null)
{
return null;
}
return res.FromEntityToDto();
}
public bool BanUser(string username) => userService.BanUser(username);
public bool UnbanUser(string email) => userService.UnbanUser(email);
}

@ -1,40 +0,0 @@
using Dto;
using Entities;
using Model.OrderCriteria;
using Shared;
using Shared.Mapper;
namespace API.Service;
public class InquiryDataServiceApi(IInquiryService<InquiryEntity> inquiryService) : IInquiryService<InquiryDto>
{
public InquiryDto UpdateInquiry(int id, InquiryDto inquiry)
{
return inquiryService.UpdateInquiry(id, inquiry.FromDtoToEntity()).FromEntityToDto();
}
public InquiryDto CreateInquiry(string title, string description, bool isUser)
{
return inquiryService.CreateInquiry(title, description, isUser).FromEntityToDto();
}
public bool DeleteInquiry(int id)
{
return inquiryService.DeleteInquiry(id);
}
public IEnumerable<InquiryDto> GetInquiries(int page, int number, InquiryOrderCriteria orderCriteria)
{
var inquiries = inquiryService.GetInquiries(page, number, orderCriteria);
return inquiries.Select(i => i.FromEntityToDto()).ToList();
}
public int GetNumberOfInquiries()
{
return inquiryService.GetNumberOfInquiries();
}
public InquiryDto GetInquiryById(int id) => inquiryService.GetInquiryById(id).FromEntityToDto();
public InquiryDto GetInquiryByTitle(string title) => inquiryService.GetInquiryByTitle(title).FromEntityToDto();
}

@ -1,13 +0,0 @@
using Dto;
using Entities;
using Shared;
namespace API.Service;
public class InquiryTableDataServiceAPI(IInquiryTableService<InquiryTableEntity> inquiryTableService) : IInquiryTableService<InquiryTableDto>
{
public string GetDatabaseNameByInquiryId(int id)
{
return inquiryTableService.GetDatabaseNameByInquiryId(id);
}
}

@ -1,36 +0,0 @@
using Dto;
using Entities;
using Model.OrderCriteria;
using Shared;
using Shared.Mapper;
namespace API.Service;
public class LessonDataServiceApi(ILessonService<LessonEntity> lessonService) : ILessonService<LessonDto>
{
public IEnumerable<LessonDto> GetLessons(int page, int number, LessonOrderCriteria orderCriteria)
{
var lessonsEntities = lessonService.GetLessons(page, number, orderCriteria);
return lessonsEntities.Select(e => e.FromEntityToDto()).ToList();
}
public int GetNumberOfLessons()
{
return lessonService.GetNumberOfLessons();
}
public LessonDto GetLessonById(int id) => lessonService.GetLessonById(id).FromEntityToDto();
public LessonDto GetLessonByTitle(string title) => lessonService.GetLessonByTitle(title).FromEntityToDto();
public bool DeleteLesson(int id) => lessonService.DeleteLesson(id);
public LessonDto UpdateLesson(int id, LessonDto lesson) =>
lessonService.UpdateLesson(id, lesson.FromDtoToEntity()).FromEntityToDto();
public LessonDto UpdateLesson(int id, LessonEntity lesson) =>
lessonService.UpdateLesson(id, lesson).FromEntityToDto();
public LessonDto CreateLesson(int id, string title, string lastPublisher, DateOnly lastEdit) =>
lessonService.CreateLesson(id, title, lastPublisher, lastEdit).FromEntityToDto();
}

@ -1,24 +0,0 @@
using Dto;
using Entities;
using Shared;
using Shared.Mapper;
namespace API.Service;
public class NotepadDataServiceAPI(INotepadService<NotepadEntity> notepadService) : INotepadService<NotepadDto>
{
public NotepadDto GetNotepadFromUserAndInquiryId(int userId, int inquiryId)
{
return notepadService.GetNotepadFromUserAndInquiryId(userId, inquiryId).FromEntityToDto();
}
public void SetNotepadFromUserAndInquiryId(int userId, int inquiryId, string notes)
{
notepadService.SetNotepadFromUserAndInquiryId(userId,inquiryId,notes);
}
public void UpdateNotepadFromUserAndInquiryId(int userId, int inquiryId, string notes)
{
notepadService.UpdateNotepadFromUserAndInquiryId(userId,inquiryId,notes);
}
}

@ -1,35 +0,0 @@
using Dto;
using Entities;
using Model.OrderCriteria;
using Shared;
using Shared.Mapper;
namespace API.Service;
public class ParagraphDataServiceApi(IParagraphService<ParagraphEntity> paragraphService)
: IParagraphService<ParagraphDto>
{
public IEnumerable<ParagraphDto> GetParagraphs(int page, int number, ParagraphOrderCriteria orderCriteria)
{
var paragraphsEntities = paragraphService.GetParagraphs(page, number, orderCriteria);
return paragraphsEntities.Select(e => e.FromEntityToDto()).ToList();
}
public IEnumerable<ParagraphDto> GetParagraphsByLessonId(int lessonId)
{
return paragraphService.GetParagraphsByLessonId(lessonId).Select(p => p.FromEntityToDto());
}
public ParagraphDto GetParagraphById(int id) => paragraphService.GetParagraphById(id).FromEntityToDto();
public ParagraphDto GetParagraphByTitle(string title) =>
paragraphService.GetParagraphByTitle(title).FromEntityToDto();
public bool DeleteParagraph(int id) => paragraphService.DeleteParagraph(id);
public ParagraphDto UpdateParagraph(int id, ParagraphDto paragraph) =>
paragraphService.UpdateParagraph(id, paragraph.FromDtoToEntity()).FromEntityToDto();
public ParagraphDto CreateParagraph(string contentTitle, string contentContent,string title, string content, string info, string query, string comment,
int lessonId) => paragraphService.CreateParagraph(contentTitle, contentContent, title, content, info, query, comment, lessonId).FromEntityToDto();
}

@ -1,176 +0,0 @@
using Dto;
using Entities;
using Model.OrderCriteria;
using Npgsql;
using Shared;
using Shared.Mapper;
using Microsoft.Extensions.Configuration;
using System.Text;
using Newtonsoft.Json;
using Microsoft.EntityFrameworkCore.Metadata.Internal;
namespace API.Service;
public class QueryDataServiceApi : IQueryService<QueryDto>{
private readonly IConfiguration _configuration;
public QueryDataServiceApi(IConfiguration configuration)
{
_configuration = configuration;
}
public QueryDto ExecuteQuery(string query, string database)
{
string connectionString = _configuration.GetConnectionString("DefaultConnection");
connectionString = connectionString.Replace("{database}", database);
if (string.IsNullOrEmpty(database))
{
return new QueryDto { Result = "Le nom de la base de données est requis." };
}
try
{
using (NpgsqlConnection connection = new NpgsqlConnection(connectionString))
{
connection.Open();
using (NpgsqlCommand command = new NpgsqlCommand(query, connection))
{
using (NpgsqlDataReader reader = command.ExecuteReader())
{
List<Dictionary<string, object>> resultList = new List<Dictionary<string, object>>();
List<string> columnNames = new List<string>();
for (int i = 0; i < reader.FieldCount; i++)
{
columnNames.Add(reader.GetName(i));
}
while (reader.Read())
{
Dictionary<string, object> row = new Dictionary<string, object>();
for (int i = 0; i < reader.FieldCount; i++)
{
row[columnNames[i]] = reader[i].ToString();
}
resultList.Add(row);
}
string resultJson = JsonConvert.SerializeObject(resultList);
QueryDto queryDto = new QueryDto { Result = resultJson };
return queryDto;
}
}
}
}
catch (Exception ex)
{
return new QueryDto { Result = ex.Message };
}
}
public QueryDto GetTables(string database)
{
string connectionString = _configuration.GetConnectionString("DefaultConnection");
connectionString = connectionString.Replace("{database}", database);
try
{
using (NpgsqlConnection connection = new NpgsqlConnection(connectionString))
{
connection.Open();
using (NpgsqlCommand command = new NpgsqlCommand())
{
command.Connection = connection;
// Donner et exclure les bonnes permissions au rôle en question
// GRANT SELECT ON TABLE information_schema.tables TO votre_utilisateur;
// GRANT SELECT ON TABLE information_schema.columns TO votre_utilisateur;
// REVOKE ALL ON SCHEMA information_schema FROM PUBLIC;
command.CommandText =
"SELECT table_name FROM information_schema.tables WHERE table_schema = 'public';";
using (NpgsqlDataReader reader = command.ExecuteReader())
{
List<string> tableNames = new List<string>();
while (reader.Read())
{
tableNames.Add(reader["table_name"].ToString());
}
List<object> tablesDict = new List<object>();
foreach (string tableName in tableNames)
{
tablesDict.Add(new { TableName = tableName});
}
string tablesJson = JsonConvert.SerializeObject(tablesDict);
QueryDto queryDto = new QueryDto { Result = tablesJson };
return queryDto;
}
}
}
}
catch (Exception ex)
{
return new QueryDto { Result = ex.Message };
}
}
public QueryDto GetColumns(string database, string table)
{
string connectionString = _configuration.GetConnectionString("DefaultConnection");
connectionString = connectionString.Replace("{database}", database);
using (NpgsqlConnection connection = new NpgsqlConnection(connectionString))
{
connection.Open();
using (NpgsqlCommand command = new NpgsqlCommand())
{
command.Connection = connection;
// Donner et exclure les bonnes permissions au rôle en question
//GRANT SELECT ON TABLE information_schema.tables TO votre_utilisateur;
//GRANT SELECT ON TABLE information_schema.columns TO votre_utilisateur;
//REVOKE ALL ON SCHEMA information_schema FROM PUBLIC;
command.CommandText =
$"SELECT column_name FROM information_schema.columns WHERE table_name = '{table}';";
Console.WriteLine(command.CommandText);
using (NpgsqlDataReader reader = command.ExecuteReader())
{
List<string> columnsNames = new List<string>();
while (reader.Read())
{
columnsNames.Add(reader["column_name"].ToString());
}
/*List<object> columnsDict = new List<object>();
foreach (string colName in columnsNames)
{
columnsDict.Add(new { ColumnName = colName});
}*/
string tablesJson = JsonConvert.SerializeObject(columnsNames);
Console.WriteLine(tablesJson);
QueryDto queryDto = new QueryDto { Result = tablesJson };
return queryDto;
}
}
}
}
}

@ -1,14 +0,0 @@
using Dto;
using Entities;
using Shared;
using Shared.Mapper;
namespace API.Service;
public class SolutionDataServiceAPI(ISolutionService<SolutionEntity> solutionService) : ISolutionService<SolutionDto>
{
public SolutionDto GetSolutionByInquiryId(int id)
{
return solutionService.GetSolutionByInquiryId(id).FromEntityToDto();
}
}

@ -1,30 +0,0 @@
using Dto;
using Entities;
using Model.OrderCriteria;
using Shared;
using Shared.Mapper;
namespace API.Service;
public class SuccessDataServiceApi(ISuccessService<SuccessEntity> sucessService) : ISuccessService<SuccessDto>
{
public IEnumerable<SuccessDto> GetSuccesses(int page, int number, SuccessOrderCriteria orderCriteria)
{
var successesEntities = sucessService.GetSuccesses(page, number, orderCriteria);
return successesEntities.Select(e => e.FromEntityToDto()).ToList();
}
public IEnumerable<SuccessDto> GetSuccessesByUserId(int id) =>
sucessService.GetSuccessesByUserId(id).Select(s => s.FromEntityToDto());
public IEnumerable<SuccessDto> GetSuccessesByInquiryId(int id) =>
sucessService.GetSuccessesByInquiryId(id).Select(s => s.FromEntityToDto());
public bool DeleteSuccess(int idUser, int idInquiry) => sucessService.DeleteSuccess(idUser, idInquiry);
public SuccessDto UpdateSuccess(int idUser, int idInquiry, SuccessDto success) =>
sucessService.UpdateSuccess(idUser, idInquiry, success.FromDtoToEntity()).FromEntityToDto();
public SuccessDto CreateSuccess(int userId, int inquiryId, bool isFinished) =>
sucessService.CreateSuccess(userId, inquiryId, isFinished).FromEntityToDto();
}

@ -1,48 +0,0 @@
using Dto;
using Entities;
using Model.OrderCriteria;
using Shared;
using Shared.Mapper;
namespace API.Service;
public class UserDataServiceApi(IUserService<UserEntity> userService) : IUserService<UserDto>
{
public IEnumerable<UserDto> GetUsers(int page, int number, UserOrderCriteria orderCriteria)
{
var usersEntities = userService.GetUsers(page, number, orderCriteria);
return usersEntities.Select(e => e.FromEntityToDto()).ToList();
}
public IEnumerable<UserDto> GetNotAdminUsers(int page, int number, UserOrderCriteria orderCriteria)
{
var usersEntities = userService.GetNotAdminUsers(page, number, orderCriteria);
return usersEntities.Select(e => e.FromEntityToDto()).ToList();
}
public int GetNumberOfUsers()
{
return userService.GetNumberOfUsers();
}
public UserDto GetUserById(int id) => userService.GetUserById(id).FromEntityToDto();
public UserDto GetUserByUsername(string username) => userService.GetUserByUsername(username).FromEntityToDto();
public UserDto GetUserByEmail(string email) => userService.GetUserByEmail(email).FromEntityToDto();
public bool DeleteUser(int id) => userService.DeleteUser(id);
public bool DeleteUserByUsername(string username) => userService.DeleteUserByUsername(username);
public UserDto UpdateUser(int id, UserDto user) =>
userService.UpdateUser(id, user.FromDtoToEntity()).FromEntityToDto();
public UserDto CreateUser(string username, string password, string email, bool isAdmin) =>
userService.CreateUser(username, password, email, isAdmin).FromEntityToDto();
public bool IsEmailTaken(string email) => userService.IsEmailTaken(email);
public bool IsUsernameTaken(string username) => userService.IsUsernameTaken(username);
public UserDto PromoteUser(int id) =>
userService.PromoteUser(id).FromEntityToDto();
}

@ -6,8 +6,6 @@ namespace API
{
public class WebAPIDbContext : IdentityDbContext<IdentityUser>
{
public WebAPIDbContext(DbContextOptions<WebAPIDbContext> options) : base(options)
{
}
public WebAPIDbContext(DbContextOptions<WebAPIDbContext> options) : base(options) { }
}
}

@ -5,8 +5,5 @@
"Microsoft.AspNetCore": "Warning"
}
},
"AllowedHosts": "*",
"ConnectionStrings": {
"DefaultConnection": "Host=localhost;Username=admin;Password=motdepasse;Database={database}"
}
"AllowedHosts": "*"
}

@ -7,7 +7,7 @@ Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "API", "API\API.csproj", "{6
EndProject
Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "Entities", "EntityFramework\Entities.csproj", "{6D079CDA-C000-4833-98A0-D07D153EA264}"
EndProject
Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "DbDataManager", "DbDataManager\DbDataManager.csproj", "{ADCC427D-A3CD-431C-A90B-F9369C4584E8}"
Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "Model", "Model\Model.csproj", "{ADCC427D-A3CD-431C-A90B-F9369C4584E8}"
EndProject
Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "TestAPI", "TestAPI\TestAPI.csproj", "{17025B90-8B2A-49E9-97D3-1A84A208DF50}"
EndProject
@ -15,17 +15,11 @@ Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "TestEF", "TestEF\TestEF.csp
EndProject
Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "DbContextLib", "DbContextLib\DbContextLib.csproj", "{BDCB3BFD-B744-4BC0-BCFC-78E08600203A}"
EndProject
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "TestConsoleAPI", "TestConsoleAPI\TestConsoleAPI.csproj", "{46376AEF-4093-4AE9-AD2F-F51B541F9C6A}"
Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "Services", "Services\Services.csproj", "{9BD3DCBA-AFD8-47FA-B07C-613B53E63968}"
EndProject
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "StubbedContextLib", "StubbedContextLib\StubbedContextLib.csproj", "{B64941C9-0550-4C47-89B6-396F6DB0486D}"
Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "ModelToEntity", "ModelToEntity\ModelToEntity.csproj", "{8F53CC62-94B3-4F9D-ABF1-F7307A6F27C0}"
EndProject
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Dto", "Dto\Dto.csproj", "{9682CA6B-2380-463B-B6BC-17C3B9E992C8}"
EndProject
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Model", "Model\Model.csproj", "{EDDA59D4-BD38-46BF-8292-26A47187B76F}"
EndProject
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Shared", "Shared\Shared.csproj", "{9DC1D2DF-AC2B-4CF5-BB30-2FB6533BFF76}"
EndProject
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "TestConsoleEf", "TestConsoleEf\TestConsoleEf.csproj", "{37378C7E-074C-4863-BFD0-60802303FEEB}"
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Shared", "Shared\Shared.csproj", "{B28FD539-6FE4-4B13-9C1F-D88F4771CC69}"
EndProject
Global
GlobalSection(SolutionConfigurationPlatforms) = preSolution
@ -57,30 +51,18 @@ Global
{BDCB3BFD-B744-4BC0-BCFC-78E08600203A}.Debug|Any CPU.Build.0 = Debug|Any CPU
{BDCB3BFD-B744-4BC0-BCFC-78E08600203A}.Release|Any CPU.ActiveCfg = Release|Any CPU
{BDCB3BFD-B744-4BC0-BCFC-78E08600203A}.Release|Any CPU.Build.0 = Release|Any CPU
{46376AEF-4093-4AE9-AD2F-F51B541F9C6A}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{46376AEF-4093-4AE9-AD2F-F51B541F9C6A}.Debug|Any CPU.Build.0 = Debug|Any CPU
{46376AEF-4093-4AE9-AD2F-F51B541F9C6A}.Release|Any CPU.ActiveCfg = Release|Any CPU
{46376AEF-4093-4AE9-AD2F-F51B541F9C6A}.Release|Any CPU.Build.0 = Release|Any CPU
{B64941C9-0550-4C47-89B6-396F6DB0486D}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{B64941C9-0550-4C47-89B6-396F6DB0486D}.Debug|Any CPU.Build.0 = Debug|Any CPU
{B64941C9-0550-4C47-89B6-396F6DB0486D}.Release|Any CPU.ActiveCfg = Release|Any CPU
{B64941C9-0550-4C47-89B6-396F6DB0486D}.Release|Any CPU.Build.0 = Release|Any CPU
{9682CA6B-2380-463B-B6BC-17C3B9E992C8}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{9682CA6B-2380-463B-B6BC-17C3B9E992C8}.Debug|Any CPU.Build.0 = Debug|Any CPU
{9682CA6B-2380-463B-B6BC-17C3B9E992C8}.Release|Any CPU.ActiveCfg = Release|Any CPU
{9682CA6B-2380-463B-B6BC-17C3B9E992C8}.Release|Any CPU.Build.0 = Release|Any CPU
{EDDA59D4-BD38-46BF-8292-26A47187B76F}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{EDDA59D4-BD38-46BF-8292-26A47187B76F}.Debug|Any CPU.Build.0 = Debug|Any CPU
{EDDA59D4-BD38-46BF-8292-26A47187B76F}.Release|Any CPU.ActiveCfg = Release|Any CPU
{EDDA59D4-BD38-46BF-8292-26A47187B76F}.Release|Any CPU.Build.0 = Release|Any CPU
{9DC1D2DF-AC2B-4CF5-BB30-2FB6533BFF76}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{9DC1D2DF-AC2B-4CF5-BB30-2FB6533BFF76}.Debug|Any CPU.Build.0 = Debug|Any CPU
{9DC1D2DF-AC2B-4CF5-BB30-2FB6533BFF76}.Release|Any CPU.ActiveCfg = Release|Any CPU
{9DC1D2DF-AC2B-4CF5-BB30-2FB6533BFF76}.Release|Any CPU.Build.0 = Release|Any CPU
{37378C7E-074C-4863-BFD0-60802303FEEB}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{37378C7E-074C-4863-BFD0-60802303FEEB}.Debug|Any CPU.Build.0 = Debug|Any CPU
{37378C7E-074C-4863-BFD0-60802303FEEB}.Release|Any CPU.ActiveCfg = Release|Any CPU
{37378C7E-074C-4863-BFD0-60802303FEEB}.Release|Any CPU.Build.0 = Release|Any CPU
{9BD3DCBA-AFD8-47FA-B07C-613B53E63968}.Debug|Any CPU.ActiveCfg = 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.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

@ -7,16 +7,14 @@
</PropertyGroup>
<ItemGroup>
<PackageReference Include="Asp.Versioning.Mvc" Version="8.0.0" />
<PackageReference Include="Microsoft.AspNetCore.Cryptography.KeyDerivation" Version="8.0.2" />
<PackageReference Include="Microsoft.AspNetCore.Identity.EntityFrameworkCore" Version="8.0.2" />
<PackageReference Include="Microsoft.EntityFrameworkCore" Version="8.0.2" />
<PackageReference Include="Microsoft.EntityFrameworkCore.Design" Version="8.0.2">
<PackageReference Include="Microsoft.AspNetCore.Cryptography.KeyDerivation" Version="8.0.1" />
<PackageReference Include="Microsoft.AspNetCore.Identity.EntityFrameworkCore" Version="8.0.0" />
<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.Sqlite" Version="8.0.2" />
<PackageReference Include="Microsoft.EntityFrameworkCore.Tools" Version="8.0.2">
<PackageReference Include="Microsoft.EntityFrameworkCore.Tools" Version="8.0.1">
<PrivateAssets>all</PrivateAssets>
<IncludeAssets>runtime; build; native; contentfiles; analyzers; buildtransitive</IncludeAssets>
</PackageReference>

@ -1,595 +0,0 @@
// <auto-generated />
using System;
using DbContextLib;
using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.Infrastructure;
using Microsoft.EntityFrameworkCore.Migrations;
using Microsoft.EntityFrameworkCore.Storage.ValueConversion;
using Npgsql.EntityFrameworkCore.PostgreSQL.Metadata;
#nullable disable
namespace DbContextLib.Migrations
{
[DbContext(typeof(UserDbContext))]
[Migration("20240403065352_v1")]
partial class v1
{
/// <inheritdoc />
protected override void BuildTargetModel(ModelBuilder modelBuilder)
{
#pragma warning disable 612, 618
modelBuilder
.HasAnnotation("ProductVersion", "8.0.2")
.HasAnnotation("Relational:MaxIdentifierLength", 63);
NpgsqlModelBuilderExtensions.UseIdentityByDefaultColumns(modelBuilder);
modelBuilder.HasSequence("ContentLessonEntitySequence");
modelBuilder.Entity("Entities.BlackListEntity", b =>
{
b.Property<string>("Email")
.HasColumnType("text");
b.Property<DateOnly>("ExpirationDate")
.HasColumnType("date");
b.HasKey("Email");
b.ToTable("BlackList");
});
modelBuilder.Entity("Entities.ContentLessonEntity", b =>
{
b.Property<int>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("integer")
.HasDefaultValueSql("nextval('\"ContentLessonEntitySequence\"')");
NpgsqlPropertyBuilderExtensions.UseSequence(b.Property<int>("Id"));
b.Property<string>("ContentContent")
.IsRequired()
.HasColumnType("text");
b.Property<string>("ContentTitle")
.IsRequired()
.HasColumnType("text");
b.Property<int>("LessonId")
.HasColumnType("integer");
b.HasKey("Id");
b.HasIndex("LessonId");
b.ToTable((string)null);
b.UseTpcMappingStrategy();
});
modelBuilder.Entity("Entities.InquiryEntity", b =>
{
b.Property<int>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("integer");
NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property<int>("Id"));
b.Property<string>("Description")
.IsRequired()
.HasColumnType("text");
b.Property<bool>("IsUser")
.HasColumnType("boolean");
b.Property<string>("Title")
.IsRequired()
.HasColumnType("text");
b.HasKey("Id");
b.ToTable("Inquiries");
});
modelBuilder.Entity("Entities.InquiryTableEntity", b =>
{
b.Property<int>("OwnerId")
.ValueGeneratedOnAdd()
.HasColumnType("integer");
b.Property<string>("ConnectionInfo")
.IsRequired()
.HasColumnType("text");
b.Property<string>("DatabaseName")
.IsRequired()
.HasColumnType("text");
b.HasKey("OwnerId");
b.ToTable("InquiryTable");
});
modelBuilder.Entity("Entities.LessonEntity", b =>
{
b.Property<int>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("integer");
NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property<int>("Id"));
b.Property<DateOnly>("LastEdit")
.HasColumnType("date");
b.Property<string>("LastPublisher")
.IsRequired()
.HasColumnType("text");
b.Property<string>("Title")
.IsRequired()
.HasColumnType("text");
b.HasKey("Id");
b.ToTable("Lesson");
});
modelBuilder.Entity("Entities.NotepadEntity", b =>
{
b.Property<int>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("integer");
NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property<int>("Id"));
b.Property<int>("InquiryId")
.HasColumnType("integer");
b.Property<string>("Notes")
.IsRequired()
.HasColumnType("text");
b.Property<int>("UserId")
.HasColumnType("integer");
b.HasKey("Id");
b.HasIndex("InquiryId");
b.HasIndex("UserId");
b.ToTable("Notepad");
});
modelBuilder.Entity("Entities.SolutionEntity", b =>
{
b.Property<int>("OwnerId")
.ValueGeneratedOnAdd()
.HasColumnType("integer");
b.Property<string>("Explaination")
.IsRequired()
.HasColumnType("text");
b.Property<string>("MurderPlace")
.IsRequired()
.HasColumnType("text");
b.Property<string>("MurderWeapon")
.IsRequired()
.HasColumnType("text");
b.Property<string>("MurdererFirstName")
.IsRequired()
.HasColumnType("text");
b.Property<string>("MurdererLastName")
.IsRequired()
.HasColumnType("text");
b.HasKey("OwnerId");
b.ToTable("Solution");
});
modelBuilder.Entity("Entities.SuccessEntity", b =>
{
b.Property<int>("InquiryId")
.HasColumnType("integer");
b.Property<bool>("IsFinished")
.HasColumnType("boolean");
b.Property<int>("UserId")
.HasColumnType("integer");
b.HasKey("InquiryId");
b.HasIndex("UserId");
b.ToTable("Success");
});
modelBuilder.Entity("Entities.UserEntity", b =>
{
b.Property<int>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("integer");
NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property<int>("Id"));
b.Property<string>("Email")
.IsRequired()
.HasColumnType("text");
b.Property<bool>("IsAdmin")
.HasColumnType("boolean");
b.Property<string>("Password")
.IsRequired()
.HasColumnType("text");
b.Property<string>("Username")
.IsRequired()
.HasColumnType("text");
b.HasKey("Id");
b.ToTable("User");
});
modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityRole", b =>
{
b.Property<string>("Id")
.HasColumnType("text");
b.Property<string>("ConcurrencyStamp")
.IsConcurrencyToken()
.HasColumnType("text");
b.Property<string>("Name")
.HasMaxLength(256)
.HasColumnType("character varying(256)");
b.Property<string>("NormalizedName")
.HasMaxLength(256)
.HasColumnType("character varying(256)");
b.HasKey("Id");
b.HasIndex("NormalizedName")
.IsUnique()
.HasDatabaseName("RoleNameIndex");
b.ToTable("AspNetRoles", (string)null);
});
modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityRoleClaim<string>", b =>
{
b.Property<int>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("integer");
NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property<int>("Id"));
b.Property<string>("ClaimType")
.HasColumnType("text");
b.Property<string>("ClaimValue")
.HasColumnType("text");
b.Property<string>("RoleId")
.IsRequired()
.HasColumnType("text");
b.HasKey("Id");
b.HasIndex("RoleId");
b.ToTable("AspNetRoleClaims", (string)null);
});
modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUser", b =>
{
b.Property<string>("Id")
.HasColumnType("text");
b.Property<int>("AccessFailedCount")
.HasColumnType("integer");
b.Property<string>("ConcurrencyStamp")
.IsConcurrencyToken()
.HasColumnType("text");
b.Property<string>("Email")
.HasMaxLength(256)
.HasColumnType("character varying(256)");
b.Property<bool>("EmailConfirmed")
.HasColumnType("boolean");
b.Property<bool>("LockoutEnabled")
.HasColumnType("boolean");
b.Property<DateTimeOffset?>("LockoutEnd")
.HasColumnType("timestamp with time zone");
b.Property<string>("NormalizedEmail")
.HasMaxLength(256)
.HasColumnType("character varying(256)");
b.Property<string>("NormalizedUserName")
.HasMaxLength(256)
.HasColumnType("character varying(256)");
b.Property<string>("PasswordHash")
.HasColumnType("text");
b.Property<string>("PhoneNumber")
.HasColumnType("text");
b.Property<bool>("PhoneNumberConfirmed")
.HasColumnType("boolean");
b.Property<string>("SecurityStamp")
.HasColumnType("text");
b.Property<bool>("TwoFactorEnabled")
.HasColumnType("boolean");
b.Property<string>("UserName")
.HasMaxLength(256)
.HasColumnType("character varying(256)");
b.HasKey("Id");
b.HasIndex("NormalizedEmail")
.HasDatabaseName("EmailIndex");
b.HasIndex("NormalizedUserName")
.IsUnique()
.HasDatabaseName("UserNameIndex");
b.ToTable("AspNetUsers", (string)null);
});
modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserClaim<string>", b =>
{
b.Property<int>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("integer");
NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property<int>("Id"));
b.Property<string>("ClaimType")
.HasColumnType("text");
b.Property<string>("ClaimValue")
.HasColumnType("text");
b.Property<string>("UserId")
.IsRequired()
.HasColumnType("text");
b.HasKey("Id");
b.HasIndex("UserId");
b.ToTable("AspNetUserClaims", (string)null);
});
modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserLogin<string>", b =>
{
b.Property<string>("LoginProvider")
.HasColumnType("text");
b.Property<string>("ProviderKey")
.HasColumnType("text");
b.Property<string>("ProviderDisplayName")
.HasColumnType("text");
b.Property<string>("UserId")
.IsRequired()
.HasColumnType("text");
b.HasKey("LoginProvider", "ProviderKey");
b.HasIndex("UserId");
b.ToTable("AspNetUserLogins", (string)null);
});
modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserRole<string>", b =>
{
b.Property<string>("UserId")
.HasColumnType("text");
b.Property<string>("RoleId")
.HasColumnType("text");
b.HasKey("UserId", "RoleId");
b.HasIndex("RoleId");
b.ToTable("AspNetUserRoles", (string)null);
});
modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserToken<string>", b =>
{
b.Property<string>("UserId")
.HasColumnType("text");
b.Property<string>("LoginProvider")
.HasColumnType("text");
b.Property<string>("Name")
.HasColumnType("text");
b.Property<string>("Value")
.HasColumnType("text");
b.HasKey("UserId", "LoginProvider", "Name");
b.ToTable("AspNetUserTokens", (string)null);
});
modelBuilder.Entity("Entities.ParagraphEntity", b =>
{
b.HasBaseType("Entities.ContentLessonEntity");
b.Property<string>("Comment")
.IsRequired()
.HasColumnType("text");
b.Property<string>("Content")
.IsRequired()
.HasColumnType("text");
b.Property<string>("Info")
.IsRequired()
.HasColumnType("text");
b.Property<string>("Query")
.IsRequired()
.HasColumnType("text");
b.Property<string>("Title")
.IsRequired()
.HasColumnType("text");
b.ToTable("Paragraph");
});
modelBuilder.Entity("Entities.ContentLessonEntity", b =>
{
b.HasOne("Entities.LessonEntity", "Lesson")
.WithMany("Content")
.HasForeignKey("LessonId")
.OnDelete(DeleteBehavior.Cascade)
.IsRequired();
b.Navigation("Lesson");
});
modelBuilder.Entity("Entities.InquiryTableEntity", b =>
{
b.HasOne("Entities.InquiryEntity", "Owner")
.WithMany()
.HasForeignKey("OwnerId")
.OnDelete(DeleteBehavior.Cascade)
.IsRequired();
b.Navigation("Owner");
});
modelBuilder.Entity("Entities.NotepadEntity", b =>
{
b.HasOne("Entities.InquiryEntity", "Inquiry")
.WithMany()
.HasForeignKey("InquiryId")
.OnDelete(DeleteBehavior.Cascade)
.IsRequired();
b.HasOne("Entities.UserEntity", "User")
.WithMany()
.HasForeignKey("UserId")
.OnDelete(DeleteBehavior.Cascade)
.IsRequired();
b.Navigation("Inquiry");
b.Navigation("User");
});
modelBuilder.Entity("Entities.SolutionEntity", b =>
{
b.HasOne("Entities.InquiryEntity", "Owner")
.WithMany()
.HasForeignKey("OwnerId")
.OnDelete(DeleteBehavior.Cascade)
.IsRequired();
b.Navigation("Owner");
});
modelBuilder.Entity("Entities.SuccessEntity", b =>
{
b.HasOne("Entities.InquiryEntity", "Inquiry")
.WithMany()
.HasForeignKey("InquiryId")
.OnDelete(DeleteBehavior.Cascade)
.IsRequired();
b.HasOne("Entities.UserEntity", "User")
.WithMany()
.HasForeignKey("UserId")
.OnDelete(DeleteBehavior.Cascade)
.IsRequired();
b.Navigation("Inquiry");
b.Navigation("User");
});
modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityRoleClaim<string>", b =>
{
b.HasOne("Microsoft.AspNetCore.Identity.IdentityRole", null)
.WithMany()
.HasForeignKey("RoleId")
.OnDelete(DeleteBehavior.Cascade)
.IsRequired();
});
modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserClaim<string>", b =>
{
b.HasOne("Microsoft.AspNetCore.Identity.IdentityUser", null)
.WithMany()
.HasForeignKey("UserId")
.OnDelete(DeleteBehavior.Cascade)
.IsRequired();
});
modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserLogin<string>", b =>
{
b.HasOne("Microsoft.AspNetCore.Identity.IdentityUser", null)
.WithMany()
.HasForeignKey("UserId")
.OnDelete(DeleteBehavior.Cascade)
.IsRequired();
});
modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserRole<string>", b =>
{
b.HasOne("Microsoft.AspNetCore.Identity.IdentityRole", null)
.WithMany()
.HasForeignKey("RoleId")
.OnDelete(DeleteBehavior.Cascade)
.IsRequired();
b.HasOne("Microsoft.AspNetCore.Identity.IdentityUser", null)
.WithMany()
.HasForeignKey("UserId")
.OnDelete(DeleteBehavior.Cascade)
.IsRequired();
});
modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserToken<string>", b =>
{
b.HasOne("Microsoft.AspNetCore.Identity.IdentityUser", null)
.WithMany()
.HasForeignKey("UserId")
.OnDelete(DeleteBehavior.Cascade)
.IsRequired();
});
modelBuilder.Entity("Entities.LessonEntity", b =>
{
b.Navigation("Content");
});
#pragma warning restore 612, 618
}
}
}

@ -1,452 +0,0 @@
using System;
using Microsoft.EntityFrameworkCore.Migrations;
using Npgsql.EntityFrameworkCore.PostgreSQL.Metadata;
#nullable disable
namespace DbContextLib.Migrations
{
/// <inheritdoc />
public partial class v1 : Migration
{
/// <inheritdoc />
protected override void Up(MigrationBuilder migrationBuilder)
{
migrationBuilder.CreateSequence(
name: "ContentLessonEntitySequence");
migrationBuilder.CreateTable(
name: "AspNetRoles",
columns: table => new
{
Id = table.Column<string>(type: "text", nullable: false),
Name = table.Column<string>(type: "character varying(256)", maxLength: 256, nullable: true),
NormalizedName = table.Column<string>(type: "character varying(256)", maxLength: 256, nullable: true),
ConcurrencyStamp = table.Column<string>(type: "text", nullable: true)
},
constraints: table =>
{
table.PrimaryKey("PK_AspNetRoles", x => x.Id);
});
migrationBuilder.CreateTable(
name: "AspNetUsers",
columns: table => new
{
Id = table.Column<string>(type: "text", nullable: false),
UserName = table.Column<string>(type: "character varying(256)", maxLength: 256, nullable: true),
NormalizedUserName = table.Column<string>(type: "character varying(256)", maxLength: 256, nullable: true),
Email = table.Column<string>(type: "character varying(256)", maxLength: 256, nullable: true),
NormalizedEmail = table.Column<string>(type: "character varying(256)", maxLength: 256, nullable: true),
EmailConfirmed = table.Column<bool>(type: "boolean", nullable: false),
PasswordHash = table.Column<string>(type: "text", nullable: true),
SecurityStamp = table.Column<string>(type: "text", nullable: true),
ConcurrencyStamp = table.Column<string>(type: "text", nullable: true),
PhoneNumber = table.Column<string>(type: "text", nullable: true),
PhoneNumberConfirmed = table.Column<bool>(type: "boolean", nullable: false),
TwoFactorEnabled = table.Column<bool>(type: "boolean", nullable: false),
LockoutEnd = table.Column<DateTimeOffset>(type: "timestamp with time zone", nullable: true),
LockoutEnabled = table.Column<bool>(type: "boolean", nullable: false),
AccessFailedCount = table.Column<int>(type: "integer", nullable: false)
},
constraints: table =>
{
table.PrimaryKey("PK_AspNetUsers", x => x.Id);
});
migrationBuilder.CreateTable(
name: "BlackList",
columns: table => new
{
Email = table.Column<string>(type: "text", nullable: false),
ExpirationDate = table.Column<DateOnly>(type: "date", nullable: false)
},
constraints: table =>
{
table.PrimaryKey("PK_BlackList", x => x.Email);
});
migrationBuilder.CreateTable(
name: "Inquiries",
columns: table => new
{
Id = table.Column<int>(type: "integer", nullable: false)
.Annotation("Npgsql:ValueGenerationStrategy", NpgsqlValueGenerationStrategy.IdentityByDefaultColumn),
Title = table.Column<string>(type: "text", nullable: false),
Description = table.Column<string>(type: "text", nullable: false),
IsUser = table.Column<bool>(type: "boolean", nullable: false)
},
constraints: table =>
{
table.PrimaryKey("PK_Inquiries", x => x.Id);
});
migrationBuilder.CreateTable(
name: "Lesson",
columns: table => new
{
Id = table.Column<int>(type: "integer", nullable: false)
.Annotation("Npgsql:ValueGenerationStrategy", NpgsqlValueGenerationStrategy.IdentityByDefaultColumn),
Title = table.Column<string>(type: "text", nullable: false),
LastPublisher = table.Column<string>(type: "text", nullable: false),
LastEdit = table.Column<DateOnly>(type: "date", nullable: false)
},
constraints: table =>
{
table.PrimaryKey("PK_Lesson", x => x.Id);
});
migrationBuilder.CreateTable(
name: "User",
columns: table => new
{
Id = table.Column<int>(type: "integer", nullable: false)
.Annotation("Npgsql:ValueGenerationStrategy", NpgsqlValueGenerationStrategy.IdentityByDefaultColumn),
Username = table.Column<string>(type: "text", nullable: false),
Password = table.Column<string>(type: "text", nullable: false),
Email = table.Column<string>(type: "text", nullable: false),
IsAdmin = table.Column<bool>(type: "boolean", nullable: false)
},
constraints: table =>
{
table.PrimaryKey("PK_User", x => x.Id);
});
migrationBuilder.CreateTable(
name: "AspNetRoleClaims",
columns: table => new
{
Id = table.Column<int>(type: "integer", nullable: false)
.Annotation("Npgsql:ValueGenerationStrategy", NpgsqlValueGenerationStrategy.IdentityByDefaultColumn),
RoleId = table.Column<string>(type: "text", nullable: false),
ClaimType = table.Column<string>(type: "text", nullable: true),
ClaimValue = table.Column<string>(type: "text", nullable: true)
},
constraints: table =>
{
table.PrimaryKey("PK_AspNetRoleClaims", x => x.Id);
table.ForeignKey(
name: "FK_AspNetRoleClaims_AspNetRoles_RoleId",
column: x => x.RoleId,
principalTable: "AspNetRoles",
principalColumn: "Id",
onDelete: ReferentialAction.Cascade);
});
migrationBuilder.CreateTable(
name: "AspNetUserClaims",
columns: table => new
{
Id = table.Column<int>(type: "integer", nullable: false)
.Annotation("Npgsql:ValueGenerationStrategy", NpgsqlValueGenerationStrategy.IdentityByDefaultColumn),
UserId = table.Column<string>(type: "text", nullable: false),
ClaimType = table.Column<string>(type: "text", nullable: true),
ClaimValue = table.Column<string>(type: "text", nullable: true)
},
constraints: table =>
{
table.PrimaryKey("PK_AspNetUserClaims", x => x.Id);
table.ForeignKey(
name: "FK_AspNetUserClaims_AspNetUsers_UserId",
column: x => x.UserId,
principalTable: "AspNetUsers",
principalColumn: "Id",
onDelete: ReferentialAction.Cascade);
});
migrationBuilder.CreateTable(
name: "AspNetUserLogins",
columns: table => new
{
LoginProvider = table.Column<string>(type: "text", nullable: false),
ProviderKey = table.Column<string>(type: "text", nullable: false),
ProviderDisplayName = table.Column<string>(type: "text", nullable: true),
UserId = table.Column<string>(type: "text", nullable: false)
},
constraints: table =>
{
table.PrimaryKey("PK_AspNetUserLogins", x => new { x.LoginProvider, x.ProviderKey });
table.ForeignKey(
name: "FK_AspNetUserLogins_AspNetUsers_UserId",
column: x => x.UserId,
principalTable: "AspNetUsers",
principalColumn: "Id",
onDelete: ReferentialAction.Cascade);
});
migrationBuilder.CreateTable(
name: "AspNetUserRoles",
columns: table => new
{
UserId = table.Column<string>(type: "text", nullable: false),
RoleId = table.Column<string>(type: "text", nullable: false)
},
constraints: table =>
{
table.PrimaryKey("PK_AspNetUserRoles", x => new { x.UserId, x.RoleId });
table.ForeignKey(
name: "FK_AspNetUserRoles_AspNetRoles_RoleId",
column: x => x.RoleId,
principalTable: "AspNetRoles",
principalColumn: "Id",
onDelete: ReferentialAction.Cascade);
table.ForeignKey(
name: "FK_AspNetUserRoles_AspNetUsers_UserId",
column: x => x.UserId,
principalTable: "AspNetUsers",
principalColumn: "Id",
onDelete: ReferentialAction.Cascade);
});
migrationBuilder.CreateTable(
name: "AspNetUserTokens",
columns: table => new
{
UserId = table.Column<string>(type: "text", nullable: false),
LoginProvider = table.Column<string>(type: "text", nullable: false),
Name = table.Column<string>(type: "text", nullable: false),
Value = table.Column<string>(type: "text", nullable: true)
},
constraints: table =>
{
table.PrimaryKey("PK_AspNetUserTokens", x => new { x.UserId, x.LoginProvider, x.Name });
table.ForeignKey(
name: "FK_AspNetUserTokens_AspNetUsers_UserId",
column: x => x.UserId,
principalTable: "AspNetUsers",
principalColumn: "Id",
onDelete: ReferentialAction.Cascade);
});
migrationBuilder.CreateTable(
name: "InquiryTable",
columns: table => new
{
OwnerId = table.Column<int>(type: "integer", nullable: false),
DatabaseName = table.Column<string>(type: "text", nullable: false),
ConnectionInfo = table.Column<string>(type: "text", nullable: false)
},
constraints: table =>
{
table.PrimaryKey("PK_InquiryTable", x => x.OwnerId);
table.ForeignKey(
name: "FK_InquiryTable_Inquiries_OwnerId",
column: x => x.OwnerId,
principalTable: "Inquiries",
principalColumn: "Id",
onDelete: ReferentialAction.Cascade);
});
migrationBuilder.CreateTable(
name: "Solution",
columns: table => new
{
OwnerId = table.Column<int>(type: "integer", nullable: false),
MurdererFirstName = table.Column<string>(type: "text", nullable: false),
MurdererLastName = table.Column<string>(type: "text", nullable: false),
MurderPlace = table.Column<string>(type: "text", nullable: false),
MurderWeapon = table.Column<string>(type: "text", nullable: false),
Explaination = table.Column<string>(type: "text", nullable: false)
},
constraints: table =>
{
table.PrimaryKey("PK_Solution", x => x.OwnerId);
table.ForeignKey(
name: "FK_Solution_Inquiries_OwnerId",
column: x => x.OwnerId,
principalTable: "Inquiries",
principalColumn: "Id",
onDelete: ReferentialAction.Cascade);
});
migrationBuilder.CreateTable(
name: "Paragraph",
columns: table => new
{
Id = table.Column<int>(type: "integer", nullable: false, defaultValueSql: "nextval('\"ContentLessonEntitySequence\"')"),
ContentContent = table.Column<string>(type: "text", nullable: false),
ContentTitle = table.Column<string>(type: "text", nullable: false),
LessonId = table.Column<int>(type: "integer", nullable: false),
Title = table.Column<string>(type: "text", nullable: false),
Content = table.Column<string>(type: "text", nullable: false),
Info = table.Column<string>(type: "text", nullable: false),
Query = table.Column<string>(type: "text", nullable: false),
Comment = table.Column<string>(type: "text", nullable: false)
},
constraints: table =>
{
table.PrimaryKey("PK_Paragraph", x => x.Id);
table.ForeignKey(
name: "FK_Paragraph_Lesson_LessonId",
column: x => x.LessonId,
principalTable: "Lesson",
principalColumn: "Id",
onDelete: ReferentialAction.Cascade);
});
migrationBuilder.CreateTable(
name: "Notepad",
columns: table => new
{
Id = table.Column<int>(type: "integer", nullable: false)
.Annotation("Npgsql:ValueGenerationStrategy", NpgsqlValueGenerationStrategy.IdentityByDefaultColumn),
UserId = table.Column<int>(type: "integer", nullable: false),
InquiryId = table.Column<int>(type: "integer", nullable: false),
Notes = table.Column<string>(type: "text", nullable: false)
},
constraints: table =>
{
table.PrimaryKey("PK_Notepad", x => x.Id);
table.ForeignKey(
name: "FK_Notepad_Inquiries_InquiryId",
column: x => x.InquiryId,
principalTable: "Inquiries",
principalColumn: "Id",
onDelete: ReferentialAction.Cascade);
table.ForeignKey(
name: "FK_Notepad_User_UserId",
column: x => x.UserId,
principalTable: "User",
principalColumn: "Id",
onDelete: ReferentialAction.Cascade);
});
migrationBuilder.CreateTable(
name: "Success",
columns: table => new
{
InquiryId = table.Column<int>(type: "integer", nullable: false),
UserId = table.Column<int>(type: "integer", nullable: false),
IsFinished = table.Column<bool>(type: "boolean", nullable: false)
},
constraints: table =>
{
table.PrimaryKey("PK_Success", x => x.InquiryId);
table.ForeignKey(
name: "FK_Success_Inquiries_InquiryId",
column: x => x.InquiryId,
principalTable: "Inquiries",
principalColumn: "Id",
onDelete: ReferentialAction.Cascade);
table.ForeignKey(
name: "FK_Success_User_UserId",
column: x => x.UserId,
principalTable: "User",
principalColumn: "Id",
onDelete: ReferentialAction.Cascade);
});
migrationBuilder.CreateIndex(
name: "IX_AspNetRoleClaims_RoleId",
table: "AspNetRoleClaims",
column: "RoleId");
migrationBuilder.CreateIndex(
name: "RoleNameIndex",
table: "AspNetRoles",
column: "NormalizedName",
unique: true);
migrationBuilder.CreateIndex(
name: "IX_AspNetUserClaims_UserId",
table: "AspNetUserClaims",
column: "UserId");
migrationBuilder.CreateIndex(
name: "IX_AspNetUserLogins_UserId",
table: "AspNetUserLogins",
column: "UserId");
migrationBuilder.CreateIndex(
name: "IX_AspNetUserRoles_RoleId",
table: "AspNetUserRoles",
column: "RoleId");
migrationBuilder.CreateIndex(
name: "EmailIndex",
table: "AspNetUsers",
column: "NormalizedEmail");
migrationBuilder.CreateIndex(
name: "UserNameIndex",
table: "AspNetUsers",
column: "NormalizedUserName",
unique: true);
migrationBuilder.CreateIndex(
name: "IX_Notepad_InquiryId",
table: "Notepad",
column: "InquiryId");
migrationBuilder.CreateIndex(
name: "IX_Notepad_UserId",
table: "Notepad",
column: "UserId");
migrationBuilder.CreateIndex(
name: "IX_Paragraph_LessonId",
table: "Paragraph",
column: "LessonId");
migrationBuilder.CreateIndex(
name: "IX_Success_UserId",
table: "Success",
column: "UserId");
}
/// <inheritdoc />
protected override void Down(MigrationBuilder migrationBuilder)
{
migrationBuilder.DropTable(
name: "AspNetRoleClaims");
migrationBuilder.DropTable(
name: "AspNetUserClaims");
migrationBuilder.DropTable(
name: "AspNetUserLogins");
migrationBuilder.DropTable(
name: "AspNetUserRoles");
migrationBuilder.DropTable(
name: "AspNetUserTokens");
migrationBuilder.DropTable(
name: "BlackList");
migrationBuilder.DropTable(
name: "InquiryTable");
migrationBuilder.DropTable(
name: "Notepad");
migrationBuilder.DropTable(
name: "Paragraph");
migrationBuilder.DropTable(
name: "Solution");
migrationBuilder.DropTable(
name: "Success");
migrationBuilder.DropTable(
name: "AspNetRoles");
migrationBuilder.DropTable(
name: "AspNetUsers");
migrationBuilder.DropTable(
name: "Lesson");
migrationBuilder.DropTable(
name: "Inquiries");
migrationBuilder.DropTable(
name: "User");
migrationBuilder.DropSequence(
name: "ContentLessonEntitySequence");
}
}
}

@ -1,592 +0,0 @@
// <auto-generated />
using System;
using DbContextLib;
using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.Infrastructure;
using Microsoft.EntityFrameworkCore.Storage.ValueConversion;
using Npgsql.EntityFrameworkCore.PostgreSQL.Metadata;
#nullable disable
namespace DbContextLib.Migrations
{
[DbContext(typeof(UserDbContext))]
partial class UserDbContextModelSnapshot : ModelSnapshot
{
protected override void BuildModel(ModelBuilder modelBuilder)
{
#pragma warning disable 612, 618
modelBuilder
.HasAnnotation("ProductVersion", "8.0.2")
.HasAnnotation("Relational:MaxIdentifierLength", 63);
NpgsqlModelBuilderExtensions.UseIdentityByDefaultColumns(modelBuilder);
modelBuilder.HasSequence("ContentLessonEntitySequence");
modelBuilder.Entity("Entities.BlackListEntity", b =>
{
b.Property<string>("Email")
.HasColumnType("text");
b.Property<DateOnly>("ExpirationDate")
.HasColumnType("date");
b.HasKey("Email");
b.ToTable("BlackList");
});
modelBuilder.Entity("Entities.ContentLessonEntity", b =>
{
b.Property<int>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("integer")
.HasDefaultValueSql("nextval('\"ContentLessonEntitySequence\"')");
NpgsqlPropertyBuilderExtensions.UseSequence(b.Property<int>("Id"));
b.Property<string>("ContentContent")
.IsRequired()
.HasColumnType("text");
b.Property<string>("ContentTitle")
.IsRequired()
.HasColumnType("text");
b.Property<int>("LessonId")
.HasColumnType("integer");
b.HasKey("Id");
b.HasIndex("LessonId");
b.ToTable((string)null);
b.UseTpcMappingStrategy();
});
modelBuilder.Entity("Entities.InquiryEntity", b =>
{
b.Property<int>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("integer");
NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property<int>("Id"));
b.Property<string>("Description")
.IsRequired()
.HasColumnType("text");
b.Property<bool>("IsUser")
.HasColumnType("boolean");
b.Property<string>("Title")
.IsRequired()
.HasColumnType("text");
b.HasKey("Id");
b.ToTable("Inquiries");
});
modelBuilder.Entity("Entities.InquiryTableEntity", b =>
{
b.Property<int>("OwnerId")
.ValueGeneratedOnAdd()
.HasColumnType("integer");
b.Property<string>("ConnectionInfo")
.IsRequired()
.HasColumnType("text");
b.Property<string>("DatabaseName")
.IsRequired()
.HasColumnType("text");
b.HasKey("OwnerId");
b.ToTable("InquiryTable");
});
modelBuilder.Entity("Entities.LessonEntity", b =>
{
b.Property<int>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("integer");
NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property<int>("Id"));
b.Property<DateOnly>("LastEdit")
.HasColumnType("date");
b.Property<string>("LastPublisher")
.IsRequired()
.HasColumnType("text");
b.Property<string>("Title")
.IsRequired()
.HasColumnType("text");
b.HasKey("Id");
b.ToTable("Lesson");
});
modelBuilder.Entity("Entities.NotepadEntity", b =>
{
b.Property<int>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("integer");
NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property<int>("Id"));
b.Property<int>("InquiryId")
.HasColumnType("integer");
b.Property<string>("Notes")
.IsRequired()
.HasColumnType("text");
b.Property<int>("UserId")
.HasColumnType("integer");
b.HasKey("Id");
b.HasIndex("InquiryId");
b.HasIndex("UserId");
b.ToTable("Notepad");
});
modelBuilder.Entity("Entities.SolutionEntity", b =>
{
b.Property<int>("OwnerId")
.ValueGeneratedOnAdd()
.HasColumnType("integer");
b.Property<string>("Explaination")
.IsRequired()
.HasColumnType("text");
b.Property<string>("MurderPlace")
.IsRequired()
.HasColumnType("text");
b.Property<string>("MurderWeapon")
.IsRequired()
.HasColumnType("text");
b.Property<string>("MurdererFirstName")
.IsRequired()
.HasColumnType("text");
b.Property<string>("MurdererLastName")
.IsRequired()
.HasColumnType("text");
b.HasKey("OwnerId");
b.ToTable("Solution");
});
modelBuilder.Entity("Entities.SuccessEntity", b =>
{
b.Property<int>("InquiryId")
.HasColumnType("integer");
b.Property<bool>("IsFinished")
.HasColumnType("boolean");
b.Property<int>("UserId")
.HasColumnType("integer");
b.HasKey("InquiryId");
b.HasIndex("UserId");
b.ToTable("Success");
});
modelBuilder.Entity("Entities.UserEntity", b =>
{
b.Property<int>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("integer");
NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property<int>("Id"));
b.Property<string>("Email")
.IsRequired()
.HasColumnType("text");
b.Property<bool>("IsAdmin")
.HasColumnType("boolean");
b.Property<string>("Password")
.IsRequired()
.HasColumnType("text");
b.Property<string>("Username")
.IsRequired()
.HasColumnType("text");
b.HasKey("Id");
b.ToTable("User");
});
modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityRole", b =>
{
b.Property<string>("Id")
.HasColumnType("text");
b.Property<string>("ConcurrencyStamp")
.IsConcurrencyToken()
.HasColumnType("text");
b.Property<string>("Name")
.HasMaxLength(256)
.HasColumnType("character varying(256)");
b.Property<string>("NormalizedName")
.HasMaxLength(256)
.HasColumnType("character varying(256)");
b.HasKey("Id");
b.HasIndex("NormalizedName")
.IsUnique()
.HasDatabaseName("RoleNameIndex");
b.ToTable("AspNetRoles", (string)null);
});
modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityRoleClaim<string>", b =>
{
b.Property<int>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("integer");
NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property<int>("Id"));
b.Property<string>("ClaimType")
.HasColumnType("text");
b.Property<string>("ClaimValue")
.HasColumnType("text");
b.Property<string>("RoleId")
.IsRequired()
.HasColumnType("text");
b.HasKey("Id");
b.HasIndex("RoleId");
b.ToTable("AspNetRoleClaims", (string)null);
});
modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUser", b =>
{
b.Property<string>("Id")
.HasColumnType("text");
b.Property<int>("AccessFailedCount")
.HasColumnType("integer");
b.Property<string>("ConcurrencyStamp")
.IsConcurrencyToken()
.HasColumnType("text");
b.Property<string>("Email")
.HasMaxLength(256)
.HasColumnType("character varying(256)");
b.Property<bool>("EmailConfirmed")
.HasColumnType("boolean");
b.Property<bool>("LockoutEnabled")
.HasColumnType("boolean");
b.Property<DateTimeOffset?>("LockoutEnd")
.HasColumnType("timestamp with time zone");
b.Property<string>("NormalizedEmail")
.HasMaxLength(256)
.HasColumnType("character varying(256)");
b.Property<string>("NormalizedUserName")
.HasMaxLength(256)
.HasColumnType("character varying(256)");
b.Property<string>("PasswordHash")
.HasColumnType("text");
b.Property<string>("PhoneNumber")
.HasColumnType("text");
b.Property<bool>("PhoneNumberConfirmed")
.HasColumnType("boolean");
b.Property<string>("SecurityStamp")
.HasColumnType("text");
b.Property<bool>("TwoFactorEnabled")
.HasColumnType("boolean");
b.Property<string>("UserName")
.HasMaxLength(256)
.HasColumnType("character varying(256)");
b.HasKey("Id");
b.HasIndex("NormalizedEmail")
.HasDatabaseName("EmailIndex");
b.HasIndex("NormalizedUserName")
.IsUnique()
.HasDatabaseName("UserNameIndex");
b.ToTable("AspNetUsers", (string)null);
});
modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserClaim<string>", b =>
{
b.Property<int>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("integer");
NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property<int>("Id"));
b.Property<string>("ClaimType")
.HasColumnType("text");
b.Property<string>("ClaimValue")
.HasColumnType("text");
b.Property<string>("UserId")
.IsRequired()
.HasColumnType("text");
b.HasKey("Id");
b.HasIndex("UserId");
b.ToTable("AspNetUserClaims", (string)null);
});
modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserLogin<string>", b =>
{
b.Property<string>("LoginProvider")
.HasColumnType("text");
b.Property<string>("ProviderKey")
.HasColumnType("text");
b.Property<string>("ProviderDisplayName")
.HasColumnType("text");
b.Property<string>("UserId")
.IsRequired()
.HasColumnType("text");
b.HasKey("LoginProvider", "ProviderKey");
b.HasIndex("UserId");
b.ToTable("AspNetUserLogins", (string)null);
});
modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserRole<string>", b =>
{
b.Property<string>("UserId")
.HasColumnType("text");
b.Property<string>("RoleId")
.HasColumnType("text");
b.HasKey("UserId", "RoleId");
b.HasIndex("RoleId");
b.ToTable("AspNetUserRoles", (string)null);
});
modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserToken<string>", b =>
{
b.Property<string>("UserId")
.HasColumnType("text");
b.Property<string>("LoginProvider")
.HasColumnType("text");
b.Property<string>("Name")
.HasColumnType("text");
b.Property<string>("Value")
.HasColumnType("text");
b.HasKey("UserId", "LoginProvider", "Name");
b.ToTable("AspNetUserTokens", (string)null);
});
modelBuilder.Entity("Entities.ParagraphEntity", b =>
{
b.HasBaseType("Entities.ContentLessonEntity");
b.Property<string>("Comment")
.IsRequired()
.HasColumnType("text");
b.Property<string>("Content")
.IsRequired()
.HasColumnType("text");
b.Property<string>("Info")
.IsRequired()
.HasColumnType("text");
b.Property<string>("Query")
.IsRequired()
.HasColumnType("text");
b.Property<string>("Title")
.IsRequired()
.HasColumnType("text");
b.ToTable("Paragraph");
});
modelBuilder.Entity("Entities.ContentLessonEntity", b =>
{
b.HasOne("Entities.LessonEntity", "Lesson")
.WithMany("Content")
.HasForeignKey("LessonId")
.OnDelete(DeleteBehavior.Cascade)
.IsRequired();
b.Navigation("Lesson");
});
modelBuilder.Entity("Entities.InquiryTableEntity", b =>
{
b.HasOne("Entities.InquiryEntity", "Owner")
.WithMany()
.HasForeignKey("OwnerId")
.OnDelete(DeleteBehavior.Cascade)
.IsRequired();
b.Navigation("Owner");
});
modelBuilder.Entity("Entities.NotepadEntity", b =>
{
b.HasOne("Entities.InquiryEntity", "Inquiry")
.WithMany()
.HasForeignKey("InquiryId")
.OnDelete(DeleteBehavior.Cascade)
.IsRequired();
b.HasOne("Entities.UserEntity", "User")
.WithMany()
.HasForeignKey("UserId")
.OnDelete(DeleteBehavior.Cascade)
.IsRequired();
b.Navigation("Inquiry");
b.Navigation("User");
});
modelBuilder.Entity("Entities.SolutionEntity", b =>
{
b.HasOne("Entities.InquiryEntity", "Owner")
.WithMany()
.HasForeignKey("OwnerId")
.OnDelete(DeleteBehavior.Cascade)
.IsRequired();
b.Navigation("Owner");
});
modelBuilder.Entity("Entities.SuccessEntity", b =>
{
b.HasOne("Entities.InquiryEntity", "Inquiry")
.WithMany()
.HasForeignKey("InquiryId")
.OnDelete(DeleteBehavior.Cascade)
.IsRequired();
b.HasOne("Entities.UserEntity", "User")
.WithMany()
.HasForeignKey("UserId")
.OnDelete(DeleteBehavior.Cascade)
.IsRequired();
b.Navigation("Inquiry");
b.Navigation("User");
});
modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityRoleClaim<string>", b =>
{
b.HasOne("Microsoft.AspNetCore.Identity.IdentityRole", null)
.WithMany()
.HasForeignKey("RoleId")
.OnDelete(DeleteBehavior.Cascade)
.IsRequired();
});
modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserClaim<string>", b =>
{
b.HasOne("Microsoft.AspNetCore.Identity.IdentityUser", null)
.WithMany()
.HasForeignKey("UserId")
.OnDelete(DeleteBehavior.Cascade)
.IsRequired();
});
modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserLogin<string>", b =>
{
b.HasOne("Microsoft.AspNetCore.Identity.IdentityUser", null)
.WithMany()
.HasForeignKey("UserId")
.OnDelete(DeleteBehavior.Cascade)
.IsRequired();
});
modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserRole<string>", b =>
{
b.HasOne("Microsoft.AspNetCore.Identity.IdentityRole", null)
.WithMany()
.HasForeignKey("RoleId")
.OnDelete(DeleteBehavior.Cascade)
.IsRequired();
b.HasOne("Microsoft.AspNetCore.Identity.IdentityUser", null)
.WithMany()
.HasForeignKey("UserId")
.OnDelete(DeleteBehavior.Cascade)
.IsRequired();
});
modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserToken<string>", b =>
{
b.HasOne("Microsoft.AspNetCore.Identity.IdentityUser", null)
.WithMany()
.HasForeignKey("UserId")
.OnDelete(DeleteBehavior.Cascade)
.IsRequired();
});
modelBuilder.Entity("Entities.LessonEntity", b =>
{
b.Navigation("Content");
});
#pragma warning restore 612, 618
}
}
}

@ -1,6 +1,8 @@
using Entities;
using Entities.SQLudeoDB;
using Microsoft.AspNetCore.Identity.EntityFrameworkCore;
using Microsoft.AspNetCore.Cryptography.KeyDerivation;
using Microsoft.EntityFrameworkCore;
using System.Security.Cryptography;
using Microsoft.AspNetCore.Identity;
namespace DbContextLib
@ -8,38 +10,66 @@ namespace DbContextLib
public class UserDbContext : IdentityDbContext<IdentityUser>
{
public DbSet<UserEntity> Users { get; set; }
public DbSet<BlackListEntity> BlackLists { get; set; }
public DbSet<InquiryEntity> Inquiries { get; set; }
public DbSet<InquiryTableEntity> InquiryTables { get; set; }
public DbSet<LessonEntity> Lessons { get; set; }
public DbSet<ParagraphEntity> Paragraphs { get; set; }
public DbSet<BlackListEntity> BlackList { get; set; }
public DbSet<InquiryEntity> Inquiry { get; set; }
public DbSet<InquiryTableEntity> InquiryTable { get; set; }
public DbSet<LessonEntity> Lesson { get; set; }
public DbSet<ContentLessonEntity> ContentLessons { get; set; }
public DbSet<ParagraphEntity> Paragraph { get; set; }
public DbSet<SolutionEntity> Solutions { get; set; }
public DbSet<SuccessEntity> Successes { get; set; }
public DbSet<NotepadEntity> Notepads { get; set; }
public UserDbContext(DbContextOptions<UserDbContext> options) : base(options)
{
}
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)
{
base.OnConfiguring(optionsBuilder);
if (!optionsBuilder.IsConfigured)
{
optionsBuilder.UseNpgsql(Environment.GetEnvironmentVariable("CO_STRING", EnvironmentVariableTarget.Process));
//optionsBuilder.UseNpgsql("Host=localhost;Database=SQLuedo;Username=admin;Password=motdepasse");
optionsBuilder.UseNpgsql("Host=localhost;Database=SQLuedo;Username=admin;Password=motdepasse").EnableSensitiveDataLogging();
}
base.OnConfiguring(optionsBuilder);
}
protected override void OnModelCreating(ModelBuilder builder)
protected override void OnModelCreating(ModelBuilder modelBuilder)
{
// Permet d'avoir les champs de la classe mère dans les classes filles et de ne pas avoir de table pour la classe mère
builder.Entity<ContentLessonEntity>().UseTpcMappingStrategy();
builder.Entity<SuccessEntity>().HasKey(s => s.UserId);
builder.Entity<SuccessEntity>().HasKey(s => s.InquiryId);
builder.Entity<InquiryEntity>().HasKey(s => s.Id);
base.OnModelCreating(builder);
modelBuilder.Entity<UserEntity>().ToTable("user");
modelBuilder.Entity<UserEntity>().HasData(
new UserEntity(1, "johnny", Convert.ToBase64String(KeyDerivation.Pbkdf2(
password: "motdepasse",
salt: RandomNumberGenerator.GetBytes(128 / 8),
prf: KeyDerivationPrf.HMACSHA256,
iterationCount: 100000,
numBytesRequested: 256 / 8)), "Johnny.RATTON@etu.uca.fr", true),
new UserEntity(2, "maxime", Convert.ToBase64String(KeyDerivation.Pbkdf2(
password: "motdepasse",
salt: RandomNumberGenerator.GetBytes(128 / 8),
prf: KeyDerivationPrf.HMACSHA256,
iterationCount: 100000,
numBytesRequested: 256 / 8)), "Maxime.SAPOUNTZIS@etu.uca.fr", true),
new UserEntity(3, "clement", Convert.ToBase64String(KeyDerivation.Pbkdf2(
password: "motdepasse",
salt: RandomNumberGenerator.GetBytes(128 / 8),
prf: KeyDerivationPrf.HMACSHA256,
iterationCount: 100000,
numBytesRequested: 256 / 8)), "Clement.CHIEU@etu.uca.fr", true),
new UserEntity(4, "erwan", Convert.ToBase64String(KeyDerivation.Pbkdf2(
password: "motdepasse",
salt: RandomNumberGenerator.GetBytes(128 / 8),
prf: KeyDerivationPrf.HMACSHA256,
iterationCount: 100000,
numBytesRequested: 256 / 8)), "Erwan.MENAGER@etu.uca.fr", true),
new UserEntity(5, "victor", Convert.ToBase64String(KeyDerivation.Pbkdf2(
password: "motdepasse",
salt: RandomNumberGenerator.GetBytes(128 / 8),
prf: KeyDerivationPrf.HMACSHA256,
iterationCount: 100000,
numBytesRequested: 256 / 8)), "Victor.GABORIT@etu.uca.fr", true));
modelBuilder.Entity<ContentLessonEntity>().HasKey(c => c.LessonId);
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);
}
}
}

@ -1,85 +0,0 @@
using DbContextLib;
using Entities;
using Microsoft.EntityFrameworkCore;
using Model.OrderCriteria;
using Shared;
namespace DbDataManager.Service;
public class BlackListDataService : IBlackListService<BlackListEntity>
{
private UserDbContext DbContext { get; set; }
public BlackListDataService(UserDbContext context)
{
DbContext = context;
context.Database.EnsureCreated();
}
public int GetNumberOfBannedUsers()
{
return DbContext.BlackLists.Count();
}
public IEnumerable<BlackListEntity> GetBannedUsers(int page, int number, BlackListOdrerCriteria orderCriteria)
{
if (page <= 0)
{
page = 1;
}
if (number <= 0)
{
number = 10;
}
IQueryable<BlackListEntity> query = DbContext.BlackLists.Skip((page - 1) * number).Take(number);
switch (orderCriteria)
{
case BlackListOdrerCriteria.None:
break;
case BlackListOdrerCriteria.ByEmail:
query = query.OrderBy(s => s.Email);
break;
case BlackListOdrerCriteria.ByExpirationDate:
query = query.OrderBy(s => s.ExpirationDate);
break;
default:
break;
}
var blackList = query.ToList();
return blackList;
}
public BlackListEntity? GetUserBannedByEmail(string email)
{
var blackListEntity = DbContext.BlackLists.FirstOrDefault(b => b.Email == email);
return blackListEntity;
}
public bool BanUser(string username)
{
var userEntity = DbContext.Users.FirstOrDefault(u => u.Username == username);
if (userEntity == null)
{
return false;
}
DbContext.BlackLists.Add(new BlackListEntity
{ Email = userEntity.Email, ExpirationDate = DateOnly.FromDateTime(DateTime.Now.AddYears(2)) });
DbContext.Users.Remove(userEntity);
DbContext.SaveChangesAsync();
return true;
}
public bool UnbanUser(string email)
{
var blackListEntity = DbContext.BlackLists.FirstOrDefault(b => b.Email == email);
if (blackListEntity == null)
{
return false;
}
DbContext.BlackLists.Remove(blackListEntity);
DbContext.SaveChangesAsync();
return true;
}
}

@ -1,125 +0,0 @@
using DbContextLib;
using Entities;
using Microsoft.EntityFrameworkCore;
using Model.OrderCriteria;
using Shared;
namespace DbDataManager.Service;
public class InquiryDataService : IInquiryService<InquiryEntity>
{
private UserDbContext DbContext { get; set; }
public InquiryDataService(UserDbContext context)
{
DbContext = context;
context.Database.EnsureCreated();
}
public IEnumerable<InquiryEntity> GetInquiries(int page, int number, InquiryOrderCriteria orderCriteria)
{
if (page <= 0)
{
page = 1;
}
if (number <= 0)
{
number = 10;
}
IQueryable<InquiryEntity> query = DbContext.Inquiries;
switch (orderCriteria)
{
case InquiryOrderCriteria.None:
break;
case InquiryOrderCriteria.ByTitle:
query = query.OrderBy(s => s.Title);
break;
case InquiryOrderCriteria.ByDescription:
query = query.OrderBy(s => s.Description);
break;
case InquiryOrderCriteria.ByIsUser:
query = query.OrderBy(s => s.IsUser);
break;
case InquiryOrderCriteria.ById:
query = query.OrderBy(s => s.Id);
break;
default:
break;
}
query = query.Skip((page - 1) * number).Take(number);
var inquiries = query.ToList();
return inquiries;
}
public int GetNumberOfInquiries()
{
return DbContext.Inquiries.Count();
}
public InquiryEntity GetInquiryById(int id)
{
var inquiryEntity = DbContext.Inquiries.FirstOrDefault(i => i.Id == id);
if (inquiryEntity == null)
{
throw new ArgumentException("Impossible de trouver l'enquête", nameof(id));
}
return inquiryEntity;
}
public InquiryEntity GetInquiryByTitle(string title)
{
var inquiryEntity = DbContext.Inquiries.FirstOrDefault(i => i.Title == title);
if (inquiryEntity == null)
{
throw new ArgumentException("Impossible de trouver l'enquête", nameof(title));
}
return inquiryEntity;
}
public InquiryEntity CreateInquiry(string title, string description, bool isUser)
{
var newInquiryEntity = new InquiryEntity
{
Title = title,
Description = description,
IsUser = isUser
};
DbContext.Inquiries.Add(newInquiryEntity);
DbContext.SaveChangesAsync();
return newInquiryEntity;
}
public bool DeleteInquiry(int id)
{
var inquiryEntity = DbContext.Inquiries.FirstOrDefault(u => u.Id == id);
if (inquiryEntity == null)
{
return false;
}
DbContext.Inquiries.Remove(inquiryEntity);
DbContext.SaveChanges();
return true;
}
public InquiryEntity UpdateInquiry(int id, InquiryEntity inquiry)
{
var updatingInquiry = DbContext.Inquiries.FirstOrDefault(u => u.Id == id);
if (updatingInquiry == null)
{
throw new ArgumentException("Impossible de trouver l'enquête", nameof(id));
}
foreach (var pptt in typeof(InquiryEntity).GetProperties()
.Where(p => p.CanWrite && p.Name != nameof(InquiryEntity.Id)))
{
pptt.SetValue(updatingInquiry, pptt.GetValue(inquiry));
}
DbContext.SaveChangesAsync();
return updatingInquiry;
}
}

@ -1,27 +0,0 @@
using DbContextLib;
using Entities;
using Shared;
namespace DbDataManager.Service;
public class InquiryTableDataService : IInquiryTableService<InquiryTableEntity>
{
private UserDbContext DbContext { get; set; }
public InquiryTableDataService(UserDbContext context)
{
DbContext = context;
context.Database.EnsureCreated();
}
public string GetDatabaseNameByInquiryId(int id)
{
var inquiryTable = DbContext.InquiryTables.FirstOrDefault(i => i.OwnerId == id);
if (inquiryTable == null)
{
throw new ArgumentException($"Erreur, impossible de trouver l'objet InquiryTable pour l'enquête d'id {id}",
nameof(id));
}
return inquiryTable.DatabaseName;
}
}

@ -1,126 +0,0 @@
using DbContextLib;
using Entities;
using Microsoft.AspNetCore.Mvc.ModelBinding;
using Microsoft.EntityFrameworkCore;
using Model.OrderCriteria;
using Shared;
namespace DbDataManager.Service;
public class LessonDataService : ILessonService<LessonEntity>
{
private UserDbContext DbContext { get; set; }
public LessonDataService(UserDbContext context)
{
DbContext = context;
context.Database.EnsureCreated();
}
public IEnumerable<LessonEntity> GetLessons(int page, int number, LessonOrderCriteria orderCriteria)
{
if (page <= 0)
{
page = 1;
}
if (number <= 0)
{
number = 10;
}
IQueryable<LessonEntity> query = DbContext.Lessons;
switch (orderCriteria)
{
case LessonOrderCriteria.None:
break;
case LessonOrderCriteria.ByTitle:
query = query.OrderBy(s => s.Title);
break;
case LessonOrderCriteria.ByLastPublisher:
query = query.OrderBy(s => s.LastPublisher);
break;
case LessonOrderCriteria.ByLastEdit:
query = query.OrderBy(s => s.LastEdit);
break;
case LessonOrderCriteria.ById:
query = query.OrderBy(s => (int) s.Id);
break;
default:
break;
}
query = query.Skip((page - 1) * number).Take(number);
var lessons = query.ToList();
return lessons;
}
public int GetNumberOfLessons()
{
return DbContext.Lessons.Count();
}
public LessonEntity GetLessonById(int id)
{
var lessonEntity = DbContext.Lessons.FirstOrDefault(u => u.Id == id);
if (lessonEntity == null)
{
throw new ArgumentException("Impossible de trouver la leçon", nameof(id));
}
return lessonEntity;
}
public LessonEntity GetLessonByTitle(string title)
{
var lessonEntity = DbContext.Lessons.FirstOrDefault(u => u.Title == title);
if (lessonEntity == null)
{
throw new ArgumentException("Impossible de trouver la leçon", nameof(title));
}
return lessonEntity;
}
public bool DeleteLesson(int id)
{
var lessonEntity = DbContext.Lessons.FirstOrDefault(l => l.Id == id);
if (lessonEntity == null)
return false;
DbContext.Lessons.Remove(lessonEntity);
DbContext.SaveChanges();
return true;
}
public LessonEntity UpdateLesson(int id, LessonEntity lesson)
{
var updatingLesson = DbContext.Lessons.FirstOrDefault(l => l.Id == id);
if (updatingLesson == null)
throw new ArgumentException("Impossible de trouver la leçon", nameof(id));
updatingLesson.Title = lesson.Title;
updatingLesson.LastPublisher = lesson.LastPublisher;
updatingLesson.LastEdit = lesson.LastEdit;
DbContext.SaveChanges();
return updatingLesson;
}
public LessonEntity CreateLesson(int id, string title, string lastPublisher, DateOnly lastEdit)
{
var newLessonEntity = new LessonEntity()
{
Id = id > 0 && DbContext.Lessons.All(l => l.Id != id) ? id : 0,
Title = title,
LastPublisher = lastPublisher,
LastEdit = lastEdit,
};
DbContext.Lessons.Add(newLessonEntity);
DbContext.SaveChanges();
return newLessonEntity;
}
}

@ -1,68 +0,0 @@
using DbContextLib;
using Entities;
using Shared;
namespace DbDataManager.Service;
public class NotepadDataService : INotepadService<NotepadEntity>
{
private UserDbContext DbContext { get; set; }
public NotepadDataService(UserDbContext context)
{
DbContext = context;
context.Database.EnsureCreated();
}
public NotepadEntity GetNotepadFromUserAndInquiryId(int userId, int inquiryId)
{
var user = DbContext.Users.FirstOrDefault(u => u.Id == userId);
if (user == null)
{
throw new ArgumentException("Erreur, aucun utilisateur ne possède l'ID fourni");
}
var inquiry = DbContext.Inquiries.FirstOrDefault(i => i.Id == inquiryId);
if (inquiry == null)
{
throw new ArgumentException("Erreur, aucune enquête ne possède l'ID fourni");
}
var notepad = DbContext.Notepads.FirstOrDefault(n => n.UserId == userId && n.InquiryId == inquiryId);
if (notepad == null)
{
throw new ArgumentException("Erreur, aucun bloc-notes n'existe pour l'utilisateur et l'enquête donnés");
}
return notepad;
}
public void SetNotepadFromUserAndInquiryId(int userId, int inquiryId, string notes)
{
var user = DbContext.Users.FirstOrDefault(u => u.Id == userId);
if (user == null)
{
throw new ArgumentException("Erreur, aucun utilisateur ne possède l'ID fourni");
}
var inquiry = DbContext.Inquiries.FirstOrDefault(i => i.Id == inquiryId);
if (inquiry == null)
{
throw new ArgumentException("Erreur, aucune enquête ne possède l'ID fourni");
}
var notepad = DbContext.Notepads.FirstOrDefault(n => n.UserId == userId && n.InquiryId == inquiryId);
if (notepad != null)
{
notepad.Notes = notes;
//throw new ArgumentException("Erreur, un bloc-notes existe déjà pour l'utilisateur et l'enquête donnée");
}
else
{
DbContext.Notepads.Add(new NotepadEntity { UserId = userId, InquiryId = inquiryId, Notes = notes });
}
DbContext.SaveChangesAsync();
}
public void UpdateNotepadFromUserAndInquiryId(int userId, int inquiryId, string notes)
{
var notepad = GetNotepadFromUserAndInquiryId(userId, inquiryId);
notepad.Notes = notes;
DbContext.SaveChangesAsync();
}
}

@ -1,146 +0,0 @@
using DbContextLib;
using Entities;
using Microsoft.EntityFrameworkCore;
using Model.OrderCriteria;
using Shared;
namespace DbDataManager.Service;
public class ParagraphDataService : IParagraphService<ParagraphEntity>
{
private UserDbContext DbContext { get; set; }
public ParagraphDataService(UserDbContext context)
{
DbContext = context;
context.Database.EnsureCreated();
}
public IEnumerable<ParagraphEntity> GetParagraphs(int page, int number, ParagraphOrderCriteria orderCriteria)
{
if (page <= 0)
{
page = 1;
}
if (number <= 0)
{
number = 10;
}
IQueryable<ParagraphEntity> query = DbContext.Paragraphs.Skip((page - 1) * number).Take(number);
switch (orderCriteria)
{
case ParagraphOrderCriteria.None:
break;
case ParagraphOrderCriteria.ByTitle:
query = query.OrderBy(s => s.Title);
break;
case ParagraphOrderCriteria.ByContent:
query = query.OrderBy(s => s.Content);
break;
case ParagraphOrderCriteria.ByInfo:
query = query.OrderBy(s => s.Info);
break;
case ParagraphOrderCriteria.ByQuery:
query = query.OrderBy(s => s.Query);
break;
case ParagraphOrderCriteria.ByComment:
query = query.OrderBy(s => s.Comment);
break;
default:
break;
}
var paragraphs = query.ToList();
return paragraphs;
}
public IEnumerable<ParagraphEntity> GetParagraphsByLessonId(int lessonId)
{
var lesson = DbContext.Lessons.FirstOrDefault(l => l.Id == lessonId);
if (lesson == null)
{
throw new ArgumentException($"Erreur, la leçon ayant pour id {lessonId} est introuvable.");
}
var list = DbContext.Paragraphs.Where(p => p.LessonId == lessonId);
return list;
}
public ParagraphEntity GetParagraphById(int id)
{
var paragraphEntity = DbContext.Paragraphs.FirstOrDefault(u => u.Id == id);
if (paragraphEntity == null)
{
throw new ArgumentException("Impossible de trouver le paragraphe", nameof(id));
}
return paragraphEntity;
}
public ParagraphEntity GetParagraphByTitle(string title)
{
var paragraphEntity = DbContext.Paragraphs.FirstOrDefault(u => u.Title == title);
if (paragraphEntity == null)
{
throw new ArgumentException("Impossible de trouver le paragraphe", nameof(title));
}
return paragraphEntity;
}
public bool DeleteParagraph(int id)
{
var paragraphEntity = DbContext.Paragraphs.FirstOrDefault(p => p.Id == id);
if (paragraphEntity == null)
{
return false;
}
DbContext.Paragraphs.Remove(paragraphEntity);
DbContext.SaveChanges();
return true;
}
public ParagraphEntity UpdateParagraph(int id, ParagraphEntity paragraph)
{
var updatingParagraph = DbContext.Paragraphs.FirstOrDefault(p => p.Id == id);
if (updatingParagraph == null)
{
throw new ArgumentException("Impossible de trouver le paragraphe", nameof(id));
}
foreach (var pptt in typeof(ParagraphEntity).GetProperties().Where(p =>
p.CanWrite && p.Name != nameof(ParagraphEntity.Id) && p.Name != nameof(ParagraphEntity.LessonId)))
{
pptt.SetValue(updatingParagraph, pptt.GetValue(paragraph));
}
/*updatingParagraph.ContentTitle = paragraph.ContentTitle;
updatingParagraph.ContentContent = paragraph.ContentContent;
updatingParagraph.Title = paragraph.Title;
updatingParagraph.Content = paragraph.Content;
updatingParagraph.Info = paragraph.Info;
updatingParagraph.Query = paragraph.Query;
updatingParagraph.Comment = paragraph.Comment;
updatingParagraph.LessonId = paragraph.LessonId;*/
DbContext.SaveChangesAsync();
return updatingParagraph;
}
public ParagraphEntity CreateParagraph(string contentTitle, string contentContent, string title, string content, string info, string query, string comment,
int lessonId)
{
var newParagraphEntity = new ParagraphEntity()
{
ContentContent = contentContent,
ContentTitle = contentTitle,
Title = title,
Content = content,
Info = info,
Query = query,
Comment = comment,
LessonId = lessonId
};
DbContext.Paragraphs.Add(newParagraphEntity);
DbContext.SaveChangesAsync();
return newParagraphEntity;
}
}

@ -1,26 +0,0 @@
using DbContextLib;
using Entities;
using Shared;
namespace DbDataManager.Service;
public class SolutionDataService : ISolutionService<SolutionEntity>
{
private UserDbContext DbContext { get; set; }
public SolutionDataService(UserDbContext context)
{
DbContext = context;
context.Database.EnsureCreated();
}
public SolutionEntity GetSolutionByInquiryId(int id)
{
var solution = DbContext.Solutions.FirstOrDefault(s => s.OwnerId == id);
if (solution == null)
{
throw new ArgumentException($"Impossible de trouver la solution pour l'enquête d'id {id}", nameof(id));
}
return solution;
}
}

@ -1,137 +0,0 @@
using DbContextLib;
using Entities;
using Microsoft.EntityFrameworkCore;
using Model.OrderCriteria;
using Shared;
namespace DbDataManager.Service;
public class SuccessDataService : ISuccessService<SuccessEntity>
{
private UserDbContext DbContext { get; set; }
public SuccessDataService(UserDbContext context)
{
DbContext = context;
context.Database.EnsureCreated();
}
public IEnumerable<SuccessEntity> GetSuccesses(int page, int number, SuccessOrderCriteria orderCriteria)
{
if (page <= 0)
{
page = 1;
}
if (number <= 0)
{
number = 10;
}
IQueryable<SuccessEntity> query = DbContext.Successes.Skip((page - 1) * number).Take(number);
switch (orderCriteria)
{
case SuccessOrderCriteria.None:
break;
case SuccessOrderCriteria.ByUserId:
query = query.OrderBy(s => s.UserId);
break;
case SuccessOrderCriteria.ByInquiryId:
query = query.OrderBy(s => s.InquiryId);
break;
case SuccessOrderCriteria.ByIsFinished:
query = query.OrderBy(s => s.IsFinished);
break;
default:
break;
}
var successes = query.ToList();
return successes;
}
public IEnumerable<SuccessEntity> GetSuccessesByUserId(int id)
{
UserIdIsValid(id);
var successes = DbContext.Successes.Where(u => u.UserId == id);
return successes;
}
public IEnumerable<SuccessEntity> GetSuccessesByInquiryId(int id)
{
InquiryIdIsValid(id);
var successes = DbContext.Successes.Where(u => u.InquiryId == id);
return successes;
}
public bool DeleteSuccess(int idUser, int idInquiry)
{
var successEntity = DbContext.Successes.FirstOrDefault(u => u.UserId == idUser && u.InquiryId == idInquiry);
if (successEntity == null)
{
return false;
}
DbContext.Successes.Remove(successEntity);
DbContext.SaveChangesAsync();
return true;
}
public SuccessEntity UpdateSuccess(int idUser, int idInquiry, SuccessEntity success)
{
AreValdIds(idUser, idInquiry);
var updatingSuccess =
DbContext.Successes.FirstOrDefaultAsync(u => u.UserId == idUser && u.InquiryId == idInquiry);
if (updatingSuccess.Result == null) throw new ArgumentException("success", nameof(idUser));
/*foreach (var pptt in typeof(SuccessEntity).GetProperties().Where(p =>
p.CanWrite && p.Name != nameof(SuccessEntity.UserId) && p.Name != nameof(SuccessEntity.InquiryId)))
{
pptt.SetValue(updatingSuccess, pptt.GetValue(success));
}*/
updatingSuccess.Result.IsFinished = success.IsFinished;
DbContext.SaveChangesAsync();
return updatingSuccess.Result;
}
public SuccessEntity CreateSuccess(int userId, int inquiryId, bool isFinished)
{
AreValdIds(userId, inquiryId);
var newSuccessEntity = new SuccessEntity
{
UserId = userId,
InquiryId = inquiryId,
IsFinished = isFinished,
};
var success = DbContext.Successes.FirstOrDefaultAsync(s => s.UserId == userId && s.InquiryId == inquiryId);
if (success.Result != null) throw new ArgumentException("success", nameof(userId));
DbContext.Successes.Add(newSuccessEntity);
DbContext.SaveChangesAsync();
return newSuccessEntity;
}
private void AreValdIds(int userId, int inquiryId)
{
UserIdIsValid(userId);
InquiryIdIsValid(inquiryId);
}
private void UserIdIsValid(int userId)
{
var user = DbContext.Users.FirstOrDefaultAsync(u => u.Id == userId);
if (user.Result == null)
{
throw new ArgumentException("userId");
}
}
private void InquiryIdIsValid(int inquiryId)
{
var inquiry = DbContext.Inquiries.FirstOrDefaultAsync(u => u.Id == inquiryId);
if (inquiry.Result == null)
{
throw new ArgumentException("inquiryId");
}
}
}

@ -1,203 +0,0 @@
using DbContextLib;
using Entities;
using Model.OrderCriteria;
using Shared;
namespace DbDataManager.Service;
public class UserDataService : IUserService<UserEntity>
{
private UserDbContext DbContext { get; set; }
public UserDataService(UserDbContext context)
{
DbContext = context;
context.Database.EnsureCreated();
}
public UserEntity GetUserById(int id)
{
var userEntity = DbContext.Users.FirstOrDefault(u => u.Id == id);
if (userEntity == null)
{
throw new ArgumentException("Impossible de trouver l'utilisateur", nameof(id));
}
return userEntity;
}
public UserEntity 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;
}
public UserEntity GetUserByEmail(string email)
{
var userEntity = DbContext.Users.FirstOrDefault(u => u.Email == email);
if (userEntity == null)
{
throw new ArgumentException("Impossible de trouver l'utilisateur", nameof(email));
}
return userEntity;
}
public IEnumerable<UserEntity> GetUsers(int page, int number, UserOrderCriteria orderCriteria)
{
if (page <= 0)
{
page = 1;
}
if (number <= 0)
{
number = 10;
}
IQueryable<UserEntity> query = DbContext.Users;
switch (orderCriteria)
{
case UserOrderCriteria.None:
break;
case UserOrderCriteria.ById:
query = query.OrderBy(s => s.Id);
break;
case UserOrderCriteria.ByUsername:
query = query.OrderBy(s => s.Username);
break;
case UserOrderCriteria.ByEmail:
query = query.OrderBy(s => s.Email);
break;
case UserOrderCriteria.ByIsAdmin:
query = query.OrderBy(s => s.IsAdmin);
break;
default:
break;
}
query = query.Skip((page - 1) * number).Take(number);
var users = query.ToList();
return users;
}
public IEnumerable<UserEntity> GetNotAdminUsers(int page, int number, UserOrderCriteria orderCriteria)
{
if (page <= 0)
{
page = 1;
}
if (number <= 0)
{
number = 10;
}
IQueryable<UserEntity> query = DbContext.Users.Where(u => u.IsAdmin == false).Skip((page - 1) * number).Take(number);
switch (orderCriteria)
{
case UserOrderCriteria.None:
break;
case UserOrderCriteria.ById:
query = query.OrderBy(s => s.Id);
break;
case UserOrderCriteria.ByUsername:
query = query.OrderBy(s => s.Username);
break;
case UserOrderCriteria.ByEmail:
query = query.OrderBy(s => s.Email);
break;
case UserOrderCriteria.ByIsAdmin:
query = query.OrderBy(s => s.IsAdmin);
break;
default:
break;
}
var users = query.ToList();
return users;
}
public int GetNumberOfUsers()
{
return DbContext.Users.Count();
}
public bool DeleteUser(int id)
{
var userEntity = DbContext.Users.FirstOrDefault(u => u.Id == id);
if (userEntity == null)
{
return false;
}
DbContext.Users.Remove(userEntity);
DbContext.SaveChangesAsync();
return true;
}
public bool DeleteUserByUsername(string username)
{
var userEntity = DbContext.Users.FirstOrDefault(u => u.Username == username);
if (userEntity == null)
{
return false;
}
DbContext.Users.Remove(userEntity);
DbContext.SaveChangesAsync();
return true;
}
public UserEntity UpdateUser(int id, UserEntity user)
{
var updatingUser = DbContext.Users.FirstOrDefault(u => u.Id == id);
if (updatingUser == null)
{
throw new ArgumentException("Impossible de trouver l'utilisateur", nameof(id));
}
foreach (var pptt in typeof(UserEntity).GetProperties()
.Where(p => p.CanWrite && p.Name != nameof(UserEntity.Id)))
{
pptt.SetValue(updatingUser, pptt.GetValue(user));
}
DbContext.SaveChangesAsync();
return updatingUser;
}
public UserEntity CreateUser(string username, string password, string email, bool isAdmin)
{
var newUserEntity = new UserEntity
{
Username = username,
Password = password,
Email = email,
IsAdmin = isAdmin
};
DbContext.Users.Add(newUserEntity);
DbContext.SaveChangesAsync();
return newUserEntity;
}
public bool IsEmailTaken(string email)
{
var isEmail = DbContext.Users.Any(u => u.Email == email);
return isEmail;
}
public bool IsUsernameTaken(string username)
{
var isUsername = DbContext.Users.Any(u => u.Username == username);
return isUsername;
}
public UserEntity PromoteUser(int id)
{
var userEdit = GetUserById(id);
var newUserEntity = UpdateUser(id,new UserEntity{Id = id,Username = userEdit.Username,Password = userEdit.Password,Email = userEdit.Email,IsAdmin = true});
DbContext.SaveChangesAsync();
return newUserEntity;
}
}

@ -1,17 +0,0 @@
namespace Dto;
public class BlackListDto
{
public string Email { get; set; }
public DateOnly ExpirationDate { get; set; }
public BlackListDto()
{
}
public BlackListDto(string email, DateOnly expirationDate)
{
Email = email;
ExpirationDate = expirationDate;
}
}

@ -1,36 +0,0 @@
using System.Runtime.Serialization;
using System.Text.Json.Serialization;
namespace Dto;
[DataContract]
public class ContentLessonDto
{
[DataMember(Name = "id")]
public int Id { get; set; }
[DataMember(Name = "contentContent")]
public string ContentContent { get; set; }
[DataMember(Name = "contentTitle")]
public string ContentTitle { get; set; }
[DataMember(Name = "lessonId")]
public int LessonId { get; set; }
public ContentLessonDto(int id, string contentContent, string contentTitle, int lessonId)
{
Id = id;
ContentContent = contentContent;
ContentTitle = contentTitle;
LessonId = lessonId;
}
protected ContentLessonDto(string contentContent, string contentTitle, int lessonId)
{
ContentContent = contentContent;
ContentTitle = contentTitle;
LessonId = lessonId;
}
public ContentLessonDto()
{
}
}

@ -1,15 +0,0 @@
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<TargetFramework>net8.0</TargetFramework>
<ImplicitUsings>enable</ImplicitUsings>
<Nullable>enable</Nullable>
</PropertyGroup>
<ItemGroup>
<Reference Include="Newtonsoft.Json">
<HintPath>..\..\..\..\..\.nuget\packages\newtonsoft.json\13.0.1\lib\netstandard2.0\Newtonsoft.Json.dll</HintPath>
</Reference>
</ItemGroup>
</Project>

@ -1,73 +0,0 @@
using System.Runtime.Serialization;
namespace Dto;
[DataContract]
public class InquiryDto : IEquatable<InquiryDto>
{
[DataMember]
public int Id { get; set; }
[DataMember]
public string Title { get; set; }
[DataMember]
public string Description { get; set; }
[DataMember]
public bool IsUser { get; set; }
public InquiryDto()
{
}
public InquiryDto(int id, string title, string description, bool isUser)
{
Id = id;
Title = title;
Description = description;
IsUser = isUser;
}
public InquiryDto(string title, string description, bool isUser)
{
Title = title;
Description = description;
IsUser = isUser;
}
public override string ToString()
{
return $"{Id}\t{Title}\t{Description}\t{IsUser}";
}
public override bool Equals(object obj)
{
if (object.ReferenceEquals(obj, null))
{
return false;
}
if (object.ReferenceEquals(this, obj))
{
return true;
}
if (this.GetType() != obj.GetType())
{
return false;
}
return this.Equals(obj as InquiryDto);
}
public bool Equals(InquiryDto other)
{
return (this.Id == other.Id);
}
public override int GetHashCode()
{
return Id;
}
}

@ -1,19 +0,0 @@
namespace Dto;
public class InquiryTableDto
{
public int OwnerId { get; set; }
public string DatabaseName { get; set; }
public string ConnectionInfo { get; set; }
public InquiryTableDto()
{
}
public InquiryTableDto(int ownerId, string databaseName, string connectionInfo)
{
OwnerId = ownerId;
DatabaseName = databaseName;
ConnectionInfo = connectionInfo;
}
}

@ -1,80 +0,0 @@
using System.Net;
using System.Runtime.Serialization;
using System.Text.Json.Serialization;
namespace Dto;
[DataContract]
public class LessonDto : IEquatable<LessonDto>
{
[DataMember]
public int Id { get; set; }
[DataMember]
public string? Title { get; set; }
[DataMember]
public string? LastPublisher { get; set; }
[DataMember]
public DateOnly? LastEdit { get; set; }
[JsonIgnore(Condition = JsonIgnoreCondition.WhenWritingNull)]
public ICollection<ContentLessonDto> Content { get; set; } = new List<ContentLessonDto>();
public LessonDto()
{
}
public LessonDto(int id, string title, string lastPublisher, DateOnly lastEdit)
{
Id = id;
Title = title;
LastPublisher = lastPublisher;
LastEdit = lastEdit;
}
public LessonDto(int id, string title, string lastPublisher, DateOnly? lastEdit, ICollection<ContentLessonDto> content)
{
Id = id;
Title = title;
LastPublisher = lastPublisher;
LastEdit = lastEdit;
Content = content;
}
public LessonDto(string title, string lastPublisher, DateOnly lastEdit)
{
Title = title;
LastPublisher = lastPublisher;
LastEdit = lastEdit;
}
public override string ToString()
{
return $"{Id}\t{Title}\t{LastPublisher}\t{LastEdit}";
}
public override bool Equals(object obj)
{
if (object.ReferenceEquals(obj, null))
{
return false;
}
if (object.ReferenceEquals(this, obj))
{
return true;
}
if (this.GetType() != obj.GetType())
{
return false;
}
return this.Equals(obj as LessonDto);
}
public bool Equals(LessonDto other)
{
return (this.Id == other.Id);
}
public override int GetHashCode()
{
return Id;
}
}

@ -1,28 +0,0 @@
namespace Dto;
public class NotepadDto
{
public int Id { get; set; }
public int UserId { get; set; }
public int InquiryId { get; set; }
public string Notes { get; set; }
public NotepadDto()
{
}
public NotepadDto(int id, int userId, int inquiryId, string notes)
{
Id = id;
UserId = userId;
InquiryId = inquiryId;
Notes = notes;
}
public NotepadDto(int userId, int inquiryId, string notes)
{
UserId = userId;
InquiryId = inquiryId;
Notes = notes;
}
}

@ -1,90 +0,0 @@
using System.Runtime.Serialization;
namespace Dto;
[DataContract]
public class ParagraphDto : ContentLessonDto, IEquatable<ParagraphDto>
{
[DataMember(Name = "title")]
public string Title { get; set; }
[DataMember(Name = "content")]
public string Content { get; set; }
[DataMember(Name = "info")]
public string Info { get; set; }
[DataMember(Name = "query")]
public string Query { get; set; }
[DataMember(Name = "comment")]
public string Comment { get; set; }
public ParagraphDto(string contentTitle, string contentContent, string title, string content, string info, string query, string comment, int lessonId) :
base(contentContent,
contentTitle, lessonId)
{
Title = title;
Content = content;
Info = info;
Query = query;
Comment = comment;
}
public ParagraphDto(string title, string content, string info, string query, string comment, int lessonId) :
base(content,
title, lessonId)
{
Title = title;
Content = content;
Info = info;
Query = query;
Comment = comment;
}
public ParagraphDto(int id, string title, string content, string info, string query, string comment, int lessonId) :
base(id, content,
title, lessonId)
{
Id = id;
Title = title;
Content = content;
Info = info;
Query = query;
Comment = comment;
}
public ParagraphDto() : base()
{
}
public override string ToString()
{
return $"{Id}\t{Title}\t{Content}\t{Info}\t{Query}\t{Comment}";
}
public override bool Equals(object obj)
{
if (object.ReferenceEquals(obj, null))
{
return false;
}
if (object.ReferenceEquals(this, obj))
{
return true;
}
if (this.GetType() != obj.GetType())
{
return false;
}
return this.Equals(obj as ParagraphDto);
}
public bool Equals(ParagraphDto other)
{
return (this.Id == other.Id);
}
public override int GetHashCode()
{
return Id;
}
}

@ -1,36 +0,0 @@
namespace Dto;
public class SolutionDto
{
public int OwnerId { get; set; }
public string MurdererFirstName { get; set; }
public string MurdererLastName { get; set; }
public string MurderPlace { get; set; }
public string MurderWeapon { get; set; }
public string Explanation { get; set; }
public SolutionDto()
{
}
public SolutionDto(int ownerId, string murdererFirstName, string murdererLastName, string murderPlace,
string murderWeapon, string explanation)
{
OwnerId = ownerId;
MurdererFirstName = murdererFirstName;
MurdererLastName = murdererLastName;
MurderPlace = murderPlace;
MurderWeapon = murderWeapon;
Explanation = explanation;
}
public SolutionDto(string murdererFirstName, string murdererLastName, string murderPlace, string murderWeapon,
string explanation)
{
MurdererFirstName = murdererFirstName;
MurdererLastName = murdererLastName;
MurderPlace = murderPlace;
MurderWeapon = murderWeapon;
Explanation = explanation;
}
}

@ -1,54 +0,0 @@
namespace Dto;
public class SuccessDto : IEquatable<SuccessDto>
{
public int UserId { get; set; }
public int InquiryId { get; set; }
public bool IsFinished { get; set; }
public SuccessDto()
{
}
public SuccessDto(int userId, int inquiryId, bool isFinished)
{
UserId = userId;
InquiryId = inquiryId;
IsFinished = isFinished;
}
public override string ToString()
{
return $"User :{UserId}\t Enquête : {InquiryId}\t{IsFinished}";
}
public override bool Equals(object obj)
{
if (object.ReferenceEquals(obj, null))
{
return false;
}
if (object.ReferenceEquals(this, obj))
{
return true;
}
if (this.GetType() != obj.GetType())
{
return false;
}
return this.Equals(obj as SuccessDto);
}
public bool Equals(SuccessDto other)
{
return (this.UserId == other.UserId && this.InquiryId == other.InquiryId);
}
public override int GetHashCode()
{
return UserId * InquiryId;
}
}

@ -1,67 +0,0 @@
namespace Dto
{
public class UserDto : IEquatable<UserDto>
{
public int Id { get; set; }
public string Username { get; set; }
public string Password { get; set; }
public string Email { get; set; }
public bool IsAdmin { get; set; }
public UserDto()
{
}
public UserDto(int id, string username, string password, string email, bool isAdmin)
{
Id = id;
Username = username;
Password = password;
Email = email;
IsAdmin = isAdmin;
}
public UserDto(string username, string password, string email, bool isAdmin)
{
Username = username;
Password = password;
Email = email;
IsAdmin = isAdmin;
}
public override string ToString()
{
return $"{Id}\t{Username}\t{Email}\t{IsAdmin}";
}
public bool Equals(UserDto? other)
{
return (this.Id == other?.Id);
}
public override bool Equals(object? obj)
{
if (object.ReferenceEquals(obj, null))
{
return false;
}
if (object.ReferenceEquals(this, obj))
{
return true;
}
if (this.GetType() != obj.GetType())
{
return false;
}
return this.Equals(obj as UserDto);
}
public override int GetHashCode()
{
return Id;
}
}
}

@ -1,11 +0,0 @@
using System.ComponentModel.DataAnnotations;
using System.ComponentModel.DataAnnotations.Schema;
namespace Entities;
[Table("BlackList")]
public class BlackListEntity
{
[Key] public string Email { get; set; }
public DateOnly ExpirationDate { get; set; }
}

@ -1,12 +0,0 @@
using System.ComponentModel.DataAnnotations.Schema;
namespace Entities;
public abstract class ContentLessonEntity
{
public int Id { get; set; }
public string ContentContent { get; set; }
public string ContentTitle { get; set; }
[ForeignKey(nameof(Lesson))] public int LessonId { get; set; }
public LessonEntity Lesson { get; set; } = null!;
}

@ -7,13 +7,12 @@
</PropertyGroup>
<ItemGroup>
<PackageReference Include="Asp.Versioning.Mvc" Version="8.0.0" />
<PackageReference Include="Microsoft.EntityFrameworkCore" Version="8.0.2" />
<PackageReference Include="Microsoft.EntityFrameworkCore.Design" Version="8.0.2">
<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.2">
<PackageReference Include="Microsoft.EntityFrameworkCore.Tools" Version="8.0.1">
<PrivateAssets>all</PrivateAssets>
<IncludeAssets>runtime; build; native; contentfiles; analyzers; buildtransitive</IncludeAssets>
</PackageReference>

@ -1,12 +0,0 @@
using System.ComponentModel.DataAnnotations;
using System.ComponentModel.DataAnnotations.Schema;
namespace Entities;
public class InquiryEntity
{
[Key] public int Id { get; set; }
public string Title { get; set; }
public string Description { get; set; }
public bool IsUser { get; set; }
}

@ -1,18 +0,0 @@
using System.ComponentModel.DataAnnotations;
using System.ComponentModel.DataAnnotations.Schema;
namespace Entities;
[Table("InquiryTable")]
public class InquiryTableEntity
{
[Key]
[ForeignKey(nameof(Owner))]
[DatabaseGenerated(DatabaseGeneratedOption.Identity)]
[Required]
public int OwnerId { get; set; }
public InquiryEntity Owner { get; set; }
public string DatabaseName { get; set; }
public string ConnectionInfo { get; set; }
}

@ -1,13 +0,0 @@
using System.ComponentModel.DataAnnotations.Schema;
namespace Entities;
[Table("Lesson")]
public class LessonEntity
{
public int Id { get; set; }
public string Title { get; set; }
public string LastPublisher { get; set; }
public DateOnly LastEdit { get; set; }
public ICollection<ContentLessonEntity> Content { get; set; } = new List<ContentLessonEntity>();
}

@ -1,16 +0,0 @@
using System.ComponentModel.DataAnnotations.Schema;
namespace Entities;
[Table("Notepad")]
public class NotepadEntity
{
public int Id { get; set; }
[ForeignKey(nameof(User))] public int UserId { get; set; }
public UserEntity User { get; set; }
[ForeignKey(nameof(Inquiry))] public int InquiryId { get; set; }
public InquiryEntity Inquiry { get; set; }
public string Notes { get; set; }
}

@ -1,17 +0,0 @@
using System.ComponentModel.DataAnnotations.Schema;
namespace Entities;
[Table("Paragraph")]
public class ParagraphEntity : ContentLessonEntity
{
// ID
// ContentContent
// ContentTitle
// LessonId
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; }
}

@ -0,0 +1,22 @@
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Entities.SQLudeoDB
{
public class BlackListEntity
{
[Key]
public string Email { get; set; }
public DateOnly ExpirationDate { get; set; }
public BlackListEntity() { }
public BlackListEntity(string email, DateOnly expirationDate)
{
Email = email;
ExpirationDate = expirationDate;
}
}
}

@ -0,0 +1,21 @@
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.ComponentModel.DataAnnotations.Schema;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Entities.SQLudeoDB
{
public class ContentLessonEntity
{
[ForeignKey(nameof(Lesson))]
public int LessonId { get; set; }
public LessonEntity Lesson { get; set; }
[ForeignKey(nameof(Paragraph))]
public int LessonPartId { get; set; }
public ParagraphEntity Paragraph { get; set; }
}
}

@ -0,0 +1,38 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Entities.SQLudeoDB
{
public class InquiryEntity
{
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 InquiryEntity() { }
public InquiryEntity(int id, string title, string description, bool isUser, InquiryTableEntity database, SolutionEntity inquiryTable)
{
Id = id;
Title = title;
Description = description;
IsUser = isUser;
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;
}
}
}

@ -0,0 +1,32 @@
using System.ComponentModel.DataAnnotations.Schema;
using System.ComponentModel.DataAnnotations;
namespace Entities.SQLudeoDB
{
public class InquiryTableEntity
{
[Key]
[ForeignKey(nameof(Owner))]
[DatabaseGenerated(DatabaseGeneratedOption.Identity)]
[Required]
public int OwnerId { get; set; }
public InquiryEntity Owner { get; set; }
public string DatabaseName { get; set; }
public string ConnectionInfo { get; set; }
public InquiryTableEntity() { }
public InquiryTableEntity(int inquiryId, string databaseName, string connectionInfo)
{
OwnerId = inquiryId;
DatabaseName = databaseName;
ConnectionInfo = connectionInfo;
}
public InquiryTableEntity(InquiryEntity owner, string databaseName, string connectionInfo)
{
Owner = owner;
DatabaseName = databaseName;
ConnectionInfo = connectionInfo;
}
}
}

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

@ -0,0 +1,43 @@
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations.Schema;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Entities.SQLudeoDB
{
public class NotepadEntity
{
public int Id { get; set; }
[ForeignKey(nameof(User))]
public int UserId { get; set; }
public UserEntity User { get; set; }
[ForeignKey(nameof(Inquiry))]
public int InquiryId { get; set; }
public InquiryEntity Inquiry { get; set; }
public string Notes { get; set; }
public NotepadEntity() { }
public NotepadEntity(int id, int userId, UserEntity user, int inquiryId, InquiryEntity inquiry, string notes)
{
Id = id;
UserId = userId;
User = user;
InquiryId = inquiryId;
Inquiry = inquiry;
Notes = notes;
}
public NotepadEntity(int userId, UserEntity user, int inquiryId, InquiryEntity inquiry, string notes)
{
UserId = userId;
User = user;
InquiryId = inquiryId;
Inquiry = inquiry;
Notes = notes;
}
}
}

@ -0,0 +1,32 @@
namespace Entities.SQLudeoDB
{
public class ParagraphEntity
{
public int Id { get; set; }
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 ParagraphEntity() { }
public ParagraphEntity(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 ParagraphEntity(string title, string content, string info, string query, string comment)
{
Title = title;
Content = content;
Info = info;
Query = query;
Comment = comment;
}
}
}

@ -0,0 +1,41 @@
using System.ComponentModel.DataAnnotations.Schema;
using System.ComponentModel.DataAnnotations;
using System.Security.Cryptography.X509Certificates;
namespace Entities.SQLudeoDB
{
public class SolutionEntity
{
[Key]
[ForeignKey(nameof(Owner))]
[DatabaseGenerated(DatabaseGeneratedOption.Identity)]
[Required]
public int OwnerId { get; set; }
public InquiryEntity Owner { get; set; }
public string MurdererFirstName { get; set; }
public string MurdererLastName { get; set; }
public string MurderPlace { get; set; }
public string MurderWeapon { get; set; }
public string Explanation { get; set; }
public SolutionEntity() { }
public SolutionEntity(int ownerId, InquiryEntity owner, string murdererFirstName, string murdererLastName, string murderPlace, string murderWeapon, string explanation)
{
OwnerId = ownerId;
Owner = owner;
MurdererFirstName = murdererFirstName;
MurdererLastName = murdererLastName;
MurderPlace = murderPlace;
MurderWeapon = murderWeapon;
Explanation = explanation;
}
public SolutionEntity(InquiryEntity owner, string murdererFirstName, string murdererLastName, string murderPlace, string murderWeapon, string explanation)
{
Owner = owner;
MurdererFirstName = murdererFirstName;
MurdererLastName = murdererLastName;
MurderPlace = murderPlace;
MurderWeapon = murderWeapon;
Explanation = explanation;
}
}
}

@ -0,0 +1,38 @@
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.ComponentModel.DataAnnotations.Schema;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Entities.SQLudeoDB
{
public class SuccessEntity
{
[ForeignKey(nameof(User))]
public int UserId { get; set; }
public UserEntity User { get; set; }
[ForeignKey(nameof(Inquiry))]
public int InquiryId { get; set; }
public InquiryEntity Inquiry { get; set; }
public bool IsFinished { get; set; }
public SuccessEntity() { }
public SuccessEntity(int userId, int inquiryId, bool isFinished)
{
UserId = userId;
InquiryId = inquiryId;
IsFinished = isFinished;
}
public SuccessEntity(UserEntity user, InquiryEntity inquiry, bool isFinished)
{
User = user;
Inquiry = inquiry;
IsFinished = isFinished;
}
}
}

@ -0,0 +1,33 @@
using System.ComponentModel.DataAnnotations.Schema;
namespace Entities.SQLudeoDB
{
[Table("user")]
public class UserEntity
{
public int Id { get; set; }
public string Username { get; set; }
public string Password { get; set; }
public string Email { get; set; }
public bool IsAdmin { get; set; }
public UserEntity() { }
public UserEntity(int id, string username, string password, string email, bool isAdmin)
{
Id = id;
Username = username;
Password = password;
Email = email;
IsAdmin = isAdmin;
}
public UserEntity(string username, string password, string email, bool isAdmin)
{
Username = username;
Password = password;
Email = email;
IsAdmin = isAdmin;
}
}
}

@ -1,21 +0,0 @@
using System.ComponentModel.DataAnnotations;
using System.ComponentModel.DataAnnotations.Schema;
namespace Entities;
[Table("Solution")]
public class SolutionEntity
{
[Key]
[ForeignKey(nameof(Owner))]
[DatabaseGenerated(DatabaseGeneratedOption.Identity)]
[Required]
public int OwnerId { get; set; }
public InquiryEntity? Owner { get; set; }
public string MurdererFirstName { get; set; }
public string MurdererLastName { get; set; }
public string MurderPlace { get; set; }
public string MurderWeapon { get; set; }
public string Explaination { get; set; }
}

@ -1,14 +0,0 @@
using System.ComponentModel.DataAnnotations.Schema;
namespace Entities;
[Table("Success")]
public class SuccessEntity
{
[ForeignKey(nameof(User))] public int UserId { get; set; }
public UserEntity User { get; set; }
[ForeignKey(nameof(Inquiry))] public int InquiryId { get; set; }
public InquiryEntity Inquiry { get; set; }
public bool IsFinished { get; set; }
}

@ -1,16 +0,0 @@
using System.ComponentModel.DataAnnotations.Schema;
using Microsoft.EntityFrameworkCore;
namespace Entities;
[Table("User")]
[Index(nameof(Username), IsUnique = true)]
[Index(nameof(Email), IsUnique = true)]
public class UserEntity
{
public int Id { get; set; }
public string Username { get; set; }
public string Password { get; set; }
public string Email { get; set; }
public bool IsAdmin { get; set; }
}

@ -1,16 +0,0 @@
namespace Model;
public class BlackList
{
public string Email { get; set; }
public DateOnly ExpirationDate { get; set; }
public BlackList(string email, DateOnly expirationDate)
{
if (email is null or "")
throw new ArgumentException("Email cannot be null or empty");
ArgumentOutOfRangeException.ThrowIfLessThan(expirationDate, DateOnly.FromDateTime(DateTime.Now));
Email = email;
ExpirationDate = expirationDate;
}
}

@ -0,0 +1,30 @@
using Entities.SQLudeoDB;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
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,21 @@
namespace Model.Business
{
public class User
{
public int Id { get; set; }
public string Username { get; set; }
public string Password { get; set; }
public string Email { get; set; }
public bool IsAdmin { get; set; }
public User() { }
public User(int id, string username, string password, string email, bool isAdmin)
{
Id = id;
Username = username;
Password = password;
Email = email;
IsAdmin = isAdmin;
}
}
}

@ -1,24 +0,0 @@
namespace Model;
public abstract class ContentLesson
{
public int Id { get; set; }
public string ContentContent { get; set; }
public string ContentTitle { get; set; }
public int LessonId { get; set; }
protected ContentLesson(string contentContent, string contentTitle)
{
ContentContent = contentContent;
ContentTitle = contentTitle;
}
protected ContentLesson(int id, string contentContent, string contentTitle, int lessonId)
{
Id = id;
ContentContent = contentContent;
ContentTitle = contentTitle;
LessonId = lessonId;
}
}

@ -0,0 +1,30 @@
using Entities.SQLudeoDB;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
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,27 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Model.DTO
{
public class UserDTO
{
public int Id { get; set; }
public string Username { get; set; }
public string Password { get; set; }
public string Email { get; set; }
public bool IsAdmin { get; set; }
public UserDTO() { }
public UserDTO(int id, string username, string password, string email, bool isAdmin)
{
Id = id;
Username = username;
Password = password;
Email = email;
IsAdmin = isAdmin;
}
}
}

@ -1,21 +0,0 @@
namespace Model;
public class Inquiry
{
public int Id { get; set; }
public string Title { get; set; }
public string Description { get; set; }
public bool IsUser { get; set; }
public Inquiry()
{
}
public Inquiry(int id, string title, string description, bool isUser)
{
Id = id;
Title = title;
Description = description;
IsUser = isUser;
}
}

@ -1,19 +0,0 @@
namespace Model;
public class InquiryTable
{
public int OwnerId { get; set; }
public string DatabaseName { get; set; }
public string ConnectionInfo { get; set; }
public InquiryTable()
{
}
public InquiryTable(int inquiryId, string databaseName, string connectionInfo)
{
OwnerId = inquiryId;
DatabaseName = databaseName;
ConnectionInfo = connectionInfo;
}
}

@ -1,25 +0,0 @@
namespace Model;
public class Lesson
{
public int Id { get; }
public string Title { get; set; }
public string LastPublisher { get; set; }
public DateOnly LastEdit { get; set; }
public ICollection<ContentLesson> Content { get; set; } = new List<ContentLesson>();
public Lesson(int id, string title, string lastPublisher, DateOnly lastEdit)
{
Id = id;
Title = title;
LastPublisher = lastPublisher;
LastEdit = lastEdit;
}
public Lesson(string title, string lastPublisher, DateOnly lastEdit)
{
Title = title;
LastPublisher = lastPublisher;
LastEdit = lastEdit;
}
}

@ -0,0 +1,17 @@
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);
}
}

@ -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 InquiryMapper
{
public static Inquiry FromDTOToModel(this InquiryDTO dto)
{
return new Inquiry(dto.Id, dto.Title, dto.Description, dto.IsUser, dto.Database, dto.InquiryTable);
}
public static Inquiry FromEntityToModel(this InquiryEntity entity)
{
return new Inquiry(entity.Id, entity.Title, entity.Description, entity.IsUser, entity.Database, entity.InquiryTable);
}
public static InquiryDTO FromModelToDTO(this Inquiry inquiry)
{
return new InquiryDTO(inquiry.Id, inquiry.Title, inquiry.Description, inquiry.IsUser, inquiry.Database, inquiry.InquiryTable);
}
public static InquiryEntity FromModelToEntity(this Inquiry inquiry)
{
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,29 @@
using Entities.SQLudeoDB;
using Model.Business;
using Model.DTO;
namespace Model.Mappers
{
public static class UserMapper
{
public static User FromDTOToModel(this UserDTO dto)
{
return new User(dto.Id, dto.Username, dto.Password, dto.Email, dto.IsAdmin);
}
public static User FromEntityToModel(this UserEntity entity)
{
return new User(entity.Id, entity.Username, entity.Password, entity.Email, entity.IsAdmin);
}
public static UserDTO FromModelToDTO(this User user)
{
return new UserDTO(user.Id, user.Username, user.Password, user.Email, user.IsAdmin);
}
public static UserEntity FromModelToEntity(this User user)
{
return new UserEntity(user.Id, user.Username, user.Password, user.Email, user.IsAdmin);
}
}
}

@ -1,9 +1,26 @@
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<TargetFramework>net8.0</TargetFramework>
<ImplicitUsings>enable</ImplicitUsings>
<Nullable>enable</Nullable>
</PropertyGroup>
<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="..\EntityFramework\Entities.csproj" />
</ItemGroup>
</Project>

@ -1,28 +0,0 @@
namespace Model;
public class Notepad
{
public int Id { get; set; }
public int UserId { get; set; }
public int InquiryId { get; set; }
public string Notes { get; set; }
public Notepad()
{
}
public Notepad(int id, int userId, int inquiryId, string notes)
{
Id = id;
UserId = userId;
InquiryId = inquiryId;
Notes = notes;
}
public Notepad(int userId, int inquiryId, string notes)
{
UserId = userId;
InquiryId = inquiryId;
Notes = notes;
}
}

@ -1,6 +0,0 @@
namespace Model.OrderCriteria;
public enum BlackListOdrerCriteria
{
None, ByEmail, ByExpirationDate
}

@ -1,10 +0,0 @@
namespace Model.OrderCriteria;
public enum UserOrderCriteria
{
None,
ById,
ByUsername,
ByEmail,
ByIsAdmin
}

@ -1,10 +0,0 @@
namespace Model.OrderCriteria;
public enum InquiryOrderCriteria
{
None,
ByTitle,
ByDescription,
ByIsUser,
ById
}

@ -1,10 +0,0 @@
namespace Model.OrderCriteria;
public enum LessonOrderCriteria
{
None,
ByTitle,
ByLastPublisher,
ByLastEdit,
ById
}

@ -1,11 +0,0 @@
namespace Model.OrderCriteria;
public enum ParagraphOrderCriteria
{
None,
ByTitle,
ByContent,
ByInfo,
ByQuery,
ByComment
}

Some files were not shown because too many files have changed in this diff Show More

Loading…
Cancel
Save