Compare commits

..

16 Commits
master ... php

Author SHA1 Message Date
Antoine JOURDAIN 1958b44b75 Mise à jour de 'README.md'
1 year ago
Antoine JOURDAIN 31966091b3 MAJ MCD/MLD
1 year ago
Anthony RICHARD 1199df9d04 fix erreur en haut de la page home
1 year ago
Anthony RICHARD dede582ca3 fix demo pour les student + visuel boutons des actions student
1 year ago
Antoine JOURDAIN a3b6b9262d Fix gateway + alert quiz + page accueil
1 year ago
Antoine JOURDAIN a7332fc69f Modification DB
1 year ago
Anthony RICHARD f7003a1309 code smells
1 year ago
Patrick BRUGIERE 684ad0d038 Merge branch 'php' of https://codefirst.iut.uca.fr/git/antoine.jourdain/SAE_2A_Anglais into php
1 year ago
Patrick BRUGIERE e224c6109f modification de l'affichage des resultats (et du code php derriere)
1 year ago
Anthony RICHARD 083cdb1f43 fix appel gateway dans les controllers
1 year ago
Anthony RICHARD 638b7e9aca fix student qui a accès à toutes les listes
1 year ago
Anthony RICHARD 8fe07e0328 Merge branch 'php' of https://codefirst.iut.uca.fr/git/antoine.jourdain/SAE_2A_Anglais into php
1 year ago
Anthony RICHARD 8d45af3abb fix fonctions inutiles + code en commentaire
1 year ago
Patrick BRUGIERE 4013db8489 Merge branch 'php' of https://codefirst.iut.uca.fr/git/antoine.jourdain/SAE_2A_Anglais into php
1 year ago
Patrick BRUGIERE 08b72fea9d ajout de la valeur de retour pour chaque fonction
1 year ago
Anthony RICHARD 647090ace5 fix titres pages
1 year ago

@ -1,114 +0,0 @@
kind: pipeline
type: docker
name: default
trigger:
event:
- push
steps:
- name: build
image: mcr.microsoft.com/dotnet/sdk:7.0
commands:
- cd Project/adminBlazor/
- dotnet restore adminBlazor.sln
- dotnet build adminBlazor.sln -c Release --no-restore
- name: tests
image: mcr.microsoft.com/dotnet/sdk:7.0
commands:
- cd Project/adminBlazor
- dotnet restore adminBlazor.sln
- dotnet test adminBlazor.sln --no-restore
depends_on: [build]
- name: code-analysis
image: hub.codefirst.iut.uca.fr/marc.chevaldonne/codefirst-dronesonarplugin-dotnet7
environment:
project_key: SAE_2A_Anglais_Blazor
sonar_host: https://codefirst.iut.uca.fr/sonar/
sonar_token:
from_secret: SECRET_SONAR_LOGIN
commands:
- cd Project/adminBlazor
- dotnet restore adminBlazor.sln
- dotnet sonarscanner begin /k:$${project_key} /d:sonar.host.url=$${sonar_host} /d:sonar.login=$${sonar_token}
- dotnet build adminBlazor.sln -c Release --no-restore
- dotnet sonarscanner end /d:sonar.login=$${sonar_token}
depends_on: [tests]
- name: generate-and-deploy-docs
image: hub.codefirst.iut.uca.fr/thomas.bellembois/codefirst-docdeployer
failure: ignore
volumes:
- name: docs
path: /docs
commands:
- /entrypoint.sh
when:
branch:
- blazor
- blazor-ci
depends_on: [ build ]
- name: docker-build-api
image: plugins/docker
settings:
dockerfile: Project/adminBlazor/adminBlazor.Api/Dockerfile
context: Project/adminBlazor/
registry: hub.codefirst.iut.uca.fr
repo: hub.codefirst.iut.uca.fr/antoine.jourdain/sae_2a_anglais
username:
from_secret: SECRET_REGISTRY_USERNAME
password:
from_secret: SECRET_REGISTRY_PASSWORD
when:
branch:
- blazor
- blazor-ci
- name: deploy-container-api
image: hub.codefirst.iut.uca.fr/thomas.bellembois/codefirst-dockerproxy-clientdrone:latest
environment:
IMAGENAME: hub.codefirst.iut.uca.fr/antoine.jourdain/sae_2a_anglais:latest
CONTAINERNAME: api-in-english-please
COMMAND: create
OVERWRITE: true
depends_on: [ docker-build-api ]
when:
branch:
- blazor
- blazor-ci
- name: docker-build-app
image: plugins/docker
settings:
dockerfile: Project/adminBlazor/adminBlazor/Dockerfile
context: Project/adminBlazor/
registry: hub.codefirst.iut.uca.fr
repo: hub.codefirst.iut.uca.fr/antoine.jourdain/sae_2a_anglais
username:
from_secret: SECRET_REGISTRY_USERNAME
password:
from_secret: SECRET_REGISTRY_PASSWORD
when:
branch:
- blazor
- blazor-ci
- name: deploy-container-app
image: hub.codefirst.iut.uca.fr/thomas.bellembois/codefirst-dockerproxy-clientdrone:latest
environment:
IMAGENAME: hub.codefirst.iut.uca.fr/antoine.jourdain/sae_2a_anglais:latest
CONTAINERNAME: in-english-please
COMMAND: create
OVERWRITE: true
depends_on: [ docker-build-app ]
when:
branch:
- blazor
- blazor-ci
volumes:
- name: docs
temp: {}

144
.gitignore vendored

@ -1,3 +1,6 @@
# ---> Linux
*~
# temporary files which can be created if a process still has a handle open of a deleted file
.fuse_hidden*
@ -10,11 +13,43 @@
# .nfs files are created when an open file is removed but is still being accessed
.nfs*
# macOS
# ---> Windows
# Windows thumbnail cache files
Thumbs.db
Thumbs.db:encryptable
ehthumbs.db
ehthumbs_vista.db
# Dump file
*.stackdump
# Folder config file
[Dd]esktop.ini
# Recycle Bin used on file shares
$RECYCLE.BIN/
# Windows Installer files
*.cab
*.msi
*.msix
*.msm
*.msp
# Windows shortcuts
*.lnk
# ---> macOS
# General
.DS_Store
.AppleDouble
.LSOverride
# Icon must end with two \r
Icon
# Thumbnails
._*
# Files that might appear in the root of a volume
@ -33,40 +68,24 @@ Network Trash Folder
Temporary Items
.apdisk
# JetBrains
.idea/
# VisualStudioCode
.vscode/*
!.vscode/settings.json
!.vscode/tasks.json
!.vscode/launch.json
!.vscode/extensions.json
*.code-workspace
# Local History for Visual Studio Code
.history/
# Windows
Thumbs.db
Thumbs.db:encryptable
ehthumbs.db
ehthumbs_vista.db
*.stackdump
[Dd]esktop.ini
$RECYCLE.BIN/
*.lnk
# Intellij
# ---> JetBrains
# Covers JetBrains IDEs: IntelliJ, RubyMine, PhpStorm, AppCode, PyCharm, CLion, Android Studio, WebStorm and Rider
# Reference: https://intellij-support.jetbrains.com/hc/en-us/articles/206544839
# User-specific stuff
.idea/**/workspace.xml
.idea/**/tasks.xml
.idea/**/usage.statistics.xml
.idea/**/dictionaries
.idea/**/shelf
# AWS User-specific
.idea/**/aws.xml
# Generated files
.idea/**/contentModel.xml
# Sensitive or high-churn files
.idea/**/dataSources/
.idea/**/dataSources.ids
.idea/**/dataSources.local.xml
@ -74,31 +93,80 @@ $RECYCLE.BIN/
.idea/**/dynamic.xml
.idea/**/uiDesigner.xml
.idea/**/dbnavigator.xml
# Gradle
.idea/**/gradle.xml
.idea/**/libraries
# Gradle and Maven with auto-import
# When using Gradle or Maven with auto-import, you should exclude module files,
# since they will be recreated, and may cause churn. Uncomment if using
# auto-import.
# .idea/artifacts
# .idea/compiler.xml
# .idea/jarRepositories.xml
# .idea/modules.xml
# .idea/*.iml
# .idea/modules
# *.iml
# *.ipr
# CMake
cmake-build-*/
# Mongo Explorer plugin
.idea/**/mongoSettings.xml
# File-based project format
*.iws
# IntelliJ
out/
# mpeltonen/sbt-idea plugin
.idea_modules/
# JIRA plugin
atlassian-ide-plugin.xml
# Cursive Clojure plugin
.idea/replstate.xml
# SonarLint plugin
.idea/sonarlint/
# Crashlytics plugin (for Android Studio and IntelliJ)
com_crashlytics_export_strings.xml
crashlytics.properties
crashlytics-build.properties
fabric.properties
# Editor-based Rest Client
.idea/httpRequests
# Android studio 3.1+ serialized cache file
.idea/caches/build_file_checksums.ser
.idea/**/sonarlint/
.idea/**/sonarIssues.xml
.idea/**/markdown-navigator.xml
.idea/**/markdown-navigator-enh.xml
.idea/**/markdown-navigator/
.idea/$CACHE_FILE$
.idea/codestream.xml
.idea/**/azureSettings.xml
/.vs
/Project/adminBlazor/.vs
/Project/EntityFramework/**/bin/
/Project/EntityFramework/**/obj/
# Idea folder
.idea/
# ---> VisualStudioCode
.vscode/*
!.vscode/settings.json
!.vscode/tasks.json
!.vscode/launch.json
!.vscode/extensions.json
!.vscode/*.code-snippets
# Local History for Visual Studio Code
.history/
# Built Visual Studio Code Extensions
*.vsix
# Fichier cache
cache/
#Fichiers composer
vendor/
*.lock

Binary file not shown.

Binary file not shown.

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

@ -1,33 +0,0 @@
<Project Sdk="Microsoft.NET.Sdk.Web">
<PropertyGroup>
<TargetFramework>net8.0</TargetFramework>
<Nullable>enable</Nullable>
<ImplicitUsings>enable</ImplicitUsings>
<StartWorkingDirectory>$(MSBuildProjectDirectory)</StartWorkingDirectory>
<UserSecretsId>1540d456-1696-425e-b511-611542ce7c5e</UserSecretsId>
<DockerDefaultTargetOS>Linux</DockerDefaultTargetOS>
</PropertyGroup>
<ItemGroup>
<PackageReference Include="Microsoft.AspNetCore.Authentication.JwtBearer" Version="8.0.3" />
<PackageReference Include="Microsoft.AspNetCore.Mvc.Versioning" Version="5.1.0" />
<PackageReference Include="Microsoft.EntityFrameworkCore" Version="8.0.2" />
<PackageReference Include="Microsoft.EntityFrameworkCore.SqlServer" Version="8.0.2" />
<PackageReference Include="Microsoft.EntityFrameworkCore.Tools" Version="8.0.2">
<PrivateAssets>all</PrivateAssets>
<IncludeAssets>runtime; build; native; contentfiles; analyzers; buildtransitive</IncludeAssets>
</PackageReference>
<PackageReference Include="Microsoft.Extensions.Options" Version="8.0.2" />
<PackageReference Include="Microsoft.VisualStudio.Azure.Containers.Tools.Targets" Version="1.19.5" />
<PackageReference Include="Swashbuckle.AspNetCore" Version="6.4.0" />
</ItemGroup>
<ItemGroup>
<ProjectReference Include="..\DTOToEntity\DTOToEntity.csproj" />
<ProjectReference Include="..\DTO\DTO.csproj" />
<ProjectReference Include="..\Entities\Entities.csproj" />
<ProjectReference Include="..\StubbedContext\StubbedContextLib.csproj" />
</ItemGroup>
</Project>

@ -1,11 +0,0 @@
<?xml version="1.0" encoding="utf-8"?>
<Project ToolsVersion="Current" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
<PropertyGroup>
<ActiveDebugProfile>https</ActiveDebugProfile>
<Controller_SelectedScaffolderID>MvcControllerEmptyScaffolder</Controller_SelectedScaffolderID>
<Controller_SelectedScaffolderCategoryPath>root/Common/MVC/Controller</Controller_SelectedScaffolderCategoryPath>
</PropertyGroup>
<PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Debug|AnyCPU'">
<DebuggerFlavor>ProjectDebugger</DebuggerFlavor>
</PropertyGroup>
</Project>

@ -1,6 +0,0 @@
@API_HostAddress = http://localhost:5124
GET {{API_HostAddress}}/weatherforecast/
Accept: application/json
###

@ -1,44 +0,0 @@
using Microsoft.AspNetCore.Mvc;
using Microsoft.IdentityModel.Tokens;
using System.IdentityModel.Tokens.Jwt;
using System.Security.Claims;
using System.Text;
namespace API.Controllers
{
[ApiController]
[Route("[controller]")]
public class AuthController : ControllerBase
{
private readonly IConfiguration _configuration;
public AuthController(IConfiguration configuration)
{
_configuration = configuration;
}
[HttpPost]
[Route("token")]
public IActionResult GetToken()
{
var tokenHandler = new JwtSecurityTokenHandler();
var key = Encoding.ASCII.GetBytes(_configuration["JwtTokenSettings:SymmetricSecurityKey"]);
var tokenDescriptor = new SecurityTokenDescriptor
{
Subject = new ClaimsIdentity(new Claim[]
{
new Claim(ClaimTypes.Name, "User1"),
}),
Expires = DateTime.UtcNow.AddHours(1),
SigningCredentials = new SigningCredentials(new SymmetricSecurityKey(key), SecurityAlgorithms.HmacSha256Signature),
Audience = _configuration["JwtTokenSettings:ValidAudience"],
Issuer = _configuration["JwtTokenSettings:ValidIssuer"]
};
var token = tokenHandler.CreateToken(tokenDescriptor);
var tokenString = tokenHandler.WriteToken(token);
return Ok(new { Token = tokenString });
}
}
}

@ -1,225 +0,0 @@
using DTO;
using DTOToEntity;
using Entities;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using StubbedContextLib;
namespace API.Controllers
{
[Authorize]
[ApiController]
[Route("api/v{version:apiVersion}/[controller]")]
[ApiVersion("1.0")]
public class GroupController : ControllerBase
{
private readonly IGroupService _service;
private readonly ILogger<GroupController> _logger;
public GroupController(IGroupService groupService, ILogger<GroupController> logger)
{
_service = groupService;
_logger = logger;
}
[HttpGet]
public async Task<ActionResult<PageResponse<GroupDTO>>> GetGroups(int index, int count)
{
try
{
_logger.LogInformation("Getting groups ");
var groups = await _service.Gets(index, count);
return groups;
}
catch (Exception ex)
{
// Journaliser l'exception
_logger.LogError(ex, "Une erreur s'est produite lors de la récupération des groupes.");
// Retourner une réponse d'erreur
return StatusCode(400, ex.Message);
}
}
[HttpGet("{id}")]
public async Task<ActionResult<GroupDTO>> GetGroup(long id)
{
try
{
_logger.LogInformation("Getting a group with id {id}", id);
var group = await _service.GetById(id);
if (group == null)
{
return NotFound();
}
return group;
}
catch (Exception ex)
{
// Journaliser l'exception
_logger.LogError(ex, "Une erreur s'est produite lors de la récupération du groupe avec l'ID {id}.", id);
// Retourner une réponse d'erreur
return StatusCode(400, ex.Message);
}
}
[HttpPut]
public async Task<ActionResult<GroupDTO>> UpdateGroup([FromBody]GroupDTO group)
{
try
{
_logger.LogInformation("Updating a group with id : {id}", group.Id);
var updatedGroup = await _service.Update(group);
return updatedGroup;
}
catch (Exception ex)
{
// Journaliser l'exception
_logger.LogError(ex, "Une erreur s'est produite lors de la mise à jour du groupe avec l'ID {id}.", group.Id);
// Retourner une réponse d'erreur
return StatusCode(400,ex.Message);
}
}
[HttpPost]
public async Task<ActionResult<GroupDTO>> AddGroup([FromBody]GroupDTO group)
{
try
{
_logger.LogInformation("Adding a group with id : {id}", group.Id);
group.Id = _service.Gets(0, 0).Result.TotalCount + 1;
var newGroup = await _service.Add(group);
return newGroup;
}
catch (Exception ex)
{
// Journaliser l'exception
_logger.LogError(ex, "Une erreur s'est produite lors de l'ajout du groupe avec l'ID {id}.", group.Id);
// Retourner une réponse d'erreur
return StatusCode(400,ex.Message);
}
}
[HttpDelete("{id}")]
public async Task<ActionResult<GroupDTO>> DeleteGroup(long id)
{
try
{
_logger.LogInformation("Deleting a group with id : {id}", id);
var group = await _service.Delete(id);
return group;
}
catch (Exception ex)
{
// Journaliser l'exception
_logger.LogError(ex, "Une erreur s'est produite lors de la suppression du groupe avec l'ID {id}.", id);
// Retourner une réponse d'erreur
return StatusCode(400,ex.Message);
}
}
[HttpGet("num/{num}")]
public async Task<ActionResult<PageResponse<GroupDTO>>> GetGroupsByNum(int index, int count, int num)
{
try
{
_logger.LogInformation("Getting groups by num : {num}", num);
var groups = await _service.GetByNum(index, count, num);
return groups;
}
catch (Exception ex)
{
// Journaliser l'exception
_logger.LogError(ex, "Une erreur s'est produite lors de la récupération des groupes avec le numéro {num}.", num);
// Retourner une réponse d'erreur
return StatusCode(400,ex.Message);
}
}
[HttpGet("sector/{sector}")]
public async Task<ActionResult<PageResponse<GroupDTO>>> GetGroupsBySector(int index, int count, string sector)
{
try
{
_logger.LogInformation("Getting groups by sector : {sector}", sector);
var groups = await _service.GetBySector(index, count, sector);
return groups;
}
catch (Exception ex)
{
// Journaliser l'exception
_logger.LogError(ex, "Une erreur s'est produite lors de la récupération des groupes avec le secteur {sector}.", sector);
// Retourner une réponse d'erreur
return StatusCode(400,ex.Message);
}
}
[HttpGet("year/{year}")]
public async Task<ActionResult<PageResponse<GroupDTO>>> GetGroupsByYear(int index, int count, int year)
{
try
{
_logger.LogInformation("Getting groups by year : {year}", year);
var groups = await _service.GetByYear(index, count, year);
return groups;
}
catch (Exception ex)
{
// Journaliser l'exception
_logger.LogError(ex, "Une erreur s'est produite lors de la récupération des groupes avec l'année {year}.", year);
// Retourner une réponse d'erreur
return StatusCode(400,ex.Message);
}
}
[HttpPost("addUser")]
public async Task<ActionResult<UserDTO>> AddUserToGroup([FromBody]long userId, long groupId)
{
try
{
_logger.LogInformation("Adding user with id : {userId} to group with id : {groupId}", userId, groupId);
var user = await _service.AddUserToGroup(userId, groupId);
return user;
}
catch (Exception ex)
{
// Journaliser l'exception
_logger.LogError(ex, "Une erreur s'est produite lors de l'ajout de l'utilisateur avec l'ID {userId} au groupe avec l'ID {groupId}.", userId, groupId);
// Retourner une réponse d'erreur
return StatusCode(400,ex.Message);
}
}
[HttpPost("addVocabularyList")]
public async Task<ActionResult<VocabularyListDTO>> AddVocabularyListToGroup([FromQuery]long vocabularyListId, long groupId)
{
try
{
_logger.LogInformation("Adding vocabulary list with id : {vocabularyListId} to group with id : {groupId}", vocabularyListId, groupId);
var vocabularyList = await _service.AddVocabularyListToGroup(vocabularyListId, groupId);
return vocabularyList;
}
catch (Exception ex)
{
// Journaliser l'exception
_logger.LogError(ex, "Une erreur s'est produite lors de l'ajout de la liste de vocabulaire avec l'ID {vocabularyListId} au groupe avec l'ID {groupId}.", vocabularyListId, groupId);
// Retourner une réponse d'erreur
return StatusCode(400,ex.Message);
}
}
}
}

@ -1,120 +0,0 @@
using DTO;
using DTOToEntity;
using Entities;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using StubbedContextLib;
namespace API.Controllers
{
[Authorize]
[ApiController]
[Route("api/v{version:apiVersion}/[controller]")]
[ApiVersion("1.0")]
public class LangueController : ControllerBase
{
private readonly IService<LangueDTO> _service;
private readonly ILogger<LangueController> _logger;
public LangueController(IService<LangueDTO> LangueService, ILogger<LangueController> logger)
{
_service = LangueService;
_logger = logger;
}
[HttpGet]
public async Task<ActionResult<PageResponse<LangueDTO>>> GetLangues(int index, int count)
{
try {
_logger.LogInformation("Getting langues ");
var groups = await _service.Gets(index,count);
return groups;
}
catch (Exception ex)
{
// Journaliser l'exception
_logger.LogError(ex, "Une erreur s'est produite lors de la récupération des langues.");
// Retourner une réponse d'erreur
return StatusCode(400, ex.Message);
}
}
[HttpGet("{name}")]
public async Task<ActionResult<LangueDTO>> GetLangue(string name)
{
try {
_logger.LogInformation("Getting a langue with name {name}",name);
var group = await _service.GetById(name);
return group;
}
catch (Exception ex)
{
// Journaliser l'exception
_logger.LogError(ex, "Une erreur s'est produite lors de la récupération de la langue avec le nom {name}.", name);
// Retourner une réponse d'erreur
return StatusCode(400, ex.Message);
}
}
//On ne peut pas changer la langue car son nom est son Id
/*
[HttpPut]
public async Task<ActionResult<LangueDTO>> UpdateLangue([FromQuery]LangueDTO langue)
{
try
{
_logger.LogInformation("Updating a langue with name : {name}", langue.name);
var updatedGroup = await _service.Update(langue);
return updatedGroup;
}
catch (Exception ex)
{
// Journaliser l'exception
_logger.LogError(ex, "Une erreur s'est produite lors de la mise à jour de la langue avec le nom {name}.", langue.name);
// Retourner une réponse d'erreur
return StatusCode(400, ex.Message);
}
}*/
[HttpPost]
public async Task<ActionResult<LangueDTO>> AddLangue([FromQuery]LangueDTO langue)
{
try
{
_logger.LogInformation("Adding a langue with name : {name}", langue.name);
var newGroup = await _service.Add(langue);
return newGroup;
}
catch (Exception ex)
{
// Journaliser l'exception
_logger.LogError(ex, "Une erreur s'est produite lors de l'ajout de la langue avec le nom {name}.", langue.name);
// Retourner une réponse d'erreur
return StatusCode(400, ex.Message);
}
}
[HttpDelete("{name}")]
public async Task<ActionResult<LangueDTO>> DeleteLangue(string name)
{
try
{
_logger.LogInformation("Deleting a langue with name : {name}", name);
var group = await _service.Delete(name);
return group;
}
catch (Exception ex)
{
// Journaliser l'exception
_logger.LogError(ex, "Une erreur s'est produite lors de la suppression de la langue avec le nom {name}.", name);
// Retourner une réponse d'erreur
return StatusCode(400, ex.Message);
}
}
}
}

@ -1,100 +0,0 @@

using DTO;
using DTOToEntity;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
namespace API.Controllers
{
[Authorize]
[ApiController]
[Route("api/v{version:apiVersion}/[controller]")]
[ApiVersion("1.0")]
public class RoleController : ControllerBase
{
private readonly IService<RoleDTO> _service;
private readonly ILogger<RoleController> _logger;
public RoleController(IService<RoleDTO> RoleService, ILogger<RoleController> logger)
{
_service = RoleService;
_logger = logger;
}
[HttpGet]
public async Task<ActionResult<PageResponse<RoleDTO>>> GetRoles(int index, int count)
{
try
{
_logger.LogInformation("Getting Roles ");
var groups = await _service.Gets(index, count);
return groups;
}
catch (Exception ex)
{
// Journaliser l'exception
_logger.LogError(ex, "Une erreur s'est produite lors de la récupération des roles.");
// Retourner une réponse d'erreur
return StatusCode(400, ex.Message);
}
}
[HttpGet("{id}")]
public async Task<ActionResult<RoleDTO>> GetRole(long id)
{
try
{
_logger.LogInformation("Getting a role with id {id}", id);
var group = await _service.GetById(id);
return group;
}
catch (Exception ex)
{
// Journaliser l'exception
_logger.LogError(ex, "Une erreur s'est produite lors de la récupération du role avec l'ID {id}.", id);
// Retourner une réponse d'erreur
return StatusCode(400, ex.Message);
}
}
[HttpPost]
public async Task<ActionResult<RoleDTO>> AddRole([FromQuery] RoleDTO role)
{
try
{
_logger.LogInformation("Adding a role with id : {id}", role.Id);
role.Id = _service.Gets(0, 0).Result.TotalCount + 1;
var newGroup = await _service.Add(role);
return newGroup;
}
catch (Exception ex)
{
// Journaliser l'exception
_logger.LogError(ex, "Une erreur s'est produite lors de l'ajout du role avec l'ID {id}.", role.Id);
// Retourner une réponse d'erreur
return StatusCode(400, ex.Message);
}
}
[HttpDelete("{id}")]
public async Task<ActionResult<RoleDTO>> DeleteRole(long id)
{
try {
_logger.LogInformation("Deleting a role with id : {id}", id);
var group = await _service.Delete(id);
return group;
}
catch (Exception ex)
{
// Journaliser l'exception
_logger.LogError(ex, "Une erreur s'est produite lors de la suppression du role avec l'ID {id}.", id);
// Retourner une réponse d'erreur
return StatusCode(400, ex.Message);
}
}
}
}

@ -1,135 +0,0 @@

using DTO;
using DTOToEntity;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
namespace API.Controllers
{
[Authorize]
[ApiController]
[Route("api/v{version:apiVersion}/[controller]")]
[ApiVersion("1.0")]
public class TranslateController : ControllerBase
{
private readonly ITranslateService _service;
private readonly ILogger<TranslateController> _logger;
public TranslateController(ITranslateService TranslateService, ILogger<TranslateController> logger)
{
_service = TranslateService;
_logger = logger;
}
[HttpGet]
public async Task<ActionResult<PageResponse<TranslateDTO>>> GetTranslates(int index, int count)
{
try
{
_logger.LogInformation("Getting Translates ");
var Translates = await _service.Gets(index, count);
return Translates;
}
catch (Exception ex)
{
// Journaliser l'exception
_logger.LogError(ex, "Une erreur s'est produite lors de la récupération des Translates.");
// Retourner une réponse d'erreur
return StatusCode(400, ex.Message);
}
}
[HttpGet("{id}")]
public async Task<ActionResult<TranslateDTO>> GetTranslate(long id)
{
try {
_logger.LogInformation("Getting a Translate with id {id}", id);
var Translate = await _service.GetById(id);
return Translate;
}
catch (Exception ex)
{
// Journaliser l'exception
_logger.LogError(ex, "Une erreur s'est produite lors de la récupération du Translate avec l'ID {id}.", id);
// Retourner une réponse d'erreur
return StatusCode(400, ex.Message);
}
}
[HttpPut]
public async Task<ActionResult<TranslateDTO>> UpdateTranslate([FromQuery] TranslateDTO Translate)
{
try {
_logger.LogInformation("Updating a Translate with id : {id}", Translate.Id);
var updatedTranslate = await _service.Update(Translate);
return updatedTranslate;
}
catch (Exception ex)
{
// Journaliser l'exception
_logger.LogError(ex, "Une erreur s'est produite lors de la mise à jour du Translate avec l'ID {id}.", Translate.Id);
// Retourner une réponse d'erreur
return StatusCode(400, ex.Message);
}
}
[HttpDelete("{id}")]
public async Task<ActionResult<TranslateDTO>> DeleteTranslate(long id)
{
try {
_logger.LogInformation("Deleting a Translate with id : {id}", id);
var Translate = await _service.Delete(id);
return Translate;
}
catch (Exception ex)
{
// Journaliser l'exception
_logger.LogError(ex, "Une erreur s'est produite lors de la suppression du Translate avec l'ID {id}.", id);
// Retourner une réponse d'erreur
return StatusCode(400, ex.Message);
}
}
[HttpPost]
public async Task<ActionResult<TranslateDTO>> AddTranslate([FromBody] TranslateDTO Translate)
{
try {
_logger.LogInformation("Adding a Translate with id : {id}", Translate.Id);
Translate.Id = _service.Gets(0,0).Result.TotalCount + 1;
var newTranslate = await _service.Add(Translate);
return newTranslate;
}
catch (Exception ex)
{
// Journaliser l'exception
_logger.LogError(ex, "Une erreur s'est produite lors de l'ajout du Translate avec l'ID {id}.", Translate.Id);
// Retourner une réponse d'erreur
return StatusCode(400, ex.Message);
}
}
[HttpPost("AddVocab")]
public async Task<ActionResult<VocabularyDTO>> AddVocab([FromQuery] string vocabId, long translateId)
{
try
{
_logger.LogInformation("Adding a Vocabulary to a Translate with id : {id}", translateId);
var newVocab = await _service.AddVocabToTranslate(vocabId, translateId);
return newVocab;
}
catch (Exception ex)
{
// Journaliser l'exception
_logger.LogError(ex, "Une erreur s'est produite lors de l'ajout du Vocabulary au Translate avec l'ID {id}.", translateId);
// Retourner une réponse d'erreur
return StatusCode(400, ex.Message);
}
}
}
}

@ -1,159 +0,0 @@

using DTO;
using DTOToEntity;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
namespace API.Controllers
{
[Authorize]
[ApiController]
[Route("api/v{version:apiVersion}/[controller]")]
[ApiVersion("1.0")]
public class UserController : ControllerBase
{
private readonly IUserService _service;
private readonly ILogger<UserController> _logger;
public UserController(IUserService userService, ILogger<UserController> logger)
{
_service = userService;
_logger = logger;
}
[HttpGet]
public async Task<ActionResult<PageResponse<UserDTO>>> GetUsers(int index,int count)
{
try
{
_logger.LogInformation("Getting Users ");
var users = await _service.Gets(index, count);
return users;
}
catch (Exception ex)
{
// Journaliser l'exception
_logger.LogError(ex, "Une erreur s'est produite lors de la récupération des utilisateurs.");
// Retourner une réponse d'erreur
return StatusCode(400, ex.Message);
}
}
[HttpPost]
public async Task<ActionResult<UserDTO>> AddUser([FromQuery] UserDTO user)
{
try
{
_logger.LogInformation("Adding a user with id : {id}", user.Id);
user.Id = _service.Gets(0, 0).Result.TotalCount + 1;
var newUser = await _service.Add(user);
return newUser;
}
catch (Exception ex)
{
// Journaliser l'exception
_logger.LogError(ex, "Une erreur s'est produite lors de l'ajout de l'utilisateur avec l'ID {id}.", user.Id);
// Retourner une réponse d'erreur
return StatusCode(400, ex.Message);
}
}
[HttpDelete("{id}")]
public async Task<ActionResult<UserDTO>> DeleteUser(long id)
{
try
{
_logger.LogInformation("Deleting a user with id : {id}", id);
var user = await _service.Delete(id);
return user;
}
catch (Exception ex)
{
// Journaliser l'exception
_logger.LogError(ex, "Une erreur s'est produite lors de la suppression de l'utilisateur avec l'ID {id}.", id);
// Retourner une réponse d'erreur
return StatusCode(400, ex.Message);
}
}
[HttpPut]
public async Task<ActionResult<UserDTO>> UpdateUser([FromQuery] UserDTO user)
{
try
{
_logger.LogInformation("Updating a user with id : {id}", user.Id);
var updatedUser = await _service.Update(user);
return updatedUser;
}
catch (Exception ex)
{
// Journaliser l'exception
_logger.LogError(ex, "Une erreur s'est produite lors de la mise à jour de l'utilisateur avec l'ID {id}.", user.Id);
// Retourner une réponse d'erreur
return StatusCode(400, ex.Message);
}
}
[HttpGet("{id}")]
public async Task<ActionResult<UserDTO>> GetUser(long id)
{
try
{
_logger.LogInformation("Getting a user with id {id}", id);
var user = await _service.GetById(id);
return user;
}
catch (Exception ex)
{
// Journaliser l'exception
_logger.LogError(ex, "Une erreur s'est produite lors de la récupération de l'utilisateur avec l'ID {id}.", id);
// Retourner une réponse d'erreur
return StatusCode(400, ex.Message);
}
}
[HttpGet("group/{group}")]
public async Task<ActionResult<PageResponse<UserDTO>>> GetUsersByGroup(int index, int count, int group)
{
try
{
_logger.LogInformation("Getting Users by group");
var users = await _service.GetByGroup(index, count, group);
return users;
}
catch (Exception ex)
{
// Journaliser l'exception
_logger.LogError(ex, "Une erreur s'est produite lors de la récupération des utilisateurs par groupe.");
// Retourner une réponse d'erreur
return StatusCode(400, ex.Message);
}
}
[HttpGet("role/{role}")]
public async Task<ActionResult<PageResponse<UserDTO>>> GetUsersByRole(int index, int count, string role)
{
try
{
_logger.LogInformation("Getting Users by role");
var users = await _service.GetByRole(index, count, role);
return users;
}
catch (Exception ex)
{
// Journaliser l'exception
_logger.LogError(ex, "Une erreur s'est produite lors de la récupération des utilisateurs par rôle.");
// Retourner une réponse d'erreur
return StatusCode(400, ex.Message);
}
}
}
}

@ -1,160 +0,0 @@

using DTO;
using DTOToEntity;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
namespace API.Controllers
{
[Authorize]
[ApiController]
[Route("api/v{version:apiVersion}/[controller]")]
[ApiVersion("1.0")]
public class VocabularyController : ControllerBase
{
private readonly IVocabularyService _service;
private readonly ILogger<VocabularyController> _logger;
public VocabularyController(IVocabularyService vocService, ILogger<VocabularyController> logger)
{
_service = vocService;
_logger = logger;
}
[HttpGet]
public async Task<ActionResult<PageResponse<VocabularyDTO>>> GetVocabularies(int index, int count)
{
try
{
_logger.LogInformation("Getting vocabularies ");
var vocabularies = await _service.Gets(index, count);
return vocabularies;
}
catch (Exception ex)
{
// Journaliser l'exception
_logger.LogError(ex, "Une erreur s'est produite lors de la récupération des vocabulaires.");
// Retourner une réponse d'erreur
return StatusCode(400, ex.Message);
}
}
[HttpGet("{word}")]
public async Task<ActionResult<VocabularyDTO>> GetVocabulary(string word)
{
try
{
_logger.LogInformation("Getting a vocabulary with id {id}", word);
var vocabulary = await _service.GetById(word);
return vocabulary;
}
catch (Exception ex)
{
// Journaliser l'exception
_logger.LogError(ex, "Une erreur s'est produite lors de la récupération du vocabulaire avec l'ID {word}.", word);
// Retourner une réponse d'erreur
return StatusCode(400, ex.Message);
}
}
[HttpPut]
public async Task<ActionResult<VocabularyDTO>> UpdateVocabulary([FromQuery] VocabularyDTO vocabulary)
{
try
{
_logger.LogInformation("Updating a vocabulary with word : {word}", vocabulary.word);
var updatedVocabulary = await _service.Update(vocabulary);
return updatedVocabulary;
}
catch (Exception ex)
{
// Journaliser l'exception
_logger.LogError(ex, "Une erreur s'est produite lors de la mise à jour du vocabulaire avec l'ID {word}.", vocabulary.word);
// Retourner une réponse d'erreur
return StatusCode(400, ex.Message);
}
}
[HttpDelete("{word}")]
public async Task<ActionResult<VocabularyDTO>> DeleteVocabulary(string word)
{
try
{
_logger.LogInformation("Deleting a vocabulary with word : {word}", word);
var vocabulary = await _service.Delete(word);
return vocabulary;
}
catch (Exception ex)
{
// Journaliser l'exception
_logger.LogError(ex, "Une erreur s'est produite lors de la suppression du vocabulaire avec l'ID {word}.", word);
// Retourner une réponse d'erreur
return StatusCode(400, ex.Message);
}
}
[HttpPost]
public async Task<ActionResult<VocabularyDTO>> AddVocabulary([FromQuery] VocabularyDTO vocabulary)
{
try
{
_logger.LogInformation("Adding a vocabulary with word : {word}", vocabulary.word);
var newVocabulary = await _service.Add(vocabulary);
return newVocabulary;
}
catch (Exception ex)
{
// Journaliser l'exception
_logger.LogError(ex, "Une erreur s'est produite lors de l'ajout du vocabulaire avec l'ID {word}.", vocabulary.word);
// Retourner une réponse d'erreur
return StatusCode(400, ex.Message);
}
}
[HttpGet("langue/{langue}")]
public async Task<ActionResult<PageResponse<VocabularyDTO>>> GetByLangue(string langue, int index, int count)
{
try
{
_logger.LogInformation("Getting vocabularies by langue {langue}",langue);
var vocabularies = await _service.GetByLangue(index, count, langue);
return vocabularies;
}
catch (Exception ex)
{
// Journaliser l'exception
_logger.LogError(ex, "Une erreur s'est produite lors de la récupération des vocabulaires par langue {langue}.",langue);
// Retourner une réponse d'erreur
return StatusCode(400, ex.Message);
}
}
[HttpPost("AddTranslation")]
public async Task<ActionResult<TranslateDTO>> AddTranslation([FromQuery] string vocId, long translationId)
{
try
{
_logger.LogInformation("Adding a translation with id : {id}", vocId);
var newVocabulary = await _service.AddTranslationToVocabulary(vocId, translationId);
return newVocabulary;
}
catch (Exception ex)
{
// Journaliser l'exception
_logger.LogError(ex, "Une erreur s'est produite lors de l'ajout de la traduction avec l'ID {id}.", vocId);
// Retourner une réponse d'erreur
return StatusCode(400, ex.Message);
}
}
}
}

@ -1,160 +0,0 @@

using DTO;
using DTOToEntity;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
namespace API.Controllers
{
[Authorize]
[ApiController]
[Route("api/v{version:apiVersion}/[controller]")]
[ApiVersion("1.0")]
public class VocabularyListController : ControllerBase
{
private readonly IVocabularyListService _service;
private readonly ILogger<VocabularyListController> _logger;
public VocabularyListController(IVocabularyListService vocService, ILogger<VocabularyListController> logger)
{
_service = vocService;
_logger = logger;
}
[HttpGet]
public async Task<ActionResult<PageResponse<VocabularyListDTO>>> GetVocabularyLists(int index, int count)
{
try
{
_logger.LogInformation("Getting VocabularyLists ");
var VocabularyLists = await _service.Gets(index, count);
return VocabularyLists;
}
catch (Exception ex)
{
// Journaliser l'exception
_logger.LogError(ex, "Une erreur s'est produite lors de la récupération des VocabularyLists.");
// Retourner une réponse d'erreur
return StatusCode(400, ex.Message);
}
}
[HttpGet("{id}")]
public async Task<ActionResult<VocabularyListDTO>> GetVocabularyList(long id)
{
try
{
_logger.LogInformation("Getting a GroupVocabularyList with id {id}", id);
var VocabularyList = await _service.GetById(id);
return VocabularyList;
}
catch (Exception ex)
{
// Journaliser l'exception
_logger.LogError(ex, "Une erreur s'est produite lors de la récupération du GroupVocabularyList avec l'ID {id}.", id);
// Retourner une réponse d'erreur
return StatusCode(400, ex.Message);
}
}
[HttpPut]
public async Task<ActionResult<VocabularyListDTO>> UpdateVocabularyList([FromQuery] VocabularyListDTO VocabularyList)
{
try
{
_logger.LogInformation("Updating a GroupVocabularyList with id : {id}", VocabularyList.Id);
var updatedVocabularyList = await _service.Update(VocabularyList);
return updatedVocabularyList;
}
catch (Exception ex)
{
// Journaliser l'exception
_logger.LogError(ex, "Une erreur s'est produite lors de la mise à jour du GroupVocabularyList avec l'ID {id}.", VocabularyList.Id);
// Retourner une réponse d'erreur
return StatusCode(400, ex.Message);
}
}
[HttpDelete("{id}")]
public async Task<ActionResult<VocabularyListDTO>> DeleteVocabularyList(long id)
{
try
{
_logger.LogInformation("Deleting a GroupVocabularyList with id : {id}", id);
var VocabularyList = await _service.Delete(id);
return VocabularyList;
}
catch (Exception ex)
{
// Journaliser l'exception
_logger.LogError(ex, "Une erreur s'est produite lors de la suppression du GroupVocabularyList avec l'ID {id}.", id);
// Retourner une réponse d'erreur
return StatusCode(400, ex.Message);
}
}
[HttpPost]
public async Task<ActionResult<VocabularyListDTO>> AddVocabularyList([FromQuery] VocabularyListDTO VocabularyList)
{
try
{
_logger.LogInformation("Adding a GroupVocabularyList with id : {id}", VocabularyList.Id);
VocabularyList.Id = _service.Gets(0, 0).Result.TotalCount + 1;
var newVocabularyList = await _service.Add(VocabularyList);
return newVocabularyList;
}
catch (Exception ex)
{
// Journaliser l'exception
_logger.LogError(ex, "Une erreur s'est produite lors de l'ajout du GroupVocabularyList avec l'ID {id}.", VocabularyList.Id);
// Retourner une réponse d'erreur
return StatusCode(400, ex.Message);
}
}
[HttpGet("user/{user}")]
public async Task<ActionResult<PageResponse<VocabularyListDTO>>> GetVocabularyListsByUser(int index, int count, int user)
{
try
{
_logger.LogInformation("Getting VocabularyLists by user {user}", user);
var VocabularyLists = await _service.GetByUser(index, count, user);
return VocabularyLists;
}
catch (Exception ex)
{
// Journaliser l'exception
_logger.LogError(ex, "Une erreur s'est produite lors de la récupération des VocabularyLists.");
// Retourner une réponse d'erreur
return StatusCode(400, ex.Message);
}
}
[HttpPost("AddGroup")]
public async Task<ActionResult<GroupDTO>> AddGroupToVocabularyList([FromQuery]long groupId, long vocabId)
{
try
{
_logger.LogInformation("Adding a group to a VocabularyList with id : {id}", vocabId);
var group = await _service.AddGroupToVocabularyList(groupId, vocabId);
return group;
}
catch (Exception ex)
{
// Journaliser l'exception
_logger.LogError(ex, "Une erreur s'est produite lors de l'ajout du groupe à la VocabularyList avec l'ID {id}.", vocabId);
// Retourner une réponse d'erreur
return StatusCode(400, ex.Message);
}
}
}
}

@ -1,30 +0,0 @@
#See https://aka.ms/customizecontainer to learn how to customize your debug container and how Visual Studio uses this Dockerfile to build your images for faster debugging.
FROM mcr.microsoft.com/dotnet/aspnet:8.0 AS base
USER app
WORKDIR /app
EXPOSE 8080
EXPOSE 8081
FROM mcr.microsoft.com/dotnet/sdk:8.0 AS build
ARG BUILD_CONFIGURATION=Release
WORKDIR /src
COPY ["API/API.csproj", "API/"]
COPY ["DTOToEntity/DTOToEntity.csproj", "DTOToEntity/"]
COPY ["DbContext/DbContextLib.csproj", "DbContext/"]
COPY ["Entities/Entities.csproj", "Entities/"]
COPY ["DTO/DTO.csproj", "DTO/"]
COPY ["StubbedContext/StubbedContextLib.csproj", "StubbedContext/"]
RUN dotnet restore "./API/./API.csproj"
COPY . .
WORKDIR "/src/API"
RUN dotnet build "./API.csproj" -c $BUILD_CONFIGURATION -o /app/build
FROM build AS publish
ARG BUILD_CONFIGURATION=Release
RUN dotnet publish "./API.csproj" -c $BUILD_CONFIGURATION -o /app/publish /p:UseAppHost=false
FROM base AS final
WORKDIR /app
COPY --from=publish /app/publish .
ENTRYPOINT ["dotnet", "API.dll"]

@ -1,117 +0,0 @@
using Microsoft.Extensions.Configuration;
using StubbedContextLib;
using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.SqlServer;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Entities;
using DTOToEntity;
using DTO;
using System;
using Microsoft.AspNetCore.Mvc;
using Microsoft.IdentityModel.Tokens;
using DbContextLib;
using Microsoft.AspNetCore.Authentication.JwtBearer;
using System.Text;
using Microsoft.OpenApi.Models;
var builder = WebApplication.CreateBuilder(args);
// Add services to the container.
builder.Services.AddControllers();
// Learn more about configuring Swagger/OpenAPI at https://aka.ms/aspnetcore/swashbuckle
builder.Services.AddEndpointsApiExplorer();
builder.Services.AddSwaggerGen();
builder.Services.AddDbContext<StubbedContext>(options =>
{
options.UseSqlServer(builder.Configuration.GetConnectionString("StubbedContext"));
});
builder.Services.AddSwaggerGen(option =>
{
option.SwaggerDoc("v1", new OpenApiInfo { Title = "Test API", Version = "v1" });
option.AddSecurityDefinition("Bearer", new OpenApiSecurityScheme
{
In = ParameterLocation.Header,
Description = "Please enter a valid token",
Name = "Authorization",
Type = SecuritySchemeType.Http,
BearerFormat = "JWT",
Scheme = "Bearer"
});
option.AddSecurityRequirement(new OpenApiSecurityRequirement
{
{
new OpenApiSecurityScheme
{
Reference = new OpenApiReference
{
Type=ReferenceType.SecurityScheme,
Id="Bearer"
}
},
new string[]{}
}
});
});
var validIssuer = builder.Configuration.GetValue<string>("JwtTokenSettings:ValidIssuer");
var validAudience = builder.Configuration.GetValue<string>("JwtTokenSettings:ValidAudience");
var symmetricSecurityKey = builder.Configuration.GetValue<string>("JwtTokenSettings:SymmetricSecurityKey");
builder.Services.AddAuthentication(options => {
options.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme;
options.DefaultChallengeScheme = JwtBearerDefaults.AuthenticationScheme;
//options.DefaultScheme = JwtBearerDefaults.AuthenticationScheme;
})
.AddJwtBearer(options =>
{
options.IncludeErrorDetails = true;
options.TokenValidationParameters = new TokenValidationParameters()
{
ValidateIssuer = true,
ValidateAudience = true,
ValidateLifetime = true,
ValidateIssuerSigningKey = true,
ValidIssuer = validIssuer,
ValidAudience = validAudience,
IssuerSigningKey = new SymmetricSecurityKey(
Encoding.UTF8.GetBytes(symmetricSecurityKey)
),
};
});
builder.Services.AddApiVersioning(o =>
{
o.DefaultApiVersion = new ApiVersion(1, 1);
o.AssumeDefaultVersionWhenUnspecified = true;
o.ReportApiVersions = true;
});
builder.Services.AddScoped<IGroupService, GroupService>();
builder.Services.AddScoped<IService<LangueDTO>,LangueService>();
builder.Services.AddScoped<IService<RoleDTO>,RoleService>();
builder.Services.AddScoped<ITranslateService,TranslateService>();
builder.Services.AddScoped<IUserService, UserService>();
builder.Services.AddScoped<IVocabularyService, VocabularyService>();
builder.Services.AddScoped<IVocabularyListService, VocabularyListService>();
var app = builder.Build();
// Configure the HTTP request pipeline.
if (app.Environment.IsDevelopment())
{
app.UseSwagger();
app.UseSwaggerUI();
}
app.UseAuthentication();
app.UseHttpsRedirection();
app.UseAuthorization();
app.MapControllers();
app.Run();

@ -1,52 +0,0 @@
{
"profiles": {
"http": {
"commandName": "Project",
"launchBrowser": true,
"launchUrl": "swagger",
"environmentVariables": {
"ASPNETCORE_ENVIRONMENT": "Development"
},
"dotnetRunMessages": true,
"applicationUrl": "http://localhost:5124"
},
"https": {
"commandName": "Project",
"launchBrowser": true,
"launchUrl": "swagger",
"environmentVariables": {
"ASPNETCORE_ENVIRONMENT": "Development"
},
"dotnetRunMessages": true,
"applicationUrl": "https://localhost:7013;http://localhost:5124"
},
"IIS Express": {
"commandName": "IISExpress",
"launchBrowser": true,
"launchUrl": "swagger",
"environmentVariables": {
"ASPNETCORE_ENVIRONMENT": "Development"
}
},
"Docker": {
"commandName": "Docker",
"launchBrowser": true,
"launchUrl": "{Scheme}://{ServiceHost}:{ServicePort}/swagger",
"environmentVariables": {
"ASPNETCORE_HTTPS_PORTS": "8081",
"ASPNETCORE_HTTP_PORTS": "8080"
},
"publishAllPorts": true,
"useSSL": true
}
},
"$schema": "http://json.schemastore.org/launchsettings.json",
"iisSettings": {
"windowsAuthentication": false,
"anonymousAuthentication": true,
"iisExpress": {
"applicationUrl": "http://localhost:32547",
"sslPort": 44345
}
}
}

@ -1,13 +0,0 @@
namespace API
{
public class WeatherForecast
{
public DateOnly Date { get; set; }
public int TemperatureC { get; set; }
public int TemperatureF => 32 + (int)(TemperatureC / 0.5556);
public string? Summary { get; set; }
}
}

@ -1,8 +0,0 @@
{
"Logging": {
"LogLevel": {
"Default": "Information",
"Microsoft.AspNetCore": "Warning"
}
}
}

@ -1,15 +0,0 @@
{
"Logging": {
"LogLevel": {
"Default": "Information",
"Microsoft.AspNetCore": "Warning"
}
},
"JwtTokenSettings": {
"ValidIssuer": "ExampleIssuer",
"ValidAudience": "ValidAudience",
"SymmetricSecurityKey": "fvh8456477hth44j6wfds98bq9hp8bqh9ubq9gjig3qr0[94vj5",
"JwtRegisteredClaimNamesSub": "345h098bb8reberbwr4vvb8945"
},
"AllowedHosts": "*"
}

@ -1,9 +0,0 @@
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<TargetFramework>net8.0</TargetFramework>
<ImplicitUsings>enable</ImplicitUsings>
<Nullable>enable</Nullable>
</PropertyGroup>
</Project>

@ -1,15 +0,0 @@
namespace DTO
{
public class GroupDTO
{
public long Id { get; set; }
public int Num { get; set; }
public int Year { get; set; }
public string sector { get; set; }
//public ICollection<UserDTO> Users { get; set; } = new List<UserDTO>();
//public ICollection<VocabularyListDTO> VocabularyList { get; set; } = new List<VocabularyListDTO>();
}
}

@ -1,16 +0,0 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace DTO
{
public class LangueDTO
{
public string
name { get; set; }
//public ICollection<VocabularyDTO> vocabularys { get; set; } = new List<VocabularyDTO>();
}
}

@ -1,15 +0,0 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace DTO
{
public class RoleDTO
{
public long Id { get; set; }
public string Name { get; set; }
//public ICollection<UserDTO> Users { get; set; } = new List<UserDTO>();
}
}

@ -1,22 +0,0 @@
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations.Schema;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace DTO
{
public class TranslateDTO
{
public long Id { get; set; }
[ForeignKey(nameof(WordsId))]
public string WordsId { get; set; }
//public ICollection<VocabularyDTO> Words { get; set; } = new List<VocabularyDTO>();
[ForeignKey(nameof(VocabularyListVocId))]
public long VocabularyListVocId { get; set; }
//public VocabularyListDTO VocabularyListVoc { get; set; } = null!;
}
}

@ -1,25 +0,0 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace DTO
{
public class UserDTO
{
public long Id { get; set; }
public string Password { get; set; }
public string Email { get; set; }
public string Name { get; set; }
public string UserName { get; set; }
public string NickName { get; set; }
public string? image { get; set; } = null;
public long GroupId { get; set; }
//public GroupDTO? Group { get; set; } = null;
public long RoleId { get; set; }
//public RoleDTO? Role { get; set; } = null!;
public Boolean ExtraTime { get; set; }
//public ICollection<VocabularyListDTO> VocabularyList { get; set; } = new List<VocabularyListDTO>();
}
}

@ -1,18 +0,0 @@
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations.Schema;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace DTO
{
public class VocabularyDTO
{
public string word { get; set; }
//public ICollection<TranslateDTO> translations { get; set; } = new List<TranslateDTO>();
public string LangueName { get; set; }
//public LangueDTO? Langue { get; set; } = null!;
}
}

@ -1,22 +0,0 @@
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations.Schema;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace DTO
{
public class VocabularyListDTO
{
public long Id { get; set; }
public string Name { get; set; }
public string Image { get; set; }
public long UserId { get; set; }
//public UserDTO User { get; set; } = null!;
//public ICollection<TranslateDTO> translation { get; set; } = new List<TranslateDTO>();
//public ICollection<GroupDTO> Groups { get; set; } = new List<GroupDTO>();
}
}

@ -1,16 +0,0 @@
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<TargetFramework>net8.0</TargetFramework>
<ImplicitUsings>enable</ImplicitUsings>
<Nullable>enable</Nullable>
</PropertyGroup>
<ItemGroup>
<ProjectReference Include="..\DbContext\DbContextLib.csproj" />
<ProjectReference Include="..\DTO\DTO.csproj" />
<ProjectReference Include="..\Entities\Entities.csproj" />
<ProjectReference Include="..\StubbedContext\StubbedContextLib.csproj" />
</ItemGroup>
</Project>

@ -1,146 +0,0 @@
using DbContextLib;
using DTO;
using Entities;
using Microsoft.EntityFrameworkCore;
using StubbedContextLib;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace DTOToEntity
{
public class GroupService : IGroupService
{
private readonly UnitOfWork context = new UnitOfWork();
public GroupService()
{
}
public GroupService(StubbedContext _context)
{
context = new UnitOfWork(_context);
}
public async Task<GroupDTO> Add(GroupDTO group)
{
if(group == null)
{
throw new ArgumentNullException();
}
GroupEntity groupEntity = group.ToEntity();
context.GroupRepository.Insert(groupEntity);
await context.SaveChangesAsync();
return groupEntity.ToDTO(); ;
}
public async Task<UserDTO> AddUserToGroup(long idUser, long idGroup)
{
var group = context.GroupRepository.GetById(idGroup);
if (group == null)
{
throw new Exception("Group not found");
}
var user = context.UserRepository.GetById(idUser);
if (user == null)
{
throw new Exception("User not found");
}
group.Users.Add(user);
await context.SaveChangesAsync();
return user.ToDTO();
}
public async Task<VocabularyListDTO> AddVocabularyListToGroup(long vocabId, long groupId)
{
var group = context.GroupRepository.GetById(groupId);
if (group == null)
{
throw new Exception("Group not found");
}
var vocab = context.VocabularyListRepository.GetById(vocabId);
if (vocab == null)
{
throw new Exception("VocabularyList not found");
}
group.GroupVocabularyList.Add(vocab);
await context.SaveChangesAsync();
return vocab.ToDTO();
}
public async Task<GroupDTO> Delete(object id)
{
var group = context.GroupRepository.GetById((long)id);
if (group != null)
{
context.GroupRepository.Delete(group);
await context.SaveChangesAsync();
}else
{
throw new Exception("Group not found");
}
return group.ToDTO();
}
public async Task<GroupDTO> GetById(object id)
{
var group = context.GroupRepository.GetById((long) id);
if (group == null)
{
throw new Exception("Group not found");
}
return group.ToDTO();
}
public async Task<PageResponse<GroupDTO>> GetByNum(int index, int count, int num)
{
var groups = context.GroupRepository.GetItems(filter: g => g.Num == num, index, count);
return new PageResponse<GroupDTO>(groups.ToList().Select(g => g.ToDTO()), context.GroupRepository.GetItems(0, 1000000000).Count());
}
public async Task<PageResponse<GroupDTO>> GetBySector(int index, int count, string sector)
{
var groups = context.GroupRepository.GetItems(filter: g => g.sector == sector, index, count);
return new PageResponse<GroupDTO>(groups.ToList().Select(g => g.ToDTO()), context.GroupRepository.GetItems(0, 100000000).Count());
}
public async Task<PageResponse<GroupDTO>> GetByYear(int index, int count, int year)
{
var groups = context.GroupRepository.GetItems(filter: g => g.year == year, index, count);
return new PageResponse<GroupDTO>(groups.ToList().Select(g => g.ToDTO()), context.GroupRepository.GetItems(0,100000000).Count());
}
public async Task<PageResponse<GroupDTO>> Gets(int index, int count)
{
IEnumerable<GroupEntity> groups = context.GroupRepository.GetItems(index,count);
return new PageResponse<GroupDTO>(groups.ToList().Select(g => g.ToDTO()), context.GroupRepository.GetItems(0, 1000000000).Count());
}
public async Task<GroupDTO> Update(GroupDTO group)
{
if(group == null)
{
throw new ArgumentNullException();
}
var existingGroup = context.GroupRepository.GetById(group.Id);
if (existingGroup == null)
{
throw new Exception("Group not found");
}
existingGroup.year = group.Year;
existingGroup.sector = group.sector;
existingGroup.Num = group.Num;
await context.SaveChangesAsync();
return existingGroup.ToDTO();
}
}
}

@ -1,20 +0,0 @@
using DTO;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace DTOToEntity
{
public interface IGroupService : IService<GroupDTO>
{
Task<PageResponse<GroupDTO>> GetByNum(int index, int count, int num);
Task<PageResponse<GroupDTO>> GetBySector(int index, int count, string sector);
Task<PageResponse<GroupDTO>> GetByYear(int index, int count, int year);
Task<UserDTO> AddUserToGroup(long idUser, long idGroup);
Task<VocabularyListDTO> AddVocabularyListToGroup(long vocabId, long groupId);
}
}

@ -1,18 +0,0 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using System.Text;
using System.Threading.Tasks;
namespace DTOToEntity
{
public interface IService<T>
{
Task<PageResponse<T>> Gets(int index, int count);
Task<T> GetById(object id);
Task<T> Add( T group);
Task<T> Delete(object id);
Task<T> Update(T group);
}
}

@ -1,14 +0,0 @@
using DTO;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace DTOToEntity
{
public interface ITranslateService : IService<TranslateDTO>
{
Task<VocabularyDTO> AddVocabToTranslate(string vocabId, long translateId);
}
}

@ -1,15 +0,0 @@
using DTO;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace DTOToEntity
{
public interface IUserService : IService<UserDTO>
{
Task<PageResponse<UserDTO>> GetByGroup(int index, int count, long group);
Task<PageResponse<UserDTO>> GetByRole(int index, int count, string role);
}
}

@ -1,16 +0,0 @@
using DTO;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace DTOToEntity
{
public interface IVocabularyListService : IService<VocabularyListDTO>
{
Task<PageResponse<VocabularyListDTO>> GetByUser(int index, int count, int user);
Task<GroupDTO> AddGroupToVocabularyList(long groupId, long vocabId);
}
}

@ -1,16 +0,0 @@
using DTO;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace DTOToEntity
{
public interface IVocabularyService : IService<VocabularyDTO>
{
Task<PageResponse<VocabularyDTO>> GetByLangue(int index, int count, string langue);
Task<TranslateDTO> AddTranslationToVocabulary(string vocabId, long translateId);
}
}

@ -1,74 +0,0 @@
using DbContextLib;
using DTO;
using Entities;
using Microsoft.EntityFrameworkCore;
using StubbedContextLib;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace DTOToEntity
{
public class LangueService : IService<LangueDTO>
{
private readonly UnitOfWork _context = new UnitOfWork();
public LangueService() { }
public LangueService(StubbedContext context)
{
this._context = new UnitOfWork(context);
}
public async Task<LangueDTO> Add(LangueDTO langue)
{
var langueEntity = langue.ToEntity();
_context.LangueRepository.Insert(langueEntity);
await _context.SaveChangesAsync();
return langue;
}
public async Task<LangueDTO> Delete(object id)
{
var langue = _context.LangueRepository.GetById(id);
if (langue != null)
{
_context.LangueRepository.Delete(langue);
await _context.SaveChangesAsync();
}
else {
throw new Exception("Langue not found");
}
return langue.ToDTO();
}
public async Task<LangueDTO> GetById(object id)
{
var langue = _context.LangueRepository.GetById(id);
if (langue == null)
{
throw new Exception("Langue not found");
}
return langue.ToDTO();
}
public async Task<PageResponse<LangueDTO>> Gets(int index,int count)
{
IEnumerable<LangueEntity> langues = _context.LangueRepository.GetItems(index, count);
return new PageResponse<LangueDTO>(langues.ToList().Select(l => l.ToDTO()), _context.LangueRepository.GetItems(0, 1000000000).Count());
}
public async Task<LangueDTO> Update(LangueDTO langue)
{
LangueEntity? langueToUpdate = _context.LangueRepository.GetById(langue.name);
if (langueToUpdate == null)
{
throw new Exception("Langue not found");
}
//langueToUpdate.vocabularys = (ICollection<VocabularyEntity>)langue.vocabularys.Select(v => v.ToEntity());
return langueToUpdate.ToDTO();
}
}
}

@ -1,20 +0,0 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace DTOToEntity
{
public class PageResponse<T>
{
public IEnumerable<T> Items { get; set; }
public long TotalCount { get; set; }
public PageResponse(IEnumerable<T> items, int totalCount)
{
Items = items;
TotalCount = totalCount;
}
}
}

@ -1,81 +0,0 @@
using DbContextLib;
using DTO;
using Entities;
using Microsoft.EntityFrameworkCore;
using StubbedContextLib;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace DTOToEntity
{
public class RoleService : IService<RoleDTO>
{
private readonly UnitOfWork _context = new UnitOfWork();
public RoleService() { }
public RoleService(StubbedContext context)
{
_context = new UnitOfWork(context);
}
public RoleService(UnitOfWork context)
{
_context = context;
}
public async Task<RoleDTO> Add(RoleDTO role)
{
var roleEntity = role.ToEntity();
_context.RoleRepository.Insert(roleEntity);
await _context.SaveChangesAsync();
return role;
}
public async Task<RoleDTO> Delete(object id)
{
RoleEntity role = _context.RoleRepository.GetById((long)id);
if (role == null)
{
throw new Exception("Role not found");
}
_context.RoleRepository.Delete((long)id);
await _context.SaveChangesAsync();
return role.ToDTO();
}
public async Task<RoleDTO> GetById(object id)
{
RoleEntity? role = _context.RoleRepository.GetById((long)id);
if (role == null)
{
throw new Exception("Role not found");
}
return role.ToDTO();
}
public async Task<PageResponse<RoleDTO>> Gets(int index, int count)
{
IEnumerable<RoleEntity> roles = _context.RoleRepository.GetItems(index, count);
return new PageResponse<RoleDTO>(roles.ToList().Select(r => r.ToDTO()), _context.RoleRepository.GetItems(0,1000000000).Count());
}
public async Task<RoleDTO> Update(RoleDTO role)
{
if (role == null)
{
throw new ArgumentNullException();
}
var roleEntity = _context.RoleRepository.GetById(role.Id);
if (roleEntity != null)
{
throw new Exception("role not found");
}
roleEntity.Name = role.Name;
_context.RoleRepository.Update(roleEntity);
await _context.SaveChangesAsync();
return roleEntity.ToDTO();
}
}
}

@ -1,98 +0,0 @@
using DbContextLib;
using DTO;
using Microsoft.EntityFrameworkCore;
using StubbedContextLib;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace DTOToEntity
{
public class TranslateService : ITranslateService
{
private readonly UnitOfWork _context = new UnitOfWork();
public TranslateService() { }
public TranslateService(StubbedContext context)
{
_context = new UnitOfWork(context);
}
public async Task<TranslateDTO> Add(TranslateDTO translate)
{
var translateEntity = translate.ToEntity();
_context.TranslateRepository.Insert(translateEntity);
await _context.SaveChangesAsync();
return translateEntity.ToDTO();
}
public async Task<VocabularyDTO> AddVocabToTranslate(string vocabId, long translateId)
{
var vocab = _context.VocabularyRepository.GetById(vocabId);
if (vocab == null)
{
throw new Exception("Vocabulary not found");
}
var translate = _context.TranslateRepository.GetById(translateId);
if (translate == null)
{
throw new Exception("Translate not found");
}
translate.TransVoc.Add(vocab);
await _context.SaveChangesAsync();
return vocab.ToDTO();
}
public async Task<TranslateDTO> Delete(object id)
{
var translate = _context.TranslateRepository.GetById((long)id);
if (translate != null)
{
_context.TranslateRepository.Delete(translate);
await _context.SaveChangesAsync();
}
else
{
throw new Exception("Translate not found");
}
return translate.ToDTO();
}
public async Task<TranslateDTO> GetById(object id)
{
var translate = _context.TranslateRepository.GetById((long)id);
if (translate == null)
{
throw new Exception("Translate not found");
}
return translate.ToDTO();
}
public async Task<PageResponse<TranslateDTO>> Gets(int index, int count)
{
var translates = _context.TranslateRepository.GetItems(index, count);
if(translates == null)
{
throw new Exception("No translates found");
}
return new PageResponse<TranslateDTO>( translates.Select(t => t.ToDTO()), _context.TranslateRepository.GetItems(0, 100000000).Count());
}
public async Task<TranslateDTO> Update(TranslateDTO translate)
{
var translateEntity = _context.TranslateRepository.GetById(translate.Id);
if (translateEntity == null)
{
throw new Exception("Translate not found");
}
translateEntity.WordsId = translate.WordsId;
translateEntity.VocabularyListVocId = translate.VocabularyListVocId;
_context.TranslateRepository.Update(translateEntity);
await _context.SaveChangesAsync();
return translateEntity.ToDTO();
}
}
}

@ -1,104 +0,0 @@
using DbContextLib;
using DTO;
using Entities;
using Microsoft.EntityFrameworkCore;
using StubbedContextLib;
using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace DTOToEntity
{
public class UserService : IUserService
{
private UnitOfWork _context = new UnitOfWork();
public UserService() { }
public UserService(StubbedContext context)
{
_context = new UnitOfWork(context);
}
public async Task<UserDTO> Add(UserDTO user)
{
UserEntity userEntity = user.ToEntity();
if(userEntity == null)
{
throw new Exception("User Entity is null");
}
_context.UserRepository.Insert(userEntity);
await _context.SaveChangesAsync();
return user;
}
public async Task<UserDTO> Delete(object id)
{
UserEntity? user = _context.UserRepository.GetById((long)id);
if(user == null)
{
throw new Exception("User not found");
}
_context.UserRepository.Delete((long)id);
await _context.SaveChangesAsync();
return user.ToDTO();
}
public async Task<PageResponse<UserDTO>> GetByGroup(int index, int count, long group)
{
var users = _context.UserRepository.GetItems(index,count).Where(u => u.GroupId == group);
return new PageResponse<UserDTO>(users.Select(u => u.ToDTO()), _context.UserRepository.GetItems(0,1000000000).Count());
}
public async Task<UserDTO> GetById(object id)
{
var user = _context.UserRepository.GetById((long)id);
if(user == null)
{
throw new Exception("User not found");
}
return user.ToDTO();
}
public async Task<PageResponse<UserDTO>> GetByRole(int index, int count, string role)
{
var users = _context.UserRepository.GetItems(filter: u => u.Role != null && u.Role.Name == role,
index: index,
count: count);
return new PageResponse<UserDTO>(users.Select(u => u.ToDTO()), _context.UserRepository.GetItems(0, 1000000000).Count());
}
public async Task<PageResponse<UserDTO>> Gets(int index, int count)
{
IEnumerable<UserEntity> users = _context.UserRepository.GetItems(index, count) ;
return new PageResponse<UserDTO>( users.Select(u => u.ToDTO()),_context.UserRepository.GetItems(0, 1000000000).Count());
}
public async Task<UserDTO> Update(UserDTO user)
{
if(user == null)
{
throw new Exception("User is null");
}
var existingUser = _context.UserRepository.GetById(user.Id);
if(existingUser == null)
{
throw new Exception("User not found");
}
existingUser.image = user.image;
existingUser.Name = user.Name;
existingUser.Password = user.Password;
existingUser.NickName = user.NickName;
existingUser.Email = user.Email;
existingUser.RoleId = user.RoleId;
existingUser.GroupId = user.GroupId;
existingUser.UserName = user.UserName;
existingUser.ExtraTime = user.ExtraTime;
await _context.SaveChangesAsync();
return existingUser.ToDTO();
}
}
}

@ -1,101 +0,0 @@
using DbContextLib;
using DTO;
using Microsoft.EntityFrameworkCore;
using StubbedContextLib;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace DTOToEntity
{
public class VocabularyListService : IVocabularyListService
{
private UnitOfWork _context = new UnitOfWork();
public VocabularyListService()
{
}
public VocabularyListService(StubbedContext context)
{
_context = new UnitOfWork(context);
}
public async Task<VocabularyListDTO> Add(VocabularyListDTO group)
{
var groupEntity = group.ToEntity();
_context.VocabularyListRepository.Insert(groupEntity);
await _context.SaveChangesAsync();
return groupEntity.ToDTO();
}
public async Task<GroupDTO> AddGroupToVocabularyList(long groupId, long vocabId)
{
var group = _context.GroupRepository.GetById(groupId);
if (group == null)
{
throw new Exception("Group not found");
}
var vocab = _context.VocabularyListRepository.GetById(vocabId);
if (vocab == null)
{
throw new Exception("Vocabulary List not found");
}
vocab.VocsGroups.Add(group);
await _context.SaveChangesAsync();
return group.ToDTO();
}
public async Task<VocabularyListDTO> Delete(object id)
{
var group = _context.VocabularyListRepository.GetById((long)id);
if (group != null)
{
_context.VocabularyListRepository.Delete(group);
await _context.SaveChangesAsync();
}
else
{
throw new Exception("Group not found");
}
return group.ToDTO();
}
public async Task<VocabularyListDTO> GetById(object id)
{
var group = _context.VocabularyListRepository.GetById((long)id);
if (group == null)
{
throw new Exception("Group not found");
}
return group.ToDTO();
}
public async Task<PageResponse<VocabularyListDTO>> GetByUser(int index, int count, int user)
{
var groups = _context.VocabularyListRepository.GetItems(filter: u => u.Id == user, index, count);
return new PageResponse<VocabularyListDTO>(groups.Select(g => g.ToDTO()), _context.VocabularyListRepository.GetItems(0,1000000000).Count());
}
public async Task<PageResponse<VocabularyListDTO>> Gets(int index, int count)
{
var groups = _context.VocabularyListRepository.GetItems(index, count);
return new PageResponse<VocabularyListDTO>(groups.Select(g => g.ToDTO()), _context.VocabularyListRepository.GetItems(0, 1000000000).Count());
}
public async Task<VocabularyListDTO> Update(VocabularyListDTO group)
{
var groupEntity = group.ToEntity();
if (groupEntity == null)
{
throw new Exception("Group Entity is null");
}
_context.VocabularyListRepository.Update(groupEntity);
await _context.SaveChangesAsync();
return group;
}
}
}

@ -1,105 +0,0 @@
using DbContextLib;
using DTO;
using Entities;
using Microsoft.EntityFrameworkCore;
using StubbedContextLib;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace DTOToEntity
{
public class VocabularyService : IVocabularyService
{
private readonly UnitOfWork _context = new UnitOfWork();
public VocabularyService() { }
public VocabularyService(StubbedContext context)
{
_context = new UnitOfWork(context);
}
public async Task<VocabularyDTO> Add(VocabularyDTO vocabulary)
{
var vocabularyEntity = vocabulary.ToEntity();
if(vocabularyEntity == null)
{
throw new ArgumentNullException();
}
_context.VocabularyRepository.Insert(vocabularyEntity);
await _context.SaveChangesAsync();
return vocabularyEntity.ToDTO();
}
public async Task<TranslateDTO> AddTranslationToVocabulary(string vocabId, long translateId)
{
var vocabulary = _context.VocabularyRepository.GetById(vocabId);
if(vocabulary == null)
{
throw new Exception("Vocabulary not found");
}
var translate = _context.TranslateRepository.GetById(translateId);
if(translate == null)
{
throw new Exception("Translate not found");
}
vocabulary.Voctranslations.Add(translate);
await _context.SaveChangesAsync();
return translate.ToDTO();
}
public async Task<VocabularyDTO> Delete(object id)
{
var vocabulary = _context.VocabularyRepository.GetById((string)id);
if(vocabulary == null)
{
throw new Exception("Vocabulary not found");
}
_context.VocabularyRepository.Delete(vocabulary);
await _context.SaveChangesAsync();
return vocabulary.ToDTO();
}
public async Task<VocabularyDTO> GetById(object id)
{
var vocabulary = _context.VocabularyRepository.GetById((string)id);
if(vocabulary == null)
{
throw new Exception("Vocabulary not found");
}
return vocabulary.ToDTO();
}
public async Task<PageResponse<VocabularyDTO>> GetByLangue(int index, int count, string langue)
{
var vocabularies = _context.VocabularyRepository.GetItems(filter: v => v.LangueName == langue, index, count);
return new PageResponse<VocabularyDTO>(vocabularies.ToList().Select(v => v.ToDTO()), _context.VocabularyRepository.GetItems(0,100000000).Count());
}
public async Task<PageResponse<VocabularyDTO>> Gets(int index, int count)
{
var vocabulary = _context.VocabularyRepository.GetItems(index, count);
return new PageResponse<VocabularyDTO>(vocabulary.Select(v => v.ToDTO()), _context.VocabularyRepository.GetItems(0, 100000000).Count());
}
public async Task<VocabularyDTO> Update(VocabularyDTO vocabulary)
{
VocabularyEntity vocabularyEntity = vocabulary.ToEntity();
if(vocabularyEntity == null)
{
throw new Exception("vocabulary not valid");
}
var VocabToUpdate = _context.VocabularyRepository.GetById(vocabulary.word);
if(VocabToUpdate == null)
{
throw new Exception("vocabulary not found");
}
VocabToUpdate.LangueName = vocabularyEntity.LangueName;
await _context.SaveChangesAsync();
return vocabularyEntity.ToDTO();
}
}
}

@ -1,172 +0,0 @@
using DTO;
using Entities;
namespace DTOToEntity
{
public static class Extensions
{
public static GroupEntity ToEntity( this GroupDTO group)
{
return new GroupEntity
{
Id = group.Id,
Num = group.Num,
year = group.Year,
sector = group.sector,
//Users = group.Users.Select(u => u.ToEntity()).ToList(),
//GroupVocabularyList = group.GroupVocabularyList.Select(v => v.ToEntity()).ToList()
};
}
public static GroupDTO ToDTO(this GroupEntity group)
{
return new GroupDTO
{
Id = group.Id,
Num = group.Num,
Year = group.year,
sector = group.sector,
//Users = group.Users.Select(u => u.ToDTO()).ToList(),
//GroupVocabularyList = group.GroupVocabularyList.Select(v => v.ToDTO()).ToList()
};
}
public static LangueEntity ToEntity(this LangueDTO langue)
{
return new LangueEntity
{
name = langue.name,
//vocabularys = langue.vocabularys.Select(v => v.ToEntity()).ToList()
};
}
public static LangueDTO ToDTO(this LangueEntity langue)
{
return new LangueDTO
{
name = langue.name,
//vocabularys = langue.vocabularys.Select(v => v.ToDTO()).ToList()
};
}
public static RoleEntity ToEntity(this RoleDTO role)
{
return new RoleEntity
{
Id = role.Id,
Name = role.Name,
//Users = role.Users.Select(u => u.ToEntity()).ToList()
};
}
public static RoleDTO ToDTO(this RoleEntity role)
{
return new RoleDTO
{
Id = role.Id,
Name = role.Name,
//Users = role.Users.Select(u => u.ToDTO()).ToList()
};
}
public static TranslateEntity ToEntity(this TranslateDTO translate)
{
return new TranslateEntity
{
Id = translate.Id,
WordsId = translate.WordsId,
//TransVoc = translate.TransVoc.Select(w => w.ToEntity()).ToList(),
//VocabularyListVoc = translate.VocabularyListVoc.ToEntity(),
VocabularyListVocId = translate.VocabularyListVocId,
};
}
public static TranslateDTO ToDTO(this TranslateEntity translate)
{
return new TranslateDTO
{
Id = translate.Id,
WordsId = translate.WordsId,
//TransVoc = translate.TransVoc.Select(w => w.ToDTO()).ToList(),
//VocabularyListVoc = translate.VocabularyListVoc.ToDTO(),
VocabularyListVocId = translate.VocabularyListVocId,
};
}
public static UserEntity ToEntity(this UserDTO user)
{
return new UserEntity
{
Id = user.Id,
Name = user.Name,
Email = user.Email,
UserName = user.UserName,
NickName = user.NickName,
image = user.image,
Password = user.Password,
GroupId = user.GroupId,
RoleId = user.RoleId,
ExtraTime = user.ExtraTime
//Group = user.Group.ToEntity(),
//Role = user.Role.ToEntity()
};
}
public static UserDTO ToDTO(this UserEntity user)
{
return new UserDTO
{
Id = user.Id,
Name = user.Name,
Email = user.Email,
UserName = user.UserName,
NickName = user.NickName,
image = user.image,
Password = user.Password,
GroupId = user.GroupId,
RoleId = user.RoleId,
ExtraTime = user.ExtraTime,
//Group = user.Group.ToDTO(),
//Role = user.Role.ToDTO()
};
}
public static VocabularyEntity ToEntity(this VocabularyDTO vocabulary)
{
return new VocabularyEntity
{
word = vocabulary.word,
//Voctranslations = vocabulary.Voctranslations.Select(t => t.ToEntity()).ToList(),
LangueName = vocabulary.LangueName,
//Langue = vocabulary.Langue.ToEntity()
};
}
public static VocabularyDTO ToDTO(this VocabularyEntity vocabulary)
{
return new VocabularyDTO
{
word = vocabulary.word,
//Voctranslations = vocabulary.Voctranslations.Select(t => t.ToDTO()).ToList(),
LangueName = vocabulary.LangueName,
//Langue = vocabulary.Langue.ToDTO()
};
}
public static VocabularyListEntity ToEntity(this VocabularyListDTO vocabularyList)
{
return new VocabularyListEntity
{
Id = vocabularyList.Id,
Name = vocabularyList.Name,
Image = vocabularyList.Image,
UserId = vocabularyList.UserId,
//translations = vocabularyList.translations.Select(t => t.ToEntity()).ToList(),
//VocsGroups = vocabularyList.VocsGroups.Select(g => g.ToEntity()).ToList()
};
}
public static VocabularyListDTO ToDTO(this VocabularyListEntity vocabularyList)
{
return new VocabularyListDTO
{
Id = vocabularyList.Id,
Name = vocabularyList.Name,
Image = vocabularyList.Image,
UserId = vocabularyList.UserId,
//translations = vocabularyList.translations.Select(t => t.ToDTO()).ToList(),
//VocsGroups = vocabularyList.VocsGroups.Select(g => g.ToDTO()).ToList()
};
}
}
}

@ -1,24 +0,0 @@
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<TargetFramework>net8.0</TargetFramework>
<ImplicitUsings>enable</ImplicitUsings>
<Nullable>enable</Nullable>
<StartWorkingDirectory>$(MSBuildProjectDirectory)</StartWorkingDirectory>
</PropertyGroup>
<ItemGroup>
<PackageReference Include="Microsoft.EntityFrameworkCore" Version="8.0.1" />
<PackageReference Include="Microsoft.EntityFrameworkCore.Sqlite" Version="8.0.1" />
<PackageReference Include="Microsoft.EntityFrameworkCore.SqlServer" Version="8.0.1" />
<PackageReference Include="Microsoft.EntityFrameworkCore.Tools" Version="8.0.1">
<PrivateAssets>all</PrivateAssets>
<IncludeAssets>runtime; build; native; contentfiles; analyzers; buildtransitive</IncludeAssets>
</PackageReference>
</ItemGroup>
<ItemGroup>
<ProjectReference Include="..\Entities\Entities.csproj" />
</ItemGroup>
</Project>

@ -1,33 +0,0 @@
using System.Collections.Generic;
using Entities;
using Microsoft.EntityFrameworkCore;
namespace DbContextLib
{
public class SAEContext : DbContext
{
// DbSet<BookEntity> est une propriété dans le contexte de base de données (DbContext) qui représente une table de livres dans la base de données.
public DbSet<UserEntity> Users { get; set; }
public DbSet<GroupEntity> Groups { get; set; }
public DbSet<LangueEntity> Langues { get; set; }
public DbSet<RoleEntity> Roles { get; set; }
public DbSet<TranslateEntity> Translates { get; set; }
public DbSet<VocabularyEntity> Vocabularys { get; set; }
public DbSet<VocabularyListEntity> VocabularyLists { get; set; }
//permet de créer une base de donnée (fichier .db) ici en Sqlite avec le nom Db.Books.db
public SAEContext(DbContextOptions<SAEContext> options): base(options)
{
}
public SAEContext()
{
}
protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
{
if (!optionsBuilder.IsConfigured)
optionsBuilder.UseSqlite($"Data Source=Db.in_english_please.db");
}
}
}

@ -1,19 +0,0 @@
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<TargetFramework>net8.0</TargetFramework>
<ImplicitUsings>enable</ImplicitUsings>
<Nullable>enable</Nullable>
</PropertyGroup>
<ItemGroup>
<PackageReference Include="Microsoft.EntityFrameworkCore" Version="8.0.1" />
<PackageReference Include="Microsoft.EntityFrameworkCore.Sqlite" Version="8.0.1" />
<PackageReference Include="Microsoft.EntityFrameworkCore.SqlServer" Version="8.0.1" />
<PackageReference Include="Microsoft.EntityFrameworkCore.Tools" Version="8.0.1">
<PrivateAssets>all</PrivateAssets>
<IncludeAssets>runtime; build; native; contentfiles; analyzers; buildtransitive</IncludeAssets>
</PackageReference>
</ItemGroup>
</Project>

@ -1,23 +0,0 @@
using System.ComponentModel.DataAnnotations;
namespace Entities
{
public class GroupEntity
{
[Key]
public long Id { get; set; }
public int Num { get; set; }
public int year { get; set; }
public string sector { get; set; }
public ICollection<UserEntity> Users { get; set; } = new List<UserEntity>();
public ICollection<VocabularyListEntity> GroupVocabularyList { get; set; } = new List<VocabularyListEntity>();
public string toString()
{
return "Id: " + Id + " Num: " + Num + " year: " + year + " sector: " + sector;
}
}
}

@ -1,18 +0,0 @@
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Entities
{
public class LangueEntity
{
[Key]
public string name { get; set; }
public ICollection<VocabularyEntity> vocabularys { get; set; } = new List<VocabularyEntity>();
}
}

@ -1,21 +0,0 @@
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Entities
{
public class RoleEntity
{
public long Id { get; set; }
public string Name { get; set; }
public ICollection<UserEntity> Users { get; set; } = new List<UserEntity>();
public string toString()
{
return Id +" " + Name;
}
}
}

@ -1,28 +0,0 @@
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations.Schema;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Entities
{
public class TranslateEntity
{
[DatabaseGenerated(DatabaseGeneratedOption.Identity)]
public long Id { get; set; }
[ForeignKey(nameof(WordsId))]
public string WordsId { get; set; }
public ICollection<VocabularyEntity> TransVoc { get; set; } = new List<VocabularyEntity>();
[ForeignKey(nameof(VocabularyListVocId))]
public long VocabularyListVocId { get; set; }
public VocabularyListEntity? VocabularyListVoc { get; set; } = null!;
public string toString()
{
return "Id : " + Id +" wordId : " + WordsId + " VocabularyListVocId : " + VocabularyListVocId ;
}
}
}

@ -1,40 +0,0 @@
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.ComponentModel.DataAnnotations.Schema;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Entities
{
public class UserEntity
{
public long Id { get; set; }
public string Password { get; set; }
public string Email { get; set; }
public string Name { get; set; }
public string UserName { get; set; }
public string NickName { get; set; }
public string? image { get; set; } = null;
[ForeignKey(nameof(GroupId))]
public long GroupId { get; set; }
public GroupEntity? Group { get; set; } = null;
[ForeignKey(nameof(RoleId))]
public long RoleId { get; set; }
public RoleEntity? Role { get; set; } = null;
public Boolean ExtraTime { get; set; }
public ICollection<VocabularyListEntity> VocabularyList { get; set; } = new List<VocabularyListEntity>();
public string toString()
{
return "Id: " + Id + " Password: " + Password + " Email: " + Email + " Name: " + Name + " UserName: " + UserName + " NickName: " + NickName + " GroupId: " + GroupId + " RoleId: " + RoleId + " ExtraTime: " + ExtraTime;
}
}
}

@ -1,28 +0,0 @@
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.ComponentModel.DataAnnotations.Schema;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Entities
{
public class VocabularyEntity
{
[Key]
[DatabaseGenerated(DatabaseGeneratedOption.None)]
public string word { get; set; }
public ICollection<TranslateEntity> Voctranslations { get; set; } = new List<TranslateEntity>();
[ForeignKey(nameof(LangueName))]
public string LangueName { get; set; }
public LangueEntity? Langue { get; set; } = null!;
public string toString()
{
return word + " " + LangueName ;
}
}
}

@ -1,28 +0,0 @@
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations.Schema;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Entities
{
public class VocabularyListEntity
{
public long Id { get; set; }
public string Name { get; set; }
public string Image { get; set; }
[ForeignKey(nameof(UserId))]
public long UserId { get; set; }
public UserEntity? User { get; set; } = null;
public ICollection<TranslateEntity> translations { get; set; } = new List<TranslateEntity>();
public ICollection<GroupEntity> VocsGroups { get; set; } = new List<GroupEntity>();
public string toString()
{
return "Id : " + Id + " Name : " + Name + " Image : " + Image + " UserId : " + UserId;
}
}
}

@ -1,15 +0,0 @@
namespace Modele
{
public class Group
{
public int Id { get; set; }
public int Num { get; set; }
public int year { get; set; }
public string sector { get; set; }
public ICollection<User> Users { get; set; } = new List<User>();
public ICollection<VocabularyList> VocabularyList { get; set; } = new List<VocabularyList>();
}
}

@ -1,18 +0,0 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Modele
{
public interface IDataManager<T>
{
Task<IEnumerable<T>> Gets();
Task<T> GetById(int id);
Task<T> AddGroup(T group);
Task<T> DeleteGroup(int id);
Task<T> UpdateGroup(T group);
}
}

@ -1,15 +0,0 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Modele
{
public class Langue
{
public string name { get; set; }
public ICollection<Vocabulary> vocabularys { get; set; } = new List<Vocabulary>();
}
}

@ -1,9 +0,0 @@
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<TargetFramework>net8.0</TargetFramework>
<ImplicitUsings>enable</ImplicitUsings>
<Nullable>enable</Nullable>
</PropertyGroup>
</Project>

@ -1,15 +0,0 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Modele
{
public class Role
{
public int Id { get; set; }
public string Name { get; set; }
public ICollection<User> Users { get; set; } = new List<User>();
}
}

@ -1,20 +0,0 @@
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations.Schema;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Modele
{
public class Translate
{
public int Id { get; set; }
[ForeignKey(nameof(WordsId))]
public string WordsId { get; set; }
public ICollection<Vocabulary> Words { get; set; } = new List<Vocabulary>();
public long VocabularyListVocId { get; set; }
public VocabularyList VocabularyListVoc { get; set; } = null!;
}
}

@ -1,25 +0,0 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Modele
{
public class User
{
public long Id { get; set; }
public string Password { get; set; }
public string Email { get; set; }
public string Name { get; set; }
public string UserName { get; set; }
public string NickName { get; set; }
public string? image { get; set; } = null;
public long GroupId { get; set; }
public Group? Group { get; set; } = null;
public long RoleId { get; set; }
public Role? Role { get; set; } = null!;
public Boolean ExtraTime { get; set; }
public ICollection<VocabularyList> VocabularyList { get; set; } = new List<VocabularyList>();
}
}

@ -1,18 +0,0 @@
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations.Schema;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Modele
{
public class Vocabulary
{
public string word { get; set; }
public ICollection<Translate> translations { get; } = new List<Translate>();
public string LangueName { get; set; }
public Langue? Langue { get; set; } = null!;
}
}

@ -1,21 +0,0 @@
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations.Schema;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Modele
{
public class VocabularyList
{
public int Id { get; set; }
public string Name { get; set; }
public string Image { get; set; }
public long UserId { get; set; }
public User User { get; set; } = null!;
public ICollection<Translate> translation { get; set; } = new List<Translate>();
public ICollection<Group> Groups { get; set; } = new List<Group>();
}
}

@ -1,38 +0,0 @@
using DbContextLib;
using DTO;
using Modele;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ModeleToDTO
{
public class GroupDataManager(LibraryContext _context) : IModele2DTO<GroupDTO, Group>
{
public Task<GroupDTO> Add(Group group)
{
throw new NotImplementedException();
}
public Task<GroupDTO> Delete(int id)
{
throw new NotImplementedException();
}
public Task<GroupDTO> GetById(int id)
{
throw new NotImplementedException();
}
public Task<IEnumerable<GroupDTO>> Gets()
{
throw new NotImplementedException();
}
public Task<GroupDTO> Update(Group group)
{
throw new NotImplementedException();
}
}
}

@ -1,13 +0,0 @@
namespace ModeleToDTO
{
public interface IModele2DTO<T, TModele>
{
Task<IEnumerable<T>> Gets();
Task<T> GetById(int id);
Task<T> Add(TModele group);
Task<T> Delete(int id);
Task<T> Update(TModele group);
}
}

@ -1,15 +0,0 @@
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<TargetFramework>net8.0</TargetFramework>
<ImplicitUsings>enable</ImplicitUsings>
<Nullable>enable</Nullable>
</PropertyGroup>
<ItemGroup>
<ProjectReference Include="..\DbContext\DbContextLib.csproj" />
<ProjectReference Include="..\DTO\DTO.csproj" />
<ProjectReference Include="..\Modele\Modele.csproj" />
</ItemGroup>
</Project>

@ -1,13 +0,0 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ModeleToDTO
{
public class extensions
{
}
}

@ -1,167 +0,0 @@
using Entities;
using Modele;
namespace ModeleToEntities
{
public static class Extensions
{
public static GroupEntity ToEntity(this Group group)
{
return new GroupEntity
{
Id = group.Id,
Num = group.Num,
year = group.year,
sector = group.sector,
VocabularyList = group.VocabularyList.Select(v => v.ToEntity()).ToList()
};
}
public static Group ToModel(this GroupEntity group)
{
return new Group
{
Id = group.Id,
Num = group.Num,
year = group.year,
sector = group.sector,
VocabularyList = group.VocabularyList.Select(v => v.ToModel()).ToList()
};
}
public static VocabularyListEntity ToEntity(this VocabularyList vocabularyList)
{
return new VocabularyListEntity
{
Id = vocabularyList.Id,
Name = vocabularyList.Name,
Image = vocabularyList.Image,
UserId = vocabularyList.UserId,
translation = vocabularyList.translation.Select(t => t.ToEntity()).ToList(),
Groups = vocabularyList.Groups.Select(g => g.ToEntity()).ToList()
};
}
public static VocabularyList ToModel(this VocabularyListEntity vocabularyList)
{
return new VocabularyList
{
Id = vocabularyList.Id,
Name = vocabularyList.Name,
Image = vocabularyList.Image,
UserId = vocabularyList.UserId,
translation = vocabularyList.translation.Select(t => t.ToModel()).ToList(),
Groups = vocabularyList.Groups.Select(g => g.ToModel()).ToList()
};
}
public static TranslateEntity ToEntity(this Translate translate)
{
return new TranslateEntity
{
Id = translate.Id,
WordsId = translate.WordsId,
Words = translate.Words.Select(w => w.ToEntity()).ToList(),
VocabularyListVocId = translate.VocabularyListVocId,
VocabularyListVoc = translate.VocabularyListVoc.ToEntity()
};
}
public static Translate ToModel(this TranslateEntity translate)
{
return new Translate
{
Id = translate.Id,
WordsId = translate.WordsId,
Words = translate.Words.Select(w => w.ToModel()).ToList(),
VocabularyListVocId = translate.VocabularyListVocId,
VocabularyListVoc = translate.VocabularyListVoc.ToModel()
};
}
public static VocabularyEntity ToEntity(this Vocabulary vocabulary)
{
return new VocabularyEntity
{
word = vocabulary.word,
LangueName = vocabulary.LangueName
};
}
public static Vocabulary ToModel(this VocabularyEntity vocabulary)
{
return new Vocabulary
{
word = vocabulary.word,
LangueName = vocabulary.LangueName
};
}
public static UserEntity ToEntity(this User user)
{
return new UserEntity
{
Id = user.Id,
Name = user.Name,
UserName = user.UserName,
NickName = user.NickName,
ExtraTime = user.ExtraTime,
GroupId = user.GroupId,
Password = user.Password,
Email = user.Email
};
}
public static User ToModel(this UserEntity user)
{
return new User
{
Id = user.Id,
Name = user.Name,
UserName = user.UserName,
NickName = user.NickName,
ExtraTime = user.ExtraTime,
GroupId = user.GroupId,
Password = user.Password,
Email = user.Email
};
}
public static RoleEntity ToEntity(this Role role)
{
return new RoleEntity
{
Id = role.Id,
Name = role.Name
};
}
public static Role ToModel(this RoleEntity role)
{
return new Role
{
Id = role.Id,
Name = role.Name
};
}
public static LangueEntity ToEntity(this Langue langue)
{
return new LangueEntity
{
name = langue.name
};
}
public static Langue ToModel(this LangueEntity langue)
{
return new Langue
{
name = langue.name
};
}
}
}

@ -1,69 +0,0 @@
using Entities;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Options;
using StubbedContextLib;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ModeleToEntities
{
public class GroupService : IService<GroupEntity>
{
private readonly StubbedContext _context = new StubbedContext();
public GroupService()
{
}
public async Task<GroupEntity> Add(GroupEntity group)
{
_context.Groups.Add(group);
await _context.SaveChangesAsync();
return group;
}
public async Task<GroupEntity> Delete(int id)
{
var group = await _context.Groups.FindAsync(id);
if (group != null)
{
_context.Groups.Remove(group);
await _context.SaveChangesAsync();
}
return group;
}
public async Task<GroupEntity> GetById(int id)
{
var group = await _context.Groups.FindAsync(id);
if (group == null)
{
throw new Exception("Group not found");
}
return group;
}
public async Task<IEnumerable<GroupEntity>> Gets()
{
var groups = await _context.Groups.ToListAsync();
return groups;
}
public async Task<GroupEntity> Update(GroupEntity group)
{
var groupToUpdate = await _context.Groups.FindAsync(group.Id);
if (groupToUpdate == null)
{
throw new Exception("Group not found");
}
groupToUpdate.sector = group.sector;
groupToUpdate.year = group.year;
await _context.SaveChangesAsync();
return groupToUpdate;
}
}
}

@ -1,18 +0,0 @@
using Entities;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ModeleToEntities
{
public interface IService<T>
{
Task<IEnumerable<T>> Gets();
Task<T> GetById(int id);
Task<T> Add(T group);
Task<T> Delete(int id);
Task<T> Update(T group);
}
}

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

@ -1,11 +0,0 @@
namespace Modeles
{
public class Group
{
public int Id { get; set; }
public int Num { get; set; }
public int year { get; set; }
public string sector { get; set; }
}
}

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

@ -1,9 +0,0 @@
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<TargetFramework>net8.0</TargetFramework>
<ImplicitUsings>enable</ImplicitUsings>
<Nullable>enable</Nullable>
</PropertyGroup>
</Project>

@ -1,14 +0,0 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Modeles
{
public class Role
{
public int Id { get; set; }
public string Name { get; set; }
}
}

@ -1,15 +0,0 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Modeles
{
public class Translate
{
public int Id { get; set; }
//public string Words1 { get; set; }
//public string Words2 { get; set; }
}
}

@ -1,22 +0,0 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Modeles
{
public class User
{
public long Id { get; set; }
public string Password { get; set; }
public string Email { get; set; }
public string Name { get; set; }
public string UserName { get; set; }
public string NickName { get; set; }
public string? image { get; set; } = null;
//public long Group { get; set; }
//public string Role { get; set; }
public Boolean ExtraTime { get; set; }
}
}

@ -1,14 +0,0 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Modeles
{
public class Vocabulary
{
public string word { get; set; }
public string LangueName { get; set; }
}
}

@ -1,17 +0,0 @@
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations.Schema;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Modeles
{
public class VocabularyList
{
public int Id { get; set; }
public string Name { get; set; }
public string Image { get; set; }
//public long User { get; set; }
}
}

@ -1,169 +0,0 @@
using Microsoft.EntityFrameworkCore;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Linq.Expressions;
using System.Text;
using System.Threading.Tasks;
namespace DbContextLib
{
public class GenericRepository<TEntity> where TEntity : class
{
private DbContext Context { get; set; }
private DbSet<TEntity> Set { get; set; }
public GenericRepository(DbContext context)
{
Context = context;
Set = Context.Set<TEntity>();
}
public virtual TEntity? GetById(object id)
{
return Context.Set<TEntity>().Find(id);
}
public virtual IEnumerable<TEntity> GetItems(Expression<Func<TEntity, bool>>? filter = null,
int index = 0, int count = 10,
params string[] includeProperties)
=> GetItems(filter, null, index, count, includeProperties);
public virtual IEnumerable<TEntity> GetItems(Func<IQueryable<TEntity>, IOrderedQueryable<TEntity>>? orderBy = null,
int index = 0, int count = 10,
params string[] includeProperties)
=> GetItems(null, orderBy, index, count, includeProperties);
public virtual IEnumerable<TEntity> GetItems(int index = 0, int count = 10,
params string[] includeProperties)
=> GetItems(null, null, index, count, includeProperties);
public virtual IEnumerable<TEntity> GetItems(Expression<Func<TEntity, bool>>? filter = null,
Func<IQueryable<TEntity>, IOrderedQueryable<TEntity>>? orderBy = null,
int index = 0, int count = 10,
params string[] includeProperties)
{
IQueryable<TEntity> query = Set;
if (filter != null)
{
query = query.Where(filter);
}
foreach (string includeProperty in includeProperties)
{
query = query.Include(includeProperty);
}
if (orderBy != null)
{
query = orderBy(query);
}
return query.Skip(index * count)
.Take(count)
.ToList();
}
public virtual void Insert(TEntity entity)
{
var primaryKeyProperty = Context.Model.FindEntityType(typeof(TEntity)).FindPrimaryKey().Properties.FirstOrDefault();
if (primaryKeyProperty != null)
{
var parameter = Expression.Parameter(typeof(TEntity), "x");
var property = Expression.Property(parameter, primaryKeyProperty.Name);
var idValue = Expression.Constant(primaryKeyProperty.GetGetter().GetClrValue(entity));
var equal = Expression.Equal(property, idValue);
var lambda = Expression.Lambda<Func<TEntity, bool>>(equal, parameter);
var existingEntity = Set.Local.FirstOrDefault(lambda.Compile());
if (existingEntity != null)
{
Set.Entry(existingEntity).Property("Count").CurrentValue = (int)Set.Entry(existingEntity).Property("Count").CurrentValue + 1;
}
else
{
Set.Add(entity);
}
}
else
{
throw new InvalidOperationException("Cannot find primary key property for entity type.");
}
}
public virtual void Insert(params TEntity[] entities)
{
foreach (var entity in entities)
{
Insert(entity);
}
}
public virtual void Delete(object id)
{
TEntity? entity = Set.Find(id);
if (entity == null) return;
Delete(entity);
}
public virtual void Delete(TEntity entity)
{
var primaryKeyProperty = Context.Model.FindEntityType(typeof(TEntity)).FindPrimaryKey().Properties.FirstOrDefault();
if (primaryKeyProperty != null)
{
var parameter = Expression.Parameter(typeof(TEntity), "x");
var property = Expression.Property(parameter, primaryKeyProperty.Name);
var idValue = Expression.Constant(primaryKeyProperty.GetGetter().GetClrValue(entity));
var equal = Expression.Equal(property, idValue);
var lambda = Expression.Lambda<Func<TEntity, bool>>(equal, parameter);
var existingEntity = Set.Local.FirstOrDefault(lambda.Compile());
if (existingEntity == null)
{
if (Context.Entry(entity).State == EntityState.Detached)
{
Set.Attach(entity);
}
Set.Remove(entity);
}
else
{
Set.Remove(existingEntity);
}
}
else
{
throw new InvalidOperationException("Cannot find primary key property for entity type.");
}
}
public virtual void Update(TEntity entity)
{
var primaryKeyProperty = Context.Model.FindEntityType(typeof(TEntity)).FindPrimaryKey().Properties.FirstOrDefault();
if (primaryKeyProperty != null)
{
var parameter = Expression.Parameter(typeof(TEntity), "x");
var property = Expression.Property(parameter, primaryKeyProperty.Name);
var idValue = Expression.Constant(primaryKeyProperty.GetGetter().GetClrValue(entity));
var equal = Expression.Equal(property, idValue);
var lambda = Expression.Lambda<Func<TEntity, bool>>(equal, parameter);
var existingEntity = Set.Local.FirstOrDefault(lambda.Compile());
if (existingEntity != null)
{
Context.Entry(existingEntity).CurrentValues.SetValues(entity);
}
else
{
Set.Attach(entity);
Context.Entry(entity).State = EntityState.Modified;
}
}
else
{
throw new InvalidOperationException("Cannot find primary key property for entity type.");
}
}
}
}

@ -1,412 +0,0 @@
// <auto-generated />
using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.Infrastructure;
using Microsoft.EntityFrameworkCore.Migrations;
using Microsoft.EntityFrameworkCore.Storage.ValueConversion;
using StubbedContextLib;
#nullable disable
namespace StubbedContextLib.Migrations
{
[DbContext(typeof(StubbedContext))]
[Migration("20240331212614_newMigs")]
partial class newMigs
{
/// <inheritdoc />
protected override void BuildTargetModel(ModelBuilder modelBuilder)
{
#pragma warning disable 612, 618
modelBuilder.HasAnnotation("ProductVersion", "8.0.1");
modelBuilder.Entity("Entities.GroupEntity", b =>
{
b.Property<long>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("INTEGER");
b.Property<int>("Num")
.HasColumnType("INTEGER");
b.Property<string>("sector")
.IsRequired()
.HasColumnType("TEXT");
b.Property<int>("year")
.HasColumnType("INTEGER");
b.HasKey("Id");
b.ToTable("Groups");
b.HasData(
new
{
Id = 1L,
Num = 1,
sector = "informatics",
year = 1
});
});
modelBuilder.Entity("Entities.LangueEntity", b =>
{
b.Property<string>("name")
.HasColumnType("TEXT");
b.HasKey("name");
b.ToTable("Langues");
b.HasData(
new
{
name = "French"
},
new
{
name = "English"
});
});
modelBuilder.Entity("Entities.RoleEntity", b =>
{
b.Property<long>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("INTEGER");
b.Property<string>("Name")
.IsRequired()
.HasColumnType("TEXT");
b.HasKey("Id");
b.ToTable("Roles");
b.HasData(
new
{
Id = 1L,
Name = "Admin"
},
new
{
Id = 2L,
Name = "Teacher"
},
new
{
Id = 3L,
Name = "Student"
});
});
modelBuilder.Entity("Entities.TranslateEntity", b =>
{
b.Property<long>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("INTEGER");
b.Property<long>("VocabularyListVocId")
.HasColumnType("INTEGER");
b.Property<string>("WordsId")
.IsRequired()
.HasColumnType("TEXT");
b.HasKey("Id");
b.HasIndex("VocabularyListVocId");
b.ToTable("Translates");
b.HasData(
new
{
Id = 1L,
VocabularyListVocId = 1L,
WordsId = "1"
});
});
modelBuilder.Entity("Entities.UserEntity", b =>
{
b.Property<long>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("INTEGER");
b.Property<string>("Email")
.IsRequired()
.HasColumnType("TEXT");
b.Property<bool>("ExtraTime")
.HasColumnType("INTEGER");
b.Property<long>("GroupId")
.HasColumnType("INTEGER");
b.Property<string>("Name")
.IsRequired()
.HasColumnType("TEXT");
b.Property<string>("NickName")
.IsRequired()
.HasColumnType("TEXT");
b.Property<string>("Password")
.IsRequired()
.HasColumnType("TEXT");
b.Property<long>("RoleId")
.HasColumnType("INTEGER");
b.Property<string>("UserName")
.IsRequired()
.HasColumnType("TEXT");
b.Property<string>("image")
.HasColumnType("TEXT");
b.HasKey("Id");
b.HasIndex("GroupId");
b.HasIndex("RoleId");
b.ToTable("Users");
b.HasData(
new
{
Id = 1L,
Email = "",
ExtraTime = true,
GroupId = 1L,
Name = "name",
NickName = "nickname",
Password = "1234",
RoleId = 1L,
UserName = "username"
},
new
{
Id = 2L,
Email = "",
ExtraTime = true,
GroupId = 1L,
Name = "name2",
NickName = "nickname2",
Password = "1234",
RoleId = 2L,
UserName = "username2"
},
new
{
Id = 3L,
Email = "",
ExtraTime = true,
GroupId = 1L,
Name = "name3",
NickName = "nickname3",
Password = "1234",
RoleId = 3L,
UserName = "username3"
});
});
modelBuilder.Entity("Entities.VocabularyEntity", b =>
{
b.Property<string>("word")
.HasColumnType("TEXT");
b.Property<string>("LangueName")
.IsRequired()
.HasColumnType("TEXT");
b.HasKey("word");
b.HasIndex("LangueName");
b.ToTable("Vocabularys");
b.HasData(
new
{
word = "Bonjour",
LangueName = "French"
});
});
modelBuilder.Entity("Entities.VocabularyListEntity", b =>
{
b.Property<long>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("INTEGER");
b.Property<string>("Image")
.IsRequired()
.HasColumnType("TEXT");
b.Property<string>("Name")
.IsRequired()
.HasColumnType("TEXT");
b.Property<long>("UserId")
.HasColumnType("INTEGER");
b.HasKey("Id");
b.HasIndex("UserId");
b.ToTable("VocabularyLists");
b.HasData(
new
{
Id = 1L,
Image = "image1",
Name = "Liste1",
UserId = 1L
});
});
modelBuilder.Entity("GroupEntityVocabularyListEntity", b =>
{
b.Property<long>("GroupVocabularyListId")
.HasColumnType("INTEGER");
b.Property<long>("VocsGroupsId")
.HasColumnType("INTEGER");
b.HasKey("GroupVocabularyListId", "VocsGroupsId");
b.HasIndex("VocsGroupsId");
b.ToTable("GroupEntityVocabularyListEntity");
});
modelBuilder.Entity("TranslateEntityVocabularyEntity", b =>
{
b.Property<string>("TransVocword")
.HasColumnType("TEXT");
b.Property<long>("VoctranslationsId")
.HasColumnType("INTEGER");
b.HasKey("TransVocword", "VoctranslationsId");
b.HasIndex("VoctranslationsId");
b.ToTable("TranslateEntityVocabularyEntity");
});
modelBuilder.Entity("Entities.TranslateEntity", b =>
{
b.HasOne("Entities.VocabularyListEntity", "VocabularyListVoc")
.WithMany("translations")
.HasForeignKey("VocabularyListVocId")
.OnDelete(DeleteBehavior.Cascade)
.IsRequired();
b.Navigation("VocabularyListVoc");
});
modelBuilder.Entity("Entities.UserEntity", b =>
{
b.HasOne("Entities.GroupEntity", "Group")
.WithMany("Users")
.HasForeignKey("GroupId")
.OnDelete(DeleteBehavior.Cascade)
.IsRequired();
b.HasOne("Entities.RoleEntity", "Role")
.WithMany("Users")
.HasForeignKey("RoleId")
.OnDelete(DeleteBehavior.Cascade)
.IsRequired();
b.Navigation("Group");
b.Navigation("Role");
});
modelBuilder.Entity("Entities.VocabularyEntity", b =>
{
b.HasOne("Entities.LangueEntity", "Langue")
.WithMany("vocabularys")
.HasForeignKey("LangueName")
.OnDelete(DeleteBehavior.Cascade)
.IsRequired();
b.Navigation("Langue");
});
modelBuilder.Entity("Entities.VocabularyListEntity", b =>
{
b.HasOne("Entities.UserEntity", "User")
.WithMany("VocabularyList")
.HasForeignKey("UserId")
.OnDelete(DeleteBehavior.Cascade)
.IsRequired();
b.Navigation("User");
});
modelBuilder.Entity("GroupEntityVocabularyListEntity", b =>
{
b.HasOne("Entities.VocabularyListEntity", null)
.WithMany()
.HasForeignKey("GroupVocabularyListId")
.OnDelete(DeleteBehavior.Cascade)
.IsRequired();
b.HasOne("Entities.GroupEntity", null)
.WithMany()
.HasForeignKey("VocsGroupsId")
.OnDelete(DeleteBehavior.Cascade)
.IsRequired();
});
modelBuilder.Entity("TranslateEntityVocabularyEntity", b =>
{
b.HasOne("Entities.VocabularyEntity", null)
.WithMany()
.HasForeignKey("TransVocword")
.OnDelete(DeleteBehavior.Cascade)
.IsRequired();
b.HasOne("Entities.TranslateEntity", null)
.WithMany()
.HasForeignKey("VoctranslationsId")
.OnDelete(DeleteBehavior.Cascade)
.IsRequired();
});
modelBuilder.Entity("Entities.GroupEntity", b =>
{
b.Navigation("Users");
});
modelBuilder.Entity("Entities.LangueEntity", b =>
{
b.Navigation("vocabularys");
});
modelBuilder.Entity("Entities.RoleEntity", b =>
{
b.Navigation("Users");
});
modelBuilder.Entity("Entities.UserEntity", b =>
{
b.Navigation("VocabularyList");
});
modelBuilder.Entity("Entities.VocabularyListEntity", b =>
{
b.Navigation("translations");
});
#pragma warning restore 612, 618
}
}
}

@ -1,310 +0,0 @@
using Microsoft.EntityFrameworkCore.Migrations;
#nullable disable
#pragma warning disable CA1814 // Prefer jagged arrays over multidimensional
namespace StubbedContextLib.Migrations
{
/// <inheritdoc />
public partial class newMigs : Migration
{
/// <inheritdoc />
protected override void Up(MigrationBuilder migrationBuilder)
{
migrationBuilder.CreateTable(
name: "Groups",
columns: table => new
{
Id = table.Column<long>(type: "INTEGER", nullable: false)
.Annotation("Sqlite:Autoincrement", true),
Num = table.Column<int>(type: "INTEGER", nullable: false),
year = table.Column<int>(type: "INTEGER", nullable: false),
sector = table.Column<string>(type: "TEXT", nullable: false)
},
constraints: table =>
{
table.PrimaryKey("PK_Groups", x => x.Id);
});
migrationBuilder.CreateTable(
name: "Langues",
columns: table => new
{
name = table.Column<string>(type: "TEXT", nullable: false)
},
constraints: table =>
{
table.PrimaryKey("PK_Langues", x => x.name);
});
migrationBuilder.CreateTable(
name: "Roles",
columns: table => new
{
Id = table.Column<long>(type: "INTEGER", nullable: false)
.Annotation("Sqlite:Autoincrement", true),
Name = table.Column<string>(type: "TEXT", nullable: false)
},
constraints: table =>
{
table.PrimaryKey("PK_Roles", x => x.Id);
});
migrationBuilder.CreateTable(
name: "Vocabularys",
columns: table => new
{
word = table.Column<string>(type: "TEXT", nullable: false),
LangueName = table.Column<string>(type: "TEXT", nullable: false)
},
constraints: table =>
{
table.PrimaryKey("PK_Vocabularys", x => x.word);
table.ForeignKey(
name: "FK_Vocabularys_Langues_LangueName",
column: x => x.LangueName,
principalTable: "Langues",
principalColumn: "name",
onDelete: ReferentialAction.Cascade);
});
migrationBuilder.CreateTable(
name: "Users",
columns: table => new
{
Id = table.Column<long>(type: "INTEGER", nullable: false)
.Annotation("Sqlite:Autoincrement", true),
Password = table.Column<string>(type: "TEXT", nullable: false),
Email = table.Column<string>(type: "TEXT", nullable: false),
Name = table.Column<string>(type: "TEXT", nullable: false),
UserName = table.Column<string>(type: "TEXT", nullable: false),
NickName = table.Column<string>(type: "TEXT", nullable: false),
image = table.Column<string>(type: "TEXT", nullable: true),
GroupId = table.Column<long>(type: "INTEGER", nullable: false),
RoleId = table.Column<long>(type: "INTEGER", nullable: false),
ExtraTime = table.Column<bool>(type: "INTEGER", nullable: false)
},
constraints: table =>
{
table.PrimaryKey("PK_Users", x => x.Id);
table.ForeignKey(
name: "FK_Users_Groups_GroupId",
column: x => x.GroupId,
principalTable: "Groups",
principalColumn: "Id",
onDelete: ReferentialAction.Cascade);
table.ForeignKey(
name: "FK_Users_Roles_RoleId",
column: x => x.RoleId,
principalTable: "Roles",
principalColumn: "Id",
onDelete: ReferentialAction.Cascade);
});
migrationBuilder.CreateTable(
name: "VocabularyLists",
columns: table => new
{
Id = table.Column<long>(type: "INTEGER", nullable: false)
.Annotation("Sqlite:Autoincrement", true),
Name = table.Column<string>(type: "TEXT", nullable: false),
Image = table.Column<string>(type: "TEXT", nullable: false),
UserId = table.Column<long>(type: "INTEGER", nullable: false)
},
constraints: table =>
{
table.PrimaryKey("PK_VocabularyLists", x => x.Id);
table.ForeignKey(
name: "FK_VocabularyLists_Users_UserId",
column: x => x.UserId,
principalTable: "Users",
principalColumn: "Id",
onDelete: ReferentialAction.Cascade);
});
migrationBuilder.CreateTable(
name: "GroupEntityVocabularyListEntity",
columns: table => new
{
GroupVocabularyListId = table.Column<long>(type: "INTEGER", nullable: false),
VocsGroupsId = table.Column<long>(type: "INTEGER", nullable: false)
},
constraints: table =>
{
table.PrimaryKey("PK_GroupEntityVocabularyListEntity", x => new { x.GroupVocabularyListId, x.VocsGroupsId });
table.ForeignKey(
name: "FK_GroupEntityVocabularyListEntity_Groups_VocsGroupsId",
column: x => x.VocsGroupsId,
principalTable: "Groups",
principalColumn: "Id",
onDelete: ReferentialAction.Cascade);
table.ForeignKey(
name: "FK_GroupEntityVocabularyListEntity_VocabularyLists_GroupVocabularyListId",
column: x => x.GroupVocabularyListId,
principalTable: "VocabularyLists",
principalColumn: "Id",
onDelete: ReferentialAction.Cascade);
});
migrationBuilder.CreateTable(
name: "Translates",
columns: table => new
{
Id = table.Column<long>(type: "INTEGER", nullable: false)
.Annotation("Sqlite:Autoincrement", true),
WordsId = table.Column<string>(type: "TEXT", nullable: false),
VocabularyListVocId = table.Column<long>(type: "INTEGER", nullable: false)
},
constraints: table =>
{
table.PrimaryKey("PK_Translates", x => x.Id);
table.ForeignKey(
name: "FK_Translates_VocabularyLists_VocabularyListVocId",
column: x => x.VocabularyListVocId,
principalTable: "VocabularyLists",
principalColumn: "Id",
onDelete: ReferentialAction.Cascade);
});
migrationBuilder.CreateTable(
name: "TranslateEntityVocabularyEntity",
columns: table => new
{
TransVocword = table.Column<string>(type: "TEXT", nullable: false),
VoctranslationsId = table.Column<long>(type: "INTEGER", nullable: false)
},
constraints: table =>
{
table.PrimaryKey("PK_TranslateEntityVocabularyEntity", x => new { x.TransVocword, x.VoctranslationsId });
table.ForeignKey(
name: "FK_TranslateEntityVocabularyEntity_Translates_VoctranslationsId",
column: x => x.VoctranslationsId,
principalTable: "Translates",
principalColumn: "Id",
onDelete: ReferentialAction.Cascade);
table.ForeignKey(
name: "FK_TranslateEntityVocabularyEntity_Vocabularys_TransVocword",
column: x => x.TransVocword,
principalTable: "Vocabularys",
principalColumn: "word",
onDelete: ReferentialAction.Cascade);
});
migrationBuilder.InsertData(
table: "Groups",
columns: new[] { "Id", "Num", "sector", "year" },
values: new object[] { 1L, 1, "informatics", 1 });
migrationBuilder.InsertData(
table: "Langues",
column: "name",
values: new object[]
{
"English",
"French"
});
migrationBuilder.InsertData(
table: "Roles",
columns: new[] { "Id", "Name" },
values: new object[,]
{
{ 1L, "Admin" },
{ 2L, "Teacher" },
{ 3L, "Student" }
});
migrationBuilder.InsertData(
table: "Users",
columns: new[] { "Id", "Email", "ExtraTime", "GroupId", "Name", "NickName", "Password", "RoleId", "UserName", "image" },
values: new object[,]
{
{ 1L, "", true, 1L, "name", "nickname", "1234", 1L, "username", null },
{ 2L, "", true, 1L, "name2", "nickname2", "1234", 2L, "username2", null },
{ 3L, "", true, 1L, "name3", "nickname3", "1234", 3L, "username3", null }
});
migrationBuilder.InsertData(
table: "Vocabularys",
columns: new[] { "word", "LangueName" },
values: new object[] { "Bonjour", "French" });
migrationBuilder.InsertData(
table: "VocabularyLists",
columns: new[] { "Id", "Image", "Name", "UserId" },
values: new object[] { 1L, "image1", "Liste1", 1L });
migrationBuilder.InsertData(
table: "Translates",
columns: new[] { "Id", "VocabularyListVocId", "WordsId" },
values: new object[] { 1L, 1L, "1" });
migrationBuilder.CreateIndex(
name: "IX_GroupEntityVocabularyListEntity_VocsGroupsId",
table: "GroupEntityVocabularyListEntity",
column: "VocsGroupsId");
migrationBuilder.CreateIndex(
name: "IX_TranslateEntityVocabularyEntity_VoctranslationsId",
table: "TranslateEntityVocabularyEntity",
column: "VoctranslationsId");
migrationBuilder.CreateIndex(
name: "IX_Translates_VocabularyListVocId",
table: "Translates",
column: "VocabularyListVocId");
migrationBuilder.CreateIndex(
name: "IX_Users_GroupId",
table: "Users",
column: "GroupId");
migrationBuilder.CreateIndex(
name: "IX_Users_RoleId",
table: "Users",
column: "RoleId");
migrationBuilder.CreateIndex(
name: "IX_VocabularyLists_UserId",
table: "VocabularyLists",
column: "UserId");
migrationBuilder.CreateIndex(
name: "IX_Vocabularys_LangueName",
table: "Vocabularys",
column: "LangueName");
}
/// <inheritdoc />
protected override void Down(MigrationBuilder migrationBuilder)
{
migrationBuilder.DropTable(
name: "GroupEntityVocabularyListEntity");
migrationBuilder.DropTable(
name: "TranslateEntityVocabularyEntity");
migrationBuilder.DropTable(
name: "Translates");
migrationBuilder.DropTable(
name: "Vocabularys");
migrationBuilder.DropTable(
name: "VocabularyLists");
migrationBuilder.DropTable(
name: "Langues");
migrationBuilder.DropTable(
name: "Users");
migrationBuilder.DropTable(
name: "Groups");
migrationBuilder.DropTable(
name: "Roles");
}
}
}

@ -1,409 +0,0 @@
// <auto-generated />
using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.Infrastructure;
using Microsoft.EntityFrameworkCore.Storage.ValueConversion;
using StubbedContextLib;
#nullable disable
namespace StubbedContextLib.Migrations
{
[DbContext(typeof(StubbedContext))]
partial class StubbedContextModelSnapshot : ModelSnapshot
{
protected override void BuildModel(ModelBuilder modelBuilder)
{
#pragma warning disable 612, 618
modelBuilder.HasAnnotation("ProductVersion", "8.0.1");
modelBuilder.Entity("Entities.GroupEntity", b =>
{
b.Property<long>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("INTEGER");
b.Property<int>("Num")
.HasColumnType("INTEGER");
b.Property<string>("sector")
.IsRequired()
.HasColumnType("TEXT");
b.Property<int>("year")
.HasColumnType("INTEGER");
b.HasKey("Id");
b.ToTable("Groups");
b.HasData(
new
{
Id = 1L,
Num = 1,
sector = "informatics",
year = 1
});
});
modelBuilder.Entity("Entities.LangueEntity", b =>
{
b.Property<string>("name")
.HasColumnType("TEXT");
b.HasKey("name");
b.ToTable("Langues");
b.HasData(
new
{
name = "French"
},
new
{
name = "English"
});
});
modelBuilder.Entity("Entities.RoleEntity", b =>
{
b.Property<long>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("INTEGER");
b.Property<string>("Name")
.IsRequired()
.HasColumnType("TEXT");
b.HasKey("Id");
b.ToTable("Roles");
b.HasData(
new
{
Id = 1L,
Name = "Admin"
},
new
{
Id = 2L,
Name = "Teacher"
},
new
{
Id = 3L,
Name = "Student"
});
});
modelBuilder.Entity("Entities.TranslateEntity", b =>
{
b.Property<long>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("INTEGER");
b.Property<long>("VocabularyListVocId")
.HasColumnType("INTEGER");
b.Property<string>("WordsId")
.IsRequired()
.HasColumnType("TEXT");
b.HasKey("Id");
b.HasIndex("VocabularyListVocId");
b.ToTable("Translates");
b.HasData(
new
{
Id = 1L,
VocabularyListVocId = 1L,
WordsId = "1"
});
});
modelBuilder.Entity("Entities.UserEntity", b =>
{
b.Property<long>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("INTEGER");
b.Property<string>("Email")
.IsRequired()
.HasColumnType("TEXT");
b.Property<bool>("ExtraTime")
.HasColumnType("INTEGER");
b.Property<long>("GroupId")
.HasColumnType("INTEGER");
b.Property<string>("Name")
.IsRequired()
.HasColumnType("TEXT");
b.Property<string>("NickName")
.IsRequired()
.HasColumnType("TEXT");
b.Property<string>("Password")
.IsRequired()
.HasColumnType("TEXT");
b.Property<long>("RoleId")
.HasColumnType("INTEGER");
b.Property<string>("UserName")
.IsRequired()
.HasColumnType("TEXT");
b.Property<string>("image")
.HasColumnType("TEXT");
b.HasKey("Id");
b.HasIndex("GroupId");
b.HasIndex("RoleId");
b.ToTable("Users");
b.HasData(
new
{
Id = 1L,
Email = "",
ExtraTime = true,
GroupId = 1L,
Name = "name",
NickName = "nickname",
Password = "1234",
RoleId = 1L,
UserName = "username"
},
new
{
Id = 2L,
Email = "",
ExtraTime = true,
GroupId = 1L,
Name = "name2",
NickName = "nickname2",
Password = "1234",
RoleId = 2L,
UserName = "username2"
},
new
{
Id = 3L,
Email = "",
ExtraTime = true,
GroupId = 1L,
Name = "name3",
NickName = "nickname3",
Password = "1234",
RoleId = 3L,
UserName = "username3"
});
});
modelBuilder.Entity("Entities.VocabularyEntity", b =>
{
b.Property<string>("word")
.HasColumnType("TEXT");
b.Property<string>("LangueName")
.IsRequired()
.HasColumnType("TEXT");
b.HasKey("word");
b.HasIndex("LangueName");
b.ToTable("Vocabularys");
b.HasData(
new
{
word = "Bonjour",
LangueName = "French"
});
});
modelBuilder.Entity("Entities.VocabularyListEntity", b =>
{
b.Property<long>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("INTEGER");
b.Property<string>("Image")
.IsRequired()
.HasColumnType("TEXT");
b.Property<string>("Name")
.IsRequired()
.HasColumnType("TEXT");
b.Property<long>("UserId")
.HasColumnType("INTEGER");
b.HasKey("Id");
b.HasIndex("UserId");
b.ToTable("VocabularyLists");
b.HasData(
new
{
Id = 1L,
Image = "image1",
Name = "Liste1",
UserId = 1L
});
});
modelBuilder.Entity("GroupEntityVocabularyListEntity", b =>
{
b.Property<long>("GroupVocabularyListId")
.HasColumnType("INTEGER");
b.Property<long>("VocsGroupsId")
.HasColumnType("INTEGER");
b.HasKey("GroupVocabularyListId", "VocsGroupsId");
b.HasIndex("VocsGroupsId");
b.ToTable("GroupEntityVocabularyListEntity");
});
modelBuilder.Entity("TranslateEntityVocabularyEntity", b =>
{
b.Property<string>("TransVocword")
.HasColumnType("TEXT");
b.Property<long>("VoctranslationsId")
.HasColumnType("INTEGER");
b.HasKey("TransVocword", "VoctranslationsId");
b.HasIndex("VoctranslationsId");
b.ToTable("TranslateEntityVocabularyEntity");
});
modelBuilder.Entity("Entities.TranslateEntity", b =>
{
b.HasOne("Entities.VocabularyListEntity", "VocabularyListVoc")
.WithMany("translations")
.HasForeignKey("VocabularyListVocId")
.OnDelete(DeleteBehavior.Cascade)
.IsRequired();
b.Navigation("VocabularyListVoc");
});
modelBuilder.Entity("Entities.UserEntity", b =>
{
b.HasOne("Entities.GroupEntity", "Group")
.WithMany("Users")
.HasForeignKey("GroupId")
.OnDelete(DeleteBehavior.Cascade)
.IsRequired();
b.HasOne("Entities.RoleEntity", "Role")
.WithMany("Users")
.HasForeignKey("RoleId")
.OnDelete(DeleteBehavior.Cascade)
.IsRequired();
b.Navigation("Group");
b.Navigation("Role");
});
modelBuilder.Entity("Entities.VocabularyEntity", b =>
{
b.HasOne("Entities.LangueEntity", "Langue")
.WithMany("vocabularys")
.HasForeignKey("LangueName")
.OnDelete(DeleteBehavior.Cascade)
.IsRequired();
b.Navigation("Langue");
});
modelBuilder.Entity("Entities.VocabularyListEntity", b =>
{
b.HasOne("Entities.UserEntity", "User")
.WithMany("VocabularyList")
.HasForeignKey("UserId")
.OnDelete(DeleteBehavior.Cascade)
.IsRequired();
b.Navigation("User");
});
modelBuilder.Entity("GroupEntityVocabularyListEntity", b =>
{
b.HasOne("Entities.VocabularyListEntity", null)
.WithMany()
.HasForeignKey("GroupVocabularyListId")
.OnDelete(DeleteBehavior.Cascade)
.IsRequired();
b.HasOne("Entities.GroupEntity", null)
.WithMany()
.HasForeignKey("VocsGroupsId")
.OnDelete(DeleteBehavior.Cascade)
.IsRequired();
});
modelBuilder.Entity("TranslateEntityVocabularyEntity", b =>
{
b.HasOne("Entities.VocabularyEntity", null)
.WithMany()
.HasForeignKey("TransVocword")
.OnDelete(DeleteBehavior.Cascade)
.IsRequired();
b.HasOne("Entities.TranslateEntity", null)
.WithMany()
.HasForeignKey("VoctranslationsId")
.OnDelete(DeleteBehavior.Cascade)
.IsRequired();
});
modelBuilder.Entity("Entities.GroupEntity", b =>
{
b.Navigation("Users");
});
modelBuilder.Entity("Entities.LangueEntity", b =>
{
b.Navigation("vocabularys");
});
modelBuilder.Entity("Entities.RoleEntity", b =>
{
b.Navigation("Users");
});
modelBuilder.Entity("Entities.UserEntity", b =>
{
b.Navigation("VocabularyList");
});
modelBuilder.Entity("Entities.VocabularyListEntity", b =>
{
b.Navigation("translations");
});
#pragma warning restore 612, 618
}
}
}

@ -1,128 +0,0 @@
using DbContextLib;
using Microsoft.EntityFrameworkCore;
using System.Reflection.Emit;
using Entities;
namespace StubbedContextLib
{
public class StubbedContext : SAEContext
{
//permet la création des données à ajouter dans la base de données
protected override void OnModelCreating(ModelBuilder modelBuilder)
{
modelBuilder.Entity<UserEntity>().HasData(
new UserEntity
{
Id = 1,
Name = "name",
UserName = "username",
NickName = "nickname",
ExtraTime = true,
GroupId = 1,
Password = "1234",
Email = "",
RoleId = 1
},
new UserEntity
{
Id = 2,
Name = "name2",
UserName = "username2",
NickName = "nickname2",
ExtraTime = true,
GroupId = 1,
Password = "1234",
Email = "",
RoleId = 2
},
new UserEntity
{
Id = 3,
Name = "name3",
UserName = "username3",
NickName = "nickname3",
ExtraTime = true,
GroupId = 1,
Password = "1234",
Email = "",
RoleId = 3,
}
);
modelBuilder.Entity<RoleEntity>().HasData(
new RoleEntity
{
Id = 1,
Name = "Admin"
},
new RoleEntity
{
Id = 2,
Name = "Teacher"
},
new RoleEntity
{
Id = 3,
Name = "Student"
}
);
modelBuilder.Entity<LangueEntity>().HasData(
new LangueEntity
{
name = "French"
},
new LangueEntity
{
name = "English"
}
);
modelBuilder.Entity<GroupEntity>().HasData(
new GroupEntity
{
Id = 1,
Num = 1,
sector = "informatics",
year = 1,
});
modelBuilder.Entity<TranslateEntity>().HasData(
new TranslateEntity
{
Id = 1,
WordsId = "1",
VocabularyListVocId = 1,
VocabularyListVoc = null
});
modelBuilder.Entity<VocabularyEntity>().HasData(
new VocabularyEntity
{
LangueName = "French",
word = "Bonjour"
});
modelBuilder.Entity<VocabularyListEntity>().HasData(
new VocabularyListEntity
{
Id = 1,
Name = "Liste1",
UserId = 1,
Image = "image1",
});
}
public StubbedContext() { }
public StubbedContext(DbContextOptions<SAEContext> options) : base(options)
{
}
}
}

@ -1,23 +0,0 @@
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<TargetFramework>net8.0</TargetFramework>
<ImplicitUsings>enable</ImplicitUsings>
<Nullable>enable</Nullable>
</PropertyGroup>
<ItemGroup>
<PackageReference Include="Microsoft.EntityFrameworkCore" Version="8.0.1" />
<PackageReference Include="Microsoft.EntityFrameworkCore.Sqlite" Version="8.0.1" />
<PackageReference Include="Microsoft.EntityFrameworkCore.SqlServer" Version="8.0.1" />
<PackageReference Include="Microsoft.EntityFrameworkCore.Tools" Version="8.0.1">
<PrivateAssets>all</PrivateAssets>
<IncludeAssets>runtime; build; native; contentfiles; analyzers; buildtransitive</IncludeAssets>
</PackageReference>
</ItemGroup>
<ItemGroup>
<ProjectReference Include="..\DbContext\DbContextLib.csproj" />
</ItemGroup>
</Project>

@ -1,197 +0,0 @@
using Entities;
using Microsoft.EntityFrameworkCore;
using StubbedContextLib;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace DbContextLib
{
public class UnitOfWork : IDisposable
{
private bool disposed = false;
private GenericRepository<GroupEntity>? groupRepository;
private GenericRepository<LangueEntity>? langueRepository;
private GenericRepository<RoleEntity>? roleRepository;
private GenericRepository<TranslateEntity>? translateRepository;
private GenericRepository<UserEntity>? userRepository;
private GenericRepository<VocabularyEntity>? vocabularyRepository;
private GenericRepository<VocabularyListEntity>? vocabularyListRepository;
private SAEContext _context { get; set; }
public UnitOfWork(SAEContext context) {
_context = context;
_context.Database.EnsureCreated();
}
public UnitOfWork(StubbedContext context)
{
_context = context;
_context.Database.EnsureCreated();
}
public UnitOfWork(DbContextOptions<SAEContext> options)
: this(new StubbedContext(options))
{
}
public UnitOfWork()
: this(new StubbedContext())
{
}
protected virtual void Dispose(bool disposing)
{
if (!this.disposed && disposing)
{
_context.Dispose();
}
this.disposed = true;
}
public void Dispose()
{
Dispose(true);
GC.SuppressFinalize(this);
}
public GenericRepository<GroupEntity> GroupRepository
{
get
{
if (groupRepository == null)
{
groupRepository = new GenericRepository<GroupEntity>(_context);
}
return groupRepository;
}
}
public GenericRepository<LangueEntity> LangueRepository
{
get
{
if (langueRepository == null)
{
langueRepository = new GenericRepository<LangueEntity>(_context);
}
return langueRepository;
}
}
public GenericRepository<RoleEntity> RoleRepository
{
get
{
if (roleRepository == null)
{
roleRepository = new GenericRepository<RoleEntity>(_context);
}
return roleRepository;
}
}
public GenericRepository<TranslateEntity> TranslateRepository
{
get
{
if (translateRepository == null)
{
translateRepository = new GenericRepository<TranslateEntity>(_context);
}
return translateRepository;
}
}
public GenericRepository<UserEntity> UserRepository
{
get
{
if (userRepository == null)
{
userRepository = new GenericRepository<UserEntity>(_context);
}
return userRepository;
}
}
public GenericRepository<VocabularyEntity> VocabularyRepository
{
get
{
if (vocabularyRepository == null)
{
vocabularyRepository = new GenericRepository<VocabularyEntity>(_context);
}
return vocabularyRepository;
}
}
public GenericRepository<VocabularyListEntity> VocabularyListRepository
{
get
{
if (vocabularyListRepository == null)
{
vocabularyListRepository = new GenericRepository<VocabularyListEntity>(_context);
}
return vocabularyListRepository;
}
}
public async Task<int> SaveChangesAsync()
{
int result = 0;
try
{
result = await _context.SaveChangesAsync();
}
catch
{
RejectChanges();
return -1;
}
foreach (var entity in _context.ChangeTracker.Entries()
.Where(e => e.State != EntityState.Detached))
{
entity.State = EntityState.Detached;
}
return result;
}
public void RejectChanges()
{
foreach (var entry in _context.ChangeTracker.Entries()
.Where(e => e.State != EntityState.Unchanged))
{
switch (entry.State)
{
case EntityState.Added:
entry.State = EntityState.Detached;
break;
case EntityState.Modified:
case EntityState.Deleted:
entry.Reload();
break;
}
}
}
}
}

@ -1,296 +0,0 @@
using DbContextLib;
using Entities;
using Microsoft.Data.Sqlite;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Logging;
using StubbedContextLib;
using API.Controllers;
using DTOToEntity;
using DTO;
using Moq;
namespace TU
{
[TestClass]
public class GroupTU
{
[TestMethod]
public async Task TestGetGroups()
{
var connection = new SqliteConnection("DataSource=:memory:");
connection.Open();
var options = new DbContextOptionsBuilder<SAEContext>()
.UseSqlite(connection)
.Options;
using (var context = new StubbedContext(options))
{
context.Database.EnsureCreated();
GroupEntity g1 = new GroupEntity { Id = 3, Num = 1, sector = "sect3", year = 2020 };
await context.Groups.AddAsync(g1);
await context.Groups.AddAsync(new GroupEntity { Id = 4, Num = 2, sector = "sect4" });
await context.SaveChangesAsync();
// Créer un mock pour le logger
var mockLogger = new Mock<ILogger<GroupController>>();
var controller = new GroupController(new GroupService(context), mockLogger.Object);
var result = await controller.GetGroups(0, 5);
Assert.IsNotNull(result.Value.Items.ToArray());
Assert.AreEqual(3, result.Value.TotalCount);
Assert.AreEqual(g1.Num, result.Value.Items.First().Num);
}
}
[TestMethod]
public async Task TestGetGroup()
{
var connection = new SqliteConnection("DataSource=:memory:");
connection.Open();
var options = new DbContextOptionsBuilder<SAEContext>()
.UseSqlite(connection)
.Options;
using (var context = new StubbedContext(options))
{
context.Database.EnsureCreated();
GroupEntity g1 = new GroupEntity { Id = 3, Num = 1, sector = "sect3", year = 2020 };
await context.Groups.AddAsync(g1);
await context.SaveChangesAsync();
// Créer un mock pour le logger
var mockLogger = new Mock<ILogger<GroupController>>();
var controller = new GroupController(new GroupService(context), mockLogger.Object);
var result = await controller.GetGroup(3);
Assert.IsNotNull(result.Value);
Assert.AreEqual(g1.Id, result.Value.Id);
}
}
[TestMethod]
public async Task TestAddGroup()
{
// Créer une connexion SQLite en mémoire
var connection = new SqliteConnection("DataSource=:memory:");
connection.Open();
var options = new DbContextOptionsBuilder<SAEContext>()
.UseSqlite(connection)
.Options;
using (var context = new StubbedContext(options))
{
context.Database.EnsureCreated();
// Créer un mock pour le logger
var mockLogger = new Mock<ILogger<GroupController>>();
var controller = new GroupController(new GroupService(context), mockLogger.Object);
var newGroupDTO = new GroupDTO { Id = 0, Num = 3, sector = "sect5", Year = 2022 };
var result = await controller.AddGroup(newGroupDTO);
Assert.IsNotNull(result.Value);
Assert.AreEqual(newGroupDTO.Num, result.Value.Num);
Assert.AreEqual(newGroupDTO.sector, result.Value.sector);
Assert.AreEqual(newGroupDTO.Year, result.Value.Year);
}
}
[TestMethod]
public async Task TestDeleteGroup()
{
var connection = new SqliteConnection("DataSource=:memory:");
connection.Open();
var options = new DbContextOptionsBuilder<SAEContext>()
.UseSqlite(connection)
.Options;
using (var context = new StubbedContext(options))
{
context.Database.EnsureCreated();
GroupEntity g1 = new GroupEntity { Id = 3, Num = 1, sector = "sect3", year = 2020 };
await context.Groups.AddAsync(g1);
await context.SaveChangesAsync();
var mockLogger = new Mock<ILogger<GroupController>>();
var controller = new GroupController(new GroupService(context), mockLogger.Object);
var result = await controller.DeleteGroup(3);
Assert.IsNotNull(result.Value);
Assert.AreEqual(g1.Num, result.Value.Num);
}
}
[TestMethod]
public async Task TestUpdateGroup()
{
var connection = new SqliteConnection("DataSource=:memory:");
connection.Open();
var options = new DbContextOptionsBuilder<SAEContext>()
.UseSqlite(connection)
.Options;
using (var context = new StubbedContext(options))
{
context.Database.EnsureCreated();
GroupEntity g1 = new GroupEntity { Id = 4, Num = 4, sector = "sect3", year = 2020 };
GroupDTO updatedGroupDTO = new GroupDTO { Id = 4, Num = 2, sector = "sect4", Year = 2021 };
await context.Groups.AddAsync(g1);
await context.SaveChangesAsync();
var mockLogger = new Mock<ILogger<GroupController>>();
var controller = new GroupController(new GroupService(context), mockLogger.Object);
var result = await controller.UpdateGroup(updatedGroupDTO);
Assert.IsNotNull(result.Value);
Assert.AreEqual(updatedGroupDTO.Num, result.Value.Num);
Assert.AreEqual(updatedGroupDTO.sector, result.Value.sector);
Assert.AreEqual(updatedGroupDTO.Year, result.Value.Year);
}
}
[TestMethod]
public async Task TestGetGroupsByNum()
{
var connection = new SqliteConnection("DataSource=:memory:");
connection.Open();
var options = new DbContextOptionsBuilder<SAEContext>()
.UseSqlite(connection)
.Options;
using (var context = new StubbedContext(options))
{
context.Database.EnsureCreated();
await context.Groups.AddRangeAsync(
new GroupEntity { Id = 3, Num = 10, sector = "sect1", year = 2021 },
new GroupEntity { Id = 4, Num = 2, sector = "sect2", year = 2021 },
new GroupEntity { Id = 5, Num = 10, sector = "sect1", year = 2022 }
);
await context.SaveChangesAsync();
var mockLogger = new Mock<ILogger<GroupController>>();
var controller = new GroupController(new GroupService(context), mockLogger.Object);
var result = await controller.GetGroupsByNum(0, 5, 10);
Assert.IsNotNull(result.Value);
Assert.AreEqual(2, result.Value.Items.Count());
}
}
[TestMethod]
public async Task TestGetGroupsBySector()
{
// Créer une connexion SQLite en mémoire
var connection = new SqliteConnection("DataSource=:memory:");
connection.Open();
var options = new DbContextOptionsBuilder<SAEContext>()
.UseSqlite(connection)
.Options;
using (var context = new StubbedContext(options))
{
context.Database.EnsureCreated();
await context.Groups.AddRangeAsync(
new GroupEntity { Id = 3, Num = 1, sector = "sect1", year = 2021 },
new GroupEntity { Id = 4, Num = 2, sector = "sect2", year = 2021 },
new GroupEntity { Id = 5, Num = 1, sector = "sect1", year = 2022 }
);
await context.SaveChangesAsync();
var mockLogger = new Mock<ILogger<GroupController>>();
var controller = new GroupController(new GroupService(context), mockLogger.Object);
var result = await controller.GetGroupsBySector(0, 5, "sect1");
Assert.IsNotNull(result.Value);
Assert.AreEqual(2, result.Value.Items.Count());
}
}
[TestMethod]
public async Task TestGetGroupsByYear()
{
var connection = new SqliteConnection("DataSource=:memory:");
connection.Open();
var options = new DbContextOptionsBuilder<SAEContext>()
.UseSqlite(connection)
.Options;
using (var context = new StubbedContext(options))
{
context.Database.EnsureCreated();
await context.Groups.AddRangeAsync(
new GroupEntity { Id = 3, Num = 1, sector = "sect1", year = 2021 },
new GroupEntity { Id = 4, Num = 2, sector = "sect2", year = 2021 },
new GroupEntity { Id = 5, Num = 1, sector = "sect1", year = 2022 }
);
await context.SaveChangesAsync();
var mockLogger = new Mock<ILogger<GroupController>>();
var controller = new GroupController(new GroupService(context), mockLogger.Object);
var result = await controller.GetGroupsByYear(0, 5, 2021);
Assert.IsNotNull(result.Value);
Assert.AreEqual(2, result.Value.Items.Count());
}
}
[TestMethod]
public async Task TestAddUserToGroup()
{
var connection = new SqliteConnection("DataSource=:memory:");
connection.Open();
var options = new DbContextOptionsBuilder<SAEContext>()
.UseSqlite(connection)
.Options;
using (var context = new StubbedContext(options))
{
context.Database.EnsureCreated();
var mockLogger = new Mock<ILogger<GroupController>>();
var controller = new GroupController(new GroupService(context), mockLogger.Object);
var result = await controller.AddUserToGroup(1, 1);
Assert.IsNotNull(result.Value);
Assert.AreEqual(1, result.Value.Id);
var test = await context.Groups.FirstOrDefaultAsync(g => g.Id == 1);
var testUser = await context.Users.FirstOrDefaultAsync(g => g.Id == 1);
Assert.IsNotNull(test);
Assert.IsNotNull(testUser);
Assert.AreEqual(test.Users.First(), testUser);
}
}
}
}

@ -1,128 +0,0 @@
using API.Controllers;
using DbContextLib;
using DTOToEntity;
using Entities;
using Microsoft.Data.Sqlite;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Logging.Abstractions;
using Microsoft.Extensions.Logging;
using StubbedContextLib;
using DTO;
using Moq;
namespace TU
{
[TestClass]
public class LangueTU
{
[TestMethod]
public async Task TestAddLangue()
{
var connection = new SqliteConnection("DataSource=:memory:");
connection.Open();
var options = new DbContextOptionsBuilder<SAEContext>()
.UseSqlite(connection)
.Options;
using (var context = new StubbedContext(options))
{
context.Database.EnsureCreated();
// Créer un mock pour le logger
var mockLogger = new Mock<ILogger<LangueController>>();
var controller = new LangueController(new LangueService(context), mockLogger.Object);
var newLangue = new LangueDTO { name = "test" };
var result = await controller.AddLangue(newLangue);
Assert.IsNotNull(result.Value);
Assert.AreEqual(newLangue.name, result.Value.name);
}
}
[TestMethod]
public async Task TestDeleteLangue()
{
var connection = new SqliteConnection("DataSource=:memory:");
connection.Open();
var options = new DbContextOptionsBuilder<SAEContext>()
.UseSqlite(connection)
.Options;
using (var context = new StubbedContext(options))
{
context.Database.EnsureCreated();
var newLangue = new LangueDTO { name = "test" };
await context.Langues.AddAsync(newLangue.ToEntity());
// Créer un mock pour le logger
var mockLogger = new Mock<ILogger<LangueController>>();
var controller = new LangueController(new LangueService(context), mockLogger.Object);
var result = await controller.DeleteLangue("test");
Assert.IsNotNull(result.Value);
Assert.AreEqual(newLangue.name, result.Value.name);
var res = await context.Langues.FirstOrDefaultAsync(l => l.name == "test");
Assert.IsNull(res);
}
}
[TestMethod]
public async Task TestGetById()
{
var connection = new SqliteConnection("DataSource=:memory:");
connection.Open();
var options = new DbContextOptionsBuilder<SAEContext>()
.UseSqlite(connection)
.Options;
using (var context = new StubbedContext(options))
{
context.Database.EnsureCreated();
var newLangue = new LangueDTO { name = "test" };
await context.Langues.AddAsync(newLangue.ToEntity());
// Créer un mock pour le logger
var mockLogger = new Mock<ILogger<LangueController>>();
var controller = new LangueController(new LangueService(context), mockLogger.Object);
var result = await controller.GetLangue("test");
Assert.IsNotNull(result.Value);
Assert.AreEqual(newLangue.name, result.Value.name);
}
}
[TestMethod]
public async Task TestGetGroups()
{
var connection = new SqliteConnection("DataSource=:memory:");
connection.Open();
var options = new DbContextOptionsBuilder<SAEContext>()
.UseSqlite(connection)
.Options;
using (var context = new StubbedContext(options))
{
context.Database.EnsureCreated();
var mockLogger = new Mock<ILogger<LangueController>>();
var controller = new LangueController(new LangueService(context), mockLogger.Object);
var result = await controller.GetLangues(0, 5);
Assert.IsNotNull(result.Value);
Assert.AreEqual(2, result.Value.TotalCount);
Assert.AreEqual("English", result.Value.Items.ToList()[0].name);
Assert.AreEqual("French", result.Value.Items.ToList()[1].name);
}
}
}
}

@ -1,122 +0,0 @@
using API.Controllers;
using DbContextLib;
using DTO;
using DTOToEntity;
using Entities;
using Microsoft.Data.Sqlite;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Logging;
using Moq;
using StubbedContextLib;
namespace TU
{
[TestClass]
public class RoleTU
{
[TestMethod]
public async Task TestAddRole()
{
var connection = new SqliteConnection("DataSource=:memory:");
connection.Open();
var options = new DbContextOptionsBuilder<SAEContext>()
.UseSqlite(connection)
.Options;
using (var context = new StubbedContext(options))
{
context.Database.EnsureCreated();
var mockLogger = new Mock<ILogger<RoleController>>();
var controller = new RoleController(new RoleService(context), mockLogger.Object);
var newRole = new RoleDTO { Id = 1, Name = "test" };
var result = await controller.AddRole(newRole);
Assert.IsNotNull(result.Value);
//ici on met 4 pour verifier que le Id n'est pas celui que l'on donne mais bien : CountList + 1
Assert.AreEqual(4, result.Value.Id);
Assert.AreEqual("test", result.Value.Name);
var test = context.Roles.Find((long)4);
Assert.IsNotNull(test);
}
}
[TestMethod]
public async Task TestDeleteRole()
{
var connection = new SqliteConnection("DataSource=:memory:");
connection.Open();
var options = new DbContextOptionsBuilder<SAEContext>()
.UseSqlite(connection)
.Options;
using (var context = new StubbedContext(options))
{
context.Database.EnsureCreated();
var mockLogger = new Mock<ILogger<RoleController>>();
var controller = new RoleController(new RoleService(context), mockLogger.Object);
var result = await controller.DeleteRole(1);
Assert.IsNotNull(result.Value);
Assert.AreEqual(1, result.Value.Id);
Assert.AreEqual("Admin", result.Value.Name);
var test = context.Roles.Find((long)1);
Assert.IsNull(test);
}
}
[TestMethod]
public async Task TestGetRole()
{
var connection = new SqliteConnection("DataSource=:memory:");
connection.Open();
var options = new DbContextOptionsBuilder<SAEContext>()
.UseSqlite(connection)
.Options;
using (var context = new StubbedContext(options))
{
context.Database.EnsureCreated();
var mockLogger = new Mock<ILogger<RoleController>>();
var controller = new RoleController(new RoleService(context), mockLogger.Object);
var result = await controller.GetRole((long)1);
Assert.IsNotNull(result.Value);
Assert.AreEqual(1, result.Value.Id);
Assert.AreEqual("Admin", result.Value.Name);
}
}
[TestMethod]
public async Task TestGetRoles()
{
var connection = new SqliteConnection("DataSource=:memory:");
connection.Open();
var options = new DbContextOptionsBuilder<SAEContext>()
.UseSqlite(connection)
.Options;
using (var context = new StubbedContext(options))
{
context.Database.EnsureCreated();
var mockLogger = new Mock<ILogger<RoleController>>();
var controller = new RoleController(new RoleService(context), mockLogger.Object);
var result = await controller.GetRoles(0, 5);
Assert.IsNotNull(result.Value);
Assert.AreEqual(3, result.Value.TotalCount);
Assert.AreEqual(3, result.Value.Items.ToList()[2].Id);
Assert.AreEqual("Student", result.Value.Items.ToList()[2].Name);
}
}
}
}

@ -1,31 +0,0 @@
<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="coverlet.collector" Version="6.0.0" />
<PackageReference Include="Microsoft.Data.Sqlite.Core" Version="8.0.1" />
<PackageReference Include="Microsoft.NET.Test.Sdk" Version="17.8.0" />
<PackageReference Include="Moq" Version="4.20.70" />
<PackageReference Include="MSTest.TestAdapter" Version="3.1.1" />
<PackageReference Include="MSTest.TestFramework" Version="3.1.1" />
</ItemGroup>
<ItemGroup>
<ProjectReference Include="..\API\API.csproj" />
<ProjectReference Include="..\DbContext\DbContextLib.csproj" />
<ProjectReference Include="..\StubbedContext\StubbedContextLib.csproj" />
</ItemGroup>
<ItemGroup>
<Using Include="Microsoft.VisualStudio.TestTools.UnitTesting" />
</ItemGroup>
</Project>

@ -1,151 +0,0 @@
using API.Controllers;
using DbContextLib;
using DTO;
using DTOToEntity;
using Microsoft.Data.Sqlite;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Logging;
using Moq;
using StubbedContextLib;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace TU
{
[TestClass]
public class TranslateTU
{
[TestMethod]
public async Task TestAddTranslate()
{
var connection = new SqliteConnection("DataSource=:memory:");
connection.Open();
var options = new DbContextOptionsBuilder<SAEContext>()
.UseSqlite(connection)
.Options;
using (var context = new StubbedContext(options))
{
context.Database.EnsureCreated();
var mockLogger = new Mock<ILogger<TranslateController>>();
var controller = new TranslateController(new TranslateService(context), mockLogger.Object);
var newTranslate = new TranslateDTO { Id = 2, WordsId = "test", VocabularyListVocId = 1 };
var result = await controller.AddTranslate(newTranslate);
Assert.IsNotNull(result.Value);
Assert.AreEqual(newTranslate.Id, result.Value.Id);
Assert.AreEqual(newTranslate.WordsId, result.Value.WordsId);
Assert.AreEqual(newTranslate.VocabularyListVocId, result.Value.VocabularyListVocId);
}
}
[TestMethod]
public async Task TestGetTranslate()
{
var connection = new SqliteConnection("DataSource=:memory:");
connection.Open();
var options = new DbContextOptionsBuilder<SAEContext>()
.UseSqlite(connection)
.Options;
using (var context = new StubbedContext(options))
{
context.Database.EnsureCreated();
var mockLogger = new Mock<ILogger<TranslateController>>();
var controller = new TranslateController(new TranslateService(context), mockLogger.Object);
var result = await controller.GetTranslate(1);
Assert.IsNotNull(result.Value);
Assert.AreEqual(1, result.Value.Id);
Assert.AreEqual("1", result.Value.WordsId);
Assert.AreEqual(1, result.Value.VocabularyListVocId);
}
}
[TestMethod]
public async Task TestGetTranslates()
{
var connection = new SqliteConnection("DataSource=:memory:");
connection.Open();
var options = new DbContextOptionsBuilder<SAEContext>()
.UseSqlite(connection)
.Options;
using (var context = new StubbedContext(options))
{
context.Database.EnsureCreated();
var mockLogger = new Mock<ILogger<TranslateController>>();
var controller = new TranslateController(new TranslateService(context), mockLogger.Object);
var result = await controller.GetTranslates(0, 1);
Assert.IsNotNull(result.Value);
Assert.AreEqual(1, result.Value.TotalCount);
Assert.AreEqual(1, result.Value.Items.ToList()[0].Id);
Assert.AreEqual("1", result.Value.Items.ToList()[0].WordsId);
Assert.AreEqual(1, result.Value.Items.ToList()[0].VocabularyListVocId);
}
}
[TestMethod]
public async Task TestUpdateTranslate()
{
var connection = new SqliteConnection("DataSource=:memory:");
connection.Open();
var options = new DbContextOptionsBuilder<SAEContext>()
.UseSqlite(connection)
.Options;
using (var context = new StubbedContext(options))
{
context.Database.EnsureCreated();
var mockLogger = new Mock<ILogger<TranslateController>>();
var controller = new TranslateController(new TranslateService(context), mockLogger.Object);
var newTranslate = await context.Translates.FirstOrDefaultAsync(t => t.Id == 1);
newTranslate.WordsId = "modifié";
var result = await controller.UpdateTranslate(newTranslate.ToDTO());
Assert.IsNotNull(result.Value);
Assert.AreEqual(1, result.Value.Id);
Assert.AreEqual("modifié", result.Value.WordsId);
Assert.AreEqual(1, result.Value.VocabularyListVocId);
}
}
[TestMethod]
public async Task TestDeleteTranslate()
{
var connection = new SqliteConnection("DataSource=:memory:");
connection.Open();
var options = new DbContextOptionsBuilder<SAEContext>()
.UseSqlite(connection)
.Options;
using (var context = new StubbedContext(options))
{
context.Database.EnsureCreated();
var mockLogger = new Mock<ILogger<TranslateController>>();
var controller = new TranslateController(new TranslateService(context), mockLogger.Object);
var result = await controller.DeleteTranslate(1);
Assert.IsNotNull(result.Value);
Assert.AreEqual(1, result.Value.Id);
Assert.AreEqual("1", result.Value.WordsId);
Assert.AreEqual(1, result.Value.VocabularyListVocId);
var res = await context.Translates.FirstOrDefaultAsync(t => t.Id == 1);
Assert.IsNull(res);
}
}
}
}

@ -1,262 +0,0 @@
using API.Controllers;
using DbContextLib;
using DTO;
using DTOToEntity;
using Microsoft.Data.Sqlite;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Logging;
using Moq;
using StubbedContextLib;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace TU
{
[TestClass]
public class UserTU
{
[TestMethod]
public async Task TestAddUser()
{
var connection = new SqliteConnection("DataSource=:memory:");
connection.Open();
var options = new DbContextOptionsBuilder<SAEContext>()
.UseSqlite(connection)
.Options;
using (var context = new StubbedContext(options))
{
context.Database.EnsureCreated();
var mockLogger = new Mock<ILogger<UserController>>();
var controller = new UserController(new UserService(context), mockLogger.Object);
var newUser = new UserDTO { Id = 100, Name = "test", Email = "e", ExtraTime = false, image = "img", NickName = "nick", Password = "pass", UserName = "username", GroupId = 1, RoleId = 2 };
var result = await controller.AddUser(newUser);
Assert.IsNotNull(result);
Assert.AreEqual(newUser.Id, result.Value.Id);
Assert.AreEqual(newUser.Name, result.Value.Name);
Assert.AreEqual(newUser.Email, result.Value.Email);
}
}
[TestMethod]
public async Task TestDeleteUser()
{
var connection = new SqliteConnection("DataSource=:memory:");
connection.Open();
var options = new DbContextOptionsBuilder<SAEContext>()
.UseSqlite(connection)
.Options;
using (var context = new StubbedContext(options))
{
context.Database.EnsureCreated();
var mockLogger = new Mock<ILogger<UserController>>();
var controller = new UserController(new UserService(context), mockLogger.Object);
var result2 = await controller.DeleteUser(1);
Assert.IsNotNull(result2);
Assert.AreEqual(1, result2.Value.Id);
Assert.AreEqual("name", result2.Value.Name);
Assert.AreEqual("", result2.Value.Email);
Assert.AreEqual(true, result2.Value.ExtraTime);
Assert.AreEqual(null, result2.Value.image);
Assert.AreEqual("nickname", result2.Value.NickName);
Assert.AreEqual("username", result2.Value.UserName);
Assert.AreEqual(1, result2.Value.GroupId);
Assert.AreEqual(1, result2.Value.RoleId);
Assert.AreEqual("1234", result2.Value.Password);
var res = await context.Users.FirstOrDefaultAsync(l => l.Id == result2.Value.Id);
Assert.IsNull(res);
}
}
[TestMethod]
public async Task TestGetUser()
{
var connection = new SqliteConnection("DataSource=:memory:");
connection.Open();
var options = new DbContextOptionsBuilder<SAEContext>()
.UseSqlite(connection)
.Options;
using (var context = new StubbedContext(options))
{
context.Database.EnsureCreated();
var mockLogger = new Mock<ILogger<UserController>>();
var controller = new UserController(new UserService(context), mockLogger.Object);
var result2 = await controller.GetUser(1);
Assert.IsNotNull(result2);
Assert.AreEqual(1, result2.Value.Id);
Assert.AreEqual("name", result2.Value.Name);
Assert.AreEqual("", result2.Value.Email);
Assert.AreEqual(true, result2.Value.ExtraTime);
Assert.AreEqual(null, result2.Value.image);
Assert.AreEqual("nickname", result2.Value.NickName);
Assert.AreEqual("username", result2.Value.UserName);
Assert.AreEqual(1, result2.Value.GroupId);
Assert.AreEqual(1, result2.Value.RoleId);
Assert.AreEqual("1234", result2.Value.Password);
}
}
[TestMethod]
public async Task TestGetUsers()
{
var connection = new SqliteConnection("DataSource=:memory:");
connection.Open();
var options = new DbContextOptionsBuilder<SAEContext>()
.UseSqlite(connection)
.Options;
using (var context = new StubbedContext(options))
{
context.Database.EnsureCreated();
var mockLogger = new Mock<ILogger<UserController>>();
var controller = new UserController(new UserService(context), mockLogger.Object);
var result = await controller.GetUsers(0,5);
Assert.IsNotNull(result.Value);
Assert.AreEqual(3, result.Value.TotalCount);
Assert.AreEqual(1, result.Value.Items.First().Id);
Assert.AreEqual("name", result.Value.Items.First().Name);
Assert.AreEqual("", result.Value.Items.First().Email);
Assert.AreEqual(true, result.Value.Items.First().ExtraTime);
Assert.AreEqual(null, result.Value.Items.First().image);
Assert.AreEqual("nickname", result.Value.Items.First().NickName);
Assert.AreEqual("username", result.Value.Items.First().UserName);
Assert.AreEqual(1, result.Value.Items.First().GroupId);
Assert.AreEqual(1, result.Value.Items.First().RoleId);
Assert.AreEqual("1234", result.Value.Items.First().Password);
}
}
[TestMethod]
public async Task TestGetUsersByGroup()
{
var connection = new SqliteConnection("DataSource=:memory:");
connection.Open();
var options = new DbContextOptionsBuilder<SAEContext>()
.UseSqlite(connection)
.Options;
using (var context = new StubbedContext(options))
{
context.Database.EnsureCreated();
var mockLogger = new Mock<ILogger<UserController>>();
var controller = new UserController(new UserService(context), mockLogger.Object);
var result = await controller.GetUsersByGroup(0, 5, 1);
Assert.IsNotNull(result.Value);
Assert.AreEqual(3, result.Value.TotalCount);
Assert.AreEqual(1, result.Value.Items.First().Id);
Assert.AreEqual("name", result.Value.Items.First().Name);
Assert.AreEqual("", result.Value.Items.First().Email);
Assert.AreEqual(true, result.Value.Items.First().ExtraTime);
Assert.AreEqual(null, result.Value.Items.First().image);
Assert.AreEqual("nickname", result.Value.Items.First().NickName);
Assert.AreEqual("username", result.Value.Items.First().UserName);
Assert.AreEqual(1, result.Value.Items.First().GroupId);
Assert.AreEqual(1, result.Value.Items.First().RoleId);
Assert.AreEqual("1234", result.Value.Items.First().Password);
}
}
[TestMethod]
public async Task TestUpdateUser()
{
var connection = new SqliteConnection("DataSource=:memory:");
connection.Open();
var options = new DbContextOptionsBuilder<SAEContext>()
.UseSqlite(connection)
.Options;
using (var context = new StubbedContext(options))
{
context.Database.EnsureCreated();
var newUser = new UserDTO { Id = 4, Name = "test", Email = "e", ExtraTime = false, image = "img", NickName = "nick", Password = "pass", UserName = "username", GroupId = 1, RoleId = 2 };
var newUser2 = new UserDTO { Id = 4, Name = "test2", Email = "e2", ExtraTime = false, image = "img2", NickName = "nick2", Password = "pass2", UserName = "username2", GroupId = 1, RoleId = 3 };
var mockLogger = new Mock<ILogger<UserController>>();
var controller = new UserController(new UserService(context), mockLogger.Object);
var result = await controller.AddUser(newUser);
Assert.IsNotNull(result);
Assert.AreEqual(newUser.Id, result.Value.Id);
Assert.AreEqual(newUser.Name, result.Value.Name);
Assert.AreEqual(newUser.Email, result.Value.Email);
var result2 = await controller.UpdateUser(newUser2);
Assert.IsNotNull(result2.Value);
Assert.AreEqual(newUser2.Id, result2.Value.Id);
Assert.AreEqual(newUser2.Name, result2.Value.Name);
Assert.AreEqual(newUser2.Email, result2.Value.Email);
Assert.AreEqual(newUser2.ExtraTime, result2.Value.ExtraTime);
Assert.AreEqual(newUser2.image, result2.Value.image);
Assert.AreEqual(newUser2.NickName, result2.Value.NickName);
Assert.AreEqual(newUser2.Password, result2.Value.Password);
Assert.AreEqual(newUser2.UserName, result2.Value.UserName);
Assert.AreEqual(newUser2.GroupId, result2.Value.GroupId);
Assert.AreEqual(newUser2.RoleId, result2.Value.RoleId);
}
}
[TestMethod]
public async Task TestGetUsersByRole()
{
var connection = new SqliteConnection("DataSource=:memory:");
connection.Open();
var options = new DbContextOptionsBuilder<SAEContext>()
.UseSqlite(connection)
.Options;
using (var context = new StubbedContext(options))
{
context.Database.EnsureCreated();
var mockLogger = new Mock<ILogger<UserController>>();
var controller = new UserController(new UserService(context), mockLogger.Object);
var result = await controller.GetUsersByRole(0, 5, "Student");
Assert.IsNotNull(result.Value);
Assert.AreEqual(3, result.Value.TotalCount);
Assert.AreEqual(3, result.Value.Items.ToList()[0].Id) ;
Assert.AreEqual("name3", result.Value.Items.Last().Name);
Assert.AreEqual("", result.Value.Items.Last().Email);
}
}
}
}

@ -1,185 +0,0 @@
using API.Controllers;
using DbContextLib;
using DTO;
using DTOToEntity;
using Microsoft.Data.Sqlite;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Logging;
using Moq;
using StubbedContextLib;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace TU
{
[TestClass]
public class VocabularyListTU
{
[TestMethod]
public async Task TestAddVocabularyList()
{
var connection = new SqliteConnection("DataSource=:memory:");
connection.Open();
var options = new DbContextOptionsBuilder<SAEContext>()
.UseSqlite(connection)
.Options;
using (var context = new StubbedContext(options))
{
context.Database.EnsureCreated();
var mockLogger = new Mock<ILogger<VocabularyListController>>();
var controller = new VocabularyListController(new VocabularyListService(context), mockLogger.Object);
var newVocabList = new VocabularyListDTO { Id = 2, Name = "TestVocabList", Image="img", UserId=1 };
var result = await controller.AddVocabularyList(newVocabList);
Assert.IsNotNull(result.Value);
Assert.AreEqual(newVocabList.Name, result.Value.Name);
var res = await context.VocabularyLists.FirstOrDefaultAsync(v => v.Id == 2);
Assert.IsNotNull(res);
Assert.AreEqual(newVocabList.Name, res.Name);
}
}
[TestMethod]
public async Task TestDeleteVocabularyList()
{
var connection = new SqliteConnection("DataSource=:memory:");
connection.Open();
var options = new DbContextOptionsBuilder<SAEContext>()
.UseSqlite(connection)
.Options;
using (var context = new StubbedContext(options))
{
context.Database.EnsureCreated();
var mockLogger = new Mock<ILogger<VocabularyListController>>();
var controller = new VocabularyListController(new VocabularyListService(context), mockLogger.Object);
var deleteResult = await controller.DeleteVocabularyList(1);
Assert.IsNotNull(deleteResult.Value);
Assert.AreEqual("Liste1", deleteResult.Value.Name);
var res2 = await context.VocabularyLists.FirstOrDefaultAsync(v => v.Id == 1);
Assert.IsNull(res2);
}
}
[TestMethod]
public async Task TestGetVocabularyListById()
{
var connection = new SqliteConnection("DataSource=:memory:");
connection.Open();
var options = new DbContextOptionsBuilder<SAEContext>()
.UseSqlite(connection)
.Options;
using (var context = new StubbedContext(options))
{
context.Database.EnsureCreated();
var mockLogger = new Mock<ILogger<VocabularyListController>>();
var controller = new VocabularyListController(new VocabularyListService(context), mockLogger.Object);
var getResult = await controller.GetVocabularyList(1);
Assert.IsNotNull(getResult.Value);
Assert.AreEqual("Liste1", getResult.Value.Name);
Assert.AreEqual("image1", getResult.Value.Image);
}
}
[TestMethod]
public async Task TestGetVocabularyLists()
{
var connection = new SqliteConnection("DataSource=:memory:");
connection.Open();
var options = new DbContextOptionsBuilder<SAEContext>()
.UseSqlite(connection)
.Options;
using (var context = new StubbedContext(options))
{
context.Database.EnsureCreated();
var mockLogger = new Mock<ILogger<VocabularyListController>>();
var controller = new VocabularyListController(new VocabularyListService(context), mockLogger.Object);
var getResult = await controller.GetVocabularyLists(0, 5);
Assert.IsNotNull(getResult.Value);
Assert.AreEqual(1, getResult.Value.TotalCount);
}
}
[TestMethod]
public async Task TestUpdateVocabularyList()
{
var connection = new SqliteConnection("DataSource=:memory:");
connection.Open();
var options = new DbContextOptionsBuilder<SAEContext>()
.UseSqlite(connection)
.Options;
using (var context = new StubbedContext(options))
{
context.Database.EnsureCreated();
var mockLogger = new Mock<ILogger<VocabularyListController>>();
var controller = new VocabularyListController(new VocabularyListService(context), mockLogger.Object);
var newVocabList = new VocabularyListDTO { Id = 1, Name = "TestVocabList", Image = "img", UserId = 1 };
var result = await controller.UpdateVocabularyList(newVocabList);
Assert.IsNotNull(result.Value);
Assert.AreEqual(newVocabList.Name, result.Value.Name);
var res = await context.VocabularyLists.FirstOrDefaultAsync(v => v.Id == 1);
Assert.IsNotNull(res);
Assert.AreEqual(newVocabList.Name, res.Name);
}
}
[TestMethod]
public async Task TestGetVocabularyListByUser()
{
var connection = new SqliteConnection("DataSource=:memory:");
connection.Open();
var options = new DbContextOptionsBuilder<SAEContext>()
.UseSqlite(connection)
.Options;
using (var context = new StubbedContext(options))
{
context.Database.EnsureCreated();
var mockLogger = new Mock<ILogger<VocabularyListController>>();
var controller = new VocabularyListController(new VocabularyListService(context), mockLogger.Object);
var getResult = await controller.GetVocabularyListsByUser(0, 5, 1);
Assert.IsNotNull(getResult.Value);
Assert.AreEqual(1, getResult.Value.TotalCount);
Assert.AreEqual("Liste1", getResult.Value.Items.ToList()[0].Name);
Assert.AreEqual("image1", getResult.Value.Items.ToList()[0].Image);
Assert.AreEqual(1, getResult.Value.Items.ToList()[0].UserId);
}
}
}
}

@ -1,179 +0,0 @@
using API.Controllers;
using DbContextLib;
using DTO;
using DTOToEntity;
using Entities;
using Microsoft.Data.Sqlite;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Logging;
using Moq;
using StubbedContextLib;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace TU
{
[TestClass]
public class VocabularyTU
{
[TestMethod]
public async Task TestAddVocabulary()
{
var connection = new SqliteConnection("DataSource=:memory:");
connection.Open();
var options = new DbContextOptionsBuilder<SAEContext>()
.UseSqlite(connection)
.Options;
using (var context = new StubbedContext(options))
{
context.Database.EnsureCreated();
var mockLogger = new Mock<ILogger<VocabularyController>>();
var controller = new VocabularyController(new VocabularyService(context), mockLogger.Object);
var newVocab = new VocabularyDTO { LangueName = "French", word = "baguette" };
var result = await controller.AddVocabulary(newVocab);
Assert.IsNotNull(result.Value);
var res = context.Vocabularys.FirstOrDefault(v => v.word == result.Value.word);
Assert.IsNotNull(res);
Assert.AreEqual(newVocab.LangueName, res.LangueName);
Assert.AreEqual(newVocab.word, res.word);
}
}
[TestMethod]
public async Task TestDeleteVocabulary()
{
var connection = new SqliteConnection("DataSource=:memory:");
connection.Open();
var options = new DbContextOptionsBuilder<SAEContext>()
.UseSqlite(connection)
.Options;
using (var context = new StubbedContext(options))
{
context.Database.EnsureCreated();
var mockLogger = new Mock<ILogger<VocabularyController>>();
var controller = new VocabularyController(new VocabularyService(context), mockLogger.Object);
var vocab = context.Vocabularys.FirstOrDefault(v => v.word == "Bonjour");
var delResult = await controller.DeleteVocabulary(vocab.word);
Assert.IsNotNull(delResult.Value);
var delRes = context.Vocabularys.FirstOrDefault(v => v.word == delResult.Value.word);
Assert.IsNull(delRes);
}
}
[TestMethod]
public async Task TestGetVocabulary()
{
var connection = new SqliteConnection("DataSource=:memory:");
connection.Open();
var options = new DbContextOptionsBuilder<SAEContext>()
.UseSqlite(connection)
.Options;
using (var context = new StubbedContext(options))
{
context.Database.EnsureCreated();
var mockLogger = new Mock<ILogger<VocabularyController>>();
var controller = new VocabularyController(new VocabularyService(context), mockLogger.Object);
var getResult = await controller.GetVocabulary("Bonjour");
Assert.IsNotNull(getResult.Value);
Assert.AreEqual("French", getResult.Value.LangueName);
Assert.AreEqual("Bonjour", getResult.Value.word);
}
}
[TestMethod]
public async Task TestGetVocabularies()
{
var connection = new SqliteConnection("DataSource=:memory:");
connection.Open();
var options = new DbContextOptionsBuilder<SAEContext>()
.UseSqlite(connection)
.Options;
using (var context = new StubbedContext(options))
{
context.Database.EnsureCreated();
var mockLogger = new Mock<ILogger<VocabularyController>>();
var controller = new VocabularyController(new VocabularyService(context), mockLogger.Object);
var getResult = await controller.GetVocabularies(0, 10);
Assert.IsNotNull(getResult.Value);
Assert.AreEqual(1, getResult.Value.TotalCount);
Assert.AreEqual("Bonjour", getResult.Value.Items.Last().word);
Assert.AreEqual("French", getResult.Value.Items.Last().LangueName);
}
}
[TestMethod]
public async Task TestUpdateVocabulary()
{
var connection = new SqliteConnection("DataSource=:memory:");
connection.Open();
var options = new DbContextOptionsBuilder<SAEContext>()
.UseSqlite(connection)
.Options;
using (var context = new StubbedContext(options))
{
context.Database.EnsureCreated();
var mockLogger = new Mock<ILogger<VocabularyController>>();
var controller = new VocabularyController(new VocabularyService(context), mockLogger.Object);
var newVocab = new VocabularyDTO { LangueName = "English", word = "Bonjour" };
var updateResult = await controller.UpdateVocabulary(newVocab);
Assert.IsNotNull(updateResult.Value);
var updatedRes = context.Vocabularys.FirstOrDefault(v => v.word == newVocab.word);
Assert.IsNotNull(updatedRes);
Assert.AreEqual(newVocab.word, updatedRes.word);
}
}
[TestMethod]
public async Task TestGetVocabulariesByLangue()
{
var connection = new SqliteConnection("DataSource=:memory:");
connection.Open();
var options = new DbContextOptionsBuilder<SAEContext>()
.UseSqlite(connection)
.Options;
using (var context = new StubbedContext(options))
{
context.Database.EnsureCreated();
var mockLogger = new Mock<ILogger<VocabularyController>>();
var controller = new VocabularyController(new VocabularyService(context), mockLogger.Object);
var getResult = await controller.GetByLangue("French", 0, 10);
Assert.IsNotNull(getResult.Value);
Assert.AreEqual(1, getResult.Value.TotalCount);
Assert.AreEqual("Bonjour", getResult.Value.Items.Last().word);
Assert.AreEqual("French", getResult.Value.Items.Last().LangueName);
}
}
}
}

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

Loading…
Cancel
Save