Compare commits

..

No commits in common. 'master' and 'testConsoleEF' have entirely different histories.

@ -20,17 +20,17 @@ steps:
- cd API_SQLuedo/
- dotnet restore API_SQLuedo.sln
- dotnet test API_SQLuedo.sln -c Release --no-build --no-restore
depends_on: [build]
depends_on: [ build ]
- name: code-inspection
image: hub.codefirst.iut.uca.fr/marc.chevaldonne/codefirst-dronesonarplugin-dotnet8
secrets: [SECRET_SONAR_LOGIN]
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/**"
coverage_exclusions: "Test*/**"
commands:
- cd API_SQLuedo/
- dotnet restore API_SQLuedo.sln
@ -40,54 +40,4 @@ steps:
- 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 ]
depends_on: [ build ]

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/**

@ -21,7 +21,6 @@
<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" />
</ItemGroup>

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

@ -5,26 +5,26 @@ 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
namespace API.Controllers
{
private readonly IInquiryService<InquiryDto> _inquiryDataService;
[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)
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(InquiryDTO), 200)]
[ProducesResponseType(typeof(string), 204)]
public IActionResult GetInquiries(int page, int number, InquiryOrderCriteria orderCriteria)
{
@ -40,7 +40,7 @@ public class InquiriesController : Controller
}
[HttpGet("inquiry/{id:int}")]
[ProducesResponseType(typeof(InquiryDto), 200)]
[ProducesResponseType(typeof(InquiryDTO), 200)]
[ProducesResponseType(typeof(string), 404)]
public IActionResult GetInquiryById(int id)
{
@ -57,7 +57,7 @@ public class InquiriesController : Controller
}
[HttpGet("inquiry/{title:alpha}")]
[ProducesResponseType(typeof(InquiryDto), 200)]
[ProducesResponseType(typeof(InquiryDTO), 200)]
[ProducesResponseType(typeof(string), 404)]
public IActionResult GetInquiryByTitle(string title)
{
@ -74,7 +74,7 @@ public class InquiriesController : Controller
}
[HttpDelete("inquiry/{id:int}")]
[ProducesResponseType(typeof(InquiryDto), 200)]
[ProducesResponseType(typeof(InquiryDTO), 200)]
[ProducesResponseType(typeof(string), 404)]
public IActionResult DeleteInquiry(int id)
{
@ -92,9 +92,9 @@ public class InquiriesController : Controller
}
[HttpPost]
[ProducesResponseType(typeof(InquiryDto), 201)]
[ProducesResponseType(typeof(InquiryDTO), 201)]
[ProducesResponseType(typeof(string), 400)]
public IActionResult CreateInquiry([FromBody] InquiryDto dto)
public IActionResult CreateInquiry([FromBody] InquiryDTO dto)
{
if (dto.Title == null || dto.Description == null)
{
@ -109,12 +109,12 @@ public class InquiriesController : Controller
}
[HttpPut("inquiry/{id:int}")]
[ProducesResponseType(typeof(InquiryDto), 200)]
[ProducesResponseType(typeof(InquiryDTO), 200)]
[ProducesResponseType(typeof(string), 400)]
[ProducesResponseType(typeof(string), 404)]
public IActionResult UpdateInquiry(int id, [FromBody] InquiryDto InquiryDto)
public IActionResult UpdateInquiry(int id, [FromBody] InquiryDTO inquiryDTO)
{
if (id != InquiryDto.Id)
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();
@ -127,23 +127,14 @@ public class InquiriesController : Controller
return BadRequest();
}
if (InquiryDto != null)
if (inquiryDTO != null)
{
_logger.LogInformation("[INFORMATION] La mise à jour de l'enquête avec l'id {id} a été effectuée", id);
return Ok(_inquiryDataService.UpdateInquiry(id, InquiryDto));
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));
}
}

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

@ -5,26 +5,26 @@ using Model.OrderCriteria;
using Shared;
using Asp.Versioning;
namespace API.Controllers;
[Route("api/v{version:apiVersion}/[controller]")]
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 ILessonService<LessonDTO> _lessonDataService;
private readonly ILogger<LessonsController> _logger;
public LessonsController(ILessonService<LessonDto> lessonDataService, 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(LessonDTO), 200)]
[ProducesResponseType(typeof(string), 204)]
public IActionResult GetLessons(int page, int number, LessonOrderCriteria orderCriteria)
{
@ -39,24 +39,8 @@ namespace API.Controllers;
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(LessonDTO), 200)]
[ProducesResponseType(typeof(string), 404)]
public IActionResult GetLessonById(int id)
{
@ -73,7 +57,7 @@ namespace API.Controllers;
}
[HttpGet("lesson/{title:alpha}")]
[ProducesResponseType(typeof(LessonDto), 200)]
[ProducesResponseType(typeof(LessonDTO), 200)]
[ProducesResponseType(typeof(string), 404)]
public IActionResult GetLessonByTitle(string title)
{
@ -90,7 +74,7 @@ namespace API.Controllers;
}
[HttpDelete("lesson/{id:int}")]
[ProducesResponseType(typeof(LessonDto), 200)]
[ProducesResponseType(typeof(LessonDTO), 200)]
[ProducesResponseType(typeof(string), 404)]
public IActionResult DeleteLesson(int id)
{
@ -108,46 +92,29 @@ namespace API.Controllers;
}
[HttpPost]
[ProducesResponseType(typeof(LessonDto), 201)]
[ProducesResponseType(typeof(LessonDTO), 201)]
[ProducesResponseType(typeof(string), 400)]
[ProducesResponseType(typeof(string), 500)]
public IActionResult CreateLesson([FromBody] LessonDto dto)
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();
}
return Created(nameof(GetLessons),
_lessonDataService.CreateLesson(dto.Title, dto.LastPublisher, dto.LastEdit));
}
[HttpPut("lesson/{id:int}")]
[ProducesResponseType(typeof(LessonDto), 200)]
[ProducesResponseType(typeof(LessonDTO), 200)]
[ProducesResponseType(typeof(string), 400)]
[ProducesResponseType(typeof(string), 404)]
public IActionResult UpdateLesson(int id, [FromBody] LessonDto LessonDto)
public IActionResult UpdateLesson(int id, [FromBody] LessonDTO lessonDTO)
{
if (id != LessonDto.Id)
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();
@ -160,13 +127,14 @@ namespace API.Controllers;
return BadRequest();
}
if (LessonDto != null)
if (lessonDTO != null)
{
_logger.LogInformation("[INFORMATION] La mise à jour de la leçon avec l'id {id} a été effectuée", id);
return Ok(_lessonDataService.UpdateLesson(id, LessonDto));
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();
}
}
}

@ -5,19 +5,19 @@ 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
namespace API.Controllers
{
private readonly IParagraphService<ParagraphDto> _paragraphDataService;
[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,
public ParagraphsController(IParagraphService<ParagraphDTO> paragraphDataService,
ILogger<ParagraphsController> logger)
{
_paragraphDataService = paragraphDataService;
@ -25,7 +25,7 @@ public class ParagraphsController : Controller
}
[HttpGet("paragraphs/{page:int}/{number:int}/{orderCriteria}")]
[ProducesResponseType(typeof(ParagraphDto), 200)]
[ProducesResponseType(typeof(ParagraphDTO), 200)]
[ProducesResponseType(typeof(string), 204)]
public IActionResult GetParagraphs(int page, int number, ParagraphOrderCriteria orderCriteria)
{
@ -40,24 +40,8 @@ public class ParagraphsController : Controller
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(ParagraphDTO), 200)]
[ProducesResponseType(typeof(string), 404)]
public IActionResult GetParagraphById(int id)
{
@ -74,7 +58,7 @@ public class ParagraphsController : Controller
}
[HttpGet("paragraph/{title:alpha}")]
[ProducesResponseType(typeof(ParagraphDto), 200)]
[ProducesResponseType(typeof(ParagraphDTO), 200)]
[ProducesResponseType(typeof(string), 404)]
public IActionResult GetParagraphByTitle(string title)
{
@ -91,7 +75,7 @@ public class ParagraphsController : Controller
}
[HttpDelete("paragraph/{id:int}")]
[ProducesResponseType(typeof(ParagraphDto), 200)]
[ProducesResponseType(typeof(ParagraphDTO), 200)]
[ProducesResponseType(typeof(string), 404)]
public IActionResult DeleteParagraph(int id)
{
@ -109,12 +93,11 @@ public class ParagraphsController : Controller
}
[HttpPost]
[ProducesResponseType(typeof(ParagraphDto), 201)]
[ProducesResponseType(typeof(ParagraphDTO), 201)]
[ProducesResponseType(typeof(string), 400)]
public IActionResult CreateParagraph([FromBody] ParagraphDto dto)
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 ||
if (dto.Title == null || dto.Content == null || dto.Info == null || dto.Query == null ||
dto.Comment == null)
{
return BadRequest();
@ -124,18 +107,17 @@ public class ParagraphsController : Controller
"[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,
_paragraphDataService.CreateParagraph(dto.Title, dto.Content, dto.Info, dto.Query, dto.Comment,
dto.LessonId));
}
[HttpPut("paragraph/{id:int}")]
[ProducesResponseType(typeof(ParagraphDto), 200)]
[ProducesResponseType(typeof(ParagraphDTO), 200)]
[ProducesResponseType(typeof(string), 400)]
[ProducesResponseType(typeof(string), 404)]
public IActionResult UpdateParagraph(int id, [FromBody] ParagraphDto ParagraphDto)
public IActionResult UpdateParagraph(int id, [FromBody] ParagraphDTO paragraphDTO)
{
if (id != ParagraphDto.Id)
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();
@ -148,13 +130,14 @@ public class ParagraphsController : Controller
return BadRequest();
}
if (ParagraphDto != null)
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));
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();
}
}
}
}

@ -5,162 +5,119 @@ 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
namespace API.Controllers
{
private readonly ISuccessService<SuccessDto> _successDataService;
[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)
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(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é.");
_logger.LogError("[ERREUR] Aucun utilisateur trouvé.");
return StatusCode(204);
}
_logger.LogInformation("[INFORMATION] {nb} Succès(s) trouvé(s)", nbUser);
_logger.LogInformation("[INFORMATION] {nb} Utilisateur(s) trouvé(s)", nbUser);
return Ok(_successDataService.GetSuccesses(page, number, orderCriteria));
}
[HttpGet("success/user/{id:int}")]
[ProducesResponseType(typeof(SuccessDto), 200)]
[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));
return Ok(_successDataService.GetSuccessByUserId(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.");
return NotFound();
}
}
[HttpGet("success/inquiry/{id:int}")]
[ProducesResponseType(typeof(SuccessDto), 200)]
[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));
return Ok(_successDataService.GetSuccessByInquiryId(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.");
return NotFound();
}
}
[HttpDelete("success/{idUser:int}/{idInquiry:int}")]
[ProducesResponseType(typeof(SuccessDto), 200)]
[HttpDelete("success/{id:int}")]
[ProducesResponseType(typeof(SuccessDTO), 200)]
[ProducesResponseType(typeof(string), 404)]
public IActionResult DeleteSuccess(int idUser, int idInquiry)
public IActionResult DeleteSuccess(int id)
{
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);
var success = _successDataService.DeleteSuccess(id);
if (success)
{
_logger.LogInformation("[INFORMATION] Le succès avec l'id {id} a été supprimé.", idUser);
return Ok(success);
_logger.LogInformation("[INFORMATION] Le succès avec l'id {id} a été supprimé.", id);
return Ok(_successDataService.DeleteSuccess(id));
}
else
{
_logger.LogError("[ERREUR] Aucun succès trouvé avec l'id {id}.", idUser);
_logger.LogError("[ERREUR] Aucun succès trouvé avec l'id {id}.", id);
return NotFound();
}
}
[HttpPost]
[ProducesResponseType(typeof(SuccessDto), 201)]
[ProducesResponseType(typeof(string), 409)]
[ProducesResponseType(typeof(string), 404)]
[ProducesResponseType(typeof(SuccessDTO), 201)]
[ProducesResponseType(typeof(string), 400)]
public IActionResult CreateSuccess([FromBody] SuccessDto dto)
public IActionResult CreateSuccess([FromBody] SuccessDTO dto)
{
if (dto.UserId < 1 || dto.InquiryId < 1)
/*if (dto.UserId == null || dto.InquiryId == null)
{
_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);
return BadRequest();
}*/
_logger.LogInformation(
"[INFORMATION] Un succès a été créé : userId - {userId}, inquiryId - {inquiryId}, isFinished - {isFinished}",
dto.UserId, dto.InquiryId, dto.IsFinished);
return Created(nameof(GetSuccesses), s);
}
catch (Exception e)
{
return HandleError(e);
}
return Created(nameof(GetSuccesses),
_successDataService.CreateSuccess(dto.UserId, dto.InquiryId, dto.IsFinished));
}
[HttpPut("success/{idUser:int}/{idInquiry:int}")]
[ProducesResponseType(typeof(SuccessDto), 200)]
[HttpPut("success/{id:int}")]
[ProducesResponseType(typeof(SuccessDTO), 200)]
[ProducesResponseType(typeof(string), 400)]
[ProducesResponseType(typeof(string), 404)]
public IActionResult UpdateSuccess(int idUser, int idInquiry, [FromBody] SuccessDto successDto)
public IActionResult UpdateSuccess(int id, [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)
if (id != successDTO.UserId)
{
_logger.LogError(
"[ERREUR] Problème ID - La mise à jour du succès avec l'id de l'utilisateur {id} a échouée.",
idUser);
"[ERREUR] Problème ID - La mise à jour du succès avec l'id de l'utilisateur {id} a échouée.", id);
return BadRequest();
}
@ -168,39 +125,19 @@ public class SuccessesController : Controller
{
_logger.LogError(
"[ERREUR] Problème controlleur - La mise à jour du succès avec l'id de l'utilisateur {id} a échouée.",
idUser);
id);
return BadRequest();
}
try
if (successDTO != null)
{
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);
}
"[INFORMATION] La mise à jour du succès avec l'id de l'utilisateur {id} a été effectuée", id);
return Ok(_successDataService.UpdateSuccess(id, successDTO));
}
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");
_logger.LogError("[ERREUR] Aucun succès trouvé avec l'id de l'utilisateur {id}.", id);
return NotFound();
}
}
}

@ -5,16 +5,16 @@ 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 UsersController(ILogger<UsersController> logger, IUserService<UserDto> userService) : ControllerBase
namespace API.Controllers
{
[Route("api/v{version:apiVersion}/[controller]")]
[Authorize]
[ApiVersion("1.0")]
[ApiController]
public class UsersController(ILogger<UsersController> logger, IUserService<UserDTO> userService) : ControllerBase
{
[HttpGet("users/{page:int}/{number:int}")]
[ProducesResponseType(typeof(UserDto), 200)]
[ProducesResponseType(typeof(UserDTO), 200)]
[ProducesResponseType(typeof(string), 204)]
public IActionResult GetUsers(int page, int number, UserOrderCriteria orderCriteria)
{
@ -29,40 +29,8 @@ public class UsersController(ILogger<UsersController> logger, IUserService<UserD
return Ok(users);
}
[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)
{
logger.LogError("[ERREUR] Aucun utilisateur trouvé.");
return StatusCode(204);
}
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)
{
logger.LogError("[ERREUR] Aucun utilisateur trouvé.");
return StatusCode(204);
}
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(UserDTO), 200)]
[ProducesResponseType(typeof(string), 404)]
public IActionResult GetUserById(int id)
{
@ -79,7 +47,7 @@ public class UsersController(ILogger<UsersController> logger, IUserService<UserD
}
[HttpGet("user/{username:alpha}")]
[ProducesResponseType(typeof(UserDto), 200)]
[ProducesResponseType(typeof(UserDTO), 200)]
[ProducesResponseType(typeof(string), 404)]
public IActionResult GetUserByUsername(string username)
{
@ -91,29 +59,12 @@ public class UsersController(ILogger<UsersController> logger, IUserService<UserD
catch (ArgumentException)
{
logger.LogError("[ERREUR] Aucun utilisateur trouvé avec l'username {username}.", username);
return NotFound("Utilisateur non trouvé !");
}
}
[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(UserDTO), 200)]
[ProducesResponseType(typeof(string), 404)]
public IActionResult DeleteUser(int id)
{
@ -130,47 +81,16 @@ public class UsersController(ILogger<UsersController> logger, IUserService<UserD
}
}
[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(UserDTO), 201)]
[ProducesResponseType(typeof(string), 400)]
[ProducesResponseType(typeof(string), 409)]
[ProducesResponseType(typeof(string), 410)]
public IActionResult CreateUser([FromBody] UserDto dto)
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é");
}
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}",
@ -180,11 +100,10 @@ public class UsersController(ILogger<UsersController> logger, IUserService<UserD
}
[HttpPut("user/{id:int}")]
[ProducesResponseType(typeof(UserDto), 200)]
[ProducesResponseType(typeof(UserDTO), 200)]
[ProducesResponseType(typeof(string), 400)]
[ProducesResponseType(typeof(string), 404)]
[ProducesResponseType(typeof(string), 409)]
public IActionResult UpdateUser(int id, [FromBody] UserDto userDto)
public IActionResult UpdateUser(int id, [FromBody] UserDTO userDto)
{
if (id != userDto.Id)
{
@ -195,40 +114,18 @@ public class UsersController(ILogger<UsersController> logger, IUserService<UserD
if (!ModelState.IsValid)
{
logger.LogError(
"[ERREUR] Problème controller - La mise à jour de l'utilisateur avec l'id {id} a échouée.", id);
"[ERREUR] Problème controlleur - La mise à jour de l'utilisateur avec l'id {id} a échouée.", id);
return BadRequest();
}
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)))
if (userDto != null)
{
logger.LogInformation("[INFORMATION] La mise à jour de l'utilisateur avec l'id {id} a été effectuée",
logger.LogInformation("[INFORMATION] La mise à jour de l'utilsiateur avec l'id {id} a été effectuée",
id);
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
{
logger.LogInformation("[INFORMATION] La promotion de l'utilisateur avec l'id {id} à échouée",
id);
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"]

@ -8,74 +8,35 @@ using Entities;
using Microsoft.AspNetCore.Identity;
using Microsoft.EntityFrameworkCore;
using Microsoft.OpenApi.Models;
using Model;
using Shared;
using StubbedContextLib;
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<IUserService<UserDTO>, UserDataServiceApi>();
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<IInquiryService<InquiryDTO>, InquiryDataServiceApi>();
builder.Services.AddScoped<IParagraphService<ParagraphEntity>, ParagraphDataService>();
builder.Services.AddScoped<IParagraphService<ParagraphDto>, ParagraphDataServiceApi>();
builder.Services.AddScoped<IParagraphService<ParagraphDTO>, ParagraphDataServiceApi>();
builder.Services.AddScoped<ISuccessService<SuccessEntity>, SuccessDataService>();
builder.Services.AddScoped<ISuccessService<SuccessDto>, SuccessDataServiceApi>();
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<ILessonService<LessonDTO>, LessonDataServiceApi>();
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 =>
{
@ -117,67 +78,16 @@ builder.Services.AddSwaggerGen(option =>
}
});
});
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);
}

@ -6,16 +6,16 @@ using Shared.Mapper;
namespace API.Service;
public class InquiryDataServiceApi(IInquiryService<InquiryEntity> inquiryService) : IInquiryService<InquiryDto>
public class InquiryDataServiceApi(IInquiryService<InquiryEntity> inquiryService) : IInquiryService<InquiryDTO>
{
public InquiryDto UpdateInquiry(int id, InquiryDto inquiry)
public InquiryDTO UpdateInquiry(int id, InquiryDTO inquiry)
{
return inquiryService.UpdateInquiry(id, inquiry.FromDtoToEntity()).FromEntityToDto();
return inquiryService.UpdateInquiry(id, inquiry.FromDTOToEntity()).FromEntityToDTO();
}
public InquiryDto CreateInquiry(string title, string description, bool isUser)
public InquiryDTO CreateInquiry(string title, string description, bool isUser)
{
return inquiryService.CreateInquiry(title, description, isUser).FromEntityToDto();
return inquiryService.CreateInquiry(title, description, isUser).FromEntityToDTO();
}
public bool DeleteInquiry(int id)
@ -23,18 +23,13 @@ public class InquiryDataServiceApi(IInquiryService<InquiryEntity> inquiryService
return inquiryService.DeleteInquiry(id);
}
public IEnumerable<InquiryDto> GetInquiries(int page, int number, InquiryOrderCriteria orderCriteria)
public IEnumerable<InquiryDTO> GetInquiries(int page, int number, InquiryOrderCriteria orderCriteria)
{
var inquiries = inquiryService.GetInquiries(page, number, orderCriteria);
return inquiries.Select(i => i.FromEntityToDto()).ToList();
return inquiries.Select(i => i.FromEntityToDTO()).ToList();
}
public int GetNumberOfInquiries()
{
return inquiryService.GetNumberOfInquiries();
}
public InquiryDto GetInquiryById(int id) => inquiryService.GetInquiryById(id).FromEntityToDto();
public InquiryDTO GetInquiryById(int id) => inquiryService.GetInquiryById(id).FromEntityToDTO();
public InquiryDto GetInquiryByTitle(string title) => inquiryService.GetInquiryByTitle(title).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);
}
}

@ -6,31 +6,26 @@ using Shared.Mapper;
namespace API.Service;
public class LessonDataServiceApi(ILessonService<LessonEntity> lessonService) : ILessonService<LessonDto>
public class LessonDataServiceApi(ILessonService<LessonEntity> lessonService) : ILessonService<LessonDTO>
{
public IEnumerable<LessonDto> GetLessons(int page, int number, LessonOrderCriteria orderCriteria)
public IEnumerable<LessonDTO> GetLessons(int page, int number, LessonOrderCriteria orderCriteria)
{
var lessonsEntities = lessonService.GetLessons(page, number, orderCriteria);
return lessonsEntities.Select(e => e.FromEntityToDto()).ToList();
return lessonsEntities.Select(e => e.FromEntityToDTO()).ToList();
}
public int GetNumberOfLessons()
{
return lessonService.GetNumberOfLessons();
}
public LessonDto GetLessonById(int id) => lessonService.GetLessonById(id).FromEntityToDto();
public LessonDTO GetLessonById(int id) => lessonService.GetLessonById(id).FromEntityToDTO();
public LessonDto GetLessonByTitle(string title) => lessonService.GetLessonByTitle(title).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, LessonDTO lesson) =>
lessonService.UpdateLesson(id, lesson.FromDTOToEntity()).FromEntityToDTO();
public LessonDto UpdateLesson(int id, LessonEntity lesson) =>
lessonService.UpdateLesson(id, lesson).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();
public LessonDTO CreateLesson(string title, string lastPublisher, DateOnly? lastEdit) =>
lessonService.CreateLesson(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);
}
}

@ -7,29 +7,25 @@ using Shared.Mapper;
namespace API.Service;
public class ParagraphDataServiceApi(IParagraphService<ParagraphEntity> paragraphService)
: IParagraphService<ParagraphDto>
: IParagraphService<ParagraphDTO>
{
public IEnumerable<ParagraphDto> GetParagraphs(int page, int number, ParagraphOrderCriteria orderCriteria)
public IEnumerable<ParagraphDTO> GetParagraphs(int page, int number, ParagraphOrderCriteria orderCriteria)
{
var paragraphsEntities = paragraphService.GetParagraphs(page, number, orderCriteria);
return paragraphsEntities.Select(e => e.FromEntityToDto()).ToList();
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 GetParagraphById(int id) => paragraphService.GetParagraphById(id).FromEntityToDTO();
public ParagraphDto GetParagraphByTitle(string title) =>
paragraphService.GetParagraphByTitle(title).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 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();
public ParagraphDTO CreateParagraph(string title, string content, string info, string query, string comment,
int lessonId) =>
paragraphService.CreateParagraph(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();
}
}

@ -6,25 +6,23 @@ using Shared.Mapper;
namespace API.Service;
public class SuccessDataServiceApi(ISuccessService<SuccessEntity> sucessService) : ISuccessService<SuccessDto>
public class SuccessDataServiceApi(ISuccessService<SuccessEntity> sucessService) : ISuccessService<SuccessDTO>
{
public IEnumerable<SuccessDto> GetSuccesses(int page, int number, SuccessOrderCriteria orderCriteria)
public IEnumerable<SuccessDTO> GetSuccesses(int page, int number, SuccessOrderCriteria orderCriteria)
{
var successesEntities = sucessService.GetSuccesses(page, number, orderCriteria);
return successesEntities.Select(e => e.FromEntityToDto()).ToList();
return successesEntities.Select(e => e.FromEntityToDTO()).ToList();
}
public IEnumerable<SuccessDto> GetSuccessesByUserId(int id) =>
sucessService.GetSuccessesByUserId(id).Select(s => s.FromEntityToDto());
public SuccessDTO GetSuccessByUserId(int id) => sucessService.GetSuccessByUserId(id).FromEntityToDTO();
public IEnumerable<SuccessDto> GetSuccessesByInquiryId(int id) =>
sucessService.GetSuccessesByInquiryId(id).Select(s => s.FromEntityToDto());
public SuccessDTO GetSuccessByInquiryId(int id) => sucessService.GetSuccessByInquiryId(id).FromEntityToDTO();
public bool DeleteSuccess(int idUser, int idInquiry) => sucessService.DeleteSuccess(idUser, idInquiry);
public bool DeleteSuccess(int id) => sucessService.DeleteSuccess(id);
public SuccessDto UpdateSuccess(int idUser, int idInquiry, SuccessDto success) =>
sucessService.UpdateSuccess(idUser, idInquiry, success.FromDtoToEntity()).FromEntityToDto();
public SuccessDTO UpdateSuccess(int id, SuccessDTO success) =>
sucessService.UpdateSuccess(id, success.FromDTOToEntity()).FromEntityToDTO();
public SuccessDto CreateSuccess(int userId, int inquiryId, bool isFinished) =>
sucessService.CreateSuccess(userId, inquiryId, isFinished).FromEntityToDto();
public SuccessDTO CreateSuccess(int userId, int inquiryId, bool isFinished) =>
sucessService.CreateSuccess(userId, inquiryId, isFinished).FromEntityToDTO();
}

@ -6,43 +6,23 @@ using Shared.Mapper;
namespace API.Service;
public class UserDataServiceApi(IUserService<UserEntity> userService) : IUserService<UserDto>
public class UserDataServiceApi(IUserService<UserEntity> userService) : IUserService<UserDTO>
{
public IEnumerable<UserDto> GetUsers(int page, int number, UserOrderCriteria orderCriteria)
public IEnumerable<UserDTO> GetUsers(int page, int number, UserOrderCriteria orderCriteria)
{
var usersEntities = userService.GetUsers(page, number, orderCriteria);
return usersEntities.Select(e => e.FromEntityToDto()).ToList();
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 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 UserDTO GetUserByUsername(string username) => userService.GetUserByUsername(username).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 UpdateUser(int id, UserDTO user) =>
userService.UpdateUser(id, user.FromDTOToEntity()).FromEntityToDTO();
public UserDto PromoteUser(int id) =>
userService.PromoteUser(id).FromEntityToDto();
public UserDTO CreateUser(string username, string password, string email, bool isAdmin) =>
userService.CreateUser(username, password, email, isAdmin).FromEntityToDTO();
}

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

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

@ -23,23 +23,23 @@ namespace DbContextLib
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");
}
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();
modelBuilder.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<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;
}
}

@ -18,15 +18,7 @@ public class InquiryDataService : IInquiryService<InquiryEntity>
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;
IQueryable<InquiryEntity> query = DbContext.Inquiries.Skip((page - 1) * number).Take(number);
switch (orderCriteria)
{
case InquiryOrderCriteria.None:
@ -40,23 +32,14 @@ public class InquiryDataService : IInquiryService<InquiryEntity>
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);
@ -81,12 +64,7 @@ public class InquiryDataService : IInquiryService<InquiryEntity>
public InquiryEntity CreateInquiry(string title, string description, bool isUser)
{
var newInquiryEntity = new InquiryEntity
{
Title = title,
Description = description,
IsUser = isUser
};
var newInquiryEntity = new InquiryEntity(title, description, isUser);
DbContext.Inquiries.Add(newInquiryEntity);
DbContext.SaveChangesAsync();
return newInquiryEntity;
@ -101,7 +79,7 @@ public class InquiryDataService : IInquiryService<InquiryEntity>
}
DbContext.Inquiries.Remove(inquiryEntity);
DbContext.SaveChanges();
DbContext.SaveChangesAsync();
return true;
}

@ -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,6 +1,5 @@
using DbContextLib;
using Entities;
using Microsoft.AspNetCore.Mvc.ModelBinding;
using Microsoft.EntityFrameworkCore;
using Model.OrderCriteria;
using Shared;
@ -19,17 +18,7 @@ public class LessonDataService : ILessonService<LessonEntity>
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;
IQueryable<LessonEntity> query = DbContext.Lessons.Skip((page - 1) * number).Take(number);
switch (orderCriteria)
{
case LessonOrderCriteria.None:
@ -43,25 +32,14 @@ public class LessonDataService : ILessonService<LessonEntity>
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);
@ -88,10 +66,12 @@ public class LessonDataService : ILessonService<LessonEntity>
{
var lessonEntity = DbContext.Lessons.FirstOrDefault(l => l.Id == id);
if (lessonEntity == null)
{
return false;
}
DbContext.Lessons.Remove(lessonEntity);
DbContext.SaveChanges();
DbContext.SaveChangesAsync();
return true;
}
@ -99,28 +79,30 @@ public class LessonDataService : ILessonService<LessonEntity>
{
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;
foreach (var pptt in typeof(LessonEntity).GetProperties()
.Where(p => p.CanWrite && p.Name != nameof(LessonEntity.Id)))
{
pptt.SetValue(updatingLesson, pptt.GetValue(lesson));
}
DbContext.SaveChanges();
DbContext.SaveChangesAsync();
return updatingLesson;
}
public LessonEntity CreateLesson(int id, string title, string lastPublisher, DateOnly lastEdit)
public LessonEntity CreateLesson(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();
DbContext.SaveChangesAsync();
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();
}
}

@ -18,14 +18,6 @@ public class ParagraphDataService : IParagraphService<ParagraphEntity>
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)
{
@ -54,17 +46,6 @@ public class ParagraphDataService : IParagraphService<ParagraphEntity>
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);
@ -96,7 +77,7 @@ public class ParagraphDataService : IParagraphService<ParagraphEntity>
}
DbContext.Paragraphs.Remove(paragraphEntity);
DbContext.SaveChanges();
DbContext.SaveChangesAsync();
return true;
}
@ -113,25 +94,16 @@ public class ParagraphDataService : IParagraphService<ParagraphEntity>
{
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,
public ParagraphEntity CreateParagraph(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,

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

@ -18,14 +18,6 @@ public class SuccessDataService : ISuccessService<SuccessEntity>
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)
{
@ -48,23 +40,31 @@ public class SuccessDataService : ISuccessService<SuccessEntity>
return successes;
}
public IEnumerable<SuccessEntity> GetSuccessesByUserId(int id)
public SuccessEntity GetSuccessByUserId(int id)
{
UserIdIsValid(id);
var successes = DbContext.Successes.Where(u => u.UserId == id);
return successes;
var userEntity = DbContext.Successes.FirstOrDefault(u => u.UserId == id);
if (userEntity == null)
{
throw new ArgumentException("Impossible de trouver le succès", nameof(id));
}
return userEntity;
}
public IEnumerable<SuccessEntity> GetSuccessesByInquiryId(int id)
public SuccessEntity GetSuccessByInquiryId(int id)
{
InquiryIdIsValid(id);
var successes = DbContext.Successes.Where(u => u.InquiryId == id);
return successes;
var userEntity = DbContext.Successes.FirstOrDefault(u => u.InquiryId == id);
if (userEntity == null)
{
throw new ArgumentException("Impossible de trouver le succès", nameof(id));
}
return userEntity;
}
public bool DeleteSuccess(int idUser, int idInquiry)
public bool DeleteSuccess(int id)
{
var successEntity = DbContext.Successes.FirstOrDefault(u => u.UserId == idUser && u.InquiryId == idInquiry);
var successEntity = DbContext.Successes.FirstOrDefault(u => u.UserId == id);
if (successEntity == null)
{
return false;
@ -75,63 +75,34 @@ public class SuccessDataService : ISuccessService<SuccessEntity>
return true;
}
public SuccessEntity UpdateSuccess(int idUser, int idInquiry, SuccessEntity success)
public SuccessEntity UpdateSuccess(int id, 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));
var updatingSuccess = DbContext.Successes.FirstOrDefault(u => u.UserId == id);
if (updatingSuccess == null)
{
throw new ArgumentException("Impossible de trouver le succès", nameof(id));
}
/*foreach (var pptt in typeof(SuccessEntity).GetProperties().Where(p =>
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;
return updatingSuccess;
}
public SuccessEntity CreateSuccess(int userId, int inquiryId, bool isFinished)
{
AreValdIds(userId, inquiryId);
var newSuccessEntity = new SuccessEntity
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");
}
}
}

@ -37,65 +37,9 @@ public class UserDataService : IUserService<UserEntity>
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);
IQueryable<UserEntity> query = DbContext.Users.Skip((page - 1) * number).Take(number);
switch (orderCriteria)
{
case UserOrderCriteria.None:
@ -119,10 +63,6 @@ public class UserDataService : IUserService<UserEntity>
var users = query.ToList();
return users;
}
public int GetNumberOfUsers()
{
return DbContext.Users.Count();
}
public bool DeleteUser(int id)
{
@ -137,18 +77,6 @@ public class UserDataService : IUserService<UserEntity>
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);
@ -180,24 +108,4 @@ public class UserDataService : IUserService<UserEntity>
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,15 +1,12 @@
namespace Dto;
public class BlackListDto
public class BlackListDTO
{
public string Email { get; set; }
public DateOnly ExpirationDate { get; set; }
public BlackListDto()
{
}
public BlackListDto(string email, DateOnly expirationDate)
public BlackListDTO() {}
public BlackListDTO(string email, DateOnly expirationDate)
{
Email = email;
ExpirationDate = expirationDate;

@ -1,21 +1,13 @@
using System.Runtime.Serialization;
using System.Text.Json.Serialization;
namespace Dto;
namespace Dto;
[DataContract]
public class ContentLessonDto
public abstract 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)
protected ContentLessonDTO(int id, string contentContent, string contentTitle, int lessonId)
{
Id = id;
ContentContent = contentContent;
@ -23,14 +15,14 @@ public class ContentLessonDto
LessonId = lessonId;
}
protected ContentLessonDto(string contentContent, string contentTitle, int lessonId)
protected ContentLessonDTO(string contentContent, string contentTitle, int lessonId)
{
ContentContent = contentContent;
ContentTitle = contentTitle;
LessonId = lessonId;
}
public ContentLessonDto()
protected ContentLessonDTO()
{
}
}

@ -6,10 +6,4 @@
<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,27 +1,17 @@
using System.Runtime.Serialization;
namespace Dto;
namespace Dto;
[DataContract]
public class InquiryDto : IEquatable<InquiryDto>
public class InquiryDTO
{
[DataMember]
public int Id { get; set; }
public int Id { get; }
[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)
public InquiryDTO(){}
public InquiryDTO(int id, string title, string description, bool isUser)
{
Id = id;
Title = title;
@ -29,45 +19,10 @@ public class InquiryDto : IEquatable<InquiryDto>
IsUser = isUser;
}
public InquiryDto(string title, string description, bool 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,16 +1,16 @@
namespace Dto;
public class InquiryTableDto
public class InquiryTableDTO
{
public int OwnerId { get; set; }
public string DatabaseName { get; set; }
public string ConnectionInfo { get; set; }
public InquiryTableDto()
public InquiryTableDTO()
{
}
public InquiryTableDto(int ownerId, string databaseName, string connectionInfo)
public InquiryTableDTO(int ownerId, string databaseName, string connectionInfo)
{
OwnerId = ownerId;
DatabaseName = databaseName;

@ -1,80 +1,29 @@
using System.Net;
using System.Runtime.Serialization;
using System.Text.Json.Serialization;
namespace Dto;
namespace Dto;
[DataContract]
public class LessonDto : IEquatable<LessonDto>
public class LessonDTO
{
[DataMember]
public int Id { get; set; }
[DataMember]
public int Id { get; }
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 ICollection<ContentLessonDTO> Content { get; set; } = new List<ContentLessonDTO>();
public LessonDto()
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)
public LessonDTO(int id, string title, string lastPublisher, DateOnly? lastEdit)
{
Id = id;
Title = title;
LastPublisher = lastPublisher;
LastEdit = lastEdit;
Content = content;
}
public LessonDto(string title, string lastPublisher, DateOnly lastEdit)
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,17 +1,17 @@
namespace Dto;
public class NotepadDto
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()
{
}
public NotepadDto(int id, int userId, int inquiryId, string notes)
public NotepadDTO(int id, int userId, int inquiryId, string notes)
{
Id = id;
UserId = userId;
@ -19,7 +19,7 @@ public class NotepadDto
Notes = notes;
}
public NotepadDto(int userId, int inquiryId, string notes)
public NotepadDTO(int userId, int inquiryId, string notes)
{
UserId = userId;
InquiryId = inquiryId;

@ -1,32 +1,14 @@
using System.Runtime.Serialization;
namespace Dto;
namespace Dto;
[DataContract]
public class ParagraphDto : ContentLessonDto, IEquatable<ParagraphDto>
public class ParagraphDTO : ContentLessonDTO
{
[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) :
public ParagraphDTO(string title, string content, string info, string query, string comment, int lessonId) :
base(content,
title, lessonId)
{
@ -37,7 +19,7 @@ public class ParagraphDto : ContentLessonDto, IEquatable<ParagraphDto>
Comment = comment;
}
public ParagraphDto(int id, string title, string content, string info, string query, string comment, int lessonId) :
public ParagraphDTO(int id, string title, string content, string info, string query, string comment, int lessonId) :
base(id, content,
title, lessonId)
{
@ -49,42 +31,7 @@ public class ParagraphDto : ContentLessonDto, IEquatable<ParagraphDto>
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()
public ParagraphDTO() : base()
{
return Id;
}
}

@ -1,13 +0,0 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Dto
{
public class QueryDto
{
public string Result { get; set; }
}
}

@ -1,6 +1,6 @@
namespace Dto;
public class SolutionDto
public class SolutionDTO
{
public int OwnerId { get; set; }
public string MurdererFirstName { get; set; }
@ -9,11 +9,11 @@ public class SolutionDto
public string MurderWeapon { get; set; }
public string Explanation { get; set; }
public SolutionDto()
public SolutionDTO()
{
}
public SolutionDto(int ownerId, string murdererFirstName, string murdererLastName, string murderPlace,
public SolutionDTO(int ownerId, string murdererFirstName, string murdererLastName, string murderPlace,
string murderWeapon, string explanation)
{
OwnerId = ownerId;
@ -24,7 +24,7 @@ public class SolutionDto
Explanation = explanation;
}
public SolutionDto(string murdererFirstName, string murdererLastName, string murderPlace, string murderWeapon,
public SolutionDTO(string murdererFirstName, string murdererLastName, string murderPlace, string murderWeapon,
string explanation)
{
MurdererFirstName = murdererFirstName;

@ -1,54 +1,19 @@
namespace Dto;
public class SuccessDto : IEquatable<SuccessDto>
public class SuccessDTO
{
public int UserId { get; set; }
public int InquiryId { get; set; }
public bool IsFinished { get; set; }
public SuccessDto()
public SuccessDTO()
{
}
public SuccessDto(int userId, int inquiryId, bool isFinished)
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,18 +1,18 @@
namespace Dto
namespace Dto;
public class UserDTO
{
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()
{
}
public UserDto(int id, string username, string password, string email, bool isAdmin)
public UserDTO(int id, string username, string password, string email, bool isAdmin)
{
Id = id;
Username = username;
@ -21,7 +21,7 @@
IsAdmin = isAdmin;
}
public UserDto(string username, string password, string email, bool isAdmin)
public UserDTO(string username, string password, string email, bool isAdmin)
{
Username = username;
Password = password;
@ -33,35 +33,4 @@
{
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;
}
}
}

@ -8,4 +8,14 @@ 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;
}
}

@ -7,6 +7,32 @@ 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!;
[ForeignKey(nameof(Lesson))] public virtual int LessonId { get; set; }
public virtual LessonEntity Lesson { get; set; } = null!;
protected ContentLessonEntity()
{
}
protected ContentLessonEntity(int id, string contentContent, string contentTitle)
{
Id = id;
ContentContent = contentContent;
ContentTitle = contentTitle;
}
protected ContentLessonEntity(int id, int lessonId, string contentContent, string contentTitle)
{
Id = id;
LessonId = lessonId;
ContentContent = contentContent;
ContentTitle = contentTitle;
}
protected ContentLessonEntity(string contentContent, string contentTitle)
{
ContentContent = contentContent;
ContentTitle = contentTitle;
}
}

@ -5,8 +5,33 @@ namespace Entities;
public class InquiryEntity
{
[Key] public int Id { get; set; }
[Key] public int Id { get; }
public string Title { get; set; }
public string Description { get; set; }
public bool IsUser { get; set; }
public InquiryEntity()
{
}
public InquiryEntity(int id)
{
Id = id;
}
public InquiryEntity(string title, string description, bool isUser)
{
Id = 0;
Title = title;
Description = description;
IsUser = isUser;
}
public InquiryEntity(int id, string title, string description, bool isUser)
{
Id = id;
Title = title;
Description = description;
IsUser = isUser;
}
}

@ -15,4 +15,27 @@ public class InquiryTableEntity
public InquiryEntity Owner { get; set; }
public string DatabaseName { get; set; }
public string ConnectionInfo { get; set; }
public InquiryTableEntity()
{
}
public InquiryTableEntity(int inquiryId)
{
OwnerId = inquiryId;
}
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;
}
}

@ -6,8 +6,27 @@ namespace Entities;
public class LessonEntity
{
public int Id { get; set; }
public string Title { get; set; }
public string LastPublisher { get; set; }
public DateOnly LastEdit { 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>();
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;
}
}

@ -13,4 +13,27 @@ public class NotepadEntity
[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;
}
}

@ -14,4 +14,28 @@ public class ParagraphEntity : ContentLessonEntity
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, int idLesson) : base(id, idLesson, content, title)
{
Title = title;
Content = content;
Info = info;
Query = query;
Comment = comment;
}
public ParagraphEntity(string title, string content, string info, string query, string comment) : base(content,
title)
{
Title = title;
Content = content;
Info = info;
Query = query;
Comment = comment;
}
}

@ -13,9 +13,52 @@ public class SolutionEntity
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; }
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; }
public SolutionEntity()
{
}
public SolutionEntity(int ownerId)
{
OwnerId = ownerId;
}
public SolutionEntity(int ownerId, InquiryEntity? owner, string murdererFirstName, string murdererLastName,
string murderPlace, string murderWeapon, string explaination)
{
OwnerId = ownerId;
Owner = owner;
MurdererFirstName = murdererFirstName;
MurdererLastName = murdererLastName;
MurderPlace = murderPlace;
MurderWeapon = murderWeapon;
Explaination = explaination;
}
public SolutionEntity(InquiryEntity? owner, string murdererFirstName, string murdererLastName, string murderPlace,
string murderWeapon, string explaination)
{
Owner = owner;
MurdererFirstName = murdererFirstName;
MurdererLastName = murdererLastName;
MurderPlace = murderPlace;
MurderWeapon = murderWeapon;
Explaination = explaination;
}
public SolutionEntity(int ownerId, string murdererFirstName, string murdererLastName, string murderPlace,
string murderWeapon, string explanation)
{
OwnerId = ownerId;
MurdererFirstName = murdererFirstName;
MurdererLastName = murdererLastName;
MurderPlace = murderPlace;
MurderWeapon = murderWeapon;
Explaination = explanation;
}
}

@ -11,4 +11,31 @@ public class SuccessEntity
[ForeignKey(nameof(Inquiry))] public int InquiryId { get; set; }
public InquiryEntity Inquiry { get; set; }
public bool IsFinished { get; set; }
public SuccessEntity()
{
}
public SuccessEntity(int userId, UserEntity user, int inquiryId, InquiryEntity inquiry, bool isFinished)
{
UserId = userId;
User = user;
InquiryId = inquiryId;
Inquiry = inquiry;
IsFinished = isFinished;
}
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;
}
}

@ -1,11 +1,8 @@
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; }
@ -13,4 +10,30 @@ public class UserEntity
public string Password { get; set; }
public string Email { get; set; }
public bool IsAdmin { get; set; }
public UserEntity()
{
}
public UserEntity(int id)
{
Id = id;
}
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;
}
}

@ -3,12 +3,12 @@
public class Lesson
{
public int Id { get; }
public string Title { get; set; }
public string LastPublisher { get; set; }
public DateOnly LastEdit { get; set; }
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)
public Lesson(int id, string title, string lastPublisher, DateOnly? lastEdit)
{
Id = id;
Title = title;
@ -16,7 +16,7 @@ public class Lesson
LastEdit = lastEdit;
}
public Lesson(string title, string lastPublisher, DateOnly lastEdit)
public Lesson(string title, string lastPublisher, DateOnly? lastEdit)
{
Title = title;
LastPublisher = lastPublisher;

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

@ -5,6 +5,5 @@ public enum InquiryOrderCriteria
None,
ByTitle,
ByDescription,
ByIsUser,
ById
ByIsUser
}

@ -5,6 +5,5 @@ public enum LessonOrderCriteria
None,
ByTitle,
ByLastPublisher,
ByLastEdit,
ById
ByLastEdit
}

@ -7,30 +7,30 @@ public class Solution
public string MurdererLastName { get; set; }
public string MurderPlace { get; set; }
public string MurderWeapon { get; set; }
public string Explaination { get; set; }
public string Explanation { get; set; }
public Solution()
{
}
public Solution(int ownerId, string murdererFirstName, string murdererLastName, string murderPlace,
string murderWeapon, string explaination)
string murderWeapon, string explanation)
{
OwnerId = ownerId;
MurdererFirstName = murdererFirstName;
MurdererLastName = murdererLastName;
MurderPlace = murderPlace;
MurderWeapon = murderWeapon;
Explaination = explaination;
Explanation = explanation;
}
public Solution(string murdererFirstName, string murdererLastName, string murderPlace, string murderWeapon,
string explaination)
string explanation)
{
MurdererFirstName = murdererFirstName;
MurdererLastName = murdererLastName;
MurderPlace = murderPlace;
MurderWeapon = murderWeapon;
Explaination = explaination;
Explanation = explanation;
}
}

@ -1,12 +0,0 @@
using Model.OrderCriteria;
namespace Shared;
public interface IBlackListService<TBlackList>
{
public IEnumerable<TBlackList> GetBannedUsers(int page, int number, BlackListOdrerCriteria orderCriteria);
public int GetNumberOfBannedUsers();
public TBlackList? GetUserBannedByEmail(string email);
public bool BanUser(string username);
public bool UnbanUser(string email);
}

@ -5,7 +5,6 @@ namespace Shared;
public interface IInquiryService<TInquiry>
{
public IEnumerable<TInquiry> GetInquiries(int page, int number, InquiryOrderCriteria orderCriteria);
public int GetNumberOfInquiries();
public TInquiry GetInquiryById(int id);
public TInquiry GetInquiryByTitle(string title);
public bool DeleteInquiry(int id);

@ -1,6 +0,0 @@
namespace Shared;
public interface IInquiryTableService<TInquiryTable>
{
public string GetDatabaseNameByInquiryId(int id);
}

@ -5,10 +5,9 @@ namespace Shared;
public interface ILessonService<TLesson>
{
public IEnumerable<TLesson> GetLessons(int page, int number, LessonOrderCriteria orderCriteria);
public int GetNumberOfLessons();
public TLesson GetLessonById(int id);
public TLesson GetLessonByTitle(string title);
public bool DeleteLesson(int id);
public TLesson UpdateLesson(int id, TLesson lesson);
public TLesson CreateLesson(int id, string title, string lastPublisher, DateOnly lastEdit);
public TLesson CreateLesson(string title, string lastPublisher, DateOnly? lastEdit);
}

@ -1,10 +0,0 @@
namespace Shared;
public interface INotepadService<TNotepad>
{
public TNotepad GetNotepadFromUserAndInquiryId(int userId, int inquiryId);
public void SetNotepadFromUserAndInquiryId(int userId, int inquiryId, string notes);
public void UpdateNotepadFromUserAndInquiryId(int userId, int inquiryId, string notes);
}

@ -5,13 +5,12 @@ namespace Shared
public interface IParagraphService<TParagraph>
{
public IEnumerable<TParagraph> GetParagraphs(int page, int number, ParagraphOrderCriteria orderCriteria);
public IEnumerable<TParagraph> GetParagraphsByLessonId(int lessonId);
public TParagraph GetParagraphById(int id);
public TParagraph GetParagraphByTitle(string title);
public bool DeleteParagraph(int id);
public TParagraph UpdateParagraph(int id, TParagraph paragraph);
public TParagraph CreateParagraph(string contentTitle, string contentContent, string title, string content, string info, string query, string comment,
public TParagraph CreateParagraph(string title, string content, string info, string query, string comment,
int lessonId);
}
}

@ -1,18 +0,0 @@
using Microsoft.AspNetCore.Mvc;
using Model.OrderCriteria;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Dto;
namespace Shared
{
public interface IQueryService<TQuery>
{
public TQuery ExecuteQuery(string query, string database);
public QueryDto GetTables(string database);
public QueryDto GetColumns(string database,string table);
}
}

@ -1,6 +0,0 @@
namespace Shared;
public interface ISolutionService<TSolution>
{
public TSolution GetSolutionByInquiryId(int id);
}

@ -5,10 +5,10 @@ namespace Shared
public interface ISuccessService<TSuccess>
{
public IEnumerable<TSuccess> GetSuccesses(int page, int number, SuccessOrderCriteria orderCriteria);
public IEnumerable<TSuccess> GetSuccessesByUserId(int id);
public IEnumerable<TSuccess> GetSuccessesByInquiryId(int id);
public bool DeleteSuccess(int idUser, int idInquiry);
public TSuccess UpdateSuccess(int idUser, int idInquiry, TSuccess success);
public TSuccess GetSuccessByUserId(int id);
public TSuccess GetSuccessByInquiryId(int id);
public bool DeleteSuccess(int id);
public TSuccess UpdateSuccess(int id, TSuccess success);
public TSuccess CreateSuccess(int userId, int inquiryId, bool isFinished);
}
}

@ -5,17 +5,10 @@ namespace Shared
public interface IUserService<TUser>
{
public IEnumerable<TUser> GetUsers(int page, int number, UserOrderCriteria orderCriteria);
public IEnumerable<TUser> GetNotAdminUsers(int page, int number, UserOrderCriteria orderCriteria);
public int GetNumberOfUsers();
public TUser GetUserById(int id);
public TUser GetUserByUsername(string username);
public TUser GetUserByEmail(string email);
public bool DeleteUser(int id);
public bool DeleteUserByUsername(string username);
public TUser UpdateUser(int id, TUser user);
public TUser CreateUser(string username, string password, string email, bool isAdmin);
public bool IsEmailTaken(string email);
public bool IsUsernameTaken(string username);
public TUser PromoteUser(int id);
}
}

@ -6,17 +6,17 @@ namespace Shared.Mapper;
public static class BlackListMapper
{
public static BlackListDto FromModelToDto(this BlackList model)
public static BlackListDTO FromModelToDTO(this BlackList model)
{
return new BlackListDto(model.Email, model.ExpirationDate);
return new BlackListDTO(model.Email, model.ExpirationDate);
}
public static BlackListDto FromEntityToDto(this BlackListEntity ent)
public static BlackListDTO FromEntityToDTO(this BlackListEntity ent)
{
return new BlackListDto(ent.Email, ent.ExpirationDate);
return new BlackListDTO(ent.Email, ent.ExpirationDate);
}
public static BlackList FromDtoToModel(this BlackListDto dto)
public static BlackList FromDTOToModel(this BlackListDTO dto)
{
return new BlackList(dto.Email, dto.ExpirationDate);
}
@ -26,21 +26,13 @@ public static class BlackListMapper
return new BlackList(ent.Email, ent.ExpirationDate);
}
public static BlackListEntity FromDtoToEntity(this BlackListDto dto)
public static BlackListEntity FromDTOToEntity(this BlackListDTO dto)
{
return new BlackListEntity
{
Email = dto.Email,
ExpirationDate = dto.ExpirationDate
};
return new BlackListEntity(dto.Email, dto.ExpirationDate);
}
public static BlackListEntity FromModelToEntity(this BlackList model)
{
return new BlackListEntity
{
Email = model.Email,
ExpirationDate = model.ExpirationDate
};
return new BlackListEntity(model.Email, model.ExpirationDate);
}
}

@ -1,13 +0,0 @@
using Dto;
using Entities;
using Model;
namespace Shared.Mapper;
public static class ContentLessonMapper
{
public static ContentLessonDto FromEntityToDto(this ContentLessonEntity entity)
{
return new ContentLessonDto(entity.Id, entity.ContentContent, entity.ContentTitle, entity.LessonId);
}
}

@ -6,7 +6,7 @@ namespace Shared.Mapper;
public static class InquiryMapper
{
public static Inquiry FromDtoToModel(this InquiryDto inqDto)
public static Inquiry FromDTOToModel(this InquiryDTO inqDto)
{
return new Inquiry(inqDto.Id, inqDto.Title, inqDto.Description, inqDto.IsUser);
}
@ -19,33 +19,21 @@ public static class InquiryMapper
public static InquiryEntity FromModelToEntity(this Inquiry inq)
{
return new InquiryEntity
{
Id = inq.Id,
Title = inq.Title,
Description = inq.Description,
IsUser = inq.IsUser
};
return new InquiryEntity(inq.Id, inq.Title, inq.Description, inq.IsUser);
}
public static InquiryEntity FromDtoToEntity(this InquiryDto inqDto)
{
return new InquiryEntity
public static InquiryEntity FromDTOToEntity(this InquiryDTO inqDto)
{
Id = inqDto.Id,
Title = inqDto.Title,
Description = inqDto.Description,
IsUser = inqDto.IsUser
};
return new InquiryEntity(inqDto.Id, inqDto.Title, inqDto.Description, inqDto.IsUser);
}
public static InquiryDto FromModelToDto(this Inquiry inq)
public static InquiryDTO FromModelToDTO(this Inquiry inq)
{
return new InquiryDto(inq.Id, inq.Title, inq.Description, inq.IsUser);
return new InquiryDTO(inq.Id, inq.Title, inq.Description, inq.IsUser);
}
public static InquiryDto FromEntityToDto(this InquiryEntity inqEntity)
public static InquiryDTO FromEntityToDTO(this InquiryEntity inqEntity)
{
return new InquiryDto(inqEntity.Id, inqEntity.Title, inqEntity.Description, inqEntity.IsUser);
return new InquiryDTO(inqEntity.Id, inqEntity.Title, inqEntity.Description, inqEntity.IsUser);
}
}

@ -6,7 +6,7 @@ namespace Shared.Mapper;
public static class InquiryTableMapper
{
public static InquiryTable FromDtoToModel(this InquiryTableDto inqTDto)
public static InquiryTable FromDTOToModel(this InquiryTableDTO inqTDto)
{
return new InquiryTable(inqTDto.OwnerId, inqTDto.ConnectionInfo, inqTDto.DatabaseName);
}
@ -16,33 +16,23 @@ public static class InquiryTableMapper
return new InquiryTable(inqTEntity.OwnerId, inqTEntity.ConnectionInfo, inqTEntity.DatabaseName);
}
public static InquiryTableDto FromModelToDto(this InquiryTable inqT)
public static InquiryTableDTO FromModelToDTO(this InquiryTable inqT)
{
return new InquiryTableDto(inqT.OwnerId, inqT.DatabaseName, inqT.ConnectionInfo);
return new InquiryTableDTO(inqT.OwnerId, inqT.DatabaseName, inqT.ConnectionInfo);
}
public static InquiryTableDto FromEntityToDto(this InquiryTableEntity inqTEntity)
public static InquiryTableDTO FromEntityToDTO(this InquiryTableEntity inqTEntity)
{
return new InquiryTableDto(inqTEntity.OwnerId, inqTEntity.DatabaseName, inqTEntity.ConnectionInfo);
return new InquiryTableDTO(inqTEntity.OwnerId, inqTEntity.DatabaseName, inqTEntity.ConnectionInfo);
}
public static InquiryTableEntity FromModelToEntity(this InquiryTable inqT)
{
return new InquiryTableEntity
{
OwnerId = inqT.OwnerId,
DatabaseName = inqT.DatabaseName,
ConnectionInfo = inqT.ConnectionInfo
};
return new InquiryTableEntity(inqT.OwnerId, inqT.DatabaseName, inqT.ConnectionInfo);
}
public static InquiryTableEntity FromDtoToEntity(this InquiryTableDto dto)
{
return new InquiryTableEntity
public static InquiryTableEntity FromDTOToEntity(this InquiryTableDTO dto)
{
OwnerId = dto.OwnerId,
DatabaseName = dto.DatabaseName,
ConnectionInfo = dto.ConnectionInfo
};
return new InquiryTableEntity(dto.OwnerId, dto.DatabaseName, dto.ConnectionInfo);
}
}

@ -6,43 +6,29 @@ namespace Shared.Mapper;
public static class LessonMapper
{
public static LessonDto FromModelToDto(this Lesson model)
public static LessonDTO FromModelToDTO(this Lesson model)
{
return new LessonDto(model.Id, model.Title, model.LastPublisher, model.LastEdit);
return new LessonDTO(model.Id, model.Title, model.LastPublisher, model.LastEdit);
}
public static LessonDto FromEntityToDto(this LessonEntity model)
public static LessonDTO FromEntityToDTO(this LessonEntity model)
{
return new LessonDto(model.Id, model.Title, model.LastPublisher, model.LastEdit, model.Content.Select(c => c.FromEntityToDto()).ToList());
return new LessonDTO(model.Id, model.Title, model.LastPublisher, model.LastEdit);
}
public static LessonEntity FromModelToEntity(this Lesson model)
{
return new LessonEntity
{
Id = model.Id,
Title = model.Title,
LastPublisher = model.LastPublisher,
LastEdit = model.LastEdit
};
return new LessonEntity(model.Id, model.Title, model.LastPublisher, model.LastEdit);
}
public static LessonEntity FromDtoToEntity(this LessonDto dto)
{
DateTime date = DateTime.Now;
return new LessonEntity
public static LessonEntity FromDTOToEntity(this LessonDTO dto)
{
Id = dto.Id,
Title = dto.Title,
LastPublisher = dto.LastPublisher,
LastEdit = dto.LastEdit ?? new DateOnly(date.Year,date.Month,date.Day)
};
return new LessonEntity(dto.Id, dto.Title, dto.LastPublisher, dto.LastEdit);
}
public static Lesson FromDtoToModel(this LessonDto dto)
public static Lesson FromDTOToModel(this LessonDTO dto)
{
DateTime date = DateTime.Now;
return new Lesson(dto.Id, dto.Title, dto.LastPublisher, dto.LastEdit ?? new DateOnly(date.Year,date.Month,date.Day));
return new Lesson(dto.Id, dto.Title, dto.LastPublisher, dto.LastEdit);
}
public static Lesson FromEntityToModel(this LessonEntity entity)

@ -6,7 +6,7 @@ namespace Shared.Mapper;
public static class NotepadMapper
{
public static Notepad FromDtoToModel(this NotepadDto dto)
public static Notepad FromDTOToModel(this NotepadDTO dto)
{
return new Notepad(dto.Id, dto.UserId, dto.InquiryId, dto.Notes);
}
@ -16,49 +16,25 @@ public static class NotepadMapper
return new Notepad(ent.Id, ent.UserId, ent.InquiryId, ent.Notes);
}
public static NotepadDto FromModelToDto(this Notepad not)
public static NotepadDTO FromModelToDTO(this Notepad not)
{
return new NotepadDto(not.Id, not.UserId, not.InquiryId, not.Notes);
return new NotepadDTO(not.Id, not.UserId, not.InquiryId, not.Notes);
}
public static NotepadDto FromEntityToDto(this NotepadEntity ent)
public static NotepadDTO FromEntityToDTO(this NotepadEntity ent)
{
return new NotepadDto(ent.Id, ent.UserId, ent.InquiryId, ent.Notes);
return new NotepadDTO(ent.Id, ent.UserId, ent.InquiryId, ent.Notes);
}
public static NotepadEntity FromDtoToEntity(this NotepadDto dto)
public static NotepadEntity FromDTOToEntity(this NotepadDTO dto)
{
return new NotepadEntity
{
Id = dto.Id,
User = new UserEntity
{
Id = dto.UserId
},
UserId = dto.UserId,
Inquiry = new InquiryEntity
{
Id = dto.InquiryId
},
Notes = dto.Notes
};
return new NotepadEntity(dto.Id, new UserEntity(dto.UserId), dto.UserId, new InquiryEntity(dto.InquiryId),
dto.Notes);
}
public static NotepadEntity FromModelToEntity(this Notepad not)
{
return new NotepadEntity
{
Id = not.Id,
User = new UserEntity
{
Id = not.UserId
},
UserId = not.UserId,
Inquiry = new InquiryEntity
{
Id = not.InquiryId
},
Notes = not.Notes
};
return new NotepadEntity(not.Id, new UserEntity(not.UserId), not.UserId, new InquiryEntity(not.InquiryId),
not.Notes);
}
}

@ -6,7 +6,7 @@ namespace Shared.Mapper;
public static class ParagraphMapper
{
public static Paragraph FromDtoToModel(this ParagraphDto dto)
public static Paragraph FromDTOToModel(this ParagraphDTO dto)
{
return new Paragraph(dto.ContentTitle, dto.ContentContent, dto.Info, dto.Query, dto.Comment);
}
@ -16,44 +16,27 @@ public static class ParagraphMapper
return new Paragraph(model.ContentTitle, model.ContentContent, model.Info, model.Query, model.Comment);
}
public static ParagraphDto FromEntityToDto(this ParagraphEntity model)
public static ParagraphDTO FromEntityToDTO(this ParagraphEntity model)
{
return new ParagraphDto(model.Id, model.Title, model.Content, model.Info, model.Query,
return new ParagraphDTO(model.Id, model.ContentTitle, model.ContentContent, model.Info, model.Query,
model.Comment, model.LessonId);
}
public static ParagraphDto FromModelToDto(this Paragraph model)
public static ParagraphDTO FromModelToDTO(this Paragraph model)
{
return new ParagraphDto(model.Id, model.ContentTitle, model.ContentContent, model.Info, model.Query,
return new ParagraphDTO(model.Id, model.ContentTitle, model.ContentContent, model.Info, model.Query,
model.Comment, model.LessonId);
}
public static ParagraphEntity FromDtoToEntity(this ParagraphDto dto)
public static ParagraphEntity FromDTOToEntity(this ParagraphDTO dto)
{
return new ParagraphEntity
{
Id = dto.Id,
ContentTitle = dto.ContentTitle,
ContentContent = dto.ContentContent,
Title = dto.Title,
Content = dto.Content,
Info = dto.Info,
Query = dto.Query,
Comment = dto.Comment,
LessonId = dto.LessonId
};
return new ParagraphEntity(dto.Id, dto.ContentTitle, dto.ContentContent, dto.Info, dto.Query, dto.Comment,
dto.LessonId);
}
public static ParagraphEntity FromModelToEntity(this Paragraph model)
{
return new ParagraphEntity
{
Id = model.Id,
ContentTitle = model.ContentTitle,
ContentContent = model.ContentContent,
Info = model.Info,
Query = model.Query,
Comment = model.Comment, LessonId = model.LessonId
};
return new ParagraphEntity(model.Id, model.ContentTitle, model.ContentContent, model.Info, model.Query,
model.Comment, model.LessonId);
}
}

@ -6,7 +6,7 @@ namespace Shared.Mapper;
public static class SolutionMapper
{
public static Solution FromDtoToModel(this SolutionDto dto)
public static Solution FromDTOToModel(this SolutionDTO dto)
{
return new Solution(dto.OwnerId, dto.MurdererFirstName, dto.MurdererLastName, dto.MurderPlace, dto.MurderWeapon,
dto.Explanation);
@ -18,49 +18,27 @@ public static class SolutionMapper
entity.MurderWeapon, entity.Explaination);
}
public static SolutionDto FromModelToDto(this Solution model)
public static SolutionDTO FromModelToDTO(this Solution model)
{
return new SolutionDto(model.OwnerId, model.MurdererFirstName, model.MurdererLastName, model.MurderPlace,
model.MurderWeapon, model.Explaination);
return new SolutionDTO(model.OwnerId, model.MurdererFirstName, model.MurdererLastName, model.MurderPlace,
model.MurderWeapon, model.Explanation);
}
public static SolutionDto FromEntityToDto(this SolutionEntity entity)
public static SolutionDTO FromEntityToDTO(this SolutionEntity entity)
{
return new SolutionDto(entity.OwnerId, entity.MurdererFirstName, entity.MurdererLastName, entity.MurderPlace,
return new SolutionDTO(entity.OwnerId, entity.MurdererFirstName, entity.MurdererLastName, entity.MurderPlace,
entity.MurderWeapon, entity.Explaination);
}
public static SolutionEntity FromModelToEntity(this Solution model)
{
return new SolutionEntity
{
OwnerId = model.OwnerId,
Owner = new InquiryEntity
{
Id = model.OwnerId
},
MurdererFirstName = model.MurdererFirstName,
MurdererLastName = model.MurdererLastName,
MurderPlace = model.MurderPlace,
MurderWeapon = model.MurderWeapon,
Explaination = model.Explaination
};
return new SolutionEntity(model.OwnerId, new InquiryEntity(model.OwnerId), model.MurdererFirstName,
model.MurdererLastName, model.MurderPlace, model.MurderWeapon, model.Explanation);
}
public static SolutionEntity FromDtoToEntity(this SolutionDto dto)
{
return new SolutionEntity
{
OwnerId = dto.OwnerId,
Owner = new InquiryEntity
public static SolutionEntity FromDTOToEntity(this SolutionDTO dto)
{
Id = dto.OwnerId
},
MurdererFirstName = dto.MurdererFirstName,
MurdererLastName = dto.MurdererLastName,
MurderPlace = dto.MurderPlace,
MurderWeapon = dto.MurderWeapon,
Explaination = dto.Explanation
};
return new SolutionEntity(dto.OwnerId, new InquiryEntity(dto.OwnerId), dto.MurdererFirstName,
dto.MurdererLastName, dto.MurderPlace, dto.MurderWeapon, dto.Explanation);
}
}

@ -6,7 +6,7 @@ namespace Shared.Mapper;
public static class SuccessMapper
{
public static Success FromDtoToModel(this SuccessDto dto)
public static Success FromDTOToModel(this SuccessDTO dto)
{
return new Success(dto.UserId, dto.InquiryId, dto.IsFinished);
}
@ -16,49 +16,25 @@ public static class SuccessMapper
return new Success(ent.UserId, ent.InquiryId, ent.IsFinished);
}
public static SuccessDto FromModelToDto(this Success suc)
public static SuccessDTO FromModelToDTO(this Success suc)
{
return new SuccessDto(suc.UserId, suc.InquiryId, suc.IsFinished);
return new SuccessDTO(suc.UserId, suc.InquiryId, suc.IsFinished);
}
public static SuccessDto FromEntityToDto(this SuccessEntity ent)
public static SuccessDTO FromEntityToDTO(this SuccessEntity ent)
{
return new SuccessDto(ent.UserId, ent.InquiryId, ent.IsFinished);
return new SuccessDTO(ent.UserId, ent.InquiryId, ent.IsFinished);
}
public static SuccessEntity FromDtoToEntity(this SuccessDto dto)
public static SuccessEntity FromDTOToEntity(this SuccessDTO dto)
{
return new SuccessEntity
{
UserId = dto.UserId,
User = new UserEntity
{
Id = dto.UserId
},
InquiryId = dto.InquiryId,
Inquiry = new InquiryEntity
{
Id = dto.InquiryId
},
IsFinished = dto.IsFinished
};
return new SuccessEntity(dto.UserId, new UserEntity(dto.UserId), dto.InquiryId,
new InquiryEntity(dto.InquiryId), dto.IsFinished);
}
public static SuccessEntity FromModelToEntity(this Success suc)
{
return new SuccessEntity
{
UserId = suc.UserId,
User = new UserEntity
{
Id = suc.UserId
},
InquiryId = suc.InquiryId,
Inquiry = new InquiryEntity
{
Id = suc.InquiryId
},
IsFinished = suc.IsFinished
};
return new SuccessEntity(suc.UserId, new UserEntity(suc.UserId), suc.InquiryId,
new InquiryEntity(suc.InquiryId), suc.IsFinished);
}
}

@ -6,21 +6,14 @@ namespace Shared.Mapper;
public static class UserMapper
{
public static User FromDtoToModel(this UserDto dto)
public static User FromDTOToModel(this UserDTO dto)
{
return new User(dto.Id, dto.Username, dto.Password, dto.Email, dto.IsAdmin);
}
public static UserEntity FromDtoToEntity(this UserDto dto)
public static UserEntity FromDTOToEntity(this UserDTO dto)
{
return new UserEntity
{
Id = dto.Id,
Username = dto.Username,
Password = dto.Password,
Email = dto.Email,
IsAdmin = dto.IsAdmin
};
return new UserEntity(dto.Id, dto.Username, dto.Password, dto.Email, dto.IsAdmin);
}
public static User FromEntityToModel(this UserEntity entity)
@ -28,25 +21,18 @@ public static class UserMapper
return new User(entity.Id, entity.Username, entity.Password, entity.Email, entity.IsAdmin);
}
public static UserDto FromEntityToDto(this UserEntity entity)
public static UserDTO FromEntityToDTO(this UserEntity entity)
{
return new UserDto(entity.Id, entity.Username, entity.Password, entity.Email, entity.IsAdmin);
return new UserDTO(entity.Id, entity.Username, entity.Password, entity.Email, entity.IsAdmin);
}
public static UserDto FromModelToDto(this User user)
public static UserDTO FromModelToDTO(this User user)
{
return new UserDto(user.Id, user.Username, user.Password, user.Email, user.IsAdmin);
return new UserDTO(user.Id, user.Username, user.Password, user.Email, user.IsAdmin);
}
public static UserEntity FromModelToEntity(this User user)
{
return new UserEntity
{
Id = user.Id,
Username = user.Username,
Password = user.Password,
Email = user.Email,
IsAdmin = user.IsAdmin
};
return new UserEntity(user.Id, user.Username, user.Password, user.Email, user.IsAdmin);
}
}

@ -1,643 +0,0 @@
// <auto-generated />
using System;
using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.Infrastructure;
using Microsoft.EntityFrameworkCore.Migrations;
using Microsoft.EntityFrameworkCore.Storage.ValueConversion;
using Npgsql.EntityFrameworkCore.PostgreSQL.Metadata;
using StubbedContextLib;
#nullable disable
namespace StubbedContextLib.Migrations
{
[DbContext(typeof(StubbedContext))]
[Migration("20240624134431_Initial")]
partial class Initial
{
/// <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.HasIndex("Email")
.IsUnique();
b.HasIndex("Username")
.IsUnique();
b.ToTable("User");
b.HasData(
new
{
Id = 1,
Email = "Johnny.RATTON@etu.uca.fr",
IsAdmin = true,
Password = "$2a$10$7Dq.5Bf5WlHBMRqHBp5Ag.5PCCnvLrBXsuMGGJnV4l4WdngeDBpnW",
Username = "johnny"
},
new
{
Id = 2,
Email = "Maxime.SAPOUNTZIS@etu.uca.fr",
IsAdmin = true,
Password = "$2a$10$OT8g325JcE9mIdc.DiEKpem3kwNBdRcQ22vT2i5IB7KmfBfek4662",
Username = "maxime"
},
new
{
Id = 3,
Email = "Clement.CHIEU@etu.uca.fr",
IsAdmin = true,
Password = "$2a$10$Qc40bG8aCDvRSVjlWIn.1Orkd52fVMxBM2uQypVVwgu/mkeM8rnVK",
Username = "clement"
},
new
{
Id = 4,
Email = "Erwan.MENAGER@etu.uca.fr",
IsAdmin = true,
Password = "$2a$10$AW23BQcrS7d//LK0CtHuH.599OfYinEKCLkTz8Sbrtn.XYWE0u0BO",
Username = "erwan"
},
new
{
Id = 5,
Email = "Victor.GABORIT@etu.uca.fr",
IsAdmin = true,
Password = "$2a$10$ZOly/r95doGABtnypi8CAun1VnMRP1ct.idsUpXGe3pwjRYqv3ZQy",
Username = "victor"
});
});
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,478 +0,0 @@
using System;
using Microsoft.EntityFrameworkCore.Migrations;
using Npgsql.EntityFrameworkCore.PostgreSQL.Metadata;
#nullable disable
#pragma warning disable CA1814 // Prefer jagged arrays over multidimensional
namespace StubbedContextLib.Migrations
{
/// <inheritdoc />
public partial class Initial : 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.InsertData(
table: "User",
columns: new[] { "Id", "Email", "IsAdmin", "Password", "Username" },
values: new object[,]
{
{ 1, "Johnny.RATTON@etu.uca.fr", true, "$2a$10$7Dq.5Bf5WlHBMRqHBp5Ag.5PCCnvLrBXsuMGGJnV4l4WdngeDBpnW", "johnny" },
{ 2, "Maxime.SAPOUNTZIS@etu.uca.fr", true, "$2a$10$OT8g325JcE9mIdc.DiEKpem3kwNBdRcQ22vT2i5IB7KmfBfek4662", "maxime" },
{ 3, "Clement.CHIEU@etu.uca.fr", true, "$2a$10$Qc40bG8aCDvRSVjlWIn.1Orkd52fVMxBM2uQypVVwgu/mkeM8rnVK", "clement" },
{ 4, "Erwan.MENAGER@etu.uca.fr", true, "$2a$10$AW23BQcrS7d//LK0CtHuH.599OfYinEKCLkTz8Sbrtn.XYWE0u0BO", "erwan" },
{ 5, "Victor.GABORIT@etu.uca.fr", true, "$2a$10$ZOly/r95doGABtnypi8CAun1VnMRP1ct.idsUpXGe3pwjRYqv3ZQy", "victor" }
});
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");
migrationBuilder.CreateIndex(
name: "IX_User_Email",
table: "User",
column: "Email",
unique: true);
migrationBuilder.CreateIndex(
name: "IX_User_Username",
table: "User",
column: "Username",
unique: true);
}
/// <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,640 +0,0 @@
// <auto-generated />
using System;
using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.Infrastructure;
using Microsoft.EntityFrameworkCore.Storage.ValueConversion;
using Npgsql.EntityFrameworkCore.PostgreSQL.Metadata;
using StubbedContextLib;
#nullable disable
namespace StubbedContextLib.Migrations
{
[DbContext(typeof(StubbedContext))]
partial class StubbedContextModelSnapshot : 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.HasIndex("Email")
.IsUnique();
b.HasIndex("Username")
.IsUnique();
b.ToTable("User");
b.HasData(
new
{
Id = 1,
Email = "Johnny.RATTON@etu.uca.fr",
IsAdmin = true,
Password = "$2a$10$7Dq.5Bf5WlHBMRqHBp5Ag.5PCCnvLrBXsuMGGJnV4l4WdngeDBpnW",
Username = "johnny"
},
new
{
Id = 2,
Email = "Maxime.SAPOUNTZIS@etu.uca.fr",
IsAdmin = true,
Password = "$2a$10$OT8g325JcE9mIdc.DiEKpem3kwNBdRcQ22vT2i5IB7KmfBfek4662",
Username = "maxime"
},
new
{
Id = 3,
Email = "Clement.CHIEU@etu.uca.fr",
IsAdmin = true,
Password = "$2a$10$Qc40bG8aCDvRSVjlWIn.1Orkd52fVMxBM2uQypVVwgu/mkeM8rnVK",
Username = "clement"
},
new
{
Id = 4,
Email = "Erwan.MENAGER@etu.uca.fr",
IsAdmin = true,
Password = "$2a$10$AW23BQcrS7d//LK0CtHuH.599OfYinEKCLkTz8Sbrtn.XYWE0u0BO",
Username = "erwan"
},
new
{
Id = 5,
Email = "Victor.GABORIT@etu.uca.fr",
IsAdmin = true,
Password = "$2a$10$ZOly/r95doGABtnypi8CAun1VnMRP1ct.idsUpXGe3pwjRYqv3ZQy",
Username = "victor"
});
});
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,5 @@
using System.Security.Cryptography;
using DbContextLib;
using DevOne.Security.Cryptography.BCrypt;
using Entities;
using Microsoft.AspNetCore.Cryptography.KeyDerivation;
using Microsoft.EntityFrameworkCore;
@ -13,200 +12,74 @@ public class StubbedContext : UserDbContext
{
}
protected override void OnModelCreating(ModelBuilder builder)
protected override void OnModelCreating(ModelBuilder modelBuilder)
{
base.OnModelCreating(builder);
builder.Entity<UserEntity>().HasData(
new UserEntity
{
Id = 1,
Username = "johnny",
/*Password = Convert.ToBase64String(KeyDerivation.Pbkdf2(
password: "Motdepasse",
base.OnModelCreating(modelBuilder);
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)),*/
Password = BCryptHelper.HashPassword("Motdepasse", BCryptHelper.GenerateSalt()),
Email = "Johnny.RATTON@etu.uca.fr",
IsAdmin = true
},
new UserEntity
{
Id = 2,
Username = "maxime",
/*Password = Convert.ToBase64String(KeyDerivation.Pbkdf2(
password: "Motdepasse",
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)),*/
Password = BCryptHelper.HashPassword("Motdepasse", BCryptHelper.GenerateSalt()),
Email = "Maxime.SAPOUNTZIS@etu.uca.fr",
IsAdmin = true
},
new UserEntity
{
Id = 3,
Username = "clement",
/*Password = Convert.ToBase64String(KeyDerivation.Pbkdf2(
password: "Motdepasse",
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)),*/
Password = BCryptHelper.HashPassword("Motdepasse", BCryptHelper.GenerateSalt()),
Email = "Clement.CHIEU@etu.uca.fr",
IsAdmin = true
},
new UserEntity
{
Id = 4,
Username = "erwan",
/*Password = Convert.ToBase64String(KeyDerivation.Pbkdf2(
password: "Motdepasse",
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)),*/
Password = BCryptHelper.HashPassword("Motdepasse", BCryptHelper.GenerateSalt()),
Email = "Erwan.MENAGER@etu.uca.fr",
IsAdmin = true
},
new UserEntity
{
Id = 5,
Username = "victor",
/*Password = Convert.ToBase64String(KeyDerivation.Pbkdf2(
password: "Motdepasse",
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)),*/
Password = BCryptHelper.HashPassword("Motdepasse", BCryptHelper.GenerateSalt()),
Email = "Victor.GABORIT@etu.uca.fr",
IsAdmin = true
});
numBytesRequested: 256 / 8)), "Victor.GABORIT@etu.uca.fr", true));
/*builder.Entity<InquiryTableEntity>().HasData(
new InquiryTableEntity
{
OwnerId = 1,
DatabaseName = "Inquiry1",
ConnectionInfo =
"Server=localhost;Database=Inquiry1;Trusted_Connection=True;MultipleActiveResultSets=true"
},
new InquiryTableEntity
{
OwnerId = 2,
DatabaseName = "Inquiry2",
ConnectionInfo =
"Server=localhost;Database=Inquiry2;Trusted_Connection=True;MultipleActiveResultSets=true"
},
new InquiryTableEntity
{
OwnerId = 3,
DatabaseName = "Inquiry3",
ConnectionInfo =
"Server=localhost;Database=Inquiry3;Trusted_Connection=True;MultipleActiveResultSets=true"
});
modelBuilder.Entity<InquiryTableEntity>().HasData(
new InquiryTableEntity(1, "Inquiry1",
"Server=localhost;Database=Inquiry1;Trusted_Connection=True;MultipleActiveResultSets=true"),
new InquiryTableEntity(2, "Inquiry2",
"Server=localhost;Database=Inquiry2;Trusted_Connection=True;MultipleActiveResultSets=true"),
new InquiryTableEntity(3, "Inquiry3",
"Server=localhost;Database=Inquiry3;Trusted_Connection=True;MultipleActiveResultSets=true"));
builder.Entity<SolutionEntity>().HasData(
new SolutionEntity
{
OwnerId = 1,
MurdererFirstName = "Maxime",
MurdererLastName = "Sapountzis",
MurderPlace = "La cuisine",
MurderWeapon = "Le couteau",
Explaination = "Parce que c'est Maxime"
},
new SolutionEntity
{
OwnerId = 2,
MurdererFirstName = "Johnny",
MurdererLastName = "Ratton",
MurderPlace = "La cuisine",
MurderWeapon = "Le couteau",
Explaination = "Parce que il est fou"
},
new SolutionEntity
{
OwnerId = 3,
MurdererFirstName = "Erwan",
MurdererLastName = "Menager",
MurderPlace = "La salle de bain",
MurderWeapon = "L'arachide",
Explaination = "Parce que c'est Erwan"
});
modelBuilder.Entity<SolutionEntity>().HasData(
new SolutionEntity(1, "Maxime", "Sapountzis", "La cuisine", "Le couteau", "Parce que c'est Maxime"),
new SolutionEntity(2, "Johnny", "Ratton", "La cuisine", "Le couteau", "Parce que il est fou"),
new SolutionEntity(3, "Erwan", "Menager", "La salle de bain", "L'arachide", "Parce que c'est Erwan"));
builder.Entity<InquiryEntity>().HasData(
new InquiryEntity
{
Id = 1,
Title = "L'enquête de la carotte",
Description = "La description de l'inquiry1",
IsUser = true
},
new InquiryEntity
{
Id = 2,
Title = "L'enquête sur les orang outan",
Description = "The new description",
IsUser = false
},
new InquiryEntity
{
Id = 3,
Title = "L'enquête sur les parapluies",
Description = "Il pleuvait",
IsUser = false
}
);
modelBuilder.Entity<LessonEntity>().HasData(
new LessonEntity(1, "La cuisine", "Maxime", new DateOnly(2021, 10, 10)),
new LessonEntity(2, "La salle de bain", "Erwan", new DateOnly(2021, 10, 10)),
new LessonEntity(3, "La chambre", "Johnny", new DateOnly(2021, 10, 10)),
new LessonEntity(4, "Le salon", "Clement", new DateOnly(2021, 10, 10)));
builder.Entity<SuccessEntity>().HasData(
new SuccessEntity
{
UserId = 1,
InquiryId = 1,
IsFinished = true
},
new SuccessEntity
{
UserId = 2,
InquiryId = 2,
IsFinished = false
},
new SuccessEntity
{
UserId = 3,
InquiryId = 3,
IsFinished = true
}
);
builder.Entity<LessonEntity>().HasData(
new LessonEntity
{
Id = 1, Title = "Lesson N°1", LastEdit = DateOnly.FromDateTime(DateTime.Now), LastPublisher = "Clément"
},
new LessonEntity
{
Id = 2, Title = "Lesson N°2", LastEdit = DateOnly.FromDateTime(DateTime.Now), LastPublisher = "Clément"
},
new LessonEntity
{
Id = 3, Title = "Lesson N°3", LastEdit = DateOnly.FromDateTime(DateTime.Now), LastPublisher = "Clément"
},
new LessonEntity
{
Id = 4, Title = "Lesson N°4", LastEdit = DateOnly.FromDateTime(DateTime.Now), LastPublisher = "Clément"
}
);
builder.Entity<ParagraphEntity>().HasData(
new ParagraphEntity { Id = 1, LessonId = 1, ContentTitle = "Paragraph N°1", ContentContent = "Content of paragraph N°1", Title = "Title Paragraph N°1", Content = "Content of paragraph N°1", Info = "Infos", Query = "SELECT * FROM Table", Comment = "Comment of paragraph N°1"},
new ParagraphEntity { Id = 2, LessonId = 1, ContentTitle = "Paragraph N°2", ContentContent = "Content of paragraph N°2", Title = "Title Paragraph N°2", Content = "Content of paragraph N°2", Info = "Infos", Query = "SELECT * FROM Table", Comment = "Comment of paragraph N°2"},
new ParagraphEntity { Id = 3, LessonId = 1, ContentTitle = "Paragraph N°3", ContentContent = "Content of paragraph N°3", Title = "Title Paragraph N°3", Content = "Content of paragraph N°3", Info = "Infos", Query = "SELECT * FROM Table", Comment = "Comment of paragraph N°3"},
new ParagraphEntity { Id = 4, LessonId = 2, ContentTitle = "Paragraph N°1", ContentContent = "Content of paragraph N°1", Title = "Title Paragraph N°1", Content = "Content of paragraph N°1", Info = "Infos", Query = "SELECT * FROM Table", Comment = "Comment of paragraph N°1"}
);*/
modelBuilder.Entity<ParagraphEntity>().HasData(
new ParagraphEntity(1, "Le premier paragraphe", "Le contenu du premier paragraphe", "Attention", "La query",
"Le commentaire", 1),
new ParagraphEntity(2, "Le deuxième paragraphe", "Le contenu du deuxième paragraphe", "Attention",
"La query", "Le commentaire", 1),
new ParagraphEntity(3, "Le troisième paragraphe", "Le contenu du troisième paragraphe", "Attention",
"query", "commentaire", 2),
new ParagraphEntity(4, "Le quatrième paragraphe", "Le contenu du quatrième paragraphe", "Attention",
"La query", "Le commentaire", 3),
new ParagraphEntity(5, "Le cinquième paragraphe", "Le contenu du quatrième paragraphe", "Attention",
"La query", "Le commentaire", 4));
modelBuilder.Entity<InquiryEntity>().HasData(
new InquiryEntity(1, "L'enquête de la carotte", "La description de l'inquiry1", true),
new InquiryEntity(2, "L'enquête sur les orang outan", "The new description", false),
new InquiryEntity(3, "L'enquête sur les parapluies", "Il pleuvait", false));
}
}

@ -11,7 +11,6 @@
</ItemGroup>
<ItemGroup>
<PackageReference Include="BCrypt" Version="1.0.0" />
<PackageReference Include="Microsoft.EntityFrameworkCore.Design" Version="8.0.2">
<PrivateAssets>all</PrivateAssets>
<IncludeAssets>runtime; build; native; contentfiles; analyzers; buildtransitive</IncludeAssets>

@ -1,195 +0,0 @@
using API.Controllers;
using Dto;
using Entities;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Logging.Abstractions;
using Model.OrderCriteria;
using Moq;
using Shared;
using TestAPI.Extensions;
namespace TestAPI;
public class BlackListUnitTest
{
private readonly Mock<IBlackListService<BlackListDto>> _blackListService;
public BlackListUnitTest()
{
_blackListService = new Mock<IBlackListService<BlackListDto>>();
}
[Fact]
public void IsBanned()
{
_blackListService.Setup(x => x.GetUserBannedByEmail("email@example.com"))
.Returns(new BlackListDto { Email = "email@example.com", ExpirationDate = DateOnly.FromDateTime(DateTime.Now)});
var usersController = new BlackListController(new NullLogger<UsersController>(), _blackListService.Object);
var result = usersController.GetUserBannedByEmail("email@example.com");
Assert.Equal(typeof(OkObjectResult), result.GetType());
}
[Fact]
public void IsBannedNotFound()
{
_blackListService.Setup(x => x.GetUserBannedByEmail("example@notfound.com"))
.Returns<BlackListDto?>(null);
var usersController = new BlackListController(new NullLogger<UsersController>(), _blackListService.Object);
var result = usersController.GetUserBannedByEmail("example@notfound.com");
Assert.Equal(typeof(NotFoundObjectResult), result.GetType());
}
[Fact]
public void BanUser()
{
_blackListService.Setup(x => x.BanUser("Test1"))
.Returns(true);
var usersController = new BlackListController(new NullLogger<UsersController>(), _blackListService.Object);
var userResult = usersController.BanUser("Test1");
Assert.Equal(typeof(OkObjectResult), userResult.GetType());
}
[Fact]
public void BanUserNotFound()
{
_blackListService.Setup(x => x.BanUser("Test1"))
.Returns(true);
var usersController = new BlackListController(new NullLogger<UsersController>(), _blackListService.Object);
var userResult = usersController.BanUser("Test42");
Assert.Equal(typeof(NotFoundResult), userResult.GetType());
}
[Fact]
public void UnbanUser()
{
_blackListService.Setup(x => x.UnbanUser("example@email.com"))
.Returns(true);
var usersController = new BlackListController(new NullLogger<UsersController>(), _blackListService.Object);
var userResult = usersController.UnbanUser("example@email.com");
Assert.Equal(typeof(OkObjectResult), userResult.GetType());
}
[Fact]
public void UnbanUserNotFound()
{
_blackListService.Setup(x => x.UnbanUser("example@email.com"))
.Returns(false);
var usersController = new BlackListController(new NullLogger<UsersController>(), _blackListService.Object);
var userResult = usersController.UnbanUser("example@email.com");
Assert.Equal(typeof(NotFoundResult), userResult.GetType());
}
[Fact]
public void GetBannedUsers_NoneOrderCriteria()
{
_blackListService.Setup(x => x.GetBannedUsers(1,10,BlackListOdrerCriteria.None))
.Returns(new List<BlackListDto>()
{
new BlackListDto { Email = "example1@email.com" , ExpirationDate = DateOnly.FromDateTime(DateTime.Now) },
new BlackListDto { Email = "example2@email.com" , ExpirationDate = DateOnly.FromDateTime(DateTime.Now) },
new BlackListDto { Email = "example3@email.com" , ExpirationDate = DateOnly.FromDateTime(DateTime.Now) }
});
var blackListController = new BlackListController(new NullLogger<UsersController>(), _blackListService.Object);
var result = blackListController.GetBannedUsers(1,10,BlackListOdrerCriteria.None);
Assert.Equal(typeof(OkObjectResult), result.GetType());
if (result is OkObjectResult okObjectResult)
{
var valeur = okObjectResult.Value;
Assert.NotNull(valeur);
Assert.Equal(GetBlackList().ToString(), valeur.ToString());
Assert.True(GetBlackList().SequenceEqual(valeur as IEnumerable<BlackListDto>, new BlackListDtoEqualityComparer()));
}
}
[Fact]
public void GetBannedUsers_OrderByEmail()
{
_blackListService.Setup(x => x.GetBannedUsers(1,10,BlackListOdrerCriteria.ByEmail))
.Returns(new List<BlackListDto>()
{
new BlackListDto { Email = "example1@email.com" , ExpirationDate = DateOnly.FromDateTime(DateTime.Now) },
new BlackListDto { Email = "example2@email.com" , ExpirationDate = DateOnly.FromDateTime(DateTime.Now) },
new BlackListDto { Email = "example3@email.com" , ExpirationDate = DateOnly.FromDateTime(DateTime.Now) }
});
var blackListController = new BlackListController(new NullLogger<UsersController>(), _blackListService.Object);
var result = blackListController.GetBannedUsers(1,10,BlackListOdrerCriteria.ByEmail);
Assert.Equal(typeof(OkObjectResult), result.GetType());
if (result is OkObjectResult okObjectResult)
{
var valeur = okObjectResult.Value;
Assert.NotNull(valeur);
Assert.Equal(GetBlackList().ToString(), valeur.ToString());
Assert.True(GetBlackList().SequenceEqual(valeur as IEnumerable<BlackListDto>, new BlackListDtoEqualityComparer()));
}
}
[Fact]
public void GetBannedUsers_OrderedByExpirationDate()
{
_blackListService.Setup(x => x.GetBannedUsers(1,10,BlackListOdrerCriteria.ByExpirationDate))
.Returns(new List<BlackListDto>()
{
new BlackListDto { Email = "example1@email.com" , ExpirationDate = DateOnly.FromDateTime(DateTime.Now) },
new BlackListDto { Email = "example2@email.com" , ExpirationDate = DateOnly.FromDateTime(DateTime.Now) },
new BlackListDto { Email = "example3@email.com" , ExpirationDate = DateOnly.FromDateTime(DateTime.Now) }
});
var blackListController = new BlackListController(new NullLogger<UsersController>(), _blackListService.Object);
var result = blackListController.GetBannedUsers(1,10,BlackListOdrerCriteria.ByExpirationDate);
Assert.Equal(typeof(OkObjectResult), result.GetType());
if (result is OkObjectResult okObjectResult)
{
var valeur = okObjectResult.Value;
Assert.NotNull(valeur);
Assert.Equal(GetBlackList().ToString(), valeur.ToString());
Assert.True(GetBlackList().SequenceEqual(valeur as IEnumerable<BlackListDto>, new BlackListDtoEqualityComparer()));
}
}
[Fact]
public void Get_0_BannedUsers_OrderedByNone()
{
_blackListService.Setup(x => x.GetBannedUsers(1, 10, BlackListOdrerCriteria.None))
.Returns(new List<BlackListDto>());
var blackListController = new BlackListController(new NullLogger<UsersController>(), _blackListService.Object);
var result = blackListController.GetBannedUsers(1, 10, BlackListOdrerCriteria.None);
Assert.Equal(typeof(StatusCodeResult), result.GetType());
if (result is NotFoundObjectResult notFoundObjectResult)
{
var valeur = notFoundObjectResult.Value;
Assert.NotNull(valeur);
}
}
[Fact]
public void GetNbBannedUsers()
{
_blackListService.Setup(x => x.GetNumberOfBannedUsers())
.Returns(10);
var usersController = new BlackListController(new NullLogger<UsersController>(), _blackListService.Object);
var userResult = usersController.GetNumberOfBannedUsers();
Assert.Equal(typeof(OkObjectResult), userResult.GetType());
Assert.Equal(10, ((KeyValuePair<string,int>)(userResult as OkObjectResult).Value).Value);
}
private IEnumerable<BlackListDto> GetBlackList()
{
return new List<BlackListDto>()
{
new BlackListDto { Email = "example1@email.com" , ExpirationDate = DateOnly.FromDateTime(DateTime.Now) },
new BlackListDto { Email = "example2@email.com" , ExpirationDate = DateOnly.FromDateTime(DateTime.Now) },
new BlackListDto { Email = "example3@email.com" , ExpirationDate = DateOnly.FromDateTime(DateTime.Now) }
};
}
}

@ -1,16 +0,0 @@
using Dto;
namespace TestAPI.Extensions;
public class BlackListDtoEqualityComparer : EqualityComparer<BlackListDto>
{
public override bool Equals(BlackListDto x, BlackListDto y)
{
return x.Email == y.Email;
}
public override int GetHashCode(BlackListDto obj)
{
return obj.Email.GetHashCode();
}
}

@ -1,16 +0,0 @@
using Dto;
namespace TestAPI.Extensions;
class InquiryIdEqualityComparer : EqualityComparer<InquiryDto>
{
public override bool Equals(InquiryDto x, InquiryDto y)
{
return x.Id == y.Id;
}
public override int GetHashCode(InquiryDto obj)
{
return obj.Id;
}
}

@ -1,16 +0,0 @@
using Dto;
namespace TestAPI.Extensions;
class LessonIdEqualityComparer : EqualityComparer<LessonDto>
{
public override bool Equals(LessonDto x, LessonDto y)
{
return x.Id == y.Id;
}
public override int GetHashCode(LessonDto obj)
{
return obj.Id;
}
}

@ -1,16 +0,0 @@
using Dto;
namespace TestAPI.Extensions;
class ParagraphIdEqualityComparer : EqualityComparer<ParagraphDto>
{
public override bool Equals(ParagraphDto x, ParagraphDto y)
{
return x.Id == y.Id;
}
public override int GetHashCode(ParagraphDto obj)
{
return obj.Id;
}
}

@ -1,16 +0,0 @@
using Dto;
namespace TestAPI.Extensions;
class SuccessIdEqualityComparer : EqualityComparer<SuccessDto>
{
public override bool Equals(SuccessDto x, SuccessDto y)
{
return x.UserId == y.UserId && x.InquiryId == y.InquiryId;
}
public override int GetHashCode(SuccessDto obj)
{
return obj.UserId * obj.InquiryId;
}
}

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

Loading…
Cancel
Save