diff --git a/.drone.yml b/.drone.yml new file mode 100644 index 0000000..894663d --- /dev/null +++ b/.drone.yml @@ -0,0 +1,82 @@ +kind: pipeline +type: docker +name: CI_ApiPm + +trigger: + event: + - push + branch: + exclude: + - master + +steps: + - name: retore & build + image: mcr.microsoft.com/dotnet/sdk:8.0 + commands: + - dotnet build WF_EF_Api/WF_EF_Api.sln --configuration Release + depend_on: [clone] + + - name: test + image: mcr.microsoft.com/dotnet/sdk:8.0 + commands: + - dotnet test WF_EF_Api/XUnitTest/XUnitTest.csproj + depends_on: [retore & build] + + - name: publish + image: mcr.microsoft.com/dotnet/sdk:8.0 + commands: + - dotnet publish WF_EF_Api/WfApi/WfApi.csproj -c Release -o out + depends_on: [retore & build, test] + +--- + +kind: pipeline +type: docker +name: CI_ApiPm_Master + +trigger: + event: + - push + branch: + - master + +volumes: + - name: doc + temp: {} + + +steps: + - name: retore & build + image: mcr.microsoft.com/dotnet/sdk:8.0 + commands: + - dotnet build --configuration Release + depend_on: [clone] + + - name: test + image: mcr.microsoft.com/dotnet/sdk:8.0 + commands: + - dotnet test + depends_on: [retore & build] + + - name: generate doc + image: mcr.microsoft.com/dotnet/sdk:8.0 + volumes: + - name: doc + path: /doc + commands: + - dotnet new tool-manifest + - dotnet tool install NSwag.ConsoleCore + - dotnet restore + - cd WF_EF_Api/WfApi + - dotnet nswag aspnetcore2openapi /output:/doc/swagger.json + depends_on: [clone, retore & build] + + #- name: code-inspection + # image: hub.codefirst.iut.uca.fr/marc.chevaldonne:codefirs-dronsonarplugin-dotnet8 + # secret: [SECRET_SONAR_LOGIN] + # A FINIR + - name: publish + image: mcr.microsoft.com/dotnet/sdk:8.0 + commands: + - dotnet publish -c Release -o out + depends_on: [retore & build, test] \ No newline at end of file diff --git a/README.md b/README.md index 94b08a7..7cf3392 100644 --- a/README.md +++ b/README.md @@ -1,2 +1,59 @@ # WF-PmAPI + +### Paquets +NSwag.AspNetCore
+Moq + +🟨 En cours / ✅ Fait / ❌ Pas fait + +### Critères Entity Framework + +niveau | description | coeff | jalon | État +--- | --- | --- | --- | --- +☢️ | Le dépôt doit être accessible par l'enseignant | ☢️ | J1 | ✅ +☢️ | un .gitignore doit exister au premier push | ☢️ | J1 | ✅ +🎬 | les *projets* et les tests compilent | 1 | J1 & J2 | ✅ +🎬 | le projet et le tests s'exécutent sans bug (concernant la partie persistance) | 3 | J1 & J2 | ✅ +🟢 | Transcription du modèle : Modèle vers entités (et inversement) | 2 | J1 | ✅ +🟢 | Requêtes CRUD simples (sur une table) | 1 | J1 | ✅ +🟢 | Utilisation de LINQ to Entities | 2 | J1 | ✅ +🟡 | Injection / indépendance du fournisseur | 1 | J1 | ✅ +🟡 | Requêtes CRUD sur des données complexes (images par exemple) | 2 | J1 | ✅ +🟢 | Tests - Appli Console | 1 | J1 | ✅ +🟢 | Tests - Tests unitaires (avec SQLite in memory) | 2 | J1 | ❌ +🟢 | Tests - Données stubbées et/ou Moq | 1 | J1 | ✅ +🟡 | CI : build, tests, Sonar (doc?) | 1 | J1 | ❌ +🟡 | Utilisation de relations (One-to-One, One-to-Many, Many-to-Many) (+ mapping, TU, Requêtes) | 4 | J1 | ✅ +🟢 | Liens avec le web service | 2 | J1 | ✅ +🟡 | Utilisation d'un *Logger* | 1 | J1 | ❌ +🟡 | Déploiement | 4 | J2 | ❌ +🔴 | Unit of Work❌ / Repository✅ + extras (héritage, accès concurrents...) | 8 | J2 | 🟨 +🟢 | Utilisation dans le projet | 2 | J2 | ❌ +🟢 | mon dépôt possède un readme qui apporte quelque chose... | 2 | J2 | ✅ + + +### Critères Web API + +niveau | description | coeff | jalon | État +--- | --- | --- | --- | --- +☢️ | Le dépôt doit être accessible par l'enseignant | ☢️ | J1 | ✅ +☢️ | un .gitignore doit exister au premier push | ☢️ | J1 | ✅ +🎬 | les *projets* et les tests compilent | 1 | J1 & J2 | ✅ +🎬 | le projet et le tests s'exécutent sans bug (concernant la partie web api) | 4 | J1 & J2 | ✅ +🟢 | Modèle <-> DTO | 1 | J1 | ❌ +🟢 | Entities <-> DTO | 1 | J1 | ✅ +🟡 | Authentification | 4 | J1 | +🟢 | Requêtes GET, PUT, POST, DELETE sur des données simples (1 seul type d'objet en retour, propriétés de types natifs) | 2 | J1 | ✅ +🟡 | Pagination & filtrage | 2 | J1 | ✅ +🟢 | Injection de service | 2 | J1 | ✅ +🟡 | Requêtes GET, PUT, POST, DELETE sur des données complexes (plusieurs données complexes en retour) | 4 | J1 | 🟨 +🟢 | Tests - Appli Console (consommation des requêtes) | 4 | J1 | 🟨 +🟢 | Tests - Tests unitaires (avec Stub et/ou Moq) | 2 | J1 | ❌ +🟡 | CI : build, tests, Sonar, Documentation (en particulier Swagger avec exemples...) | 1 | J1 | ❌ +🟢 | Liens avec la persistance en base de données | 4 | J1 | ✅ +🟡 | Utilisation d'un *Logger* | 1 | J1 | ❌ +🟡 | Déploiement | 4 | J2 | ❌ +🟡 | Utilisation dans le projet | 4 | J2 | ❌ +🎬 | mon dépôt possède un readme qui apporte quelque chose... | 1 | J2 | ✅ + diff --git a/WF_EF_Api/.dockerignore b/WF_EF_Api/.dockerignore new file mode 100644 index 0000000..4d72b4f --- /dev/null +++ b/WF_EF_Api/.dockerignore @@ -0,0 +1,30 @@ +**/.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/** \ No newline at end of file diff --git a/WF_EF_Api/ConsoleTest/ConsoleTest.csproj b/WF_EF_Api/ConsoleTest/ConsoleTest.csproj new file mode 100644 index 0000000..73a6de7 --- /dev/null +++ b/WF_EF_Api/ConsoleTest/ConsoleTest.csproj @@ -0,0 +1,22 @@ + + + + Exe + net8.0 + enable + enable + + + + + all + runtime; build; native; contentfiles; analyzers; buildtransitive + + + + + + + + + diff --git a/WF_EF_Api/ConsoleTest/Program.cs b/WF_EF_Api/ConsoleTest/Program.cs new file mode 100644 index 0000000..4c4c4f5 --- /dev/null +++ b/WF_EF_Api/ConsoleTest/Program.cs @@ -0,0 +1,134 @@ +using Contextlib; +using Entity; +using Microsoft.Data.Sqlite; +using Microsoft.EntityFrameworkCore; +using Microsoft.Extensions.Options; +using StubbedContextLib; +using static System.Net.Mime.MediaTypeNames; +using static System.Net.WebRequestMethods; + +var connection = new SqliteConnection("DataSource=:memory:"); +connection.Open(); +var options = new DbContextOptionsBuilder() + .UseSqlite(connection) + .Options; + +using (var _context = new StubWTFContext(options)) +{ + _context.Database.EnsureCreated(); + + // ---- Test Image ---- // + + var imageManager = new DbImagesManager(_context); + + + await imageManager.AddImage(new Images() { Id = 0, ImgPath = "https://www.bing.com/ck/a?!&&p=390428c2820add92760900204667aa721b17d4eb9e8537c91544d76283d06b14JmltdHM9MTc0MjQyODgwMA&ptn=3&ver=2&hsh=4&fclid=297ef5ed-ac44-66f2-2498-e058adb06776&u=a1aHR0cHM6Ly93d3cucG9rZXBlZGlhLmZyL01hamFzcGlj&ntb=1" }); + await imageManager.AddImage(new Images() { Id = 0, ImgPath = "https://www.bing.com/images/search?view=detailV2&ccid=t57OzeAT&id=1CCCBB65825E5FB93F10CA6D29EFDBBFEB5CDF27&thid=OIP.t57OzeATZKjBDDrzXqbc5gHaE7&mediaurl=https%3a%2f%2fimg-19.commentcamarche.net%2fP51ArxVXHJKsgdTzGDaqajlWJ3s%3d%2f1500x%2fsmart%2f7b5dd43e607643fea1a61960e3f66fc4%2fccmcms-commentcamarche%2f39481621.jpg&cdnurl=https%3a%2f%2fth.bing.com%2fth%2fid%2fR.b79ececde01364a8c10c3af35ea6dce6%3frik%3dJ99c67%252fb7yltyg%26pid%3dImgRaw%26r%3d0&exph=999&expw=1500&q=image&simid=608026907577902968&ck=0D54F216D075AD6E0ABC46B3AAB7E80A&selectedIndex=19&itb=0" }); + Console.WriteLine("---- Test ajout image (id : 11, 12)"); + var images = await imageManager.GetAllImage(); + foreach (var image in images.items) + { + Console.WriteLine($"- ({image.Id}) : {(image.ImgPath.Length <= 40 ? image.ImgPath : image.ImgPath.Substring(0, 40)+"...")}"); + + + } + Console.WriteLine(""); + + + await imageManager.UpdateImage(12, new Images() { ImgPath = "https://testUpdate/stub"}); + Console.WriteLine("---- Test mise a jour image (id : 12)"); + images = await imageManager.GetAllImage(); + foreach (var image in images.items) + { + Console.WriteLine($"- ({image.Id}) : {(image.ImgPath.Length <= 40 ? image.ImgPath : image.ImgPath.Substring(0, 40) + "...")}"); + } + Console.WriteLine(""); + + + await imageManager.RemoveImage(12); + Console.WriteLine("---- Test suppression image (id : 12)"); + images = await imageManager.GetAllImage(); + foreach (var image in images.items) + { + Console.WriteLine($"- ({image.Id}) : {(image.ImgPath.Length <= 40 ? image.ImgPath : image.ImgPath.Substring(0, 40) + "...")}"); + } + Console.WriteLine(""); + + + Console.WriteLine("---- Test getById image (id : 11)"); + var img = await imageManager.GetImageById(11); + Console.WriteLine($"- ({img.Id}) : {(img.ImgPath.Length <= 40 ? img.ImgPath : img.ImgPath.Substring(0, 40) + "...")}"); + Console.WriteLine(""); + + + Console.WriteLine("---- Test getSomme image (nb : 5, page : 1)"); + images = await imageManager.GetSomeImage(1,5); + foreach (var image in images.items) + { + Console.WriteLine($"- ({image.Id}) : {(image.ImgPath.Length <= 40 ? image.ImgPath : image.ImgPath.Substring(0, 40) + "...")}"); + } + Console.WriteLine(""); + + + Console.WriteLine("---- Test LastId image"); + var id = await imageManager.GetLastImageId(); + Console.WriteLine($"- Last image id : {id}"); + Console.WriteLine(""); + + Console.WriteLine("-------------------------------------------------------------------------------"); + + // ---- Test Character ---- // + + var characterManager = new DbCharacterManager(_context); + + + await characterManager.AddCharacter(new Character() { Id = 0, Name = "Vipélière", IdImage = 11 }); + Console.WriteLine("---- Test ajout charcter (id : 11)"); + var characters = await characterManager.GetAll(); + foreach (var charac in characters.items) + { + Console.WriteLine($"- ({charac.Id}) : {charac.Name} -> {charac.IdImage} : {(charac.Images.ImgPath.Length <= 40 ? charac.Images.ImgPath : charac.Images.ImgPath.Substring(0, 40) + "...")}"); + } + Console.WriteLine(""); + + + await characterManager.UpdateCharacter(11,new Character() {Name = "Majespic"}); + Console.WriteLine("---- Test mise a jour charcter (id : 11)"); + characters = await characterManager.GetAll(); + foreach (var charac in characters.items) + { + Console.WriteLine($"- ({charac.Id}) : {charac.Name} -> {charac.IdImage} : {(charac.Images.ImgPath.Length <= 40 ? charac.Images.ImgPath : charac.Images.ImgPath.Substring(0, 40) + "...")}"); + } + Console.WriteLine(""); + + + await characterManager.RemoveCharacter(11); + Console.WriteLine("---- Test sup (id : 5)"); + characters = await characterManager.GetAll(); + foreach (var charac in characters.items) + { + Console.WriteLine($"- ({charac.Id}) : {charac.Name} -> {charac.IdImage} : {(charac.Images.ImgPath.Length <= 40 ? charac.Images.ImgPath : charac.Images.ImgPath.Substring(0, 40) + "...")}"); + } + Console.WriteLine(""); + + + Console.WriteLine("---- Test GetById (id : 5)"); + var chara = await characterManager.GetCharById(5); + Console.WriteLine($"- ({chara.Id}) : {chara.Name} -> {chara.IdImage} : {(chara.Images.ImgPath.Length <= 40 ? chara.Images.ImgPath : chara.Images.ImgPath.Substring(0, 40) + "...")}"); + Console.WriteLine(""); + + + Console.WriteLine("---- Test GetByName (name : Jon Snow)"); + chara = await characterManager.GetCharByName("Jon Snow"); + Console.WriteLine($"- ({chara.Id}) : {chara.Name} -> {chara.IdImage} : {(chara.Images.ImgPath.Length <= 40 ? chara.Images.ImgPath : chara.Images.ImgPath.Substring(0, 40) + "...")}"); + Console.WriteLine(""); + + + Console.WriteLine("---- Test LastId Character"); + id = await characterManager.GetLastCharId(); + Console.WriteLine($"- Last character id : {id}"); + Console.WriteLine(""); +} + + + diff --git a/WF_EF_Api/Contextlib/Contextlib.csproj b/WF_EF_Api/Contextlib/Contextlib.csproj new file mode 100644 index 0000000..960e394 --- /dev/null +++ b/WF_EF_Api/Contextlib/Contextlib.csproj @@ -0,0 +1,29 @@ + + + + net8.0 + enable + enable + + + + + + all + runtime; build; native; contentfiles; analyzers; buildtransitive + + + + + all + runtime; build; native; contentfiles; analyzers; buildtransitive + + + + + + + + + + diff --git a/WF_EF_Api/Contextlib/DbCharacterManager.cs b/WF_EF_Api/Contextlib/DbCharacterManager.cs new file mode 100644 index 0000000..7d01f7f --- /dev/null +++ b/WF_EF_Api/Contextlib/DbCharacterManager.cs @@ -0,0 +1,137 @@ +using Entity; +using Microsoft.EntityFrameworkCore; +using Shared; +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace Contextlib +{ + public class DbCharacterManager : ICharacterService + { + private WTFContext _context; + private GenericRepository _repo; + + public DbCharacterManager(WTFContext context) + { + _context = context ?? throw new ArgumentNullException(nameof(context), "Database context cannot be null."); + _repo = new GenericRepository(_context); + } + + /// + /// Adds a new character to the database. + /// + /// The character to be added to the database. + /// A task that represents the asynchronous operation. + /// Thrown when the provided character is null. + public async Task AddCharacter(Character character) + { + if (character == null) + { + throw new ArgumentNullException(nameof(character), "character cannot be null."); + } + _repo.Insert(character); + await _context.SaveChangesAsync(); + } + + /// + /// Retrieves all characters from the database and returns them in a paginated format. + /// + /// A task representing the asynchronous operation, with a as its result containing the full list of characters and pagination information. + public async Task> GetAll() + { + List charLst = _repo.GetItems(0, _repo.Count(), [nameof(Character.Images)]).ToList(); + return new PaginationResult(charLst.Count, 0, charLst.Count, charLst); + } + + /// + /// Retrieves a character by its ID from the database. + /// + /// The unique identifier of the character to retrieve. + /// A task that represents the asynchronous operation, with a as its result. + /// Thrown when no character is found with the given ID. + public async Task GetCharById(int id) + { + Character? character = _repo.GetById(id, item => item.Id == id, nameof(Character.Images)); + if (character == null) + { + throw new KeyNotFoundException($"Error : No character found with the ID: {id}."); + } + return character; + } + + /// + /// Retrieves a character by its name from the database. + /// + /// The name of the character to retrieve. + /// A task that represents the asynchronous operation, with a as its result. + /// Thrown when no character is found with the given name. + public async Task GetCharByName(string name) + { + var character = _repo.GetItems(item => item.Name == name,0,1, [nameof(Character.Images)]).FirstOrDefault(); + + return character; + } + + /// + /// Retrieves the highest character ID from the database. + /// + /// The highest character ID in the database. 0 if there is no character in the database + public async Task GetLastCharId() + { + PaginationResult characters = await GetAll(); + int lastCharId = 0; + foreach (Character character in characters.items) + { + if (character.Id >= lastCharId) + { + lastCharId = character.Id + 1; + } + } + return lastCharId; + } + + /// + /// Removes a character from the database by its ID. + /// + /// The ID of the character to remove. + /// A task representing the asynchronous operation. + /// Thrown when no character is found with the given ID. + public async Task RemoveCharacter(int id) + { + _repo.Delete(id); + await _context.SaveChangesAsync(); + } + + /// + /// Updates a character's details by its ID. + /// + /// The ID of the character to update. + /// The updated character information. + /// A task representing the asynchronous operation. + /// /// Thrown when the provided character is null. + /// Thrown when no character is found with the given ID. + public async Task UpdateCharacter(int id, Character character) + { + Character? charac = _repo.GetById(id); + if (charac != null) + { + bool change = false; + if (character.IdImage != 0) + { + charac.IdImage = character.IdImage; + change = true; + } + if (character.Name != null) + { + charac.Name = character.Name; + change = true; + } + _repo.Update(charac); + if (change) _context.SaveChanges(); + } + } + } +} diff --git a/WF_EF_Api/Contextlib/DbCommentaryManager.cs b/WF_EF_Api/Contextlib/DbCommentaryManager.cs new file mode 100644 index 0000000..bac04e3 --- /dev/null +++ b/WF_EF_Api/Contextlib/DbCommentaryManager.cs @@ -0,0 +1,221 @@ +using Entity; +using Microsoft.EntityFrameworkCore; +using Microsoft.EntityFrameworkCore.Update; +using Shared; +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace Contextlib +{ + public class DbCommentaryManager : ICommentaryService + { + private WTFContext _context; + private GenericRepository _repo; + + public DbCommentaryManager(WTFContext context) + { + _context = context ?? throw new ArgumentNullException(nameof(context), "Database context cannot be null."); + _repo = new GenericRepository(context); + } + + /// + /// Adds a new comment to the database. + /// + /// The comment to add. + /// A task representing the asynchronous operation. + /// Thrown when the comment is null. + public async Task AddComment(Commentary comment, int idQuote) + { + if (comment == null) + { + throw new ArgumentNullException(nameof(comment), "Comment cannot be null."); + } + + var quote = await _context.quotes + .Include(q => q.Commentarys) // collection des commentaires est chargée + .FirstOrDefaultAsync(q => q.Id == idQuote); + + var dbU = new DbUsersManager(_context); + var User = await dbU.GetUserByUsername(comment.User.UserName); + if (User == null) + { + throw new ArgumentException("Quote not exist", nameof(comment.User.UserName)); + } + + if (quote == null) + { + throw new ArgumentException("Quote not exist", nameof(idQuote)); + } + + comment.User = User; + comment.IdUser = User.Id; + + // Lien entre le commentaire et la citation + comment.Quote = quote; + comment.IdQuote = idQuote; + + // Ajout commentaire à la collection des commentaires de la citation + //_repo.Insert(comment); + _context.Add(comment); + await _context.SaveChangesAsync(); + } + + /// + /// Deletes all comments associated with a specific quote ID from the database. + /// + /// The ID of the quote whose comments need to be deleted. + /// A task representing the asynchronous operation. + /// Thrown when no comments are found for the provided quote ID. + public async Task DeleteCommentaryForQuote(int quoteId) + { + var comments = await _context.comments.Where(x => x.IdQuote == quoteId).ToListAsync(); + if (!comments.Any()) + { + throw new KeyNotFoundException($"No comments found for the quote ID: {quoteId}."); + } + + _context.comments.RemoveRange(comments); + await _context.SaveChangesAsync(); + } + + /// + /// Deletes all comments associated with a specific user ID from the database. + /// + /// The ID of the user whose comments need to be deleted. + /// A task representing the asynchronous operation. + /// Thrown when no comments are found for the provided user ID. + public async Task DeleteCommentaryForUser(int userId) + { + var comments = await _context.comments.Include(c => c.User).Where(x => x.IdUser == userId).ToListAsync(); + if (!comments.Any()) + { + throw new KeyNotFoundException($"No comments found for the user ID: {userId}."); + } + + _context.comments.RemoveRange(comments); + await _context.SaveChangesAsync(); + } + + public async Task> GetAllCommentary() + { + var comments = await _context.comments.Include(c => c.User).Include(c=>c.User.Images).ToListAsync(); + return new PaginationResult(comments.Count, 0, comments.Count, comments); + } + + public async Task GetCommentaryById(int id) + { + var comment = await _context.comments.Include(c => c.User).Include(c => c.User.Images).Where(x => x.Id == id).FirstOrDefaultAsync(); + if(comment == null) + { + throw new KeyNotFoundException($"No comments found with the given ID: {id}."); + } + return comment; + } + + public async Task> GetCommentaryByQuote(int quoteId, int index, int pageSize) + { + var comments = await _context.comments.Include(c => c.User).Include(c => c.User.Images).Where(x => x.IdQuote == quoteId).ToListAsync(); + if (!comments.Any()) + { + throw new KeyNotFoundException($"No comments found for the quote ID: {quoteId}."); + } + if ((index * pageSize + pageSize) > comments.Count) + { + if (pageSize > comments.Count) + { + return new PaginationResult(comments.Count(), index, pageSize, comments); + } + else + { + return new PaginationResult(pageSize, index, pageSize, comments.Skip(index * pageSize - (((index * pageSize) + pageSize) - comments.Count)).Take(pageSize).ToList()); + } + + } + return new PaginationResult(comments.Count, index, pageSize, comments.Skip(index * pageSize).Take(pageSize).ToList()); + } + + public async Task> GetCommentaryByUser(int userId, int index, int pageSize) + { + var comments = await _context.comments.Include(c => c.User).Where(x => x.IdUser == userId).ToListAsync(); + if (!comments.Any()) + { + throw new KeyNotFoundException($"No comments found for the user ID: {userId}."); + } + if ((index * pageSize + pageSize) > comments.Count) + { + if (pageSize > comments.Count) + { + return new PaginationResult(comments.Count(), index, pageSize, comments); + } + else + { + return new PaginationResult(pageSize, index, pageSize, comments.Skip(index * pageSize - (((index * pageSize) + pageSize) - comments.Count)).Take(pageSize).ToList()); + } + + } + return new PaginationResult(comments.Count, index, pageSize, comments.Skip(index * pageSize).Take(pageSize).ToList()); + } + + public async Task LastCommentaryId() + { + var last = await _context.comments.OrderByDescending(x => x.Id).FirstOrDefaultAsync(); + if(last == null) + { + return 0; + } + return last.Id; + } + + public async Task RemoveCommentary(int id) + { + + Commentary? commentary = await GetCommentaryById(id); + if (commentary == null) + { + throw new KeyNotFoundException($"Error : No comment found with the ID: {id}."); + } + _repo.Delete(commentary); + await _context.SaveChangesAsync(); + } + + public async Task UpdateCommentary(int id, Commentary comment) + { + var modif = false; + var com = await _context.comments.Where(x => x.Id == id).FirstOrDefaultAsync(); + if (comment == null) + { + throw new ArgumentNullException(nameof(comment), "The updated comment data cannot be null."); + } + if (com == null) + { + throw new KeyNotFoundException($"No comments found with the given ID: {id}."); + } + if (comment.Comment != null) + { + com.Comment = comment.Comment; + modif = true; + } + if(comment.DateCommentary != null){ + com.DateCommentary = comment.DateCommentary; + modif = true; + } + if(comment.IdQuote != 0) + { + com.IdQuote = comment.IdQuote; + modif = true; + } + if (comment.IdUser != 0) + { + com.IdUser = comment.IdUser; + modif = true; + } + if (modif) + { + await _context.SaveChangesAsync(); + } + } + } +} diff --git a/WF_EF_Api/Contextlib/DbFavoriteManager.cs b/WF_EF_Api/Contextlib/DbFavoriteManager.cs new file mode 100644 index 0000000..0fbdd59 --- /dev/null +++ b/WF_EF_Api/Contextlib/DbFavoriteManager.cs @@ -0,0 +1,117 @@ +using Entity; +using Microsoft.EntityFrameworkCore; +using Microsoft.EntityFrameworkCore.Metadata.Internal; +using Shared; +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace Contextlib +{ + public class DbFavoriteManager : IFavoriteService + { + private WTFContext _context; + private GenericRepository _repo; + + public DbFavoriteManager(WTFContext context) + { + _context = context ?? throw new ArgumentNullException(nameof(context), "Database context cannot be null."); + _repo = new GenericRepository(context); + } + + public async Task AddFavorite(int quoteid, int userId) + { + var quote = await _context.quotes // collection des commentaires est chargée + .Include(q => q.Favorite) + .FirstOrDefaultAsync(q => q.Id == quoteid); + + var user = await _context.users // collection des commentaires est chargée + .Include(u => u.Favorite) + .FirstOrDefaultAsync(q => q.Id == userId); + + if (quote == null && user == null) + { + throw new ArgumentException("Quote or User not exist", nameof(quoteid)); + } + + + var fav = new Favorite + { + // Lien entre le favorite et la citation + Quote = quote, + IdQuote = quoteid, + // Lien entre le favorite et le user + Users = user, + IdUsers = userId, + }; + + if (fav != null) + { + // Ajout favorite à la collection des favorites de la citation + quote.Favorite.Add(user); + + // Ajout favorite à la collection des favorites de la citation + user.Favorite.Add(quote); + } + _context.Add(fav); + await _context.SaveChangesAsync(); + } + + + public async Task RemoveAllFavoriteForQuote(int quoteId) + { + var fav = _context.favorites.Where(item => item.IdQuote == quoteId).ToList(); + + if (fav == null) throw new KeyNotFoundException(); + + foreach (var item in fav) + { + _context.favorites.Remove(item); + } + + await _context.SaveChangesAsync(); + } + + public async Task RemoveAllFavoriteForUser(int userId) + { + var fav = _context.favorites.Where(item => item.IdUsers == userId).ToList(); + + if (fav == null) throw new KeyNotFoundException(); + + foreach (var item in fav) + { + _context.favorites.Remove(item); + } + + await _context.SaveChangesAsync(); + } + + public async Task RemoveFavorite(int quoteid, int userId) + { + var fav = await _context.favorites.Where(item=>item.IdQuote==quoteid && item.IdUsers==userId).FirstAsync(); + + if (fav == null) throw new KeyNotFoundException(); + + _context.favorites.Remove(fav); + + await _context.SaveChangesAsync(); + } + + public async Task GetFavorite(int userId, int idQuote) + { + return await _context.quotes.Where( item => item.Id == idQuote && item.Favorite.Any(u => u.Id == userId) ) + .Include(q => q.Source).Include(q => q.Character).ThenInclude(c => c.Images).Include(q=>q.Favorite) + .FirstOrDefaultAsync(); + } + + public async Task> GetFavoriteByIdUser(int userId, int index, int count) + { + List fav = await _context.quotes.Where(item => item.Favorite.Any(u => u.Id == userId)) + .Include(q => q.Source).Include(q => q.Character).ThenInclude(c => c.Images).Include(q => q.Favorite) + .Skip(index * count).Take(count).ToListAsync(); + return new PaginationResult(fav.Count,index,count,fav); + } + } +} diff --git a/WF_EF_Api/Contextlib/DbImagesManager.cs b/WF_EF_Api/Contextlib/DbImagesManager.cs new file mode 100644 index 0000000..e549cf9 --- /dev/null +++ b/WF_EF_Api/Contextlib/DbImagesManager.cs @@ -0,0 +1,97 @@ +using Entity; +using Microsoft.EntityFrameworkCore; +using Microsoft.EntityFrameworkCore.Metadata.Internal; +using Shared; +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; +using System.Xml.Linq; + +namespace Contextlib +{ + public class DbImagesManager : IImagesService + { + private WTFContext _context; + private GenericRepository _repository; + + public DbImagesManager(WTFContext context) + { + _context = context ?? throw new ArgumentNullException(nameof(context), "Database context cannot be null."); + _repository = new GenericRepository(context); + } + + public async Task AddImage(Images image) + { + _repository.Insert(image); + await _context.SaveChangesAsync(); + } + + public async Task> GetAllImage() + { + return new PaginationResult(await CountImage(), 0, await CountImage(), _repository.GetItems(0, await CountImage()).ToList()); + } + + public async Task GetImageById(int id) + { + return _repository.GetById(id); + } + + public async Task GetLastImageId() + { + var last = await GetAllImage(); + int id = 1; + { + foreach (Images image in last.items) + { + if(image.Id >= id) + id = image.Id + 1; + } + } + return id; + } + + public async Task> GetSomeImage(int index, int pageSize) + { + var images = _repository.GetItems(index, pageSize); + return new PaginationResult(images.Count(),index,pageSize,images.ToList()); + } + + public async Task RemoveImage(int id) + { + _repository.Delete(id); + await _context.SaveChangesAsync(); + } + + public async Task UpdateImage(int id, Images image) + { + var img = _repository.GetById(id); + var modif = false; + if (image != null && img != null) + { + if (image.ImgPath != null) + { + img.ImgPath = image.ImgPath; + modif = true; + } + _repository.Update(img); + if (modif) + { + await _context.SaveChangesAsync(); + } + } + } + + public async Task CountImage() + { + return await _context.images.CountAsync(); + } + + public async Task GetImageByPath(string path) + { + var image = _repository.GetItems(item => item.ImgPath == path,0,1).FirstOrDefault(); + return image; + } + } +} diff --git a/WF_EF_Api/Contextlib/DbQuestionManager.cs b/WF_EF_Api/Contextlib/DbQuestionManager.cs new file mode 100644 index 0000000..5e323b7 --- /dev/null +++ b/WF_EF_Api/Contextlib/DbQuestionManager.cs @@ -0,0 +1,155 @@ +using Entity; +using Microsoft.EntityFrameworkCore; +using Shared; +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace Contextlib +{ + public class DbQuestionManager : IQuestionService + { + private WTFContext _context; + private GenericRepository _repository; + + public DbQuestionManager(WTFContext context) + { + _context = context ?? throw new ArgumentNullException(nameof(context), "Database context cannot be null."); + _repository = new GenericRepository(context); + } + + public async Task AddQuestion(Question question) + { + _repository.Insert(question); + await _context.SaveChangesAsync(); + } + + public async Task CountQuestions() + { + return _repository.Count(); + } + + public async Task> GetAllQuestion() + { + return new PaginationResult(_repository.Count(), 0, _repository.Count(), _repository.GetItems(0,_repository.Count()).ToList()); + } + + public async Task> GetInvalidQuestion(int index, int pageSize) + { + List questionList = _repository.GetItems(item => item.IsValid == false, index, pageSize).ToList(); + return new PaginationResult(questionList.Count(), index, pageSize, questionList); + } + + public async Task GetQuestionById(int id) + { + return _repository.GetById(id); + } + + public async Task GetRandomQuestion() + { + Random rnd = new Random(); + Question? question = null; + while(question == null) + { + question = await GetQuestionById(rnd.Next(0, await LastId()-1)); + } + return question; + } + + public async Task GetRandomQuestionQuoteToCharacter() + { + //dabord implémenter get random quote + throw new NotImplementedException(); + } + + public async Task GetRandomQuestionQuoteToSource() + { + //dabord implémenter get random quote + throw new NotImplementedException(); + } + + public async Task> GetSomeQuestion(int index, int pageSize) + { + List questionList = _repository.GetItems(item => item.IsValid == false, index, pageSize).ToList(); + return new PaginationResult(questionList.Count(), index, pageSize, questionList); + } + + public async Task RemoveQuestion(int id) + { + _repository.Delete(id); + await _context.SaveChangesAsync(); + } + + public async Task UpdateQuestion(int id, Question question) + { + Question? questionUpdated = await GetQuestionById(id); + if (question != null && questionUpdated != null) + { + bool modified = false; + if (question.IsValid != questionUpdated.IsValid) + { + questionUpdated.IsValid = question.IsValid; + modified = true; + } + if (question.Text != null) + { + questionUpdated.Text = question.Text; + modified = true; + } + if (question.AnswerA != null) + { + questionUpdated.AnswerA = question.AnswerA; + modified = true; + } + if (question.AnswerB != null) + { + questionUpdated.AnswerB = question.AnswerB; + modified = true; + } + if (question.AnswerC != null) + { + questionUpdated.AnswerC = question.AnswerC; + modified = true; + } + if (question.AnswerD != null) + { + questionUpdated.AnswerD = question.AnswerD; + modified = true; + } + if (question.CorrectAnswer != null) + { + questionUpdated.CorrectAnswer = question.CorrectAnswer; + modified = true; + } + _repository.Update(questionUpdated); + if(modified) _context.SaveChanges(); + } + ; + + } + + public async Task ValidateQuestion(int id, bool isvalid) + { + Question? question = await GetQuestionById(id); + if (question == null) throw new KeyNotFoundException($"Aucune question avec l'id {id}"); + question.IsValid = isvalid; + _repository.Update(question); + } + + public async Task LastId() + { + PaginationResult questions = await GetAllQuestion(); + int id = 1; + foreach (Question question in questions.items) + { + if (question.Id >= id) + { + id = question.Id + 1; + } + } + return id; + } + } +} diff --git a/WF_EF_Api/Contextlib/DbQuoteManager.cs b/WF_EF_Api/Contextlib/DbQuoteManager.cs new file mode 100644 index 0000000..0a4236a --- /dev/null +++ b/WF_EF_Api/Contextlib/DbQuoteManager.cs @@ -0,0 +1,298 @@ +using System; +using System.Collections; +using System.Collections.Generic; +using System.Linq; +using System.Security.Cryptography; +using System.Text; +using System.Threading.Tasks; +using Entity; +using Microsoft.EntityFrameworkCore; +using Microsoft.EntityFrameworkCore.Metadata.Internal; +using Shared; + +namespace Contextlib +{ + public class DbQuoteManager : IQuoteService + { + private WTFContext _context; + private GenericRepository _repo; + private DbCharacterManager _dbC; + private DbSourceManager _dbS; + private DbImagesManager _dbI; + + public DbQuoteManager(WTFContext context) + { + _context = context ?? throw new ArgumentNullException(nameof(context), "Database context cannot be null."); + _repo = new GenericRepository(_context); + _dbS = new DbSourceManager(_context); + _dbC = new DbCharacterManager(_context); + _dbI = new DbImagesManager(_context); + + } + + + public async Task AddQuote(Quote quote) + { + if (quote == null) + { + throw new ArgumentNullException(nameof(quote), "quote cannot be null."); + } + //Character + var c = await _dbC.GetCharByName(quote.Character.Name); + if (c != null) + { + quote.IdCharacter = c.Id; + quote.Character = c; + } + //Image + var i = await _dbI.GetImageByPath(quote.Character.Images.ImgPath); + if (i != null) + { + quote.Character.IdImage = i.Id; + quote.Character.Images = i; + } + //Source + var s = await _dbS.GetSourceByTitle(quote.Source.Title); + if (s != null) + { + quote.IdSource = s.Id; + quote.Source = s; + } + + _repo.Insert(quote); + await _context.SaveChangesAsync(); + return quote; + } + + public async Task> GetAllQuote() + { + List quotes = _context.quotes.Where(item => item.IsValid) + .Include(q => q.Source).Include(q => q.Character).ThenInclude(c => c.Images) + .ToList(); + return new PaginationResult(quotes.Count, 0, quotes.Count, quotes); + } + + public async Task> GetAllQuoteLang(int index, int pageSize, int lang) + { + List quotes = await _context.quotes.Where(item => item.IsValid && item.Langage == (LangEnum)lang) + .Include(q => q.Source).Include(q => q.Character).ThenInclude(c => c.Images) + .Skip(index * pageSize).Take(pageSize).ToListAsync(); + return new PaginationResult(quotes.Count, index, pageSize, quotes); + } + + public async Task GetDailyQuote(DateOnly date, int lang) + { + List quotes = await _context.quotes.Where(item => item.IsValid && item.Langage == (LangEnum)lang) + .Include(q => q.Source).Include(q => q.Character).ThenInclude(c => c.Images).Include(q => q.Favorite) + .ToListAsync(); + if (quotes.Count() == 0) return null; + Quote quote = quotes[date.DayNumber % quotes.Count()]; + + return quote; + } + + public async Task> GetFavorites(int index, int pageSize, int UserId) + { + List quotes = _context.quotes.Where(item => item.IsValid && item.Favorite.Where(p => p.Id == UserId) != null) + .Include(q => q.Source).Include(q => q.Character).ThenInclude(c => c.Images).Include(q => q.Favorite) + .Skip(index * pageSize).Take(pageSize).ToList(); + + return new PaginationResult(quotes.Count, index, pageSize, quotes); + } + + public async Task> GetInvalidQuote(int index, int pageSize, int lang) + { + List quotes = _context.quotes.Where(item => !item.IsValid && item.Langage == (LangEnum)lang) + .Include(q => q.Source).Include(q => q.Character).ThenInclude(c => c.Images) + .Skip(index * pageSize).Take(pageSize).ToList(); + + return new PaginationResult(quotes.Count, index, pageSize, quotes); + } + + public async Task> GetInvalidQuote(int index, int pageSize) + { + List quotes = _context.quotes.Where(item => !item.IsValid) + .Include(q => q.Source).Include(q => q.Character).ThenInclude(c => c.Images) + .Skip(index * pageSize).Take(pageSize).ToList(); + + return new PaginationResult(quotes.Count, index, pageSize, quotes); + } + + public async Task GetLastQuoteId() + { + PaginationResult quotes = await GetAllQuote(); + int lastQuoteId = 0; + foreach (Quote quote in quotes.items) + { + if (quote.Id >= lastQuoteId) + { + lastQuoteId = quote.Id + 1; + } + } + return lastQuoteId; + } + + public async Task GetQuoteById(int id) + { + Quote? quote = _context.quotes.Where(item => item.Id == id) + .Include(q => q.Source).Include(q => q.Character).ThenInclude(c => c.Images) + .FirstOrDefault(); + + return quote; + } + + public async Task> GetSomeQuote(int index, int pageSize) + { + List quotes = _context.quotes.Where(item => item.IsValid) + .Include(q => q.Source).Include(q => q.Character).ThenInclude(c => c.Images) + .Skip(index * pageSize).Take(pageSize).ToList(); + + return new PaginationResult(quotes.Count, index, pageSize, quotes); + } + + public async Task> GetSuggestions(int index, int pageSize, int lang) // A changer Suggestion Random + { + List quotes = _context.quotes.Where(item => item.IsValid && item.Langage == (LangEnum)lang) + .Include(q => q.Source).Include(q => q.Character).ThenInclude(c => c.Images) + //.OrderBy(q=> new Random() ) + .Skip(index * pageSize).Take(pageSize).ToList(); + + return new PaginationResult(quotes.Count, index, pageSize, quotes); + } + + public async Task> GetValidQuote(int index, int pageSize) + { + List quotes = _context.quotes.Where(item => item.IsValid) + .Include(q => q.Source).Include(q => q.Character).ThenInclude(c => c.Images) + .Skip(index * pageSize).Take(pageSize).ToList(); + + return new PaginationResult(quotes.Count, index, pageSize, quotes); + } + + public async Task> SearchByCharacter(string character, int index, int pageSize, int lang) + { + List quotes = _context.quotes.Where(item => item.IsValid && item.Langage==(LangEnum)lang && (item.Character.Name).Contains(character)) + .Include(q => q.Source).Include(q => q.Character).ThenInclude(c => c.Images) + .Skip(index * pageSize).Take(pageSize).ToList(); + + return new PaginationResult(quotes.Count, index, pageSize, quotes); + } + + public async Task> SearchByContent(string content, int index, int pageSize, int lang) + { + List quotes = _context.quotes.Where(item => item.IsValid && item.Langage == (LangEnum)lang && (item.Content).Contains(content)) + .Include(q => q.Source).Include(q => q.Character).ThenInclude(c => c.Images) + .Skip(index * pageSize).Take(pageSize).ToList(); + + return new PaginationResult(quotes.Count, index, pageSize, quotes); + } + + public async Task> SearchBySource(string source, int index, int pageSize, int lang) + { + List quotes = _context.quotes.Where(item => item.IsValid && item.Langage == (LangEnum)lang && (item.Source.Title).Contains(source)) + .Include(q => q.Source).Include(q => q.Character).ThenInclude(c => c.Images) + .Skip(index * pageSize).Take(pageSize).ToList(); + + return new PaginationResult(quotes.Count, index, pageSize, quotes); + } + + + + + + public async Task RemoveQuote(int quoteId) + { + var quote = _repo.GetById(quoteId); + if (quote == null) throw new KeyNotFoundException(); + _repo.Delete( quote ); + await _context.SaveChangesAsync(); + } + + public async Task UpdateQuote(int quoteId, Quote quote) + { + //Character + var c = await _dbC.GetCharByName(quote.Character.Name); + if (c != null) + { + quote.IdCharacter = c.Id; + quote.Character = c; + } + //Image + var i = await _dbI.GetImageByPath(quote.Character.Images.ImgPath); + if (c != null) + { + quote.Character.IdImage = i.Id; + quote.Character.Images = i; + } + //Source + var s = await _dbS.GetSourceByTitle(quote.Source.Title); + if (c != null) + { + quote.IdSource = s.Id; + quote.Source = s; + } + + Quote? q = _repo.GetById(quoteId); + if (q != null) + { + bool change = false; + if (quote.IdSource != 0) + { + q.IdSource = quote.IdSource; + change = true; + } + if (quote.IdCharacter != 0) + { + q.IdCharacter = quote.IdCharacter; + change = true; + } + if (quote.IdSource != 0) + { + q.IdSource = quote.IdSource; + change = true; + } + if (quote.IdUsersPropose !=0) + { + q.IdUsersPropose = quote.IdUsersPropose; + change = true; + } + if (quote.Content != null || quote.Content == "") + { + q.Content = quote.Content; + change = true; + } + if (quote.IsValid != q.IsValid) + { + q.IsValid = quote.IsValid; + change = true; + } + if (quote.Likes != q.Likes) + { + q.Likes = quote.Likes; + change = true; + } + if (quote.Langage != q.Langage) + { + q.Langage = quote.Langage; + change = true; + } + + _repo.Update(q); + if (change) _context.SaveChanges(); + } + return ; + } + + public async Task ValidateQuote(int quoteId, bool isValidate) + { + Quote? q = _repo.GetById(quoteId); + if (q != null) + { + q.IsValid = isValidate; + _repo.Update(q); + _context.SaveChanges(); + } + return; + } + } +} diff --git a/WF_EF_Api/Contextlib/DbSourceManager.cs b/WF_EF_Api/Contextlib/DbSourceManager.cs new file mode 100644 index 0000000..e2ed299 --- /dev/null +++ b/WF_EF_Api/Contextlib/DbSourceManager.cs @@ -0,0 +1,114 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; +using Entity; +using Shared; +using static System.Runtime.InteropServices.JavaScript.JSType; + +namespace Contextlib +{ + public class DbSourceManager : ISourceService + { + private WTFContext _context; + private GenericRepository _repo; + + public DbSourceManager(WTFContext context) + { + _context = context ?? throw new ArgumentNullException(nameof(context), "Database context cannot be null."); + _repo = new GenericRepository(_context); + } + + public async Task AddSource(Source source) + { + if (source == null) + { + throw new ArgumentNullException(nameof(source), "character cannot be null."); + } + _repo.Insert(source); + await _context.SaveChangesAsync(); + } + + public async Task> GetAll() + { + List srcLst = _repo.GetItems(0, _repo.Count(), []).ToList(); + return new PaginationResult(srcLst.Count, 0, srcLst.Count, srcLst); + } + + public async Task GetLastSourceId() + { + throw new NotImplementedException(); + } + + public async Task> GetSomesSource(int page, int count) + { + var srcLst = _repo.GetItems(page, count, []).ToList(); + return new PaginationResult(srcLst.Count, 0, srcLst.Count, srcLst); + } + + public async Task> GetSourceByDate(int date) + { + + var srcLst = _repo.GetItems(item => item.Year == date, 0, _repo.Count(), []).ToList(); + + return new PaginationResult(srcLst.Count, 0, srcLst.Count, srcLst); + } + + public async Task GetSourceById(int id) + { + Source? source = _repo.GetById(id, item => item.Id == id, []); + if (source == null) + { + throw new KeyNotFoundException($"Error : No source found with the ID: {id}."); + } + return source; + } + + public async Task GetSourceByTitle(string title) + { + var source = _repo.GetItems(item => item.Title == title, 0, 1, []).FirstOrDefault(); + + return source; + } + + public async Task GetSourceByType(int type) + { + var source = _repo.GetItems(item => item.TypeSrc == (TypeSrcEnum)type, 0, 1, []).FirstOrDefault(); + + return source; + } + + public async Task RemoveSource(int id) + { + _repo.Delete(id); + await _context.SaveChangesAsync(); + } + + public async Task UpdateSource(int id, Source source) + { + Source? src = _repo.GetById(id); + if (src != null) + { + bool change = false; + if (src.Title != source.Title) + { + src.Title = source.Title; + change = true; + } + if (src.Year != source.Year) + { + src.Year = source.Year; + change = true; + } + if (src.TypeSrc != source.TypeSrc) + { + src.TypeSrc = source.TypeSrc; + change = true; + } + _repo.Update(src); + if (change) _context.SaveChanges(); + } + } + } +} diff --git a/WF_EF_Api/Contextlib/DbUsersManager.cs b/WF_EF_Api/Contextlib/DbUsersManager.cs new file mode 100644 index 0000000..e10ca69 --- /dev/null +++ b/WF_EF_Api/Contextlib/DbUsersManager.cs @@ -0,0 +1,185 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; +using Entity; +using Microsoft.EntityFrameworkCore; +using Shared; + +namespace Contextlib +{ + public class DbUsersManager : IUserService + { + private WTFContext _context; + private GenericRepository _repo; + + public DbUsersManager( WTFContext context ) + { + _context = context ?? throw new ArgumentNullException(nameof(context), "Database context cannot be null."); + _repo = new GenericRepository(_context); + } + + + + public async Task AddUser(Users user) + { + /*if (await ExistEmail(user.Email) || (await ExistUsername(user.UserName))) + { + throw new ArgumentException("The given Email or Username Already exist"); + }*/ + if (user == null) { + throw new ArgumentNullException(nameof(user), "user cannot be null."); + } + var dbI = new DbImagesManager(_context); + var image = await dbI.GetImageByPath(user.Images.ImgPath); + if(image != null) + { + user.IdImage = image.Id; + user.Images = image; + } + _repo.Insert(user); + await _context.SaveChangesAsync(); + } + + public async Task CountUser() + { + return _repo.Count(); + } + + public async Task ExistEmail(string email) + { + Users? users = await _context.users.Where(u=>u.Email == email).FirstOrDefaultAsync(); + return users != null; + } + + public async Task ExistUsername(string username) + { + Users? users = await _context.users.Where(u => u.UserName == username).FirstOrDefaultAsync(); + return users != null; + } + + public async Task> GetAllUser() + { + List users = _repo.GetItems(0,_repo.Count(),[nameof(Users.Images)]).ToList(); + return new PaginationResult(users.Count,0,users.Count,users); + } + + public async Task GetHashPassword(string username) + { + Users? user = _context.users.Where(u=>u.UserName == username).FirstOrDefault(); + if (user == null) + { + return ""; + } + return user.Password; + } + + public async Task GetLastUserId() + { + PaginationResult users = await GetAllUser(); + int lastUserId = 0; + foreach (Users user in users.items) + { + if (user.Id >= lastUserId) + { + lastUserId = user.Id + 1; + } + } + return lastUserId; + } + + public async Task> GetSomeUser(int index, int pageSize) + { + List users = _repo.GetItems(index, pageSize, [nameof(Users.Images)]).ToList(); + return new PaginationResult(users.Count, index, pageSize, users); + } + + public async Task GetUserByEmail(string email) + { + var user = _repo.GetItems(item => item.Email == email, 0, 1, [nameof(Character.Images)]).FirstOrDefault(); + + if (user == null) + { + throw new KeyNotFoundException($"Error : No user found with the email: {email}."); + } + + return user; + } + + public async Task GetUserById(int id) + { + Users? user =_repo.GetById(id, item => item.Id == id, nameof(Users.Images)); + if (user == null) + { + throw new KeyNotFoundException($"Error : No users found with the ID: {id}."); + } + return user; + } + + public async Task GetUserByUsername(string username) + { + var user = _repo.GetItems(item => item.UserName == username, 0, 1, [nameof(Character.Images)]).FirstOrDefault(); + + if (user == null) + { + throw new KeyNotFoundException($"Error : No user found with the name: {username}."); + } + + return user; + } + + public async Task RemoveUser(int id) + { + Users? user = _repo.GetById(id); + if (user == null) + { + throw new KeyNotFoundException($"Error : No users found with the ID: {id}."); + } + _repo.Delete(user); + await _context.SaveChangesAsync(); + } + + public async Task SetAdminRole(bool isAdmin) + { + throw new NotImplementedException(); + } + + public async Task UpdateUser(int userId, Users user) + { + Users? u = _repo.GetById(userId, item => item.Id == userId, nameof(Users.Images)); + if (u != null) + { + bool change = false; + if (user.Images.ImgPath != null) + { + var dbI = new DbImagesManager(_context); + var img = await dbI.GetImageByPath(user.Images.ImgPath); + if (img != null) + { + u.IdImage = dbI.GetImageByPath(user.Images.ImgPath).Id; + change = true; + } + } + if (user.UserName != null) + { + u.UserName = user.UserName; + change = true; + } + if (user.Email != null) + { + u.Email = user.Email; + change = true; + } + if (user.Password != null) + { + u.Password = user.Password; + change = true; + } + _repo.Update(u); + if (change)_context.SaveChanges(); + } + return u; + } + } +} diff --git a/WF_EF_Api/Contextlib/GenericRepository.cs b/WF_EF_Api/Contextlib/GenericRepository.cs new file mode 100644 index 0000000..0bee129 --- /dev/null +++ b/WF_EF_Api/Contextlib/GenericRepository.cs @@ -0,0 +1,120 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Linq.Expressions; +using System.Text; +using System.Threading.Tasks; +using Microsoft.EntityFrameworkCore; +using Microsoft.EntityFrameworkCore.Metadata.Internal; + +namespace Contextlib +{ + public class GenericRepository where T : class + { + private DbContext Context { get; set; } + private DbSet Set { get; set; } + + public GenericRepository(DbContext context) + { + Context = context; + Set = Context.Set(); + } + + public virtual T? GetById(object id) + => Set.Find(id); + + public virtual T? GetById(object id, Expression>? filter = null, params string[] includeProperties) + { + IQueryable query = Set; + if (filter != null) + { + query = query.Where(filter); + } + foreach (string includeProperty in includeProperties) + { + query = query.Include(includeProperty); + } + return query.FirstOrDefault(); + } + + public virtual IEnumerable GetItems(Expression>? filter = null, + int index = 0, int count = 10, + params string[] includeProperties) + => GetItems(filter, null, index, count, includeProperties); + + public virtual IEnumerable GetItems(Func, IOrderedQueryable>? orderBy = null, + int index = 0, int count = 10, + params string[] includeProperties) + => GetItems(null, orderBy, index, count, includeProperties); + + public virtual IEnumerable GetItems(int index = 0, int count = 10, + params string[] includeProperties) + => GetItems(null, null, index, count, includeProperties); + + public virtual IEnumerable GetItems(Expression>? filter = null, + Func, IOrderedQueryable>? orderBy = null, + int index = 0, int count = 10, + params string[] includeProperties) + { + IQueryable 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(T entity) + { + if (Set.Entry(entity).IsKeySet) + return; + Set.Add(entity); + } + + public virtual void Insert(params T[] entities) + { + foreach (var entity in entities) + { + Insert(entity); + } + } + + public virtual void Delete(object id) + { + T? entity = Set.Find(id); + if (entity == null) return; + Delete(entity); + } + + public virtual void Delete(T entity) + { + if (Context.Entry(entity).State == EntityState.Detached) + { + Set.Attach(entity); + } + Set.Remove(entity); + } + + public virtual void Update(T entity) + { + Set.Attach(entity); + Context.Entry(entity).State = EntityState.Modified; + } + + public virtual int Count() + { + return Set.Count(); + } + + } +} diff --git a/WF_EF_Api/Contextlib/WTFContext.cs b/WF_EF_Api/Contextlib/WTFContext.cs new file mode 100644 index 0000000..af9c12a --- /dev/null +++ b/WF_EF_Api/Contextlib/WTFContext.cs @@ -0,0 +1,97 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Runtime.CompilerServices; +using System.Text; +using System.Threading.Tasks; +using Entity; +using Microsoft.EntityFrameworkCore; + +namespace Contextlib +{ + public class WTFContext : DbContext + { + //public DbSet admins { get; set; } + public DbSet characters { get; set; } + public DbSet comments { get; set; } + public DbSet favorites { get; set; } + public DbSet images { get; set; } + public DbSet question { get; set; } + public DbSet quizzes { get; set; } + //public DbSet quizQuestions { get; set; } + public DbSet quotes { get; set; } + //public DbSet records { get; set; } + public DbSet sources { get; set; } + public DbSet users { get; set; } + public DbSet admins { get; set; } + + protected override void OnModelCreating(ModelBuilder modelBuilder) + { + base.OnModelCreating(modelBuilder); + + modelBuilder.Entity() + .HasMany(q => q.Favorite) + .WithMany(u => u.Favorite) + .UsingEntity( + l => l.HasOne(f => f.Quote) + .WithMany() + .OnDelete(DeleteBehavior.ClientCascade) + .HasForeignKey(f => f.IdQuote), + r => r.HasOne(f => f.Users) + .WithMany() + .OnDelete(DeleteBehavior.ClientCascade) + .HasForeignKey(f => f.IdUsers) + ); + + modelBuilder.Entity() + .HasMany(u => u.Quotes) + .WithOne(q => q.User) + .OnDelete(DeleteBehavior.ClientSetNull) + .HasForeignKey(q => q.IdUsersPropose); + + modelBuilder.Entity() + .HasMany() + .WithMany() + .UsingEntity( + i => i.HasKey(e => e.Id) + ); + + modelBuilder.Entity() + .HasOne(c => c.User) + .WithMany() + .HasForeignKey(c => c.IdUser); + + modelBuilder.Entity() + .HasMany(q => q.Commentarys) + .WithOne(c => c.Quote) + .OnDelete(DeleteBehavior.ClientCascade) + .HasForeignKey(c => c.IdQuote); + + modelBuilder.Entity() + .HasMany(q => q.Questions) + .WithMany(u => u.Quizs) + .UsingEntity( + l => l.HasOne().WithMany().HasForeignKey(q => q.IdQuestion), + r => r.HasOne().WithMany().HasForeignKey(u => u.IdQuiz) + ); + //modelBuilder.Entity() + // .HasOne(a => a.User) + // .WithOne(u => u.admin); + } + + public WTFContext() + { } + + public WTFContext(DbContextOptions options) + : base(options) + { } + + protected override void OnConfiguring(DbContextOptionsBuilder options) + { + if (!options.IsConfigured) + { + options.UseSqlServer(@"Server=(localdb)\mssqllocaldb;Database=Wf-Database.mdf;Trusted_Connection=True;"); + } + } + } +} diff --git a/WF_EF_Api/DTO/CharacterDTO.cs b/WF_EF_Api/DTO/CharacterDTO.cs new file mode 100644 index 0000000..00d402c --- /dev/null +++ b/WF_EF_Api/DTO/CharacterDTO.cs @@ -0,0 +1,15 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace DTO +{ + public class CharacterDTO + { + public int Id { get; set; } + public string Name { get; set; } + public string imagePath { get; set; } + } +} diff --git a/WF_EF_Api/DTO/CommentaryDTO.cs b/WF_EF_Api/DTO/CommentaryDTO.cs new file mode 100644 index 0000000..b901f14 --- /dev/null +++ b/WF_EF_Api/DTO/CommentaryDTO.cs @@ -0,0 +1,17 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace DTO +{ + public class CommentaryDTO + { + public int Id { get; set; } + public string Comment { get; set; } + public DateTime Date { get; set; } + public string User { get; set; } + public string ImagePath { get; set; } + } +} diff --git a/WF_EF_Api/DTO/DTO.csproj b/WF_EF_Api/DTO/DTO.csproj new file mode 100644 index 0000000..99264a0 --- /dev/null +++ b/WF_EF_Api/DTO/DTO.csproj @@ -0,0 +1,16 @@ + + + + net8.0 + enable + enable + + + + + all + runtime; build; native; contentfiles; analyzers; buildtransitive + + + + diff --git a/WF_EF_Api/DTO/FavoriteDTO.cs b/WF_EF_Api/DTO/FavoriteDTO.cs new file mode 100644 index 0000000..16173a4 --- /dev/null +++ b/WF_EF_Api/DTO/FavoriteDTO.cs @@ -0,0 +1,14 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace DTO +{ + public class FavoriteDTO + { + public int IdUser { get; set; } + public int IdQuote { get; set; } + } +} diff --git a/WF_EF_Api/DTO/ImageDTO.cs b/WF_EF_Api/DTO/ImageDTO.cs new file mode 100644 index 0000000..2037793 --- /dev/null +++ b/WF_EF_Api/DTO/ImageDTO.cs @@ -0,0 +1,14 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace DTO +{ + public class ImageDTO + { + public int IdImage { get; set; } + public string ImagePath { get; set; } + } +} diff --git a/WF_EF_Api/DTO/QuestionDTO.cs b/WF_EF_Api/DTO/QuestionDTO.cs new file mode 100644 index 0000000..cdf2fb1 --- /dev/null +++ b/WF_EF_Api/DTO/QuestionDTO.cs @@ -0,0 +1,19 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace DTO +{ + public class QuestionDTO + { + public int Id { get; set; } + public string Question { get; set; } + public string AnswerA { get; set; } + public string AnswerB { get; set; } + public string AnswerC { get; set; } + public string AnswerD { get; set; } + public string CorrectAnswer { get; set; } + } +} diff --git a/WF_EF_Api/DTO/QuizDTO.cs b/WF_EF_Api/DTO/QuizDTO.cs new file mode 100644 index 0000000..abdeb3a --- /dev/null +++ b/WF_EF_Api/DTO/QuizDTO.cs @@ -0,0 +1,16 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace DTO +{ + public class QuizDTO + { + public int Id { get; set; } + public int NbQuestion { get; set; } + public string ImagePath { get; set; } + public string Title { get; set; } + } +} diff --git a/WF_EF_Api/DTO/QuizQuestionDTO.cs b/WF_EF_Api/DTO/QuizQuestionDTO.cs new file mode 100644 index 0000000..fe5cf76 --- /dev/null +++ b/WF_EF_Api/DTO/QuizQuestionDTO.cs @@ -0,0 +1,14 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace DTO +{ + public class QuizQuestionDTO + { + public int IdQuestion { get; set; } + public int IdQuiz { get; set; } + } +} diff --git a/WF_EF_Api/DTO/QuoteDTO.cs b/WF_EF_Api/DTO/QuoteDTO.cs new file mode 100644 index 0000000..a60b283 --- /dev/null +++ b/WF_EF_Api/DTO/QuoteDTO.cs @@ -0,0 +1,22 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace DTO +{ + public class QuoteDTO + { + public int Id { get; set; } + public string Content { get; set; } + public string Character { get; set; } + public string ImagePath { get; set; } + public string TitleSource { get; set; } + public int DateSource { get; set; } + public int Like { get; set; } + public TypeLangageDTO Langage { get; set; } + public TypeSrcEnumDTO Type { get; set; } + public Boolean IsValide { get; set; } + } +} diff --git a/WF_EF_Api/DTO/SourceDTO.cs b/WF_EF_Api/DTO/SourceDTO.cs new file mode 100644 index 0000000..fbb40b7 --- /dev/null +++ b/WF_EF_Api/DTO/SourceDTO.cs @@ -0,0 +1,16 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace DTO +{ + public class SourceDTO + { + public int Id { get; set; } + public string Title { get; set; } + public int Date { get; set; } + public TypeSrcEnumDTO Type { get; set; } + } +} diff --git a/WF_EF_Api/DTO/TypeLangageDTO.cs b/WF_EF_Api/DTO/TypeLangageDTO.cs new file mode 100644 index 0000000..855168f --- /dev/null +++ b/WF_EF_Api/DTO/TypeLangageDTO.cs @@ -0,0 +1,14 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace DTO +{ + public enum TypeLangageDTO + { + vo, + vf + } +} diff --git a/WF_EF_Api/DTO/TypeSrcEnumDTO.cs b/WF_EF_Api/DTO/TypeSrcEnumDTO.cs new file mode 100644 index 0000000..8d5049d --- /dev/null +++ b/WF_EF_Api/DTO/TypeSrcEnumDTO.cs @@ -0,0 +1,16 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace DTO +{ + public enum TypeSrcEnumDTO + { + movie, + serie, + book, + videogame + } +} diff --git a/WF_EF_Api/DTO/UserDTO.cs b/WF_EF_Api/DTO/UserDTO.cs new file mode 100644 index 0000000..a01494b --- /dev/null +++ b/WF_EF_Api/DTO/UserDTO.cs @@ -0,0 +1,12 @@ +namespace DTO +{ + public class UserDTO + { + public int Id { get; set; } + public string Pseudo { get; set; } + public string Password { get; set; } + public string Email { get; set; } + public DateTime date { get; set; } + public string ImageProfil { get; set; } + } +} diff --git a/WF_EF_Api/Dto2Entities/Dto2Entities.csproj b/WF_EF_Api/Dto2Entities/Dto2Entities.csproj new file mode 100644 index 0000000..7455396 --- /dev/null +++ b/WF_EF_Api/Dto2Entities/Dto2Entities.csproj @@ -0,0 +1,21 @@ + + + + net8.0 + enable + enable + + + + + all + runtime; build; native; contentfiles; analyzers; buildtransitive + + + + + + + + + diff --git a/WF_EF_Api/Dto2Entities/Extention.cs b/WF_EF_Api/Dto2Entities/Extention.cs new file mode 100644 index 0000000..fcd8407 --- /dev/null +++ b/WF_EF_Api/Dto2Entities/Extention.cs @@ -0,0 +1,502 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; +using Entity; +using DTO; +using System.Reflection.Metadata; + +namespace Dto2Entities +{ + public static class Extention + { + // --------------------------- ToDto --------------------------- \\ + + public static CharacterDTO ToDto(this Character item) + { + if (item == null) return null; + CharacterDTO character = new CharacterDTO(); + character.Id = item.Id; + character.Name = item.Name; + character.imagePath = item.Images.ImgPath; + return character; + } + + public static List ToDto(this List item) + { + List characterDTOs = new List(); + foreach (Character character in item) + { + characterDTOs.Add(character.ToDto()); + } + return characterDTOs; + } + + public static CommentaryDTO ToDto(this Commentary item) + { + if (item == null) return null; + CommentaryDTO commentary = new CommentaryDTO(); + commentary.Id = item.Id; + commentary.Date = item.DateCommentary; + commentary.Comment = item.Comment; + commentary.User = item.User.UserName; + commentary.ImagePath = item.User.Images.ImgPath; + return commentary; + } + + public static List ToDto(this List item) + { + List commentaryDTOs = new List(); + foreach (Commentary commentary in item) + { + commentaryDTOs.Add(commentary.ToDto()); + } + return commentaryDTOs; + } + + // Surement a refaire car Faoirite Entity modifier sur branche EF + public static FavoriteDTO ToDto(this Favorite item) + { + if (item == null) return null; + FavoriteDTO favorite = new FavoriteDTO(); + favorite.IdUser = item.IdUsers; + favorite.IdQuote = item.IdQuote; + return favorite; + } + + public static List ToDto(this List item) + { + List favoriteDTOs = new List(); + foreach (Favorite favorite in item) + { + favoriteDTOs.Add(favorite.ToDto()); + } + return favoriteDTOs; + } + + public static ImageDTO ToDto(this Images item) + { + if (item == null) return null; + ImageDTO image = new ImageDTO(); + image.IdImage = item.Id; + image.ImagePath = item.ImgPath; + return image; + } + + public static List ToDto(this List item) + { + List imageDTOs = new List(); + foreach (Images images in item) + { + imageDTOs.Add(images.ToDto()); + } + return imageDTOs; + } + + public static QuestionDTO ToDto(this Question item) + { + if (item == null) return null; + QuestionDTO question = new QuestionDTO(); + question.Id = item.Id; + question.Question = item.Text; + question.AnswerA = item.AnswerA; + question.AnswerB = item.AnswerB; + question.AnswerC = item.AnswerC; + question.AnswerD = item.AnswerD; + question.CorrectAnswer = item.CorrectAnswer; + return question; + } + + public static List ToDto(this List item) + { + List questionDTOs = new List(); + foreach (Question question in item) + { + questionDTOs.Add(question.ToDto()); + } + return questionDTOs; + } + + public static QuizDTO ToDto(this Quiz item) + { + if (item == null) return null; + QuizDTO quiz = new QuizDTO(); + quiz.Id = item.Id; + quiz.NbQuestion = item.NbQuestion; + quiz.Title = item.Title; + quiz.ImagePath = item.Images.ImgPath; + return quiz; + } + + public static List ToDto(this List item) + { + List quizDTOs = new List(); + foreach (Quiz quiz in item) + { + quizDTOs.Add(quiz.ToDto()); + } + return quizDTOs; + } + + // Surement a refaire car QuizQuestion Entity modifier sur branche EF + public static QuizQuestionDTO ToDto(this QuizQuestion item) + { + if (item == null) return null; + QuizQuestionDTO quizQuestion = new QuizQuestionDTO(); + quizQuestion.IdQuiz = item.IdQuiz; + quizQuestion.IdQuestion = item.IdQuestion; + return quizQuestion; + } + + public static List ToDto(this List item) + { + List quizQuestionDTOs = new List(); + foreach (QuizQuestion quizQuestion in item) + { + quizQuestionDTOs.Add(quizQuestion.ToDto()); + } + return quizQuestionDTOs; + } + + public static QuoteDTO ToDto(this Quote item) + { + if (item == null) return null; + QuoteDTO quote = new QuoteDTO(); + quote.Id = item.Id; + quote.Content = item.Content; + quote.DateSource = item.Source.Year; + quote.Character = item.Character.Name; + quote.TitleSource = item.Source.Title; + quote.Langage = item.Langage.ToDto(); + quote.ImagePath = item.Character.Images.ImgPath; + quote.Like = item.Likes; + quote.Type = item.Source.TypeSrc.ToDto(); + quote.IsValide = item.IsValid; + return quote; + } + + public static List ToDto(this List item) + { + List quoteDTOs = new List(); + foreach (Quote quote in item) + { + quoteDTOs.Add(quote.ToDto()); + } + return quoteDTOs; + } + + public static SourceDTO ToDto(this Source item) + { + if (item == null) return null; + SourceDTO source = new SourceDTO(); + source.Id = item.Id; + source.Date = item.Year; + source.Title = item.Title; + source.Type = item.TypeSrc.ToDto(); + return source; + } + + public static List ToDto(this List item) + { + List sourceDTOs = new List(); + foreach (Source source in item) + { + sourceDTOs.Add(source.ToDto()); + } + return sourceDTOs; + } + + public static UserDTO ToDto(this Users item) + { + if (item == null) return null; + UserDTO user = new UserDTO(); + user.Id = item.Id; + user.Pseudo = item.UserName; + user.Password = item.Password; + user.Email = item.Email; + user.date = item.Created; + user.ImageProfil = item.Images.ImgPath; + return user; + } + + public static List ToDto(this List item) + { + List users = new List(); + foreach (Users user in item) + { + users.Add(user.ToDto()); + } + return users; + } + + public static TypeLangageDTO ToDto(this LangEnum item) + { + switch (item) + { + case LangEnum.vf: return TypeLangageDTO.vf; + case LangEnum.vo: return TypeLangageDTO.vo; + default: return TypeLangageDTO.vo; + } + } + + public static TypeSrcEnumDTO ToDto(this TypeSrcEnum item) + { + switch (item) + { + case TypeSrcEnum.movie: return TypeSrcEnumDTO.movie; + case TypeSrcEnum.book: return TypeSrcEnumDTO.book; + case TypeSrcEnum.series: return TypeSrcEnumDTO.serie; + case TypeSrcEnum.videogame: return TypeSrcEnumDTO.videogame; + default: return TypeSrcEnumDTO.movie; + } + } + + // --------------------------- ToEntity --------------------------- \\ + + + public static Character ToEntity(this CharacterDTO item) + { + if (item == null) return null; + Character character = new Character(); + character.Id = item.Id; + character.Name = item.Name; + character.Images.ImgPath = item.imagePath ; + return character; + } + + public static List ToEntity(this List item) + { + List characters = new List(); + foreach (CharacterDTO character in item) + { + characters.Add(character.ToEntity()); + } + return characters; + } + + public static Commentary ToEntity(this CommentaryDTO item) + { + if (item == null) return null; + Commentary commentary = new Commentary(); + commentary.Id = item.Id; + commentary.DateCommentary = item.Date; + commentary.Comment = item.Comment; + commentary.User = new Users(); + commentary.User.UserName = item.User; + commentary.User.Images = new Images(); + commentary.User.Images.ImgPath = item.ImagePath; + return commentary; + } + + public static List ToEntity(this List item) + { + List commentarys = new List(); + foreach (CommentaryDTO commentary in item) + { + commentarys.Add(commentary.ToEntity()); + } + return commentarys; + } + + // Surement a refaire car Faoirite Entity modifier sur branche EF + public static Favorite ToEntity(this FavoriteDTO item) + { + if (item == null) return null; + Favorite favorite = new Favorite(); + favorite.IdUsers = item.IdUser; + favorite.IdQuote = item.IdQuote; + return favorite; + } + + public static List ToEntity(this List item) + { + List favorites = new List(); + foreach (FavoriteDTO favorite in item) + { + favorites.Add(favorite.ToEntity()); + } + return favorites; + } + + public static Images ToEntity(this ImageDTO item) + { + if (item == null) return null; + Images image = new Images(); + image.Id = item.IdImage; + image.ImgPath = item.ImagePath; + return image; + } + + public static List ToEntity(this List item) + { + List images = new List(); + foreach (ImageDTO image in item) + { + images.Add(image.ToEntity()); + } + return images; + } + + public static Question ToEntity(this QuestionDTO item) + { + if (item == null) return null; + Question question = new Question(); + question.Id = item.Id; + question.Text = item.Question; + question.AnswerA = item.AnswerA; + question.AnswerB = item.AnswerB; + question.AnswerC = item.AnswerC; + question.AnswerD = item.AnswerD; + question.CorrectAnswer = item.CorrectAnswer; + return question; + } + public static List ToEntity(this List item) + { + List questions = new List(); + foreach (QuestionDTO question in item) + { + questions.Add(question.ToEntity()); + } + return questions; + } + + public static Quiz ToEntity(this QuizDTO item) + { + if (item == null) return null; + Quiz quiz = new Quiz(); + quiz.Id = item.Id; + quiz.NbQuestion = item.NbQuestion; + quiz.Title = item.Title; + quiz.Images.ImgPath = item.ImagePath; + return quiz; + } + + public static List ToEntity(this List item) + { + List quizs = new List(); + foreach (QuizDTO quiz in item) + { + quizs.Add(quiz.ToEntity()); + } + return quizs; + } + + // Surement a refaire car QuizQuestion Entity modifier sur branche EF + public static QuizQuestion ToEntity(this QuizQuestionDTO item) + { + if (item == null) return null; + QuizQuestion quizQuestion = new QuizQuestion(); + quizQuestion.IdQuiz = item.IdQuiz; + quizQuestion.IdQuestion = item.IdQuestion; + return quizQuestion; + } + + public static List ToEntity(this List item) + { + List quizQuestions = new List(); + foreach (QuizQuestionDTO quizQuestion in item) + { + quizQuestions.Add(quizQuestion.ToEntity()); + } + return quizQuestions; + } + + public static Quote ToEntity(this QuoteDTO item) + { + if (item == null) return null; + Quote quote = new Quote(); + quote.Id = item.Id; + quote.Content = item.Content; + quote.Source = new Source(); + quote.Source.Year = item.DateSource; + quote.Character = new Character(); + quote.Character.Name = item.Character; + quote.Source.Title = item.TitleSource; + quote.Langage = item.Langage.ToEntity(); + quote.Character.Images = new Images(); + quote.Character.Images.ImgPath = item.ImagePath; + quote.Likes = item.Like; + quote.Source.TypeSrc = item.Type.ToEntity(); + quote.IsValid = item.IsValide; + return quote; + } + + public static List ToEntity(this List item) + { + List quotes = new List(); + foreach (QuoteDTO quote in item) + { + quotes.Add(quote.ToEntity()); + } + return quotes; + } + + public static Source ToEntity(this SourceDTO item) + { + if (item == null) return null; + Source source = new Source(); + source.Id = item.Id; + source.Year = item.Date; + source.Title = item.Title; + source.TypeSrc = item.Type.ToEntity(); + return source; + } + + public static List ToEntity(this List item) + { + List sources = new List(); + foreach (SourceDTO source in item) + { + sources.Add(source.ToEntity()); + } + return sources; + } + + public static Users ToEntity(this UserDTO item) + { + if (item == null) return null; + Users user = new Users(); + user.Id = item.Id; + user.UserName = item.Pseudo; + user.Password = item.Password; + user.Email = item.Email; + user.Created = item.date; + user.Images = new Images(); + user.Images.ImgPath = item.ImageProfil; + return user; + } + + public static List ToEntity(this List item) + { + List users = new List(); + foreach (UserDTO user in item) + { + users.Add(user.ToEntity()); + } + return users; + } + + public static LangEnum ToEntity(this TypeLangageDTO item) + { + switch (item) + { + case TypeLangageDTO.vf: return LangEnum.vf; + case TypeLangageDTO.vo: return LangEnum.vo; + default: return LangEnum.vo; + } + } + + public static TypeSrcEnum ToEntity(this TypeSrcEnumDTO item) + { + switch (item) + { + case TypeSrcEnumDTO.movie: return TypeSrcEnum.movie; + case TypeSrcEnumDTO.book: return TypeSrcEnum.book; + case TypeSrcEnumDTO.serie: return TypeSrcEnum.series; + case TypeSrcEnumDTO.videogame: return TypeSrcEnum.videogame; + default: return TypeSrcEnum.movie; + } + } + } +} \ No newline at end of file diff --git a/WF_EF_Api/Entity/Admin.cs b/WF_EF_Api/Entity/Admin.cs new file mode 100644 index 0000000..0c62388 --- /dev/null +++ b/WF_EF_Api/Entity/Admin.cs @@ -0,0 +1,19 @@ +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 Entity +{ + public class Admin + { + [Key] + [ForeignKey(nameof(Users))] + public int IdUsers { get; set; } + + public Users User { get; set; } = null!; + } +} diff --git a/WF_EF_Api/Entity/Character.cs b/WF_EF_Api/Entity/Character.cs new file mode 100644 index 0000000..f1ba455 --- /dev/null +++ b/WF_EF_Api/Entity/Character.cs @@ -0,0 +1,28 @@ +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 Entity +{ + public class Character + { + [Key] + [DatabaseGenerated(DatabaseGeneratedOption.Identity)] + public int Id { get; set; } + + [Required] + [StringLength(50)] + public string Name { get; set; } + + [ForeignKey(nameof(Images))] + public int IdImage { get; set; } + + public Images Images { get; set; } = null!; + + public ICollection Quotes { get; set; } = new List(); + } +} diff --git a/WF_EF_Api/Entity/Commentary.cs b/WF_EF_Api/Entity/Commentary.cs new file mode 100644 index 0000000..92b2908 --- /dev/null +++ b/WF_EF_Api/Entity/Commentary.cs @@ -0,0 +1,37 @@ +using System; +using System.Collections.Generic; +using System.ComponentModel.DataAnnotations.Schema; +using System.ComponentModel.DataAnnotations; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace Entity +{ + public class Commentary + { + [Key] + [DatabaseGenerated(DatabaseGeneratedOption.Identity)] + public int Id { get; set; } + + [Required] + [ForeignKey(nameof(Users))] + public int IdUser { get; set; } + + [Required] + [ForeignKey(nameof(Quote))] + public int IdQuote { get; set; } + + [Required] + [Column("DateCommentary", TypeName = "date")] + public DateTime DateCommentary { get; set; } + + [Required] + [MaxLength(100)] + public string Comment { get; set; } + + public Quote Quote { get; set; } = null!; + + public Users User { get; set; } = null!; + } +} diff --git a/WF_EF_Api/Entity/Entity.csproj b/WF_EF_Api/Entity/Entity.csproj new file mode 100644 index 0000000..99264a0 --- /dev/null +++ b/WF_EF_Api/Entity/Entity.csproj @@ -0,0 +1,16 @@ + + + + net8.0 + enable + enable + + + + + all + runtime; build; native; contentfiles; analyzers; buildtransitive + + + + diff --git a/WF_EF_Api/Entity/Favorite.cs b/WF_EF_Api/Entity/Favorite.cs new file mode 100644 index 0000000..06e1185 --- /dev/null +++ b/WF_EF_Api/Entity/Favorite.cs @@ -0,0 +1,21 @@ +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 Entity +{ + public class Favorite + { + public int IdUsers { get; set; } + + public Users Users { get; set; } + + public int IdQuote { get; set; } + + public Quote Quote { get; set; } + } +} diff --git a/WF_EF_Api/Entity/Images.cs b/WF_EF_Api/Entity/Images.cs new file mode 100644 index 0000000..d03b214 --- /dev/null +++ b/WF_EF_Api/Entity/Images.cs @@ -0,0 +1,26 @@ +using System; +using System.Collections.Generic; +using System.ComponentModel.DataAnnotations.Schema; +using System.ComponentModel.DataAnnotations; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace Entity +{ + public class Images + { + [Key] + [DatabaseGenerated(DatabaseGeneratedOption.Identity)] + public int Id { get; set; } + + [Required] + public string ImgPath { get; set; } + + public ICollection Characters { get; set; } = new List(); + + public ICollection Users { get; set; } = new List(); + + public ICollection Quizs { get; set; } = new List(); + } +} diff --git a/WF_EF_Api/Entity/LangEnum.cs b/WF_EF_Api/Entity/LangEnum.cs new file mode 100644 index 0000000..3f8f2a1 --- /dev/null +++ b/WF_EF_Api/Entity/LangEnum.cs @@ -0,0 +1,14 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace Entity +{ + public enum LangEnum + { + vo, + vf + } +} diff --git a/WF_EF_Api/Entity/Question.cs b/WF_EF_Api/Entity/Question.cs new file mode 100644 index 0000000..19c211b --- /dev/null +++ b/WF_EF_Api/Entity/Question.cs @@ -0,0 +1,46 @@ +using System; +using System.Collections.Generic; +using System.ComponentModel.DataAnnotations.Schema; +using System.ComponentModel.DataAnnotations; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace Entity +{ + public class Question + { + [Key] + [DatabaseGenerated(DatabaseGeneratedOption.Identity)] + public int Id { get; set; } + + [Required] + [StringLength(200)] + public string Text { get; set; } + + [Required] + [StringLength(50)] + public string AnswerA { get; set; } + + [Required] + [StringLength(50)] + public string AnswerB { get; set; } + + [Required] + [StringLength(50)] + public string AnswerC { get; set; } + + [Required] + [StringLength(50)] + public string AnswerD { get; set; } + + [Required] + [StringLength(1)] + public string CorrectAnswer { get; set; } + + [Required] + public bool IsValid { get; set; } + + public ICollection Quizs { get; set; } = new List(); + } +} diff --git a/WF_EF_Api/Entity/Quiz.cs b/WF_EF_Api/Entity/Quiz.cs new file mode 100644 index 0000000..27f69ee --- /dev/null +++ b/WF_EF_Api/Entity/Quiz.cs @@ -0,0 +1,32 @@ +using System; +using System.Collections.Generic; +using System.ComponentModel.DataAnnotations.Schema; +using System.ComponentModel.DataAnnotations; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace Entity +{ + public class Quiz + { + [Key] + [DatabaseGenerated(DatabaseGeneratedOption.Identity)] + public int Id { get; set; } + + [Required] + [StringLength(50)] + public string Title { get; set; } + + [Required] + [ForeignKey(nameof(Images))] + public int IdImage { get; set; } + + [Required] + public int NbQuestion { get; set; } + + public Images Images { get; set; } = null!; + + public ICollection Questions { get; } = new List(); + } +} diff --git a/WF_EF_Api/Entity/QuizQuestion.cs b/WF_EF_Api/Entity/QuizQuestion.cs new file mode 100644 index 0000000..5e7086b --- /dev/null +++ b/WF_EF_Api/Entity/QuizQuestion.cs @@ -0,0 +1,17 @@ +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 Entity +{ + public class QuizQuestion + { + public int IdQuiz { get; set; } + + public int IdQuestion { get; set; } + } +} diff --git a/WF_EF_Api/Entity/Quote.cs b/WF_EF_Api/Entity/Quote.cs new file mode 100644 index 0000000..08b148b --- /dev/null +++ b/WF_EF_Api/Entity/Quote.cs @@ -0,0 +1,53 @@ +using System; +using System.Collections.Generic; +using System.ComponentModel.DataAnnotations.Schema; +using System.ComponentModel.DataAnnotations; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace Entity +{ + public class Quote + { + [Key] + [DatabaseGenerated(DatabaseGeneratedOption.Identity)] + public int Id { get; set; } + + [Required] + [StringLength(100)] + public string Content { get; set; } + + [Required] + public int Likes { get; set; } + + [Required] + public LangEnum Langage { get; set; } + + [Required] + public bool IsValid { get; set; } + + [Required] + [ForeignKey(nameof(Character))] + public int IdCharacter { get; set; } + + [Required] + [ForeignKey(nameof(Source))] + public int IdSource { get; set; } + + [ForeignKey(nameof(Users))] + public int? IdUsersPropose { get; set; } + //Réson de pour quoi j'ai mis le user en nullable et mis .OnDelete(DeleteBehavior.ClientSetNull) dans WTFContext + //https://learn.microsoft.com/fr-fr/ef/core/saving/cascade-delete + //Les suppressions en cascade sont nécessaires quand une entité dépendante/enfant ne peut plus être associée à son entité principale/parente actuelle. Cela peut se produire à la suite de la suppression de l’entité principale/parente, ou quand l’entité principale/parente existe toujours mais que l’entité dépendante/enfant ne lui est plus associée. + public Users? User { get; set; } = null!; + + public Source Source { get; set; } = null!; + + public Character Character { get; set; } = null!; + + public ICollection Commentarys { get; set; } = new List(); + + public ICollection Favorite { get; } = new List(); + } +} diff --git a/WF_EF_Api/Entity/Source.cs b/WF_EF_Api/Entity/Source.cs new file mode 100644 index 0000000..60cda07 --- /dev/null +++ b/WF_EF_Api/Entity/Source.cs @@ -0,0 +1,29 @@ +using System; +using System.Collections.Generic; +using System.ComponentModel.DataAnnotations.Schema; +using System.ComponentModel.DataAnnotations; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace Entity +{ + public class Source + { + [Key] + [DatabaseGenerated(DatabaseGeneratedOption.Identity)] + public int Id { get; set; } + + [Required] + [StringLength(100)] + public string Title { get; set; } + + [Required] + public int Year { get; set; } + + [Required] + public TypeSrcEnum TypeSrc { get; set; } + + public ICollection Quotes { get; set; } = new List(); + } +} diff --git a/WF_EF_Api/Entity/TypeSrcEnum.cs b/WF_EF_Api/Entity/TypeSrcEnum.cs new file mode 100644 index 0000000..b5aa4e1 --- /dev/null +++ b/WF_EF_Api/Entity/TypeSrcEnum.cs @@ -0,0 +1,16 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace Entity +{ + public enum TypeSrcEnum + { + movie, + series, + book, + videogame + } +} diff --git a/WF_EF_Api/Entity/Users.cs b/WF_EF_Api/Entity/Users.cs new file mode 100644 index 0000000..abcf80e --- /dev/null +++ b/WF_EF_Api/Entity/Users.cs @@ -0,0 +1,47 @@ +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 Entity +{ + public class Users + { + [Key] + [DatabaseGenerated(DatabaseGeneratedOption.Identity)] + public int Id { get; set; } + + [Required] + [StringLength(50)] + public string UserName { get; set; } + + [Required] + [StringLength(50)] + public string Email { get; set; } + + [Required] + [StringLength(200)] + public string Password { get; set; } + + [ForeignKey(nameof(Images))] + public int IdImage { get; set; } + + [Required] + [Column("Created", TypeName = "date")] + public DateTime Created { get; set; } + + public Images Images { get; set; } + + public ICollection Quotes { get; set; } = new List(); + + public ICollection Favorite { get; set; } = new List(); + + + //[ForeignKey(nameof(Admin))] + //public int Idadmin { get; set; } + //public Admin admin { get; set; } + } +} diff --git a/WF_EF_Api/Model/Model.csproj b/WF_EF_Api/Model/Model.csproj new file mode 100644 index 0000000..bb23fb7 --- /dev/null +++ b/WF_EF_Api/Model/Model.csproj @@ -0,0 +1,9 @@ + + + + net8.0 + enable + enable + + + diff --git a/WF_EF_Api/Model2entities/Class1.cs b/WF_EF_Api/Model2entities/Class1.cs new file mode 100644 index 0000000..7214afa --- /dev/null +++ b/WF_EF_Api/Model2entities/Class1.cs @@ -0,0 +1,7 @@ +namespace Model2entities +{ + public class Class1 + { + + } +} diff --git a/WF_EF_Api/Model2entities/Model2Entities.csproj b/WF_EF_Api/Model2entities/Model2Entities.csproj new file mode 100644 index 0000000..bb23fb7 --- /dev/null +++ b/WF_EF_Api/Model2entities/Model2Entities.csproj @@ -0,0 +1,9 @@ + + + + net8.0 + enable + enable + + + diff --git a/WF_EF_Api/ServicesApi/CharacterService.cs b/WF_EF_Api/ServicesApi/CharacterService.cs new file mode 100644 index 0000000..399586a --- /dev/null +++ b/WF_EF_Api/ServicesApi/CharacterService.cs @@ -0,0 +1,59 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; +using DTO; +using Entity; +using Shared; +using Dto2Entities; + +namespace ServicesApi +{ + public class CharacterService : ICharacterService + { + private ICharacterService characterService; + + public CharacterService(ICharacterService character) + { + characterService = character; + } + + + public async Task AddCharacter(CharacterDTO character) + { + await characterService.AddCharacter(character.ToEntity()); + } + + public async Task> GetAll() + { + var characters = characterService.GetAll().Result.items; + return new PaginationResult(characters.Count(), 0, 10, characters.ToDto()); + } + + public async Task GetCharById(int id) + { + return characterService.GetCharById(id).Result.ToDto(); + } + + public async Task GetCharByName(string name) + { + return characterService.GetCharByName(name).Result.ToDto(); + } + + public async Task GetLastCharId() + { + return await characterService.GetLastCharId(); + } + + public async Task RemoveCharacter(int id) + { + await characterService.RemoveCharacter(id); + } + + public async Task UpdateCharacter(int id, CharacterDTO character) + { + await characterService.UpdateCharacter(id, character.ToEntity()); + } + } +} diff --git a/WF_EF_Api/ServicesApi/CommentaryService.cs b/WF_EF_Api/ServicesApi/CommentaryService.cs new file mode 100644 index 0000000..4758ba6 --- /dev/null +++ b/WF_EF_Api/ServicesApi/CommentaryService.cs @@ -0,0 +1,82 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; +using DTO; +using Entity; +using Shared; +using Dto2Entities; + +namespace ServicesApi +{ + public class CommentaryService : ICommentaryService + { + private ICommentaryService commentaryService; + + public CommentaryService(ICommentaryService commentary) + { + commentaryService = commentary; + } + + public async Task AddComment(CommentaryDTO commentary, int idQuote) + { + await commentaryService.AddComment(commentary.ToEntity(), idQuote); + } + + public async Task DeleteCommentaryForQuote(int quoteId) + { + await commentaryService.DeleteCommentaryForQuote(quoteId); + } + + public async Task DeleteCommentaryForUser(int userId) + { + await commentaryService.DeleteCommentaryForUser(userId); + } + + public async Task> GetAllCommentary() + { + var commentaries = commentaryService.GetAllCommentary().Result.items; + return new PaginationResult(commentaries.Count(), 0, 10, commentaries.ToDto()); + } + + public async Task GetCommentaryById(int id) + { + try + { + return (await commentaryService.GetCommentaryById(id)).ToDto(); + } + catch(KeyNotFoundException) + { + throw new KeyNotFoundException($"No comments found with the given ID: {id}."); + } + } + + public async Task> GetCommentaryByQuote(int quoteId, int index, int pageSize) + { + var commentaries = commentaryService.GetCommentaryByQuote(quoteId,index,pageSize).Result.items; + return new PaginationResult(commentaries.Count(), 0, 10, commentaries.ToDto()); + } + + public async Task> GetCommentaryByUser(int userId, int index, int pageSize) + { + var commentaries = commentaryService.GetCommentaryByUser(userId, index,pageSize).Result.items; + return new PaginationResult(commentaries.Count(), 0, 10, commentaries.ToDto()); + } + + public async Task LastCommentaryId() + { + return await commentaryService.LastCommentaryId(); + } + + public async Task RemoveCommentary(int id) + { + await commentaryService.RemoveCommentary(id); + } + + public async Task UpdateCommentary(int id, CommentaryDTO commentary) + { + await commentaryService.UpdateCommentary(id,commentary.ToEntity()); + } + } +} diff --git a/WF_EF_Api/ServicesApi/FavoriteService.cs b/WF_EF_Api/ServicesApi/FavoriteService.cs new file mode 100644 index 0000000..b68d082 --- /dev/null +++ b/WF_EF_Api/ServicesApi/FavoriteService.cs @@ -0,0 +1,58 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; +using DTO; +using Entity; +using Shared; +using Dto2Entities; +using static System.Net.Mime.MediaTypeNames; +using static System.Runtime.InteropServices.JavaScript.JSType; + +namespace ServicesApi +{ + public class FavoriteService : IFavoriteService + { + + private IFavoriteService favoriteService; + + public FavoriteService(IFavoriteService favorite) + { + favoriteService = favorite; + } + + + public async Task AddFavorite(int quoteid, int userId) + { + await favoriteService.AddFavorite(quoteid, userId); + } + + public async Task RemoveAllFavoriteForQuote(int quoteId) + { + await favoriteService.RemoveAllFavoriteForQuote(quoteId); + } + + public async Task RemoveAllFavoriteForUser(int userId) + { + await favoriteService.RemoveAllFavoriteForUser(userId); + } + + public async Task RemoveFavorite(int quoteid, int userId) + { + await favoriteService.RemoveFavorite(quoteid, userId); + } + + public async Task GetFavorite(int userId, int idQuote) + { + return (await favoriteService.GetFavorite(userId,idQuote) ).ToDto(); + } + + public async Task> GetFavoriteByIdUser(int userId, int index, int count) + { + var fav = (await favoriteService.GetFavoriteByIdUser(userId, index, count)).items; + return new PaginationResult(fav.Count(), 0, 10, fav.ToDto()); + + } + } +} diff --git a/WF_EF_Api/ServicesApi/ImageService.cs b/WF_EF_Api/ServicesApi/ImageService.cs new file mode 100644 index 0000000..caefb31 --- /dev/null +++ b/WF_EF_Api/ServicesApi/ImageService.cs @@ -0,0 +1,59 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; +using DTO; +using Entity; +using Shared; +using Dto2Entities; + +namespace ServicesApi +{ + public class ImageService : IImagesService + { + private IImagesService imageService; + + public ImageService(IImagesService image) + { + imageService = image; + } + + public async Task AddImage(ImageDTO image) + { + await imageService.AddImage(image.ToEntity()); + } + + public async Task> GetAllImage() + { + var images = imageService.GetAllImage().Result.items; + return new PaginationResult(images.Count(), 0, 10, images.ToDto()); + } + + public async Task GetImageById(int id) + { + return imageService.GetImageById(id).Result.ToDto(); + } + + public async Task GetLastImageId() + { + return await imageService.GetLastImageId(); + } + + public async Task> GetSomeImage(int index, int pageSize) + { + var images = imageService.GetSomeImage(index,pageSize).Result.items; + return new PaginationResult(images.Count(), 0, 10, images.ToDto()); + } + + public async Task RemoveImage(int id) + { + await imageService.RemoveImage(id); + } + + public async Task UpdateImage(int id, ImageDTO image) + { + await imageService.UpdateImage(id, image.ToEntity()); + } + } +} diff --git a/WF_EF_Api/ServicesApi/QuestionService.cs b/WF_EF_Api/ServicesApi/QuestionService.cs new file mode 100644 index 0000000..4d71308 --- /dev/null +++ b/WF_EF_Api/ServicesApi/QuestionService.cs @@ -0,0 +1,89 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; +using DTO; +using Entity; +using Shared; +using Dto2Entities; +using static System.Net.Mime.MediaTypeNames; +using Microsoft.EntityFrameworkCore.Metadata.Internal; + +namespace ServicesApi +{ + public class QuestionService : IQuestionService + { + private IQuestionService questionService; + + public QuestionService(IQuestionService question) + { + questionService = question; + } + + + + public async Task AddQuestion(QuestionDTO question) + { + await questionService.AddQuestion(question.ToEntity()); + } + + public async Task CountQuestions() + { + return await questionService.CountQuestions(); + } + + public async Task> GetAllQuestion() + { + var questions = questionService.GetAllQuestion().Result.items; + return new PaginationResult(questions.Count(), 0, 10, questions.ToDto()); + } + + public async Task> GetInvalidQuestion(int index, int pageSize) + { + var questions = questionService.GetInvalidQuestion(index,pageSize).Result.items; + return new PaginationResult(questions.Count(), 0, 10, questions.ToDto()); + } + + public async Task GetQuestionById(int id) + { + return questionService.GetQuestionById(id).Result.ToDto(); + } + + public async Task GetRandomQuestion() + { + return questionService.GetRandomQuestion().Result.ToDto(); + } + + public async Task GetRandomQuestionQuoteToCharacter() + { + return questionService.GetRandomQuestionQuoteToCharacter().Result.ToDto(); + } + + public async Task GetRandomQuestionQuoteToSource() + { + return questionService.GetRandomQuestionQuoteToSource().Result.ToDto(); + } + + public async Task> GetSomeQuestion(int index, int pageSize) + { + var questions = questionService.GetSomeQuestion(index, pageSize).Result.items; + return new PaginationResult(questions.Count(), 0, 10, questions.ToDto()); + } + + public async Task RemoveQuestion(int id) + { + await questionService.RemoveQuestion(id); + } + + public async Task UpdateQuestion(int id, QuestionDTO question) + { + await questionService.UpdateQuestion(id, question.ToEntity()); + } + + public async Task ValidateQuestion(int id, bool isvalid) + { + await questionService.ValidateQuestion(id, isvalid); + } + } +} diff --git a/WF_EF_Api/ServicesApi/QuoteService.cs b/WF_EF_Api/ServicesApi/QuoteService.cs new file mode 100644 index 0000000..7538781 --- /dev/null +++ b/WF_EF_Api/ServicesApi/QuoteService.cs @@ -0,0 +1,126 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Reflection.Metadata; +using System.Text; +using System.Threading.Tasks; +using DTO; +using Dto2Entities; +using Entity; +using Shared; + +namespace ServicesApi +{ + public class QuoteService : IQuoteService + { + private IQuoteService quoteService; + + public QuoteService(IQuoteService quote) + { + quoteService = quote; + } + + public async Task AddQuote(QuoteDTO quote) + { + return (await quoteService.AddQuote(quote.ToEntity())).ToDto(); + } + + public async Task> GetAllQuote() + { + var quotes = quoteService.GetAllQuote().Result.items; + return new PaginationResult(quotes.Count(), 0, 10, quotes.ToDto()); + } + + public async Task> GetAllQuoteLang(int index, int pageSize, int lang) + { + var quotes = quoteService.GetAllQuoteLang(index, pageSize,lang).Result.items; + return new PaginationResult(quotes.Count(), 0, 10, quotes.ToDto()); + } + + public async Task GetDailyQuote(DateOnly date, int lang) + { + return quoteService.GetDailyQuote(date, lang).Result.ToDto(); + } + + public async Task> GetFavorites(int index, int pageSize, int UserId) + { + var quotes = quoteService.GetFavorites(index, pageSize, UserId).Result.items; + return new PaginationResult(quotes.Count(), 0, 10, quotes.ToDto()); + } + + public async Task> GetInvalidQuote(int index, int pageSize, int lang) + { + var quotes = quoteService.GetInvalidQuote(index, pageSize, lang).Result.items; + return new PaginationResult(quotes.Count(), 0, 10, quotes.ToDto()); + } + + public async Task> GetInvalidQuote(int index, int pageSize) + { + var quotes = quoteService.GetInvalidQuote(index, pageSize).Result.items; + return new PaginationResult(quotes.Count(), 0, 10, quotes.ToDto()); + } + + public async Task GetLastQuoteId() + { + return await quoteService.GetLastQuoteId(); + } + + public async Task GetQuoteById(int id) + { + var quote= quoteService.GetQuoteById(id).Result; + if (quote != null) return quote.ToDto(); + else return null; + } + + public async Task> GetSomeQuote(int index, int pageSize) + { + var quotes = quoteService.GetSomeQuote(index, pageSize).Result.items; + return new PaginationResult(quotes.Count(), 0, 10, quotes.ToDto()); + } + + public async Task> GetSuggestions(int index, int pageSize, int lang) + { + var quotes = quoteService.GetSuggestions(index, pageSize, lang).Result.items; + return new PaginationResult(quotes.Count(), 0, 10, quotes.ToDto()); + } + + public async Task> GetValidQuote(int index, int pageSize) + { + var quotes = quoteService.GetValidQuote(index, pageSize).Result.items; + return new PaginationResult(quotes.Count(), 0, 10, quotes.ToDto()); + } + + public async Task RemoveQuote(int quoteId) + { + await quoteService.RemoveQuote(quoteId); + } + + public async Task> SearchByCharacter(string character, int index, int pageSize, int lang) + { + var quotes = quoteService.SearchByCharacter(character, index, pageSize, lang).Result.items; + return new PaginationResult(quotes.Count(), 0, 10, quotes.ToDto()); + } + + public async Task> SearchByContent(string content, int index, int pageSize, int lang) + { + var quotes = quoteService.SearchByContent(content, index, pageSize, lang).Result.items; + return new PaginationResult(quotes.Count(), 0, 10, quotes.ToDto()); + } + + public async Task> SearchBySource(string source, int index, int pageSize, int lang) + { + var quotes = quoteService.SearchBySource(source, index, pageSize, lang).Result.items; + return new PaginationResult(quotes.Count(), 0, 10, quotes.ToDto()); + } + + public async Task UpdateQuote(int quoteId, QuoteDTO quote) + { + await quoteService.UpdateQuote(quoteId, quote.ToEntity()); + } + + public async Task ValidateQuote(int quoteId, bool isValidate) + { + await quoteService.ValidateQuote(quoteId, isValidate); + } + } +} diff --git a/WF_EF_Api/ServicesApi/ServicesApi.csproj b/WF_EF_Api/ServicesApi/ServicesApi.csproj new file mode 100644 index 0000000..074190e --- /dev/null +++ b/WF_EF_Api/ServicesApi/ServicesApi.csproj @@ -0,0 +1,23 @@ + + + + net8.0 + enable + enable + + + + + all + runtime; build; native; contentfiles; analyzers; buildtransitive + + + + + + + + + + + diff --git a/WF_EF_Api/ServicesApi/SourceService.cs b/WF_EF_Api/ServicesApi/SourceService.cs new file mode 100644 index 0000000..acefbcc --- /dev/null +++ b/WF_EF_Api/ServicesApi/SourceService.cs @@ -0,0 +1,76 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; +using DTO; +using Entity; +using Shared; +using Dto2Entities; +using static System.Net.Mime.MediaTypeNames; +using static System.Runtime.InteropServices.JavaScript.JSType; + +namespace ServicesApi +{ + public class SourceService : ISourceService + { + private ISourceService srcService; + + public SourceService(ISourceService src) + { + srcService = src; + } + public async Task AddSource(SourceDTO source) + { + await srcService.AddSource(source.ToEntity()); + } + + public async Task> GetAll() + { + var sources = srcService.GetAll().Result.items; + return new PaginationResult(sources.Count(), 0, 10, sources.ToDto()); + } + + public async Task GetLastSourceId() + { + return await srcService.GetLastSourceId(); + } + + public async Task> GetSomesSource(int page, int count) + { + var sources = (await srcService.GetSomesSource(page, count)).items; + return new PaginationResult(sources.Count(), page, count, sources.ToDto()); + } + + public async Task> GetSourceByDate(int date) + { + var sources = (await srcService.GetSourceByDate(date)).items; + return new PaginationResult(sources.Count(), 0, 10, sources.ToDto()); + } + + public async Task GetSourceById(int id) + { + return (await srcService.GetSourceById(id)).ToDto(); + } + + public async Task GetSourceByTitle(string title) + { + return srcService.GetSourceByTitle(title).Result.ToDto(); + } + + public async Task GetSourceByType(int type) + { + return srcService.GetSourceByType(type).Result.ToDto(); + } + + public async Task RemoveSource(int id) + { + await srcService.RemoveSource(id); + } + + public async Task UpdateSource(int id, SourceDTO source) + { + await srcService.UpdateSource(id, source.ToEntity()); + } + } +} diff --git a/WF_EF_Api/ServicesApi/UserService.cs b/WF_EF_Api/ServicesApi/UserService.cs new file mode 100644 index 0000000..3a5cc02 --- /dev/null +++ b/WF_EF_Api/ServicesApi/UserService.cs @@ -0,0 +1,100 @@ +using Shared; +using DTO; +using Contextlib; +using Entity; +using System.Xml.XPath; +using Dto2Entities; +namespace ServicesApi +{ + public class UserService : IUserService + { + + private IUserService userService; + + public UserService(IUserService user) + { + userService = user; + } + + + + public async Task AddUser(UserDTO user) + { + await userService.AddUser(user.ToEntity()); + } + + public async Task CountUser() + { + return await userService.CountUser(); + } + + public async Task ExistEmail(string email) + { + return await userService.ExistEmail(email); + } + + public async Task ExistUsername(string username) + { + return await userService.ExistUsername(username); + } + + public async Task> GetAllUser() + { + var users = userService.GetAllUser().Result.items; + return new PaginationResult(users.Count(), 0, 10, users.ToDto()); + } + + public async Task GetHashPassword(string username) + { + return await userService.GetHashPassword(username); + } + + public async Task GetLastUserId() + { + return await userService.GetLastUserId(); + } + + public async Task> GetSomeUser(int index, int pageSize) + { + var users = userService.GetSomeUser(index, pageSize).Result.items; + return new PaginationResult(users.Count(),index, pageSize, users.ToDto()); + } + + public async Task GetUserByEmail(string email) + { + return userService.GetUserByEmail(email).Result.ToDto(); + } + + public async Task GetUserById(int id) + { + try + { + return (await userService.GetUserById(id)).ToDto(); + } + catch(KeyNotFoundException e) + { + throw new KeyNotFoundException(e.Message); + } + } + + public async Task GetUserByUsername(string username) + { + return userService.GetUserByUsername(username).Result.ToDto(); + } + + public async Task RemoveUser(int id) + { + await userService.RemoveUser(id); + } + + public async Task SetAdminRole(bool isAdmin) + { + await userService.SetAdminRole(isAdmin); + } + + public async Task UpdateUser(int userId, UserDTO user) + { + return userService.UpdateUser(userId, user.ToEntity()).Result.ToDto(); + } + } +} diff --git a/WF_EF_Api/Shared/ICharacterService.cs b/WF_EF_Api/Shared/ICharacterService.cs new file mode 100644 index 0000000..a1c1a57 --- /dev/null +++ b/WF_EF_Api/Shared/ICharacterService.cs @@ -0,0 +1,39 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace Shared +{ + public interface ICharacterService + { + // Retrieves a character by its unique identifier (id). + // 'id' is the unique identifier of the character. + Task GetCharById(int id); + + // Retrieves a character by its name. + // 'name' is the name of the character to be retrieved. + Task GetCharByName(string name); + + // Retrieves all characters, with pagination support. + // This returns a list of all characters in the system. + Task> GetAll(); + + // Adds a new character to the system. + // 'character' is the character object that will be added to the system. + Task AddCharacter(TChar character); + + // Updates an existing character identified by its unique identifier ('id'). + // 'id' is the unique identifier of the character to be updated + // 'character' contains the updated character data. + Task UpdateCharacter(int id, TChar character); + + // Removes a character from the system based on its unique identifier ('id'). + // 'id' is the unique identifier of the character to be removed. + Task RemoveCharacter(int id); + + // Retrieves the unique identifier of the last added character. + Task GetLastCharId(); + } +} diff --git a/WF_EF_Api/Shared/IComentaryService.cs b/WF_EF_Api/Shared/IComentaryService.cs new file mode 100644 index 0000000..3808b6d --- /dev/null +++ b/WF_EF_Api/Shared/IComentaryService.cs @@ -0,0 +1,54 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace Shared +{ + public interface ICommentaryService + { + // Retrieves a comment by its unique identifier (id). + // 'id' is the unique identifier of the comment. + Task GetCommentaryById(int id); + + // Retrieves comments related to a specific quote, with pagination. + // 'quoteId' is the unique identifier of the quote. + // 'index' is the page number (for pagination). + // 'pageSize' is the number of comments per page. + Task> GetCommentaryByQuote(int quoteId, int index, int pageSize); + + // Retrieves all comments, with pagination support. + // This returns a list of all comments. + Task> GetAllCommentary(); + + // Retrieves comments made by a specific user, with pagination. + // 'userId' is the unique identifier of the user. + // 'index' is the page number (for pagination). + // 'pageSize' is the number of comments per page. + Task> GetCommentaryByUser(int userId, int index, int pageSize); + + // Adds a new commenT. + // 'comment' is the comment object that will be added. + Task AddComment(TComment commentary, int idQuote); + + // Updates an existing comment identified by 'id'. + // 'id' is the unique identifier of the comment, and 'comment' contains the updated comment data. + Task UpdateCommentary(int id, TComment comment); + + // Removes a comment based on its unique identifier ('id'). + // 'id' is the unique identifier of the comment to be removed. + Task RemoveCommentary(int id); + + // Deletes all comments related to a specific quote. + // 'quoteId' is the unique identifier of the quote for which comments will be deleted. + Task DeleteCommentaryForQuote(int quoteId); + + // Deletes all comments made by a specific user. + // 'userId' is the unique identifier of the user whose comments will be deleted. + Task DeleteCommentaryForUser(int userId); + + // Retrieves the last comment ID. + Task LastCommentaryId(); + } +} diff --git a/WF_EF_Api/Shared/IFavoriteService.cs b/WF_EF_Api/Shared/IFavoriteService.cs new file mode 100644 index 0000000..08a32de --- /dev/null +++ b/WF_EF_Api/Shared/IFavoriteService.cs @@ -0,0 +1,33 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Reflection; +using System.Text; +using System.Threading.Tasks; + +namespace Shared +{ + public interface IFavoriteService + { + // Adds a quote to a user's list of favorites. + // 'quoteid' is the unique identifier of the quote to be added to favorites. + // 'userId' is the unique identifier of the user who is adding the quote to their favorites. + Task AddFavorite(int quoteid, int userId); + + // Removes a quote from a user's list of favorites. + // 'quoteid' is the unique identifier of the quote to be removed from favorites. + // 'userId' is the unique identifier of the user who is removing the quote from their favorites. + Task RemoveFavorite(int quoteid, int userId); + + // Removes all favorite quotes for a specific user. + // 'userId' is the unique identifier of the user whose favorites will be removed. + Task RemoveAllFavoriteForUser(int userId); + + // Removes a specific quote from the favorite lists of all users. + // 'quoteId' is the unique identifier of the quote to be removed from all users' favorites. + Task RemoveAllFavoriteForQuote(int quoteId); + + Task> GetFavoriteByIdUser(int userId, int index, int count); + Task GetFavorite(int userId, int idQuote); + } +} diff --git a/WF_EF_Api/Shared/IImagesService.cs b/WF_EF_Api/Shared/IImagesService.cs new file mode 100644 index 0000000..0bc6bf0 --- /dev/null +++ b/WF_EF_Api/Shared/IImagesService.cs @@ -0,0 +1,39 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace Shared +{ + public interface IImagesService + { + // Retrieves an image by its unique identifier (id). + // 'id' is the unique identifier of the image. + Task GetImageById(int id); + + // Retrieves all images, with pagination support. + // This returns a list of all images in the system. + Task> GetAllImage(); + + // Retrieves a subset of images based on the provided index and page size. + // 'index' is the starting point for pagination (page number). + // 'pageSize' is the number of images per page. + Task> GetSomeImage(int index, int pageSize); + + // Adds a new image to the system. + // 'image' is the image object that will be added to the system. + Task AddImage(TImage image); + + // Updates an existing image identified by its unique identifier ('id'). + // 'id' is the unique identifier of the image to be updated, and 'image' contains the updated image data. + Task UpdateImage(int id, TImage image); + + // Removes an image from the system based on its unique identifier ('id'). + // 'id' is the unique identifier of the image to be removed from the system. + Task RemoveImage(int id); + + // Retrieves the last Image ID. + Task GetLastImageId(); + } +} diff --git a/WF_EF_Api/Shared/IQuestionService.cs b/WF_EF_Api/Shared/IQuestionService.cs new file mode 100644 index 0000000..73b8f0d --- /dev/null +++ b/WF_EF_Api/Shared/IQuestionService.cs @@ -0,0 +1,59 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace Shared +{ + public interface IQuestionService + { + // Retrieves all questions, with pagination support. + // This returns a list of all questions in the system. + Task> GetAllQuestion(); + + // Retrieves a subset of questions based on the provided index and page size. + // 'index' is the starting point for pagination (page number). + // 'pageSize' is the number of questions per page. + Task> GetSomeQuestion(int index, int pageSize); + + // Retrieves questions that are marked as invalid, with pagination support. + // 'index' is the starting page (page number) + // 'pageSize' is the number of questions per page. + Task> GetInvalidQuestion(int index, int pageSize); + + // Retrieves a specific question by its unique identifier (id). + // 'id' is the unique identifier of the question. + Task GetQuestionById(int id); + + // Retrieves a random question from the system. + Task GetRandomQuestion(); + + // Adds a new question to the system. + // 'question' is the question object that will be added. + Task AddQuestion(TQuestion question); + + // Updates an existing question identified by 'id'. + // 'id' is the unique identifier of the question + // 'question' contains the new question data. + Task UpdateQuestion(int id, TQuestion question); + + // Removes a question from the system based on its unique identifier ('id'). + // 'id' is the unique identifier of the question to be removed. + Task RemoveQuestion(int id); + + // Retrieves the total count of questions in the system. + Task CountQuestions(); + + // Validates or invalidates a question based on its unique identifier ('id'). + // 'id' is the unique identifier of the question + // 'isvalid' is a boolean indicating whether the question is valid. + Task ValidateQuestion(int id, bool isvalid); + + // Retrieves a random question from a quote to a character. + Task GetRandomQuestionQuoteToCharacter(); + + // Retrieves a random question from a quote to a source. + Task GetRandomQuestionQuoteToSource(); + } +} diff --git a/WF_EF_Api/Shared/IQuizService.cs b/WF_EF_Api/Shared/IQuizService.cs new file mode 100644 index 0000000..e0735b2 --- /dev/null +++ b/WF_EF_Api/Shared/IQuizService.cs @@ -0,0 +1,41 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace Shared +{ + public interface IQuizService + { + // Retrieves a specific quiz by its unique identifier (id). + // 'id' is the unique identifier of the quiz to be retrieved. + Task GetQuizById(int id); + + // Retrieves all quizzes, with pagination support. + // This returns a list of all quizzes in the system. + Task> GetAllQuiz(); + + // Retrieves a subset of quizzes based on the provided index and page size. + // 'index' is the starting point for pagination (page number). + // 'pageSize' is the number of quizzes per page. + Task> GetSomeQuiz(int index, int pageSize); + + // Adds a new quiz to the system. + // 'quiz' is the quiz object that will be added to the system. + Task AddQuiz(TQuiz quiz); + + // Updates an existing quiz identified by its unique identifier ('quizId'). + // 'quizId' is the unique identifier of the quiz to be updated + // 'quiz' contains the updated quiz data. + Task UpdateQiz(int quizId, TQuiz quiz); + + // Removes a quiz from the system based on its unique identifier ('quizId'). + // 'quizId' is the unique identifier of the quiz to be removed from the system. + Task RemoveQuiz(int quizId); + + // Retrieves the number of questions in a specific quiz identified by its unique identifier ('quizId'). + // 'quizId' is the unique identifier of the quiz for which the number of questions is requested. + Task GetNbQuestionQuiz(int quizId); + } +} diff --git a/WF_EF_Api/Shared/IQuoteService.cs b/WF_EF_Api/Shared/IQuoteService.cs new file mode 100644 index 0000000..4632463 --- /dev/null +++ b/WF_EF_Api/Shared/IQuoteService.cs @@ -0,0 +1,97 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace Shared +{ + public interface IQuoteService + { + // Retrieves the daily quote in a specified language. + // 'lang' is a language code. + Task GetDailyQuote(DateOnly date, int lang); + + // Retrieves a specific quote by its unique identifier (id). + Task GetQuoteById(int id); + + // Retrieves all available quotes in the system, without any filters. + Task> GetAllQuote(); + + // Retrieves a page of some availble quote based on the index (pagination) + // 'index' is the starting point for pagination + // 'pageSize' determines the number of quotes per page + Task> GetSomeQuote(int index, int pageSize); + + // Retrieves all available quotes but filtered by language. + // 'lang' is a language code used to filter the quotes in the chosen language. + Task> GetAllQuoteLang(int index, int pageSize, int lang); + + // Retrieves all inavailable quotes but filtered by language. + // 'lang' is a language code used to filter the quotes in the chosen language. + Task> GetInvalidQuote(int index, int pageSize, int lang); + // Retrieves a page of quote suggestions based on the index (pagination) and language. + // 'index' is the starting point for pagination + // 'pageSize' determines the number of quotes per page + // 'lang' specifies the language for the suggestions. + Task> GetSuggestions(int index, int pageSize, int lang); + + // Retrieves the favorite quotes of a specific user. + // 'index' is the starting point for pagination + // 'pageSize' determines the number of quotes per page + // 'UserId' is the identifier of the user to fetch their favorite quotes. + Task> GetFavorites(int index, int pageSize, int UserId); + + // Retrieves a page of valid quotes with pagination. + // 'index' is the current page + // 'pageSize' is the number of quotes per page. + Task> GetValidQuote(int index, int pageSize); + + // Retrieves a page of invalid quotes with pagination. + // 'index' is the current page + // 'pageSize' is the number of quotes per page. + Task> GetInvalidQuote(int index, int pageSize); + + + // Searches for quotes based on content (text of the quote), with pagination and filtering by language. + // 'content' is the text of the quote + // 'index' is the current page + // 'pageSize' is the number of results per page + // 'lang' is the language code to filter the results. + Task> SearchByContent(string content, int index, int pageSize, int lang); + + // Searches for quotes by their source, with pagination and filtering by language. + // 'source' is the source of the quote + // 'index' is the current page + // 'pageSize' is the number of results per page + // 'lang' is the language code to filter the results. + Task> SearchBySource(string source, int index, int pageSize, int lang); + + // Searches for quotes related to a specific character, with pagination and filtering by language. + // 'character' refers to a name or role in the content + // 'index' is the current page + // 'pageSize' is the number of results per page, + // 'lang' is the language code to filter the results. + Task> SearchByCharacter(string character, int index, int pageSize, int lang); + + // Adds a new quote. + // 'quote' is the quote object that will be added. + Task AddQuote(TQuote quote); + + // Updates an existing quote identified by 'quoteId' with new details. + // 'quoteId' is the ID of the quote to be updated + // 'quote' contains the new data. + Task UpdateQuote(int quoteId, TQuote quote); + + // Removes a quote based on its unique identifier ('quoteId'). + Task RemoveQuote(int quoteId); + + // Retrieves the last ID. + Task GetLastQuoteId(); + + // Validates or invalidates a quote based on the 'quoteId' and a boolean value ('isValidate'). + // If 'isValidate' is true, the quote is marked as valid; if false, it is invalid. + Task ValidateQuote(int quoteId, bool isValidate); + + } +} diff --git a/WF_EF_Api/Shared/ISourceService.cs b/WF_EF_Api/Shared/ISourceService.cs new file mode 100644 index 0000000..73fd2c6 --- /dev/null +++ b/WF_EF_Api/Shared/ISourceService.cs @@ -0,0 +1,48 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace Shared +{ + public interface ISourceService + { + // Retrieves a source by its unique identifier (id). + // 'id' is the unique identifier of the source. + Task GetSourceById(int id); + + // Retrieves a source by its title. + // 'title' is the title of the source to be retrieved. + Task GetSourceByTitle(string title); + + // Retrieves a source by its date. + // 'date' is the date associated with the source to be retrieved. + Task> GetSourceByDate(int date); + // Retrieves a source by its type. + // 'type' is the type of the source to be retrieved. + Task GetSourceByType(int type); + + // Retrieves all sources, with pagination support. + // This returns a list of all sources in the system. + Task> GetAll(); + + // Adds a new source to the system. + // 'source' is the source object that will be added. + Task AddSource(TSource source); + + // Updates an existing source identified by its unique identifier ('id'). + // 'id' is the unique identifier of the source to be updated + // 'source' contains the updated source data. + Task UpdateSource(int id, TSource source); + + // Removes a source from the system based on its unique identifier ('id'). + // 'id' is the unique identifier of the source to be removed. + Task RemoveSource(int id); + + // Retrieves the unique identifier of the last added source. + Task GetLastSourceId(); + + Task> GetSomesSource(int page, int count); + } +} diff --git a/WF_EF_Api/Shared/IUserService.cs b/WF_EF_Api/Shared/IUserService.cs new file mode 100644 index 0000000..e55135a --- /dev/null +++ b/WF_EF_Api/Shared/IUserService.cs @@ -0,0 +1,67 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace Shared +{ + public interface IUserService + { + // Retrieves a user by their unique identifier (id). + // 'id' is the unique identifier of the user. + Task GetUserById(int id); + + // Retrieves a user by their username. + // 'username' is the username of the user to be retrieved. + Task GetUserByUsername(string username); + + // Retrieves a user by their email address. + // 'email' is the email address of the user to be retrieved. + Task GetUserByEmail(string email); + + // Retrieves all users. + // This returns a list of users with pagination information (e.g., total count, page size). + Task> GetAllUser(); + + // Retrieves a subset of users based on the provided index and page size. + // 'index' is the starting point for pagination (page number). + // 'pageSize' is the number of users per page. + Task> GetSomeUser(int index, int pageSize); + + // Adds a new user to the system. + // 'user' is the user object that will be added to the system. + Task AddUser(TUser user); + + // Updates the details of an existing user identified by 'userId'. + // 'userId' is the ID of the user to be updated, and 'user' contains the new user data. + Task UpdateUser(int userId, TUser user); + + // Removes a user from the system based on their unique identifier ('userId'). + // 'userId' is the unique identifier of the user to be removed. + Task RemoveUser(int id); + + // Retrieves the hashed password for a given username. + // 'username' is the username for which the password hash is to be retrieved. + Task GetHashPassword(string username); + + + // Checks if a username already exists. + // 'username' is the username to check for existence. + Task ExistUsername(string username); + + // Checks if an email address already exists. + // 'email' is the email address to check for existence. + Task ExistEmail(string email); + + // Sets the admin role for a user. + // 'isAdmin' is a boolean indicating whether the user should have admin privileges. + Task SetAdminRole(bool isAdmin); + + // Retrieves the total count of users. + Task CountUser(); + + // Retrieves the last user ID. + Task GetLastUserId(); + } +} diff --git a/WF_EF_Api/Shared/Mapper.cs b/WF_EF_Api/Shared/Mapper.cs new file mode 100644 index 0000000..890c8d3 --- /dev/null +++ b/WF_EF_Api/Shared/Mapper.cs @@ -0,0 +1,47 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace Shared +{ + public class Mapper where T : class + where U : class + { + readonly HashSet> mapper = new HashSet>(); + + public bool AddMapping(T t, U u) + { + var mapping = new Tuple(t, u); + if (mapper.Contains(mapping)) return false; + mapper.Add(mapping); + return true; + } + + public T? GetT(U u) + { + var result = mapper.Where(tuple => ReferenceEquals(tuple.Item2, u)); + if (result.Count() != 1) + { + return null; + } + return result.First().Item1; + } + + public U? GetU(T t) + { + var result = mapper.Where(tuple => ReferenceEquals(tuple.Item1, t)); + if (result.Count() != 1) + { + return null; + } + return result.First().Item2; + } + + public void Reset() + { + mapper.Clear(); + } + } +} diff --git a/WF_EF_Api/Shared/PaginationResult.cs b/WF_EF_Api/Shared/PaginationResult.cs new file mode 100644 index 0000000..5347d3e --- /dev/null +++ b/WF_EF_Api/Shared/PaginationResult.cs @@ -0,0 +1,33 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +// Represents a paginated result set for a collection of items. +public class PaginationResult +{ + // Total number in the item List. + public int totalCount { get; set; } + + // The current page index (starting from 0). + public int pageIndex { get; set; } + + // The number of items displayed per page. + public int countPerPage { get; set; } + + // The list of items for the current page. + public List items { get; set; } + + // Constructor to initialize a new instance of the PaginationResult class. + // 'totalCount' is the total number of items, 'pageIndex' is the current page, + // 'countPerPage' is the number of items per page, and 'items' is the list of items for the current page. + public PaginationResult(int totalCount, int pageIndex, int countPerPage, List items) + { + this.totalCount = totalCount; // Sets the total number of items available. + this.pageIndex = pageIndex; // Sets the current page index (starting from 1). + this.countPerPage = countPerPage; // Sets the number of items per page. + this.items = items; // Sets the items for the current page. + } +} + diff --git a/WF_EF_Api/Shared/Shared.csproj b/WF_EF_Api/Shared/Shared.csproj new file mode 100644 index 0000000..99264a0 --- /dev/null +++ b/WF_EF_Api/Shared/Shared.csproj @@ -0,0 +1,16 @@ + + + + net8.0 + enable + enable + + + + + all + runtime; build; native; contentfiles; analyzers; buildtransitive + + + + diff --git a/WF_EF_Api/StubApi/QuoteServiceStub.cs b/WF_EF_Api/StubApi/QuoteServiceStub.cs new file mode 100644 index 0000000..f06a6e1 --- /dev/null +++ b/WF_EF_Api/StubApi/QuoteServiceStub.cs @@ -0,0 +1,153 @@ +using DTO; +using Shared; +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace StubApi +{ + public class QuoteServiceStub : IQuoteService + { + private readonly List _quotes; + + public QuoteServiceStub() + { + _quotes = new List + { + new QuoteDTO{Id=0, Content="Que la force soit avec toi", Character="Obi-Wan", ImagePath="http://image1", TitleSource="Star Wars", DateSource=1977, Like=32, Langage=TypeLangageDTO.vo, Type=TypeSrcEnumDTO.movie,IsValide=true}, + new QuoteDTO{Id=1, Content="Je suis ton père", Character="Darth Vader", ImagePath="http://image2", TitleSource="Star Wars", DateSource=1980, Like=120, Langage=TypeLangageDTO.vo, Type=TypeSrcEnumDTO.movie,IsValide=true}, + new QuoteDTO{Id=2, Content="Que la vengeance commence", Character="Anakin Skywalker", ImagePath="http://image3", TitleSource="Star Wars: Episode III", DateSource=2005, Like=95, Langage=TypeLangageDTO.vo, Type=TypeSrcEnumDTO.movie,IsValide=true}, + new QuoteDTO{Id=3, Content="J'adore l'odeur du napalm au matin", Character="Kilgore", ImagePath="http://image4", TitleSource="Apocalypse Now", DateSource=1979, Like=56, Langage=TypeLangageDTO.vo, Type=TypeSrcEnumDTO.movie,IsValide=true}, + new QuoteDTO{Id=4, Content="Je suis Groot", Character="Groot", ImagePath="http://image5", TitleSource="Guardians of the Galaxy", DateSource=2014, Like=200, Langage=TypeLangageDTO.vo, Type=TypeSrcEnumDTO.movie,IsValide=true}, + new QuoteDTO{Id=5, Content="La vie est un rêve", Character="Don Quichotte", ImagePath="http://image6", TitleSource="Don Quichotte", DateSource=1605, Like=34, Langage=TypeLangageDTO.vf, Type=TypeSrcEnumDTO.book,IsValide=true}, + new QuoteDTO{Id=6, Content="To infinity and beyond!", Character="Buzz Lightyear", ImagePath="http://image7", TitleSource="Toy Story", DateSource=1995, Like=180, Langage=TypeLangageDTO.vo, Type=TypeSrcEnumDTO.movie,IsValide=true}, + new QuoteDTO{Id=7, Content="Je ne suis pas un héros", Character="Bruce Wayne", ImagePath="http://image8", TitleSource="The Dark Knight", DateSource=2008, Like=250, Langage=TypeLangageDTO.vo, Type=TypeSrcEnumDTO.movie,IsValide=true}, + new QuoteDTO{Id=8, Content="Je suis le maître du jeu", Character="Jigsaw", ImagePath="http://image9", TitleSource="Saw", DateSource=2004, Like=65, Langage=TypeLangageDTO.vo, Type=TypeSrcEnumDTO.movie,IsValide=true}, + new QuoteDTO{Id=9, Content="Liberté, égalité, fraternité", Character="La devise de la France", ImagePath="http://image10", TitleSource="Révolution française", DateSource=1789, Like=300, Langage=TypeLangageDTO.vf, Type=TypeSrcEnumDTO.book,IsValide=true}, + new QuoteDTO{Id=10, Content="Un petit pas pour l'homme, un grand pas pour l'humanité", Character="Neil Armstrong", ImagePath="http://image11", TitleSource="Moon landing", DateSource=1969, Like=500, Langage=TypeLangageDTO.vo, Type=TypeSrcEnumDTO.book,IsValide=true}, + new QuoteDTO{Id=11, Content="C'est la vie", Character="Charles", ImagePath="http://image12", TitleSource="French Movie", DateSource=2013, Like=45, Langage=TypeLangageDTO.vf, Type=TypeSrcEnumDTO.movie,IsValide=true}, + new QuoteDTO{Id=12, Content="Voici Johnny!", Character="Jack Torrance", ImagePath="http://image13", TitleSource="The Shining", DateSource=1980, Like=300, Langage=TypeLangageDTO.vo, Type=TypeSrcEnumDTO.movie,IsValide=true}, + new QuoteDTO{Id=13, Content="Je suis un simple serveur", Character="Hannibal", ImagePath="http://image14", TitleSource="The Silence of the Lambs", DateSource=1991, Like=200, Langage=TypeLangageDTO.vo, Type=TypeSrcEnumDTO.movie,IsValide=true}, + new QuoteDTO{Id=14, Content="N'attends pas le moment parfait, prends le moment et rends-le parfait", Character="Zig Ziglar", ImagePath="http://image15", TitleSource="Motivation", DateSource=1995, Like=150, Langage=TypeLangageDTO.vf, Type=TypeSrcEnumDTO.book,IsValide=true}, + new QuoteDTO{Id=15, Content="Le seul vrai voyage est de changer de regard", Character="Marcel Proust", ImagePath="http://image16", TitleSource="À la recherche du temps perdu", DateSource=1913, Like=125, Langage=TypeLangageDTO.vf, Type=TypeSrcEnumDTO.book,IsValide=true}, + new QuoteDTO{Id=16, Content="La force sera avec toi, toujours", Character="Obi-Wan Kenobi", ImagePath="http://image17", TitleSource="Star Wars: Episode IV", DateSource=1977, Like=320, Langage=TypeLangageDTO.vo, Type=TypeSrcEnumDTO.movie,IsValide=true}, + new QuoteDTO{Id=17, Content="J'ai toujours rêvé d'être un gangster", Character="Henry Hill", ImagePath="http://image18", TitleSource="Goodfellas", DateSource=1990, Like=500, Langage=TypeLangageDTO.vo, Type=TypeSrcEnumDTO.movie,IsValide=true}, + new QuoteDTO{Id=18, Content="Je vous ai compris", Character="De Gaulle", ImagePath="http://image19", TitleSource="Discours de Gaulle", DateSource=1958, Like=250, Langage=TypeLangageDTO.vf, Type=TypeSrcEnumDTO.book,IsValide=true}, + new QuoteDTO{Id=19, Content="Courage, fuyons!", Character="Frédéric", ImagePath="http://image20", TitleSource="Le Pourceau", DateSource=1834, Like=75, Langage=TypeLangageDTO.vf, Type=TypeSrcEnumDTO.book,IsValide=false} + }; + } + + public async Task AddQuote(QuoteDTO quote) + { + _quotes.Add(quote); + return quote; + } + + public async Task> GetAllQuote() + { + return new PaginationResult(_quotes.Where(q=>q.IsValide == true).ToList().Count, + 0, + _quotes.Count, + _quotes.Where(q => q.IsValide == true).ToList()); + } + + public async Task> GetAllQuoteLang(int index, int pageSize, int lang) + { + TypeLangageDTO langageType = (TypeLangageDTO)lang; + + return new PaginationResult(_quotes.Where(q => q.IsValide = true).ToList().Count, + index, + pageSize, + _quotes.Where(q => q.IsValide == true && q.Langage == langageType ).ToList().Skip(index * pageSize).Take(pageSize).ToList() + ); + + } + + public async Task GetDailyQuote(DateOnly date, int lang) + { + int nb = _quotes.Where(q => q.Langage == (TypeLangageDTO)lang && q.IsValide == true).Count(); + return _quotes.Where(q => q.Langage == (TypeLangageDTO)lang && q.IsValide == true).ToList().Find(q => q.Id == date.DayNumber%nb) ?? _quotes.Where(q => q.Langage == (TypeLangageDTO)lang && q.IsValide == true).First(); + } + + public async Task> GetFavorites(int index, int pageSize, int UserId) + { + throw new NotImplementedException(); + } + + public async Task> GetInvalidQuote(int index, int pageSize) + { + throw new NotImplementedException(); + } + + public async Task GetLastQuoteId() // JE VOIS PAS L'INTERET + { + throw new NotImplementedException(); + } + + public async Task GetQuoteById(int id) + { + return _quotes.FirstOrDefault(q => q.Id == id); + } + + public async Task> GetSomeQuote(int index, int pageSize) + { + return new PaginationResult(_quotes.Where(q => q.IsValide = true).ToList().Count, + index, + pageSize, + _quotes.Where(q => q.IsValide = true).ToList().Skip(index * pageSize).Take(pageSize).ToList() + ); + } + + public async Task> GetSuggestions(int index, int pageSize, int lang) + { + throw new NotImplementedException(); + } + + public async Task> GetValidQuote(int index, int pageSize) + { + throw new NotImplementedException(); + } + + public async Task RemoveQuote(int quoteId) + { + _quotes.Remove( GetQuoteById(quoteId).Result ); + } + + public async Task> SearchByCharacter(string character, int index, int pageSize, int lang) + { + throw new NotImplementedException(); + } + + public async Task> SearchByContent(string content, int index, int pageSize, int lang) + { + throw new NotImplementedException(); + } + + public async Task> SearchBySource(string source, int index, int pageSize, int lang) + { + throw new NotImplementedException(); + } + + public async Task UpdateQuote(int quoteId, QuoteDTO quote) + { + throw new NotImplementedException(); + } + + public async Task ValidateQuote(int quoteId, bool isValidate) + { + throw new NotImplementedException(); + } + public async Task> GetInvalidQuote(int index, int pageSize, int lang) + { + TypeLangageDTO langageType = (TypeLangageDTO)lang; + + return new PaginationResult(_quotes.Where(q => q.IsValide == false && q.Langage == langageType).ToList().Count, + index, + pageSize, + _quotes.Where(q => q.IsValide == false && q.Langage == langageType).ToList().Skip(index * pageSize).Take(pageSize).ToList() + ); + } + } +} diff --git a/WF_EF_Api/StubApi/StubApi.csproj b/WF_EF_Api/StubApi/StubApi.csproj new file mode 100644 index 0000000..2df8a10 --- /dev/null +++ b/WF_EF_Api/StubApi/StubApi.csproj @@ -0,0 +1,21 @@ + + + + net8.0 + enable + enable + + + + + all + runtime; build; native; contentfiles; analyzers; buildtransitive + + + + + + + + + diff --git a/WF_EF_Api/StubApi/UserServiceStub.cs b/WF_EF_Api/StubApi/UserServiceStub.cs new file mode 100644 index 0000000..71fb7f0 --- /dev/null +++ b/WF_EF_Api/StubApi/UserServiceStub.cs @@ -0,0 +1,123 @@ +using Shared; +using DTO; +namespace StubApi +{ + public class UserServiceStub : IUserService + { + private readonly List _users; + + public UserServiceStub() + { + _users = new List + { + new UserDTO { Id = 1, Pseudo = "dev", Password = "1234", Email = "testeur@example.com", date = new DateTime(2025,1,1), ImageProfil = "https://image_profil_1" }, + new UserDTO { Id = 2, Pseudo = "admin", Password = "admin123", Email = "admin@example.com", date = new DateTime(2025,1,1), ImageProfil = "https://image_profil_2" }, + new UserDTO { Id = 3, Pseudo = "user123", Password = "password123", Email = "user123@example.com", date = new DateTime(2022,1,1), ImageProfil = "https://image_profil_3" }, + new UserDTO { Id = 4, Pseudo = "testuser", Password = "testpass", Email = "testuser@example.com", date = new DateTime(2024,1,1), ImageProfil = "https://image_profil_4" }, + new UserDTO { Id = 5, Pseudo = "johnDoe", Password = "john123", Email = "johndoe@example.com", date = new DateTime(2021,1,1), ImageProfil = "https://image_profil_5" }, + new UserDTO { Id = 6, Pseudo = "janedoe", Password = "jane123", Email = "janedoe@example.com", date = new DateTime(2023,1,1), ImageProfil = "https://image_profil_6" }, + new UserDTO { Id = 7, Pseudo = "mark_smith", Password = "mark1234", Email = "marks@example.com", date = new DateTime(2022,1,1), ImageProfil = "https://image_profil_7" }, + new UserDTO { Id = 8, Pseudo = "alice", Password = "alicepass", Email = "alice@example.com", date = new DateTime(2025,1,1), ImageProfil = "https://image_profil_8" }, + new UserDTO { Id = 9, Pseudo = "bob_lee", Password = "bob123", Email = "bob@example.com", date = new DateTime(2021,1,1), ImageProfil = "https://image_profil_9" }, + new UserDTO { Id = 10, Pseudo = "lucas", Password = "lucaspass", Email = "lucas@example.com", date = new DateTime(2023,1,1), ImageProfil = "https://image_profil_10" }, + new UserDTO { Id = 11, Pseudo = "emily", Password = "emily2024", Email = "emily@example.com", date = new DateTime(2022,1,1), ImageProfil = "https://image_profil_11" }, + new UserDTO { Id = 12, Pseudo = "chris", Password = "chris1234", Email = "chris@example.com", date = new DateTime(2025,1,1), ImageProfil = "https://image_profil_12" }, + new UserDTO { Id = 13, Pseudo = "susan", Password = "susan123", Email = "susan@example.com", date = new DateTime(2023,1,1), ImageProfil = "https://image_profil_13" }, + new UserDTO { Id = 14, Pseudo = "michael", Password = "michael2025", Email = "michael@example.com", date = new DateTime(2022,1,1), ImageProfil = "https://image_profil_14" }, + new UserDTO { Id = 15, Pseudo = "olivia", Password = "olivia2024", Email = "olivia@example.com", date = new DateTime(2025,1,1), ImageProfil = "https://image_profil_15" }, + new UserDTO { Id = 16, Pseudo = "david", Password = "david123", Email = "david@example.com", date = new DateTime(2021,1,1), ImageProfil = "https://image_profil_16" }, + new UserDTO { Id = 17, Pseudo = "laura", Password = "laura456", Email = "laura@example.com", date = new DateTime(2023,1,1), ImageProfil = "https://image_profil_17" }, + new UserDTO { Id = 18, Pseudo = "steve", Password = "steve789", Email = "steve@example.com", date = new DateTime(2022,1,1), ImageProfil = "https://image_profil_18" }, + new UserDTO { Id = 19, Pseudo = "tina", Password = "tina321", Email = "tina@example.com", date = new DateTime(2025,1,1), ImageProfil = "https://image_profil_19" }, + new UserDTO { Id = 20, Pseudo = "peter", Password = "peter123", Email = "peter@example.com", date = new DateTime(2024,1,1), ImageProfil = "https://image_profil_20" } + + }; + } + + public async Task AddUser(UserDTO user) + { + _users.Add(user); + } + + public async Task CountUser() + { + return _users.Count; + } + + public async Task ExistEmail(string email) + { + if (_users.FirstOrDefault(u => u.Email == email) == null) return false; + return true; + } + + public async Task ExistUsername(string username) + { + if (_users.FirstOrDefault(u => u.Pseudo == username) == null) return false; + return true; + } + + public async Task> GetAllUser() + { + return new PaginationResult(_users.Count,0,_users.Count, _users); + } + + public async Task GetHashPassword(string username) + { + return _users.FirstOrDefault(u => u.Pseudo == username).Password; + } + + public async Task GetLastUserId() // JE VOIS PAS L'INTERET + { + throw new NotImplementedException(); + } + + public async Task> GetSomeUser(int index, int pageSize) + { + return new PaginationResult(_users.Count, index, pageSize, _users.Skip(index* pageSize).Take(pageSize).ToList()); + } + + public async Task GetUserByEmail(string email) + { + return _users.FirstOrDefault(u => u.Email == email); + } + + public async Task GetUserById(int id) + { + return _users.FirstOrDefault(u => u.Id == id); + } + + + public async Task GetUserByUsername(string username) + { + return _users.FirstOrDefault(u => u.Pseudo == username); + } + + public async Task RemoveUser(int id) + { + var user = await GetUserById(id); + _users.Remove(user); + } + + public async Task SetAdminRole(bool isAdmin) + { + throw new NotImplementedException(); + } + + + + public async Task UpdateUser(int userId, UserDTO user) + { + UserDTO userUpdate = new UserDTO(); + userUpdate = GetUserById(userId).Result; + + // Update users properties + userUpdate.Pseudo = user.Pseudo; + userUpdate.Password = user.Password; + userUpdate.Email = user.Email; + userUpdate.date = user.date; + userUpdate.ImageProfil = user.ImageProfil; + + return userUpdate; + } + } +} diff --git a/WF_EF_Api/StubbedContextLib/Migrations/20250402113707_pm_api.Designer.cs b/WF_EF_Api/StubbedContextLib/Migrations/20250402113707_pm_api.Designer.cs new file mode 100644 index 0000000..c1cc023 --- /dev/null +++ b/WF_EF_Api/StubbedContextLib/Migrations/20250402113707_pm_api.Designer.cs @@ -0,0 +1,1074 @@ +// +using System; +using Microsoft.EntityFrameworkCore; +using Microsoft.EntityFrameworkCore.Infrastructure; +using Microsoft.EntityFrameworkCore.Metadata; +using Microsoft.EntityFrameworkCore.Migrations; +using Microsoft.EntityFrameworkCore.Storage.ValueConversion; +using StubbedContextLib; + +#nullable disable + +namespace StubbedContextLib.Migrations +{ + [DbContext(typeof(StubWTFContext))] + [Migration("20250402113707_pm_api")] + partial class pm_api + { + /// + protected override void BuildTargetModel(ModelBuilder modelBuilder) + { +#pragma warning disable 612, 618 + modelBuilder + .HasAnnotation("ProductVersion", "9.0.3") + .HasAnnotation("Relational:MaxIdentifierLength", 128); + + SqlServerModelBuilderExtensions.UseIdentityColumns(modelBuilder); + + modelBuilder.Entity("Entity.Admin", b => + { + b.Property("IdUsers") + .ValueGeneratedOnAdd() + .HasColumnType("int"); + + SqlServerPropertyBuilderExtensions.UseIdentityColumn(b.Property("IdUsers")); + + b.Property("UserId") + .HasColumnType("int"); + + b.HasKey("IdUsers"); + + b.HasIndex("UserId"); + + b.ToTable("admins"); + }); + + modelBuilder.Entity("Entity.Character", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("int"); + + SqlServerPropertyBuilderExtensions.UseIdentityColumn(b.Property("Id")); + + b.Property("IdImage") + .HasColumnType("int"); + + b.Property("Name") + .IsRequired() + .HasMaxLength(50) + .HasColumnType("nvarchar(50)"); + + b.HasKey("Id"); + + b.HasIndex("IdImage"); + + b.ToTable("characters"); + + b.HasData( + new + { + Id = 1, + IdImage = 1, + Name = "Alan Grant" + }, + new + { + Id = 2, + IdImage = 2, + Name = "Aragorn" + }, + new + { + Id = 3, + IdImage = 3, + Name = "Legolas" + }, + new + { + Id = 4, + IdImage = 4, + Name = "Frodon" + }, + new + { + Id = 5, + IdImage = 5, + Name = "Dobby" + }, + new + { + Id = 6, + IdImage = 6, + Name = "Jon Snow" + }, + new + { + Id = 7, + IdImage = 7, + Name = "Daenerys Targaryen" + }, + new + { + Id = 8, + IdImage = 8, + Name = "Luke Skywalker" + }, + new + { + Id = 9, + IdImage = 9, + Name = "Princess Leia" + }, + new + { + Id = 10, + IdImage = 10, + Name = "Harry Potter" + }); + }); + + modelBuilder.Entity("Entity.Commentary", b => + { + b.Property("IdUser") + .HasColumnType("int"); + + b.Property("IdQuote") + .HasColumnType("int"); + + b.Property("Comment") + .IsRequired() + .HasMaxLength(100) + .HasColumnType("nvarchar(100)"); + + b.Property("DateCommentary") + .HasColumnType("date") + .HasColumnName("DateCommentary"); + + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("int"); + + SqlServerPropertyBuilderExtensions.UseIdentityColumn(b.Property("Id")); + + b.HasKey("IdUser", "IdQuote"); + + b.HasIndex("IdQuote"); + + b.ToTable("comments"); + + b.HasData( + new + { + IdUser = 2, + IdQuote = 1, + Comment = "Ce film est le meilleur", + DateCommentary = new DateTime(2025, 2, 3, 0, 0, 0, 0, DateTimeKind.Unspecified), + Id = 1 + }, + new + { + IdUser = 3, + IdQuote = 1, + Comment = "Very good", + DateCommentary = new DateTime(2025, 3, 11, 0, 0, 0, 0, DateTimeKind.Unspecified), + Id = 2 + }); + }); + + modelBuilder.Entity("Entity.Favorite", b => + { + b.Property("IdQuote") + .HasColumnType("int"); + + b.Property("IdUsers") + .HasColumnType("int"); + + b.HasKey("IdQuote", "IdUsers"); + + b.HasIndex("IdUsers"); + + b.ToTable("favorites"); + + b.HasData( + new + { + IdQuote = 2, + IdUsers = 8 + }, + new + { + IdQuote = 5, + IdUsers = 3 + }, + new + { + IdQuote = 9, + IdUsers = 1 + }, + new + { + IdQuote = 4, + IdUsers = 10 + }, + new + { + IdQuote = 3, + IdUsers = 2 + }, + new + { + IdQuote = 6, + IdUsers = 7 + }, + new + { + IdQuote = 1, + IdUsers = 6 + }, + new + { + IdQuote = 8, + IdUsers = 9 + }, + new + { + IdQuote = 10, + IdUsers = 5 + }); + }); + + modelBuilder.Entity("Entity.Images", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("int"); + + SqlServerPropertyBuilderExtensions.UseIdentityColumn(b.Property("Id")); + + b.Property("ImgPath") + .IsRequired() + .HasColumnType("nvarchar(max)"); + + b.HasKey("Id"); + + b.ToTable("images"); + + b.HasData( + new + { + Id = 1, + ImgPath = "https://th.bing.com/th/id/OIP.TJuWNCsibz8MVmhdNQEdMwHaE8?w=244&h=180&c=7&r=0&o=5&pid=1.7" + }, + new + { + Id = 2, + ImgPath = "https://th.bing.com/th/id/OIP.NgXRQ5-IknA6_qOPFhLWIwHaHK?w=165&h=180&c=7&r=0&o=5&pid=1.7" + }, + new + { + Id = 3, + ImgPath = "https://th.bing.com/th/id/OIP.XcJoJ6bC9sAMjol1pJn5UQHaLH?w=118&h=180&c=7&r=0&o=5&pid=1.7" + }, + new + { + Id = 4, + ImgPath = "https://th.bing.com/th/id/OIP.PPIESqZaNDa-qUcfSDXhdQHaGK?w=210&h=180&c=7&r=0&o=5&pid=1.7" + }, + new + { + Id = 5, + ImgPath = "https://th.bing.com/th/id/OIP.XBghSl2kfRNNtQoSxc901wHaHa?w=177&h=180&c=7&r=0&o=5&pid=1.7" + }, + new + { + Id = 6, + ImgPath = "https://th.bing.com/th/id/OIP.af1Aid64cqEKoIOBgCPxtQHaJO?w=145&h=182&c=7&r=0&o=5&pid=1.7" + }, + new + { + Id = 7, + ImgPath = "https://th.bing.com/th/id/OIP.ri5vSXr5lNTLt4DO6KQXyQHaI4?w=158&h=189&c=7&r=0&o=5&pid=1.7" + }, + new + { + Id = 8, + ImgPath = "https://th.bing.com/th/id/OIP.uPTRLR8uspCiafiunUqKfQHaMJ?w=115&h=180&c=7&r=0&o=5&pid=1.7" + }, + new + { + Id = 9, + ImgPath = "https://th.bing.com/th/id/OIP.hcJis4rKbyQtugsoFJU2ngHaM_?w=118&h=207&c=7&r=0&o=5&pid=1.7" + }, + new + { + Id = 10, + ImgPath = "https://th.bing.com/th/id/OIP.Py1_XfUrKJY_A6tYEmFS5wHaE8?w=280&h=187&c=7&r=0&o=5&pid=1.7" + }); + }); + + modelBuilder.Entity("Entity.Question", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("int"); + + SqlServerPropertyBuilderExtensions.UseIdentityColumn(b.Property("Id")); + + b.Property("AnswerA") + .IsRequired() + .HasMaxLength(50) + .HasColumnType("nvarchar(50)"); + + b.Property("AnswerB") + .IsRequired() + .HasMaxLength(50) + .HasColumnType("nvarchar(50)"); + + b.Property("AnswerC") + .IsRequired() + .HasMaxLength(50) + .HasColumnType("nvarchar(50)"); + + b.Property("AnswerD") + .IsRequired() + .HasMaxLength(50) + .HasColumnType("nvarchar(50)"); + + b.Property("CorrectAnswer") + .IsRequired() + .HasMaxLength(1) + .HasColumnType("nvarchar(1)"); + + b.Property("IsValid") + .HasColumnType("bit"); + + b.Property("Text") + .IsRequired() + .HasMaxLength(200) + .HasColumnType("nvarchar(200)"); + + b.HasKey("Id"); + + b.ToTable("question"); + + b.HasData( + new + { + Id = 1, + AnswerA = "Gimli", + AnswerB = "Aragorn", + AnswerC = "Frodon", + AnswerD = "Gandalf", + CorrectAnswer = "B", + IsValid = true, + Text = "Qui est le leader de la Communauté de l'Anneau ?" + }, + new + { + Id = 2, + AnswerA = "Serdaigle", + AnswerB = "Gryffondor", + AnswerC = "Serpentard", + AnswerD = "Poufsouffle", + CorrectAnswer = "B", + IsValid = false, + Text = "Dans quelle maison Harry Potter est-il ?" + }, + new + { + Id = 3, + AnswerA = "Saroumane", + AnswerB = "Sauron", + AnswerC = "Gollum", + AnswerD = "Gothmog", + CorrectAnswer = "B", + IsValid = true, + Text = "Qui est le Seigneur des Ténèbres dans la saga Le Seigneur des Anneaux ?" + }, + new + { + Id = 4, + AnswerA = "Han Solo", + AnswerB = "Princesse Leia", + AnswerC = "Chewbacca", + AnswerD = "R2-D2", + CorrectAnswer = "A", + IsValid = true, + Text = "Dans le film Star Wars : Episode IV, qui sauve Luke Skywalker de l'Étoile de la Mort ?" + }, + new + { + Id = 5, + AnswerA = "Reine Jadis", + AnswerB = "Aslan", + AnswerC = "Edmund", + AnswerD = "Lucy", + CorrectAnswer = "B", + IsValid = true, + Text = "Qui est le souverain de Narnia dans Le Lion, la Sorcière Blanche et l'Armoire Magique ?" + }, + new + { + Id = 6, + AnswerA = "Smaug", + AnswerB = "Falkor", + AnswerC = "Norbert", + AnswerD = "Shenron", + CorrectAnswer = "A", + IsValid = true, + Text = "Quel est le nom du dragon dans Le Hobbit ?" + }, + new + { + Id = 7, + AnswerA = "Bella Swan", + AnswerB = "Edward Cullen", + AnswerC = "Jacob Black", + AnswerD = "Victoria", + CorrectAnswer = "A", + IsValid = true, + Text = "Qui est la première personne à être mordue par un vampire dans Twilight ?" + }, + new + { + Id = 8, + AnswerA = "Obi-Wan Kenobi", + AnswerB = "Yoda", + AnswerC = "Han Solo", + AnswerD = "Luke Skywalker", + CorrectAnswer = "A", + IsValid = true, + Text = "Quel personnage dit Que la Force soit avec toi dans Star Wars ?" + }, + new + { + Id = 9, + AnswerA = "Dr. Ellie Sattler", + AnswerB = "Alan Grant", + AnswerC = "John Hammond", + AnswerD = "Dennis Nedry", + CorrectAnswer = "B", + IsValid = true, + Text = "Dans Jurassic Park, quel est le nom du paléontologue sur l'île ?" + }, + new + { + Id = 10, + AnswerA = "Cersei Lannister", + AnswerB = "Arya Stark", + AnswerC = "Daenerys Targaryen", + AnswerD = "Sansa Stark", + CorrectAnswer = "C", + IsValid = true, + Text = "Dans Game of Thrones, qui est surnommée la Mère des Dragons ?" + }); + }); + + modelBuilder.Entity("Entity.Quiz", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("int"); + + SqlServerPropertyBuilderExtensions.UseIdentityColumn(b.Property("Id")); + + b.Property("IdImage") + .HasColumnType("int"); + + b.Property("NbQuestion") + .HasColumnType("int"); + + b.Property("Title") + .IsRequired() + .HasMaxLength(50) + .HasColumnType("nvarchar(50)"); + + b.HasKey("Id"); + + b.HasIndex("IdImage"); + + b.ToTable("quizzes"); + + b.HasData( + new + { + Id = 1, + IdImage = 1, + NbQuestion = 5, + Title = "Quiz 1" + }, + new + { + Id = 2, + IdImage = 2, + NbQuestion = 5, + Title = "Quiz 2" + }); + }); + + modelBuilder.Entity("Entity.QuizQuestion", b => + { + b.Property("IdQuestion") + .HasColumnType("int"); + + b.Property("IdQuiz") + .HasColumnType("int"); + + b.HasKey("IdQuestion", "IdQuiz"); + + b.HasIndex("IdQuiz"); + + b.ToTable("QuizQuestion"); + + b.HasData( + new + { + IdQuestion = 1, + IdQuiz = 1 + }, + new + { + IdQuestion = 2, + IdQuiz = 1 + }, + new + { + IdQuestion = 3, + IdQuiz = 1 + }, + new + { + IdQuestion = 4, + IdQuiz = 1 + }, + new + { + IdQuestion = 5, + IdQuiz = 1 + }, + new + { + IdQuestion = 6, + IdQuiz = 2 + }, + new + { + IdQuestion = 7, + IdQuiz = 2 + }, + new + { + IdQuestion = 8, + IdQuiz = 2 + }, + new + { + IdQuestion = 9, + IdQuiz = 2 + }, + new + { + IdQuestion = 10, + IdQuiz = 2 + }); + }); + + modelBuilder.Entity("Entity.Quote", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("int"); + + SqlServerPropertyBuilderExtensions.UseIdentityColumn(b.Property("Id")); + + b.Property("Content") + .IsRequired() + .HasMaxLength(100) + .HasColumnType("nvarchar(100)"); + + b.Property("IdCharacter") + .HasColumnType("int"); + + b.Property("IdSource") + .HasColumnType("int"); + + b.Property("IdUsersPropose") + .HasColumnType("int"); + + b.Property("IsValid") + .HasColumnType("bit"); + + b.Property("Langage") + .HasColumnType("int"); + + b.Property("Likes") + .HasColumnType("int"); + + b.HasKey("Id"); + + b.HasIndex("IdCharacter"); + + b.HasIndex("IdSource"); + + b.HasIndex("IdUsersPropose"); + + b.ToTable("quotes"); + + b.HasData( + new + { + Id = 1, + Content = "Je n'y crois pas. Je n'y crois pas. Ce n'est pas possible", + IdCharacter = 1, + IdSource = 1, + IdUsersPropose = 1, + IsValid = true, + Langage = 1, + Likes = 11025 + }, + new + { + Id = 2, + Content = "There is always hope", + IdCharacter = 2, + IdSource = 2, + IdUsersPropose = 1, + IsValid = true, + Langage = 0, + Likes = 11025 + }, + new + { + Id = 3, + Content = "A red sun rises. Blood has been spilled this night.", + IdCharacter = 3, + IdSource = 2, + IdUsersPropose = 1, + IsValid = true, + Langage = 0, + Likes = 11025 + }, + new + { + Id = 4, + Content = "I wish the Ring had never come to me.I wish none of this had happened.", + IdCharacter = 4, + IdSource = 2, + IdUsersPropose = 1, + IsValid = true, + Langage = 0, + Likes = 11025 + }, + new + { + Id = 5, + Content = "Dobby is a free elf!", + IdCharacter = 5, + IdSource = 4, + IdUsersPropose = 1, + IsValid = true, + Langage = 0, + Likes = 11025 + }, + new + { + Id = 6, + Content = "Winter is comming", + IdCharacter = 6, + IdSource = 3, + IdUsersPropose = 1, + IsValid = true, + Langage = 0, + Likes = 11025 + }, + new + { + Id = 7, + Content = "Je suis la dernière Targaryen. Je suis la reine des dragons", + IdCharacter = 7, + IdSource = 3, + IdUsersPropose = 1, + IsValid = true, + Langage = 1, + Likes = 11025 + }, + new + { + Id = 8, + Content = "Je ne suis pas prêt à affronter ça. C'est trop pour moi.", + IdCharacter = 8, + IdSource = 5, + IdUsersPropose = 1, + IsValid = true, + Langage = 1, + Likes = 11025 + }, + new + { + Id = 9, + Content = "Aidez-moi, Obi-Wan Kenobi, vous êtes mon seul espoir.", + IdCharacter = 9, + IdSource = 5, + IdUsersPropose = 1, + IsValid = true, + Langage = 1, + Likes = 11025 + }, + new + { + Id = 10, + Content = "La quoi ?", + IdCharacter = 10, + IdSource = 4, + IdUsersPropose = 1, + IsValid = false, + Langage = 1, + Likes = 11025 + }); + }); + + modelBuilder.Entity("Entity.Source", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("int"); + + SqlServerPropertyBuilderExtensions.UseIdentityColumn(b.Property("Id")); + + b.Property("Title") + .IsRequired() + .HasMaxLength(100) + .HasColumnType("nvarchar(100)"); + + b.Property("TypeSrc") + .HasColumnType("int"); + + b.Property("Year") + .HasColumnType("int"); + + b.HasKey("Id"); + + b.ToTable("sources"); + + b.HasData( + new + { + Id = 1, + Title = "Jurassic Park", + TypeSrc = 0, + Year = 1993 + }, + new + { + Id = 2, + Title = "Le Seigneur des anneaux : La Communauté de l'anneau", + TypeSrc = 0, + Year = 2001 + }, + new + { + Id = 3, + Title = "Game of throne", + TypeSrc = 1, + Year = 2011 + }, + new + { + Id = 4, + Title = "Harry Potter à l'école des sorcier", + TypeSrc = 0, + Year = 1997 + }, + new + { + Id = 5, + Title = "Star Wars, épisode IV : Un nouvel espoir", + TypeSrc = 0, + Year = 1977 + }); + }); + + modelBuilder.Entity("Entity.Users", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("int"); + + SqlServerPropertyBuilderExtensions.UseIdentityColumn(b.Property("Id")); + + b.Property("Created") + .HasColumnType("date") + .HasColumnName("Created"); + + b.Property("Email") + .IsRequired() + .HasMaxLength(50) + .HasColumnType("nvarchar(50)"); + + b.Property("IdImage") + .HasColumnType("int"); + + b.Property("Password") + .IsRequired() + .HasMaxLength(200) + .HasColumnType("nvarchar(200)"); + + b.Property("UserName") + .IsRequired() + .HasMaxLength(50) + .HasColumnType("nvarchar(50)"); + + b.HasKey("Id"); + + b.HasIndex("IdImage"); + + b.ToTable("users"); + + b.HasData( + new + { + Id = 1, + Created = new DateTime(2025, 5, 12, 0, 0, 0, 0, DateTimeKind.Unspecified), + Email = "jhonDhoe@gmail.com", + IdImage = 1, + Password = "1234", + UserName = "Jhon-Dhoe" + }, + new + { + Id = 2, + Created = new DateTime(2025, 3, 19, 0, 0, 0, 0, DateTimeKind.Unspecified), + Email = "lucy_rose@outlook.com", + IdImage = 2, + Password = "abcd", + UserName = "Lucy-Rose" + }, + new + { + Id = 3, + Created = new DateTime(2024, 11, 2, 0, 0, 0, 0, DateTimeKind.Unspecified), + Email = "mark.taylor@yahoo.com", + IdImage = 3, + Password = "5678", + UserName = "Mark-Taylor" + }, + new + { + Id = 4, + Created = new DateTime(2025, 2, 28, 0, 0, 0, 0, DateTimeKind.Unspecified), + Email = "sophie.martin@gmail.com", + IdImage = 4, + Password = "4321", + UserName = "Sophie-Martin" + }, + new + { + Id = 5, + Created = new DateTime(2025, 1, 15, 0, 0, 0, 0, DateTimeKind.Unspecified), + Email = "nathan_doe@aol.com", + IdImage = 5, + Password = "8765", + UserName = "Nathan-Doe" + }, + new + { + Id = 6, + Created = new DateTime(2025, 4, 7, 0, 0, 0, 0, DateTimeKind.Unspecified), + Email = "ella.brown@icloud.com", + IdImage = 6, + Password = "2468", + UserName = "Ella-Brown" + }, + new + { + Id = 7, + Created = new DateTime(2024, 12, 25, 0, 0, 0, 0, DateTimeKind.Unspecified), + Email = "oliver_smith@gmail.com", + IdImage = 7, + Password = "1357", + UserName = "Oliver-Smith" + }, + new + { + Id = 8, + Created = new DateTime(2025, 3, 5, 0, 0, 0, 0, DateTimeKind.Unspecified), + Email = "mia.jones@outlook.com", + IdImage = 8, + Password = "1122", + UserName = "Mia-Jones" + }, + new + { + Id = 9, + Created = new DateTime(2025, 2, 22, 0, 0, 0, 0, DateTimeKind.Unspecified), + Email = "kevin_williams@aol.com", + IdImage = 9, + Password = "2233", + UserName = "Kevin-Williams" + }, + new + { + Id = 10, + Created = new DateTime(2025, 1, 3, 0, 0, 0, 0, DateTimeKind.Unspecified), + Email = "olivia.white@yahoo.com", + IdImage = 10, + Password = "3344", + UserName = "Olivia-White" + }); + }); + + modelBuilder.Entity("Entity.Admin", b => + { + b.HasOne("Entity.Users", "User") + .WithMany() + .HasForeignKey("UserId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.Navigation("User"); + }); + + modelBuilder.Entity("Entity.Character", b => + { + b.HasOne("Entity.Images", "Images") + .WithMany("Characters") + .HasForeignKey("IdImage") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.Navigation("Images"); + }); + + modelBuilder.Entity("Entity.Commentary", b => + { + b.HasOne("Entity.Quote", "Quote") + .WithMany("Commentarys") + .HasForeignKey("IdQuote") + .OnDelete(DeleteBehavior.ClientCascade) + .IsRequired(); + + b.HasOne("Entity.Users", "User") + .WithMany() + .HasForeignKey("IdUser") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.Navigation("Quote"); + + b.Navigation("User"); + }); + + modelBuilder.Entity("Entity.Favorite", b => + { + b.HasOne("Entity.Quote", "Quote") + .WithMany() + .HasForeignKey("IdQuote") + .OnDelete(DeleteBehavior.ClientCascade) + .IsRequired(); + + b.HasOne("Entity.Users", "Users") + .WithMany() + .HasForeignKey("IdUsers") + .OnDelete(DeleteBehavior.ClientCascade) + .IsRequired(); + + b.Navigation("Quote"); + + b.Navigation("Users"); + }); + + modelBuilder.Entity("Entity.Quiz", b => + { + b.HasOne("Entity.Images", "Images") + .WithMany("Quizs") + .HasForeignKey("IdImage") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.Navigation("Images"); + }); + + modelBuilder.Entity("Entity.QuizQuestion", b => + { + b.HasOne("Entity.Question", null) + .WithMany() + .HasForeignKey("IdQuestion") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.HasOne("Entity.Quiz", null) + .WithMany() + .HasForeignKey("IdQuiz") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + }); + + modelBuilder.Entity("Entity.Quote", b => + { + b.HasOne("Entity.Character", "Character") + .WithMany("Quotes") + .HasForeignKey("IdCharacter") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.HasOne("Entity.Source", "Source") + .WithMany("Quotes") + .HasForeignKey("IdSource") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.HasOne("Entity.Users", "User") + .WithMany("Quotes") + .HasForeignKey("IdUsersPropose"); + + b.Navigation("Character"); + + b.Navigation("Source"); + + b.Navigation("User"); + }); + + modelBuilder.Entity("Entity.Users", b => + { + b.HasOne("Entity.Images", "Images") + .WithMany("Users") + .HasForeignKey("IdImage") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.Navigation("Images"); + }); + + modelBuilder.Entity("Entity.Character", b => + { + b.Navigation("Quotes"); + }); + + modelBuilder.Entity("Entity.Images", b => + { + b.Navigation("Characters"); + + b.Navigation("Quizs"); + + b.Navigation("Users"); + }); + + modelBuilder.Entity("Entity.Quote", b => + { + b.Navigation("Commentarys"); + }); + + modelBuilder.Entity("Entity.Source", b => + { + b.Navigation("Quotes"); + }); + + modelBuilder.Entity("Entity.Users", b => + { + b.Navigation("Quotes"); + }); +#pragma warning restore 612, 618 + } + } +} diff --git a/WF_EF_Api/StubbedContextLib/Migrations/20250402113707_pm_api.cs b/WF_EF_Api/StubbedContextLib/Migrations/20250402113707_pm_api.cs new file mode 100644 index 0000000..f9dd7c8 --- /dev/null +++ b/WF_EF_Api/StubbedContextLib/Migrations/20250402113707_pm_api.cs @@ -0,0 +1,491 @@ +using System; +using Microsoft.EntityFrameworkCore.Migrations; + +#nullable disable + +#pragma warning disable CA1814 // Prefer jagged arrays over multidimensional + +namespace StubbedContextLib.Migrations +{ + /// + public partial class pm_api : Migration + { + /// + protected override void Up(MigrationBuilder migrationBuilder) + { + migrationBuilder.CreateTable( + name: "images", + columns: table => new + { + Id = table.Column(type: "int", nullable: false) + .Annotation("SqlServer:Identity", "1, 1"), + ImgPath = table.Column(type: "nvarchar(max)", nullable: false) + }, + constraints: table => + { + table.PrimaryKey("PK_images", x => x.Id); + }); + + migrationBuilder.CreateTable( + name: "question", + columns: table => new + { + Id = table.Column(type: "int", nullable: false) + .Annotation("SqlServer:Identity", "1, 1"), + Text = table.Column(type: "nvarchar(200)", maxLength: 200, nullable: false), + AnswerA = table.Column(type: "nvarchar(50)", maxLength: 50, nullable: false), + AnswerB = table.Column(type: "nvarchar(50)", maxLength: 50, nullable: false), + AnswerC = table.Column(type: "nvarchar(50)", maxLength: 50, nullable: false), + AnswerD = table.Column(type: "nvarchar(50)", maxLength: 50, nullable: false), + CorrectAnswer = table.Column(type: "nvarchar(1)", maxLength: 1, nullable: false), + IsValid = table.Column(type: "bit", nullable: false) + }, + constraints: table => + { + table.PrimaryKey("PK_question", x => x.Id); + }); + + migrationBuilder.CreateTable( + name: "sources", + columns: table => new + { + Id = table.Column(type: "int", nullable: false) + .Annotation("SqlServer:Identity", "1, 1"), + Title = table.Column(type: "nvarchar(100)", maxLength: 100, nullable: false), + Year = table.Column(type: "int", nullable: false), + TypeSrc = table.Column(type: "int", nullable: false) + }, + constraints: table => + { + table.PrimaryKey("PK_sources", x => x.Id); + }); + + migrationBuilder.CreateTable( + name: "characters", + columns: table => new + { + Id = table.Column(type: "int", nullable: false) + .Annotation("SqlServer:Identity", "1, 1"), + Name = table.Column(type: "nvarchar(50)", maxLength: 50, nullable: false), + IdImage = table.Column(type: "int", nullable: false) + }, + constraints: table => + { + table.PrimaryKey("PK_characters", x => x.Id); + table.ForeignKey( + name: "FK_characters_images_IdImage", + column: x => x.IdImage, + principalTable: "images", + principalColumn: "Id", + onDelete: ReferentialAction.Cascade); + }); + + migrationBuilder.CreateTable( + name: "quizzes", + columns: table => new + { + Id = table.Column(type: "int", nullable: false) + .Annotation("SqlServer:Identity", "1, 1"), + Title = table.Column(type: "nvarchar(50)", maxLength: 50, nullable: false), + IdImage = table.Column(type: "int", nullable: false), + NbQuestion = table.Column(type: "int", nullable: false) + }, + constraints: table => + { + table.PrimaryKey("PK_quizzes", x => x.Id); + table.ForeignKey( + name: "FK_quizzes_images_IdImage", + column: x => x.IdImage, + principalTable: "images", + principalColumn: "Id", + onDelete: ReferentialAction.Cascade); + }); + + migrationBuilder.CreateTable( + name: "users", + columns: table => new + { + Id = table.Column(type: "int", nullable: false) + .Annotation("SqlServer:Identity", "1, 1"), + UserName = table.Column(type: "nvarchar(50)", maxLength: 50, nullable: false), + Email = table.Column(type: "nvarchar(50)", maxLength: 50, nullable: false), + Password = table.Column(type: "nvarchar(200)", maxLength: 200, nullable: false), + IdImage = table.Column(type: "int", nullable: false), + Created = table.Column(type: "date", nullable: false) + }, + constraints: table => + { + table.PrimaryKey("PK_users", x => x.Id); + table.ForeignKey( + name: "FK_users_images_IdImage", + column: x => x.IdImage, + principalTable: "images", + principalColumn: "Id", + onDelete: ReferentialAction.Cascade); + }); + + migrationBuilder.CreateTable( + name: "QuizQuestion", + columns: table => new + { + IdQuiz = table.Column(type: "int", nullable: false), + IdQuestion = table.Column(type: "int", nullable: false) + }, + constraints: table => + { + table.PrimaryKey("PK_QuizQuestion", x => new { x.IdQuestion, x.IdQuiz }); + table.ForeignKey( + name: "FK_QuizQuestion_question_IdQuestion", + column: x => x.IdQuestion, + principalTable: "question", + principalColumn: "Id", + onDelete: ReferentialAction.Cascade); + table.ForeignKey( + name: "FK_QuizQuestion_quizzes_IdQuiz", + column: x => x.IdQuiz, + principalTable: "quizzes", + principalColumn: "Id", + onDelete: ReferentialAction.Cascade); + }); + + migrationBuilder.CreateTable( + name: "admins", + columns: table => new + { + IdUsers = table.Column(type: "int", nullable: false) + .Annotation("SqlServer:Identity", "1, 1"), + UserId = table.Column(type: "int", nullable: false) + }, + constraints: table => + { + table.PrimaryKey("PK_admins", x => x.IdUsers); + table.ForeignKey( + name: "FK_admins_users_UserId", + column: x => x.UserId, + principalTable: "users", + principalColumn: "Id", + onDelete: ReferentialAction.Cascade); + }); + + migrationBuilder.CreateTable( + name: "quotes", + columns: table => new + { + Id = table.Column(type: "int", nullable: false) + .Annotation("SqlServer:Identity", "1, 1"), + Content = table.Column(type: "nvarchar(100)", maxLength: 100, nullable: false), + Likes = table.Column(type: "int", nullable: false), + Langage = table.Column(type: "int", nullable: false), + IsValid = table.Column(type: "bit", nullable: false), + IdCharacter = table.Column(type: "int", nullable: false), + IdSource = table.Column(type: "int", nullable: false), + IdUsersPropose = table.Column(type: "int", nullable: true) + }, + constraints: table => + { + table.PrimaryKey("PK_quotes", x => x.Id); + table.ForeignKey( + name: "FK_quotes_characters_IdCharacter", + column: x => x.IdCharacter, + principalTable: "characters", + principalColumn: "Id", + onDelete: ReferentialAction.Cascade); + table.ForeignKey( + name: "FK_quotes_sources_IdSource", + column: x => x.IdSource, + principalTable: "sources", + principalColumn: "Id", + onDelete: ReferentialAction.Cascade); + table.ForeignKey( + name: "FK_quotes_users_IdUsersPropose", + column: x => x.IdUsersPropose, + principalTable: "users", + principalColumn: "Id"); + }); + + migrationBuilder.CreateTable( + name: "comments", + columns: table => new + { + IdUser = table.Column(type: "int", nullable: false), + IdQuote = table.Column(type: "int", nullable: false), + Id = table.Column(type: "int", nullable: false) + .Annotation("SqlServer:Identity", "1, 1"), + DateCommentary = table.Column(type: "date", nullable: false), + Comment = table.Column(type: "nvarchar(100)", maxLength: 100, nullable: false) + }, + constraints: table => + { + table.PrimaryKey("PK_comments", x => new { x.IdUser, x.IdQuote }); + table.ForeignKey( + name: "FK_comments_quotes_IdQuote", + column: x => x.IdQuote, + principalTable: "quotes", + principalColumn: "Id"); + table.ForeignKey( + name: "FK_comments_users_IdUser", + column: x => x.IdUser, + principalTable: "users", + principalColumn: "Id", + onDelete: ReferentialAction.Cascade); + }); + + migrationBuilder.CreateTable( + name: "favorites", + columns: table => new + { + IdUsers = table.Column(type: "int", nullable: false), + IdQuote = table.Column(type: "int", nullable: false) + }, + constraints: table => + { + table.PrimaryKey("PK_favorites", x => new { x.IdQuote, x.IdUsers }); + table.ForeignKey( + name: "FK_favorites_quotes_IdQuote", + column: x => x.IdQuote, + principalTable: "quotes", + principalColumn: "Id"); + table.ForeignKey( + name: "FK_favorites_users_IdUsers", + column: x => x.IdUsers, + principalTable: "users", + principalColumn: "Id"); + }); + + migrationBuilder.InsertData( + table: "images", + columns: new[] { "Id", "ImgPath" }, + values: new object[,] + { + { 1, "https://th.bing.com/th/id/OIP.TJuWNCsibz8MVmhdNQEdMwHaE8?w=244&h=180&c=7&r=0&o=5&pid=1.7" }, + { 2, "https://th.bing.com/th/id/OIP.NgXRQ5-IknA6_qOPFhLWIwHaHK?w=165&h=180&c=7&r=0&o=5&pid=1.7" }, + { 3, "https://th.bing.com/th/id/OIP.XcJoJ6bC9sAMjol1pJn5UQHaLH?w=118&h=180&c=7&r=0&o=5&pid=1.7" }, + { 4, "https://th.bing.com/th/id/OIP.PPIESqZaNDa-qUcfSDXhdQHaGK?w=210&h=180&c=7&r=0&o=5&pid=1.7" }, + { 5, "https://th.bing.com/th/id/OIP.XBghSl2kfRNNtQoSxc901wHaHa?w=177&h=180&c=7&r=0&o=5&pid=1.7" }, + { 6, "https://th.bing.com/th/id/OIP.af1Aid64cqEKoIOBgCPxtQHaJO?w=145&h=182&c=7&r=0&o=5&pid=1.7" }, + { 7, "https://th.bing.com/th/id/OIP.ri5vSXr5lNTLt4DO6KQXyQHaI4?w=158&h=189&c=7&r=0&o=5&pid=1.7" }, + { 8, "https://th.bing.com/th/id/OIP.uPTRLR8uspCiafiunUqKfQHaMJ?w=115&h=180&c=7&r=0&o=5&pid=1.7" }, + { 9, "https://th.bing.com/th/id/OIP.hcJis4rKbyQtugsoFJU2ngHaM_?w=118&h=207&c=7&r=0&o=5&pid=1.7" }, + { 10, "https://th.bing.com/th/id/OIP.Py1_XfUrKJY_A6tYEmFS5wHaE8?w=280&h=187&c=7&r=0&o=5&pid=1.7" } + }); + + migrationBuilder.InsertData( + table: "question", + columns: new[] { "Id", "AnswerA", "AnswerB", "AnswerC", "AnswerD", "CorrectAnswer", "IsValid", "Text" }, + values: new object[,] + { + { 1, "Gimli", "Aragorn", "Frodon", "Gandalf", "B", true, "Qui est le leader de la Communauté de l'Anneau ?" }, + { 2, "Serdaigle", "Gryffondor", "Serpentard", "Poufsouffle", "B", false, "Dans quelle maison Harry Potter est-il ?" }, + { 3, "Saroumane", "Sauron", "Gollum", "Gothmog", "B", true, "Qui est le Seigneur des Ténèbres dans la saga Le Seigneur des Anneaux ?" }, + { 4, "Han Solo", "Princesse Leia", "Chewbacca", "R2-D2", "A", true, "Dans le film Star Wars : Episode IV, qui sauve Luke Skywalker de l'Étoile de la Mort ?" }, + { 5, "Reine Jadis", "Aslan", "Edmund", "Lucy", "B", true, "Qui est le souverain de Narnia dans Le Lion, la Sorcière Blanche et l'Armoire Magique ?" }, + { 6, "Smaug", "Falkor", "Norbert", "Shenron", "A", true, "Quel est le nom du dragon dans Le Hobbit ?" }, + { 7, "Bella Swan", "Edward Cullen", "Jacob Black", "Victoria", "A", true, "Qui est la première personne à être mordue par un vampire dans Twilight ?" }, + { 8, "Obi-Wan Kenobi", "Yoda", "Han Solo", "Luke Skywalker", "A", true, "Quel personnage dit Que la Force soit avec toi dans Star Wars ?" }, + { 9, "Dr. Ellie Sattler", "Alan Grant", "John Hammond", "Dennis Nedry", "B", true, "Dans Jurassic Park, quel est le nom du paléontologue sur l'île ?" }, + { 10, "Cersei Lannister", "Arya Stark", "Daenerys Targaryen", "Sansa Stark", "C", true, "Dans Game of Thrones, qui est surnommée la Mère des Dragons ?" } + }); + + migrationBuilder.InsertData( + table: "sources", + columns: new[] { "Id", "Title", "TypeSrc", "Year" }, + values: new object[,] + { + { 1, "Jurassic Park", 0, 1993 }, + { 2, "Le Seigneur des anneaux : La Communauté de l'anneau", 0, 2001 }, + { 3, "Game of throne", 1, 2011 }, + { 4, "Harry Potter à l'école des sorcier", 0, 1997 }, + { 5, "Star Wars, épisode IV : Un nouvel espoir", 0, 1977 } + }); + + migrationBuilder.InsertData( + table: "characters", + columns: new[] { "Id", "IdImage", "Name" }, + values: new object[,] + { + { 1, 1, "Alan Grant" }, + { 2, 2, "Aragorn" }, + { 3, 3, "Legolas" }, + { 4, 4, "Frodon" }, + { 5, 5, "Dobby" }, + { 6, 6, "Jon Snow" }, + { 7, 7, "Daenerys Targaryen" }, + { 8, 8, "Luke Skywalker" }, + { 9, 9, "Princess Leia" }, + { 10, 10, "Harry Potter" } + }); + + migrationBuilder.InsertData( + table: "quizzes", + columns: new[] { "Id", "IdImage", "NbQuestion", "Title" }, + values: new object[,] + { + { 1, 1, 5, "Quiz 1" }, + { 2, 2, 5, "Quiz 2" } + }); + + migrationBuilder.InsertData( + table: "users", + columns: new[] { "Id", "Created", "Email", "IdImage", "Password", "UserName" }, + values: new object[,] + { + { 1, new DateTime(2025, 5, 12, 0, 0, 0, 0, DateTimeKind.Unspecified), "jhonDhoe@gmail.com", 1, "1234", "Jhon-Dhoe" }, + { 2, new DateTime(2025, 3, 19, 0, 0, 0, 0, DateTimeKind.Unspecified), "lucy_rose@outlook.com", 2, "abcd", "Lucy-Rose" }, + { 3, new DateTime(2024, 11, 2, 0, 0, 0, 0, DateTimeKind.Unspecified), "mark.taylor@yahoo.com", 3, "5678", "Mark-Taylor" }, + { 4, new DateTime(2025, 2, 28, 0, 0, 0, 0, DateTimeKind.Unspecified), "sophie.martin@gmail.com", 4, "4321", "Sophie-Martin" }, + { 5, new DateTime(2025, 1, 15, 0, 0, 0, 0, DateTimeKind.Unspecified), "nathan_doe@aol.com", 5, "8765", "Nathan-Doe" }, + { 6, new DateTime(2025, 4, 7, 0, 0, 0, 0, DateTimeKind.Unspecified), "ella.brown@icloud.com", 6, "2468", "Ella-Brown" }, + { 7, new DateTime(2024, 12, 25, 0, 0, 0, 0, DateTimeKind.Unspecified), "oliver_smith@gmail.com", 7, "1357", "Oliver-Smith" }, + { 8, new DateTime(2025, 3, 5, 0, 0, 0, 0, DateTimeKind.Unspecified), "mia.jones@outlook.com", 8, "1122", "Mia-Jones" }, + { 9, new DateTime(2025, 2, 22, 0, 0, 0, 0, DateTimeKind.Unspecified), "kevin_williams@aol.com", 9, "2233", "Kevin-Williams" }, + { 10, new DateTime(2025, 1, 3, 0, 0, 0, 0, DateTimeKind.Unspecified), "olivia.white@yahoo.com", 10, "3344", "Olivia-White" } + }); + + migrationBuilder.InsertData( + table: "QuizQuestion", + columns: new[] { "IdQuestion", "IdQuiz" }, + values: new object[,] + { + { 1, 1 }, + { 2, 1 }, + { 3, 1 }, + { 4, 1 }, + { 5, 1 }, + { 6, 2 }, + { 7, 2 }, + { 8, 2 }, + { 9, 2 }, + { 10, 2 } + }); + + migrationBuilder.InsertData( + table: "quotes", + columns: new[] { "Id", "Content", "IdCharacter", "IdSource", "IdUsersPropose", "IsValid", "Langage", "Likes" }, + values: new object[,] + { + { 1, "Je n'y crois pas. Je n'y crois pas. Ce n'est pas possible", 1, 1, 1, true, 1, 11025 }, + { 2, "There is always hope", 2, 2, 1, true, 0, 11025 }, + { 3, "A red sun rises. Blood has been spilled this night.", 3, 2, 1, true, 0, 11025 }, + { 4, "I wish the Ring had never come to me.I wish none of this had happened.", 4, 2, 1, true, 0, 11025 }, + { 5, "Dobby is a free elf!", 5, 4, 1, true, 0, 11025 }, + { 6, "Winter is comming", 6, 3, 1, true, 0, 11025 }, + { 7, "Je suis la dernière Targaryen. Je suis la reine des dragons", 7, 3, 1, true, 1, 11025 }, + { 8, "Je ne suis pas prêt à affronter ça. C'est trop pour moi.", 8, 5, 1, true, 1, 11025 }, + { 9, "Aidez-moi, Obi-Wan Kenobi, vous êtes mon seul espoir.", 9, 5, 1, true, 1, 11025 }, + { 10, "La quoi ?", 10, 4, 1, false, 1, 11025 } + }); + + migrationBuilder.InsertData( + table: "comments", + columns: new[] { "IdQuote", "IdUser", "Comment", "DateCommentary", "Id" }, + values: new object[,] + { + { 1, 2, "Ce film est le meilleur", new DateTime(2025, 2, 3, 0, 0, 0, 0, DateTimeKind.Unspecified), 1 }, + { 1, 3, "Very good", new DateTime(2025, 3, 11, 0, 0, 0, 0, DateTimeKind.Unspecified), 2 } + }); + + migrationBuilder.InsertData( + table: "favorites", + columns: new[] { "IdQuote", "IdUsers" }, + values: new object[,] + { + { 1, 6 }, + { 2, 8 }, + { 3, 2 }, + { 4, 10 }, + { 5, 3 }, + { 6, 7 }, + { 8, 9 }, + { 9, 1 }, + { 10, 5 } + }); + + migrationBuilder.CreateIndex( + name: "IX_admins_UserId", + table: "admins", + column: "UserId"); + + migrationBuilder.CreateIndex( + name: "IX_characters_IdImage", + table: "characters", + column: "IdImage"); + + migrationBuilder.CreateIndex( + name: "IX_comments_IdQuote", + table: "comments", + column: "IdQuote"); + + migrationBuilder.CreateIndex( + name: "IX_favorites_IdUsers", + table: "favorites", + column: "IdUsers"); + + migrationBuilder.CreateIndex( + name: "IX_QuizQuestion_IdQuiz", + table: "QuizQuestion", + column: "IdQuiz"); + + migrationBuilder.CreateIndex( + name: "IX_quizzes_IdImage", + table: "quizzes", + column: "IdImage"); + + migrationBuilder.CreateIndex( + name: "IX_quotes_IdCharacter", + table: "quotes", + column: "IdCharacter"); + + migrationBuilder.CreateIndex( + name: "IX_quotes_IdSource", + table: "quotes", + column: "IdSource"); + + migrationBuilder.CreateIndex( + name: "IX_quotes_IdUsersPropose", + table: "quotes", + column: "IdUsersPropose"); + + migrationBuilder.CreateIndex( + name: "IX_users_IdImage", + table: "users", + column: "IdImage"); + } + + /// + protected override void Down(MigrationBuilder migrationBuilder) + { + migrationBuilder.DropTable( + name: "admins"); + + migrationBuilder.DropTable( + name: "comments"); + + migrationBuilder.DropTable( + name: "favorites"); + + migrationBuilder.DropTable( + name: "QuizQuestion"); + + migrationBuilder.DropTable( + name: "quotes"); + + migrationBuilder.DropTable( + name: "question"); + + migrationBuilder.DropTable( + name: "quizzes"); + + migrationBuilder.DropTable( + name: "characters"); + + migrationBuilder.DropTable( + name: "sources"); + + migrationBuilder.DropTable( + name: "users"); + + migrationBuilder.DropTable( + name: "images"); + } + } +} diff --git a/WF_EF_Api/StubbedContextLib/Migrations/20250402134601_pm_apiV2.Designer.cs b/WF_EF_Api/StubbedContextLib/Migrations/20250402134601_pm_apiV2.Designer.cs new file mode 100644 index 0000000..efad120 --- /dev/null +++ b/WF_EF_Api/StubbedContextLib/Migrations/20250402134601_pm_apiV2.Designer.cs @@ -0,0 +1,1076 @@ +// +using System; +using Microsoft.EntityFrameworkCore; +using Microsoft.EntityFrameworkCore.Infrastructure; +using Microsoft.EntityFrameworkCore.Metadata; +using Microsoft.EntityFrameworkCore.Migrations; +using Microsoft.EntityFrameworkCore.Storage.ValueConversion; +using StubbedContextLib; + +#nullable disable + +namespace StubbedContextLib.Migrations +{ + [DbContext(typeof(StubWTFContext))] + [Migration("20250402134601_pm_apiV2")] + partial class pm_apiV2 + { + /// + protected override void BuildTargetModel(ModelBuilder modelBuilder) + { +#pragma warning disable 612, 618 + modelBuilder + .HasAnnotation("ProductVersion", "9.0.3") + .HasAnnotation("Relational:MaxIdentifierLength", 128); + + SqlServerModelBuilderExtensions.UseIdentityColumns(modelBuilder); + + modelBuilder.Entity("Entity.Admin", b => + { + b.Property("IdUsers") + .ValueGeneratedOnAdd() + .HasColumnType("int"); + + SqlServerPropertyBuilderExtensions.UseIdentityColumn(b.Property("IdUsers")); + + b.Property("UserId") + .HasColumnType("int"); + + b.HasKey("IdUsers"); + + b.HasIndex("UserId"); + + b.ToTable("admins"); + }); + + modelBuilder.Entity("Entity.Character", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("int"); + + SqlServerPropertyBuilderExtensions.UseIdentityColumn(b.Property("Id")); + + b.Property("IdImage") + .HasColumnType("int"); + + b.Property("Name") + .IsRequired() + .HasMaxLength(50) + .HasColumnType("nvarchar(50)"); + + b.HasKey("Id"); + + b.HasIndex("IdImage"); + + b.ToTable("characters"); + + b.HasData( + new + { + Id = 1, + IdImage = 1, + Name = "Alan Grant" + }, + new + { + Id = 2, + IdImage = 2, + Name = "Aragorn" + }, + new + { + Id = 3, + IdImage = 3, + Name = "Legolas" + }, + new + { + Id = 4, + IdImage = 4, + Name = "Frodon" + }, + new + { + Id = 5, + IdImage = 5, + Name = "Dobby" + }, + new + { + Id = 6, + IdImage = 6, + Name = "Jon Snow" + }, + new + { + Id = 7, + IdImage = 7, + Name = "Daenerys Targaryen" + }, + new + { + Id = 8, + IdImage = 8, + Name = "Luke Skywalker" + }, + new + { + Id = 9, + IdImage = 9, + Name = "Princess Leia" + }, + new + { + Id = 10, + IdImage = 10, + Name = "Harry Potter" + }); + }); + + modelBuilder.Entity("Entity.Commentary", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("int"); + + SqlServerPropertyBuilderExtensions.UseIdentityColumn(b.Property("Id")); + + b.Property("Comment") + .IsRequired() + .HasMaxLength(100) + .HasColumnType("nvarchar(100)"); + + b.Property("DateCommentary") + .HasColumnType("date") + .HasColumnName("DateCommentary"); + + b.Property("IdQuote") + .HasColumnType("int"); + + b.Property("IdUser") + .HasColumnType("int"); + + b.HasKey("Id"); + + b.HasIndex("IdQuote"); + + b.HasIndex("IdUser"); + + b.ToTable("comments"); + + b.HasData( + new + { + Id = 1, + Comment = "Ce film est le meilleur", + DateCommentary = new DateTime(2025, 2, 3, 0, 0, 0, 0, DateTimeKind.Unspecified), + IdQuote = 1, + IdUser = 2 + }, + new + { + Id = 2, + Comment = "Very good", + DateCommentary = new DateTime(2025, 3, 11, 0, 0, 0, 0, DateTimeKind.Unspecified), + IdQuote = 1, + IdUser = 3 + }); + }); + + modelBuilder.Entity("Entity.Favorite", b => + { + b.Property("IdQuote") + .HasColumnType("int"); + + b.Property("IdUsers") + .HasColumnType("int"); + + b.HasKey("IdQuote", "IdUsers"); + + b.HasIndex("IdUsers"); + + b.ToTable("favorites"); + + b.HasData( + new + { + IdQuote = 2, + IdUsers = 8 + }, + new + { + IdQuote = 5, + IdUsers = 3 + }, + new + { + IdQuote = 9, + IdUsers = 1 + }, + new + { + IdQuote = 4, + IdUsers = 10 + }, + new + { + IdQuote = 3, + IdUsers = 2 + }, + new + { + IdQuote = 6, + IdUsers = 7 + }, + new + { + IdQuote = 1, + IdUsers = 6 + }, + new + { + IdQuote = 8, + IdUsers = 9 + }, + new + { + IdQuote = 10, + IdUsers = 5 + }); + }); + + modelBuilder.Entity("Entity.Images", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("int"); + + SqlServerPropertyBuilderExtensions.UseIdentityColumn(b.Property("Id")); + + b.Property("ImgPath") + .IsRequired() + .HasColumnType("nvarchar(max)"); + + b.HasKey("Id"); + + b.ToTable("images"); + + b.HasData( + new + { + Id = 1, + ImgPath = "https://th.bing.com/th/id/OIP.TJuWNCsibz8MVmhdNQEdMwHaE8?w=244&h=180&c=7&r=0&o=5&pid=1.7" + }, + new + { + Id = 2, + ImgPath = "https://th.bing.com/th/id/OIP.NgXRQ5-IknA6_qOPFhLWIwHaHK?w=165&h=180&c=7&r=0&o=5&pid=1.7" + }, + new + { + Id = 3, + ImgPath = "https://th.bing.com/th/id/OIP.XcJoJ6bC9sAMjol1pJn5UQHaLH?w=118&h=180&c=7&r=0&o=5&pid=1.7" + }, + new + { + Id = 4, + ImgPath = "https://th.bing.com/th/id/OIP.PPIESqZaNDa-qUcfSDXhdQHaGK?w=210&h=180&c=7&r=0&o=5&pid=1.7" + }, + new + { + Id = 5, + ImgPath = "https://th.bing.com/th/id/OIP.XBghSl2kfRNNtQoSxc901wHaHa?w=177&h=180&c=7&r=0&o=5&pid=1.7" + }, + new + { + Id = 6, + ImgPath = "https://th.bing.com/th/id/OIP.af1Aid64cqEKoIOBgCPxtQHaJO?w=145&h=182&c=7&r=0&o=5&pid=1.7" + }, + new + { + Id = 7, + ImgPath = "https://th.bing.com/th/id/OIP.ri5vSXr5lNTLt4DO6KQXyQHaI4?w=158&h=189&c=7&r=0&o=5&pid=1.7" + }, + new + { + Id = 8, + ImgPath = "https://th.bing.com/th/id/OIP.uPTRLR8uspCiafiunUqKfQHaMJ?w=115&h=180&c=7&r=0&o=5&pid=1.7" + }, + new + { + Id = 9, + ImgPath = "https://th.bing.com/th/id/OIP.hcJis4rKbyQtugsoFJU2ngHaM_?w=118&h=207&c=7&r=0&o=5&pid=1.7" + }, + new + { + Id = 10, + ImgPath = "https://th.bing.com/th/id/OIP.Py1_XfUrKJY_A6tYEmFS5wHaE8?w=280&h=187&c=7&r=0&o=5&pid=1.7" + }); + }); + + modelBuilder.Entity("Entity.Question", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("int"); + + SqlServerPropertyBuilderExtensions.UseIdentityColumn(b.Property("Id")); + + b.Property("AnswerA") + .IsRequired() + .HasMaxLength(50) + .HasColumnType("nvarchar(50)"); + + b.Property("AnswerB") + .IsRequired() + .HasMaxLength(50) + .HasColumnType("nvarchar(50)"); + + b.Property("AnswerC") + .IsRequired() + .HasMaxLength(50) + .HasColumnType("nvarchar(50)"); + + b.Property("AnswerD") + .IsRequired() + .HasMaxLength(50) + .HasColumnType("nvarchar(50)"); + + b.Property("CorrectAnswer") + .IsRequired() + .HasMaxLength(1) + .HasColumnType("nvarchar(1)"); + + b.Property("IsValid") + .HasColumnType("bit"); + + b.Property("Text") + .IsRequired() + .HasMaxLength(200) + .HasColumnType("nvarchar(200)"); + + b.HasKey("Id"); + + b.ToTable("question"); + + b.HasData( + new + { + Id = 1, + AnswerA = "Gimli", + AnswerB = "Aragorn", + AnswerC = "Frodon", + AnswerD = "Gandalf", + CorrectAnswer = "B", + IsValid = true, + Text = "Qui est le leader de la Communauté de l'Anneau ?" + }, + new + { + Id = 2, + AnswerA = "Serdaigle", + AnswerB = "Gryffondor", + AnswerC = "Serpentard", + AnswerD = "Poufsouffle", + CorrectAnswer = "B", + IsValid = false, + Text = "Dans quelle maison Harry Potter est-il ?" + }, + new + { + Id = 3, + AnswerA = "Saroumane", + AnswerB = "Sauron", + AnswerC = "Gollum", + AnswerD = "Gothmog", + CorrectAnswer = "B", + IsValid = true, + Text = "Qui est le Seigneur des Ténèbres dans la saga Le Seigneur des Anneaux ?" + }, + new + { + Id = 4, + AnswerA = "Han Solo", + AnswerB = "Princesse Leia", + AnswerC = "Chewbacca", + AnswerD = "R2-D2", + CorrectAnswer = "A", + IsValid = true, + Text = "Dans le film Star Wars : Episode IV, qui sauve Luke Skywalker de l'Étoile de la Mort ?" + }, + new + { + Id = 5, + AnswerA = "Reine Jadis", + AnswerB = "Aslan", + AnswerC = "Edmund", + AnswerD = "Lucy", + CorrectAnswer = "B", + IsValid = true, + Text = "Qui est le souverain de Narnia dans Le Lion, la Sorcière Blanche et l'Armoire Magique ?" + }, + new + { + Id = 6, + AnswerA = "Smaug", + AnswerB = "Falkor", + AnswerC = "Norbert", + AnswerD = "Shenron", + CorrectAnswer = "A", + IsValid = true, + Text = "Quel est le nom du dragon dans Le Hobbit ?" + }, + new + { + Id = 7, + AnswerA = "Bella Swan", + AnswerB = "Edward Cullen", + AnswerC = "Jacob Black", + AnswerD = "Victoria", + CorrectAnswer = "A", + IsValid = true, + Text = "Qui est la première personne à être mordue par un vampire dans Twilight ?" + }, + new + { + Id = 8, + AnswerA = "Obi-Wan Kenobi", + AnswerB = "Yoda", + AnswerC = "Han Solo", + AnswerD = "Luke Skywalker", + CorrectAnswer = "A", + IsValid = true, + Text = "Quel personnage dit Que la Force soit avec toi dans Star Wars ?" + }, + new + { + Id = 9, + AnswerA = "Dr. Ellie Sattler", + AnswerB = "Alan Grant", + AnswerC = "John Hammond", + AnswerD = "Dennis Nedry", + CorrectAnswer = "B", + IsValid = true, + Text = "Dans Jurassic Park, quel est le nom du paléontologue sur l'île ?" + }, + new + { + Id = 10, + AnswerA = "Cersei Lannister", + AnswerB = "Arya Stark", + AnswerC = "Daenerys Targaryen", + AnswerD = "Sansa Stark", + CorrectAnswer = "C", + IsValid = true, + Text = "Dans Game of Thrones, qui est surnommée la Mère des Dragons ?" + }); + }); + + modelBuilder.Entity("Entity.Quiz", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("int"); + + SqlServerPropertyBuilderExtensions.UseIdentityColumn(b.Property("Id")); + + b.Property("IdImage") + .HasColumnType("int"); + + b.Property("NbQuestion") + .HasColumnType("int"); + + b.Property("Title") + .IsRequired() + .HasMaxLength(50) + .HasColumnType("nvarchar(50)"); + + b.HasKey("Id"); + + b.HasIndex("IdImage"); + + b.ToTable("quizzes"); + + b.HasData( + new + { + Id = 1, + IdImage = 1, + NbQuestion = 5, + Title = "Quiz 1" + }, + new + { + Id = 2, + IdImage = 2, + NbQuestion = 5, + Title = "Quiz 2" + }); + }); + + modelBuilder.Entity("Entity.QuizQuestion", b => + { + b.Property("IdQuestion") + .HasColumnType("int"); + + b.Property("IdQuiz") + .HasColumnType("int"); + + b.HasKey("IdQuestion", "IdQuiz"); + + b.HasIndex("IdQuiz"); + + b.ToTable("QuizQuestion"); + + b.HasData( + new + { + IdQuestion = 1, + IdQuiz = 1 + }, + new + { + IdQuestion = 2, + IdQuiz = 1 + }, + new + { + IdQuestion = 3, + IdQuiz = 1 + }, + new + { + IdQuestion = 4, + IdQuiz = 1 + }, + new + { + IdQuestion = 5, + IdQuiz = 1 + }, + new + { + IdQuestion = 6, + IdQuiz = 2 + }, + new + { + IdQuestion = 7, + IdQuiz = 2 + }, + new + { + IdQuestion = 8, + IdQuiz = 2 + }, + new + { + IdQuestion = 9, + IdQuiz = 2 + }, + new + { + IdQuestion = 10, + IdQuiz = 2 + }); + }); + + modelBuilder.Entity("Entity.Quote", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("int"); + + SqlServerPropertyBuilderExtensions.UseIdentityColumn(b.Property("Id")); + + b.Property("Content") + .IsRequired() + .HasMaxLength(100) + .HasColumnType("nvarchar(100)"); + + b.Property("IdCharacter") + .HasColumnType("int"); + + b.Property("IdSource") + .HasColumnType("int"); + + b.Property("IdUsersPropose") + .HasColumnType("int"); + + b.Property("IsValid") + .HasColumnType("bit"); + + b.Property("Langage") + .HasColumnType("int"); + + b.Property("Likes") + .HasColumnType("int"); + + b.HasKey("Id"); + + b.HasIndex("IdCharacter"); + + b.HasIndex("IdSource"); + + b.HasIndex("IdUsersPropose"); + + b.ToTable("quotes"); + + b.HasData( + new + { + Id = 1, + Content = "Je n'y crois pas. Je n'y crois pas. Ce n'est pas possible", + IdCharacter = 1, + IdSource = 1, + IdUsersPropose = 1, + IsValid = true, + Langage = 1, + Likes = 11025 + }, + new + { + Id = 2, + Content = "There is always hope", + IdCharacter = 2, + IdSource = 2, + IdUsersPropose = 1, + IsValid = true, + Langage = 0, + Likes = 11025 + }, + new + { + Id = 3, + Content = "A red sun rises. Blood has been spilled this night.", + IdCharacter = 3, + IdSource = 2, + IdUsersPropose = 1, + IsValid = true, + Langage = 0, + Likes = 11025 + }, + new + { + Id = 4, + Content = "I wish the Ring had never come to me.I wish none of this had happened.", + IdCharacter = 4, + IdSource = 2, + IdUsersPropose = 1, + IsValid = true, + Langage = 0, + Likes = 11025 + }, + new + { + Id = 5, + Content = "Dobby is a free elf!", + IdCharacter = 5, + IdSource = 4, + IdUsersPropose = 1, + IsValid = true, + Langage = 0, + Likes = 11025 + }, + new + { + Id = 6, + Content = "Winter is comming", + IdCharacter = 6, + IdSource = 3, + IdUsersPropose = 1, + IsValid = true, + Langage = 0, + Likes = 11025 + }, + new + { + Id = 7, + Content = "Je suis la dernière Targaryen. Je suis la reine des dragons", + IdCharacter = 7, + IdSource = 3, + IdUsersPropose = 1, + IsValid = true, + Langage = 1, + Likes = 11025 + }, + new + { + Id = 8, + Content = "Je ne suis pas prêt à affronter ça. C'est trop pour moi.", + IdCharacter = 8, + IdSource = 5, + IdUsersPropose = 1, + IsValid = true, + Langage = 1, + Likes = 11025 + }, + new + { + Id = 9, + Content = "Aidez-moi, Obi-Wan Kenobi, vous êtes mon seul espoir.", + IdCharacter = 9, + IdSource = 5, + IdUsersPropose = 1, + IsValid = true, + Langage = 1, + Likes = 11025 + }, + new + { + Id = 10, + Content = "La quoi ?", + IdCharacter = 10, + IdSource = 4, + IdUsersPropose = 1, + IsValid = false, + Langage = 1, + Likes = 11025 + }); + }); + + modelBuilder.Entity("Entity.Source", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("int"); + + SqlServerPropertyBuilderExtensions.UseIdentityColumn(b.Property("Id")); + + b.Property("Title") + .IsRequired() + .HasMaxLength(100) + .HasColumnType("nvarchar(100)"); + + b.Property("TypeSrc") + .HasColumnType("int"); + + b.Property("Year") + .HasColumnType("int"); + + b.HasKey("Id"); + + b.ToTable("sources"); + + b.HasData( + new + { + Id = 1, + Title = "Jurassic Park", + TypeSrc = 0, + Year = 1993 + }, + new + { + Id = 2, + Title = "Le Seigneur des anneaux : La Communauté de l'anneau", + TypeSrc = 0, + Year = 2001 + }, + new + { + Id = 3, + Title = "Game of throne", + TypeSrc = 1, + Year = 2011 + }, + new + { + Id = 4, + Title = "Harry Potter à l'école des sorcier", + TypeSrc = 0, + Year = 1997 + }, + new + { + Id = 5, + Title = "Star Wars, épisode IV : Un nouvel espoir", + TypeSrc = 0, + Year = 1977 + }); + }); + + modelBuilder.Entity("Entity.Users", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("int"); + + SqlServerPropertyBuilderExtensions.UseIdentityColumn(b.Property("Id")); + + b.Property("Created") + .HasColumnType("date") + .HasColumnName("Created"); + + b.Property("Email") + .IsRequired() + .HasMaxLength(50) + .HasColumnType("nvarchar(50)"); + + b.Property("IdImage") + .HasColumnType("int"); + + b.Property("Password") + .IsRequired() + .HasMaxLength(200) + .HasColumnType("nvarchar(200)"); + + b.Property("UserName") + .IsRequired() + .HasMaxLength(50) + .HasColumnType("nvarchar(50)"); + + b.HasKey("Id"); + + b.HasIndex("IdImage"); + + b.ToTable("users"); + + b.HasData( + new + { + Id = 1, + Created = new DateTime(2025, 5, 12, 0, 0, 0, 0, DateTimeKind.Unspecified), + Email = "jhonDhoe@gmail.com", + IdImage = 1, + Password = "1234", + UserName = "Jhon-Dhoe" + }, + new + { + Id = 2, + Created = new DateTime(2025, 3, 19, 0, 0, 0, 0, DateTimeKind.Unspecified), + Email = "lucy_rose@outlook.com", + IdImage = 2, + Password = "abcd", + UserName = "Lucy-Rose" + }, + new + { + Id = 3, + Created = new DateTime(2024, 11, 2, 0, 0, 0, 0, DateTimeKind.Unspecified), + Email = "mark.taylor@yahoo.com", + IdImage = 3, + Password = "5678", + UserName = "Mark-Taylor" + }, + new + { + Id = 4, + Created = new DateTime(2025, 2, 28, 0, 0, 0, 0, DateTimeKind.Unspecified), + Email = "sophie.martin@gmail.com", + IdImage = 4, + Password = "4321", + UserName = "Sophie-Martin" + }, + new + { + Id = 5, + Created = new DateTime(2025, 1, 15, 0, 0, 0, 0, DateTimeKind.Unspecified), + Email = "nathan_doe@aol.com", + IdImage = 5, + Password = "8765", + UserName = "Nathan-Doe" + }, + new + { + Id = 6, + Created = new DateTime(2025, 4, 7, 0, 0, 0, 0, DateTimeKind.Unspecified), + Email = "ella.brown@icloud.com", + IdImage = 6, + Password = "2468", + UserName = "Ella-Brown" + }, + new + { + Id = 7, + Created = new DateTime(2024, 12, 25, 0, 0, 0, 0, DateTimeKind.Unspecified), + Email = "oliver_smith@gmail.com", + IdImage = 7, + Password = "1357", + UserName = "Oliver-Smith" + }, + new + { + Id = 8, + Created = new DateTime(2025, 3, 5, 0, 0, 0, 0, DateTimeKind.Unspecified), + Email = "mia.jones@outlook.com", + IdImage = 8, + Password = "1122", + UserName = "Mia-Jones" + }, + new + { + Id = 9, + Created = new DateTime(2025, 2, 22, 0, 0, 0, 0, DateTimeKind.Unspecified), + Email = "kevin_williams@aol.com", + IdImage = 9, + Password = "2233", + UserName = "Kevin-Williams" + }, + new + { + Id = 10, + Created = new DateTime(2025, 1, 3, 0, 0, 0, 0, DateTimeKind.Unspecified), + Email = "olivia.white@yahoo.com", + IdImage = 10, + Password = "3344", + UserName = "Olivia-White" + }); + }); + + modelBuilder.Entity("Entity.Admin", b => + { + b.HasOne("Entity.Users", "User") + .WithMany() + .HasForeignKey("UserId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.Navigation("User"); + }); + + modelBuilder.Entity("Entity.Character", b => + { + b.HasOne("Entity.Images", "Images") + .WithMany("Characters") + .HasForeignKey("IdImage") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.Navigation("Images"); + }); + + modelBuilder.Entity("Entity.Commentary", b => + { + b.HasOne("Entity.Quote", "Quote") + .WithMany("Commentarys") + .HasForeignKey("IdQuote") + .OnDelete(DeleteBehavior.ClientCascade) + .IsRequired(); + + b.HasOne("Entity.Users", "User") + .WithMany() + .HasForeignKey("IdUser") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.Navigation("Quote"); + + b.Navigation("User"); + }); + + modelBuilder.Entity("Entity.Favorite", b => + { + b.HasOne("Entity.Quote", "Quote") + .WithMany() + .HasForeignKey("IdQuote") + .OnDelete(DeleteBehavior.ClientCascade) + .IsRequired(); + + b.HasOne("Entity.Users", "Users") + .WithMany() + .HasForeignKey("IdUsers") + .OnDelete(DeleteBehavior.ClientCascade) + .IsRequired(); + + b.Navigation("Quote"); + + b.Navigation("Users"); + }); + + modelBuilder.Entity("Entity.Quiz", b => + { + b.HasOne("Entity.Images", "Images") + .WithMany("Quizs") + .HasForeignKey("IdImage") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.Navigation("Images"); + }); + + modelBuilder.Entity("Entity.QuizQuestion", b => + { + b.HasOne("Entity.Question", null) + .WithMany() + .HasForeignKey("IdQuestion") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.HasOne("Entity.Quiz", null) + .WithMany() + .HasForeignKey("IdQuiz") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + }); + + modelBuilder.Entity("Entity.Quote", b => + { + b.HasOne("Entity.Character", "Character") + .WithMany("Quotes") + .HasForeignKey("IdCharacter") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.HasOne("Entity.Source", "Source") + .WithMany("Quotes") + .HasForeignKey("IdSource") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.HasOne("Entity.Users", "User") + .WithMany("Quotes") + .HasForeignKey("IdUsersPropose"); + + b.Navigation("Character"); + + b.Navigation("Source"); + + b.Navigation("User"); + }); + + modelBuilder.Entity("Entity.Users", b => + { + b.HasOne("Entity.Images", "Images") + .WithMany("Users") + .HasForeignKey("IdImage") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.Navigation("Images"); + }); + + modelBuilder.Entity("Entity.Character", b => + { + b.Navigation("Quotes"); + }); + + modelBuilder.Entity("Entity.Images", b => + { + b.Navigation("Characters"); + + b.Navigation("Quizs"); + + b.Navigation("Users"); + }); + + modelBuilder.Entity("Entity.Quote", b => + { + b.Navigation("Commentarys"); + }); + + modelBuilder.Entity("Entity.Source", b => + { + b.Navigation("Quotes"); + }); + + modelBuilder.Entity("Entity.Users", b => + { + b.Navigation("Quotes"); + }); +#pragma warning restore 612, 618 + } + } +} diff --git a/WF_EF_Api/StubbedContextLib/Migrations/20250402134601_pm_apiV2.cs b/WF_EF_Api/StubbedContextLib/Migrations/20250402134601_pm_apiV2.cs new file mode 100644 index 0000000..ec12b89 --- /dev/null +++ b/WF_EF_Api/StubbedContextLib/Migrations/20250402134601_pm_apiV2.cs @@ -0,0 +1,86 @@ +using System; +using Microsoft.EntityFrameworkCore.Migrations; + +#nullable disable + +#pragma warning disable CA1814 // Prefer jagged arrays over multidimensional + +namespace StubbedContextLib.Migrations +{ + /// + public partial class pm_apiV2 : Migration + { + /// + protected override void Up(MigrationBuilder migrationBuilder) + { + migrationBuilder.DropPrimaryKey( + name: "PK_comments", + table: "comments"); + + migrationBuilder.DeleteData( + table: "comments", + keyColumns: new[] { "IdQuote", "IdUser" }, + keyValues: new object[] { 1, 2 }); + + migrationBuilder.DeleteData( + table: "comments", + keyColumns: new[] { "IdQuote", "IdUser" }, + keyValues: new object[] { 1, 3 }); + + migrationBuilder.AddPrimaryKey( + name: "PK_comments", + table: "comments", + column: "Id"); + + migrationBuilder.InsertData( + table: "comments", + columns: new[] { "Id", "Comment", "DateCommentary", "IdQuote", "IdUser" }, + values: new object[,] + { + { 1, "Ce film est le meilleur", new DateTime(2025, 2, 3, 0, 0, 0, 0, DateTimeKind.Unspecified), 1, 2 }, + { 2, "Very good", new DateTime(2025, 3, 11, 0, 0, 0, 0, DateTimeKind.Unspecified), 1, 3 } + }); + + migrationBuilder.CreateIndex( + name: "IX_comments_IdUser", + table: "comments", + column: "IdUser"); + } + + /// + protected override void Down(MigrationBuilder migrationBuilder) + { + migrationBuilder.DropPrimaryKey( + name: "PK_comments", + table: "comments"); + + migrationBuilder.DropIndex( + name: "IX_comments_IdUser", + table: "comments"); + + migrationBuilder.DeleteData( + table: "comments", + keyColumn: "Id", + keyValue: 1); + + migrationBuilder.DeleteData( + table: "comments", + keyColumn: "Id", + keyValue: 2); + + migrationBuilder.AddPrimaryKey( + name: "PK_comments", + table: "comments", + columns: new[] { "IdUser", "IdQuote" }); + + migrationBuilder.InsertData( + table: "comments", + columns: new[] { "IdQuote", "IdUser", "Comment", "DateCommentary", "Id" }, + values: new object[,] + { + { 1, 2, "Ce film est le meilleur", new DateTime(2025, 2, 3, 0, 0, 0, 0, DateTimeKind.Unspecified), 1 }, + { 1, 3, "Very good", new DateTime(2025, 3, 11, 0, 0, 0, 0, DateTimeKind.Unspecified), 2 } + }); + } + } +} diff --git a/WF_EF_Api/StubbedContextLib/Migrations/StubWTFContextModelSnapshot.cs b/WF_EF_Api/StubbedContextLib/Migrations/StubWTFContextModelSnapshot.cs new file mode 100644 index 0000000..08ef8a9 --- /dev/null +++ b/WF_EF_Api/StubbedContextLib/Migrations/StubWTFContextModelSnapshot.cs @@ -0,0 +1,1073 @@ +// +using System; +using Microsoft.EntityFrameworkCore; +using Microsoft.EntityFrameworkCore.Infrastructure; +using Microsoft.EntityFrameworkCore.Metadata; +using Microsoft.EntityFrameworkCore.Storage.ValueConversion; +using StubbedContextLib; + +#nullable disable + +namespace StubbedContextLib.Migrations +{ + [DbContext(typeof(StubWTFContext))] + partial class StubWTFContextModelSnapshot : ModelSnapshot + { + protected override void BuildModel(ModelBuilder modelBuilder) + { +#pragma warning disable 612, 618 + modelBuilder + .HasAnnotation("ProductVersion", "9.0.3") + .HasAnnotation("Relational:MaxIdentifierLength", 128); + + SqlServerModelBuilderExtensions.UseIdentityColumns(modelBuilder); + + modelBuilder.Entity("Entity.Admin", b => + { + b.Property("IdUsers") + .ValueGeneratedOnAdd() + .HasColumnType("int"); + + SqlServerPropertyBuilderExtensions.UseIdentityColumn(b.Property("IdUsers")); + + b.Property("UserId") + .HasColumnType("int"); + + b.HasKey("IdUsers"); + + b.HasIndex("UserId"); + + b.ToTable("admins"); + }); + + modelBuilder.Entity("Entity.Character", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("int"); + + SqlServerPropertyBuilderExtensions.UseIdentityColumn(b.Property("Id")); + + b.Property("IdImage") + .HasColumnType("int"); + + b.Property("Name") + .IsRequired() + .HasMaxLength(50) + .HasColumnType("nvarchar(50)"); + + b.HasKey("Id"); + + b.HasIndex("IdImage"); + + b.ToTable("characters"); + + b.HasData( + new + { + Id = 1, + IdImage = 1, + Name = "Alan Grant" + }, + new + { + Id = 2, + IdImage = 2, + Name = "Aragorn" + }, + new + { + Id = 3, + IdImage = 3, + Name = "Legolas" + }, + new + { + Id = 4, + IdImage = 4, + Name = "Frodon" + }, + new + { + Id = 5, + IdImage = 5, + Name = "Dobby" + }, + new + { + Id = 6, + IdImage = 6, + Name = "Jon Snow" + }, + new + { + Id = 7, + IdImage = 7, + Name = "Daenerys Targaryen" + }, + new + { + Id = 8, + IdImage = 8, + Name = "Luke Skywalker" + }, + new + { + Id = 9, + IdImage = 9, + Name = "Princess Leia" + }, + new + { + Id = 10, + IdImage = 10, + Name = "Harry Potter" + }); + }); + + modelBuilder.Entity("Entity.Commentary", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("int"); + + SqlServerPropertyBuilderExtensions.UseIdentityColumn(b.Property("Id")); + + b.Property("Comment") + .IsRequired() + .HasMaxLength(100) + .HasColumnType("nvarchar(100)"); + + b.Property("DateCommentary") + .HasColumnType("date") + .HasColumnName("DateCommentary"); + + b.Property("IdQuote") + .HasColumnType("int"); + + b.Property("IdUser") + .HasColumnType("int"); + + b.HasKey("Id"); + + b.HasIndex("IdQuote"); + + b.HasIndex("IdUser"); + + b.ToTable("comments"); + + b.HasData( + new + { + Id = 1, + Comment = "Ce film est le meilleur", + DateCommentary = new DateTime(2025, 2, 3, 0, 0, 0, 0, DateTimeKind.Unspecified), + IdQuote = 1, + IdUser = 2 + }, + new + { + Id = 2, + Comment = "Very good", + DateCommentary = new DateTime(2025, 3, 11, 0, 0, 0, 0, DateTimeKind.Unspecified), + IdQuote = 1, + IdUser = 3 + }); + }); + + modelBuilder.Entity("Entity.Favorite", b => + { + b.Property("IdQuote") + .HasColumnType("int"); + + b.Property("IdUsers") + .HasColumnType("int"); + + b.HasKey("IdQuote", "IdUsers"); + + b.HasIndex("IdUsers"); + + b.ToTable("favorites"); + + b.HasData( + new + { + IdQuote = 2, + IdUsers = 8 + }, + new + { + IdQuote = 5, + IdUsers = 3 + }, + new + { + IdQuote = 9, + IdUsers = 1 + }, + new + { + IdQuote = 4, + IdUsers = 10 + }, + new + { + IdQuote = 3, + IdUsers = 2 + }, + new + { + IdQuote = 6, + IdUsers = 7 + }, + new + { + IdQuote = 1, + IdUsers = 6 + }, + new + { + IdQuote = 8, + IdUsers = 9 + }, + new + { + IdQuote = 10, + IdUsers = 5 + }); + }); + + modelBuilder.Entity("Entity.Images", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("int"); + + SqlServerPropertyBuilderExtensions.UseIdentityColumn(b.Property("Id")); + + b.Property("ImgPath") + .IsRequired() + .HasColumnType("nvarchar(max)"); + + b.HasKey("Id"); + + b.ToTable("images"); + + b.HasData( + new + { + Id = 1, + ImgPath = "https://th.bing.com/th/id/OIP.TJuWNCsibz8MVmhdNQEdMwHaE8?w=244&h=180&c=7&r=0&o=5&pid=1.7" + }, + new + { + Id = 2, + ImgPath = "https://th.bing.com/th/id/OIP.NgXRQ5-IknA6_qOPFhLWIwHaHK?w=165&h=180&c=7&r=0&o=5&pid=1.7" + }, + new + { + Id = 3, + ImgPath = "https://th.bing.com/th/id/OIP.XcJoJ6bC9sAMjol1pJn5UQHaLH?w=118&h=180&c=7&r=0&o=5&pid=1.7" + }, + new + { + Id = 4, + ImgPath = "https://th.bing.com/th/id/OIP.PPIESqZaNDa-qUcfSDXhdQHaGK?w=210&h=180&c=7&r=0&o=5&pid=1.7" + }, + new + { + Id = 5, + ImgPath = "https://th.bing.com/th/id/OIP.XBghSl2kfRNNtQoSxc901wHaHa?w=177&h=180&c=7&r=0&o=5&pid=1.7" + }, + new + { + Id = 6, + ImgPath = "https://th.bing.com/th/id/OIP.af1Aid64cqEKoIOBgCPxtQHaJO?w=145&h=182&c=7&r=0&o=5&pid=1.7" + }, + new + { + Id = 7, + ImgPath = "https://th.bing.com/th/id/OIP.ri5vSXr5lNTLt4DO6KQXyQHaI4?w=158&h=189&c=7&r=0&o=5&pid=1.7" + }, + new + { + Id = 8, + ImgPath = "https://th.bing.com/th/id/OIP.uPTRLR8uspCiafiunUqKfQHaMJ?w=115&h=180&c=7&r=0&o=5&pid=1.7" + }, + new + { + Id = 9, + ImgPath = "https://th.bing.com/th/id/OIP.hcJis4rKbyQtugsoFJU2ngHaM_?w=118&h=207&c=7&r=0&o=5&pid=1.7" + }, + new + { + Id = 10, + ImgPath = "https://th.bing.com/th/id/OIP.Py1_XfUrKJY_A6tYEmFS5wHaE8?w=280&h=187&c=7&r=0&o=5&pid=1.7" + }); + }); + + modelBuilder.Entity("Entity.Question", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("int"); + + SqlServerPropertyBuilderExtensions.UseIdentityColumn(b.Property("Id")); + + b.Property("AnswerA") + .IsRequired() + .HasMaxLength(50) + .HasColumnType("nvarchar(50)"); + + b.Property("AnswerB") + .IsRequired() + .HasMaxLength(50) + .HasColumnType("nvarchar(50)"); + + b.Property("AnswerC") + .IsRequired() + .HasMaxLength(50) + .HasColumnType("nvarchar(50)"); + + b.Property("AnswerD") + .IsRequired() + .HasMaxLength(50) + .HasColumnType("nvarchar(50)"); + + b.Property("CorrectAnswer") + .IsRequired() + .HasMaxLength(1) + .HasColumnType("nvarchar(1)"); + + b.Property("IsValid") + .HasColumnType("bit"); + + b.Property("Text") + .IsRequired() + .HasMaxLength(200) + .HasColumnType("nvarchar(200)"); + + b.HasKey("Id"); + + b.ToTable("question"); + + b.HasData( + new + { + Id = 1, + AnswerA = "Gimli", + AnswerB = "Aragorn", + AnswerC = "Frodon", + AnswerD = "Gandalf", + CorrectAnswer = "B", + IsValid = true, + Text = "Qui est le leader de la Communauté de l'Anneau ?" + }, + new + { + Id = 2, + AnswerA = "Serdaigle", + AnswerB = "Gryffondor", + AnswerC = "Serpentard", + AnswerD = "Poufsouffle", + CorrectAnswer = "B", + IsValid = false, + Text = "Dans quelle maison Harry Potter est-il ?" + }, + new + { + Id = 3, + AnswerA = "Saroumane", + AnswerB = "Sauron", + AnswerC = "Gollum", + AnswerD = "Gothmog", + CorrectAnswer = "B", + IsValid = true, + Text = "Qui est le Seigneur des Ténèbres dans la saga Le Seigneur des Anneaux ?" + }, + new + { + Id = 4, + AnswerA = "Han Solo", + AnswerB = "Princesse Leia", + AnswerC = "Chewbacca", + AnswerD = "R2-D2", + CorrectAnswer = "A", + IsValid = true, + Text = "Dans le film Star Wars : Episode IV, qui sauve Luke Skywalker de l'Étoile de la Mort ?" + }, + new + { + Id = 5, + AnswerA = "Reine Jadis", + AnswerB = "Aslan", + AnswerC = "Edmund", + AnswerD = "Lucy", + CorrectAnswer = "B", + IsValid = true, + Text = "Qui est le souverain de Narnia dans Le Lion, la Sorcière Blanche et l'Armoire Magique ?" + }, + new + { + Id = 6, + AnswerA = "Smaug", + AnswerB = "Falkor", + AnswerC = "Norbert", + AnswerD = "Shenron", + CorrectAnswer = "A", + IsValid = true, + Text = "Quel est le nom du dragon dans Le Hobbit ?" + }, + new + { + Id = 7, + AnswerA = "Bella Swan", + AnswerB = "Edward Cullen", + AnswerC = "Jacob Black", + AnswerD = "Victoria", + CorrectAnswer = "A", + IsValid = true, + Text = "Qui est la première personne à être mordue par un vampire dans Twilight ?" + }, + new + { + Id = 8, + AnswerA = "Obi-Wan Kenobi", + AnswerB = "Yoda", + AnswerC = "Han Solo", + AnswerD = "Luke Skywalker", + CorrectAnswer = "A", + IsValid = true, + Text = "Quel personnage dit Que la Force soit avec toi dans Star Wars ?" + }, + new + { + Id = 9, + AnswerA = "Dr. Ellie Sattler", + AnswerB = "Alan Grant", + AnswerC = "John Hammond", + AnswerD = "Dennis Nedry", + CorrectAnswer = "B", + IsValid = true, + Text = "Dans Jurassic Park, quel est le nom du paléontologue sur l'île ?" + }, + new + { + Id = 10, + AnswerA = "Cersei Lannister", + AnswerB = "Arya Stark", + AnswerC = "Daenerys Targaryen", + AnswerD = "Sansa Stark", + CorrectAnswer = "C", + IsValid = true, + Text = "Dans Game of Thrones, qui est surnommée la Mère des Dragons ?" + }); + }); + + modelBuilder.Entity("Entity.Quiz", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("int"); + + SqlServerPropertyBuilderExtensions.UseIdentityColumn(b.Property("Id")); + + b.Property("IdImage") + .HasColumnType("int"); + + b.Property("NbQuestion") + .HasColumnType("int"); + + b.Property("Title") + .IsRequired() + .HasMaxLength(50) + .HasColumnType("nvarchar(50)"); + + b.HasKey("Id"); + + b.HasIndex("IdImage"); + + b.ToTable("quizzes"); + + b.HasData( + new + { + Id = 1, + IdImage = 1, + NbQuestion = 5, + Title = "Quiz 1" + }, + new + { + Id = 2, + IdImage = 2, + NbQuestion = 5, + Title = "Quiz 2" + }); + }); + + modelBuilder.Entity("Entity.QuizQuestion", b => + { + b.Property("IdQuestion") + .HasColumnType("int"); + + b.Property("IdQuiz") + .HasColumnType("int"); + + b.HasKey("IdQuestion", "IdQuiz"); + + b.HasIndex("IdQuiz"); + + b.ToTable("QuizQuestion"); + + b.HasData( + new + { + IdQuestion = 1, + IdQuiz = 1 + }, + new + { + IdQuestion = 2, + IdQuiz = 1 + }, + new + { + IdQuestion = 3, + IdQuiz = 1 + }, + new + { + IdQuestion = 4, + IdQuiz = 1 + }, + new + { + IdQuestion = 5, + IdQuiz = 1 + }, + new + { + IdQuestion = 6, + IdQuiz = 2 + }, + new + { + IdQuestion = 7, + IdQuiz = 2 + }, + new + { + IdQuestion = 8, + IdQuiz = 2 + }, + new + { + IdQuestion = 9, + IdQuiz = 2 + }, + new + { + IdQuestion = 10, + IdQuiz = 2 + }); + }); + + modelBuilder.Entity("Entity.Quote", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("int"); + + SqlServerPropertyBuilderExtensions.UseIdentityColumn(b.Property("Id")); + + b.Property("Content") + .IsRequired() + .HasMaxLength(100) + .HasColumnType("nvarchar(100)"); + + b.Property("IdCharacter") + .HasColumnType("int"); + + b.Property("IdSource") + .HasColumnType("int"); + + b.Property("IdUsersPropose") + .HasColumnType("int"); + + b.Property("IsValid") + .HasColumnType("bit"); + + b.Property("Langage") + .HasColumnType("int"); + + b.Property("Likes") + .HasColumnType("int"); + + b.HasKey("Id"); + + b.HasIndex("IdCharacter"); + + b.HasIndex("IdSource"); + + b.HasIndex("IdUsersPropose"); + + b.ToTable("quotes"); + + b.HasData( + new + { + Id = 1, + Content = "Je n'y crois pas. Je n'y crois pas. Ce n'est pas possible", + IdCharacter = 1, + IdSource = 1, + IdUsersPropose = 1, + IsValid = true, + Langage = 1, + Likes = 11025 + }, + new + { + Id = 2, + Content = "There is always hope", + IdCharacter = 2, + IdSource = 2, + IdUsersPropose = 1, + IsValid = true, + Langage = 0, + Likes = 11025 + }, + new + { + Id = 3, + Content = "A red sun rises. Blood has been spilled this night.", + IdCharacter = 3, + IdSource = 2, + IdUsersPropose = 1, + IsValid = true, + Langage = 0, + Likes = 11025 + }, + new + { + Id = 4, + Content = "I wish the Ring had never come to me.I wish none of this had happened.", + IdCharacter = 4, + IdSource = 2, + IdUsersPropose = 1, + IsValid = true, + Langage = 0, + Likes = 11025 + }, + new + { + Id = 5, + Content = "Dobby is a free elf!", + IdCharacter = 5, + IdSource = 4, + IdUsersPropose = 1, + IsValid = true, + Langage = 0, + Likes = 11025 + }, + new + { + Id = 6, + Content = "Winter is comming", + IdCharacter = 6, + IdSource = 3, + IdUsersPropose = 1, + IsValid = true, + Langage = 0, + Likes = 11025 + }, + new + { + Id = 7, + Content = "Je suis la dernière Targaryen. Je suis la reine des dragons", + IdCharacter = 7, + IdSource = 3, + IdUsersPropose = 1, + IsValid = true, + Langage = 1, + Likes = 11025 + }, + new + { + Id = 8, + Content = "Je ne suis pas prêt à affronter ça. C'est trop pour moi.", + IdCharacter = 8, + IdSource = 5, + IdUsersPropose = 1, + IsValid = true, + Langage = 1, + Likes = 11025 + }, + new + { + Id = 9, + Content = "Aidez-moi, Obi-Wan Kenobi, vous êtes mon seul espoir.", + IdCharacter = 9, + IdSource = 5, + IdUsersPropose = 1, + IsValid = true, + Langage = 1, + Likes = 11025 + }, + new + { + Id = 10, + Content = "La quoi ?", + IdCharacter = 10, + IdSource = 4, + IdUsersPropose = 1, + IsValid = false, + Langage = 1, + Likes = 11025 + }); + }); + + modelBuilder.Entity("Entity.Source", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("int"); + + SqlServerPropertyBuilderExtensions.UseIdentityColumn(b.Property("Id")); + + b.Property("Title") + .IsRequired() + .HasMaxLength(100) + .HasColumnType("nvarchar(100)"); + + b.Property("TypeSrc") + .HasColumnType("int"); + + b.Property("Year") + .HasColumnType("int"); + + b.HasKey("Id"); + + b.ToTable("sources"); + + b.HasData( + new + { + Id = 1, + Title = "Jurassic Park", + TypeSrc = 0, + Year = 1993 + }, + new + { + Id = 2, + Title = "Le Seigneur des anneaux : La Communauté de l'anneau", + TypeSrc = 0, + Year = 2001 + }, + new + { + Id = 3, + Title = "Game of throne", + TypeSrc = 1, + Year = 2011 + }, + new + { + Id = 4, + Title = "Harry Potter à l'école des sorcier", + TypeSrc = 0, + Year = 1997 + }, + new + { + Id = 5, + Title = "Star Wars, épisode IV : Un nouvel espoir", + TypeSrc = 0, + Year = 1977 + }); + }); + + modelBuilder.Entity("Entity.Users", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("int"); + + SqlServerPropertyBuilderExtensions.UseIdentityColumn(b.Property("Id")); + + b.Property("Created") + .HasColumnType("date") + .HasColumnName("Created"); + + b.Property("Email") + .IsRequired() + .HasMaxLength(50) + .HasColumnType("nvarchar(50)"); + + b.Property("IdImage") + .HasColumnType("int"); + + b.Property("Password") + .IsRequired() + .HasMaxLength(200) + .HasColumnType("nvarchar(200)"); + + b.Property("UserName") + .IsRequired() + .HasMaxLength(50) + .HasColumnType("nvarchar(50)"); + + b.HasKey("Id"); + + b.HasIndex("IdImage"); + + b.ToTable("users"); + + b.HasData( + new + { + Id = 1, + Created = new DateTime(2025, 5, 12, 0, 0, 0, 0, DateTimeKind.Unspecified), + Email = "jhonDhoe@gmail.com", + IdImage = 1, + Password = "1234", + UserName = "Jhon-Dhoe" + }, + new + { + Id = 2, + Created = new DateTime(2025, 3, 19, 0, 0, 0, 0, DateTimeKind.Unspecified), + Email = "lucy_rose@outlook.com", + IdImage = 2, + Password = "abcd", + UserName = "Lucy-Rose" + }, + new + { + Id = 3, + Created = new DateTime(2024, 11, 2, 0, 0, 0, 0, DateTimeKind.Unspecified), + Email = "mark.taylor@yahoo.com", + IdImage = 3, + Password = "5678", + UserName = "Mark-Taylor" + }, + new + { + Id = 4, + Created = new DateTime(2025, 2, 28, 0, 0, 0, 0, DateTimeKind.Unspecified), + Email = "sophie.martin@gmail.com", + IdImage = 4, + Password = "4321", + UserName = "Sophie-Martin" + }, + new + { + Id = 5, + Created = new DateTime(2025, 1, 15, 0, 0, 0, 0, DateTimeKind.Unspecified), + Email = "nathan_doe@aol.com", + IdImage = 5, + Password = "8765", + UserName = "Nathan-Doe" + }, + new + { + Id = 6, + Created = new DateTime(2025, 4, 7, 0, 0, 0, 0, DateTimeKind.Unspecified), + Email = "ella.brown@icloud.com", + IdImage = 6, + Password = "2468", + UserName = "Ella-Brown" + }, + new + { + Id = 7, + Created = new DateTime(2024, 12, 25, 0, 0, 0, 0, DateTimeKind.Unspecified), + Email = "oliver_smith@gmail.com", + IdImage = 7, + Password = "1357", + UserName = "Oliver-Smith" + }, + new + { + Id = 8, + Created = new DateTime(2025, 3, 5, 0, 0, 0, 0, DateTimeKind.Unspecified), + Email = "mia.jones@outlook.com", + IdImage = 8, + Password = "1122", + UserName = "Mia-Jones" + }, + new + { + Id = 9, + Created = new DateTime(2025, 2, 22, 0, 0, 0, 0, DateTimeKind.Unspecified), + Email = "kevin_williams@aol.com", + IdImage = 9, + Password = "2233", + UserName = "Kevin-Williams" + }, + new + { + Id = 10, + Created = new DateTime(2025, 1, 3, 0, 0, 0, 0, DateTimeKind.Unspecified), + Email = "olivia.white@yahoo.com", + IdImage = 10, + Password = "3344", + UserName = "Olivia-White" + }); + }); + + modelBuilder.Entity("Entity.Admin", b => + { + b.HasOne("Entity.Users", "User") + .WithMany() + .HasForeignKey("UserId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.Navigation("User"); + }); + + modelBuilder.Entity("Entity.Character", b => + { + b.HasOne("Entity.Images", "Images") + .WithMany("Characters") + .HasForeignKey("IdImage") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.Navigation("Images"); + }); + + modelBuilder.Entity("Entity.Commentary", b => + { + b.HasOne("Entity.Quote", "Quote") + .WithMany("Commentarys") + .HasForeignKey("IdQuote") + .OnDelete(DeleteBehavior.ClientCascade) + .IsRequired(); + + b.HasOne("Entity.Users", "User") + .WithMany() + .HasForeignKey("IdUser") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.Navigation("Quote"); + + b.Navigation("User"); + }); + + modelBuilder.Entity("Entity.Favorite", b => + { + b.HasOne("Entity.Quote", "Quote") + .WithMany() + .HasForeignKey("IdQuote") + .OnDelete(DeleteBehavior.ClientCascade) + .IsRequired(); + + b.HasOne("Entity.Users", "Users") + .WithMany() + .HasForeignKey("IdUsers") + .OnDelete(DeleteBehavior.ClientCascade) + .IsRequired(); + + b.Navigation("Quote"); + + b.Navigation("Users"); + }); + + modelBuilder.Entity("Entity.Quiz", b => + { + b.HasOne("Entity.Images", "Images") + .WithMany("Quizs") + .HasForeignKey("IdImage") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.Navigation("Images"); + }); + + modelBuilder.Entity("Entity.QuizQuestion", b => + { + b.HasOne("Entity.Question", null) + .WithMany() + .HasForeignKey("IdQuestion") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.HasOne("Entity.Quiz", null) + .WithMany() + .HasForeignKey("IdQuiz") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + }); + + modelBuilder.Entity("Entity.Quote", b => + { + b.HasOne("Entity.Character", "Character") + .WithMany("Quotes") + .HasForeignKey("IdCharacter") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.HasOne("Entity.Source", "Source") + .WithMany("Quotes") + .HasForeignKey("IdSource") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.HasOne("Entity.Users", "User") + .WithMany("Quotes") + .HasForeignKey("IdUsersPropose"); + + b.Navigation("Character"); + + b.Navigation("Source"); + + b.Navigation("User"); + }); + + modelBuilder.Entity("Entity.Users", b => + { + b.HasOne("Entity.Images", "Images") + .WithMany("Users") + .HasForeignKey("IdImage") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.Navigation("Images"); + }); + + modelBuilder.Entity("Entity.Character", b => + { + b.Navigation("Quotes"); + }); + + modelBuilder.Entity("Entity.Images", b => + { + b.Navigation("Characters"); + + b.Navigation("Quizs"); + + b.Navigation("Users"); + }); + + modelBuilder.Entity("Entity.Quote", b => + { + b.Navigation("Commentarys"); + }); + + modelBuilder.Entity("Entity.Source", b => + { + b.Navigation("Quotes"); + }); + + modelBuilder.Entity("Entity.Users", b => + { + b.Navigation("Quotes"); + }); +#pragma warning restore 612, 618 + } + } +} diff --git a/WF_EF_Api/StubbedContextLib/StubWTFContext.cs b/WF_EF_Api/StubbedContextLib/StubWTFContext.cs new file mode 100644 index 0000000..864c6af --- /dev/null +++ b/WF_EF_Api/StubbedContextLib/StubWTFContext.cs @@ -0,0 +1,150 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; +using Contextlib; +using Entity; +using Microsoft.EntityFrameworkCore; +using Microsoft.Extensions.Options; + +namespace StubbedContextLib +{ + public class StubWTFContext : WTFContext + { + protected override void OnModelCreating(ModelBuilder modelBuilder) + { + base.OnModelCreating(modelBuilder); + + /*modelBuilder.Entity().HasData( + new Admin() { IdUsers = 1 } + );*/ + + modelBuilder.Entity().HasData( + new Images() { Id = 1, ImgPath = "https://th.bing.com/th/id/OIP.TJuWNCsibz8MVmhdNQEdMwHaE8?w=244&h=180&c=7&r=0&o=5&pid=1.7" }, + new Images() { Id = 2, ImgPath = "https://th.bing.com/th/id/OIP.NgXRQ5-IknA6_qOPFhLWIwHaHK?w=165&h=180&c=7&r=0&o=5&pid=1.7" }, + new Images() { Id = 3, ImgPath = "https://th.bing.com/th/id/OIP.XcJoJ6bC9sAMjol1pJn5UQHaLH?w=118&h=180&c=7&r=0&o=5&pid=1.7" }, + new Images() { Id = 4, ImgPath = "https://th.bing.com/th/id/OIP.PPIESqZaNDa-qUcfSDXhdQHaGK?w=210&h=180&c=7&r=0&o=5&pid=1.7" }, + new Images() { Id = 5, ImgPath = "https://th.bing.com/th/id/OIP.XBghSl2kfRNNtQoSxc901wHaHa?w=177&h=180&c=7&r=0&o=5&pid=1.7" }, + new Images() { Id = 6, ImgPath = "https://th.bing.com/th/id/OIP.af1Aid64cqEKoIOBgCPxtQHaJO?w=145&h=182&c=7&r=0&o=5&pid=1.7" }, + new Images() { Id = 7, ImgPath = "https://th.bing.com/th/id/OIP.ri5vSXr5lNTLt4DO6KQXyQHaI4?w=158&h=189&c=7&r=0&o=5&pid=1.7" }, + new Images() { Id = 8, ImgPath = "https://th.bing.com/th/id/OIP.uPTRLR8uspCiafiunUqKfQHaMJ?w=115&h=180&c=7&r=0&o=5&pid=1.7" }, + new Images() { Id = 9, ImgPath = "https://th.bing.com/th/id/OIP.hcJis4rKbyQtugsoFJU2ngHaM_?w=118&h=207&c=7&r=0&o=5&pid=1.7" }, + new Images() { Id = 10, ImgPath = "https://th.bing.com/th/id/OIP.Py1_XfUrKJY_A6tYEmFS5wHaE8?w=280&h=187&c=7&r=0&o=5&pid=1.7" } + ); + + modelBuilder.Entity().HasData( + new Users() { Id = 1, Email = "jhonDhoe@gmail.com", Password = "1234", Created = new DateTime(2025, 5, 12), UserName = "Jhon-Dhoe", IdImage = 1 }, + new Users() { Id = 2, Email = "lucy_rose@outlook.com", Password = "abcd", Created = new DateTime(2025, 3, 19), UserName = "Lucy-Rose", IdImage = 2 }, + new Users() { Id = 3, Email = "mark.taylor@yahoo.com", Password = "5678", Created = new DateTime(2024, 11, 2), UserName = "Mark-Taylor", IdImage = 3 }, + new Users() { Id = 4, Email = "sophie.martin@gmail.com", Password = "4321", Created = new DateTime(2025, 2, 28), UserName = "Sophie-Martin", IdImage = 4 }, + new Users() { Id = 5, Email = "nathan_doe@aol.com", Password = "8765", Created = new DateTime(2025, 1, 15), UserName = "Nathan-Doe", IdImage = 5 }, + new Users() { Id = 6, Email = "ella.brown@icloud.com", Password = "2468", Created = new DateTime(2025, 4, 7), UserName = "Ella-Brown", IdImage = 6 }, + new Users() { Id = 7, Email = "oliver_smith@gmail.com", Password = "1357", Created = new DateTime(2024, 12, 25), UserName = "Oliver-Smith", IdImage = 7 }, + new Users() { Id = 8, Email = "mia.jones@outlook.com", Password = "1122", Created = new DateTime(2025, 3, 5), UserName = "Mia-Jones", IdImage = 8 }, + new Users() { Id = 9, Email = "kevin_williams@aol.com", Password = "2233", Created = new DateTime(2025, 2, 22), UserName = "Kevin-Williams", IdImage = 9 }, + new Users() { Id = 10, Email = "olivia.white@yahoo.com", Password = "3344", Created = new DateTime(2025, 1, 3), UserName = "Olivia-White", IdImage = 10 } + ); + + modelBuilder.Entity().HasData( + new Character() { Id = 1 , Name = "Alan Grant", IdImage = 1}, + new Character() { Id = 2, Name = "Aragorn", IdImage = 2 }, + new Character() { Id = 3, Name = "Legolas", IdImage = 3 }, + new Character() { Id = 4, Name = "Frodon", IdImage = 4 }, + new Character() { Id = 5, Name = "Dobby", IdImage = 5 }, + new Character() { Id = 6, Name = "Jon Snow", IdImage = 6 }, + new Character() { Id = 7, Name = "Daenerys Targaryen", IdImage = 7 }, + new Character() { Id = 8, Name = "Luke Skywalker", IdImage = 8 }, + new Character() { Id = 9, Name = "Princess Leia", IdImage = 9 }, + new Character() { Id = 10, Name = "Harry Potter", IdImage = 10 } + ); + + modelBuilder.Entity().HasData( + new Quote() { Id = 1, Content = "Je n'y crois pas. Je n'y crois pas. Ce n'est pas possible", IdCharacter = 1, IdSource = 1, IdUsersPropose = 1, IsValid = true, Langage = LangEnum.vf, Likes = 11025 }, + new Quote() { Id = 2, Content = "There is always hope", IdCharacter = 2, IdSource = 2, IdUsersPropose = 1, IsValid = true, Langage = LangEnum.vo, Likes = 11025 }, + new Quote() { Id = 3, Content = "A red sun rises. Blood has been spilled this night.", IdCharacter = 3, IdSource = 2, IdUsersPropose = 1, IsValid = true, Langage = LangEnum.vo, Likes = 11025 }, + new Quote() { Id = 4, Content = "I wish the Ring had never come to me.I wish none of this had happened.", IdCharacter = 4, IdSource = 2, IdUsersPropose = 1, IsValid = true, Langage = LangEnum.vo, Likes = 11025 }, + new Quote() { Id = 5, Content = "Dobby is a free elf!", IdCharacter = 5, IdSource = 4, IdUsersPropose = 1, IsValid = true, Langage = LangEnum.vo, Likes = 11025 }, + new Quote() { Id = 6, Content = "Winter is comming", IdCharacter = 6, IdSource = 3, IdUsersPropose = 1, IsValid = true, Langage = LangEnum.vo, Likes = 11025 }, + new Quote() { Id = 7, Content = "Je suis la dernière Targaryen. Je suis la reine des dragons", IdCharacter = 7, IdSource = 3, IdUsersPropose = 1, IsValid = true, Langage = LangEnum.vf, Likes = 11025 }, + new Quote() { Id = 8, Content = "Je ne suis pas prêt à affronter ça. C'est trop pour moi.", IdCharacter = 8, IdSource = 5, IdUsersPropose = 1, IsValid = true, Langage = LangEnum.vf, Likes = 11025 }, + new Quote() { Id = 9, Content = "Aidez-moi, Obi-Wan Kenobi, vous êtes mon seul espoir.", IdCharacter = 9, IdSource = 5, IdUsersPropose = 1, IsValid = true, Langage = LangEnum.vf, Likes = 11025 }, + new Quote() { Id = 10, Content = "La quoi ?", IdCharacter = 10, IdSource = 4, IdUsersPropose = 1, IsValid = false, Langage = LangEnum.vf, Likes = 11025 } + ); + + modelBuilder.Entity().HasData( + new Commentary() { Id = 1, Comment = "Ce film est le meilleur", DateCommentary = new DateTime(2025,2,3), IdQuote = 1, IdUser = 2 }, + new Commentary() { Id = 2, Comment = "Very good", DateCommentary = new DateTime(2025, 3, 11), IdQuote = 1, IdUser = 3 } + ); + + + modelBuilder.Entity().HasData( + new Favorite() { IdQuote = 2, IdUsers = 8 }, + new Favorite() { IdQuote = 5, IdUsers = 3 }, + new Favorite() { IdQuote = 9, IdUsers = 1 }, + new Favorite() { IdQuote = 4, IdUsers = 10 }, + new Favorite() { IdQuote = 3, IdUsers = 2 }, + new Favorite() { IdQuote = 6, IdUsers = 7 }, + new Favorite() { IdQuote = 1, IdUsers = 6 }, + new Favorite() { IdQuote = 8, IdUsers = 9 }, + new Favorite() { IdQuote = 10, IdUsers = 5 } + ); + + + + modelBuilder.Entity().HasData( + new Question() { Id = 1, Text = "Qui est le leader de la Communauté de l'Anneau ?", AnswerA = "Gimli", AnswerB = "Aragorn", AnswerC = "Frodon", AnswerD = "Gandalf", CorrectAnswer = "B", IsValid = true }, + new Question() { Id = 2, Text = "Dans quelle maison Harry Potter est-il ?", AnswerA = "Serdaigle", AnswerB = "Gryffondor", AnswerC = "Serpentard", AnswerD = "Poufsouffle", CorrectAnswer = "B" }, + new Question() { Id = 3, Text = "Qui est le Seigneur des Ténèbres dans la saga Le Seigneur des Anneaux ?", AnswerA = "Saroumane", AnswerB = "Sauron", AnswerC = "Gollum", AnswerD = "Gothmog", CorrectAnswer = "B", IsValid = true }, + new Question() { Id = 4, Text = "Dans le film Star Wars : Episode IV, qui sauve Luke Skywalker de l'Étoile de la Mort ?", AnswerA = "Han Solo", AnswerB = "Princesse Leia", AnswerC = "Chewbacca", AnswerD = "R2-D2", CorrectAnswer = "A", IsValid = true }, + new Question() { Id = 5, Text = "Qui est le souverain de Narnia dans Le Lion, la Sorcière Blanche et l'Armoire Magique ?", AnswerA = "Reine Jadis", AnswerB = "Aslan", AnswerC = "Edmund", AnswerD = "Lucy", CorrectAnswer = "B", IsValid = true }, + new Question() { Id = 6, Text = "Quel est le nom du dragon dans Le Hobbit ?", AnswerA = "Smaug", AnswerB = "Falkor", AnswerC = "Norbert", AnswerD = "Shenron", CorrectAnswer = "A", IsValid = true }, + new Question() { Id = 7, Text = "Qui est la première personne à être mordue par un vampire dans Twilight ?", AnswerA = "Bella Swan", AnswerB = "Edward Cullen", AnswerC = "Jacob Black", AnswerD = "Victoria", CorrectAnswer = "A", IsValid = true }, + new Question() { Id = 8, Text = "Quel personnage dit Que la Force soit avec toi dans Star Wars ?", AnswerA = "Obi-Wan Kenobi", AnswerB = "Yoda", AnswerC = "Han Solo", AnswerD = "Luke Skywalker", CorrectAnswer = "A", IsValid = true }, + new Question() { Id = 9, Text = "Dans Jurassic Park, quel est le nom du paléontologue sur l'île ?", AnswerA = "Dr. Ellie Sattler", AnswerB = "Alan Grant", AnswerC = "John Hammond", AnswerD = "Dennis Nedry", CorrectAnswer = "B", IsValid = true }, + new Question() { Id = 10, Text = "Dans Game of Thrones, qui est surnommée la Mère des Dragons ?", AnswerA = "Cersei Lannister", AnswerB = "Arya Stark", AnswerC = "Daenerys Targaryen", AnswerD = "Sansa Stark", CorrectAnswer = "C", IsValid = true } + ); + + modelBuilder.Entity().HasData( + new Quiz() { Id = 1, IdImage = 1, Title = "Quiz 1", NbQuestion = 5 }, + new Quiz() { Id = 2, IdImage = 2, Title = "Quiz 2", NbQuestion = 5 } + ); + + modelBuilder.Entity().HasData( + new QuizQuestion() { IdQuestion = 1, IdQuiz = 1 }, + new QuizQuestion() { IdQuestion = 2, IdQuiz = 1 }, + new QuizQuestion() { IdQuestion = 3, IdQuiz = 1 }, + new QuizQuestion() { IdQuestion = 4, IdQuiz = 1 }, + new QuizQuestion() { IdQuestion = 5, IdQuiz = 1 }, + new QuizQuestion() { IdQuestion = 6, IdQuiz = 2 }, + new QuizQuestion() { IdQuestion = 7, IdQuiz = 2 }, + new QuizQuestion() { IdQuestion = 8, IdQuiz = 2 }, + new QuizQuestion() { IdQuestion = 9, IdQuiz = 2 }, + new QuizQuestion() { IdQuestion = 10, IdQuiz = 2 } + ); + + modelBuilder.Entity().HasData( + new Source() { Id = 1, Title = "Jurassic Park", TypeSrc = TypeSrcEnum.movie, Year = 1993 }, + new Source() { Id = 2, Title = "Le Seigneur des anneaux : La Communauté de l'anneau", TypeSrc = TypeSrcEnum.movie, Year = 2001 }, + new Source() { Id = 3, Title = "Game of throne", TypeSrc = TypeSrcEnum.series, Year = 2011 }, + new Source() { Id = 4, Title = "Harry Potter à l'école des sorcier", TypeSrc = TypeSrcEnum.movie, Year = 1997 }, + new Source() { Id = 5, Title = "Star Wars, épisode IV : Un nouvel espoir", TypeSrc = TypeSrcEnum.movie, Year = 1977 } + ); + } + + public StubWTFContext() + { } + + public StubWTFContext(DbContextOptions options) + : base(options) + { } + + protected override void OnConfiguring(DbContextOptionsBuilder options) + { + if (!options.IsConfigured) + { + options.UseSqlServer(@"Server=(localdb)\mssqllocaldb;Database=Wf-Database.mdf;Trusted_Connection=True;"); + } + } + } +} diff --git a/WF_EF_Api/StubbedContextLib/StubbedContextLib.csproj b/WF_EF_Api/StubbedContextLib/StubbedContextLib.csproj new file mode 100644 index 0000000..4ae6e1b --- /dev/null +++ b/WF_EF_Api/StubbedContextLib/StubbedContextLib.csproj @@ -0,0 +1,25 @@ + + + + net8.0 + enable + enable + + + + + all + runtime; build; native; contentfiles; analyzers; buildtransitive + + + + + + + + + + + + + diff --git a/WF_EF_Api/TestEf/Program.cs b/WF_EF_Api/TestEf/Program.cs new file mode 100644 index 0000000..83fa4f4 --- /dev/null +++ b/WF_EF_Api/TestEf/Program.cs @@ -0,0 +1,2 @@ +// See https://aka.ms/new-console-template for more information +Console.WriteLine("Hello, World!"); diff --git a/WF_EF_Api/TestEf/TestEf.csproj b/WF_EF_Api/TestEf/TestEf.csproj new file mode 100644 index 0000000..206b89a --- /dev/null +++ b/WF_EF_Api/TestEf/TestEf.csproj @@ -0,0 +1,10 @@ + + + + Exe + net8.0 + enable + enable + + + diff --git a/WF_EF_Api/TestModel2Entities/TestModel2Entities.csproj b/WF_EF_Api/TestModel2Entities/TestModel2Entities.csproj new file mode 100644 index 0000000..99264a0 --- /dev/null +++ b/WF_EF_Api/TestModel2Entities/TestModel2Entities.csproj @@ -0,0 +1,16 @@ + + + + net8.0 + enable + enable + + + + + all + runtime; build; native; contentfiles; analyzers; buildtransitive + + + + diff --git a/WF_EF_Api/WF_EF_Api.sln b/WF_EF_Api/WF_EF_Api.sln new file mode 100644 index 0000000..bb798b1 --- /dev/null +++ b/WF_EF_Api/WF_EF_Api.sln @@ -0,0 +1,90 @@ +Microsoft Visual Studio Solution File, Format Version 12.00 +# Visual Studio Version 17 +VisualStudioVersion = 17.9.34723.18 +MinimumVisualStudioVersion = 10.0.40219.1 +Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "ConsoleTest", "ConsoleTest\ConsoleTest.csproj", "{A8B0E4D8-0726-4248-BB6D-DAA2545270B1}" +EndProject +Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "Shared", "Shared\Shared.csproj", "{792EF125-E2D4-457C-B536-BDAEFB49D14E}" +EndProject +Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "Entity", "Entity\Entity.csproj", "{69A4450C-AA43-4622-A866-9A5F7C8A2C14}" +EndProject +Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "Contextlib", "Contextlib\Contextlib.csproj", "{32977454-CE94-4532-AE26-29F6951B78CF}" +EndProject +Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "StubbedContextLib", "StubbedContextLib\StubbedContextLib.csproj", "{5CD69B14-C6AE-4628-A374-996C486E25F2}" +EndProject +Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "TestModel2Entities", "TestModel2Entities\TestModel2Entities.csproj", "{2CF20FAC-C2F1-4048-9D46-F39081B0FBEF}" +EndProject +Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "XUnitTest", "XUnitTest\XUnitTest.csproj", "{48002CA2-7CFF-4077-90CF-392476320CE3}" +EndProject +Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "WfApi", "WfApi\WfApi.csproj", "{D4EEE1BF-CDCB-4E66-997B-7A5984DA7995}" +EndProject +Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "StubApi", "StubApi\StubApi.csproj", "{4C5F324C-28C3-4153-B402-A07B099C24C6}" +EndProject +Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "DTO", "DTO\DTO.csproj", "{99F43B70-4143-4807-9EE7-B8A799B1E702}" +EndProject +Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Dto2Entities", "Dto2Entities\Dto2Entities.csproj", "{08194729-E222-4C9A-B860-D944225B8895}" +EndProject +Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "ServicesApi", "ServicesApi\ServicesApi.csproj", "{6A9AC3D2-C1CD-450A-BD3C-22FAFC9B5328}" +EndProject +Global + GlobalSection(SolutionConfigurationPlatforms) = preSolution + Debug|Any CPU = Debug|Any CPU + Release|Any CPU = Release|Any CPU + EndGlobalSection + GlobalSection(ProjectConfigurationPlatforms) = postSolution + {A8B0E4D8-0726-4248-BB6D-DAA2545270B1}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {A8B0E4D8-0726-4248-BB6D-DAA2545270B1}.Debug|Any CPU.Build.0 = Debug|Any CPU + {A8B0E4D8-0726-4248-BB6D-DAA2545270B1}.Release|Any CPU.ActiveCfg = Release|Any CPU + {A8B0E4D8-0726-4248-BB6D-DAA2545270B1}.Release|Any CPU.Build.0 = Release|Any CPU + {792EF125-E2D4-457C-B536-BDAEFB49D14E}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {792EF125-E2D4-457C-B536-BDAEFB49D14E}.Debug|Any CPU.Build.0 = Debug|Any CPU + {792EF125-E2D4-457C-B536-BDAEFB49D14E}.Release|Any CPU.ActiveCfg = Release|Any CPU + {792EF125-E2D4-457C-B536-BDAEFB49D14E}.Release|Any CPU.Build.0 = Release|Any CPU + {69A4450C-AA43-4622-A866-9A5F7C8A2C14}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {69A4450C-AA43-4622-A866-9A5F7C8A2C14}.Debug|Any CPU.Build.0 = Debug|Any CPU + {69A4450C-AA43-4622-A866-9A5F7C8A2C14}.Release|Any CPU.ActiveCfg = Release|Any CPU + {69A4450C-AA43-4622-A866-9A5F7C8A2C14}.Release|Any CPU.Build.0 = Release|Any CPU + {32977454-CE94-4532-AE26-29F6951B78CF}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {32977454-CE94-4532-AE26-29F6951B78CF}.Debug|Any CPU.Build.0 = Debug|Any CPU + {32977454-CE94-4532-AE26-29F6951B78CF}.Release|Any CPU.ActiveCfg = Release|Any CPU + {32977454-CE94-4532-AE26-29F6951B78CF}.Release|Any CPU.Build.0 = Release|Any CPU + {5CD69B14-C6AE-4628-A374-996C486E25F2}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {5CD69B14-C6AE-4628-A374-996C486E25F2}.Debug|Any CPU.Build.0 = Debug|Any CPU + {5CD69B14-C6AE-4628-A374-996C486E25F2}.Release|Any CPU.ActiveCfg = Release|Any CPU + {5CD69B14-C6AE-4628-A374-996C486E25F2}.Release|Any CPU.Build.0 = Release|Any CPU + {2CF20FAC-C2F1-4048-9D46-F39081B0FBEF}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {2CF20FAC-C2F1-4048-9D46-F39081B0FBEF}.Debug|Any CPU.Build.0 = Debug|Any CPU + {2CF20FAC-C2F1-4048-9D46-F39081B0FBEF}.Release|Any CPU.ActiveCfg = Release|Any CPU + {2CF20FAC-C2F1-4048-9D46-F39081B0FBEF}.Release|Any CPU.Build.0 = Release|Any CPU + {48002CA2-7CFF-4077-90CF-392476320CE3}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {48002CA2-7CFF-4077-90CF-392476320CE3}.Debug|Any CPU.Build.0 = Debug|Any CPU + {48002CA2-7CFF-4077-90CF-392476320CE3}.Release|Any CPU.ActiveCfg = Release|Any CPU + {48002CA2-7CFF-4077-90CF-392476320CE3}.Release|Any CPU.Build.0 = Release|Any CPU + {D4EEE1BF-CDCB-4E66-997B-7A5984DA7995}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {D4EEE1BF-CDCB-4E66-997B-7A5984DA7995}.Debug|Any CPU.Build.0 = Debug|Any CPU + {D4EEE1BF-CDCB-4E66-997B-7A5984DA7995}.Release|Any CPU.ActiveCfg = Release|Any CPU + {D4EEE1BF-CDCB-4E66-997B-7A5984DA7995}.Release|Any CPU.Build.0 = Release|Any CPU + {4C5F324C-28C3-4153-B402-A07B099C24C6}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {4C5F324C-28C3-4153-B402-A07B099C24C6}.Debug|Any CPU.Build.0 = Debug|Any CPU + {4C5F324C-28C3-4153-B402-A07B099C24C6}.Release|Any CPU.ActiveCfg = Release|Any CPU + {4C5F324C-28C3-4153-B402-A07B099C24C6}.Release|Any CPU.Build.0 = Release|Any CPU + {99F43B70-4143-4807-9EE7-B8A799B1E702}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {99F43B70-4143-4807-9EE7-B8A799B1E702}.Debug|Any CPU.Build.0 = Debug|Any CPU + {99F43B70-4143-4807-9EE7-B8A799B1E702}.Release|Any CPU.ActiveCfg = Release|Any CPU + {99F43B70-4143-4807-9EE7-B8A799B1E702}.Release|Any CPU.Build.0 = Release|Any CPU + {08194729-E222-4C9A-B860-D944225B8895}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {08194729-E222-4C9A-B860-D944225B8895}.Debug|Any CPU.Build.0 = Debug|Any CPU + {08194729-E222-4C9A-B860-D944225B8895}.Release|Any CPU.ActiveCfg = Release|Any CPU + {08194729-E222-4C9A-B860-D944225B8895}.Release|Any CPU.Build.0 = Release|Any CPU + {6A9AC3D2-C1CD-450A-BD3C-22FAFC9B5328}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {6A9AC3D2-C1CD-450A-BD3C-22FAFC9B5328}.Debug|Any CPU.Build.0 = Debug|Any CPU + {6A9AC3D2-C1CD-450A-BD3C-22FAFC9B5328}.Release|Any CPU.ActiveCfg = Release|Any CPU + {6A9AC3D2-C1CD-450A-BD3C-22FAFC9B5328}.Release|Any CPU.Build.0 = Release|Any CPU + EndGlobalSection + GlobalSection(SolutionProperties) = preSolution + HideSolutionNode = FALSE + EndGlobalSection + GlobalSection(ExtensibilityGlobals) = postSolution + SolutionGuid = {EC43AAEE-68F6-4CA2-A195-14A91E7D53C0} + EndGlobalSection +EndGlobal diff --git a/WF_EF_Api/WfApi/Controllers/CommentariesController.cs b/WF_EF_Api/WfApi/Controllers/CommentariesController.cs new file mode 100644 index 0000000..7fd26bc --- /dev/null +++ b/WF_EF_Api/WfApi/Controllers/CommentariesController.cs @@ -0,0 +1,104 @@ +using System.Net; +using DTO; +using Entity; +using Microsoft.AspNetCore.Mvc; +using Shared; + +namespace WfApi.Controllers +{ + [ApiController] + [Route("api/v1/commentary")] //Version API + public class CommentariesController : ControllerBase + { + private readonly ICommentaryService _commentary; + + private readonly ILogger _logger; + public CommentariesController(ICommentaryService commentaryService, ILogger logger) + { + _commentary = commentaryService; + _logger = logger; + } + + + + [HttpGet("{id}")] // Indiquer que l'id est dans l'URL + public async Task GetCommentary(int id, int index = 0, int count = 5) + { + try + { + var result =await _commentary.GetCommentaryByQuote(id, index, count); + + if (result != null) + { + return await Task.FromResult(Ok(result)); + } + else + { + return NoContent(); + } + } + catch (Exception) + { + return StatusCode((int)HttpStatusCode.InternalServerError, new { message = "Internal Server Error" }); + } + } + + [HttpPost] + [ProducesResponseType(StatusCodes.Status201Created)] + [ProducesResponseType(StatusCodes.Status400BadRequest)] + [ProducesResponseType(StatusCodes.Status409Conflict)] + [ProducesResponseType(StatusCodes.Status500InternalServerError)] + public async Task CreateCommentary([FromBody] CommentaryDTO newCommentary, int idQuote) + { + try + { + if (newCommentary == null) + { + return BadRequest(new { message = "Comment data is required." }); + } + + try + { + var existingCommentary = await _commentary.GetCommentaryById(newCommentary.Id); + return Conflict(new { message = "A comment with this ID already exists." }); + } + catch (KeyNotFoundException e) + { + await _commentary.AddComment(newCommentary, idQuote); + + return CreatedAtAction(nameof(GetCommentary), new { id = newCommentary.Id }, newCommentary); + } + } + catch (Exception) + { + return StatusCode((int)HttpStatusCode.InternalServerError, new { message = "Erreur interne du serveur." }); + } + } + + + [HttpDelete] // /api/v1/commentary?id=51 + [ProducesResponseType(StatusCodes.Status200OK)] + [ProducesResponseType(StatusCodes.Status404NotFound)] + [ProducesResponseType(StatusCodes.Status500InternalServerError)] + public async Task DeleteCommentary([FromQuery] int id) + { + try + { + + var existingCommentary = _commentary.GetCommentaryById(id).Result; + if (existingCommentary == null) + { + return NotFound(new { message = "Commentary not found." }); + } + + await _commentary.RemoveCommentary(existingCommentary.Id); + + return Ok(new { message = $"Commentary {id} deleted successfully." }); + } + catch (Exception) + { + return StatusCode((int)HttpStatusCode.InternalServerError, new { message = "Internal server error." }); + } + } + } +} diff --git a/WF_EF_Api/WfApi/Controllers/FavoriteController.cs b/WF_EF_Api/WfApi/Controllers/FavoriteController.cs new file mode 100644 index 0000000..20ca251 --- /dev/null +++ b/WF_EF_Api/WfApi/Controllers/FavoriteController.cs @@ -0,0 +1,158 @@ +using System.Net; +using DTO; +using Entity; +using Microsoft.AspNetCore.Mvc; +using ServicesApi; +using Shared; + +namespace WfApi.Controllers +{ + [ApiController] + [Route("api/v1/favorite")] //Version API + public class FavoriteController : ControllerBase + { + private readonly IFavoriteService _favorite; + + private readonly ILogger _logger; + public FavoriteController(IFavoriteService favoriteService, ILogger logger) + { + _favorite = favoriteService; + _logger = logger; + } + + + + [HttpGet("{idUser}")] // Indiquer que l'id est dans l'URL + public async Task GetFavoriteByIdUser(int idUser, int index = 0, int count = 10) + { + try + { + var result = await _favorite.GetFavoriteByIdUser(idUser, index, count); + + if (result != null) + { + return await Task.FromResult(Ok(result)); + } + else + { + return NoContent(); + } + } + catch (Exception) + { + return StatusCode((int)HttpStatusCode.InternalServerError, new { message = "Internal Server Error" }); + } + } + [HttpGet()] // Indiquer que l'id est dans l'URL + public async Task GetFavoriteByIdUser(int idUser , int idQuote) + { + try + { + var result = await _favorite.GetFavorite(idUser, idQuote); + + if (result != null) + { + return await Task.FromResult(Ok(result)); + } + else + { + return NoContent(); + } + } + catch (Exception) + { + return StatusCode((int)HttpStatusCode.InternalServerError, new { message = "Internal Server Error" }); + } + } + + [HttpPost] + [ProducesResponseType(StatusCodes.Status201Created)] + [ProducesResponseType(StatusCodes.Status400BadRequest)] + [ProducesResponseType(StatusCodes.Status409Conflict)] + [ProducesResponseType(StatusCodes.Status500InternalServerError)] + public async Task CreateFavorite(int idUser , int idQuote) + { + try + { + + var existingFavorite = _favorite.GetFavorite(idUser,idQuote).Result; + if (existingFavorite != null) + { + return Conflict(new { message = "A favorite with this ID already exists." }); + } + + await _favorite.AddFavorite(idUser, idQuote); + var fav = new Favorite(); + fav.IdQuote = idQuote; + fav.IdUsers = idUser; + return CreatedAtAction(nameof(GetFavoriteByIdUser), new { id = idUser }, fav); + } + catch (Exception) + { + return StatusCode((int)HttpStatusCode.InternalServerError, new { message = "Erreur interne du serveur." }); + } + } + + + [HttpDelete] // /api/v1/commentary?id=51 + [ProducesResponseType(StatusCodes.Status200OK)] + [ProducesResponseType(StatusCodes.Status404NotFound)] + [ProducesResponseType(StatusCodes.Status500InternalServerError)] + public async Task DeleteFavorite([FromQuery] int idUser, [FromQuery] int idQuote) + { + try + { + + var existingFavorite = await _favorite.GetFavorite(idUser, idQuote); + if (existingFavorite == null) + { + return NotFound(new { message = "Favorite not found." }); + } + + await _favorite.RemoveFavorite(idUser, idQuote); + + return Ok(new { message = $"Favorite from user {idUser} and quote {idQuote} deleted successfully." }); + } + catch (Exception) + { + return StatusCode((int)HttpStatusCode.InternalServerError, new { message = "Internal server error." }); + } + } + [HttpDelete("alluser")] // /api/v1/commentary?id=51 + [ProducesResponseType(StatusCodes.Status200OK)] + [ProducesResponseType(StatusCodes.Status404NotFound)] + [ProducesResponseType(StatusCodes.Status500InternalServerError)] + public async Task DeleteAllFavoriteForUser([FromQuery] int idUser) + { + try + { + + await _favorite.RemoveAllFavoriteForUser(idUser); + + return Ok(new { message = $"Favorite from user {idUser} deleted successfully." }); + } + catch (Exception) + { + return StatusCode((int)HttpStatusCode.InternalServerError, new { message = "Internal server error." }); + } + } + [HttpDelete("allquote")] // /api/v1/commentary?id=51 + [ProducesResponseType(StatusCodes.Status200OK)] + [ProducesResponseType(StatusCodes.Status404NotFound)] + [ProducesResponseType(StatusCodes.Status500InternalServerError)] + public async Task DeleteAllFavoriteForQuote([FromQuery] int idQuote) + { + try + { + + await _favorite.RemoveAllFavoriteForQuote(idQuote); + + return Ok(new { message = $"Favorite from quote {idQuote} deleted successfully." }); + } + catch (Exception) + { + return StatusCode((int)HttpStatusCode.InternalServerError, new { message = "Internal server error." }); + } + } + } +} diff --git a/WF_EF_Api/WfApi/Controllers/QuotesController.cs b/WF_EF_Api/WfApi/Controllers/QuotesController.cs new file mode 100644 index 0000000..ddcdb79 --- /dev/null +++ b/WF_EF_Api/WfApi/Controllers/QuotesController.cs @@ -0,0 +1,361 @@ +using DTO; +using Entity; +using Microsoft.AspNetCore.Http; +using Microsoft.AspNetCore.Mvc; +using Shared; +using System.Net; + +namespace WfApi.Controllers +{ + [ApiController] + [Route("api/v1/quote")] //Version API + public class QuotesController : ControllerBase + { + private readonly IQuoteService _quote; + + private readonly ILogger _logger; + public QuotesController(IQuoteService quoteService, ILogger logger) + { + _quote = quoteService; + _logger = logger; + + } + + + + //===================================== ROUTE GET ===================================== + [HttpGet("{id}")] // Indiquer que l'id est dans l'URL + [ProducesResponseType(StatusCodes.Status200OK)] + [ProducesResponseType(StatusCodes.Status204NoContent)] + [ProducesResponseType(StatusCodes.Status500InternalServerError)] + public async Task GetQuote(int id) + { + try + { + var result = await _quote.GetQuoteById(id); + if (result!=null) + { + return Ok(result); + } + else + { + return NoContent(); + } + } + catch (Exception) + { + return StatusCode((int)HttpStatusCode.InternalServerError, new { message = "Internal Server Error" }); + } + } + + + [HttpGet("all")] + [ProducesResponseType(StatusCodes.Status200OK)] + [ProducesResponseType(StatusCodes.Status204NoContent)] + [ProducesResponseType(StatusCodes.Status500InternalServerError)] + public async Task GetAllQuote(int index = 0, int count = 10) + { + try + { + var result = await _quote.GetSomeQuote(index, count); + + if (result != null) + { + return await Task.FromResult(Ok(result)); + } + else + { + return NoContent(); + } + } + catch (Exception) + { + return StatusCode((int)HttpStatusCode.InternalServerError, new { message = "Internal Server Error" }); + } + } + [HttpGet("allbylang")] + [ProducesResponseType(StatusCodes.Status200OK)] + [ProducesResponseType(StatusCodes.Status204NoContent)] + [ProducesResponseType(StatusCodes.Status500InternalServerError)] + public async Task GetAllQuoteByLang(TypeLangageDTO lang,int index = 0, int count = 10) + { + try + { + var result = await _quote.GetAllQuoteLang(index, count,(int)lang); + + if (result != null) + { + return await Task.FromResult(Ok(result)); + //return Ok(result)); + } + else + { + return NoContent(); + } + } + catch (Exception) + { + return StatusCode((int)HttpStatusCode.InternalServerError, new { message = "Internal Server Error" }); + } + } + [HttpGet("dailyquote")] + [ProducesResponseType(StatusCodes.Status200OK)] + [ProducesResponseType(StatusCodes.Status204NoContent)] + [ProducesResponseType(StatusCodes.Status500InternalServerError)] + public async Task GetDailyQuote([FromQuery] int year, [FromQuery] int month, [FromQuery] int day, TypeLangageDTO lang) + { + try + { + DateOnly date = new DateOnly(year, month, day); + + var result = await _quote.GetDailyQuote(date, (int)lang); + + if (result != null) + { + return await Task.FromResult(Ok(result)); + } + else + { + return NoContent(); + } + } + catch (Exception) + { + return StatusCode((int)HttpStatusCode.InternalServerError, new { message = "Internal Server Error" }); + } + } + [HttpGet("invalid")] + [ProducesResponseType(StatusCodes.Status200OK)] + [ProducesResponseType(StatusCodes.Status204NoContent)] + [ProducesResponseType(StatusCodes.Status500InternalServerError)] + public async Task GetInvalidQuote(TypeLangageDTO lang, int index = 0, int count = 10) + { + try + { + var result =await _quote.GetInvalidQuote(index, count, (int)lang); + + if (result != null) + { + return await Task.FromResult(Ok(result)); + } + else + { + return NoContent(); + } + } + catch (Exception) + { + return StatusCode((int)HttpStatusCode.InternalServerError, new { message = "Internal Server Error" }); + } + } + [HttpGet("suggest")] + [ProducesResponseType(StatusCodes.Status200OK)] + [ProducesResponseType(StatusCodes.Status204NoContent)] + [ProducesResponseType(StatusCodes.Status500InternalServerError)] + public async Task GetSuggestQuote(TypeLangageDTO lang, int index = 0, int count = 10) + { + try + { + var result = await _quote.GetSuggestions(index, count, (int)lang); + + if (result != null) + { + return await Task.FromResult(Ok(result)); + } + else + { + return NoContent(); + } + } + catch (Exception) + { + return StatusCode((int)HttpStatusCode.InternalServerError, new { message = "Internal Server Error" }); + } + } + [HttpGet("searchByCharacter")] + [ProducesResponseType(StatusCodes.Status200OK)] + [ProducesResponseType(StatusCodes.Status204NoContent)] + [ProducesResponseType(StatusCodes.Status500InternalServerError)] + public async Task GetQuoteSearchByCharacter(TypeLangageDTO lang, string character, int index = 0, int count = 10) + { + try + { + var result = await _quote.SearchByCharacter(character, index, count, (int)lang); + + if (result != null) + { + return await Task.FromResult(Ok(result)); + } + else + { + return NoContent(); + } + } + catch (Exception) + { + return StatusCode((int)HttpStatusCode.InternalServerError, new { message = "Internal Server Error" }); + } + } + [HttpGet("searchBySource")] + [ProducesResponseType(StatusCodes.Status200OK)] + [ProducesResponseType(StatusCodes.Status204NoContent)] + [ProducesResponseType(StatusCodes.Status500InternalServerError)] + public async Task GetQuoteSearchBySource(TypeLangageDTO lang, string source, int index = 0, int count = 10) + { + try + { + var result = await _quote.SearchBySource(source, index, count, (int)lang); + + if (result != null) + { + return await Task.FromResult(Ok(result)); + } + else + { + return NoContent(); + } + } + catch (Exception) + { + return StatusCode((int)HttpStatusCode.InternalServerError, new { message = "Internal Server Error" }); + } + } + [HttpGet("searchByContent")] + [ProducesResponseType(StatusCodes.Status200OK)] + [ProducesResponseType(StatusCodes.Status204NoContent)] + [ProducesResponseType(StatusCodes.Status500InternalServerError)] + public async Task GetQuoteSearchByContent(TypeLangageDTO lang, string content, int index = 0, int count = 10) + { + try + { + var result =await _quote.SearchByContent(content, index, count, (int)lang); + + if (result != null) + { + return await Task.FromResult(Ok(result)); + } + else + { + return NoContent(); + } + } + catch (Exception) + { + return StatusCode((int)HttpStatusCode.InternalServerError, new { message = "Internal Server Error" }); + } + } + + //===================================== ROUTE POST ===================================== + + [HttpPost] + [ProducesResponseType(StatusCodes.Status200OK)] + [ProducesResponseType(StatusCodes.Status204NoContent)] + [ProducesResponseType(StatusCodes.Status500InternalServerError)] + public async Task CreateQuote([FromBody] QuoteDTO newQuote) + { + try + { + try + { + if (newQuote == null) + { + return BadRequest(new { message = "Les données de la quote sont requises." }); + } + + + if (await _quote.GetQuoteById(newQuote.Id) != null) + { + return Conflict(new { message = "Une quote avec cet ID existe déjà." }); + } + newQuote.IsValide=false; + var quote=await _quote.AddQuote(newQuote); + + return CreatedAtAction(nameof(CreateQuote), new { id = newQuote.Id }, quote); + } + catch (KeyNotFoundException e) + { + return StatusCode((int)HttpStatusCode.NotFound, e); + } + } + catch (Exception) + { + return StatusCode((int)HttpStatusCode.InternalServerError, new { message = "Erreur interne du serveur." }); + } + } + //===================================== ROUTE PUT ===================================== + [HttpPut()] + [ProducesResponseType(StatusCodes.Status200OK)] + [ProducesResponseType(StatusCodes.Status204NoContent)] + [ProducesResponseType(StatusCodes.Status500InternalServerError)] + public async Task UpdateQuote([FromQuery] int id, [FromBody] QuoteDTO updatedquote) + { + try + { + if (updatedquote == null) + { + return BadRequest(new { message = "Quote data is required." }); + } + + var result = _quote.UpdateQuote(id, updatedquote); + + return Ok(result); + } + catch (Exception) + { + return StatusCode((int)HttpStatusCode.InternalServerError, new { message = "Internal server error." }); + } + } + [HttpPut("valide")] + [ProducesResponseType(StatusCodes.Status200OK)] + [ProducesResponseType(StatusCodes.Status204NoContent)] + [ProducesResponseType(StatusCodes.Status500InternalServerError)] + public async Task ValideQuote([FromQuery] int id) + { + try + { + var updatedquote = _quote.GetQuoteById(id).Result; + if (updatedquote == null) + { + return BadRequest(new { message = "Id Quote is underfined." }); + } + updatedquote.IsValide = true; + var result = _quote.UpdateQuote(id, updatedquote); + + return Ok(result); + } + catch (Exception) + { + return StatusCode((int)HttpStatusCode.InternalServerError, new { message = "Internal server error." }); + } + } + + + //===================================== ROUTE DELETE ===================================== + [HttpDelete("delete")] + [ProducesResponseType(StatusCodes.Status200OK)] + [ProducesResponseType(StatusCodes.Status204NoContent)] + [ProducesResponseType(StatusCodes.Status500InternalServerError)] + public async Task DeleteQuote([FromQuery] int idQuote) + { + try { + try + { + _quote.RemoveQuote(idQuote).Wait(); + + + return await Task.FromResult(Ok()); + + + } + catch (KeyNotFoundException e) + { + return StatusCode((int)HttpStatusCode.NotFound, e); + } + } + catch (Exception) + { + return StatusCode((int) HttpStatusCode.InternalServerError, new { message = "Erreur interne du serveur." }); + } + } + } +} diff --git a/WF_EF_Api/WfApi/Controllers/SourceController.cs b/WF_EF_Api/WfApi/Controllers/SourceController.cs new file mode 100644 index 0000000..744a737 --- /dev/null +++ b/WF_EF_Api/WfApi/Controllers/SourceController.cs @@ -0,0 +1,125 @@ +using System.Net; +using DTO; +using Entity; +using Microsoft.AspNetCore.Mvc; +using Shared; + +namespace WfApi.Controllers +{ + [Route("api/v1/source")] + [ApiController] + public class SourceController : ControllerBase + { + private readonly ISourceService _source; + + private readonly ILogger _logger; + public SourceController(ISourceService sourceService, ILogger logger) + { + _source = sourceService; + _logger = logger; + + } + + [HttpGet("{id}")] // Indiquer que l'id est dans l'URL + [ProducesResponseType(StatusCodes.Status200OK)] + [ProducesResponseType(StatusCodes.Status204NoContent)] + [ProducesResponseType(StatusCodes.Status500InternalServerError)] + public async Task GetSource(int id) + { + try + { + var source = await _source.GetSourceById(id); + if(source != null) + { + return Ok(source); + } + else + { + return NoContent(); + } + } + catch(Exception e) + { + return StatusCode((int)HttpStatusCode.InternalServerError, new { message = "Internal Server Error (" + e + ")" }); + } + } + + [HttpGet("all")] + [ProducesResponseType(StatusCodes.Status200OK)] + [ProducesResponseType(StatusCodes.Status204NoContent)] + [ProducesResponseType(StatusCodes.Status500InternalServerError)] + public async Task GetAllSource(int index = 0, int count = 10) + { + try + { + var result = await _source.GetSomesSource(index, count); + + if (result != null) + { + return await Task.FromResult(Ok(result)); + } + else + { + return NoContent(); + } + } + catch (Exception e) + { + return StatusCode((int)HttpStatusCode.InternalServerError, new { message = "Internal Server Error (" + e + ")" }); + } + } + + [HttpPost] + [ProducesResponseType(StatusCodes.Status200OK)] + [ProducesResponseType(StatusCodes.Status204NoContent)] + [ProducesResponseType(StatusCodes.Status500InternalServerError)] + [ProducesResponseType(StatusCodes.Status400BadRequest)] + public async Task CreateSource([FromBody] SourceDTO newSource) + { + try + { + if(newSource == null) + { + return BadRequest(new { message = "Source data is required." }); + } + try + { + var existingSource = await _source.GetSourceById(newSource.Id); + return Conflict(new { message = "A source with this ID already exists." }); + } + catch(KeyNotFoundException e) + { + await _source.AddSource(newSource); + return CreatedAtAction(nameof(GetAllSource), new { id = newSource.Id }, newSource); + } + } + catch (Exception e) + { + return StatusCode((int)HttpStatusCode.InternalServerError, new { message = "Internal Server Error (" + e + ")" }); + } + } + + [HttpPut()] + [ProducesResponseType(StatusCodes.Status200OK)] + [ProducesResponseType(StatusCodes.Status204NoContent)] + [ProducesResponseType(StatusCodes.Status500InternalServerError)] + public async Task UpdateSource([FromQuery] int id, [FromBody] SourceDTO updatedSource) + { + try + { + if (updatedSource == null) + { + return BadRequest(new { message = "new source data is required." }); + } + + var result = _source.UpdateSource(id, updatedSource); + + return Ok(result); + } + catch (Exception e) + { + return StatusCode((int)HttpStatusCode.InternalServerError, new { message = "Internal Server Error (" + e + ")" }); + } + } + } +} diff --git a/WF_EF_Api/WfApi/Controllers/UsersController.cs b/WF_EF_Api/WfApi/Controllers/UsersController.cs new file mode 100644 index 0000000..fac14f8 --- /dev/null +++ b/WF_EF_Api/WfApi/Controllers/UsersController.cs @@ -0,0 +1,651 @@ +using DTO; +using Microsoft.AspNetCore.Http; +using Microsoft.AspNetCore.Mvc; +using Shared; +using System.Net; +namespace WfApi.Controllers +{ + [ApiController] + [Route("api/v1/users")] //Version API + + public class UsersController : ControllerBase + { + private readonly IUserService _user; + + private readonly ILogger _logger; + public UsersController(IUserService userService, ILogger logger) + { + _user = userService; + _logger = logger; + + } + + //===================================== ROUTE GET ===================================== + /// + /// Gets a user by their unique identifier. + /// + /// The unique identifier of the user + /// + /// + /// ## **Sample request**: + /// + /// GET /users/{id} + /// + /// Where `{id}` is the unique identifier of the user you want to retrieve. + /// + /// ## **Returns** + /// + /// - **200 OK** : Returns the user data if the user with the given ID exists. + /// - **204 No Content** : No user found for the provided ID, or the operation failed. + /// - **500 Internal Server Error** : If there is an exception during the process. + /// + /// ## **Error Handling** + /// - In case of an internal server error (e.g., database issues), a `500 Internal Server Error` will be returned with an error message. + /// + /// Returns the user data corresponding to the provided ID + /// No content if no user is found or the operation fails + /// Internal server error in case of an exception + [ProducesResponseType(StatusCodes.Status200OK)] + [ProducesResponseType(StatusCodes.Status204NoContent)] + [ProducesResponseType(StatusCodes.Status500InternalServerError)] + [HttpGet("{id}")] // Indiquer que l'id est dans l'URL + public async Task Get(int id) + { + try + { + var result =await _user.GetUserById(id); + + if (result != null) + { + return await Task.FromResult(Ok(result)); + } + else + { + return NoContent(); + } + } + catch (Exception) + { + return StatusCode((int)HttpStatusCode.InternalServerError, new { message = "Internal Server Error" }); + } + } + + + /// + /// Gets a list of users with pagination support. + /// + /// The index of the page to retrieve (default is 0) + /// The number of users to retrieve per page (default is 5) + /// + /// + /// ## **Sample request**: + /// + /// GET /users/all?index=0&count=5 + /// + /// The `index` parameter specifies the page number to retrieve (starting from 0), and the `count` parameter specifies how many users to return per page. + /// + /// ## **Returns** + /// + /// - **200 OK** : Returns a list of users if the operation is successful. + /// - **204 No Content** : If no users are found or the operation fails. + /// - **500 Internal Server Error** : If there is an exception during the execution of the request. + /// + /// ## **Error Handling** + /// - In case of an internal server error (e.g., database issues), a `500 Internal Server Error` is returned with an error message. + /// + /// Returns a list of users + /// No content if no users are found or the operation fails + /// Internal server error in case of an exception + [HttpGet("all")] + [ProducesResponseType(StatusCodes.Status200OK)] + [ProducesResponseType(StatusCodes.Status204NoContent)] + [ProducesResponseType(StatusCodes.Status500InternalServerError)] + public async Task GetAllUsers(int index = 0, int count = 5) + { + try + { + var result =await _user.GetSomeUser(index, count); + + if (result != null) + { + return await Task.FromResult(Ok(result)); + } + else + { + return NoContent(); + } + } + catch (Exception) + { + return StatusCode((int)HttpStatusCode.InternalServerError, new { message = "Internal Server Error" }); + } + } + + + /// + /// Gets the hashed password for a given username. + /// + /// The username to retrieve the hashed password for + /// + /// + /// ## **Sample request**: + /// + /// GET /users/hashpassword?username=johndoe + /// + /// The `username` parameter specifies the username for which to retrieve the hashed password. + /// + /// ## **Returns** + /// + /// - **200 OK** : Returns the hashed password for the user if the username exists. + /// - **400 Bad Request** : If no username is provided or if the username is invalid. + /// - **204 No Content** : If no hashed password is found for the provided username. + /// - **500 Internal Server Error** : If an exception occurs while processing the request. + /// + /// ## **Error Handling** + /// - In case of a missing or invalid `username`, a `400 Bad Request` is returned with a relevant message. + /// - If there is an exception during the process (e.g., database errors), a `500 Internal Server Error` is returned. + /// + /// Returns the hashed password for the provided username + /// Bad request if no username is provided or invalid + /// No content if no hashed password is found + /// Internal server error in case of an exception + [HttpGet("hashpassword")] + [ProducesResponseType(StatusCodes.Status200OK)] + [ProducesResponseType(StatusCodes.Status400BadRequest)] + [ProducesResponseType(StatusCodes.Status204NoContent)] + [ProducesResponseType(StatusCodes.Status500InternalServerError)] + public async Task GetHashPassword([FromQuery] string username) + { + if (string.IsNullOrWhiteSpace(username)) + { + return BadRequest(new { message = "No user defined" }); + } + + try + { + var result =await _user.GetHashPassword(username); + + if (result != null) + { + return await Task.FromResult(Ok(result)); + } + else + { + return NoContent(); + } + } + catch (Exception) + { + return StatusCode((int)HttpStatusCode.InternalServerError, new { message = "Internal Server Error" }); + } + } + + + /// + /// Gets a user by their username. + /// + /// The username to retrieve the user + /// + /// + /// ## **Sample request**: + /// + /// GET /users/username?username=johndoe + /// + /// The `username` parameter specifies the username of the user you want to retrieve. + /// + /// ## **Returns** + /// + /// - **200 OK** : Returns the user data if the username exists. + /// - **400 Bad Request** : If no username is provided or if the username is invalid. + /// - **204 No Content** : If no user is found with the provided username. + /// - **500 Internal Server Error** : If an exception occurs while processing the request. + /// + /// ## **Error Handling** + /// - In case of a missing or invalid `username`, a `400 Bad Request` is returned with a relevant message. + /// - If there is an exception during the process (e.g., database errors), a `500 Internal Server Error` is returned. + /// + /// Returns the user data for the provided username + /// Bad request if no username is provided or invalid + /// No content if no user is found with the provided username + /// Internal server error in case of an exception + [HttpGet("username")] + [ProducesResponseType(StatusCodes.Status200OK)] + [ProducesResponseType(StatusCodes.Status400BadRequest)] + [ProducesResponseType(StatusCodes.Status204NoContent)] + [ProducesResponseType(StatusCodes.Status500InternalServerError)] + public async Task GetUserByUsername([FromQuery] string username) + { + if (string.IsNullOrWhiteSpace(username)) + { + return BadRequest(new { message = "No user defined" }); + } + + try + { + var result =await _user.GetUserByUsername(username); + + if (result != null) + { + return await Task.FromResult(Ok(result)); + } + else + { + return NoContent(); + } + } + catch (Exception) + { + return StatusCode((int)HttpStatusCode.InternalServerError, new { message = "Internal Server Error" }); + } + } + + + /// + /// Gets a user by their email address. + /// + /// The email address of the user + /// + /// + /// ## **Sample request**: + /// + /// GET /users/email?email=johndoe@example.com + /// + /// The `email` parameter specifies the email address of the user you want to retrieve. + /// + /// ## **Returns** + /// + /// - **200 OK** : Returns the user data if the email exists. + /// - **400 Bad Request** : If no email is provided or if the email is invalid. + /// - **204 No Content** : If no user is found with the provided email. + /// - **500 Internal Server Error** : If an exception occurs while processing the request. + /// + /// ## **Error Handling** + /// - In case of a missing or invalid `email`, a `400 Bad Request` is returned with a relevant message. + /// - If there is an exception during the process (e.g., database errors), a `500 Internal Server Error` is returned. + /// + /// Returns the user data for the provided email + /// Bad request if no email is provided or invalid + /// No content if no user is found with the provided email + /// Internal server error in case of an exception + [HttpGet("email")] + [ProducesResponseType(StatusCodes.Status200OK)] + [ProducesResponseType(StatusCodes.Status400BadRequest)] + [ProducesResponseType(StatusCodes.Status204NoContent)] + [ProducesResponseType(StatusCodes.Status500InternalServerError)] + public async Task GetUserByEmail([FromQuery] string email) + { + if (string.IsNullOrWhiteSpace(email)) + { + return BadRequest(new { message = "No user email defined" }); + } + try + { + var result =await _user.GetUserByEmail(email); + + if (result != null) + { + return await Task.FromResult(Ok(result)); + } + else + { + return NoContent(); + } + } + catch (Exception) + { + return StatusCode((int)HttpStatusCode.InternalServerError, new { message = "Internal Server Error" }); + } + } + + + /// + /// Gets the total number of users. + /// + /// + /// + /// ## **Sample request**: + /// + /// GET /users/count + /// + /// This endpoint returns the total number of users present in the system. + /// + /// ## **Returns** + /// + /// - **200 OK** : Returns the total count of users. + /// - **204 No Content** : If no users are found or the operation fails. + /// - **500 Internal Server Error** : If an exception occurs while processing the request. + /// + /// ## **Error Handling** + /// - In case of an exception during the process (e.g., database errors), a `500 Internal Server Error` is returned with a relevant message. + /// + /// Returns the total count of users + /// No content if the count could not be retrieved + /// Internal server error in case of an exception + [HttpGet("count")] + [ProducesResponseType(StatusCodes.Status200OK)] + [ProducesResponseType(StatusCodes.Status204NoContent)] + [ProducesResponseType(StatusCodes.Status500InternalServerError)] + public async Task GetCountUser() + { + try + { + var result =await _user.CountUser(); + + if (result!=null) + { + return await Task.FromResult(Ok(result)); + } + else + { + return NoContent(); + } + } + catch (Exception) + { + return StatusCode((int)HttpStatusCode.InternalServerError, new { message = "Internal Server Error" }); + } + } + + + + /// + /// Checks if a user exists by their username. + /// + /// The username to check for existence + /// + /// + /// ## **Sample request**: + /// + /// GET /users/existusername?username=johndoe + /// + /// The `username` parameter specifies the username to check if it exists in the system. + /// + /// ## **Returns** + /// + /// - **200 OK** : If the username exists, returns a success message. + /// - **400 Bad Request** : If no username is provided or if the username is invalid. + /// - **404 Not Found** : If the user with the specified username does not exist. + /// - **500 Internal Server Error** : If an exception occurs while processing the request. + /// + /// ## **Error Handling** + /// - In case of a missing or invalid `username`, a `400 Bad Request` is returned with a relevant message. + /// - If the user does not exist, a `404 Not Found` response is returned. + /// - If there is an exception during the process (e.g., database errors), a `500 Internal Server Error` is returned with an appropriate message. + /// + /// Returns a success message if the username exists + /// Bad request if no username is provided or invalid + /// Not found if the user with the provided username does not exist + /// Internal server error in case of an exception + [HttpGet("existusername")] + [ProducesResponseType(StatusCodes.Status200OK)] + [ProducesResponseType(StatusCodes.Status400BadRequest)] + [ProducesResponseType(StatusCodes.Status404NotFound)] + [ProducesResponseType(StatusCodes.Status500InternalServerError)] + public async Task GetExistUsername([FromQuery] string username) + { + if (string.IsNullOrWhiteSpace(username)) + { + return BadRequest(new { message = "No user defined" }); + } + try + { + var result =await _user.ExistUsername(username); + + if (result!=null) + { + return await Task.FromResult(Ok(result)); + } + else + { + return NotFound("User not found"); + } + } + catch (Exception) + { + return StatusCode((int)HttpStatusCode.InternalServerError, new { message = "Internal Server Error" }); + } + } + + + /// + /// Checks if a user exists by their email address. + /// + /// The email address to check for existence + /// + /// + /// ## **Sample request**: + /// + /// GET /users/existemail?email=johndoe@example.com + /// + /// The `email` parameter specifies the email address to check if it exists in the system. + /// + /// ## **Returns** + /// + /// - **200 OK** : If the email exists, returns a success message. + /// - **400 Bad Request** : If no email is provided or if the email is invalid. + /// - **404 Not Found** : If the user with the specified email does not exist. + /// - **500 Internal Server Error** : If an exception occurs while processing the request. + /// + /// ## **Error Handling** + /// - In case of a missing or invalid `email`, a `400 Bad Request` is returned with a relevant message. + /// - If the user does not exist, a `404 Not Found` response is returned. + /// - If there is an exception during the process (e.g., database errors), a `500 Internal Server Error` is returned with an appropriate message. + /// + /// Returns a success message if the email exists + /// Bad request if no email is provided or invalid + /// Not found if the user with the provided email does not exist + /// Internal server error in case of an exception + [HttpGet("existemail")] + [ProducesResponseType(StatusCodes.Status200OK)] + [ProducesResponseType(StatusCodes.Status400BadRequest)] + [ProducesResponseType(StatusCodes.Status404NotFound)] + [ProducesResponseType(StatusCodes.Status500InternalServerError)] + public async Task GetExistEmail([FromQuery] string email) + { + if (string.IsNullOrWhiteSpace(email)) + { + return BadRequest(new { message = "No user email defined" }); + } + try + { + var result =await _user.ExistEmail(email); + + if (result!=null) + { + return await Task.FromResult(Ok(result)); + } + else + { + return NotFound("User email not found"); + } + } + catch (Exception) + { + return StatusCode((int)HttpStatusCode.InternalServerError, new { message = "Internal Server Error" }); + } + } + + //===================================== ROUTE PUT ===================================== + + + /// + /// Updates an existing user's data. + /// + /// The ID of the user to update + /// The updated user data + /// + /// + /// ## **Sample request**: + /// + /// PUT /users?id=1 + /// Body: + /// { + /// "username": "newusername", + /// "email": "newemail@example.com", + /// "fullName": "New Name" + /// } + /// + /// The `id` parameter specifies the user ID to be updated, and the body contains the updated user data. + /// + /// ## **Returns** + /// + /// - **200 OK** : If the user was successfully updated. + /// - **400 Bad Request** : If the provided user data is invalid or missing. + /// - **500 Internal Server Error** : If an error occurs while processing the update. + /// + /// ## **Error Handling** + /// - If the `updateduser` object is `null`, a `400 Bad Request` is returned with a message indicating that player data is required. + /// - If an exception occurs during the process (e.g., database errors), a `500 Internal Server Error` is returned with an appropriate message. + /// + /// Returns the updated user data + /// Bad request if no user data is provided or invalid + /// Internal server error in case of an exception + [HttpPut()] + [ProducesResponseType(StatusCodes.Status200OK)] + [ProducesResponseType(StatusCodes.Status400BadRequest)] + [ProducesResponseType(StatusCodes.Status500InternalServerError)] + public async Task UpdateUser([FromQuery] int id, [FromBody] UserDTO updateduser) + { + try + { + if (updateduser == null) + { + return BadRequest(new { message = "Player data is required." }); + } + + var result = _user.UpdateUser(id,updateduser); + + return Ok(result); + } + catch (Exception) + { + return StatusCode((int)HttpStatusCode.InternalServerError, new { message = "Internal server error." }); + } + } + + + + //===================================== ROUTE POST ===================================== + + /// + /// Creates a new user in the system. + /// + /// The user data to create the new user + /// + /// + /// ## **Sample request**: + /// + /// POST /users + /// Body: + /// { + /// "id": 123, + /// "username": "newuser", + /// "email": "newuser@example.com", + /// "fullName": "New User" + /// } + /// + /// The `newUser` parameter in the body contains the data of the new user to be created. + /// + /// ## **Returns** + /// + /// - **201 Created** : If the user was successfully created. The location of the created resource is returned in the response header. + /// - **400 Bad Request** : If the provided user data is invalid or missing. + /// - **409 Conflict** : If a user with the specified ID already exists. + /// - **500 Internal Server Error** : If an error occurs while processing the creation of the user. + /// + /// ## **Error Handling** + /// - If the `newUser` object is `null`, a `400 Bad Request` is returned with a message indicating that user data is required. + /// - If the user already exists (based on `Id`), a `409 Conflict` is returned with a message indicating that a user with this ID already exists. + /// - If there is an exception during the process (e.g., database errors), a `500 Internal Server Error` is returned with an appropriate message. + /// + /// Returns the created user and its location + /// Bad request if no user data is provided or invalid + /// Conflict if a user with the same ID already exists + /// Internal server error in case of an exception + [HttpPost] + [ProducesResponseType(StatusCodes.Status201Created)] + [ProducesResponseType(StatusCodes.Status400BadRequest)] + [ProducesResponseType(StatusCodes.Status409Conflict)] + [ProducesResponseType(StatusCodes.Status500InternalServerError)] + public async Task CreateUser([FromBody] UserDTO newUser) + { + try + { + if (newUser == null) + { + return BadRequest(new { message = "User data is required." }); + } + + try + { + var existingPlayer = await _user.GetUserById(newUser.Id); + return Conflict(new { message = "A user with this ID already exists." }); + } + catch(KeyNotFoundException e) + { + _user.AddUser(newUser); + + return CreatedAtAction(nameof(GetAllUsers), new { id = newUser.Id }, newUser); + } + } + catch (Exception e) + { + return StatusCode((int)HttpStatusCode.InternalServerError, new { message = "Erreur interne du serveur." + e.Message }); + } + } + + + + //===================================== ROUTE DELETE ===================================== + + /// + /// Deletes a player by their ID. + /// + /// The ID of the player to be deleted + /// + /// + /// ## **Sample request**: + /// + /// DELETE /api/v1/players?id=51 + /// + /// The `id` parameter specifies the ID of the player to be deleted. + /// + /// ## **Returns** + /// + /// - **200 OK** : If the player was successfully deleted, a success message is returned. + /// - **404 Not Found** : If no player with the given ID is found. + /// - **500 Internal Server Error** : If an error occurs while deleting the player. + /// + /// ## **Error Handling** + /// - If no player is found with the specified `id`, a `404 Not Found` response is returned with a message "Player not found." + /// - If there is an exception during the process (e.g., database errors), a `500 Internal Server Error` response is returned with a message "Internal server error." + /// + /// Returns a success message indicating the player was deleted + /// Not found if no player with the specified ID is found + /// Internal server error in case of an exception + [HttpDelete] // /api/v1/players?id=51 + [ProducesResponseType(StatusCodes.Status200OK)] + [ProducesResponseType(StatusCodes.Status404NotFound)] + [ProducesResponseType(StatusCodes.Status500InternalServerError)] + public async Task DeletePlayer([FromQuery] int id) + { + try + { + + var existingPlayer = _user.GetUserById(id).Result; + if (existingPlayer == null) + { + return NotFound(new { message = "Player not found." }); + } + + await _user.RemoveUser(id); + + return Ok(new { message = $"User {id} deleted successfully." }); + } + catch (Exception) + { + return StatusCode((int)HttpStatusCode.InternalServerError, new { message = "Internal server error." }); + } + } + } +} diff --git a/WF_EF_Api/WfApi/Dockerfile b/WF_EF_Api/WfApi/Dockerfile new file mode 100644 index 0000000..a318a5b --- /dev/null +++ b/WF_EF_Api/WfApi/Dockerfile @@ -0,0 +1,25 @@ +#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 ["WfApi/WfApi.csproj", "WfApi/"] +RUN dotnet restore "./WfApi/WfApi.csproj" +COPY . . +WORKDIR "/src/WfApi" +RUN dotnet build "./WfApi.csproj" -c $BUILD_CONFIGURATION -o /app/build + +FROM build AS publish +ARG BUILD_CONFIGURATION=Release +RUN dotnet publish "./WfApi.csproj" -c $BUILD_CONFIGURATION -o /app/publish /p:UseAppHost=false + +FROM base AS final +WORKDIR /app +COPY --from=publish /app/publish . +ENTRYPOINT ["dotnet", "WfApi.dll"] \ No newline at end of file diff --git a/WF_EF_Api/WfApi/Program.cs b/WF_EF_Api/WfApi/Program.cs new file mode 100644 index 0000000..71bbd5b --- /dev/null +++ b/WF_EF_Api/WfApi/Program.cs @@ -0,0 +1,83 @@ +using DTO; +using Shared; +using StubApi; +using Contextlib; +using Entity; +using StubbedContextLib; +using ServicesApi; +using Microsoft.EntityFrameworkCore; + +//API +var builder = WebApplication.CreateBuilder(args); + +builder.Services.AddScoped, UserService>(); +builder.Services.AddScoped, QuoteService>(); +builder.Services.AddScoped, FavoriteService>(); +builder.Services.AddScoped, CommentaryService>(); +builder.Services.AddScoped, CharacterService>(); +builder.Services.AddScoped, ImageService>(); +builder.Services.AddScoped, SourceService>(); +builder.Services.AddScoped, QuestionService>(); + + +//EF +builder.Services.AddScoped(); + + +builder.Services.AddScoped, DbUsersManager>(); +builder.Services.AddScoped, DbQuoteManager>(); +builder.Services.AddScoped, DbFavoriteManager>(); +builder.Services.AddScoped, DbCommentaryManager>(); +builder.Services.AddScoped, DbCharacterManager>(); +builder.Services.AddScoped, DbImagesManager>(); +builder.Services.AddScoped, DbSourceManager>(); +builder.Services.AddScoped, DbQuestionManager>(); +//... + +// Add services to the container. + +builder.Services.AddControllers(); +builder.Services.AddOpenApiDocument(options => { + options.PostProcess = document => + { + document.Info = new NSwag.OpenApiInfo + { + Version = "v1", + Title = "What The Fantasy's API", + Description = "What The Fantasy Site API", + TermsOfService = "", + Contact = new NSwag.OpenApiContact + { + Name = "The PM Mobile What The Fantasy team", + Url = "" + }, + License = new NSwag.OpenApiLicense + { + Name = "No license", + Url = "https://license.fr" + } + }; + }; +}); + + +// Learn more about configuring Swagger/OpenAPI at https://aka.ms/aspnetcore/swashbuckle +builder.Services.AddEndpointsApiExplorer(); +builder.Services.AddSwaggerGen(); + +var app = builder.Build(); + +// Configure the HTTP request pipeline. +if (app.Environment.IsDevelopment()) +{ + app.UseOpenApi(); // Active la documentation OpenAPI + app.UseSwaggerUI(); +} + +app.UseHttpsRedirection(); + +app.UseAuthorization(); + +app.MapControllers(); + +app.Run(); diff --git a/WF_EF_Api/WfApi/Properties/launchSettings.json b/WF_EF_Api/WfApi/Properties/launchSettings.json new file mode 100644 index 0000000..6e4ee26 --- /dev/null +++ b/WF_EF_Api/WfApi/Properties/launchSettings.json @@ -0,0 +1,52 @@ +{ + "profiles": { + "http": { + "commandName": "Project", + "launchBrowser": true, + "launchUrl": "swagger", + "environmentVariables": { + "ASPNETCORE_ENVIRONMENT": "Development" + }, + "dotnetRunMessages": true, + "applicationUrl": "http://localhost:5239" + }, + "https": { + "commandName": "Project", + "launchBrowser": true, + "launchUrl": "swagger", + "environmentVariables": { + "ASPNETCORE_ENVIRONMENT": "Development" + }, + "dotnetRunMessages": true, + "applicationUrl": "https://localhost:7250;http://localhost:5239" + }, + "IIS Express": { + "commandName": "IISExpress", + "launchBrowser": true, + "launchUrl": "swagger", + "environmentVariables": { + "ASPNETCORE_ENVIRONMENT": "Development" + } + }, + "Container (Dockerfile)": { + "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:23612", + "sslPort": 44320 + } + } +} \ No newline at end of file diff --git a/WF_EF_Api/WfApi/WfApi.csproj b/WF_EF_Api/WfApi/WfApi.csproj new file mode 100644 index 0000000..638d2f5 --- /dev/null +++ b/WF_EF_Api/WfApi/WfApi.csproj @@ -0,0 +1,33 @@ + + + + net8.0 + enable + enable + 283a610b-b95e-4b09-af22-b7d3270a917d + Linux + true + $(NoWarn);1591 + + + + + all + runtime; build; native; contentfiles; analyzers; buildtransitive + + + + + + + + + + + + + + + + + diff --git a/WF_EF_Api/WfApi/WfApi.http b/WF_EF_Api/WfApi/WfApi.http new file mode 100644 index 0000000..4fd1d65 --- /dev/null +++ b/WF_EF_Api/WfApi/WfApi.http @@ -0,0 +1,6 @@ +@WfApi_HostAddress = http://localhost:5239 + +GET {{WfApi_HostAddress}}/weatherforecast/ +Accept: application/json + +### diff --git a/WF_EF_Api/WfApi/appsettings.Development.json b/WF_EF_Api/WfApi/appsettings.Development.json new file mode 100644 index 0000000..ff66ba6 --- /dev/null +++ b/WF_EF_Api/WfApi/appsettings.Development.json @@ -0,0 +1,8 @@ +{ + "Logging": { + "LogLevel": { + "Default": "Information", + "Microsoft.AspNetCore": "Warning" + } + } +} diff --git a/WF_EF_Api/WfApi/appsettings.json b/WF_EF_Api/WfApi/appsettings.json new file mode 100644 index 0000000..4d56694 --- /dev/null +++ b/WF_EF_Api/WfApi/appsettings.json @@ -0,0 +1,9 @@ +{ + "Logging": { + "LogLevel": { + "Default": "Information", + "Microsoft.AspNetCore": "Warning" + } + }, + "AllowedHosts": "*" +} diff --git a/WF_EF_Api/XUnitTest/ApiUnitTest.cs b/WF_EF_Api/XUnitTest/ApiUnitTest.cs new file mode 100644 index 0000000..8692e14 --- /dev/null +++ b/WF_EF_Api/XUnitTest/ApiUnitTest.cs @@ -0,0 +1,283 @@ +using Microsoft.AspNetCore.Mvc; +using Microsoft.Extensions.Logging; +using Moq; + + +using WfApi.Controllers; +using Shared; +using DTO; + +namespace XUnitTest +{ + public class UnitTest1 + { + //private readonly Mock> _mockUserService; + //private readonly Mock> _mockLogger; + //private readonly UsersController _userController; + + //public UnitTest1() + //{ + // // Initialisation des mocks + // _mockUserService = new Mock>(); + // _mockLogger = new Mock>(); + // _userController = new UsersController(_mockUserService.Object, _mockLogger.Object); + //} + + + + //[Fact] + //public async Task Get_ReturnsOk_WhenUserExists() + //{ + // // Arrange + // var userId = 1; + // var userDTO = new UserDTO + // { + // Id = userId, + // Pseudo = "test", + // Email = "test@unitaire.fr", + // ImageProfil = "http://test", + // Password = "1234" + // }; + + // _mockUserService.Setup(service => service.GetUserById(userId)).ReturnsAsync(userDTO); + + // // Act + // var result = await _userController.Get(userId); + + // // Assert + // Assert.IsType(result); + //} + + + + + //[Fact] + //public async Task GetAllUsers_ReturnsOk() + //{ + // // Arrange + // var userDTO = new UserDTO + // { + // Id = 1, + // Pseudo = "test", + // Email = "test@unitaire.fr", + // ImageProfil = "http://test", + // Password = "1234" + // }; + // var userDTO2 = new UserDTO + // { + // Id = 2, + // Pseudo = "test", + // Email = "test@unitaire.fr", + // ImageProfil = "http://test", + // Password = "1234" + // }; + + // _mockUserService.Setup(service => service.GetUserById(1)).ReturnsAsync(userDTO); + // _mockUserService.Setup(service => service.GetUserById(2)).ReturnsAsync(userDTO); + + // // Act + // var result = await _userController.GetAllUsers(); + + // // Assert + // Assert.IsType(result); + //} + + + + //[Fact] + //public async Task GetHashPassword_ReturnsOk_WhenPasswordHashIsFound() + //{ + // // Arrange + // var username = "testUser"; + // var expectedHash = "hashedPassword"; + + // var taskResult = Task.FromResult(expectedHash); + // _mockUserService.Setup(service => service.GetHashPassword(username)).Returns(taskResult); + + // // Act + // var result = await _userController.GetHashPassword(username); + + // // Assert + // Assert.IsType(result); + //} + + //[Fact] + //public async Task GetUserByUsername_ReturnsOk_WhenPasswordHashIsFound() + //{ + // // Arrange + // var username = "testUser"; + // var userDTO = new UserDTO + // { + // Id = 1, + // Pseudo = "testUser", + // Email = "test@unitaire.fr", + // ImageProfil = "http://test", + // Password = "1234" + // }; + + // var taskResult = Task.FromResult(userDTO); + // _mockUserService.Setup(service => service.GetUserByUsername(username)).Returns(taskResult); + + // // Act + // var result = await _userController.GetUserByUsername(username); + + // // Assert + // Assert.IsType(result); + //} + + //[Fact] + //public async Task GetUserByEmail_ReturnsOk_WhenUserExists() + //{ + // // Arrange + // var email = "test@unitaire.fr"; + // var userDTO = new UserDTO + // { + // Id = 1, + // Pseudo = "testUser", + // Email = email, + // ImageProfil = "http://test", + // Password = "1234" + // }; + + + // var taskResult = Task.FromResult(userDTO); + // _mockUserService.Setup(service => service.GetUserByEmail(email)).Returns(taskResult); + + // // Act + // var result = await _userController.GetUserByEmail(email); + + // // Assert + // Assert.IsType(result); + //} + + //[Fact] + //public async Task GetCountUser_ReturnsOk_WhenCountIsSuccessful() + //{ + // // Arrange + // var expectedCount = 5; + // var taskResult = Task.FromResult(expectedCount); + + // _mockUserService.Setup(service => service.CountUser()).Returns(taskResult); + + // // Act + // var result = await _userController.GetCountUser(); + + // // Assert + // Assert.IsType(result); + //} + + //[Fact] + //public async Task GetExistUsername_ReturnsOk_WhenUserExists() + //{ + // // Arrange + // var username = "testUser"; + // var taskResult = Task.FromResult(true); + + + // _mockUserService.Setup(service => service.ExistUsername(username)).Returns(taskResult); + + // // Act + // var result = await _userController.GetExistUsername(username); + + // // Assert + // Assert.IsType(result); + + //} + + //[Fact] + //public async Task GetExistEmail_ReturnsOk_WhenEmailExists() + //{ + // // Arrange + // var email = "test@unitaire.fr"; + // var taskResult = Task.FromResult(true); + + // _mockUserService.Setup(service => service.ExistEmail(email)).Returns(taskResult); + + // // Act + // var result = await _userController.GetExistEmail(email); + + // // Assert + // Assert.IsType(result); + + //} + //[Fact] + //public async Task UpdateUser_ReturnsOk_WhenUserDataIsValid() + //{ + // // Arrange + // var id = 1; + // var updatedUser = new UserDTO + // { + // Id = id, + // Pseudo = "UpdatedUser", + // Email = "updated@unitaire.fr", + // ImageProfil = "http://updatedImage.com", + // Password = "newPassword123" + // }; + + // var taskResult = Task.FromResult(updatedUser); + + // _mockUserService.Setup(service => service.UpdateUser(id, updatedUser)).Returns(taskResult); + + // // Act + // var result = await _userController.UpdateUser(id, updatedUser); + + // // Assert + // var okResult = Assert.IsType(result); + + // Assert.IsType(result); + //} + //[Fact] + //public async Task CreateUser_ReturnsCreatedAtAction_WhenUserIsValid() + //{ + // // Arrange + // var newUser = new UserDTO + // { + // Id = 2, + // Pseudo = "NewUser", + // Email = "newuser@unitaire.fr", + // ImageProfil = "http://newuserimage.com", + // Password = "newPassword123" + // }; + + // _mockUserService.Setup(service => service.GetUserById(newUser.Id)).ReturnsAsync((UserDTO)null); + + // _mockUserService.Setup(service => service.AddUser(newUser)).Verifiable(); + + // // Act + // var result = await _userController.CreateUser(newUser); + + // // Assert + // var createdResult = Assert.IsType(result); + // Assert.Equal(newUser.Id, createdResult.RouteValues["id"]); + //} + + + //[Fact] + //public async Task DeletePlayer_ReturnsOk_WhenPlayerExists() + //{ + // // Arrange + // var id = 1; + // var existingPlayer = new UserDTO + // { + // Id = id, + // Pseudo = "ExistingUser", + // Email = "existing@unitaire.fr", + // ImageProfil = "http://existingimage.com", + // Password = "existingPassword123" + // }; + + // _mockUserService.Setup(service => service.GetUserById(id)).ReturnsAsync(existingPlayer); + + // _mockUserService.Setup(service => service.RemoveUser(existingPlayer.Id)).Verifiable(); + + // // Act + // var result = await _userController.DeletePlayer(id); + + // // Assert + // Assert.IsType(result); + + //} + + + } +} \ No newline at end of file diff --git a/WF_EF_Api/XUnitTest/XUnitTest.csproj b/WF_EF_Api/XUnitTest/XUnitTest.csproj new file mode 100644 index 0000000..0578038 --- /dev/null +++ b/WF_EF_Api/XUnitTest/XUnitTest.csproj @@ -0,0 +1,36 @@ + + + + net8.0 + enable + enable + + false + true + + + + + + all + runtime; build; native; contentfiles; analyzers; buildtransitive + + + + + + + + + + + + + + + + + + + +