enorme avancer normalement le dernier commit. Corrections des Many To Many qui marchent tous, plus aucun probleme avec la bd, tous les Test marches et ajout du JWT fonctionnel.
continuous-integration/drone/push Build is passing Details

master
Patrick BRUGIERE 1 year ago
parent 679dfc1717
commit 532b3295f5

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

@ -0,0 +1,44 @@
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,11 +1,13 @@
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")]
@ -86,7 +88,7 @@ namespace API.Controllers
}
[HttpPost]
public async Task<ActionResult<GroupDTO>> AddGroup([FromQuery]GroupDTO group)
public async Task<ActionResult<GroupDTO>> AddGroup([FromBody]GroupDTO group)
{
try
{
@ -181,6 +183,43 @@ namespace API.Controllers
}
}
[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,11 +1,13 @@
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")]

@ -1,10 +1,12 @@

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")]

@ -1,19 +1,21 @@

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 IService<TranslateDTO> _service;
private readonly ITranslateService _service;
private readonly ILogger<TranslateController> _logger;
public TranslateController(IService<TranslateDTO> TranslateService, ILogger<TranslateController> logger)
public TranslateController(ITranslateService TranslateService, ILogger<TranslateController> logger)
{
_service = TranslateService;
_logger = logger;
@ -110,5 +112,24 @@ namespace API.Controllers
}
}
[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,10 +1,12 @@

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")]

@ -1,10 +1,12 @@

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")]
@ -135,5 +137,24 @@ namespace API.Controllers
}
}
[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,10 +1,12 @@

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")]
@ -135,5 +137,24 @@ namespace API.Controllers
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);
}
}
}
}

@ -11,6 +11,10 @@ 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.
@ -19,6 +23,68 @@ 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);
@ -28,7 +94,7 @@ builder.Services.AddApiVersioning(o =>
builder.Services.AddScoped<IGroupService, GroupService>();
builder.Services.AddScoped<IService<LangueDTO>,LangueService>();
builder.Services.AddScoped<IService<RoleDTO>,RoleService>();
builder.Services.AddScoped<IService<TranslateDTO>,TranslateService>();
builder.Services.AddScoped<ITranslateService,TranslateService>();
builder.Services.AddScoped<IUserService, UserService>();
builder.Services.AddScoped<IVocabularyService, VocabularyService>();
builder.Services.AddScoped<IVocabularyListService, VocabularyListService>();
@ -40,8 +106,10 @@ if (app.Environment.IsDevelopment())
app.UseSwaggerUI();
}
app.UseHttpsRedirection();
app.UseAuthentication();
app.UseHttpsRedirection();
app.UseAuthorization();
app.MapControllers();

@ -5,5 +5,11 @@
"Microsoft.AspNetCore": "Warning"
}
},
"JwtTokenSettings": {
"ValidIssuer": "ExampleIssuer",
"ValidAudience": "ValidAudience",
"SymmetricSecurityKey": "fvh8456477hth44j6wfds98bq9hp8bqh9ubq9gjig3qr0[94vj5",
"JwtRegisteredClaimNamesSub": "345h098bb8reberbwr4vvb8945"
},
"AllowedHosts": "*"
}

@ -38,6 +38,42 @@ namespace DTOToEntity
return res.Entity.ToDTO(); ;
}
public async Task<UserDTO> AddUserToGroup(long idUser, long idGroup)
{
var group = context.Groups.Find(idGroup);
if (group == null)
{
throw new Exception("Group not found");
}
var user = context.Users.Find(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.Groups.Find(groupId);
if (group == null)
{
throw new Exception("Group not found");
}
var vocab = context.VocabularyLists.Find(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 = await context.Groups.FindAsync((long)id);
@ -64,25 +100,25 @@ namespace DTOToEntity
public async Task<PageResponse<GroupDTO>> GetByNum(int index, int count, int num)
{
var groups = context.Groups.Where(g => g.Num == num).Skip(index).Take(count);
var groups = context.Groups.Where(g => g.Num == num).Skip(index * count).Take(count);
return new PageResponse<GroupDTO>(groups.ToList().Select(g => g.ToDTO()), context.Groups.Count());
}
public async Task<PageResponse<GroupDTO>> GetBySector(int index, int count, string sector)
{
var groups = context.Groups.Where(g => g.sector == sector).Skip(index).Take(count);
var groups = context.Groups.Where(g => g.sector == sector).Skip(index * count).Take(count);
return new PageResponse<GroupDTO>(groups.ToList().Select(g => g.ToDTO()), context.Groups.Count());
}
public async Task<PageResponse<GroupDTO>> GetByYear(int index, int count, int year)
{
var groups = context.Groups.Where(g => g.year == year).Skip(index).Take(count);
var groups = context.Groups.Where(g => g.year == year).Skip(index * count).Take(count);
return new PageResponse<GroupDTO>(groups.ToList().Select(g => g.ToDTO()), context.Groups.Count());
}
public async Task<PageResponse<GroupDTO>> Gets(int index, int count)
{
IEnumerable<GroupEntity> groups = await context.Groups.Skip(index).Take(count).ToListAsync();
IEnumerable<GroupEntity> groups = await context.Groups.Skip(index * count).Take(count).ToListAsync();
return new PageResponse<GroupDTO>(groups.ToList().Select(g => g.ToDTO()), context.Groups.Count());
}

@ -12,5 +12,9 @@ namespace DTOToEntity
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);
}
}

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

@ -10,5 +10,7 @@ namespace DTOToEntity
public interface IVocabularyListService : IService<VocabularyListDTO>
{
Task<PageResponse<VocabularyListDTO>> GetByUser(int index, int count, int user);
Task<GroupDTO> AddGroupToVocabularyList(long groupId, long vocabId);
}
}

@ -10,5 +10,7 @@ namespace DTOToEntity
public interface IVocabularyService : IService<VocabularyDTO>
{
Task<PageResponse<VocabularyDTO>> GetByLangue(int index, int count, string langue);
Task<TranslateDTO> AddTranslationToVocabulary(string vocabId, long translateId);
}
}

@ -55,7 +55,7 @@ namespace DTOToEntity
public async Task<PageResponse<LangueDTO>> Gets(int index,int count)
{
IEnumerable<LangueEntity> langues = await _context.Langues.Skip(index).Take(count).ToListAsync();
IEnumerable<LangueEntity> langues = await _context.Langues.Skip(index * count).Take(count).ToListAsync();
return new PageResponse<LangueDTO>(langues.ToList().Select(l => l.ToDTO()), _context.Langues.Count());
}

@ -55,7 +55,7 @@ namespace DTOToEntity
public async Task<PageResponse<RoleDTO>> Gets(int index, int count)
{
IEnumerable<RoleEntity> roles = await _context.Roles.Skip(index).Take(count).ToListAsync();
IEnumerable<RoleEntity> roles = await _context.Roles.Skip(index * count).Take(count).ToListAsync();
return new PageResponse<RoleDTO>(roles.ToList().Select(r => r.ToDTO()), _context.Roles.Count());
}
@ -75,4 +75,4 @@ namespace DTOToEntity
return roleEntity.ToDTO();
}
}
}
}

@ -9,7 +9,7 @@ using System.Threading.Tasks;
namespace DTOToEntity
{
public class TranslateService : IService<TranslateDTO>
public class TranslateService : ITranslateService
{
private readonly StubbedContext _context = new StubbedContext();
@ -28,6 +28,23 @@ namespace DTOToEntity
}
public async Task<VocabularyDTO> AddVocabToTranslate(string vocabId, long translateId)
{
var vocab = _context.Vocabularys.Find(vocabId);
if (vocab == null)
{
throw new Exception("Vocabulary not found");
}
var translate = _context.Translates.Find(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 = await _context.Translates.FirstOrDefaultAsync(t => t.Id == (int)id);
@ -55,7 +72,7 @@ namespace DTOToEntity
public async Task<PageResponse<TranslateDTO>> Gets(int index, int count)
{
var translates = await _context.Translates.Skip(index).Take(count).ToListAsync();
var translates = await _context.Translates.Skip(index * count).Take(count).ToListAsync();
if(translates == null)
{
throw new Exception("No translates found");

@ -45,7 +45,7 @@ namespace DTOToEntity
public async Task<PageResponse<UserDTO>> GetByGroup(int index, int count, long group)
{
var users = _context.Users.Where(u => u.GroupId == group).Skip(index).Take(count);
var users = _context.Users.Where(u => u.GroupId == group).Skip(index * count).Take(count);
return new PageResponse<UserDTO>(users.Select(u => u.ToDTO()), _context.Users.Count());
}
@ -61,33 +61,14 @@ namespace DTOToEntity
public async Task<PageResponse<UserDTO>> GetByRole(int index, int count, string role)
{
long roleId = 0;
if(role == "Student")
{
role = "Student";
roleId = 3;
}
else if(role == "Teacher")
{
role = "Teacher";
roleId = 2;
}
else if(role == "Admin")
{
role = "Admin";
roleId = 1;
}
else
{
throw new Exception("Role not found");
}
var users = _context.Users.Where(u => u.RoleId == roleId).Skip(index).Take(count);
var users = _context.Users.Where(u => u.Role.Name == role).Skip(index * count).Take(count);
return new PageResponse<UserDTO>(users.Select(u => u.ToDTO()), _context.Users.Count());
}
public async Task<PageResponse<UserDTO>> Gets(int index, int count)
{
IEnumerable<UserEntity> users = await _context.Users.Skip(index).Take(count).ToListAsync();
IEnumerable<UserEntity> users = await _context.Users.Skip(index * count).Take(count).ToListAsync();
return new PageResponse<UserDTO>( users.Select(u => u.ToDTO()),_context.Users.Count());
}

@ -29,6 +29,24 @@ namespace DTOToEntity
return groupEntity.ToDTO();
}
public async Task<GroupDTO> AddGroupToVocabularyList(long groupId, long vocabId)
{
var group = _context.Groups.Find(groupId);
if (group == null)
{
throw new Exception("Group not found");
}
var vocab = _context.VocabularyLists.Find(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 = await _context.VocabularyLists.FindAsync(id);
@ -56,14 +74,14 @@ namespace DTOToEntity
public async Task<PageResponse<VocabularyListDTO>> GetByUser(int index, int count, int user)
{
var groups = _context.VocabularyLists.Where(g => g.UserId == user).Skip(index).Take(count);
var groups = _context.VocabularyLists.Where(g => g.UserId == user).Skip(index * count).Take(count);
return new PageResponse<VocabularyListDTO>(groups.Select(g => g.ToDTO()), _context.VocabularyLists.Count());
}
public async Task<PageResponse<VocabularyListDTO>> Gets(int index, int count)
{
var groups = await _context.VocabularyLists.Skip(index).Take(count).ToListAsync();
var groups = await _context.VocabularyLists.Skip(index * count).Take(count).ToListAsync();
return new PageResponse<VocabularyListDTO>(groups.Select(g => g.ToDTO()), _context.VocabularyLists.Count());
}

@ -32,6 +32,23 @@ namespace DTOToEntity
return vocabularyEntity.ToDTO();
}
public async Task<TranslateDTO> AddTranslationToVocabulary(string vocabId, long translateId)
{
var vocabulary = _context.Vocabularys.Find(vocabId);
if(vocabulary == null)
{
throw new Exception("Vocabulary not found");
}
var translate = _context.Translates.Find(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 = await _context.Vocabularys.FirstOrDefaultAsync(v => v.word == (string)id);
@ -56,14 +73,14 @@ namespace DTOToEntity
public async Task<PageResponse<VocabularyDTO>> GetByLangue(int index, int count, string langue)
{
var vocabularies = _context.Vocabularys.Where(v => v.LangueName == langue).Skip(index).Take(count);
var vocabularies = _context.Vocabularys.Where(v => v.LangueName == langue).Skip(index * count).Take(count);
return new PageResponse<VocabularyDTO>(vocabularies.ToList().Select(v => v.ToDTO()), _context.Vocabularys.Count());
}
public async Task<PageResponse<VocabularyDTO>> Gets(int index, int count)
{
var vocabulary = await _context.Vocabularys.Skip(index).Take(count).ToListAsync();
var vocabulary = await _context.Vocabularys.Skip(index * count).Take(count).ToListAsync();
return new PageResponse<VocabularyDTO>(vocabulary.Select(v => v.ToDTO()), _context.Vocabularys.Count());
}

@ -14,7 +14,7 @@ namespace DTOToEntity
year = group.Year,
sector = group.sector,
//Users = group.Users.Select(u => u.ToEntity()).ToList(),
//VocabularyList = group.VocabularyList.Select(v => v.ToEntity()).ToList()
//GroupVocabularyList = group.GroupVocabularyList.Select(v => v.ToEntity()).ToList()
};
}
@ -27,7 +27,7 @@ namespace DTOToEntity
Year = group.year,
sector = group.sector,
//Users = group.Users.Select(u => u.ToDTO()).ToList(),
//VocabularyList = group.VocabularyList.Select(v => v.ToDTO()).ToList()
//GroupVocabularyList = group.GroupVocabularyList.Select(v => v.ToDTO()).ToList()
};
}
public static LangueEntity ToEntity(this LangueDTO langue)
@ -71,7 +71,7 @@ namespace DTOToEntity
{
Id = translate.Id,
WordsId = translate.WordsId,
//Words = translate.Words.Select(w => w.ToEntity()).ToList(),
//TransVoc = translate.TransVoc.Select(w => w.ToEntity()).ToList(),
//VocabularyListVoc = translate.VocabularyListVoc.ToEntity(),
VocabularyListVocId = translate.VocabularyListVocId,
};
@ -82,7 +82,7 @@ namespace DTOToEntity
{
Id = translate.Id,
WordsId = translate.WordsId,
//Words = translate.Words.Select(w => w.ToDTO()).ToList(),
//TransVoc = translate.TransVoc.Select(w => w.ToDTO()).ToList(),
//VocabularyListVoc = translate.VocabularyListVoc.ToDTO(),
VocabularyListVocId = translate.VocabularyListVocId,
};
@ -128,7 +128,7 @@ namespace DTOToEntity
return new VocabularyEntity
{
word = vocabulary.word,
//translations = vocabulary.translations.Select(t => t.ToEntity()).ToList(),
//Voctranslations = vocabulary.Voctranslations.Select(t => t.ToEntity()).ToList(),
LangueName = vocabulary.LangueName,
//Langue = vocabulary.Langue.ToEntity()
@ -139,7 +139,7 @@ namespace DTOToEntity
return new VocabularyDTO
{
word = vocabulary.word,
//translations = vocabulary.translations.Select(t => t.ToDTO()).ToList(),
//Voctranslations = vocabulary.Voctranslations.Select(t => t.ToDTO()).ToList(),
LangueName = vocabulary.LangueName,
//Langue = vocabulary.Langue.ToDTO()
};
@ -152,8 +152,8 @@ namespace DTOToEntity
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()
//translations = vocabularyList.translations.Select(t => t.ToEntity()).ToList(),
//VocsGroups = vocabularyList.VocsGroups.Select(g => g.ToEntity()).ToList()
};
}
public static VocabularyListDTO ToDTO(this VocabularyListEntity vocabularyList)
@ -164,8 +164,8 @@ namespace DTOToEntity
Name = vocabularyList.Name,
Image = vocabularyList.Image,
UserId = vocabularyList.UserId,
//translation = vocabularyList.translation.Select(t => t.ToDTO()).ToList(),
//Groups = vocabularyList.Groups.Select(g => g.ToDTO()).ToList()
//translations = vocabularyList.translations.Select(t => t.ToDTO()).ToList(),
//VocsGroups = vocabularyList.VocsGroups.Select(g => g.ToDTO()).ToList()
};
}
}

@ -17,8 +17,8 @@ namespace DbContextLib
public DbSet<VocabularyListEntity> GroupVocabularyList { get; set; }
public DbSet<GroupEntity> VocsGroups { get; set; }
public DbSet<VocabularyEntity> Voctranslations { get; set; }
public DbSet<TranslateEntity> TransVoc { get; set; }
public DbSet<TranslateEntity> Voctranslations { get; set; }
public DbSet<VocabularyEntity> TransVoc { get; set; }
//permet de créer une base de donnée (fichier .db) ici en Sqlite avec le nom Db.Books.db

@ -11,7 +11,7 @@ namespace Entities
public string sector { get; set; }
public ICollection<UserEntity> Users { get; set; } = new List<UserEntity>();
public ICollection<VocabularyListEntity> VocabularyList { get; set; } = new List<VocabularyListEntity>();
public ICollection<VocabularyListEntity> GroupVocabularyList { get; set; } = new List<VocabularyListEntity>();
public string toString()
{

@ -14,7 +14,7 @@ namespace Entities
[ForeignKey(nameof(WordsId))]
public string WordsId { get; set; }
public ICollection<VocabularyEntity> Words { get; set; } = new List<VocabularyEntity>();
public ICollection<VocabularyEntity> TransVoc { get; set; } = new List<VocabularyEntity>();
[ForeignKey(nameof(VocabularyListVocId))]
public long VocabularyListVocId { get; set; }
@ -22,7 +22,7 @@ namespace Entities
public string toString()
{
return Id + "" + WordsId ;
return "Id : " + Id +" wordId : " + WordsId + " VocabularyListVocId : " + VocabularyListVocId ;
}
}
}

@ -13,7 +13,7 @@ namespace Entities
[Key]
[DatabaseGenerated(DatabaseGeneratedOption.None)]
public string word { get; set; }
public ICollection<TranslateEntity> translations { get; set; } = new List<TranslateEntity>();
public ICollection<TranslateEntity> Voctranslations { get; set; } = new List<TranslateEntity>();
[ForeignKey(nameof(LangueName))]
public string LangueName { get; set; }

@ -17,7 +17,12 @@ namespace Entities
public long UserId { get; set; }
public UserEntity? User { get; set; } = null;
public ICollection<TranslateEntity> translation { get; set; } = new List<TranslateEntity>();
public ICollection<GroupEntity> Groups { get; set; } = new List<GroupEntity>();
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,14 +0,0 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Entities
{
public class VocabularyListGroup
{
public long GroupId { get; set; }
public long VocabularyListId { get; set; }
}
}

@ -1,14 +0,0 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Entities
{
public class VocabularyTranslateEntity
{
public string Word { get; set; }
public string Translation { get; set; }
}
}

@ -257,5 +257,66 @@ namespace TU
}
}
[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);
}
}
[TestMethod]
public async Task TestAddVocabListToGroup()
{
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.AddVocabularyListToGroup(1, 1);
Assert.IsNotNull(result.Value);
Assert.AreEqual(1, result.Value.Id);
var test = await context.Groups.FirstOrDefaultAsync(g => g.Id == 1);
var testVocab = await context.VocabularyLists.FirstOrDefaultAsync(g => g.Id == 1);
Assert.IsNotNull(test);
Assert.IsNotNull(testVocab);
Assert.AreEqual(test.GroupVocabularyList.First(), testVocab);
}
}
}
}

@ -147,5 +147,38 @@ namespace TU
Assert.IsNull(res);
}
}
[TestMethod]
public async Task TestAddVocabToTranslate()
{
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.AddVocab("Bonjour", 1);
Assert.IsNotNull(result.Value);
Assert.AreEqual("Bonjour", result.Value.word);
var res = await context.Translates.FirstOrDefaultAsync(v => v.Id == 1);
Assert.IsNotNull(res);
var test = res.TransVoc.FirstOrDefault(t => t.word == "Bonjour");
Assert.IsNotNull(test);
Assert.AreEqual("Bonjour", test.word);
var test2 = await context.TransVoc.FirstOrDefaultAsync(t => t.word == "Bonjour");
Assert.IsNotNull(test2);
Assert.AreEqual("Bonjour", test2.word);
}
}
}
}

@ -179,6 +179,43 @@ namespace TU
}
}
[TestMethod]
public async Task TestAddGroupToVocabularyList()
{
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 result = await controller.AddGroupToVocabularyList(1, 1);
Assert.IsNotNull(result.Value);
Assert.AreEqual("informatics", result.Value.sector);
Assert.AreEqual(1, result.Value.Id);
var res = await context.VocabularyLists.FirstOrDefaultAsync(v => v.Id == 1);
Assert.IsNotNull(res);
var test = res.VocsGroups.FirstOrDefault(g => g.Id == 1);
Assert.IsNotNull(test);
Assert.AreEqual("informatics", test.sector);
Assert.AreEqual(1, test.Id);
var test2 = await context.VocsGroups.FirstOrDefaultAsync(g => g.Id == 1);
Assert.IsNotNull(test2);
Assert.AreEqual("informatics", test2.sector);
Assert.AreEqual(1, test2.Id);
}
}
}

@ -174,6 +174,43 @@ namespace TU
}
}
[TestMethod]
public async Task TestAddTranslation()
{
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 result3 = await controller.AddTranslation("Bonjour",1);
Assert.IsNotNull(result3.Value);
Assert.AreEqual(1, result3.Value.Id);
var res = await context.Vocabularys.FirstOrDefaultAsync(v => v.word == "Bonjour");
Assert.IsNotNull(res);
var test = res.Voctranslations.FirstOrDefault(t => t.Id == 1);
Assert.IsNotNull(test);
Assert.AreEqual(1, test.Id);
var test2 = await context.Voctranslations.FirstOrDefaultAsync(t => t.Id == 1);
Assert.IsNotNull(test2);
Assert.AreEqual(1, test2.Id);
}
}
}
}

@ -19,11 +19,11 @@ var getGroup = await client.GetAsync("Group/1");
Console.WriteLine("rep : " + getGroup.StatusCode);
Console.WriteLine("test get Group" + await getGroup.Content.ReadAsStringAsync());
var addGroup = await client.PostAsJsonAsync("Group", new GroupDTO{ Id=2, Num = 1, sector = "sector1", Year = 2024 });
var addGroup = await client.PostAsJsonAsync("Group", new GroupDTO { Num = 1, Year = 2025, sector = "newSec" });
Console.WriteLine("rep : " + addGroup.StatusCode);
Console.WriteLine("test add Group" + await addGroup.Content.ReadAsStringAsync());
var updateGroup = await client.PutAsJsonAsync("Group", new GroupDTO{Id=2, Num = 1, sector = "sector1", Year = 2024 });
var updateGroup = await client.PutAsJsonAsync("Group", new GroupDTO{ Num =1, Year =2025, sector = "SectorModif"});
Console.WriteLine("rep : " + updateGroup.StatusCode);
Console.WriteLine("test update Group" + await updateGroup.Content.ReadAsStringAsync());
@ -44,7 +44,7 @@ var addTranslate = await client.PostAsJsonAsync("Translate", new TranslateDTO{
Console.WriteLine("rep : " + addTranslate.StatusCode);
Console.WriteLine("test add Translate" + await addTranslate.Content.ReadAsStringAsync());
var updateTranslate = await client.PutAsJsonAsync("Translate/1", new TranslateDTO{ WordsId = "Bonjour", VocabularyListVocId = 1 });
var updateTranslate = await client.PutAsJsonAsync("Translate", new TranslateDTO{ WordsId = "Bonjour", VocabularyListVocId = 1 });
Console.WriteLine("rep : " + updateTranslate.StatusCode);
Console.WriteLine("test update Translate" + await updateTranslate.Content.ReadAsStringAsync());
@ -62,11 +62,11 @@ var getVocabularyList = await client.GetAsync("VocabularyList/1");
Console.WriteLine("rep : " + getVocabularyList.StatusCode);
Console.WriteLine("test get VocabularyList" + await getVocabularyList.Content.ReadAsStringAsync());
var addVocabularyList = await client.PostAsJsonAsync("VocabularyList", new VocabularyListDTO{ Id=2, Image="img", Name="name" });
var addVocabularyList = await client.PostAsJsonAsync("VocabularyList", new VocabularyListDTO{ Id=2, Image="img", Name="name", UserId=1 });
Console.WriteLine("rep : " + addVocabularyList.StatusCode);
Console.WriteLine("test add VocabularyList" + await addVocabularyList.Content.ReadAsStringAsync());
var updateVocabularyList = await client.PutAsJsonAsync("VocabularyList", new VocabularyListDTO { Id = 2, Image = "img2", Name = "name2" });
var updateVocabularyList = await client.PutAsJsonAsync("VocabularyList", new VocabularyListDTO { Id = 2, Image = "img2", Name = "name2", UserId=1 });
Console.WriteLine("rep : " + updateVocabularyList.StatusCode);
Console.WriteLine("test update VocabularyList" + await updateVocabularyList.Content.ReadAsStringAsync());
@ -87,7 +87,7 @@ var addVocabulary = await client.PostAsJsonAsync("Vocabulary", new VocabularyDTO
Console.WriteLine("rep : " + addVocabulary.StatusCode);
Console.WriteLine("test add Vocabulary" + await addVocabulary.Content.ReadAsStringAsync());
var updateVocabulary = await client.PutAsJsonAsync("Vocabulary", new { word = "Test", LangueName = "French" });
var updateVocabulary = await client.PutAsJsonAsync("Vocabulary", new VocabularyDTO{ word = "Test", LangueName = "French" });
Console.WriteLine("rep : " + updateVocabulary.StatusCode);
Console.WriteLine("test update Vocabulary" + await updateVocabulary.Content.ReadAsStringAsync());
@ -123,7 +123,41 @@ var getUser = await client.GetAsync("User/1");
Console.WriteLine("rep : " + getUser.StatusCode);
Console.WriteLine("test get User" + await getUser.Content.ReadAsStringAsync());
var addUser = await client.PostAsJsonAsync("User", new { email = "" });
var addUser = await client.PostAsJsonAsync("User", new UserDTO { Id=2, Email="em", ExtraTime=false, image="img", NickName="nickname", Password="password", Name="name", UserName="username", RoleId=1, GroupId=1 });
Console.WriteLine("rep : " + addUser.StatusCode);
Console.WriteLine("test add User" + await addUser.Content.ReadAsStringAsync());
var updateUser = await client.PutAsJsonAsync("User", new UserDTO { Id = 2, Email = "em2", ExtraTime = false, image = "img2", NickName = "nickname2", Password = "password2", Name = "name2", UserName = "username2", RoleId = 1, GroupId = 1 });
Console.WriteLine("rep : " + updateUser.StatusCode);
Console.WriteLine("test update User" + await updateUser.Content.ReadAsStringAsync());
var deleteUser = await client.DeleteAsync("User/2");
Console.WriteLine("rep : " + deleteUser.StatusCode);
Console.WriteLine("test delete User" + await deleteUser.Content.ReadAsStringAsync());
Console.WriteLine("test Roles");
var GetRoles = await client.GetAsync("Role");
Console.WriteLine("rep : " + GetRoles.StatusCode);
Console.WriteLine("test get Roles" + await GetRoles.Content.ReadAsStringAsync());
var getRole = await client.GetAsync("Role/1");
Console.WriteLine("rep : " + getRole.StatusCode);
Console.WriteLine("test get Role" + await getRole.Content.ReadAsStringAsync());
var addRole = await client.PostAsJsonAsync("Role", new RoleDTO { Id=4, Name="name" });
Console.WriteLine("rep : " + addRole.StatusCode);
Console.WriteLine("test add Role" + await addRole.Content.ReadAsStringAsync());
var updateRole = await client.PutAsJsonAsync("Role", new RoleDTO { Id = 4, Name = "name2" });
Console.WriteLine("rep : " + updateRole.StatusCode);
Console.WriteLine("test update Role" + await updateRole.Content.ReadAsStringAsync());
var deleteRole = await client.DeleteAsync("Role/4");
Console.WriteLine("rep : " + deleteRole.StatusCode);
Console.WriteLine("test delete Role" + await deleteRole.Content.ReadAsStringAsync());

@ -7,4 +7,8 @@
<Nullable>enable</Nullable>
</PropertyGroup>
<ItemGroup>
<ProjectReference Include="..\DTO\DTO.csproj" />
</ItemGroup>
</Project>

@ -9,18 +9,20 @@ Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "DbContextLib", "DbContext\D
EndProject
Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "StubbedContextLib", "StubbedContext\StubbedContextLib.csproj", "{169337C2-F9BD-4ED6-BFA9-A33849792A1E}"
EndProject
Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "TestConsole", "TestConsole\TestConsole.csproj", "{5D719F4D-DA04-4715-96C3-1FD685162F61}"
Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "TestConsole_EF", "TestConsole\TestConsole_EF.csproj", "{5D719F4D-DA04-4715-96C3-1FD685162F61}"
EndProject
Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "API", "API\API.csproj", "{C5A83081-2B72-45F4-BBF5-70B55BC37CA2}"
EndProject
Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "TU", "TU\TU.csproj", "{582BF4E1-B466-490B-9B7F-4997E273AF26}"
Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "TU_API", "TU\TU_API.csproj", "{582BF4E1-B466-490B-9B7F-4997E273AF26}"
EndProject
Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "DTO", "DTO\DTO.csproj", "{A668727B-5109-4D96-8B83-8F914E24BAB3}"
EndProject
Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "Modele", "Modele\Modele.csproj", "{3EB1B73A-FAAF-4B4A-BB54-228A42528AEB}"
EndProject
Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "DTOToEntity", "DTOToEntity\DTOToEntity.csproj", "{9E919C0A-547E-4307-9071-672E9554AB1E}"
EndProject
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "TU_EF", "TU_EF\TU_EF.csproj", "{9F0D1307-F865-4AEA-A915-8124E2A88419}"
EndProject
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "TestConsole_API", "TestConsole_API\TestConsole_API.csproj", "{C44B74ED-3901-4E5D-97B1-1A60A0BA87FF}"
EndProject
Global
GlobalSection(SolutionConfigurationPlatforms) = preSolution
Debug|Any CPU = Debug|Any CPU
@ -55,14 +57,18 @@ Global
{A668727B-5109-4D96-8B83-8F914E24BAB3}.Debug|Any CPU.Build.0 = Debug|Any CPU
{A668727B-5109-4D96-8B83-8F914E24BAB3}.Release|Any CPU.ActiveCfg = Release|Any CPU
{A668727B-5109-4D96-8B83-8F914E24BAB3}.Release|Any CPU.Build.0 = Release|Any CPU
{3EB1B73A-FAAF-4B4A-BB54-228A42528AEB}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{3EB1B73A-FAAF-4B4A-BB54-228A42528AEB}.Debug|Any CPU.Build.0 = Debug|Any CPU
{3EB1B73A-FAAF-4B4A-BB54-228A42528AEB}.Release|Any CPU.ActiveCfg = Release|Any CPU
{3EB1B73A-FAAF-4B4A-BB54-228A42528AEB}.Release|Any CPU.Build.0 = Release|Any CPU
{9E919C0A-547E-4307-9071-672E9554AB1E}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{9E919C0A-547E-4307-9071-672E9554AB1E}.Debug|Any CPU.Build.0 = Debug|Any CPU
{9E919C0A-547E-4307-9071-672E9554AB1E}.Release|Any CPU.ActiveCfg = Release|Any CPU
{9E919C0A-547E-4307-9071-672E9554AB1E}.Release|Any CPU.Build.0 = Release|Any CPU
{9F0D1307-F865-4AEA-A915-8124E2A88419}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{9F0D1307-F865-4AEA-A915-8124E2A88419}.Debug|Any CPU.Build.0 = Debug|Any CPU
{9F0D1307-F865-4AEA-A915-8124E2A88419}.Release|Any CPU.ActiveCfg = Release|Any CPU
{9F0D1307-F865-4AEA-A915-8124E2A88419}.Release|Any CPU.Build.0 = Release|Any CPU
{C44B74ED-3901-4E5D-97B1-1A60A0BA87FF}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{C44B74ED-3901-4E5D-97B1-1A60A0BA87FF}.Debug|Any CPU.Build.0 = Debug|Any CPU
{C44B74ED-3901-4E5D-97B1-1A60A0BA87FF}.Release|Any CPU.ActiveCfg = Release|Any CPU
{C44B74ED-3901-4E5D-97B1-1A60A0BA87FF}.Release|Any CPU.Build.0 = Release|Any CPU
EndGlobalSection
GlobalSection(SolutionProperties) = preSolution
HideSolutionNode = FALSE

Loading…
Cancel
Save