#106 Ajout du mode Repositories Local

This commit is contained in:
Loic Masi
2026-03-26 18:48:41 +01:00
parent c95f77b6e6
commit d65d21ea64
14 changed files with 302 additions and 495 deletions

View File

@@ -49,20 +49,5 @@ namespace Webzine.Entity.Fixtures
return artisteFaker.Generate();
}
/// <summary>
/// Permet de retourner une liste d'artiste pour seeder la base
/// de données.
/// </summary>
/// <param name="nombre"></param>
/// <returns>Liste d'artiste.</returns>
public static List<Artiste> CreerListeArtiste(int nombre)
{
Faker<Artiste> faker = new Faker<Artiste>("fr")
.RuleFor(a => a.Nom, f => f.Person.FullName)
.RuleFor(a => a.Biographie, f => f.Lorem.Paragraph(2));
return faker.Generate(nombre);
}
}
}

View File

@@ -8,26 +8,6 @@ namespace Webzine.Entity.Fixtures
{
public class CommentaireFactory
{
/// <summary>
/// Seeder pour la base de données.
/// </summary>
/// <param name="titre">Titre.</param>
/// <param name="min">Min.</param>
/// <param name="max">Max.</param>
/// <returns>Liste de commentaire.</returns>
public static List<Commentaire> CreerListeCommentaire(Titre titre, int min = 0, int max = 5)
{
Random random = new Random();
int count = random.Next(min, max + 1);
Faker<Commentaire> faker = new Faker<Commentaire>("fr")
.RuleFor(c => c.Auteur, f => f.Internet.UserName())
.RuleFor(c => c.Contenu, f => f.Lorem.Sentences(2))
.RuleFor(c => c.DateCreation, f => f.Date.Recent(60))
.RuleFor(c => c.Titre, _ => titre)
.RuleFor(c => c.IdTitre, _ => titre.IdTitre);
return faker.Generate(count);
}
}
}

View File

@@ -3,12 +3,151 @@
// </copyright>
namespace Webzine.Entity.Fixtures
{
{
using Bogus;
public class SeedDataLocal
{
public SeedDataLocal()
{
}
/// <summary>
/// Generer une liste d'artiste.
/// </summary>
/// <param name="nombre">Nombre d'artiste.</param>
/// <returns>Liste d'artiste.</returns>
public static List<Artiste> GenererListeArtiste(int nombre)
{
Faker<Artiste> artistes = new Faker<Artiste>("fr")
.RuleFor(a => a.Nom, f => f.Person.FullName)
.RuleFor(a => a.Biographie, f => f.Lorem.Paragraph(2));
return artistes.Generate(nombre);
}
/// <summary>
/// Generer une liste de titre.
/// </summary>
/// <param name="count">Nombre de titre à créer.</param>
/// <param name="artistes">Liste d'artiste.</param>
/// <param name="styles">Liste de style.</param>
/// <returns>Liste de titre.</returns>
public static List<Titre> GenererListeTitre(
int count,
List<Artiste> artistes,
List<Style> styles,
List<string> albums)
{
Random random = new Random();
Faker<Titre> faker = new Faker<Titre>("fr")
.RuleFor(t => t.Libelle, f => f.Lorem.Sentence(3).Replace(".", string.Empty))
.RuleFor(t => t.Chronique, f => f.Lorem.Paragraphs(3))
.RuleFor(t => t.DateCreation, f => f.Date.Recent(120))
.RuleFor(t => t.DateSortie, (f, t) => f.Date.Past(10, t.DateCreation))
.RuleFor(t => t.Duree, f => f.Random.Int(120, 420))
.RuleFor(t => t.UrlJaquette, f => $"https://picsum.photos/seed/{Guid.NewGuid():N}/640/640")
.RuleFor(t => t.UrlEcoute, f => $"https://example.com/listen/{Guid.NewGuid():N}")
.RuleFor(t => t.NbLectures, f => f.Random.Int(0, 5000))
.RuleFor(t => t.NbLikes, f => f.Random.Int(0, 1000))
.RuleFor(t => t.Album, f => f.PickRandom(albums))
.RuleFor(t => t.Artiste, f => f.PickRandom(artistes));
List<Titre> titres = faker.Generate(count);
foreach (Titre titre in titres)
{
int nbStyles = random.Next(1, 4);
titre.Styles = styles
.OrderBy(_ => Guid.NewGuid())
.Take(nbStyles)
.ToList();
titre.IdArtiste = titre.Artiste.IdArtiste;
}
return titres;
}
/// <summary>
/// Générer une liste de style pour seeder la base
/// de données.
/// </summary>
/// <returns>Liste de style.</returns>
public static List<Style> GenererListeStyle(int minCount = 15, int maxCount = 20)
{
List<string> libelles = new List<string>
{
"Pop",
"Rock",
"Jazz",
"Blues",
"Hip-Hop",
"Rap",
"Electro",
"Techno",
"House",
"Metal",
"Funk",
"Soul",
"R&B",
"Classique",
"Reggae",
"Punk",
"Folk",
"Disco",
"Ambient",
"Indie",
};
Random random = new Random();
int count = random.Next(minCount, maxCount + 1);
return libelles
.Take(count)
.Select(libelle => new Style
{
Libelle = libelle,
})
.ToList();
}
/// <summary>
/// Seeder pour la base de données.
/// </summary>
/// <param name="titre">Titre.</param>
/// <param name="min">Min.</param>
/// <param name="max">Max.</param>
/// <returns>Liste de commentaire.</returns>
public static List<Commentaire> GenererListeCommentaire(Titre titre, int min = 0, int max = 5)
{
Random random = new Random();
int count = random.Next(min, max + 1);
Faker<Commentaire> faker = new Faker<Commentaire>("fr")
.RuleFor(c => c.Auteur, f => f.Internet.UserName())
.RuleFor(c => c.Contenu, f => f.Lorem.Sentences(2))
.RuleFor(c => c.DateCreation, f => f.Date.Recent(60))
.RuleFor(c => c.Titre, _ => titre)
.RuleFor(c => c.IdTitre, _ => titre.IdTitre);
return faker.Generate(count);
}
public static List<string> GenererListeAlbums(int nombre)
{
Faker faker = new Faker("fr");
HashSet<string> albums = new HashSet<string>();
while (albums.Count < nombre)
{
albums.Add(faker.Company.CatchPhrase());
}
return albums.ToList();
}
}
}

View File

@@ -7,47 +7,6 @@ namespace Webzine.Entity.Fixtures
using Webzine.Entity;
public class StyleFactory
{
/// <summary>
/// Générer une liste de style pour seeder la base
/// de données.
/// </summary>
/// <returns>Liste de style.</returns>
public static List<Style> CreerListeStyle(int minCount = 15, int maxCount = 20)
{
List<string> libelles = new List<string>
{
"Pop",
"Rock",
"Jazz",
"Blues",
"Hip-Hop",
"Rap",
"Electro",
"Techno",
"House",
"Metal",
"Funk",
"Soul",
"R&B",
"Classique",
"Reggae",
"Punk",
"Folk",
"Disco",
"Ambient",
"Indie",
};
Random random = new Random();
int count = random.Next(minCount, maxCount + 1);
return libelles
.Take(count)
.Select(libelle => new Style
{
Libelle = libelle,
})
.ToList();
}
}
}

View File

@@ -74,50 +74,4 @@ namespace Webzine.Repository.Fake
return titres;
}
}
public class TitreFactory
{
/// <summary>
/// Initializes a new instance of the <see cref="TitreFactory"/> class.
/// </summary>
public TitreFactory()
{
}
public static List<Titre> CreerListeTitre(
int count,
List<Artiste> artistes,
List<Style> styles)
{
Random random = new Random();
Faker<Titre> faker = new Faker<Titre>("fr")
.RuleFor(t => t.Libelle, f => f.Lorem.Sentence(3).Replace(".", string.Empty))
.RuleFor(t => t.Chronique, f => f.Lorem.Paragraphs(3))
.RuleFor(t => t.DateCreation, f => f.Date.Recent(120))
.RuleFor(t => t.DateSortie, (f, t) => f.Date.Past(10, t.DateCreation))
.RuleFor(t => t.Duree, f => f.Random.Int(120, 420))
.RuleFor(t => t.UrlJaquette, f => $"https://picsum.photos/seed/{Guid.NewGuid():N}/640/640")
.RuleFor(t => t.UrlEcoute, f => $"https://example.com/listen/{Guid.NewGuid():N}")
.RuleFor(t => t.NbLectures, f => f.Random.Int(0, 5000))
.RuleFor(t => t.NbLikes, f => f.Random.Int(0, 1000))
.RuleFor(t => t.Album, f => f.Company.CatchPhrase())
.RuleFor(t => t.Artiste, f => f.PickRandom(artistes));
List<Titre> titres = faker.Generate(count);
foreach (Titre titre in titres)
{
int nbStyles = random.Next(1, 4);
titre.Styles = styles
.OrderBy(_ => Guid.NewGuid())
.Take(nbStyles)
.ToList();
titre.IdArtiste = titre.Artiste.IdArtiste;
}
return titres;
}
}
}

View File

@@ -7,7 +7,6 @@ namespace Webzine.Repository
using Webzine.EntitiesContext;
using Webzine.Entity;
using Webzine.Entity.Fixtures;
using Webzine.Repository.Fake;
public class DbEntityRepository
{
@@ -18,6 +17,15 @@ namespace Webzine.Repository
this.context = context;
}
/// <summary>
/// Seed la base de donnée à l'aide de SeedDataLocal.
/// </summary>
/// <param name="nbArtistes">Nombre d'artiste.</param>
/// <param name="nbTitres">Nombre de titre.</param>
/// <param name="minStyles">Nombre min de style.</param>
/// <param name="maxStyles">Nombre mac de style.</param>
/// <param name="minCommentairesParTitre">Min commentaire par titre.</param>
/// <param name="maxCommentairesParTitre">Max commentaire par titre</param>
public void SeedBaseDeDonnees(
int nbArtistes = 100,
int nbTitres = 500,
@@ -34,14 +42,16 @@ namespace Webzine.Repository
return;
}
List<Artiste> artistes = ArtisteFactory.CreerListeArtiste(nbArtistes);
List<Style> styles = StyleFactory.CreerListeStyle(minStyles, maxStyles);
List<Artiste> artistes = SeedDataLocal.GenererListeArtiste(nbArtistes);
List<Style> styles = SeedDataLocal.GenererListeStyle(minStyles, maxStyles);
this.context.Artistes.AddRange(artistes);
this.context.Styles.AddRange(styles);
this.context.SaveChanges();
List<Titre> titres = TitreFactory.CreerListeTitre(nbTitres, artistes, styles);
List<string> albums = SeedDataLocal.GenererListeAlbums(3);
List<Titre> titres = SeedDataLocal.GenererListeTitre(nbTitres, artistes, styles, albums);
this.context.Titres.AddRange(titres);
this.context.SaveChanges();
@@ -50,7 +60,7 @@ namespace Webzine.Repository
foreach (Titre titre in titres)
{
commentaires.AddRange(
CommentaireFactory.CreerListeCommentaire(
SeedDataLocal.GenererListeCommentaire(
titre,
minCommentairesParTitre,
maxCommentairesParTitre));

View File

@@ -0,0 +1,15 @@
using System;
using System.Collections.Generic;
using System.Text;
using Webzine.Entity;
namespace Webzine.Repository
{
public class InMemoryDataStore
{
public List<Artiste> Artistes { get; set; } = new();
public List<Titre> Titres { get; set; } = new();
public List<Style> Styles { get; set; } = new();
public List<Commentaire> Commentaires { get; set; } = new();
}
}

View File

@@ -15,7 +15,9 @@ namespace Webzine.Repository
public class LocalArtisteRepository : IArtisteRepository
{
private readonly ILogger<LocalArtisteRepository> logger;
private readonly List<Artiste> artistes;
//private readonly List<Artiste> artistes;
private readonly InMemoryDataStore dataStore;
/// <summary>
/// Initializes a new instance of the <see cref="LocalArtisteRepository"/> class.
@@ -23,111 +25,54 @@ namespace Webzine.Repository
/// </summary>
/// <param name="artistes">La liste des artistes à initialiser. Ne peut pas être null.</param>
/// <param name="logger">Le logger à utiliser pour enregistrer les messages de journalisation. Ne peut pas être null.</param>
public LocalArtisteRepository(List<Artiste> artistes, ILogger<LocalArtisteRepository> logger)
public LocalArtisteRepository(InMemoryDataStore dataStore, ILogger<LocalArtisteRepository> logger)
{
this.logger = logger;
this.artistes = artistes;
//this.artistes = artistes;
this.dataStore = dataStore;
}
/// <inheritdoc/>
public void Add(Artiste artiste)
{
try
{
if (this.artistes.Any(a => a.IdArtiste == artiste.IdArtiste))
{
this.logger.LogWarning("Un artiste avec l'ID {Id} existe déjà. L'ajout est ignoré.", artiste.IdArtiste);
return;
}
this.artistes.Add(artiste);
this.logger.LogInformation("Artiste ajouté : {Nom}", artiste.Nom);
}
catch (Exception ex)
{
this.logger.LogError(ex, "Erreur lors de l'ajout de l'artiste : {Nom}", artiste?.Nom);
throw;
}
throw new NotSupportedException("Mode Local");
}
/// <inheritdoc/>
public void Delete(Artiste artiste)
{
try
{
this.artistes.Remove(artiste);
this.logger.LogInformation("Artiste supprimé : {Nom}", artiste.Nom);
}
catch (Exception ex)
{
this.logger.LogError(ex, "Erreur lors de la suppression de l'artiste : {Nom}", artiste.Nom);
throw;
}
throw new NotSupportedException("Mode Local");
}
/// <inheritdoc/>
public Artiste Find(int id)
{
try
var artiste = this.dataStore.Artistes.First(a => a.IdArtiste == id);
if (artiste == null)
{
Artiste artiste = this.artistes.First(a => a.IdArtiste == id);
return artiste;
}
catch (Exception ex)
{
this.logger.LogError(ex, "Erreur lors de la recherche de l'artiste avec ID: {Id}", id);
throw;
return new Artiste();
}
return artiste;
}
/// <inheritdoc/>
public Artiste FindByName(string nom)
{
try
{
Artiste artiste = this.artistes.First(a => a.Nom == nom);
return artiste;
}
catch (Exception ex)
{
this.logger.LogError(ex, "Erreur lors de la recherche de l'artiste avec le nom: {Nom}", nom);
throw;
}
return this.dataStore.Artistes.First(a => a.Nom == nom);
}
/// <inheritdoc/>
/// La liste retournée est une copie de la liste interne, donc elle ne peut être nulle.
public IEnumerable<Artiste> FindAll()
{
return this.artistes;
return this.dataStore.Artistes;
}
/// <inheritdoc/>
public void Update(Artiste artiste)
{
try
{
var artisteToUpdate = this.artistes.FirstOrDefault(a => a.IdArtiste == artiste.IdArtiste);
if (artisteToUpdate != null)
{
artisteToUpdate.Nom = artiste.Nom;
artisteToUpdate.Biographie = artiste.Biographie;
artisteToUpdate.Titres = artiste.Titres;
this.logger.LogInformation("Artiste {Id} mis à jour avec succès.", artiste.IdArtiste);
}
else
{
this.logger.LogWarning("Mise à jour impossible : l'artiste avec l'ID {Id} n'existe pas.", artiste.IdArtiste);
throw new KeyNotFoundException($"L'artiste {artiste.IdArtiste} est introuvable.");
}
}
catch (Exception ex)
{
this.logger.LogError(ex, "Une erreur est survenue lors de la mise à jour de l'artiste {Id}.", artiste.IdArtiste);
throw;
}
throw new NotSupportedException("Mode Local");
}
}
}

View File

@@ -0,0 +1,43 @@
// <copyright file="LocalCommentaireRepository.cs" company="PlaceholderCompany">
// Copyright (c) PlaceholderCompany. All rights reserved.
// </copyright>
using Webzine.Entity;
using Webzine.Repository.Contracts;
namespace Webzine.Repository
{
public class LocalCommentaireRepository : ICommentaireRepository
{
private readonly InMemoryDataStore dataStore;
public LocalCommentaireRepository(InMemoryDataStore dataStore)
{
this.dataStore = dataStore;
}
/// <inheritdoc/>
public void Add(Commentaire commentaire)
{
throw new NotSupportedException();
}
/// <inheritdoc/>
public void Delete(Commentaire commentaire)
{
throw new NotSupportedException();
}
/// <inheritdoc/>
public Commentaire Find(int id)
{
return this.dataStore.Commentaires.Find(c => c.IdCommentaire == id);
}
/// <inheritdoc/>
public IEnumerable<Commentaire> FindAll()
{
return this.dataStore.Commentaires.ToList();
}
}
}

View File

@@ -10,126 +10,48 @@ namespace Webzine.Repository;
public class LocalStyleRepository : IStyleRepository
{
private readonly ILogger<LocalStyleRepository> logger;
private readonly List<Style> styles;
//private readonly List<Style> styles;
private readonly InMemoryDataStore dataStore;
/// <summary>
/// Initializes a new instance of the <see cref="LocalStyleRepository"/> class.
/// </summary>
/// <param name="logger">Le service de journalisation injecté pour suivre les opérations du repository.</param>
/// <param name="styles">La liste de styles à utiliser comme source de données pour le repository.</param>
public LocalStyleRepository(ILogger<LocalStyleRepository> logger, List<Style> styles)
public LocalStyleRepository(ILogger<LocalStyleRepository> logger, InMemoryDataStore dataStore)
{
this.logger = logger;
this.styles = styles;
this.dataStore = dataStore;
this.logger.LogDebug(1, "NLog injecté dans LocalStyleRepository");
}
/// <inheritdoc/>
public void Add(Style style)
{
try
{
this.logger.LogDebug("Ajout du style: {Libelle}", style.Libelle);
this.styles.Add(style);
this.logger.LogDebug("Style ajouté avec succès, ID: {IdStyle}", style.IdStyle);
}
catch (Exception ex)
{
this.logger.LogError(ex, "Erreur lors de l'ajout du style: {Libelle}", style.Libelle);
throw;
}
throw new NotSupportedException("Mode local");
}
/// <inheritdoc/>
public void Delete(Style style)
{
try
{
this.logger.LogDebug("Suppression du style ID: {IdStyle}", style.IdStyle);
if (!this.styles.Contains(style))
{
this.logger.LogWarning("Le style avec l'identifiant {IdStyle} n'existe pas dans la liste.", style.IdStyle);
}
this.styles.Remove(style);
this.logger.LogDebug("Style supprimé avec succès, ID: {IdStyle}", style.IdStyle);
}
catch (Exception ex)
{
this.logger.LogError(ex, "Erreur lors de la suppression du style ID: {IdStyle}", style.IdStyle);
throw;
}
throw new NotSupportedException("Mode local");
}
/// <inheritdoc/>
public Style Find(int id)
{
try
{
this.logger.LogDebug("Recherche du style avec ID: {Id}", id);
if (id <= 0)
{
this.logger.LogWarning("Tentative de recherche d'un style avec un Id invalide: {Id}", id);
return new Style();
}
Style style = this.styles.First(s => s.IdStyle == id);
this.logger.LogDebug("Style trouvé: {Libelle}", style.Libelle);
return style;
}
catch (InvalidOperationException ex)
{
this.logger.LogWarning(ex, "Aucun style trouvé avec l'ID: {Id}", id);
throw;
}
catch (Exception ex)
{
this.logger.LogError(ex, "Erreur lors de la recherche du style avec ID: {Id}", id);
throw;
}
return this.dataStore.Styles.Find(s => s.IdStyle == id);
}
/// <inheritdoc/>
public IEnumerable<Style> FindAll()
{
try
{
this.logger.LogDebug("Récupération de tous les styles");
var result = this.styles;
this.logger.LogDebug("{Count} styles récupérés", result.Count);
return result;
}
catch (Exception ex)
{
this.logger.LogError(ex, "Erreur lors de la récupération de tous les styles");
throw;
}
return this.dataStore.Styles.ToList();
}
/// <inheritdoc/>
public void Update(Style style)
{
try
{
this.logger.LogDebug("Mise à jour du style ID: {IdStyle}", style.IdStyle);
int index = this.styles.FindIndex(s => s.IdStyle == style.IdStyle);
if (index == -1)
{
this.logger.LogWarning("Aucun style trouvé avec l'identifiant {IdStyle}.", style.IdStyle);
throw new InvalidOperationException($"Aucun style trouvé avec l'identifiant {style.IdStyle}.");
}
this.styles[index] = style;
this.logger.LogDebug("Style mis à jour avec succès, ID: {IdStyle}", style.IdStyle);
}
catch (Exception ex)
{
this.logger.LogError(ex, "Erreur lors de la mise à jour du style ID: {IdStyle}", style.IdStyle);
throw;
}
throw new NotSupportedException("Mode local");
}
}

View File

@@ -10,265 +10,90 @@ namespace Webzine.Repository;
public class LocalTitreRepository : ITitreRepository
{
private readonly ILogger<LocalTitreRepository> logger;
private readonly List<Titre> titres;
private readonly InMemoryDataStore dataStore;
/// <summary>
/// Initializes a new instance of the <see cref="LocalTitreRepository"/> class.
/// </summary>
/// <param name="logger">Le service de journalisation injecté pour suivre les opérations du repository.</param>
/// <param name="titres">La liste de titres à utiliser comme source de données pour le repository.</param>
public LocalTitreRepository(ILogger<LocalTitreRepository> logger, List<Titre> titres)
/// <param name="dataStore">La liste de titres à utiliser comme source de données pour le repository.</param>
public LocalTitreRepository(ILogger<LocalTitreRepository> logger, InMemoryDataStore dataStore)
{
this.logger = logger;
this.titres = titres;
this.dataStore = dataStore;
this.logger.LogDebug(1, "NLog injecté dans LocalTitreRepository");
}
/// <inheritdoc/>
public void Add(Titre titre)
{
try
{
this.logger.LogDebug("Ajout du titre: {Libelle}", titre.Libelle);
this.titres.Add(titre);
this.logger.LogDebug("Titre ajouté avec succès, ID: {IdTitre}", titre.IdTitre);
}
catch (Exception ex)
{
this.logger.LogError(ex, "Erreur lors de l'ajout du titre: {Libelle}", titre.Libelle);
throw;
}
throw new NotSupportedException("Mode local");
}
/// <inheritdoc/>
public int Count()
{
try
{
var count = this.titres.Count;
this.logger.LogDebug("Nombre total de titres: {Count}", count);
return count;
}
catch (Exception ex)
{
this.logger.LogError(ex, "Erreur lors du comptage des titres");
throw;
}
var count = this.dataStore.Titres.Count();
return count;
}
/// <inheritdoc/>
public void Delete(Titre titre)
{
try
{
this.logger.LogDebug("Suppression du titre ID: {IdTitre}", titre.IdTitre);
if (!this.titres.Contains(titre))
{
this.logger.LogWarning("Le titre avec l'identifiant {IdTitre} n'existe pas dans la liste.", titre.IdTitre);
}
this.titres.Remove(titre);
this.logger.LogDebug("Titre supprimé avec succès, ID: {IdTitre}", titre.IdTitre);
}
catch (Exception ex)
{
this.logger.LogError(ex, "Erreur lors de la suppression du titre ID: {IdTitre}", titre.IdTitre);
throw;
}
throw new NotSupportedException("Mode Local");
}
/// <inheritdoc/>
public IEnumerable<Titre> FindTitres(int offset, int limit)
{
try
{
this.logger.LogDebug("Recherche des titres avec offset: {Offset}, limit: {Limit}", offset, limit);
if (offset < 0 || limit <= 0)
{
this.logger.LogWarning("FindTitres appelé avec offset {Offset} ou limit {Limit} invalide.", offset, limit);
return Enumerable.Empty<Titre>();
}
var result = this.titres.Skip(offset).Take(limit).ToList();
this.logger.LogDebug("{Count} titres trouvés", result.Count);
return result;
}
catch (Exception ex)
{
this.logger.LogError(ex, "Erreur lors de la recherche des titres avec offset: {Offset}, limit: {Limit}", offset, limit);
throw;
}
return this.dataStore.Titres
.OrderByDescending(t => t.DateCreation)
.Skip(offset)
.Take(limit);
}
/// <inheritdoc/>
public void IncrementNbLectures(Titre titre)
{
try
{
this.logger.LogDebug("Incrémentation du nombre de lectures pour le titre ID: {IdTitre}", titre.IdTitre);
titre.NbLectures++;
this.logger.LogDebug("Nouveau nombre de lectures: {NbLectures}", titre.NbLectures);
}
catch (Exception ex)
{
this.logger.LogError(ex, "Erreur lors de l'incrémentation des lectures pour le titre ID: {IdTitre}", titre.IdTitre);
throw;
}
titre.NbLectures++;
}
/// <inheritdoc/>
public void IncrementNbLikes(Titre titre)
{
try
{
this.logger.LogDebug("Incrémentation du nombre de likes pour le titre ID: {IdTitre}", titre.IdTitre);
titre.NbLikes++;
this.logger.LogDebug("Nouveau nombre de likes: {NbLikes}", titre.NbLikes);
}
catch (Exception ex)
{
this.logger.LogError(ex, "Erreur lors de l'incrémentation des likes pour le titre ID: {IdTitre}", titre.IdTitre);
throw;
}
titre.NbLikes++;
}
/// <inheritdoc/>
public IEnumerable<Titre> Search(string mot)
{
try
{
this.logger.LogDebug("Recherche de titres avec le mot-clé: {Mot}", mot);
if (string.IsNullOrWhiteSpace(mot))
{
this.logger.LogWarning("Search appelé avec une chaîne vide ou contenant uniquement des espaces.");
return Enumerable.Empty<Titre>();
}
IEnumerable<Titre> list = this.titres
.Where(t => !string.IsNullOrWhiteSpace(t.Libelle)
&& t.Libelle.Contains(mot, StringComparison.OrdinalIgnoreCase))
.OrderBy(t => t.Libelle)
.ToList();
if (!list.Any())
{
this.logger.LogInformation("Aucun titre trouvé correspondant au terme de recherche '{Mot}'.", mot);
}
else
{
this.logger.LogDebug("{Count} titres trouvés pour le mot-clé '{Mot}'", list.Count(), mot);
}
return list;
}
catch (Exception ex)
{
this.logger.LogError(ex, "Erreur lors de la recherche des titres avec le mot-clé: {Mot}", mot);
throw;
}
return this.dataStore.Titres
.Where(t => t.Libelle != null && t.Libelle.Contains(mot));
}
/// <inheritdoc/>
public Titre Find(int idTitre)
{
try
{
this.logger.LogDebug("Recherche du titre avec ID: {IdTitre}", idTitre);
Titre titre = this.titres.First(t => t.IdTitre == idTitre);
this.logger.LogDebug("Titre trouvé: {Libelle}", titre.Libelle);
return titre;
}
catch (InvalidOperationException ex)
{
this.logger.LogWarning(ex, "Aucun titre trouvé avec l'ID: {IdTitre}", idTitre);
throw;
}
catch (Exception ex)
{
this.logger.LogError(ex, "Erreur lors de la recherche du titre avec ID: {IdTitre}", idTitre);
throw;
}
return this.dataStore.Titres
.First(t => t.IdTitre == idTitre);
}
/// <inheritdoc/>
public IEnumerable<Titre> FindAll()
{
try
{
this.logger.LogDebug("Récupération de tous les titres");
var result = this.titres;
this.logger.LogDebug("{Count} titres récupérés", result.Count);
return result;
}
catch (Exception ex)
{
this.logger.LogError(ex, "Erreur lors de la récupération de tous les titres");
throw;
}
return this.dataStore.Titres;
}
/// <inheritdoc/>
public IEnumerable<Titre> SearchByStyle(string libelle)
{
try
{
this.logger.LogDebug("Recherche des titres par style: {Libelle}", libelle);
if (string.IsNullOrWhiteSpace(libelle))
{
this.logger.LogWarning("SearchByStyle appelé avec une chaîne vide ou contenant uniquement des espaces.");
return Enumerable.Empty<Titre>();
}
IEnumerable<Titre> list = this.titres
.Where(t => t.Styles.Any(s => !string.IsNullOrWhiteSpace(s.Libelle)
&& s.Libelle.Contains(libelle, StringComparison.OrdinalIgnoreCase)))
.OrderBy(t => t.Libelle)
.ToList();
if (!list.Any())
{
this.logger.LogInformation("Aucun titre trouvé correspondant au style '{Libelle}'.", libelle);
}
else
{
this.logger.LogDebug("{Count} titres trouvés pour le style '{Libelle}'", list.Count(), libelle);
}
return list;
}
catch (Exception ex)
{
this.logger.LogError(ex, "Erreur lors de la recherche des titres par style: {Libelle}", libelle);
throw;
}
return this.dataStore.Titres
.Where(t => t.Styles.Any(s => s.Libelle == libelle));
}
/// <inheritdoc/>
public void Update(Titre titre)
{
try
{
this.logger.LogDebug("Mise à jour du titre ID: {IdTitre}", titre.IdTitre);
int index = this.titres.FindIndex(t => t.IdTitre == titre.IdTitre);
if (index == -1)
{
this.logger.LogWarning("Aucun titre trouvé avec l'identifiant {IdTitre}.", titre.IdTitre);
throw new InvalidOperationException($"Aucun titre trouvé avec l'identifiant {titre.IdTitre}.");
}
this.titres[index] = titre;
this.logger.LogDebug("Titre mis à jour avec succès, ID: {IdTitre}", titre.IdTitre);
}
catch (Exception ex)
{
this.logger.LogError(ex, "Erreur lors de la mise à jour du titre ID: {IdTitre}", titre.IdTitre);
throw;
}
throw new NotSupportedException("Mode local");
}
}

View File

@@ -1,7 +1,9 @@
using Microsoft.EntityFrameworkCore;
using NLog;
using NLog.Web;
using Microsoft.EntityFrameworkCore;
using Webzine.EntitiesContext;
using Webzine.Entity;
using Webzine.Entity.Fixtures;
using Webzine.Repository;
using Webzine.Repository.Contracts;
@@ -43,7 +45,8 @@ try
builder.Services.AddScoped<ITitreRepository, LocalTitreRepository>();
builder.Services.AddScoped<IStyleRepository, LocalStyleRepository>();
builder.Services.AddScoped<IArtisteRepository, LocalArtisteRepository>();
//builder.Services.AddScoped<ICommentaireRepository, LocalCommentaireRepository>();
builder.Services.AddScoped<ICommentaireRepository, LocalCommentaireRepository>();
builder.Services.AddSingleton<InMemoryDataStore>();
}
// https://learn.microsoft.com/fr-fr/aspnet/core/performance/response-compression?view=aspnetcore-10.0#configuration
@@ -52,13 +55,40 @@ try
var app = builder.Build();
using (var scope = app.Services.CreateScope())
if (useDatabase)
{
var db = scope.ServiceProvider.GetRequiredService<WebzineDbContext>();
db.Database.EnsureDeleted();
db.Database.EnsureCreated();
var repo = scope.ServiceProvider.GetRequiredService<DbEntityRepository>();
repo.SeedBaseDeDonnees();
using (var scope = app.Services.CreateScope())
{
var db = scope.ServiceProvider.GetRequiredService<WebzineDbContext>();
db.Database.EnsureDeleted();
db.Database.EnsureCreated();
var repo = scope.ServiceProvider.GetRequiredService<DbEntityRepository>();
repo.SeedBaseDeDonnees();
}
}
else
{
using (var scope = app.Services.CreateScope())
{
var store = scope.ServiceProvider.GetRequiredService<InMemoryDataStore>();
var artistes = SeedDataLocal.GenererListeArtiste(100);
var styles = SeedDataLocal.GenererListeStyle(15, 20);
var albums = SeedDataLocal.GenererListeAlbums(50);
var titres = SeedDataLocal.GenererListeTitre(500, artistes, styles, albums);
var commentaires = new List<Commentaire>();
foreach (var titre in titres)
{
commentaires.AddRange(SeedDataLocal.GenererListeCommentaire(titre, 0, 5));
}
store.Artistes.AddRange(artistes);
store.Styles = styles;
store.Titres = titres;
store.Commentaires.AddRange(commentaires);
}
}
app.UseResponseCompression();

View File

@@ -156,7 +156,7 @@
<h4 class="mb-4">Commentaires</h4>
@if (Model.Details.Commentaires.Any())
@if (Model.Details.Commentaires != null && Model.Details.Commentaires.Any())
{
foreach (var comment in Model.Details.Commentaires.OrderByDescending(c => c.DateCreation))
{

View File

@@ -10,7 +10,7 @@
"NombreDerniereChronique": 3,
"NombreDeTopTitres": 3
},
"UseDatabase": true,
"UseDatabase": false,
"ConnectionStrings": {
"DefaultConnection": "Data Source=Data/webzine.sqlite"
},