Réglage du bug lors du POST d'un paragraph qui maintenant fonctionne mais le GET sur leçon ne renvoie pas les paragraphes associés. Ajout de la création d'un utilisateur admin pour Identity.
continuous-integration/drone/push Build is passing Details

pull/45/head
Johnny RATTON 1 year ago
parent f9b325c706
commit b4a5640ede

@ -1,4 +1,5 @@
using Microsoft.AspNetCore.Authorization;
using System.Net;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using Dto;
using Model.OrderCriteria;
@ -13,18 +14,18 @@ namespace API.Controllers
[ApiController]
public class LessonsController : Controller
{
private readonly ILessonService<LessonDto> _lessonDataService;
private readonly ILessonService<LessonDTO> _lessonDataService;
private readonly ILogger<LessonsController> _logger;
public LessonsController(ILessonService<LessonDto> lessonDataService, ILogger<LessonsController> logger)
public LessonsController(ILessonService<LessonDTO> lessonDataService, ILogger<LessonsController> logger)
{
_lessonDataService = lessonDataService;
_logger = logger;
}
[HttpGet("lessons/{page:int}/{number:int}/{orderCriteria}")]
[ProducesResponseType(typeof(LessonDto), 200)]
[ProducesResponseType(typeof(LessonDTO), 200)]
[ProducesResponseType(typeof(string), 204)]
public IActionResult GetLessons(int page, int number, LessonOrderCriteria orderCriteria)
{
@ -40,7 +41,7 @@ namespace API.Controllers
}
[HttpGet("lesson/{id:int}")]
[ProducesResponseType(typeof(LessonDto), 200)]
[ProducesResponseType(typeof(LessonDTO), 200)]
[ProducesResponseType(typeof(string), 404)]
public IActionResult GetLessonById(int id)
{
@ -57,7 +58,7 @@ namespace API.Controllers
}
[HttpGet("lesson/{title:alpha}")]
[ProducesResponseType(typeof(LessonDto), 200)]
[ProducesResponseType(typeof(LessonDTO), 200)]
[ProducesResponseType(typeof(string), 404)]
public IActionResult GetLessonByTitle(string title)
{
@ -74,7 +75,7 @@ namespace API.Controllers
}
[HttpDelete("lesson/{id:int}")]
[ProducesResponseType(typeof(LessonDto), 200)]
[ProducesResponseType(typeof(LessonDTO), 200)]
[ProducesResponseType(typeof(string), 404)]
public IActionResult DeleteLesson(int id)
{
@ -92,29 +93,44 @@ namespace API.Controllers
}
[HttpPost]
[ProducesResponseType(typeof(LessonDto), 201)]
[ProducesResponseType(typeof(LessonDTO), 201)]
[ProducesResponseType(typeof(string), 400)]
public IActionResult CreateLesson([FromBody] LessonDto dto)
[ProducesResponseType(typeof(string), 500)]
public IActionResult CreateLesson([FromBody] LessonDTO dto)
{
if (dto.Title == null || dto.LastPublisher == null)
{
return BadRequest();
}
_logger.LogInformation(
"[INFORMATION] Une leçon a été créé : title - {title}, lastPublisher - {publisher}, lastEdit - {lastEdit}",
dto.Title, dto.LastPublisher, dto.LastEdit);
return Created(nameof(GetLessons),
_lessonDataService.CreateLesson(dto.Title, dto.LastPublisher, dto.LastEdit));
try
{
var createdLesson = _lessonDataService.CreateLesson(dto.Id, dto.Title, dto.LastPublisher, dto.LastEdit);
if (createdLesson != null)
{
_logger.LogInformation(
"[INFORMATION] Une leçon a été créé : title - {title}, lastPublisher - {publisher}, lastEdit - {lastEdit}",
dto.Title, dto.LastPublisher, dto.LastEdit);
return Created(nameof(GetLessons), createdLesson);
}
else
{
return StatusCode(500);
}
}
catch (ArgumentException e)
{
_logger.LogError("[ERREUR] " + e.Message);
return Created();
}
}
[HttpPut("lesson/{id:int}")]
[ProducesResponseType(typeof(LessonDto), 200)]
[ProducesResponseType(typeof(LessonDTO), 200)]
[ProducesResponseType(typeof(string), 400)]
[ProducesResponseType(typeof(string), 404)]
public IActionResult UpdateLesson(int id, [FromBody] LessonDto lessonDTO)
public IActionResult UpdateLesson(int id, [FromBody] LessonDTO lessonDto)
{
if (id != lessonDTO.Id)
if (id != lessonDto.Id)
{
_logger.LogError("[ERREUR] Problème ID - La mise à jour de la leçon avec l'id {id} a échouée.", id);
return BadRequest();
@ -127,10 +143,10 @@ namespace API.Controllers
return BadRequest();
}
if (lessonDTO != null)
if (lessonDto != null)
{
_logger.LogInformation("[INFORMATION] La mise à jour de la leçon avec l'id {id} a été effectuée", id);
return Ok(_lessonDataService.UpdateLesson(id, lessonDTO));
return Ok(_lessonDataService.UpdateLesson(id, lessonDto));
}
_logger.LogError("[ERREUR] Aucune leçon trouvée avec l'id {id}.", id);

@ -107,7 +107,7 @@ namespace API.Controllers
"[INFORMATION] Un paragraphe a été créé : title - {title}, content - {content}, info - {info}, query - {query}, comment - {comment}",
dto.Title, dto.Content, dto.Info, dto.Query, dto.Comment);
return Created(nameof(GetParagraphs),
_paragraphDataService.CreateParagraph(dto.Title, dto.Content, dto.Info, dto.Query, dto.Comment,
_paragraphDataService.CreateParagraph(dto.ContentTitle, dto.ContentContent,dto.Title, dto.Content, dto.Info, dto.Query, dto.Comment,
dto.LessonId));
}

@ -32,11 +32,12 @@ builder.Services.AddScoped<ISuccessService<SuccessEntity>, SuccessDataService>()
builder.Services.AddScoped<ISuccessService<SuccessDto>, SuccessDataServiceApi>();
builder.Services.AddScoped<ILessonService<LessonEntity>, LessonDataService>();
builder.Services.AddScoped<ILessonService<LessonDto>, LessonDataServiceApi>();
builder.Services.AddScoped<ILessonService<LessonDTO>, LessonDataServiceApi>();
builder.Services.AddDbContext<DbContext, UserDbContext>();
builder.Services.AddDbContext<WebAPIDbContext>(options => options.UseInMemoryDatabase("appDb"));
builder.Services.AddIdentityApiEndpoints<IdentityUser>().AddEntityFrameworkStores<WebAPIDbContext>();
builder.Services.AddAuthorization();
builder.Services.AddApiVersioning(o =>
{
@ -81,6 +82,36 @@ builder.Services.AddSwaggerGen(option =>
var app = builder.Build();
// Création de l'utilisateur admin pour la base de données Identity
using (var scope = app.Services.CreateScope())
{
var services = scope.ServiceProvider;
var userManager = services.GetRequiredService<UserManager<IdentityUser>>();
try
{
var user = new IdentityUser { UserName = "admin@example.com", Email = "admin@example.com" };
var result = await userManager.CreateAsync(user, "Mdp_1234");
if (result.Succeeded)
{
Console.WriteLine("Utilisateur admin créé avec succès.");
}
else
{
foreach (var error in result.Errors)
{
Console.WriteLine($"Erreur lors de la création de l'utilisateur : {error.Description}");
}
}
}
catch (Exception ex)
{
var logger = services.GetRequiredService<ILogger<Program>>();
logger.LogError(ex, "Une erreur s'est produite lors de la création de l'utilisateur.");
}
}
// Configure the HTTP request pipeline.
if (app.Environment.IsDevelopment())
{

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

@ -25,7 +25,7 @@ public class ParagraphDataServiceApi(IParagraphService<ParagraphEntity> paragrap
public ParagraphDto UpdateParagraph(int id, ParagraphDto paragraph) =>
paragraphService.UpdateParagraph(id, paragraph.FromDTOToEntity()).FromEntityToDTO();
public ParagraphDto CreateParagraph(string title, string content, string info, string query, string comment,
public ParagraphDto CreateParagraph(string contentTitle, string contentContent,string title, string content, string info, string query, string comment,
int lessonId) =>
paragraphService.CreateParagraph(title, content, info, query, comment, lessonId).FromEntityToDTO();
paragraphService.CreateParagraph(contentTitle, contentContent, title, content, info, query, comment, lessonId).FromEntityToDTO();
}

@ -1,5 +1,6 @@
using DbContextLib;
using Entities;
using Microsoft.AspNetCore.Mvc.ModelBinding;
using Microsoft.EntityFrameworkCore;
using Model.OrderCriteria;
using Shared;
@ -64,45 +65,64 @@ public class LessonDataService : ILessonService<LessonEntity>
public bool DeleteLesson(int id)
{
var lessonEntity = DbContext.Lessons.FirstOrDefault(l => l.Id == id);
if (lessonEntity == null)
using (UserDbContext context = new UserDbContext(new DbContextOptions<UserDbContext>()))
{
return false;
}
var lessonEntity = context.Lessons.FirstOrDefault(l => l.Id == id);
if (lessonEntity == null)
{
return false;
}
DbContext.Lessons.Remove(lessonEntity);
DbContext.SaveChangesAsync();
return true;
context.Lessons.Remove(lessonEntity);
context.SaveChangesAsync();
return true;
}
}
public LessonEntity UpdateLesson(int id, LessonEntity lesson)
{
var updatingLesson = DbContext.Lessons.FirstOrDefault(l => l.Id == id);
if (updatingLesson == null)
using (UserDbContext context = new UserDbContext(new DbContextOptions<UserDbContext>()))
{
throw new ArgumentException("Impossible de trouver la leçon", nameof(id));
}
var updatingLesson = context.Lessons.FirstOrDefault(l => l.Id == id);
if (updatingLesson == null)
{
throw new ArgumentException("Impossible de trouver la leçon", nameof(id));
}
foreach (var pptt in typeof(LessonEntity).GetProperties()
.Where(p => p.CanWrite && p.Name != nameof(LessonEntity.Id)))
{
pptt.SetValue(updatingLesson, pptt.GetValue(lesson));
}
foreach (var pptt in typeof(LessonEntity).GetProperties()
.Where(p => p.CanWrite && p.Name != nameof(LessonEntity.Id)))
{
pptt.SetValue(updatingLesson, pptt.GetValue(lesson));
}
DbContext.SaveChangesAsync();
return updatingLesson;
context.SaveChangesAsync();
return updatingLesson;
}
}
public LessonEntity CreateLesson(string title, string lastPublisher, DateOnly? lastEdit)
public LessonEntity CreateLesson(int id, string title, string lastPublisher, DateOnly? lastEdit)
{
var newLessonEntity = new LessonEntity()
using (UserDbContext context = new UserDbContext(new DbContextOptions<UserDbContext>()))
{
Title = title,
LastPublisher = lastPublisher,
LastEdit = lastEdit,
};
DbContext.Lessons.Add(newLessonEntity);
DbContext.SaveChangesAsync();
return newLessonEntity;
var newLessonEntity = new LessonEntity()
{
Title = title,
LastPublisher = lastPublisher,
LastEdit = lastEdit,
};
var lesson = context.Lessons.FirstOrDefault(l => l.Id == id);
if (lesson == null && id > 0)
{
newLessonEntity.Id = id;
context.Lessons.Add(newLessonEntity);
context.SaveChangesAsync();
throw new ArgumentException(
$"Erreur, l'ID {id} est déjà utilisé pour une autre leçon, un id par a été attribué.");
}
context.Lessons.Add(newLessonEntity);
context.SaveChangesAsync();
return newLessonEntity;
}
}
}

@ -99,11 +99,13 @@ public class ParagraphDataService : IParagraphService<ParagraphEntity>
return updatingParagraph;
}
public ParagraphEntity CreateParagraph(string title, string content, string info, string query, string comment,
public ParagraphEntity CreateParagraph(string contentTitle, string contentContent, string title, string content, string info, string query, string comment,
int lessonId)
{
var newParagraphEntity = new ParagraphEntity()
{
ContentContent = contentContent,
ContentTitle = contentTitle,
Title = title,
Content = content,
Info = info,

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

@ -6,4 +6,10 @@
<Nullable>enable</Nullable>
</PropertyGroup>
<ItemGroup>
<Reference Include="Newtonsoft.Json">
<HintPath>..\..\..\..\..\.nuget\packages\newtonsoft.json\13.0.1\lib\netstandard2.0\Newtonsoft.Json.dll</HintPath>
</Reference>
</ItemGroup>
</Project>

@ -1,26 +1,45 @@
namespace Dto;
using System.Net;
using System.Runtime.Serialization;
using System.Text.Json.Serialization;
public class LessonDto
namespace Dto;
[DataContract]
public class LessonDTO
{
public int Id { get; }
[DataMember]
public int Id { get; set; }
[DataMember]
public string? Title { get; set; }
[DataMember]
public string? LastPublisher { get; set; }
[DataMember]
public DateOnly? LastEdit { get; set; }
[JsonIgnore(Condition = JsonIgnoreCondition.WhenWritingNull)]
public ICollection<ContentLessonDto> Content { get; set; } = new List<ContentLessonDto>();
public LessonDto()
public LessonDTO()
{
}
public LessonDTO(int id, string title, string lastPublisher, DateOnly? lastEdit)
{
Id = id;
Title = title;
LastPublisher = lastPublisher;
LastEdit = lastEdit;
}
public LessonDto(int id, string title, string lastPublisher, DateOnly? lastEdit)
public LessonDTO(int id, string title, string lastPublisher, DateOnly? lastEdit, ICollection<ContentLessonDto> content)
{
Id = id;
Title = title;
LastPublisher = lastPublisher;
LastEdit = lastEdit;
Content = content;
}
public LessonDto(string title, string lastPublisher, DateOnly? lastEdit)
public LessonDTO(string title, string lastPublisher, DateOnly? lastEdit)
{
Title = title;
LastPublisher = lastPublisher;

@ -1,11 +1,19 @@
namespace Dto;
using System.Runtime.Serialization;
namespace Dto;
[DataContract]
public class ParagraphDto : ContentLessonDto
{
[DataMember(Name = "title")]
public string Title { get; set; }
[DataMember(Name = "content")]
public string Content { get; set; }
[DataMember(Name = "info")]
public string Info { get; set; }
[DataMember(Name = "query")]
public string Query { get; set; }
[DataMember(Name = "comment")]
public string Comment { get; set; }
public ParagraphDto(string title, string content, string info, string query, string comment, int lessonId) :

@ -9,5 +9,5 @@ public interface ILessonService<TLesson>
public TLesson GetLessonByTitle(string title);
public bool DeleteLesson(int id);
public TLesson UpdateLesson(int id, TLesson lesson);
public TLesson CreateLesson(string title, string lastPublisher, DateOnly? lastEdit);
public TLesson CreateLesson(int id, string title, string lastPublisher, DateOnly? lastEdit);
}

@ -10,7 +10,7 @@ namespace Shared
public bool DeleteParagraph(int id);
public TParagraph UpdateParagraph(int id, TParagraph paragraph);
public TParagraph CreateParagraph(string title, string content, string info, string query, string comment,
public TParagraph CreateParagraph(string contentTitle, string contentContent, string title, string content, string info, string query, string comment,
int lessonId);
}
}

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

@ -6,14 +6,19 @@ namespace Shared.Mapper;
public static class LessonMapper
{
public static LessonDto FromModelToDTO(this Lesson model)
public static LessonDTO FromModelToDTO(this Lesson model)
{
return new LessonDto(model.Id, model.Title, model.LastPublisher, model.LastEdit);
return new LessonDTO(model.Id, model.Title, model.LastPublisher, model.LastEdit);
}
public static LessonDto FromEntityToDTO(this LessonEntity model)
public static LessonDTO FromEntityToDTOGet(this LessonEntity model)
{
return new LessonDto(model.Id, model.Title, model.LastPublisher, model.LastEdit);
return new LessonDTO(model.Id, model.Title, model.LastPublisher, model.LastEdit, model.Content.Select(c => c.FromEntityToDTO()).ToList());
}
public static LessonDTO FromEntityToDTOPost(this LessonEntity model)
{
return new LessonDTO(model.Id, model.Title, model.LastPublisher, model.LastEdit);
}
public static LessonEntity FromModelToEntity(this Lesson model)
@ -21,12 +26,12 @@ public static class LessonMapper
return new LessonEntity(model.Id, model.Title, model.LastPublisher, model.LastEdit);
}
public static LessonEntity FromDTOToEntity(this LessonDto dto)
public static LessonEntity FromDTOToEntity(this LessonDTO dto)
{
return new LessonEntity(dto.Id, dto.Title, dto.LastPublisher, dto.LastEdit);
}
public static Lesson FromDTOToModel(this LessonDto dto)
public static Lesson FromDTOToModel(this LessonDTO dto)
{
return new Lesson(dto.Id, dto.Title, dto.LastPublisher, dto.LastEdit);
}

@ -75,7 +75,7 @@ using (var context = new UserDbContext(options))
{
Console.WriteLine();
var lessons = lessonController.GetLessons(1, 10, LessonOrderCriteria.None) as OkObjectResult;
foreach (var item in lessons.Value as IEnumerable<LessonDto>)
foreach (var item in lessons.Value as IEnumerable<LessonDTO>)
{
Console.WriteLine(item);
}
@ -144,7 +144,7 @@ using (var context = new UserDbContext(options))
return;
}
Console.WriteLine(lesson.Value as LessonDto);
Console.WriteLine(lesson.Value as LessonDTO);
}
void SearchSuccessByUserId()
@ -228,7 +228,7 @@ using (var context = new UserDbContext(options))
return;
}
Console.WriteLine(lesson.Value as LessonDto);
Console.WriteLine(lesson.Value as LessonDTO);
}
void AddUser()
@ -305,7 +305,7 @@ using (var context = new UserDbContext(options))
Console.WriteLine("Veuillez saisir votre nom :");
var lastPublisher = Console.ReadLine();
var res = lessonController.CreateLesson(
new LessonDto(title, lastPublisher, DateOnly.FromDateTime(DateTime.Now)));
new LessonDTO(title, lastPublisher, DateOnly.FromDateTime(DateTime.Now)));
if (res.GetType() == typeof(CreatedResult))
{
Console.WriteLine("\nLeçon créée avec succès");
@ -471,7 +471,7 @@ using (var context = new UserDbContext(options))
var res = (lessonController.GetLessonById(id));
if (res.GetType() == typeof(OkObjectResult))
{
var lesson = (res as OkObjectResult).Value as LessonDto;
var lesson = (res as OkObjectResult).Value as LessonDTO;
if (lesson == null)
{
Console.WriteLine("Erreur, un problème est survenu");
@ -485,7 +485,7 @@ using (var context = new UserDbContext(options))
Console.WriteLine("Veuillez saisir votre nom :");
var lastPublisher = Console.ReadLine();
var retour = lessonController.UpdateLesson(id,
new LessonDto(id, title, lastPublisher, DateOnly.FromDateTime(DateTime.Now)));
new LessonDTO(id, title, lastPublisher, DateOnly.FromDateTime(DateTime.Now)));
if (retour.GetType() == typeof(OkObjectResult))
{
Console.WriteLine("Mise à jour effectué avec succès !");

Loading…
Cancel
Save