Merge pull request 'pagination' (#1) from pagination into master
continuous-integration/drone/push Build is failing Details

Reviewed-on: #1
testTony
Louis LABORIE 1 year ago
commit 600b55de43

@ -0,0 +1,53 @@
kind: pipeline
type: docker
name: CI
trigger:
event:
- push
steps:
- name: build
image: mcr.microsoft.com/dotnet/sdk:8.0
commands:
- cd Verax_API_EF
- cd Verax_API_EF
- dotnet restore Verax_API_EF.sln
- dotnet build Verax_API_EF.sln -c Release --no-restore
- dotnet publish Verax_API_EF.sln -c Release --no-restore -o $CI_PROJECT_DIR/build/release
- name: tests
image: mcr.microsoft.com/dotnet/sdk:8.0
commands:
- cd Verax_API_EF
- cd Verax_API_EF
- dotnet restore Verax_API_EF.sln
- dotnet test Verax_API_EF.sln --no-restore
depends_on: [build]
- name: code-inspection
image: hub.codefirst.iut.uca.fr/marc.chevaldonne/codefirst-dronesonarplugin-dotnet7
secrets: [ SECRET_SONAR_LOGIN ]
environment:
sonar_host: https://codefirst.iut.uca.fr/sonar/
sonar_token:
from_secret: SECRET_SONAR_LOGIN
project_key: Verax_API_EF
coverage_exclusions: "TestsUnitaires/**"
commands:
- cd Verax_API_EF/
- cd Verax_API_EF/
- dotnet restore Verax_API_EF.sln
- dotnet sonarscanner begin /k:$${project_key} /d:sonar.host.url=$${sonar_host} /d:sonar.coverageReportPaths="coveragereport/SonarQube.xml" /d:sonar.coverage.exclusions=$${coverage_exclusions} /d:sonar.login=$${sonar_token}
- dotnet build Verax_API_EF.sln -c Release --no-restore
- dotnet test Verax_API_EF.sln --logger trx --no-restore
- reportgenerator -reports:"**/coverage.cobertura.xml" -reporttypes:SonarQube -targetdir:"coveragereport"
- dotnet publish Verax_API_EF.sln -c Release --no-restore -o $CI_PROJECT_DIR/build/release
- dotnet sonarscanner end /d:sonar.login=$${sonar_token}
when:
branch:
- master
event:
- push
- pull_request
depends_on: [build,tests]

@ -1,6 +1,6 @@
<?xml version="1.0" encoding="UTF-8"?> <?xml version="1.0" encoding="UTF-8"?>
<project version="4"> <project version="4">
<component name="VcsDirectoryMappings"> <component name="VcsDirectoryMappings">
<mapping directory="$PROJECT_DIR$/.." vcs="Git" /> <mapping directory="$PROJECT_DIR$" vcs="" />
</component> </component>
</project> </project>

@ -21,11 +21,13 @@
<PrivateAssets>all</PrivateAssets> <PrivateAssets>all</PrivateAssets>
<IncludeAssets>runtime; build; native; contentfiles; analyzers; buildtransitive</IncludeAssets> <IncludeAssets>runtime; build; native; contentfiles; analyzers; buildtransitive</IncludeAssets>
</PackageReference> </PackageReference>
<PackageReference Include="Microsoft.VisualStudio.Web.CodeGeneration.Design" Version="8.0.1" />
<PackageReference Include="Swashbuckle.AspNetCore" Version="6.4.0"/> <PackageReference Include="Swashbuckle.AspNetCore" Version="6.4.0"/>
</ItemGroup> </ItemGroup>
<ItemGroup> <ItemGroup>
<ProjectReference Include="..\API_DbDataManager\API_DbDataManager.csproj" /> <ProjectReference Include="..\API_DbDataManager\API_DbDataManager.csproj" />
<ProjectReference Include="..\API_Mapping\API_Mapping.csproj" />
<ProjectReference Include="..\API_Services\API_Services.csproj" /> <ProjectReference Include="..\API_Services\API_Services.csproj" />
<ProjectReference Include="..\StubbedContextLib\StubbedContextLib.csproj" /> <ProjectReference Include="..\StubbedContextLib\StubbedContextLib.csproj" />
</ItemGroup> </ItemGroup>

@ -1,3 +1,4 @@
using API_Mapping;
using API_Services; using API_Services;
using Microsoft.AspNetCore.Mvc; using Microsoft.AspNetCore.Mvc;
using Model; using Model;
@ -10,53 +11,117 @@ namespace API.Controllers
public class ArticleController : ControllerBase public class ArticleController : ControllerBase
{ {
private readonly IArticleService _articleService; //private readonly IArticleService _articleService;
private readonly IDataManager _dataManager;
private readonly ILogger<ArticleController> _logger;
public ArticleController(IArticleService articleService) public ArticleController(IDataManager dataManager, ILogger<ArticleController> logger)
{ {
_articleService = articleService; this._dataManager = dataManager;
this._logger = logger;
} }
[Route("/articles")]
[HttpGet] [HttpGet]
public async Task<IActionResult> GetAllArticles() public async Task<IActionResult> GetAllArticles([FromQuery] int index = 0, [FromQuery] int count = 10, [FromQuery] ArticleOrderCriteria orderCriterium = ArticleOrderCriteria.None)
{ {
var result = await _articleService.GetAllArticles(); _logger.LogInformation("Executing {Action} - with parameters: {Parameters}",nameof(GetAllArticles), index, count, orderCriterium);
if (result == null) try
{ {
return NotFound(); var result = (await _dataManager.ArticleService.GetAllArticles(index, count, orderCriterium)).Select(a => a.ToDTO());
if (result == null)
{
return NotFound();
}
return Ok(result);
}
catch (Exception error)
{
_logger.LogError(error.Message);
return BadRequest(error.Message);
} }
return Ok(result);
} }
[HttpGet("/article/{id}")] [HttpGet("/article/{id}")]
public async Task<Article?> GetArticleById(int id) public async Task<IActionResult> GetArticleById(int id)
{ {
var result = await _articleService.GetArticleById(id); _logger.LogInformation("Executing {Action} - with parameters: {Parameters}",nameof(GetArticleById), id);
if (result == null) try
{
var result = (await _dataManager.ArticleService.GetArticleById(id)).ToDTO();
if (result == null)
{
return NotFound($"Article ID {id} not found");
}
return Ok(result);
}
catch (Exception error)
{ {
return null; _logger.LogError(error.Message);
return BadRequest(error.Message);
} }
return result;
} }
[HttpPost("/article")] [HttpPost("/article")]
public async Task<Article?> CreateArticle(long id, string title, string description, string author, string date, int lectureTime) public async Task<IActionResult> CreateArticle(Article article)
{ {
return await _articleService.CreateArticle(id, title, description, author, date, lectureTime); _logger.LogInformation("Executing {Action} - with parameters: {Parameters}",nameof(CreateArticle), article);
try
{
var result = (await _dataManager.ArticleService.CreateArticle(article)).ToDTO();
if (result == null)
{
return BadRequest($"Article not created");
}
return Ok(result);
}
catch (Exception error)
{
_logger.LogError(error.Message);
return BadRequest(error.Message);
}
} }
[HttpDelete("/article/{id}")] [HttpDelete("/article/{id}")]
public async Task<Article?> DeleteArticle(long id) public async Task<IActionResult> DeleteArticle(long id)
{ {
return await _articleService.DeleteArticle(id); _logger.LogInformation("Executing {Action} - with parameters: {Parameters}",nameof(DeleteArticle), id);
try
{
var result = await _dataManager.ArticleService.DeleteArticle(id);
if (result == null)
{
return NotFound($"Article ID {id} not found");
}
return Ok(result.ToDTO());
}
catch (Exception error)
{
_logger.LogError(error.Message);
return BadRequest(error.Message);
}
} }
[HttpPut("/article/{id}")] [HttpPut("/article/{id}")]
public async Task<bool> UpdateArticle(long id, Article? a) public async Task<IActionResult> UpdateArticle(long id, Article? a)
{ {
return await _articleService.UpdateArticle(id, a); _logger.LogInformation("Executing {Action} - with parameters: {Parameters}",nameof(UpdateArticle), id, a);
try
{
var result = (await _dataManager.ArticleService.UpdateArticle(id, a)).ToDTO();
if (result == null)
{
return NotFound($"Article ID {id} not found");
}
return Ok(result);
}
catch (Exception error)
{
_logger.LogError(error.Message);
return BadRequest(error.Message);
}
} }

@ -4,6 +4,7 @@ using Model;
using System; using System;
using System.Collections.Generic; using System.Collections.Generic;
using System.Threading.Tasks; using System.Threading.Tasks;
using API_Mapping;
namespace API.Controllers namespace API.Controllers
{ {
@ -11,41 +12,118 @@ namespace API.Controllers
[ApiController] [ApiController]
public class FormulaireController : ControllerBase public class FormulaireController : ControllerBase
{ {
private readonly IFormulaireService _form; //private readonly IFormulaireService _form;
private readonly IDataManager _dataManager;
private readonly ILogger<FormulaireController> _logger;
public FormulaireController(IFormulaireService iform) public FormulaireController(IDataManager dataManager, ILogger<FormulaireController> logger)
{ {
this._form = iform; this._dataManager = dataManager;
this._logger = logger;
} }
[HttpGet("/forms/{id}")] [HttpGet("/formulaires")]
public Task<IEnumerable<Formulaire?>> GetAllForm() public async Task<IActionResult> GetAllForm([FromQuery] int index = 0, [FromQuery] int count = 10, [FromQuery] FormOrderCriteria orderCriteria = FormOrderCriteria.None)
{ {
throw new NotImplementedException(); _logger.LogInformation("Executing {Action} - with parameters: {Parameters}",nameof(GetAllForm), index, count, orderCriteria);
try
{
var result = (await _dataManager.FormulaireService.GetAllForm(index, count, orderCriteria)).Select(f => f.ToDTO());
if (result == null)
{
return NotFound($"No form found");
}
return Ok(result);
}
catch (Exception error)
{
_logger.LogError(error.Message);
return BadRequest(error.Message);
}
} }
[HttpGet("{id}")] [HttpGet("/formulaire/{id}")]
public Task<Formulaire?> GetById(long id) public async Task<IActionResult> GetById(long id)
{ {
throw new NotImplementedException(); _logger.LogInformation("Executing {Action} - with parameters: {Parameters}",nameof(GetById), id);
try
{
var result = (await _dataManager.FormulaireService.GetById(id)).ToDTO();
if (result == null)
{
return NotFound($"form ID {id} not found");
}
return Ok(result);
}
catch (Exception error)
{
_logger.LogError(error.Message);
return BadRequest(error.Message);
}
} }
[HttpPost] [HttpPost ("/formulaire")]
public Task<Formulaire?> CreateForm(Formulaire formulaire) public async Task<IActionResult> CreateForm(Formulaire formulaire)
{ {
throw new NotImplementedException(); _logger.LogInformation("Executing {Action} - with parameters: {Parameters}",nameof(CreateForm), formulaire);
try
{
var result = (await _dataManager.FormulaireService.CreateForm(formulaire)).ToDTO();
if (result == null)
{
return BadRequest($"Form Id {formulaire.Id} already exists");
}
return Ok(result);
}
catch (Exception error)
{
_logger.LogError(error.Message);
return BadRequest(error.Message);
}
} }
[HttpDelete("{id}")] [HttpDelete("/formulaire/{id}")]
public Task<bool> DeleteForm(long id) public async Task<IActionResult> DeleteForm(long id)
{ {
throw new NotImplementedException(); _logger.LogInformation("Executing {Action} - with parameters: {Parameters}",nameof(DeleteForm), id);
try
{
var result = (await _dataManager.FormulaireService.DeleteForm(id)).ToDTO();
if (result == null)
{
return NotFound($"Form Id {id} not found");
}
return Ok(result);
}
catch (Exception error)
{
_logger.LogError(error.Message);
return BadRequest(error.Message);
}
} }
[HttpPut("{id}")] [HttpPut("/formulaire/{id}")]
public Task<bool> UpdateForm(long id, Formulaire formulaire) public async Task<IActionResult> UpdateForm(long id, Formulaire formulaire)
{ {
throw new NotImplementedException(); _logger.LogInformation("Executing {Action} - with parameters: {Parameters}",nameof(UpdateForm), formulaire);
try
{
var result = (await _dataManager.FormulaireService.UpdateForm(id, formulaire)).ToDTO();
if (result == null)
{
return NotFound($"form Id {id} not found");
}
return Ok(result);
}
catch (Exception error)
{
_logger.LogError(error.Message);
return BadRequest(error.Message);
}
} }
} }
} }

@ -2,6 +2,8 @@
using Microsoft.AspNetCore.Mvc; using Microsoft.AspNetCore.Mvc;
using API_Services; using API_Services;
using Model; using Model;
using API_Mapping;
using Entities;
namespace API.Controllers namespace API.Controllers
@ -10,42 +12,220 @@ namespace API.Controllers
[ApiController] [ApiController]
public class UserController : ControllerBase public class UserController : ControllerBase
{ {
private readonly IUserService _us; //private readonly IUserService _us;
private readonly IDataManager _dataManager;
private readonly ILogger<UserController> _logger;
public UserController(IDataManager dataManager, ILogger<UserController> logger)
{
this._logger = logger;
this._dataManager = dataManager;
}
public UserController(IUserService us) [HttpGet("/users")]
public async Task<IActionResult> GetAll([FromQuery] int index = 0, [FromQuery] int count = 10, [FromQuery] UserOrderCriteria orderCriteria = UserOrderCriteria.None)
{ {
this._us = us; _logger.LogInformation("Executing {Action} - with parameters: {Parameters}",nameof(GetAll), index, count, orderCriteria);
try
{
var result = (await _dataManager.UserService.GetAll(index, count, orderCriteria)).Select(u => u.ToDTO());
if (result == null)
{
return NotFound($"No user found with the given parameters");
}
return Ok(result);
}
catch (Exception error)
{
_logger.LogError(error.Message);
return BadRequest(error.Message);
}
}
[HttpGet("/user/{pseudo}")]
public async Task<IActionResult> GetByPseudo(string pseudo)
{
_logger.LogInformation("Executing {Action} - with parameters: {Parameters}",nameof(GetByPseudo), pseudo);
try
{
var result = (await _dataManager.UserService.GetByPseudo(pseudo)).ToDTO();
if (result == null)
{
return NotFound($"Psuedo {pseudo} not found");
}
return Ok(result);
}
catch (Exception error)
{
_logger.LogError(error.Message);
return BadRequest(error.Message);
}
} }
[HttpPost("/user")] [HttpPost("/user")]
public Task<bool> Create(User user) public async Task<IActionResult> Create(User user)
{ {
throw new NotImplementedException(); _logger.LogInformation("Executing {Action} - with parameters: {Parameters}",nameof(Create), user);
try
{
var result = (await _dataManager.UserService.Create(user)).ToDTO();
if (result == null)
{
return BadRequest($"User {user.Pseudo} already exists");
}
return Ok(result);
}
catch (Exception error)
{
_logger.LogError(error.Message);
return BadRequest(error.Message);
}
} }
[HttpPut("/user/{pseudo}")] [HttpPut("/user/{pseudo}")]
public Task<bool> Update(User user) public async Task<IActionResult> Update(User user, string pseudo)
{ {
throw new NotImplementedException(); _logger.LogInformation("Executing {Action} - with parameters: {Parameters}",nameof(Update), user, pseudo);
try
{
var result = (await _dataManager.UserService.Update(user, pseudo)).ToDTO();
if (result == null)
{
return NotFound();
}
return Ok(result);
}
catch (Exception error)
{
_logger.LogError(error.Message);
return BadRequest(error.Message);
}
} }
[HttpDelete("/user/{pseudo}")] [HttpDelete("/user/{pseudo}")]
public Task<bool> Delete(string pseudo) public async Task<IActionResult> Delete(string pseudo)
{ {
throw new NotImplementedException(); _logger.LogInformation("Executing {Action} - with parameters: {Parameters}",nameof(Delete), pseudo);
try
{
var result = (await _dataManager.UserService.Delete(pseudo)).ToDTO();
if (result == null)
{
return NotFound();
}
return Ok(result);
}
catch (Exception error)
{
_logger.LogError(error.Message);
return BadRequest(error.Message);
}
} }
[HttpGet("/user/{pseudo}")] [HttpGet("/articleUsers")]
public Task<User?> GetByPseudo(string pseudo) public async Task<IActionResult> GetAllArticleUsers()
{
_logger.LogInformation("Executing {Action} - with parameters: {Parameters}",nameof(GetAllArticleUsers), "");
try
{
var result = (await _dataManager.UserService.GetAllArticleUsers()).Select(u => u.ToDTO());
if (result == null)
{
return NoContent();
}
return Ok(result);
}
catch (Exception error)
{ {
throw new NotImplementedException(); _logger.LogError(error.Message);
return BadRequest(error.Message);
} }
}
[HttpGet("/users")] [HttpGet("/user/{pseudo}/article")]
public Task<IEnumerable<User?>> GetAll() public async Task<IActionResult> GetArticleUser(string pseudo)
{
_logger.LogInformation("Executing {Action} - with parameters: {Parameters}",nameof(GetArticleUser), pseudo);
try
{ {
throw new NotImplementedException(); var result = (await _dataManager.UserService.GetArticleUser(pseudo)).Select(a => a.ToDTO());
if (result == null)
{
return NoContent();
}
return Ok(result);
} }
catch (Exception error)
{
_logger.LogError(error.Message);
return BadRequest(error.Message);
}
}
[HttpPost("/user/article")]
public async Task<IActionResult> CreateArticleUser(ArticleUserEntity articleUser)
{
_logger.LogInformation("Executing {Action} - with parameters: {Parameters}",nameof(CreateArticleUser), articleUser);
try
{
Console.WriteLine(articleUser);
var result = await _dataManager.UserService.CreateArticleUser(articleUser);
if (result == null)
{
return BadRequest($"ArticleUser {articleUser.UserEntityPseudo} already exists");
}
return Ok(result);
}
catch (Exception error)
{
_logger.LogError(error.Message);
return BadRequest(error.Message);
}
}
[HttpDelete("/user/{pseudo}/{id}")]
public async Task<IActionResult> DeleteArticleUser(string pseudo, long id)
{
_logger.LogInformation("Executing {Action} - with parameters: {Parameters}",nameof(DeleteArticleUser), pseudo);
try
{
var result = await _dataManager.UserService.DeleteArticleUser(pseudo, id);
if (!result)
{
return BadRequest($"User {pseudo} or {id} does not exist");
}
return Ok(result);
}
catch (Exception error)
{
_logger.LogError(error.Message);
return BadRequest(error.Message);
}
}
[HttpPut("/user/{pseudo}/article")]
public async Task<IActionResult> UpdateArticleUser(ArticleUserEntity articleUser)
{
_logger.LogInformation("Executing {Action} - with parameters: {Parameters}",nameof(UpdateArticleUser), articleUser);
try
{
var result = (await _dataManager.UserService.UpdateArticleUser(articleUser));
if (!result)
{
return BadRequest($"ArticleUser {articleUser.UserEntityPseudo} does not exist");
}
return Ok(result);
}
catch (Exception error)
{
_logger.LogError(error.Message);
return BadRequest(error.Message);
}
}
} }
} }

@ -2,6 +2,7 @@ using API_Services;
using DbContextLib; using DbContextLib;
using DbDataManager; using DbDataManager;
using Microsoft.EntityFrameworkCore; using Microsoft.EntityFrameworkCore;
using Model;
using StubbedContextLib; using StubbedContextLib;
var builder = WebApplication.CreateBuilder(args); var builder = WebApplication.CreateBuilder(args);
@ -20,9 +21,9 @@ builder.Services.AddDbContext<LibraryContext>(options =>
options.UseSqlite("Data Source=Entity_FrameWork.Article.db"); options.UseSqlite("Data Source=Entity_FrameWork.Article.db");
}); });
builder.Services.AddScoped<IArticleService, DbManagerArticle>(); builder.Services.AddScoped<IDataManager, DbManager>();
builder.Services.AddScoped<IUserService, DbManagerUser>();
builder.Services.AddScoped<IFormulaireService, DbManagerFormulaire>();
var app = builder.Build(); var app = builder.Build();

@ -0,0 +1,34 @@
info: 03/15/2024 16:59:22.173 RelationalEventId.CommandExecuted[20101] (Microsoft.EntityFrameworkCore.Database.Command)
Executed DbCommand (6ms) [Parameters=[], CommandType='Text', CommandTimeout='30']
SELECT COUNT(*) FROM "sqlite_master" WHERE "name" = '__EFMigrationsHistory' AND "type" = 'table';
info: 03/15/2024 16:59:22.176 RelationalEventId.CommandExecuted[20101] (Microsoft.EntityFrameworkCore.Database.Command)
Executed DbCommand (0ms) [Parameters=[], CommandType='Text', CommandTimeout='30']
SELECT COUNT(*) FROM "sqlite_master" WHERE "name" = '__EFMigrationsHistory' AND "type" = 'table';
info: 03/15/2024 16:59:22.182 RelationalEventId.CommandExecuted[20101] (Microsoft.EntityFrameworkCore.Database.Command)
Executed DbCommand (0ms) [Parameters=[], CommandType='Text', CommandTimeout='30']
SELECT "MigrationId", "ProductVersion"
FROM "__EFMigrationsHistory"
ORDER BY "MigrationId";
info: 03/15/2024 16:59:22.190 RelationalEventId.MigrationsNotApplied[20405] (Microsoft.EntityFrameworkCore.Migrations)
No migrations were applied. The database is already up to date.
info: 03/15/2024 16:59:30.063 RelationalEventId.CommandExecuted[20101] (Microsoft.EntityFrameworkCore.Database.Command)
Executed DbCommand (0ms) [Parameters=[], CommandType='Text', CommandTimeout='30']
SELECT "a"."Id", "a"."Author", "a"."DatePublished", "a"."Description", "a"."LectureTime", "a"."Title"
FROM "ArticleSet" AS "a"
info: 03/15/2024 17:08:29.557 RelationalEventId.CommandExecuted[20101] (Microsoft.EntityFrameworkCore.Database.Command)
Executed DbCommand (6ms) [Parameters=[], CommandType='Text', CommandTimeout='30']
SELECT COUNT(*) FROM "sqlite_master" WHERE "name" = '__EFMigrationsHistory' AND "type" = 'table';
info: 03/15/2024 17:08:29.561 RelationalEventId.CommandExecuted[20101] (Microsoft.EntityFrameworkCore.Database.Command)
Executed DbCommand (0ms) [Parameters=[], CommandType='Text', CommandTimeout='30']
SELECT COUNT(*) FROM "sqlite_master" WHERE "name" = '__EFMigrationsHistory' AND "type" = 'table';
info: 03/15/2024 17:08:29.567 RelationalEventId.CommandExecuted[20101] (Microsoft.EntityFrameworkCore.Database.Command)
Executed DbCommand (0ms) [Parameters=[], CommandType='Text', CommandTimeout='30']
SELECT "MigrationId", "ProductVersion"
FROM "__EFMigrationsHistory"
ORDER BY "MigrationId";
info: 03/15/2024 17:08:29.575 RelationalEventId.MigrationsNotApplied[20405] (Microsoft.EntityFrameworkCore.Migrations)
No migrations were applied. The database is already up to date.
info: 03/15/2024 17:08:33.305 RelationalEventId.CommandExecuted[20101] (Microsoft.EntityFrameworkCore.Database.Command)
Executed DbCommand (0ms) [Parameters=[], CommandType='Text', CommandTimeout='30']
SELECT "a"."Id", "a"."Author", "a"."DatePublished", "a"."Description", "a"."LectureTime", "a"."Title"
FROM "ArticleSet" AS "a"

@ -1,12 +1,30 @@
using API_Services;
using DbContextLib; using DbContextLib;
using Model;
namespace DbDataManager; namespace DbDataManager;
public class DbManager public class DbManager : IDataManager
{ {
protected LibraryContext _context; protected LibraryContext _context { get; set; }
public DbManager() public DbManager()
{ {
_context = new LibraryContext(); _context = new LibraryContext();
ArticleService = new DbManagerArticle(_context);
UserService = new DbManagerUser(_context);
FormulaireService = new DbManagerFormulaire(_context);
} }
public DbManager(LibraryContext context)
{
_context = context;
ArticleService = new DbManagerArticle(_context);
UserService = new DbManagerUser(_context);
FormulaireService = new DbManagerFormulaire(_context);
}
public IArticleService ArticleService { get; set; }
public IUserService UserService { get; set; }
public IFormulaireService FormulaireService { get; set; }
} }

@ -11,25 +11,60 @@ public class DbManagerArticle : IArticleService
private readonly LibraryContext _context; private readonly LibraryContext _context;
public DbManagerArticle(LibraryContext context) public DbManagerArticle(LibraryContext context)
=> this._context = context;
public async Task<IEnumerable<Article?>> GetAllArticles(int index, int count, ArticleOrderCriteria orderCriterium)
{ {
_context = context; List<Article> articles = new List<Article>();
switch (orderCriterium)
{
case ArticleOrderCriteria.None:
articles = _context.ArticleSet.Select(a => a.ToModel()).ToList();
break;
case ArticleOrderCriteria.ByLectureTime:
articles = _context.ArticleSet.OrderBy(a => a.LectureTime).Select(a => a.ToModel()).ToList();
break;
case ArticleOrderCriteria.ByTitle:
articles = _context.ArticleSet.OrderBy(a => a.Title).Select(a => a.ToModel()).ToList();
break;
case ArticleOrderCriteria.ByAuthor:
articles = _context.ArticleSet.OrderBy(a => a.Author).Select(a => a.ToModel()).ToList();
break;
case ArticleOrderCriteria.ByDatePublished:
articles = _context.ArticleSet.OrderBy(a => a.DatePublished).Select(a => a.ToModel()).ToList();
break;
case ArticleOrderCriteria.ByDescription:
articles = _context.ArticleSet.OrderBy(a => a.Description).Select(a => a.ToModel()).ToList();
break;
default:
articles = _context.ArticleSet.Select(a => a.ToModel()).ToList();
break;
}
return await Task.FromResult(articles.AsEnumerable());
} }
public Task<Article?> GetArticleById(int id)
{
var entity = _context.ArticleSet.FirstOrDefault(a => a.Id == id);
if (entity == null) return Task.FromResult<Article?>(null);
return Task.FromResult(entity.ToModel());
}
public async Task<Article?> CreateArticle(long id, string title, string description, string author, string date, int lectureTime)
public async Task<Article?> CreateArticle(Article article)
{ {
var entity = new Entities.ArticleEntity() var entity = new Entities.ArticleEntity()
{ {
Id = id, Id = article.Id,
Title = title, Title = article.Title,
Description = description, Description = article.Description,
Author = author, Author = article.Author,
DatePublished = date, DatePublished = article.DatePublished,
LectureTime = lectureTime, LectureTime = article.LectureTime,
}; };
_context.ArticleSet.Add(entity); _context.ArticleSet.Add(entity);
await _context.SaveChangesAsync(); var result = await _context.SaveChangesAsync();
if (result == 0) return await Task.FromResult<Article?>(null);
return entity.ToModel(); return entity.ToModel();
} }
@ -39,31 +74,25 @@ public class DbManagerArticle : IArticleService
Console.WriteLine(entity); Console.WriteLine(entity);
if (entity == null) return null; if (entity == null) return null;
_context.ArticleSet.Remove(entity); _context.ArticleSet.Remove(entity);
await _context.SaveChangesAsync(); var result = await _context.SaveChangesAsync();
if (result == 0) return await Task.FromResult<Article?>(null);
return entity.ToModel(); return entity.ToModel();
} }
public async Task<bool> UpdateArticle(long id, Article? a) public async Task<Article?> UpdateArticle(long id, Article? a)
{ {
var entity = _context.ArticleSet.FirstOrDefault(a => a.Id == id); var entity = _context.ArticleSet.FirstOrDefault(a => a.Id == id);
if (entity == null) return false; if (entity == null) return await Task.FromResult<Article?>(null);
entity.Title = a.Title; entity.Title = a.Title;
entity.Description = a.Description; entity.Description = a.Description;
entity.Author = a.Author; entity.Author = a.Author;
entity.DatePublished = a.DatePublished; entity.DatePublished = a.DatePublished;
entity.LectureTime = a.LectureTime; entity.LectureTime = a.LectureTime;
await _context.SaveChangesAsync(); var result = await _context.SaveChangesAsync();
return true; if (result == 0) return await Task.FromResult<Article?>(null);
return entity.ToModel();
} }
public Task<Article?> GetArticleById(int id)
{
var entity = _context.ArticleSet.FirstOrDefault(a => a.Id == id);
return Task.FromResult(entity.ToModel());
}
public async Task<IEnumerable<Article?>> GetAllArticles()
{
return await Task.FromResult(_context.ArticleSet.Select(a => a.ToModel()).AsEnumerable());
}
} }

@ -11,13 +11,33 @@ public class DbManagerFormulaire : IFormulaireService
private readonly LibraryContext _context; private readonly LibraryContext _context;
public DbManagerFormulaire(LibraryContext context) public DbManagerFormulaire(LibraryContext context)
{ => this._context = context;
_context = context;
}
public async Task<IEnumerable<Formulaire?>> GetAllForm() public async Task<IEnumerable<Formulaire?>> GetAllForm(int index, int count, FormOrderCriteria orderCriteria)
{ {
return await Task.FromResult(_context.FormSet.Select(f => f.ToModel()).AsEnumerable()); List<Formulaire> formulaireList = new List<Formulaire>();
switch (orderCriteria)
{
case FormOrderCriteria.None:
formulaireList = _context.FormSet.Skip(index * count).Select(f => f.ToModel()).ToList();
break;
case FormOrderCriteria.ByTheme:
formulaireList = _context.FormSet.Skip(index * count).OrderBy(f => f.Theme).Select(f => f.ToModel()).ToList();
break;
case FormOrderCriteria.ByLien:
formulaireList = _context.FormSet.Skip(index * count).OrderBy(f => f.Link).Select(f => f.ToModel()).ToList();
break;
case FormOrderCriteria.ByDate:
formulaireList = _context.FormSet.Skip(index * count).OrderBy(f => f.DatePublication).Select(f => f.ToModel()).ToList();
break;
case FormOrderCriteria.ByPseudo:
formulaireList = _context.FormSet.Skip(index * count).OrderBy(f => f.UserEntityPseudo).Select(f => f.ToModel()).ToList();
break;
default:
formulaireList = _context.FormSet.Skip(index * count).Select(f => f.ToModel()).ToList();
break;
}
return await Task.FromResult(formulaireList.AsEnumerable());
} }
public async Task<Formulaire?> GetById(long id) public async Task<Formulaire?> GetById(long id)
@ -32,33 +52,38 @@ public class DbManagerFormulaire : IFormulaireService
var entity = new FormEntity() var entity = new FormEntity()
{ {
Id = formulaire.Id, Id = formulaire.Id,
Pseudo = formulaire.Pseudo, Link = formulaire.Lien,
Theme = formulaire.Theme, Theme = formulaire.Theme,
DatePublication = formulaire.Date DatePublication = formulaire.Date,
UserEntityPseudo = formulaire.UserPseudo
}; };
_context.FormSet.Add(entity); _context.FormSet.Add(entity);
await _context.SaveChangesAsync(); var result = await _context.SaveChangesAsync();
if (result == 0) return await Task.FromResult<Formulaire?>(null);
return entity.ToModel(); return entity.ToModel();
} }
public async Task<bool> DeleteForm(long id) public async Task<Formulaire?> DeleteForm(long id)
{ {
var entity = _context.FormSet.FirstOrDefault(f => f.Id == id); var entity = _context.FormSet.FirstOrDefault(f => f.Id == id);
if (entity == null) return false; if (entity == null) return Task.FromResult<Formulaire?>(null).Result;
_context.FormSet.Remove(entity); _context.FormSet.Remove(entity);
await _context.SaveChangesAsync(); var result = await _context.SaveChangesAsync();
return true; if (result == 0) return await Task.FromResult<Formulaire?>(null);
return entity.ToModel();
} }
public async Task<bool> UpdateForm(long id, Formulaire formulaire) public async Task<Formulaire?> UpdateForm(long id, Formulaire formulaire)
{ {
var entity = _context.FormSet.FirstOrDefault(f => f.Id == id); var entity = _context.FormSet.FirstOrDefault(f => f.Id == id);
if (entity == null) return false; if (entity == null) return Task.FromResult<Formulaire?>(null).Result;
entity.Pseudo = formulaire.Pseudo;
entity.Theme = formulaire.Theme; entity.Theme = formulaire.Theme;
entity.DatePublication = formulaire.Date; entity.DatePublication = formulaire.Date;
await _context.SaveChangesAsync(); entity.Link = formulaire.Lien;
return true; entity.UserEntityPseudo = formulaire.UserPseudo;
var result = await _context.SaveChangesAsync();
if (result == 0) return await Task.FromResult<Formulaire?>(null);
return entity.ToModel();
} }
} }

@ -11,11 +11,39 @@ public class DbManagerUser: IUserService
private readonly LibraryContext _context; private readonly LibraryContext _context;
public DbManagerUser(LibraryContext context) public DbManagerUser(LibraryContext context)
=> this._context = context;
public async Task<IEnumerable<User?>> GetAll(int index, int count, UserOrderCriteria orderCriteria)
{
List<User> users = new List<User>();
switch(orderCriteria)
{
case UserOrderCriteria.None:
users = _context.UserSet.Skip(index * count).Select(u => u.ToModel()).ToList();
break;
case UserOrderCriteria.ByFirstName:
users = _context.UserSet.Skip(index * count).OrderBy(u => u.Prenom).Select(u => u.ToModel()).ToList();
break;
case UserOrderCriteria.ByLastName:
users = _context.UserSet.Skip(index * count).OrderBy(u => u.Nom).Select(u => u.ToModel()).ToList();
break;
default:
users = _context.UserSet.Skip(index * count).Select(u => u.ToModel()).ToList();
break;
}
return await Task.FromResult(users.AsEnumerable());
}
public async Task<User?> GetByPseudo(string pseudo)
{ {
_context = context; var entity = _context.UserSet.FirstOrDefault(u => u.Pseudo == pseudo);
if (entity == null) return await Task.FromResult<User?>(null);
return await Task.FromResult(entity.ToModel());
} }
public async Task<bool> Create(User user) public async Task<User?> Create(User user)
{ {
var entity = new UserEntity() var entity = new UserEntity()
{ {
@ -27,41 +55,99 @@ public class DbManagerUser: IUserService
Role = user.Role Role = user.Role
}; };
_context.UserSet.Add(entity); _context.UserSet.Add(entity);
await _context.SaveChangesAsync(); var result = await _context.SaveChangesAsync();
return true; if (result == 0) return await Task.FromResult<User?>(null);
return await Task.FromResult(entity.ToModel());
} }
public async Task<bool> Update(User user) public async Task<User?> Update(User user, string pseudo)
{ {
var entity = _context.UserSet.FirstOrDefault(u => u.Pseudo == user.Pseudo); var entity = _context.UserSet.FirstOrDefault(u => u.Pseudo == pseudo);
if (entity == null) return false; if (entity == null) return await Task.FromResult<User?>(null);
entity.Mdp = user.Mdp; entity.Mdp = user.Mdp;
entity.Mail = user.Mail; entity.Mail = user.Mail;
entity.Role = user.Role; entity.Role = user.Role;
entity.Prenom = user.Prenom; entity.Prenom = user.Prenom;
entity.Nom = user.Nom; entity.Nom = user.Nom;
await _context.SaveChangesAsync(); var result = await _context.SaveChangesAsync();
return true; if (result == 0) return await Task.FromResult<User?>(null);
return await Task.FromResult(entity.ToModel());
} }
public async Task<bool> Delete(string pseudo) public async Task<User?> Delete(string pseudo)
{ {
var entity = _context.UserSet.FirstOrDefault(u => u.Pseudo == pseudo); var entity = _context.UserSet.FirstOrDefault(u => u.Pseudo == pseudo);
if (entity == null) return await Task.FromResult(false); if (entity == null) return await Task.FromResult<User?>(null);
_context.UserSet.Remove(entity); _context.UserSet.Remove(entity);
var result = await _context.SaveChangesAsync();
if (result == 0) return await Task.FromResult<User?>(null);
return await Task.FromResult(entity.ToModel());
}
public async Task<IEnumerable<User?>> GetAllArticleUsers()
{
var entities = _context.ArticleUserSet.ToList();
List<UserEntity> users = new List<UserEntity>();
foreach( var articleUser in entities)
{
var user = _context.UserSet.FirstOrDefault(u => u.Pseudo.Equals(articleUser.UserEntityPseudo));
if (user != null) users.Add(user);
}
if (users == null) return await Task.FromResult<IEnumerable<User?>>(null);
return await Task.FromResult(users.Select(u => u.ToModel()).AsEnumerable());
}
public async Task<IEnumerable<Article?>> GetArticleUser(string pseudo)
{
var entities = _context.ArticleUserSet.Where(a => a.UserEntityPseudo.Equals(pseudo));
List<ArticleEntity> articles = new List<ArticleEntity>();
foreach (var article in entities)
{
var art = _context.ArticleSet.FirstOrDefault(a => a.Id.Equals(article.ArticleEntityId));
if (art != null) articles.Add(art);
}
if (articles == null) return await Task.FromResult<IEnumerable<Article?>>(null);
return await Task.FromResult(articles.Select(a => a.ToModel()).AsEnumerable());
}
public async Task<bool> CreateArticleUser(ArticleUserEntity articleUser)
{
var result = await GetByPseudo(articleUser.UserEntityPseudo);
if (result == null) return await Task.FromResult(false);
var entity = new ArticleUserEntity()
{
ArticleEntityId = articleUser.ArticleEntityId,
UserEntityPseudo = articleUser.UserEntityPseudo
};
if (entity == null) return await Task.FromResult(false);
_context.ArticleUserSet.Add(entity);
await _context.SaveChangesAsync(); await _context.SaveChangesAsync();
return await Task.FromResult(true); return await Task.FromResult(true);
} }
public async Task<User?> GetByPseudo(string pseudo) public async Task<bool> DeleteArticleUser(string pseudo, long id)
{ {
var entity = _context.UserSet.FirstOrDefault(u => u.Pseudo == pseudo);
return await Task.FromResult(entity.ToModel()); var entity = _context.ArticleUserSet.FirstOrDefault(a => a.UserEntityPseudo.Equals(pseudo) && a.ArticleEntityId.Equals(id));
if (entity == null) return await Task.FromResult(false);
_context.ArticleUserSet.Remove(entity);
await _context.SaveChangesAsync();
return await Task.FromResult(true);
} }
public async Task<IEnumerable<User?>> GetAll() public async Task<bool> UpdateArticleUser(ArticleUserEntity articleUser)
{ {
return await Task.FromResult(_context.UserSet.Select(u => u.ToModel()).AsEnumerable()); var entity = _context.ArticleUserSet.FirstOrDefault(a => a.UserEntityPseudo.Equals(articleUser.UserEntityPseudo));
if (entity == null) return await Task.FromResult(false);
entity.ArticleEntityId = articleUser.ArticleEntityId;
entity.UserEntityPseudo = articleUser.UserEntityPseudo;
await _context.SaveChangesAsync();
return await Task.FromResult(true);
} }
} }

@ -26,10 +26,10 @@ public static class Extensions
=> new User{ Pseudo = user.Pseudo, Mdp = user.Mdp, Prenom = user.Prenom, Nom = user.Nom, Mail = user.Mail, Role = user.Role}; => new User{ Pseudo = user.Pseudo, Mdp = user.Mdp, Prenom = user.Prenom, Nom = user.Nom, Mail = user.Mail, Role = user.Role};
public static FormEntity ToEntity(this Formulaire form) public static FormEntity ToEntity(this Formulaire form)
=> new FormEntity{ Id = form.Id, Pseudo = form.Pseudo, Theme = form.Theme, Link = form.Lien}; => new FormEntity{ Id = form.Id, UserEntityPseudo = form.UserPseudo, Theme = form.Theme, Link = form.Lien};
public static Formulaire ToModel(this FormEntity form) public static Formulaire ToModel(this FormEntity form)
=> new Formulaire{ Id = form.Id, Pseudo = form.Pseudo, Theme = form.Theme, Lien = form.Link}; => new Formulaire{ Id = form.Id, UserPseudo = form.UserEntityPseudo, Theme = form.Theme, Lien = form.Link};
} }

@ -5,7 +5,7 @@ namespace API_Mapping;
public static class ArticleMapper public static class ArticleMapper
{ {
public static ArticleDTO ToDTO(this Article a) => new() public static ArticleDTO ToDTO(this Article? a) => new()
{ {
Id = a.Id, Id = a.Id,
Title = a.Title, Title = a.Title,

@ -5,13 +5,13 @@ namespace API_Mapping;
public static class FormulaireMapping public static class FormulaireMapping
{ {
public static FormulaireDTO ToDTO(this Formulaire f) => new() public static FormulaireDTO ToDTO(this Formulaire? f) => new()
{ {
Id = f.Id, Id = f.Id,
Theme = f.Theme, Theme = f.Theme,
Date = f.Date, Date = f.Date,
Lien = f.Lien, Lien = f.Lien,
Pseudo = f.Pseudo UserPseudo = f.UserPseudo
}; };
public static Formulaire ToModel(this FormulaireDTO f) => new() public static Formulaire ToModel(this FormulaireDTO f) => new()
@ -20,6 +20,6 @@ public static class FormulaireMapping
Theme = f.Theme, Theme = f.Theme,
Date = f.Date, Date = f.Date,
Lien = f.Lien, Lien = f.Lien,
Pseudo = f.Pseudo UserPseudo = f.UserPseudo
}; };
} }

@ -5,7 +5,7 @@ namespace API_Mapping;
public static class UserMapping public static class UserMapping
{ {
public static UserDTO ToDTO(this User u) => new() public static UserDTO ToDTO(this User? u) => new()
{ {
Pseudo = u.Pseudo, Pseudo = u.Pseudo,
Mdp = u.Mdp, Mdp = u.Mdp,

@ -6,7 +6,7 @@ public class FormulaireDTO
public string Theme { get; set; } public string Theme { get; set; }
public string Date { get; set; } public string Date { get; set; }
public string Lien { get; set; } public string Lien { get; set; }
public string Pseudo { get; set; } public string UserPseudo { get; set; }
} }

@ -7,6 +7,7 @@
</PropertyGroup> </PropertyGroup>
<ItemGroup> <ItemGroup>
<ProjectReference Include="..\Entities\Entities.csproj" />
<ProjectReference Include="..\Model\Model.csproj" /> <ProjectReference Include="..\Model\Model.csproj" />
</ItemGroup> </ItemGroup>

@ -4,16 +4,18 @@ namespace API_Services
{ {
public interface IArticleService public interface IArticleService
{ {
Task<Article?> CreateArticle(long id, string title, string description, string author, string date,
int lectureTime);
Task<Article?> DeleteArticle(long id); Task<IEnumerable<Article?>> GetAllArticles(int index, int count, ArticleOrderCriteria orderCriterium);
Task<bool> UpdateArticle(long id, Article? a);
Task<Article?> GetArticleById(int id); Task<Article?> GetArticleById(int id);
Task<IEnumerable<Article?>> GetAllArticles();
Task<Article?> CreateArticle(Article article);
Task<Article?> DeleteArticle(long id);
Task<Article?> UpdateArticle(long id, Article? a);
} }
} }

@ -0,0 +1,13 @@
namespace Model;
using API_Services;
public interface IDataManager
{
IArticleService ArticleService { get; }
IUserService UserService { get; }
IFormulaireService FormulaireService { get; }
}

@ -5,14 +5,14 @@ namespace API_Services;
public interface IFormulaireService public interface IFormulaireService
{ {
Task<IEnumerable<Formulaire?>> GetAllForm(); Task<IEnumerable<Formulaire?>> GetAllForm(int index, int count, FormOrderCriteria orderCriteria);
Task<Formulaire?> GetById(long id); Task<Formulaire?> GetById(long id);
Task<Formulaire?> CreateForm(Formulaire formulaire); Task<Formulaire?> CreateForm(Formulaire formulaire);
Task<bool> DeleteForm(long id); Task<Formulaire?> DeleteForm(long id);
Task<bool> UpdateForm(long id, Formulaire formulaire); Task<Formulaire?> UpdateForm(long id, Formulaire formulaire);
} }

@ -1,18 +1,29 @@
using Model; using Entities;
using Model;
namespace API_Services namespace API_Services
{ {
public interface IUserService public interface IUserService
{ {
Task<bool> Create(User user);
Task<bool> Update(User user);
Task<bool> Delete(string pseudo); Task<IEnumerable<User?>> GetAll(int index, int count, UserOrderCriteria orderCriteria);
Task<User?> GetByPseudo(string pseudo);
Task<User?> Create(User user);
Task<User?> Update(User user, string pseudo);
Task<User?> Delete(string pseudo);
Task<IEnumerable<User?>> GetAllArticleUsers();
Task<IEnumerable<Article?>> GetArticleUser(string pseudo);
Task<bool> CreateArticleUser(ArticleUserEntity articleUser);
Task<bool> DeleteArticleUser(string pseudo, long id);
Task<bool> UpdateArticleUser(ArticleUserEntity articleUser);
Task<User?> GetByPseudo(string pseudo);
Task<IEnumerable<User?>> GetAll();

@ -0,0 +1,15 @@
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<OutputType>Exe</OutputType>
<TargetFramework>net8.0</TargetFramework>
<ImplicitUsings>enable</ImplicitUsings>
<Nullable>enable</Nullable>
</PropertyGroup>
<ItemGroup>
<ProjectReference Include="..\Entities\Entities.csproj" />
<ProjectReference Include="..\Model\Model.csproj" />
</ItemGroup>
</Project>

@ -0,0 +1,427 @@
// See https://aka.ms/new-console-template for more information
using System.Text;
using System.Text.Json;
using Entities;
using Model;
class Tests_Console
{
static readonly HttpClient client = new HttpClient();
static async Task Main(string[] args)
{
//await TestUser();
await TestFormulaire();
//await TestArticle();
}
private static async Task TestFormulaire()
{
await TestFormulaireGetAll();
//await TestFormulaireGetId();
//await TestFormulaireCreate();
//await TestFormulaireDelete();
//await TestFormulaireUpdate();
}
private static async Task TestUser()
{
//await TestUserGetAll();
//await TestUserGetId();
//await TestUserCreate();
//await TestUserDelete();
//await TestUserUpdate();
//await TestGetAllArticleUser();
//await TestGetArticleByUser();
//await TestCreateArticleUser();
//await TestDeleteArticleUser();
//await TestUpdateArticleUser();
}
static async Task TestArticle()
{
await TestArticleGetId();
await TestArticleCreate();
await TestArticleGetAll();
await TestArticleDelete();
await TestArticleUpdate();
}
static async Task TestArticleGetAll()
{
try
{
var response = await client.GetAsync("http://localhost:5052/api/Article");
response.EnsureSuccessStatusCode();
var responseBody = await response.Content.ReadAsStringAsync();
Console.WriteLine(responseBody);
}
catch (Exception e)
{
Console.WriteLine(e.Message);
}
}
static async Task TestArticleGetId()
{
try
{
var response = await client.GetAsync("http://localhost:5052/article/1");
response.EnsureSuccessStatusCode();
var responseBody = await response.Content.ReadAsStringAsync();
Console.WriteLine(responseBody);
}
catch (Exception e)
{
Console.WriteLine(e.Message);
}
}
static async Task TestArticleCreate()
{
try
{
var article = new Article()
{
Title = "Test",
Description = "Test",
Author = "Test",
DatePublished = "Test",
LectureTime = 0
};
var json = JsonSerializer.Serialize(article);
var data = new StringContent(json, Encoding.UTF8, "application/json");
var response = await client.PostAsync("http://localhost:5052/article", data);
response.EnsureSuccessStatusCode();
var responseBody = await response.Content.ReadAsStringAsync();
Console.WriteLine(responseBody);
}
catch (Exception e)
{
Console.WriteLine(e.Message);
}
}
static async Task TestArticleDelete()
{
try
{
var response = await client.DeleteAsync("http://localhost:5052/article/4");
response.EnsureSuccessStatusCode();
var responseBody = await response.Content.ReadAsStringAsync();
Console.WriteLine(responseBody);
}
catch (Exception e)
{
Console.WriteLine(e.Message);
}
}
static async Task TestArticleUpdate()
{
try
{
var article = new Article()
{
Title = "Louis",
Description = "Je",
Author = "T'",
DatePublished = "aime",
LectureTime = 0
};
var json = JsonSerializer.Serialize(article);
var data = new StringContent(json, Encoding.UTF8, "application/json");
var response = await client.PutAsync("http://localhost:5052/article/1", data);
response.EnsureSuccessStatusCode();
var responseBody = await response.Content.ReadAsStringAsync();
Console.WriteLine(responseBody);
}
catch (Exception e)
{
Console.WriteLine(e.Message);
}
}
static async Task TestFormulaireGetAll()
{
try
{
var response = await client.GetAsync("http://localhost:5052/formulaires");
response.EnsureSuccessStatusCode();
var responseBody = await response.Content.ReadAsStringAsync();
Console.WriteLine(responseBody);
}
catch (Exception e)
{
Console.WriteLine(e.Message);
}
}
static async Task TestFormulaireGetId()
{
try
{
var response = await client.GetAsync("http://localhost:5052/formulaire/2");
response.EnsureSuccessStatusCode();
var responseBody = await response.Content.ReadAsStringAsync();
Console.WriteLine(responseBody);
}
catch (Exception e)
{
Console.WriteLine(e.Message);
}
}
static async Task TestFormulaireCreate()
{
try
{
var formulaire = new Formulaire()
{
Theme = "Test",
Date = "Test",
Lien = "Test",
UserPseudo = "Sha"
};
var json = JsonSerializer.Serialize(formulaire);
var data = new StringContent(json, Encoding.UTF8, "application/json");
var response = await client.PostAsync("http://localhost:5052/formulaire", data);
response.EnsureSuccessStatusCode();
var responseBody = await response.Content.ReadAsStringAsync();
Console.WriteLine(responseBody);
}
catch (Exception e)
{
Console.WriteLine(e.Message);
}
}
static async Task TestFormulaireDelete()
{
try
{
var response = await client.DeleteAsync("http://localhost:5052/formulaire/5");
response.EnsureSuccessStatusCode();
var responseBody = await response.Content.ReadAsStringAsync();
Console.WriteLine(responseBody);
}
catch (Exception e)
{
Console.WriteLine(e.Message);
}
}
static async Task TestFormulaireUpdate()
{
try
{
var formulaire = new Formulaire()
{
Theme = "J'",
Date = "aime",
Lien = "Les",
UserPseudo = "Sha"
};
var json = JsonSerializer.Serialize(formulaire);
var data = new StringContent(json, Encoding.UTF8, "application/json");
var response = await client.PutAsync("http://localhost:5052/formulaire/4", data);
response.EnsureSuccessStatusCode();
var responseBody = await response.Content.ReadAsStringAsync();
Console.WriteLine(responseBody);
}
catch (Exception e)
{
Console.WriteLine(e.Message);
}
}
static async Task TestUserGetAll()
{
try
{
var response = await client.GetAsync("http://localhost:5052/users");
response.EnsureSuccessStatusCode();
var responseBody = await response.Content.ReadAsStringAsync();
Console.WriteLine(responseBody);
}
catch (Exception e)
{
Console.WriteLine(e.Message);
}
}
static async Task TestUserGetId()
{
try
{
var response = await client.GetAsync("http://localhost:5052/user/Sha");
response.EnsureSuccessStatusCode();
var responseBody = await response.Content.ReadAsStringAsync();
Console.WriteLine(responseBody);
}
catch (Exception e)
{
Console.WriteLine(e.Message);
}
}
static async Task TestUserCreate()
{
try
{
var user = new User()
{
Pseudo = "J",
Nom = "'",
Prenom = "aime",
Mail = "les",
Mdp = "pieds",
Role = "Admin"
};
var json = JsonSerializer.Serialize(user);
var data = new StringContent(json, Encoding.UTF8, "application/json");
var response = await client.PostAsync("http://localhost:5052/user", data);
response.EnsureSuccessStatusCode();
var responseBody = await response.Content.ReadAsStringAsync();
Console.WriteLine(responseBody);
}
catch (Exception e)
{
Console.WriteLine(e.Message);
}
}
static async Task TestUserDelete()
{
try
{
var response = await client.DeleteAsync("http://localhost:5052/user/J");
response.EnsureSuccessStatusCode();
var responseBody = await response.Content.ReadAsStringAsync();
Console.WriteLine(responseBody);
}
catch (Exception e)
{
Console.WriteLine(e.Message);
}
}
static async Task TestUserUpdate()
{
try
{
var user = new User()
{
Pseudo = "Sha",
Nom = "J'",
Prenom = "aime",
Mail = "les",
Mdp = "pieds",
Role = "Admin"
};
var json = JsonSerializer.Serialize(user);
var data = new StringContent(json, Encoding.UTF8, "application/json");
var response = await client.PutAsync("http://localhost:5052/user/Sha", data);
response.EnsureSuccessStatusCode();
var responseBody = await response.Content.ReadAsStringAsync();
Console.WriteLine(responseBody);
}
catch (Exception e)
{
Console.WriteLine(e.Message);
}
}
static async Task TestGetAllArticleUser()
{
try
{
var response = await client.GetAsync("http://localhost:5052/ArticleUsers");
response.EnsureSuccessStatusCode();
var responseBody = await response.Content.ReadAsStringAsync();
Console.WriteLine(responseBody);
}
catch (Exception e)
{
Console.WriteLine(e.Message);
}
}
static async Task TestGetArticleByUser()
{
try
{
var response = await client.GetAsync("http://localhost:5052/user/Sha/article");
response.EnsureSuccessStatusCode();
var responseBody = await response.Content.ReadAsStringAsync();
Console.WriteLine(responseBody);
}
catch (Exception e)
{
Console.WriteLine(e.Message);
}
}
static async Task TestCreateArticleUser()
{
try
{
var articleUser = new ArticleUserEntity()
{
ArticleEntityId = 1,
UserEntityPseudo = "Sha"
};
var json = JsonSerializer.Serialize(articleUser);
var data = new StringContent(json, Encoding.UTF8, "application/json");
var response = await client.PostAsync("http://localhost:5052/user/article", data);
response.EnsureSuccessStatusCode();
var responseBody = await response.Content.ReadAsStringAsync();
Console.WriteLine(responseBody);
}
catch (Exception e)
{
Console.WriteLine(e.Message);
}
}
static async Task TestDeleteArticleUser()
{
try
{
var response = await client.DeleteAsync("http://localhost:5052/user/Sha/article");
response.EnsureSuccessStatusCode();
var responseBody = await response.Content.ReadAsStringAsync();
Console.WriteLine(responseBody);
}
catch (Exception e)
{
Console.WriteLine(e.Message);
}
}
static async Task TestUpdateArticleUser()
{
try
{
var articleUser = new ArticleUserEntity()
{
ArticleEntityId = 1,
UserEntityPseudo = "Sha"
};
var json = JsonSerializer.Serialize(articleUser);
var data = new StringContent(json, Encoding.UTF8, "application/json");
var response = await client.PutAsync("http://localhost:5052/user/Sha/article", data);
response.EnsureSuccessStatusCode();
var responseBody = await response.Content.ReadAsStringAsync();
Console.WriteLine(responseBody);
}
catch (Exception e)
{
Console.WriteLine(e.Message);
}
}
}

@ -0,0 +1,30 @@
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<TargetFramework>net8.0</TargetFramework>
<ImplicitUsings>enable</ImplicitUsings>
<Nullable>enable</Nullable>
<IsPackable>false</IsPackable>
<IsTestProject>true</IsTestProject>
</PropertyGroup>
<ItemGroup>
<PackageReference Include="Microsoft.NET.Test.Sdk" Version="17.6.0"/>
<PackageReference Include="Moq" Version="4.20.70" />
<PackageReference Include="xunit" Version="2.4.2"/>
<PackageReference Include="xunit.runner.visualstudio" Version="2.4.5">
<IncludeAssets>runtime; build; native; contentfiles; analyzers; buildtransitive</IncludeAssets>
<PrivateAssets>all</PrivateAssets>
</PackageReference>
<PackageReference Include="coverlet.collector" Version="6.0.0">
<IncludeAssets>runtime; build; native; contentfiles; analyzers; buildtransitive</IncludeAssets>
<PrivateAssets>all</PrivateAssets>
</PackageReference>
</ItemGroup>
<ItemGroup>
<ProjectReference Include="..\API_Services\API_Services.csproj" />
</ItemGroup>
</Project>

@ -0,0 +1,129 @@
using API_Services;
using Model;
using Moq;
namespace API_Unit_Test;
public class UnitTest_Article
{
[Fact]
public void TestGetArticleById()
{
var mockArticleService = new Mock<IArticleService>();
var expected = new Article()
{
Id = 1,
Title = "Test",
Description = "Test",
Author = "Test",
DatePublished = "Test",
LectureTime = 10
};
mockArticleService.Setup(x => x.GetArticleById(1)).ReturnsAsync(expected);
var result = mockArticleService.Object.GetArticleById(1);
Assert.Equal(expected, result.Result);
}
[Fact]
public void TestGetAllArticles()
{
var mockArticleService = new Mock<IArticleService>();
var expected = new List<Article>()
{
new Article()
{
Id = 1,
Title = "Test",
Description = "Test",
Author = "Test",
DatePublished = "Test",
LectureTime = 10
},
new Article()
{
Id = 2,
Title = "Test",
Description = "Test",
Author = "Test",
DatePublished = "Test",
LectureTime = 10
}
};
mockArticleService.Setup(x => x.GetAllArticles(0, 10, ArticleOrderCriteria.None)).ReturnsAsync(expected);
var result = mockArticleService.Object.GetAllArticles(0, 10, ArticleOrderCriteria.None);
Assert.Equal(expected, result.Result);
}
[Fact]
public void TestAddArticle()
{
var mockArticleService = new Mock<IArticleService>();
var expected = new Article()
{
Id = 1,
Title = "Test",
Description = "Test",
Author = "Test",
DatePublished = "Test",
LectureTime = 10
};
mockArticleService.Setup(x => x.CreateArticle(expected)).ReturnsAsync(expected);
var result = mockArticleService.Object.CreateArticle(expected);
Assert.Equal(expected, result.Result);
}
[Fact]
public void UpdateArticle()
{
var mockArticleService = new Mock<IArticleService>();
var expected = new Article()
{
Title = "Test",
Description = "Test",
Author = "Test",
DatePublished = "Test",
LectureTime = 10
};
mockArticleService.Setup(x => x.CreateArticle(expected));
var result = mockArticleService.Object.CreateArticle(expected);
Assert.Equal(1, result.Id );
var updated = new Article()
{
Title = "Updated Test",
Description = "Test",
Author = "Test",
DatePublished = "Test",
LectureTime = 10
};
mockArticleService.Setup(x => x.UpdateArticle(1, updated)).ReturnsAsync(updated);
var resultUpdated = mockArticleService.Object.UpdateArticle(1, updated);
Assert.Equal(updated ,resultUpdated.Result);
}
[Fact]
static void DeletedArticle()
{
var mockArticleService = new Mock<IArticleService>();
var expected = new Article()
{
Id = 1,
Title = "Test",
Description = "Test",
Author = "Test",
DatePublished = "Test",
LectureTime = 10
};
mockArticleService.Setup(x => x.CreateArticle(expected)).ReturnsAsync(expected);
var result = mockArticleService.Object.CreateArticle(expected);
Assert.Equal(expected, result.Result);
mockArticleService.Setup(x => x.DeleteArticle(1)).ReturnsAsync(expected);
var resultDeleted = mockArticleService.Object.DeleteArticle(1);
Assert.Equal(expected, result.Result);
}
}

@ -0,0 +1,99 @@
using API_Services;
using Model;
using Moq;
namespace API_Unit_Test;
public class UnitTest_Form
{
[Fact]
public void TestGetAllForm()
{
var mockFormService = new Mock<IFormulaireService>();
var expected = new List<Formulaire>()
{
new Formulaire()
{
Lien = "Test",
Theme = "Test",
Date = "Test",
UserPseudo = "Test"
},
new Formulaire()
{
Lien = "Test",
Theme = "Test",
Date = "Test",
UserPseudo = "Test"
}
};
mockFormService.Setup(x => x.GetAllForm(0, 10, FormOrderCriteria.None)).ReturnsAsync(expected);
var result = mockFormService.Object.GetAllForm(0, 10, FormOrderCriteria.None);
Assert.Equal(expected, result.Result);
}
[Fact]
public void TestGetFormById()
{
var mockFormService = new Mock<IFormulaireService>();
var expected = new Formulaire()
{
Lien = "Test",
Theme = "Test",
Date = "Test",
UserPseudo = "Test"
};
mockFormService.Setup(x => x.GetById(1)).ReturnsAsync(expected);
var result = mockFormService.Object.GetById(1);
Assert.Equal(expected, result.Result);
}
[Fact]
public void TestCreateForm()
{
var mockFormService = new Mock<IFormulaireService>();
var expected = new Formulaire()
{
Lien = "Test",
Theme = "Test",
Date = "Test",
UserPseudo = "Test"
};
mockFormService.Setup(x => x.CreateForm(expected)).ReturnsAsync(expected);
var result = mockFormService.Object.CreateForm(expected);
Assert.Equal(expected, result.Result);
}
[Fact]
public void TestUpdateForm()
{
var mockFormService = new Mock<IFormulaireService>();
var expected = new Formulaire()
{
Lien = "Test",
Theme = "Test",
Date = "Test",
UserPseudo = "Test"
};
mockFormService.Setup(x => x.CreateForm(expected)).ReturnsAsync(expected);
var result = mockFormService.Object.CreateForm(expected);
Assert.Equal(expected, result.Result);
}
[Fact]
public void TestDeleteForm()
{
var mockFormService = new Mock<IFormulaireService>();
var expected = new Formulaire()
{
Lien = "Test",
Theme = "Test",
Date = "Test",
UserPseudo = "Test"
};
mockFormService.Setup(x => x.DeleteForm(1)).ReturnsAsync(expected);
var result = mockFormService.Object.DeleteForm(1);
Assert.Equal(expected, result.Result);
}
}

@ -0,0 +1,215 @@
using API_Services;
using Entities;
using Model;
using Moq;
namespace API_Unit_Test;
public class UnitTest_User
{
[Fact]
static void TestAllUser()
{
var mockUserService = new Mock<IUserService>();
var expected = new List<User>()
{
new User()
{
Pseudo = "Tofgasy",
Prenom = "Tony",
Nom = "Fages",
Mail = "mail@mail.com",
Mdp = "1234",
Role = "Admin"
},
new User()
{
Pseudo = "Blizzard",
Prenom = "Louis",
Nom = "Laborie",
Mail = "mail@mail.com",
Mdp = "1234",
Role = "Admin",
},
};
mockUserService.Setup(x => x.GetAll(0, 10, UserOrderCriteria.None)).ReturnsAsync(expected);
var result = mockUserService.Object.GetAll(0, 10, UserOrderCriteria.None);
Assert.Equal(expected, result.Result);
}
[Fact]
static void TestGetUserByPseudo()
{
var mockUserService = new Mock<IUserService>();
var expected = new User()
{
Pseudo = "Tofgasy",
Prenom = "Tony",
Nom = "Fages",
Mail = "mail@mail.com",
Mdp = "1234",
Role = "Admin"
};
mockUserService.Setup(x => x.GetByPseudo("Tofgasy")).ReturnsAsync(expected);
var result = mockUserService.Object.GetByPseudo("Tofgasy");
Assert.Equal(expected, result.Result);
}
[Fact]
static void TestCreateUser()
{
var mockUserService = new Mock<IUserService>();
var user = new User()
{
Pseudo = "Tofgasy",
Prenom = "Tony",
Nom = "Fages",
Mail = "mail@mail.com",
Mdp = "1234",
Role = "Admin"
};
mockUserService.Setup(x => x.Create(user)).ReturnsAsync(user);
var result = mockUserService.Object.Create(user);
Assert.Equal( user,result.Result);
}
[Fact]
static void TestUpdateUser()
{
var mockUserService = new Mock<IUserService>();
var user = new User()
{
Pseudo = "Tofgasy",
Prenom = "Tonio",
Nom = "Fages",
Mail = "mail@mail.com",
Mdp = "1234",
Role = "Admin"
};
mockUserService.Setup(x => x.Update(user, "Tofgasy")).ReturnsAsync(user);
var result = mockUserService.Object.Update(user, "Tofgasy");
Assert.Equal( user,result.Result);
}
[Fact]
static void TestDeleteUser()
{
var mockUserService = new Mock<IUserService>();
var user = new User()
{
Pseudo = "Tofgasy",
Prenom = "Tonio",
Nom = "Fages",
Mail = "mail@mail.com",
Mdp = "1234",
Role = "Admin"
};
mockUserService.Setup(x => x.Delete("Tofgasy")).ReturnsAsync(user);
var result = mockUserService.Object.Delete("Tofgasy");
Assert.Equal( user,result.Result);
}
[Fact]
static void TestGetAllArticleUsers()
{
var mockUserService = new Mock<IUserService>();
var expected = new List<User>()
{
new User()
{
Pseudo = "Tofgasy",
Prenom = "Tony",
Nom = "Fages",
Mail = "",
Mdp = "",
Role = "",
},
new User()
{
Pseudo = "Blizzard",
Prenom = "Louis",
Nom = "Laborie",
Mail = "",
Mdp = "",
Role = "",
},
};
mockUserService.Setup(x => x.GetAllArticleUsers()).ReturnsAsync(expected);
var result = mockUserService.Object.GetAllArticleUsers();
Assert.Equal(expected, result.Result);
}
[Fact]
static void TestGetArticleUser()
{
var mockUserService = new Mock<IUserService>();
var expected = new List<Article>()
{
new Article()
{
Id = 1,
Title = "Test",
Description = "Test",
Author = "Test",
DatePublished = "Test",
LectureTime = 10
},
new Article()
{
Id = 2,
Title = "Test",
Description = "Test",
Author = "Test",
DatePublished = "Test",
LectureTime = 10
}
};
mockUserService.Setup(x => x.GetArticleUser("Tofgasy")).ReturnsAsync(expected);
var result = mockUserService.Object.GetArticleUser("Tofgasy");
Assert.Equal(expected, result.Result);
}
[Fact]
static void TestCreateArticleUser()
{
var mockUserService = new Mock<IUserService>();
var articleUser = new ArticleUserEntity()
{
ArticleEntityId = 1,
UserEntityPseudo = "Tofgasy"
};
mockUserService.Setup(x => x.CreateArticleUser(articleUser)).ReturnsAsync(true);
var result = mockUserService.Object.CreateArticleUser(articleUser);
Assert.True(result.Result);
}
[Fact]
static void TestDeleteArticleUser()
{
var mockUserService = new Mock<IUserService>();
mockUserService.Setup(x => x.DeleteArticleUser("Tofgasy", 1)).ReturnsAsync(true);
var result = mockUserService.Object.DeleteArticleUser("Tofgasy", 1);
Assert.True(result.Result);
}
[Fact]
static void TestUpdateArticleUser()
{
var mockUserService = new Mock<IUserService>();
var articleUser = new ArticleUserEntity()
{
ArticleEntityId = 1,
UserEntityPseudo = "Tofgasy"
};
mockUserService.Setup(x => x.UpdateArticleUser(articleUser)).ReturnsAsync(true);
var result = mockUserService.Object.UpdateArticleUser(articleUser);
Assert.True(result.Result);
}
}

@ -1,17 +1,21 @@
using Entities; using Entities;
using Microsoft.EntityFrameworkCore; using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Logging;
namespace DbContextLib; namespace DbContextLib;
public class LibraryContext : DbContext public class LibraryContext : DbContext
{ {
public LibraryContext() public LibraryContext()
: base() : base()
{ } {
}
public LibraryContext(DbContextOptions<LibraryContext> options) public LibraryContext(DbContextOptions<LibraryContext> options)
: base(options) : base(options)
{ } {
}
@ -19,8 +23,15 @@ public class LibraryContext : DbContext
public DbSet<UserEntity> UserSet { get; set; } public DbSet<UserEntity> UserSet { get; set; }
public DbSet<FormEntity> FormSet { get; set; } public DbSet<FormEntity> FormSet { get; set; }
public DbSet<ArticleUserEntity> ArticleUserSet { get; set; }
protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder) protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
{ {
optionsBuilder.LogTo(message =>
{
using var logFile = new StreamWriter("log.txt", append: true);
logFile.WriteLine(message);
}, LogLevel.Information);
if (!optionsBuilder.IsConfigured) if (!optionsBuilder.IsConfigured)
{ {
optionsBuilder.UseSqlite($"Data Source=Entity_FrameWork.Article.db"); optionsBuilder.UseSqlite($"Data Source=Entity_FrameWork.Article.db");
@ -39,13 +50,13 @@ public class LibraryContext : DbContext
modelBuilder.Entity<UserEntity>() modelBuilder.Entity<UserEntity>()
.HasMany(u => u.Forms) .HasMany(u => u.Forms)
.WithOne(f => f.User) .WithOne(f => f.User)
.HasForeignKey(f => f.UserEntityId); .HasForeignKey(f => f.UserEntityPseudo);
modelBuilder.Entity<FormEntity>() modelBuilder.Entity<FormEntity>()
.HasOne(f => f.User) .HasOne(f => f.User)
.WithMany(u => u.Forms) .WithMany(u => u.Forms)
.HasForeignKey(f => f.UserEntityId); .HasForeignKey(f => f.UserEntityPseudo);
/*
modelBuilder.Entity<ArticleEntity>().HasData( modelBuilder.Entity<ArticleEntity>().HasData(
new ArticleEntity new ArticleEntity
{ {
@ -81,16 +92,24 @@ public class LibraryContext : DbContext
modelBuilder.Entity<UserEntity>().HasData( modelBuilder.Entity<UserEntity>().HasData(
new UserEntity new UserEntity
{ {
Id = 1, Nom = "Fages", Prenom = "Tony", Pseudo = "TonyF", Mail = "tony@gmail.com", Mdp = "1234", Role = "Admin" Nom = "Fages", Prenom = "Tony", Pseudo = "TonyF", Mail = "tony@gmail.com", Mdp = "1234", Role = "Admin"
}, },
new UserEntity new UserEntity
{ {
Id = 2, Nom = "Smith", Prenom = "Tom", Pseudo = "TomS", Mail = "tom@mail.com", Mdp = "1234", Nom = "Smith", Prenom = "Tom", Pseudo = "TomS", Mail = "tom@mail.com", Mdp = "1234",
Role = "User" Role = "User"
}, },
new UserEntity new UserEntity
{ {
Id = 3, Nom = "M&M's", Prenom = "Red", Pseudo = "RedM", Mail = "M&M#mail.com", Mdp = "1234", Role = "Modérator" Nom = "M&M's", Prenom = "Red", Pseudo = "RedM", Mail = "M&M#mail.com", Mdp = "1234", Role = "Modérator"
},
new UserEntity
{
Nom = "Cascarra", Prenom = "Cascarra", Pseudo = "Sha", Mail = "ShaCasca@gmail.com", Mdp = "1234", Role = "Admin"
},
new UserEntity
{
Nom = "Sillard", Prenom = "Noa", Pseudo = "NoaSil", Mail = "", Mdp = "1234", Role = "Admin"
} }
); );
@ -98,27 +117,27 @@ public class LibraryContext : DbContext
new ArticleUserEntity new ArticleUserEntity
{ {
ArticleEntityId = 1, ArticleEntityId = 1,
UserEntityId = 1 UserEntityPseudo = "TonyF"
}, },
new ArticleUserEntity new ArticleUserEntity
{ {
ArticleEntityId = 2, ArticleEntityId = 2,
UserEntityId = 2 UserEntityPseudo = "NoaSil"
}, },
new ArticleUserEntity new ArticleUserEntity
{ {
ArticleEntityId = 3, ArticleEntityId = 3,
UserEntityId = 3 UserEntityPseudo = "Sha"
}, },
new ArticleUserEntity new ArticleUserEntity
{ {
ArticleEntityId = 3, ArticleEntityId = 3,
UserEntityId = 1 UserEntityPseudo = "RedM"
}, },
new ArticleUserEntity new ArticleUserEntity
{ {
ArticleEntityId = 2, ArticleEntityId = 2,
UserEntityId = 3 UserEntityPseudo = "TomS"
} }
); );
@ -126,27 +145,25 @@ public class LibraryContext : DbContext
new FormEntity new FormEntity
{ {
Id = 1, Id = 1,
Pseudo= "Form 1",
DatePublication = "Form 1 Description", DatePublication = "Form 1 Description",
Link = "hhtp://form1.com", Link = "hhtp://form1.com",
UserEntityId = 1 UserEntityPseudo = "Sha"
}, },
new FormEntity new FormEntity
{ {
Id = 2, Id = 2,
Pseudo= "Form 2",
DatePublication = "Form 2 Description", DatePublication = "Form 2 Description",
Link = "hhtp://form2.com", Link = "hhtp://form2.com",
UserEntityId = 2 UserEntityPseudo = "Sha"
}, },
new FormEntity new FormEntity
{ {
Id = 3, Id = 3,
Pseudo= "Form 3",
DatePublication = "Form 3 Description", DatePublication = "Form 3 Description",
Link = "hhtp://form3.com", Link = "hhtp://form3.com",
UserEntityId = 3 UserEntityPseudo = "Sha"
} }
); );
*/
} }
} }

@ -1,16 +1,16 @@
// <auto-generated /> // <auto-generated />
using DbContextLib;
using Microsoft.EntityFrameworkCore; using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.Infrastructure; using Microsoft.EntityFrameworkCore.Infrastructure;
using Microsoft.EntityFrameworkCore.Migrations; using Microsoft.EntityFrameworkCore.Migrations;
using Microsoft.EntityFrameworkCore.Storage.ValueConversion; using Microsoft.EntityFrameworkCore.Storage.ValueConversion;
using StubbedContextLib;
#nullable disable #nullable disable
namespace StubbedContextLib.Migrations namespace DbContextLib.Migrations
{ {
[DbContext(typeof(StubbedContext))] [DbContext(typeof(LibraryContext))]
[Migration("20240307182411_mrg1")] [Migration("20240312155559_mrg1")]
partial class mrg1 partial class mrg1
{ {
/// <inheritdoc /> /// <inheritdoc />
@ -83,40 +83,40 @@ namespace StubbedContextLib.Migrations
b.Property<long>("ArticleEntityId") b.Property<long>("ArticleEntityId")
.HasColumnType("INTEGER"); .HasColumnType("INTEGER");
b.Property<long>("UserEntityId") b.Property<string>("UserEntityPseudo")
.HasColumnType("INTEGER"); .HasColumnType("TEXT");
b.HasKey("ArticleEntityId", "UserEntityId"); b.HasKey("ArticleEntityId", "UserEntityPseudo");
b.HasIndex("UserEntityId"); b.HasIndex("UserEntityPseudo");
b.ToTable("ArticleUserEntity"); b.ToTable("ArticleUserSet");
b.HasData( b.HasData(
new new
{ {
ArticleEntityId = 1L, ArticleEntityId = 1L,
UserEntityId = 1L UserEntityPseudo = "TonyF"
}, },
new new
{ {
ArticleEntityId = 2L, ArticleEntityId = 2L,
UserEntityId = 2L UserEntityPseudo = "NoaSil"
}, },
new new
{ {
ArticleEntityId = 3L, ArticleEntityId = 3L,
UserEntityId = 3L UserEntityPseudo = "Sha"
}, },
new new
{ {
ArticleEntityId = 3L, ArticleEntityId = 3L,
UserEntityId = 1L UserEntityPseudo = "RedM"
}, },
new new
{ {
ArticleEntityId = 2L, ArticleEntityId = 2L,
UserEntityId = 3L UserEntityPseudo = "TomS"
}); });
}); });
@ -134,29 +134,51 @@ namespace StubbedContextLib.Migrations
.IsRequired() .IsRequired()
.HasColumnType("TEXT"); .HasColumnType("TEXT");
b.Property<string>("Pseudo") b.Property<string>("Theme")
.IsRequired() .IsRequired()
.HasColumnType("TEXT"); .HasColumnType("TEXT");
b.Property<string>("Theme") b.Property<string>("UserEntityPseudo")
.IsRequired() .IsRequired()
.HasColumnType("TEXT"); .HasColumnType("TEXT");
b.Property<long>("UserEntityId")
.HasColumnType("INTEGER");
b.HasKey("Id"); b.HasKey("Id");
b.HasIndex("UserEntityId"); b.HasIndex("UserEntityPseudo");
b.ToTable("FormSet"); b.ToTable("FormSet");
b.HasData(
new
{
Id = 1L,
DatePublication = "Form 1 Description",
Link = "hhtp://form1.com",
Theme = "",
UserEntityPseudo = "Sha"
},
new
{
Id = 2L,
DatePublication = "Form 2 Description",
Link = "hhtp://form2.com",
Theme = "",
UserEntityPseudo = "Sha"
},
new
{
Id = 3L,
DatePublication = "Form 3 Description",
Link = "hhtp://form3.com",
Theme = "",
UserEntityPseudo = "Sha"
});
}); });
modelBuilder.Entity("Entities.UserEntity", b => modelBuilder.Entity("Entities.UserEntity", b =>
{ {
b.Property<long>("Id") b.Property<string>("Pseudo")
.ValueGeneratedOnAdd() .HasColumnType("TEXT");
.HasColumnType("INTEGER");
b.Property<string>("Mail") b.Property<string>("Mail")
.IsRequired() .IsRequired()
@ -174,48 +196,59 @@ namespace StubbedContextLib.Migrations
.IsRequired() .IsRequired()
.HasColumnType("TEXT"); .HasColumnType("TEXT");
b.Property<string>("Pseudo")
.IsRequired()
.HasColumnType("TEXT");
b.Property<string>("Role") b.Property<string>("Role")
.IsRequired() .IsRequired()
.HasColumnType("TEXT"); .HasColumnType("TEXT");
b.HasKey("Id"); b.HasKey("Pseudo");
b.ToTable("UserSet"); b.ToTable("UserSet");
b.HasData( b.HasData(
new new
{ {
Id = 1L, Pseudo = "TonyF",
Mail = "tony@gmail.com", Mail = "tony@gmail.com",
Mdp = "1234", Mdp = "1234",
Nom = "Fages", Nom = "Fages",
Prenom = "Tony", Prenom = "Tony",
Pseudo = "TonyF",
Role = "Admin" Role = "Admin"
}, },
new new
{ {
Id = 2L, Pseudo = "TomS",
Mail = "tom@mail.com", Mail = "tom@mail.com",
Mdp = "1234", Mdp = "1234",
Nom = "Smith", Nom = "Smith",
Prenom = "Tom", Prenom = "Tom",
Pseudo = "TomS",
Role = "User" Role = "User"
}, },
new new
{ {
Id = 3L, Pseudo = "RedM",
Mail = "M&M#mail.com", Mail = "M&M#mail.com",
Mdp = "1234", Mdp = "1234",
Nom = "M&M's", Nom = "M&M's",
Prenom = "Red", Prenom = "Red",
Pseudo = "RedM",
Role = "Modérator" Role = "Modérator"
},
new
{
Pseudo = "Sha",
Mail = "ShaCasca@gmail.com",
Mdp = "1234",
Nom = "Cascarra",
Prenom = "Cascarra",
Role = "Admin"
},
new
{
Pseudo = "NoaSil",
Mail = "",
Mdp = "1234",
Nom = "Sillard",
Prenom = "Noa",
Role = "Admin"
}); });
}); });
@ -229,7 +262,7 @@ namespace StubbedContextLib.Migrations
b.HasOne("Entities.UserEntity", null) b.HasOne("Entities.UserEntity", null)
.WithMany() .WithMany()
.HasForeignKey("UserEntityId") .HasForeignKey("UserEntityPseudo")
.OnDelete(DeleteBehavior.Cascade) .OnDelete(DeleteBehavior.Cascade)
.IsRequired(); .IsRequired();
}); });
@ -238,7 +271,7 @@ namespace StubbedContextLib.Migrations
{ {
b.HasOne("Entities.UserEntity", "User") b.HasOne("Entities.UserEntity", "User")
.WithMany("Forms") .WithMany("Forms")
.HasForeignKey("UserEntityId") .HasForeignKey("UserEntityPseudo")
.OnDelete(DeleteBehavior.Cascade) .OnDelete(DeleteBehavior.Cascade)
.IsRequired(); .IsRequired();

@ -4,7 +4,7 @@
#pragma warning disable CA1814 // Prefer jagged arrays over multidimensional #pragma warning disable CA1814 // Prefer jagged arrays over multidimensional
namespace StubbedContextLib.Migrations namespace DbContextLib.Migrations
{ {
/// <inheritdoc /> /// <inheritdoc />
public partial class mrg1 : Migration public partial class mrg1 : Migration
@ -33,8 +33,6 @@ namespace StubbedContextLib.Migrations
name: "UserSet", name: "UserSet",
columns: table => new columns: table => new
{ {
Id = table.Column<long>(type: "INTEGER", nullable: false)
.Annotation("Sqlite:Autoincrement", true),
Pseudo = table.Column<string>(type: "TEXT", nullable: false), Pseudo = table.Column<string>(type: "TEXT", nullable: false),
Mdp = table.Column<string>(type: "TEXT", nullable: false), Mdp = table.Column<string>(type: "TEXT", nullable: false),
Nom = table.Column<string>(type: "TEXT", nullable: false), Nom = table.Column<string>(type: "TEXT", nullable: false),
@ -44,30 +42,30 @@ namespace StubbedContextLib.Migrations
}, },
constraints: table => constraints: table =>
{ {
table.PrimaryKey("PK_UserSet", x => x.Id); table.PrimaryKey("PK_UserSet", x => x.Pseudo);
}); });
migrationBuilder.CreateTable( migrationBuilder.CreateTable(
name: "ArticleUserEntity", name: "ArticleUserSet",
columns: table => new columns: table => new
{ {
UserEntityId = table.Column<long>(type: "INTEGER", nullable: false), UserEntityPseudo = table.Column<string>(type: "TEXT", nullable: false),
ArticleEntityId = table.Column<long>(type: "INTEGER", nullable: false) ArticleEntityId = table.Column<long>(type: "INTEGER", nullable: false)
}, },
constraints: table => constraints: table =>
{ {
table.PrimaryKey("PK_ArticleUserEntity", x => new { x.ArticleEntityId, x.UserEntityId }); table.PrimaryKey("PK_ArticleUserSet", x => new { x.ArticleEntityId, x.UserEntityPseudo });
table.ForeignKey( table.ForeignKey(
name: "FK_ArticleUserEntity_ArticleSet_ArticleEntityId", name: "FK_ArticleUserSet_ArticleSet_ArticleEntityId",
column: x => x.ArticleEntityId, column: x => x.ArticleEntityId,
principalTable: "ArticleSet", principalTable: "ArticleSet",
principalColumn: "Id", principalColumn: "Id",
onDelete: ReferentialAction.Cascade); onDelete: ReferentialAction.Cascade);
table.ForeignKey( table.ForeignKey(
name: "FK_ArticleUserEntity_UserSet_UserEntityId", name: "FK_ArticleUserSet_UserSet_UserEntityPseudo",
column: x => x.UserEntityId, column: x => x.UserEntityPseudo,
principalTable: "UserSet", principalTable: "UserSet",
principalColumn: "Id", principalColumn: "Pseudo",
onDelete: ReferentialAction.Cascade); onDelete: ReferentialAction.Cascade);
}); });
@ -80,17 +78,16 @@ namespace StubbedContextLib.Migrations
Theme = table.Column<string>(type: "TEXT", nullable: false), Theme = table.Column<string>(type: "TEXT", nullable: false),
DatePublication = table.Column<string>(type: "TEXT", nullable: false), DatePublication = table.Column<string>(type: "TEXT", nullable: false),
Link = table.Column<string>(type: "TEXT", nullable: false), Link = table.Column<string>(type: "TEXT", nullable: false),
Pseudo = table.Column<string>(type: "TEXT", nullable: false), UserEntityPseudo = table.Column<string>(type: "TEXT", nullable: false)
UserEntityId = table.Column<long>(type: "INTEGER", nullable: false)
}, },
constraints: table => constraints: table =>
{ {
table.PrimaryKey("PK_FormSet", x => x.Id); table.PrimaryKey("PK_FormSet", x => x.Id);
table.ForeignKey( table.ForeignKey(
name: "FK_FormSet_UserSet_UserEntityId", name: "FK_FormSet_UserSet_UserEntityPseudo",
column: x => x.UserEntityId, column: x => x.UserEntityPseudo,
principalTable: "UserSet", principalTable: "UserSet",
principalColumn: "Id", principalColumn: "Pseudo",
onDelete: ReferentialAction.Cascade); onDelete: ReferentialAction.Cascade);
}); });
@ -106,42 +103,54 @@ namespace StubbedContextLib.Migrations
migrationBuilder.InsertData( migrationBuilder.InsertData(
table: "UserSet", table: "UserSet",
columns: new[] { "Id", "Mail", "Mdp", "Nom", "Prenom", "Pseudo", "Role" }, columns: new[] { "Pseudo", "Mail", "Mdp", "Nom", "Prenom", "Role" },
values: new object[,] values: new object[,]
{ {
{ 1L, "tony@gmail.com", "1234", "Fages", "Tony", "TonyF", "Admin" }, { "NoaSil", "", "1234", "Sillard", "Noa", "Admin" },
{ 2L, "tom@mail.com", "1234", "Smith", "Tom", "TomS", "User" }, { "RedM", "M&M#mail.com", "1234", "M&M's", "Red", "Modérator" },
{ 3L, "M&M#mail.com", "1234", "M&M's", "Red", "RedM", "Modérator" } { "Sha", "ShaCasca@gmail.com", "1234", "Cascarra", "Cascarra", "Admin" },
{ "TomS", "tom@mail.com", "1234", "Smith", "Tom", "User" },
{ "TonyF", "tony@gmail.com", "1234", "Fages", "Tony", "Admin" }
}); });
migrationBuilder.InsertData( migrationBuilder.InsertData(
table: "ArticleUserEntity", table: "ArticleUserSet",
columns: new[] { "ArticleEntityId", "UserEntityId" }, columns: new[] { "ArticleEntityId", "UserEntityPseudo" },
values: new object[,]
{
{ 1L, "TonyF" },
{ 2L, "NoaSil" },
{ 2L, "TomS" },
{ 3L, "RedM" },
{ 3L, "Sha" }
});
migrationBuilder.InsertData(
table: "FormSet",
columns: new[] { "Id", "DatePublication", "Link", "Theme", "UserEntityPseudo" },
values: new object[,] values: new object[,]
{ {
{ 1L, 1L }, { 1L, "Form 1 Description", "hhtp://form1.com", "", "Sha" },
{ 2L, 2L }, { 2L, "Form 2 Description", "hhtp://form2.com", "", "Sha" },
{ 2L, 3L }, { 3L, "Form 3 Description", "hhtp://form3.com", "", "Sha" }
{ 3L, 1L },
{ 3L, 3L }
}); });
migrationBuilder.CreateIndex( migrationBuilder.CreateIndex(
name: "IX_ArticleUserEntity_UserEntityId", name: "IX_ArticleUserSet_UserEntityPseudo",
table: "ArticleUserEntity", table: "ArticleUserSet",
column: "UserEntityId"); column: "UserEntityPseudo");
migrationBuilder.CreateIndex( migrationBuilder.CreateIndex(
name: "IX_FormSet_UserEntityId", name: "IX_FormSet_UserEntityPseudo",
table: "FormSet", table: "FormSet",
column: "UserEntityId"); column: "UserEntityPseudo");
} }
/// <inheritdoc /> /// <inheritdoc />
protected override void Down(MigrationBuilder migrationBuilder) protected override void Down(MigrationBuilder migrationBuilder)
{ {
migrationBuilder.DropTable( migrationBuilder.DropTable(
name: "ArticleUserEntity"); name: "ArticleUserSet");
migrationBuilder.DropTable( migrationBuilder.DropTable(
name: "FormSet"); name: "FormSet");

@ -1,15 +1,15 @@
// <auto-generated /> // <auto-generated />
using DbContextLib;
using Microsoft.EntityFrameworkCore; using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.Infrastructure; using Microsoft.EntityFrameworkCore.Infrastructure;
using Microsoft.EntityFrameworkCore.Storage.ValueConversion; using Microsoft.EntityFrameworkCore.Storage.ValueConversion;
using StubbedContextLib;
#nullable disable #nullable disable
namespace StubbedContextLib.Migrations namespace DbContextLib.Migrations
{ {
[DbContext(typeof(StubbedContext))] [DbContext(typeof(LibraryContext))]
partial class StubbedContextModelSnapshot : ModelSnapshot partial class LibraryContextModelSnapshot : ModelSnapshot
{ {
protected override void BuildModel(ModelBuilder modelBuilder) protected override void BuildModel(ModelBuilder modelBuilder)
{ {
@ -80,40 +80,40 @@ namespace StubbedContextLib.Migrations
b.Property<long>("ArticleEntityId") b.Property<long>("ArticleEntityId")
.HasColumnType("INTEGER"); .HasColumnType("INTEGER");
b.Property<long>("UserEntityId") b.Property<string>("UserEntityPseudo")
.HasColumnType("INTEGER"); .HasColumnType("TEXT");
b.HasKey("ArticleEntityId", "UserEntityId"); b.HasKey("ArticleEntityId", "UserEntityPseudo");
b.HasIndex("UserEntityId"); b.HasIndex("UserEntityPseudo");
b.ToTable("ArticleUserEntity"); b.ToTable("ArticleUserSet");
b.HasData( b.HasData(
new new
{ {
ArticleEntityId = 1L, ArticleEntityId = 1L,
UserEntityId = 1L UserEntityPseudo = "TonyF"
}, },
new new
{ {
ArticleEntityId = 2L, ArticleEntityId = 2L,
UserEntityId = 2L UserEntityPseudo = "NoaSil"
}, },
new new
{ {
ArticleEntityId = 3L, ArticleEntityId = 3L,
UserEntityId = 3L UserEntityPseudo = "Sha"
}, },
new new
{ {
ArticleEntityId = 3L, ArticleEntityId = 3L,
UserEntityId = 1L UserEntityPseudo = "RedM"
}, },
new new
{ {
ArticleEntityId = 2L, ArticleEntityId = 2L,
UserEntityId = 3L UserEntityPseudo = "TomS"
}); });
}); });
@ -131,29 +131,51 @@ namespace StubbedContextLib.Migrations
.IsRequired() .IsRequired()
.HasColumnType("TEXT"); .HasColumnType("TEXT");
b.Property<string>("Pseudo") b.Property<string>("Theme")
.IsRequired() .IsRequired()
.HasColumnType("TEXT"); .HasColumnType("TEXT");
b.Property<string>("Theme") b.Property<string>("UserEntityPseudo")
.IsRequired() .IsRequired()
.HasColumnType("TEXT"); .HasColumnType("TEXT");
b.Property<long>("UserEntityId")
.HasColumnType("INTEGER");
b.HasKey("Id"); b.HasKey("Id");
b.HasIndex("UserEntityId"); b.HasIndex("UserEntityPseudo");
b.ToTable("FormSet"); b.ToTable("FormSet");
b.HasData(
new
{
Id = 1L,
DatePublication = "Form 1 Description",
Link = "hhtp://form1.com",
Theme = "",
UserEntityPseudo = "Sha"
},
new
{
Id = 2L,
DatePublication = "Form 2 Description",
Link = "hhtp://form2.com",
Theme = "",
UserEntityPseudo = "Sha"
},
new
{
Id = 3L,
DatePublication = "Form 3 Description",
Link = "hhtp://form3.com",
Theme = "",
UserEntityPseudo = "Sha"
});
}); });
modelBuilder.Entity("Entities.UserEntity", b => modelBuilder.Entity("Entities.UserEntity", b =>
{ {
b.Property<long>("Id") b.Property<string>("Pseudo")
.ValueGeneratedOnAdd() .HasColumnType("TEXT");
.HasColumnType("INTEGER");
b.Property<string>("Mail") b.Property<string>("Mail")
.IsRequired() .IsRequired()
@ -171,48 +193,59 @@ namespace StubbedContextLib.Migrations
.IsRequired() .IsRequired()
.HasColumnType("TEXT"); .HasColumnType("TEXT");
b.Property<string>("Pseudo")
.IsRequired()
.HasColumnType("TEXT");
b.Property<string>("Role") b.Property<string>("Role")
.IsRequired() .IsRequired()
.HasColumnType("TEXT"); .HasColumnType("TEXT");
b.HasKey("Id"); b.HasKey("Pseudo");
b.ToTable("UserSet"); b.ToTable("UserSet");
b.HasData( b.HasData(
new new
{ {
Id = 1L, Pseudo = "TonyF",
Mail = "tony@gmail.com", Mail = "tony@gmail.com",
Mdp = "1234", Mdp = "1234",
Nom = "Fages", Nom = "Fages",
Prenom = "Tony", Prenom = "Tony",
Pseudo = "TonyF",
Role = "Admin" Role = "Admin"
}, },
new new
{ {
Id = 2L, Pseudo = "TomS",
Mail = "tom@mail.com", Mail = "tom@mail.com",
Mdp = "1234", Mdp = "1234",
Nom = "Smith", Nom = "Smith",
Prenom = "Tom", Prenom = "Tom",
Pseudo = "TomS",
Role = "User" Role = "User"
}, },
new new
{ {
Id = 3L, Pseudo = "RedM",
Mail = "M&M#mail.com", Mail = "M&M#mail.com",
Mdp = "1234", Mdp = "1234",
Nom = "M&M's", Nom = "M&M's",
Prenom = "Red", Prenom = "Red",
Pseudo = "RedM",
Role = "Modérator" Role = "Modérator"
},
new
{
Pseudo = "Sha",
Mail = "ShaCasca@gmail.com",
Mdp = "1234",
Nom = "Cascarra",
Prenom = "Cascarra",
Role = "Admin"
},
new
{
Pseudo = "NoaSil",
Mail = "",
Mdp = "1234",
Nom = "Sillard",
Prenom = "Noa",
Role = "Admin"
}); });
}); });
@ -226,7 +259,7 @@ namespace StubbedContextLib.Migrations
b.HasOne("Entities.UserEntity", null) b.HasOne("Entities.UserEntity", null)
.WithMany() .WithMany()
.HasForeignKey("UserEntityId") .HasForeignKey("UserEntityPseudo")
.OnDelete(DeleteBehavior.Cascade) .OnDelete(DeleteBehavior.Cascade)
.IsRequired(); .IsRequired();
}); });
@ -235,7 +268,7 @@ namespace StubbedContextLib.Migrations
{ {
b.HasOne("Entities.UserEntity", "User") b.HasOne("Entities.UserEntity", "User")
.WithMany("Forms") .WithMany("Forms")
.HasForeignKey("UserEntityId") .HasForeignKey("UserEntityPseudo")
.OnDelete(DeleteBehavior.Cascade) .OnDelete(DeleteBehavior.Cascade)
.IsRequired(); .IsRequired();

@ -1,7 +1,10 @@
using System.ComponentModel.DataAnnotations;
namespace Entities; namespace Entities;
public class ArticleEntity public class ArticleEntity
{ {
[Key]
public long Id { get; set; } public long Id { get; set; }
public string Title { get; set; } = string.Empty; public string Title { get; set; } = string.Empty;
public string Description { get; set; } = string.Empty; public string Description { get; set; } = string.Empty;

@ -2,6 +2,6 @@ namespace Entities;
public class ArticleUserEntity public class ArticleUserEntity
{ {
public long UserEntityId { get; set; } public string UserEntityPseudo { get; set; }
public long ArticleEntityId { get; set; } public long ArticleEntityId { get; set; }
} }

@ -1,16 +1,16 @@
using System.ComponentModel.DataAnnotations;
namespace Entities; namespace Entities;
public class FormEntity public class FormEntity
{ {
[Key]
public long Id { get; set; } public long Id { get; set; }
public string Theme { get; set; } = string.Empty; public string Theme { get; set; } = string.Empty;
public string DatePublication { get; set; } = string.Empty; public string DatePublication { get; set; } = string.Empty;
public string Link { get; set; } = string.Empty; public string Link { get; set; } = string.Empty;
public string Pseudo { get; set; } = string.Empty;
public long UserEntityId { get; set; }
public UserEntity User { get; set; } = null;
public string UserEntityPseudo{ get; set; }
public UserEntity User { get; set; } = null!;
} }

@ -1,8 +1,10 @@
using System.ComponentModel.DataAnnotations;
namespace Entities; namespace Entities;
public class UserEntity public class UserEntity
{ {
public long Id { get; set; } [Key]
public string Pseudo { get; set; } = string.Empty; public string Pseudo { get; set; } = string.Empty;
public string Mdp { get; set; } = string.Empty; public string Mdp { get; set; } = string.Empty;

@ -2,7 +2,7 @@ namespace Model;
public class Article public class Article
{ {
public long Id { get; set; } public long Id;
public string Title { get; set; } = string.Empty; public string Title { get; set; } = string.Empty;
public string Description { get; set; } = string.Empty; public string Description { get; set; } = string.Empty;
public string DatePublished { get; set; } = string.Empty; public string DatePublished { get; set; } = string.Empty;

@ -0,0 +1,6 @@
namespace Model;
public enum ArticleOrderCriteria
{
None, ByTitle, ByAuthor, ByLectureTime, ByDatePublished, ByDescription
}

@ -0,0 +1,6 @@
namespace Model;
public enum FormOrderCriteria
{
None, ByTheme, ByDate, ByPseudo, ByLien
}

@ -6,5 +6,5 @@ public class Formulaire
public string Theme { get; set; } public string Theme { get; set; }
public string Date { get; set; } public string Date { get; set; }
public string Lien { get; set; } public string Lien { get; set; }
public string Pseudo { get; set; } public string UserPseudo { get; set; }
} }

@ -0,0 +1,6 @@
namespace Model;
public enum UserOrderCriteria
{
None, ByFirstName, ByLastName
}

@ -45,16 +45,16 @@ public class StubbedContext : LibraryContext
modelBuilder.Entity<UserEntity>().HasData( modelBuilder.Entity<UserEntity>().HasData(
new UserEntity new UserEntity
{ {
Id = 1, Nom = "Fages", Prenom = "Tony", Pseudo = "TonyF", Mail = "tony@gmail.com", Mdp = "1234", Role = "Admin" Nom = "Fages", Prenom = "Tony", Pseudo = "TonyF", Mail = "tony@gmail.com", Mdp = "1234", Role = "Admin"
}, },
new UserEntity new UserEntity
{ {
Id = 2, Nom = "Smith", Prenom = "Tom", Pseudo = "TomS", Mail = "tom@mail.com", Mdp = "1234", Nom = "Smith", Prenom = "Tom", Pseudo = "TomS", Mail = "tom@mail.com", Mdp = "1234",
Role = "User" Role = "User"
}, },
new UserEntity new UserEntity
{ {
Id = 3, Nom = "M&M's", Prenom = "Red", Pseudo = "RedM", Mail = "M&M#mail.com", Mdp = "1234", Role = "Modérator" Nom = "M&M's", Prenom = "Red", Pseudo = "RedM", Mail = "M&M#mail.com", Mdp = "1234", Role = "Modérator"
} }
); );
@ -62,27 +62,27 @@ public class StubbedContext : LibraryContext
new ArticleUserEntity new ArticleUserEntity
{ {
ArticleEntityId = 1, ArticleEntityId = 1,
UserEntityId = 1 UserEntityPseudo = "Sha"
}, },
new ArticleUserEntity new ArticleUserEntity
{ {
ArticleEntityId = 2, ArticleEntityId = 2,
UserEntityId = 2 UserEntityPseudo = "Sha"
}, },
new ArticleUserEntity new ArticleUserEntity
{ {
ArticleEntityId = 3, ArticleEntityId = 3,
UserEntityId = 3 UserEntityPseudo = "Sha"
}, },
new ArticleUserEntity new ArticleUserEntity
{ {
ArticleEntityId = 3, ArticleEntityId = 3,
UserEntityId = 1 UserEntityPseudo = "Sha"
}, },
new ArticleUserEntity new ArticleUserEntity
{ {
ArticleEntityId = 2, ArticleEntityId = 2,
UserEntityId = 3 UserEntityPseudo = "Sha"
} }
); );
} }

@ -1,26 +0,0 @@
using Entities;
using Model;
namespace StubbedContextLib;
public class StubTest
{
private List<Article> _article;
public List<Article> StubArticle()
{
_article = new List<Article>
{
new Article
{
Id = 1,
Title = "Test",
Description = "Test",
Author = "Test",
DatePublished = "Test",
LectureTime = 1
}
};
return _article;
}
}

@ -1,83 +0,0 @@
// See https://aka.ms/new-console-template for more information
using DbContextLib;
using Entities;
addArticle();
listArticle();
// Allows to list all the articles from the db
void listArticle()
{
using (var context = new LibraryContext())
{
var articles = context.ArticleSet;
foreach (var article in articles)
{
Console.WriteLine($"{article.Author} - {article.Title} - {article.Description} - {article.DatePublished} - {article.LectureTime}");
}
}
}
// Allows to list all the articles from the db by author
void listArticleByAuthor()
{
using (var context = new LibraryContext())
{
var articles = context.ArticleSet.Where(a => a.Author.Equals("Tony Fages"));
foreach (var article in articles)
{
Console.WriteLine($"{article.Author} - {article.Title} - {article.Description} - {article.DatePublished} - {article.LectureTime}");
}
}
}
// Allows to add an article to the db
void addArticle()
{
using (var context = new LibraryContext())
{
var article = new ArticleEntity
{
Title = "Louis is not sick anymore",
Description = "Louis is not sick anymore, he is now healthy and happy",
DatePublished = "16-02-2024",
LectureTime = 1,
Author = "Tony Fages"
};
context.ArticleSet.Add(article);
context.SaveChanges();
}
}
// Allows to modify an article from the db
void modifyArticle()
{
using (var context = new LibraryContext())
{
var article = context.ArticleSet.Where(a => a.Author.Equals("Tom Smith"));
foreach (var articles in article)
{
articles.Title = "Demain des l'aube";
context.SaveChanges();
}
}
}
// Allows to delete an article from the db
void deleteArticle()
{
using (var context = new LibraryContext())
{
var article = context.ArticleSet.Where(a => a.Author.Equals("M&M's Red"));
foreach (var articles in article)
{
context.ArticleSet.Remove(articles);
context.SaveChanges();
}
}
}

@ -0,0 +1,303 @@
// See https://aka.ms/new-console-template for more information
using DbContextLib;
using Entities;
//Article
//addArticle();
listArticle();
//modifyArticle();
//deleteArticle();
//listArticleByAuthor();
//Form
//addForm();
listForms();
//updateForm();
//deleteForm();
//User
//listUser();
//addUser();
//updateUser();
//deleteUser();
//ArticleUser
//listArticleUser();
//addArticleUser();
//updateArticleUser();
//deleteArticleUser();
//FormUser
listFormUser();
//addFormUser();
// Allows to list all the articles from the db
void listArticle()
{
using (var context = new LibraryContext())
{
var articles = context.ArticleSet;
foreach (var article in articles)
{
Console.WriteLine($"{article.Author} - {article.Title} - {article.Description} - {article.DatePublished} - {article.LectureTime}");
}
}
}
// Allows to list all the articles from the db by author
void listArticleByAuthor()
{
using (var context = new LibraryContext())
{
var articles = context.ArticleSet.Where(a => a.Author.Equals("Tony Fages"));
foreach (var article in articles)
{
Console.WriteLine($"{article.Author} - {article.Title} - {article.Description} - {article.DatePublished} - {article.LectureTime}");
}
}
}
// Allows to add an article to the db
void addArticle()
{
using (var context = new LibraryContext())
{
var article = new ArticleEntity
{
Title = "Louis is not sick anymore",
Description = "Louis is not sick anymore, he is now healthy and happy",
DatePublished = "16-02-2024",
LectureTime = 1,
Author = "Tony Fages"
};
context.ArticleSet.Add(article);
context.SaveChanges();
}
}
// Allows to modify an article from the db
void modifyArticle()
{
using (var context = new LibraryContext())
{
var article = context.ArticleSet.Where(a => a.Author.Equals("Tom Smith"));
foreach (var articles in article)
{
articles.Title = "Demain des l'aube";
context.SaveChanges();
}
}
}
// Allows to delete an article from the db
void deleteArticle()
{
using (var context = new LibraryContext())
{
var article = context.ArticleSet.Where(a => a.Author.Equals("M&M's Red"));
foreach (var articles in article)
{
context.ArticleSet.Remove(articles);
context.SaveChanges();
}
}
}
// Allow to get all forms
void listForms()
{
using (var context = new LibraryContext())
{
var forms = context.FormSet;
foreach (var form in forms)
{
Console.WriteLine($"{form.Id} - {form.Link} - {form.DatePublication} - {form.Theme} - {form.UserEntityPseudo}");
}
}
}
void addForm()
{
using (var context = new LibraryContext())
{
var form = new FormEntity
{
Id = 5,
Theme = "Covid",
DatePublication = "16-02-2024",
Link = "https://www.covid.com",
UserEntityPseudo = "Sha"
};
context.FormSet.Add(form);
context.SaveChanges();
}
}
void updateForm()
{
using (var context = new LibraryContext())
{
var form = context.FormSet.Where(f => f.Id.Equals(5));
foreach (var forms in form)
{
forms.Theme = "Demain des l'aube";
context.SaveChanges();
}
}
}
void deleteForm()
{
using (var context = new LibraryContext())
{
var form = context.FormSet.Where(f => f.Id.Equals(5));
foreach (var forms in form)
{
context.FormSet.Remove(forms);
context.SaveChanges();
}
}
}
void listUser()
{
using (var context = new LibraryContext())
{
var users = context.UserSet;
foreach (var user in users)
{
Console.WriteLine($" {user.Pseudo} - {user.Nom} - {user.Prenom} - {user.Mail} - {user.Role}");
}
}
}
void addUser()
{
using (var context = new LibraryContext())
{
var user = new UserEntity
{
Nom = "Fages", Prenom = "Tony", Pseudo = "TonyF", Mail = "tony@gmail.com", Mdp = "1234", Role = "Admin"
};
context.UserSet.Add(user);
context.SaveChanges();
}
listUser();
}
void updateUser()
{
using (var context = new LibraryContext())
{
var user = context.UserSet.Where(u => u.Pseudo.Equals("Sha"));
foreach (var users in user)
{
users.Nom = "Thomas";
context.SaveChanges();
}
}
listUser();
}
void deleteUser()
{
using (var context = new LibraryContext())
{
var user = context.UserSet.Where(u => u.Pseudo.Equals("Sha"));
foreach (var users in user)
{
context.UserSet.Remove(users);
context.SaveChanges();
}
}
listUser();
}
void listArticleUser()
{
using (var context = new LibraryContext())
{
var articleUsers = context.ArticleUserSet;
foreach (var articleUser in articleUsers)
{
Console.WriteLine($"{articleUser.ArticleEntityId} - {articleUser.UserEntityPseudo}");
}
}
}
void addArticleUser()
{
using (var context = new LibraryContext())
{
var articleUser = new ArticleUserEntity
{
ArticleEntityId = 2,
UserEntityPseudo = "Sha"
};
context.ArticleUserSet.Add(articleUser);
context.SaveChanges();
}
listArticleUser();
}
void updateArticleUser()
{
using (var context = new LibraryContext())
{
var articleUser = context.ArticleUserSet.FirstOrDefault(au => au.UserEntityPseudo.Equals("Sha"));
if (articleUser != null) articleUser.UserEntityPseudo = "Sha";
context.SaveChanges();
}
listArticleUser();
}
void deleteArticleUser()
{
using (var context = new LibraryContext())
{
var articleUser = context.ArticleUserSet.Where(au => au.UserEntityPseudo.Equals(1)).Where(u => u.ArticleEntityId.Equals(1));
foreach (var articleUsers in articleUser)
{
context.ArticleUserSet.Remove(articleUsers);
context.SaveChanges();
}
}
listArticleUser();
}
void listFormUser()
{
using (var context = new LibraryContext())
{
var formUsers = context.FormSet.Where(u => u.UserEntityPseudo.Equals(1));
foreach (var formUser in formUsers)
{
Console.WriteLine($"{formUser.UserEntityPseudo} - {formUser.Theme} - {formUser.Link}");
}
}
}
void addFormUser()
{
using (var context = new LibraryContext())
{
var formUser = new FormEntity
{
UserEntityPseudo = "Sha",
};
context.FormSet.Add(formUser);
context.SaveChanges();
}
}

@ -1,35 +0,0 @@
using System.Reflection;
using System.Runtime.InteropServices;
// General Information about an assembly is controlled through the following
// set of attributes. Change these attribute values to modify the information
// associated with an assembly.
[assembly: AssemblyTitle("TestsUnitaires")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("TestsUnitaires")]
[assembly: AssemblyCopyright("Copyright © 2024")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
// Setting ComVisible to false makes the types in this assembly not visible
// to COM components. If you need to access a type in this assembly from
// COM, set the ComVisible attribute to true on that type.
[assembly: ComVisible(false)]
// The following GUID is for the ID of the typelib if this project is exposed to COM
[assembly: Guid("FF8AFA55-12FE-4856-A0A1-21344D366E12")]
// Version information for an assembly consists of the following four values:
//
// Major Version
// Minor Version
// Build Number
// Revision
//
// You can specify all the values or you can default the Build and Revision Numbers
// by using the '*' as shown below:
// [assembly: AssemblyVersion("1.0.*")]
[assembly: AssemblyVersion("1.0.0.0")]
[assembly: AssemblyFileVersion("1.0.0.0")]

@ -1,14 +0,0 @@
using System;
using Xunit;
namespace TestsUnitaires
{
public class Tests
{
[Fact]
public void Test1()
{
Assert.True(true);
}
}
}

@ -1,66 +0,0 @@
<?xml version="1.0" encoding="utf-8"?>
<Project ToolsVersion="4.0" DefaultTargets="Build" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
<Import Project="$(MSBuildExtensionsPath)\$(MSBuildToolsVersion)\Microsoft.Common.props"
Condition="Exists('$(MSBuildExtensionsPath)\$(MSBuildToolsVersion)\Microsoft.Common.props')"/>
<PropertyGroup>
<Configuration Condition=" '$(Configuration)' == '' ">Debug</Configuration>
<Platform Condition=" '$(Platform)' == '' ">AnyCPU</Platform>
<ProjectGuid>{FF8AFA55-12FE-4856-A0A1-21344D366E12}</ProjectGuid>
<ProjectTypeGuids>{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}</ProjectTypeGuids>
<OutputType>Library</OutputType>
<AppDesignerFolder>Properties</AppDesignerFolder>
<RootNamespace>TestsUnitaires</RootNamespace>
<AssemblyName>TestsUnitaires</AssemblyName>
<TargetFrameworkVersion>v4.8</TargetFrameworkVersion>
<FileAlignment>512</FileAlignment>
</PropertyGroup>
<PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Debug|AnyCPU' ">
<PlatformTarget>AnyCPU</PlatformTarget>
<DebugSymbols>true</DebugSymbols>
<DebugType>full</DebugType>
<Optimize>false</Optimize>
<OutputPath>bin\Debug\</OutputPath>
<DefineConstants>DEBUG;TRACE</DefineConstants>
<ErrorReport>prompt</ErrorReport>
<WarningLevel>4</WarningLevel>
</PropertyGroup>
<PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Release|AnyCPU' ">
<PlatformTarget>AnyCPU</PlatformTarget>
<DebugType>pdbonly</DebugType>
<Optimize>true</Optimize>
<OutputPath>bin\Release\</OutputPath>
<DefineConstants>TRACE</DefineConstants>
<ErrorReport>prompt</ErrorReport>
<WarningLevel>4</WarningLevel>
</PropertyGroup>
<ItemGroup>
<Reference Include="System"/>
<Reference Include="System.Core"/>
<Reference Include="System.Data"/>
<Reference Include="System.Xml"/>
<Reference Include="xunit.abstractions, Version=2.0.0.0, Culture=neutral, PublicKeyToken=8d05b1bb7a6fdb6c">
<HintPath>..\packages\xunit.abstractions.2.0.0\lib\net35\xunit.abstractions.dll</HintPath>
</Reference>
<Reference Include="xunit.assert, Version=2.1.0.3179, Culture=neutral, PublicKeyToken=8d05b1bb7a6fdb6c">
<HintPath>..\packages\xunit.assert.2.1.0\lib\dotnet\xunit.assert.dll</HintPath>
</Reference>
<Reference Include="xunit.core, Version=2.1.0.3179, Culture=neutral, PublicKeyToken=8d05b1bb7a6fdb6c">
<HintPath>..\packages\xunit.extensibility.core.2.1.0\lib\dotnet\xunit.core.dll</HintPath>
</Reference>
<Reference Include="xunit.execution.desktop, Version=2.1.0.3179, Culture=neutral, PublicKeyToken=8d05b1bb7a6fdb6c">
<HintPath>..\packages\xunit.extensibility.execution.2.1.0\lib\net45\xunit.execution.desktop.dll</HintPath>
</Reference>
</ItemGroup>
<ItemGroup>
<Compile Include="Tests.cs"/>
<Compile Include="Properties\AssemblyInfo.cs"/>
</ItemGroup>
<Import Project="$(MSBuildToolsPath)\Microsoft.CSharp.targets"/>
<!-- To modify your build process, add your task inside one of the targets below and uncomment it.
Other similar extension points exist, see Microsoft.Common.targets.
<Target Name="BeforeBuild">
</Target>
<Target Name="AfterBuild">
</Target>
-->
</Project>

@ -1,9 +0,0 @@
<?xml version="1.0" encoding="utf-8"?>
<packages>
<package id="xunit" version="2.1.0" targetFramework="net45" />
<package id="xunit.abstractions" version="2.0.0" targetFramework="net45" />
<package id="xunit.assert" version="2.1.0" targetFramework="net45" />
<package id="xunit.core" version="2.1.0" targetFramework="net45" />
<package id="xunit.extensibility.core" version="2.1.0" targetFramework="net45" />
<package id="xunit.extensibility.execution" version="2.1.0" targetFramework="net45" />
</packages>

@ -0,0 +1,102 @@
using DbContextLib;
using Entities;
using Microsoft.Data.Sqlite;
using Microsoft.EntityFrameworkCore;
namespace TestsUnitaires;
public class TestsArticleEntity
{
[Fact]
public void Add_Test()
{
var connection = new SqliteConnection("DataSource=:memory:");
connection.Open();
var options = new DbContextOptionsBuilder<LibraryContext>()
.UseSqlite(connection)
.Options;
using (var context = new LibraryContext(options))
{
context.Database.EnsureCreated();
ArticleEntity a1 = new ArticleEntity { Title = "Breaking News Elisabeth 2 Died", Description = "The queen of England died today at the age of 95", DatePublished = "2022-02-06", LectureTime = 2, Author = "Tom Smith" };
ArticleEntity a2 = new ArticleEntity { Title = "The new iPhone 15", Description = "The new iPhone 15 is out and it's the best phone ever", DatePublished = "2022-02-06", LectureTime = 3, Author = "Tom Smith" };
ArticleEntity a3 = new ArticleEntity { Title = "M&M's new recipe", Description = "M&M's new recipe is out and it's the best chocolate ever", DatePublished = "2022-02-06", LectureTime = 1, Author = "M&M's Red" };
context.ArticleSet.Add(a1);
context.ArticleSet.Add(a2);
context.ArticleSet.Add(a3);
context.SaveChanges();
Assert.Equal(3, context.ArticleSet.Count());
Assert.Equal("Tom Smith", context.ArticleSet.First().Author);
connection.Close();
}
}
[Fact]
public void Modify_Test()
{
var connection = new SqliteConnection("DataSource=:memory:");
connection.Open();
var options = new DbContextOptionsBuilder<LibraryContext>()
.UseSqlite(connection)
.Options;
using (var context = new LibraryContext(options))
{
context.Database.EnsureCreated();
ArticleEntity a1 = new ArticleEntity { Id = 1, Title = "Breaking News Elisabeth 2 Died", Description = "The queen of England died today at the age of 95", DatePublished = "2022-02-06", LectureTime = 2, Author = "Tom Smith" };
ArticleEntity a2 = new ArticleEntity { Id = 2, Title = "The new iPhone 15", Description = "The new iPhone 15 is out and it's the best phone ever", DatePublished = "2022-02-06", LectureTime = 3, Author = "Tom Smith" };
ArticleEntity a3 = new ArticleEntity { Id = 3, Title = "M&M's new recipe", Description = "M&M's new recipe is out and it's the best chocolate ever", DatePublished = "2022-02-06", LectureTime = 1, Author = "M&M's Red" };
context.ArticleSet.Add(a1);
context.ArticleSet.Add(a2);
context.ArticleSet.Add(a3);
context.SaveChanges();
var article = context.ArticleSet.First(a => a.Title.Equals("Breaking News Elisabeth 2 Died"));
article.Author = "Louis Laborie";
context.SaveChanges();
string persRemove = "Tom Smith";
string persNew = "Louis Laborie";
Assert.Equal(1, context.ArticleSet.Count(a => a.Author.Equals(persRemove)));
Assert.Equal(1, context.ArticleSet.Count(a => a.Author.Equals(persNew)));
connection.Close();
}
}
[Fact]
public void Remove_Test()
{
var connection = new SqliteConnection("DataSource=:memory:");
connection.Open();
var options = new DbContextOptionsBuilder<LibraryContext>()
.UseSqlite(connection)
.Options;
using (var context = new LibraryContext(options))
{
context.Database.EnsureCreated();
ArticleEntity a1 = new ArticleEntity { Id = 1, Title = "Breaking News Elisabeth 2 Died", Description = "The queen of England died today at the age of 95", DatePublished = "2022-02-06", LectureTime = 2, Author = "Tom Smith" };
ArticleEntity a2 = new ArticleEntity { Id = 2, Title = "The new iPhone 15", Description = "The new iPhone 15 is out and it's the best phone ever", DatePublished = "2022-02-06", LectureTime = 3, Author = "Tom Smith" };
ArticleEntity a3 = new ArticleEntity { Id = 3, Title = "M&M's new recipe", Description = "M&M's new recipe is out and it's the best chocolate ever", DatePublished = "2022-02-06", LectureTime = 1, Author = "M&M's Red" };
context.Add(a1);
context.Add(a2);
context.Add(a3);
context.SaveChanges();
var article = context.ArticleSet.First(a => a.Title.Equals("Breaking News Elisabeth 2 Died"));
context.Remove(article);
context.SaveChanges();
Assert.Equal(2, context.ArticleSet.Count());
Assert.Equal(0, context.ArticleSet.Count(a => a.Title.Equals("Breaking News Elisabeth 2 Died")));
connection.Close();
}
}
}

@ -0,0 +1,182 @@
using DbContextLib;
using Entities;
using Microsoft.Data.Sqlite;
using Microsoft.EntityFrameworkCore;
namespace Tests;
public class TestsUserEntity
{
[Fact]
public void Add_Test()
{
var connection = new SqliteConnection("DataSource=:memory:");
connection.Open();
var options = new DbContextOptionsBuilder<LibraryContext>()
.UseSqlite(connection)
.Options;
using (var context = new LibraryContext(options))
{
context.Database.EnsureCreated();
UserEntity u1 = new UserEntity
{
Pseudo = "Tofgasy", Prenom = "Tony", Nom = "Fages", Mail = "he@gmail.com", Mdp = "1234", Role = "Admin"
};
UserEntity u2 = new UserEntity
{
Pseudo = "Blizzard", Prenom = "Louis", Nom = "Laborie", Mail = "he@gmail.com", Mdp = "1234",
Role = "Admin"
};
UserEntity u3 = new UserEntity
{
Pseudo = "TomS", Prenom = "Tom", Nom = "Smith", Mail = "TomS@gmail.com", Mdp = "1234", Role = "User"
};
UserEntity u4 = new UserEntity
{
Pseudo = "Siwa", Prenom = "Jean", Nom = "Marcillac", Mail = "occitan@gmail.com", Mdp = "1234",
Role = "Amin"
};
UserEntity u5 = new UserEntity
{
Pseudo = "Sha", Prenom = "Shana", Nom = "Cascarra", Mail = "shacas@gmail.com", Mdp = "1234",
Role = "Modérator"
};
UserEntity u6 = new UserEntity
{
Pseudo = "NoaSil", Prenom = "Noa", Nom = "Sillard", Mail = "noaSillar@gmail.com", Mdp = "1234",
Role = "Admin"
};
context.UserSet.Add(u1);
context.UserSet.Add(u2);
context.UserSet.Add(u3);
context.UserSet.Add(u4);
context.UserSet.Add(u5);
context.UserSet.Add(u6);
context.SaveChanges();
Assert.Equal(6, context.UserSet.Count());
Assert.Equal("Blizzard", context.UserSet.First().Pseudo);
connection.Close();
}
}
[Fact]
public void Modify_Test()
{
var connection = new SqliteConnection("DataSource=:memory:");
connection.Open();
var options = new DbContextOptionsBuilder<LibraryContext>()
.UseSqlite(connection)
.Options;
using (var context = new LibraryContext(options))
{
context.Database.EnsureCreated();
UserEntity u1 = new UserEntity
{
Pseudo = "Tofgasy", Prenom = "Tony", Nom = "Fages", Mail = "he@gmail.com", Mdp = "1234", Role = "Admin"
};
UserEntity u2 = new UserEntity
{
Pseudo = "Blizzard", Prenom = "Louis", Nom = "Laborie", Mail = "he@gmail.com", Mdp = "1234",
Role = "Admin"
};
UserEntity u3 = new UserEntity
{
Pseudo = "TomS", Prenom = "Tom", Nom = "Smith", Mail = "TomS@gmail.com", Mdp = "1234", Role = "User"
};
UserEntity u4 = new UserEntity
{
Pseudo = "Siwa", Prenom = "Jean", Nom = "Marcillac", Mail = "occitan@gmail.com", Mdp = "1234",
Role = "Amin"
};
UserEntity u5 = new UserEntity
{
Pseudo = "Sha", Prenom = "Shana", Nom = "Cascarra", Mail = "shacas@gmail.com", Mdp = "1234",
Role = "Modérator"
};
UserEntity u6 = new UserEntity
{
Pseudo = "NoaSil", Prenom = "Noa", Nom = "Sillard", Mail = "noaSillar@gmail.com", Mdp = "1234",
Role = "Admin"
};
context.UserSet.Add(u1);
context.UserSet.Add(u2);
context.UserSet.Add(u3);
context.UserSet.Add(u4);
context.UserSet.Add(u5);
context.UserSet.Add(u6);
context.SaveChanges();
var user = context.UserSet.First(u => u.Pseudo.Equals("Tofgasy"));
user.Prenom = "Tof";
context.SaveChanges();
string persRemove = "Tony";
string persNew = "Tof";
Assert.Equal(1, context.UserSet.Count(u => u.Prenom.Equals(persNew)));
Assert.Equal(0, context.UserSet.Count(u => u.Prenom.Equals(persRemove)));
connection.Close();
}
}
[Fact]
public void Remove_Test()
{
var connection = new SqliteConnection("DataSource=:memory:");
connection.Open();
var options = new DbContextOptionsBuilder<LibraryContext>()
.UseSqlite(connection)
.Options;
using (var context = new LibraryContext(options))
{
context.Database.EnsureCreated();
UserEntity u1 = new UserEntity
{
Pseudo = "Tofgasy", Prenom = "Tony", Nom = "Fages", Mail = "he@gmail.com", Mdp = "1234", Role = "Admin"
};
UserEntity u2 = new UserEntity
{
Pseudo = "Blizzard", Prenom = "Louis", Nom = "Laborie", Mail = "he@gmail.com", Mdp = "1234",
Role = "Admin"
};
UserEntity u3 = new UserEntity
{
Pseudo = "TomS", Prenom = "Tom", Nom = "Smith", Mail = "TomS@gmail.com", Mdp = "1234", Role = "User"
};
UserEntity u4 = new UserEntity
{
Pseudo = "Siwa", Prenom = "Jean", Nom = "Marcillac", Mail = "occitan@gmail.com", Mdp = "1234",
Role = "Amin"
};
UserEntity u5 = new UserEntity
{
Pseudo = "Sha", Prenom = "Shana", Nom = "Cascarra", Mail = "shacas@gmail.com", Mdp = "1234",
Role = "Modérator"
};
UserEntity u6 = new UserEntity
{
Pseudo = "NoaSil", Prenom = "Noa", Nom = "Sillard", Mail = "noaSillar@gmail.com", Mdp = "1234",
Role = "Admin"
};
context.UserSet.Add(u1);
context.UserSet.Add(u2);
context.UserSet.Add(u3);
context.UserSet.Add(u4);
context.UserSet.Add(u5);
context.UserSet.Add(u6);
context.SaveChanges();
Assert.Equal(6, context.UserSet.Count());
var user = context.UserSet.First(u => u.Pseudo.Equals("Tofgasy"));
context.Remove(user);
context.SaveChanges();
Assert.Equal(5, context.UserSet.Count());
Assert.Equal(0, context.UserSet.Count(u => u.Pseudo.Equals("Tofgasy")));
connection.Close();
}
}
}

@ -0,0 +1,35 @@
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<TargetFramework>net8.0</TargetFramework>
<ImplicitUsings>enable</ImplicitUsings>
<Nullable>enable</Nullable>
<IsPackable>false</IsPackable>
<IsTestProject>true</IsTestProject>
<RootNamespace>TestsUnitaires</RootNamespace>
</PropertyGroup>
<ItemGroup>
<PackageReference Include="coverlet.collector" Version="6.0.0" />
<PackageReference Include="Microsoft.EntityFrameworkCore" Version="8.0.2" />
<PackageReference Include="Microsoft.EntityFrameworkCore.InMemory" Version="8.0.2" />
<PackageReference Include="Microsoft.EntityFrameworkCore.Sqlite" Version="8.0.2" />
<PackageReference Include="Microsoft.NET.Test.Sdk" Version="17.8.0" />
<PackageReference Include="xunit" Version="2.7.0" />
<PackageReference Include="xunit.runner.visualstudio" Version="2.5.7">
<PrivateAssets>all</PrivateAssets>
<IncludeAssets>runtime; build; native; contentfiles; analyzers; buildtransitive</IncludeAssets>
</PackageReference>
</ItemGroup>
<ItemGroup>
<ProjectReference Include="..\DbContextLib\DbContextLib.csproj" />
<ProjectReference Include="..\Entities\Entities.csproj" />
</ItemGroup>
<ItemGroup>
<Using Include="Xunit" />
</ItemGroup>
</Project>

@ -1,24 +1,33 @@
 
Microsoft Visual Studio Solution File, Format Version 12.00 Microsoft Visual Studio Solution File, Format Version 12.00
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Test_Console_EF", "Test_Console_EF\Test_Console_EF.csproj", "{E27E2617-28A1-4675-B12B-89430582C05E}" # Visual Studio Version 17
VisualStudioVersion = 17.8.34525.116
MinimumVisualStudioVersion = 10.0.40219.1
Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "Test_Console_EF", "Test_Console_EF\Test_Console_EF.csproj", "{E27E2617-28A1-4675-B12B-89430582C05E}"
EndProject EndProject
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Entities", "Entities\Entities.csproj", "{40BD34D7-3F07-410A-BC04-2A5B09E758C0}" Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "Entities", "Entities\Entities.csproj", "{40BD34D7-3F07-410A-BC04-2A5B09E758C0}"
EndProject EndProject
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "DbContextLib", "DbContextLib\DbContextLib.csproj", "{F94BEE1F-302F-4654-8D85-AD41E0BACD03}" Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "DbContextLib", "DbContextLib\DbContextLib.csproj", "{F94BEE1F-302F-4654-8D85-AD41E0BACD03}"
EndProject EndProject
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "StubbedContextLib", "StubbedContextLib\StubbedContextLib.csproj", "{F1B4BCE5-8DE7-4EFB-8BC1-D7E04EA75302}" Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "StubbedContextLib", "StubbedContextLib\StubbedContextLib.csproj", "{F1B4BCE5-8DE7-4EFB-8BC1-D7E04EA75302}"
EndProject EndProject
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "API_DbDataManager", "API_DbDataManager\API_DbDataManager.csproj", "{FBA0CF18-7488-4088-A7C5-5D2071D19CCB}" Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "API_DbDataManager", "API_DbDataManager\API_DbDataManager.csproj", "{FBA0CF18-7488-4088-A7C5-5D2071D19CCB}"
EndProject EndProject
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "API_Services", "API_Services\API_Services.csproj", "{4FB7D286-B583-44BC-BB79-4AE3058AFEDE}" Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "API_Services", "API_Services\API_Services.csproj", "{4FB7D286-B583-44BC-BB79-4AE3058AFEDE}"
EndProject EndProject
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "API_Model", "API_Model\API_Model.csproj", "{F09B566E-8D25-4D70-B9F0-99E6969D4D1F}" Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "API_Model", "API_Model\API_Model.csproj", "{F09B566E-8D25-4D70-B9F0-99E6969D4D1F}"
EndProject EndProject
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "API_Mapping", "API_Mapping\API_Mapping.csproj", "{BECFAD2C-E442-4300-8121-5AE6610B92DF}" Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "API_Mapping", "API_Mapping\API_Mapping.csproj", "{BECFAD2C-E442-4300-8121-5AE6610B92DF}"
EndProject EndProject
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Model", "Model\Model.csproj", "{96FDB5DE-6707-4856-94CD-EFAF0C7CEB4B}" Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "Model", "Model\Model.csproj", "{96FDB5DE-6707-4856-94CD-EFAF0C7CEB4B}"
EndProject EndProject
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "API", "API\API.csproj", "{6AACD337-70A0-429B-979C-1B1E004BF2E0}" Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "API", "API\API.csproj", "{6AACD337-70A0-429B-979C-1B1E004BF2E0}"
EndProject
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Unit_Test_EF", "Unit_Test_EF\Unit_Test_EF.csproj", "{C1982C7C-AE09-4E96-B1A9-B6ADE4097452}"
EndProject
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "API_Unit_Test", "API_Unit_Test\API_Unit_Test.csproj", "{B3B9C0F5-98A3-438B-A22A-ECFF33DA8F23}"
EndProject
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "API_Tests_Console", "API_Tests_Console\API_Tests_Console.csproj", "{EEB45245-5B65-4C99-A2B4-942991AE5F1A}"
EndProject EndProject
Global Global
GlobalSection(SolutionConfigurationPlatforms) = preSolution GlobalSection(SolutionConfigurationPlatforms) = preSolution
@ -66,5 +75,20 @@ Global
{6AACD337-70A0-429B-979C-1B1E004BF2E0}.Debug|Any CPU.Build.0 = Debug|Any CPU {6AACD337-70A0-429B-979C-1B1E004BF2E0}.Debug|Any CPU.Build.0 = Debug|Any CPU
{6AACD337-70A0-429B-979C-1B1E004BF2E0}.Release|Any CPU.ActiveCfg = Release|Any CPU {6AACD337-70A0-429B-979C-1B1E004BF2E0}.Release|Any CPU.ActiveCfg = Release|Any CPU
{6AACD337-70A0-429B-979C-1B1E004BF2E0}.Release|Any CPU.Build.0 = Release|Any CPU {6AACD337-70A0-429B-979C-1B1E004BF2E0}.Release|Any CPU.Build.0 = Release|Any CPU
{C1982C7C-AE09-4E96-B1A9-B6ADE4097452}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{C1982C7C-AE09-4E96-B1A9-B6ADE4097452}.Debug|Any CPU.Build.0 = Debug|Any CPU
{C1982C7C-AE09-4E96-B1A9-B6ADE4097452}.Release|Any CPU.ActiveCfg = Release|Any CPU
{C1982C7C-AE09-4E96-B1A9-B6ADE4097452}.Release|Any CPU.Build.0 = Release|Any CPU
{B3B9C0F5-98A3-438B-A22A-ECFF33DA8F23}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{B3B9C0F5-98A3-438B-A22A-ECFF33DA8F23}.Debug|Any CPU.Build.0 = Debug|Any CPU
{B3B9C0F5-98A3-438B-A22A-ECFF33DA8F23}.Release|Any CPU.ActiveCfg = Release|Any CPU
{B3B9C0F5-98A3-438B-A22A-ECFF33DA8F23}.Release|Any CPU.Build.0 = Release|Any CPU
{EEB45245-5B65-4C99-A2B4-942991AE5F1A}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{EEB45245-5B65-4C99-A2B4-942991AE5F1A}.Debug|Any CPU.Build.0 = Debug|Any CPU
{EEB45245-5B65-4C99-A2B4-942991AE5F1A}.Release|Any CPU.ActiveCfg = Release|Any CPU
{EEB45245-5B65-4C99-A2B4-942991AE5F1A}.Release|Any CPU.Build.0 = Release|Any CPU
EndGlobalSection
GlobalSection(SolutionProperties) = preSolution
HideSolutionNode = FALSE
EndGlobalSection EndGlobalSection
EndGlobal EndGlobal

@ -0,0 +1,15 @@
# Default ignored files
/shelf/
/workspace.xml
# Rider ignored files
/modules.xml
/projectSettingsUpdater.xml
/.idea.Verax_API_EF.iml
/contentModel.xml
# Editor-based HTTP Client requests
/httpRequests/
# Datasource local storage ignored files
/dataSources/
/dataSources.local.xml
# GitHub Copilot persisted chat sessions
/copilot/chatSessions

@ -0,0 +1,8 @@
<?xml version="1.0" encoding="UTF-8"?>
<project version="4">
<component name="UserContentModel">
<attachedFolders />
<explicitIncludes />
<explicitExcludes />
</component>
</project>

@ -0,0 +1,6 @@
<?xml version="1.0" encoding="UTF-8"?>
<project version="4">
<component name="VcsDirectoryMappings">
<mapping directory="$PROJECT_DIR$/../.." vcs="Git" />
</component>
</project>
Loading…
Cancel
Save