From b9b995a99b824f6f8a20309d115b21c08ac0216a Mon Sep 17 00:00:00 2001 From: Emre Date: Fri, 3 Mar 2023 20:08:38 +0100 Subject: [PATCH 01/10] Comple ChampionHttpClient --- .vs/LolProjects/v17/.suo | Bin 0 -> 11776 bytes .../Sources/Client/ChampionHttpClient.cs | 6 +++--- 2 files changed, 3 insertions(+), 3 deletions(-) create mode 100644 .vs/LolProjects/v17/.suo diff --git a/.vs/LolProjects/v17/.suo b/.vs/LolProjects/v17/.suo new file mode 100644 index 0000000000000000000000000000000000000000..ba24d1abde67da4a6a26e1494102fb8304a01450 GIT binary patch literal 11776 zcmeHN&2Jk;6n{=A(DGS60+a#GOOZ$u>ZIY2iyg0%H2#w9&?1Dy zjVo~D1{b6rIPgbstjd)e+>!VTX!!kRckJ=nyBXU_niRiiyt6ZJ=FR(>_hvS~-#`E7 zPrqLHOMEaV!}4JNtUPYCM~u2WFY+AT+4f+6f1h2fqdI_7B!L@J#$R2caz#pbR^>630n3Rpo^9F#OJiOb6|%$=|6_{ArxEw-vF-mYs%qYlL6FU@aAIkdDN+@mrs2fMVkL>nB@6kM`=) z$ao4W2iZZbB#Y`dkIZ8WtyPr+xjj%~2Y3(p2Xh21r4A@#( zITth0n%tCR+gN|YJD|^eQs*T8{!Z^)FY_hBBDl|h7OCxk^6j=&xOhRo$iEuAQwBkJ zW;^X)zh4H;EF`^!Kjxk5O5&TcjklUc3VB9*pwGRWzDihtzRSo)i=bP@(>CvQM~hs9 z{CVzUtgz+(B5*Hx6Raxf@5(2TehpergLCHKb=g!_d5{d4{|;j=9eccKLm#iB*GoUt zd4m>Lh0SGP3szHfB52a;*FnD|ImqC)tl+nX_c{uF zvy&{w!9U}&&c8z$_c|Hhf1}a>e)}W;q@Tt)un5cK?hpp=_RW8*{VzcdMNs8A)RaXh z-nlO9KVADDZDrMC%Fq7-C_Au(U7QBXN*3IS%$0Zpy~h;f&say>C$#o_giGzOdBQ$AUSMm_@F zGTtk49T>D$S0i(v<~`Z%d!1N1G+s(q9F2+9G|SVt4}lFG6`T$FQYOx|)6(-nR)) zBX^%;?i@I)${6gwH7<@}hbn{foZ1QYAg4N~5%Ay8y)FGWF;45h8~Th>b?n%T$|bCN z8}rQfK>sa_)93%Rvi7Q)jaEhqH_*0;LLNVb&M6Vb##&>S#snTDL7(x2xt=Zm=KdF^ z{}oUz;m?88uPUyacBkpX{=1exZC~p@jQ&lk4}^Ug`K7Mt@yp0VP?6#Zw!UgC8b);GemVKL5@*+1ONS#))N<`9v(2%Fo2}+01l) zditw{SbB9fIXgc4Wj>S5r{WW-*wjJjDQk2pfP&}~KD*D%uXh-2%YbSUMJ_mwzX|LE z{0##yjE13D^_~0Xhq-%q|M}Jm*+430YIUc&_e-zisfK=d=yyErupj#LBaUy*QJKf9 zHT1iFYeE5t&2o)>*CU4JdZDHBm|n(m4CTLqvM95%A#2#v8SQGQ zGxuSAL*)WI3o|BesOZStkT}c<3SRbb3%xuku-zW|)jxMXcP}?Bc@3?c`5Lz|^DowT z3$K}DSU)o0S$qkyb~C#)l?oWq*4n|V$%egFMq=ljoKXe!q&t4 zSANgpow_am%-MtJH}Bth+v=VTaCVd^7DTR_20OAv*rI0(|_bJ z_20BV>+e6x|M*SMR{qTQfUdxAe}nHoyz@T3??2p&xqnk5ynpQW{O3Qvw4N?Qu8T={ PaQ`cQ`6;J3#-INH+C5Wo literal 0 HcmV?d00001 diff --git a/src/EntityFramework_LoL/Sources/Client/ChampionHttpClient.cs b/src/EntityFramework_LoL/Sources/Client/ChampionHttpClient.cs index 2fa8957..21155ed 100644 --- a/src/EntityFramework_LoL/Sources/Client/ChampionHttpClient.cs +++ b/src/EntityFramework_LoL/Sources/Client/ChampionHttpClient.cs @@ -28,15 +28,15 @@ namespace Client await _httpClient.PostAsJsonAsync(ApiChampions, champion); } -/* public async void Delete(ChampionDto champion) + public async void Delete(ChampionDto champion) { - await _httpClient.DeleteAsync(champion); + await _httpClient.DeleteAsync(champion.Name); } public async void Update(ChampionDto champion) { await _httpClient.PutAsJsonAsync(ApiChampions, champion); - }*/ + } } } -- 2.36.3 From 72dc884125532513e3ec519adb199c54a5a077ef Mon Sep 17 00:00:00 2001 From: Emre Date: Fri, 3 Mar 2023 20:13:41 +0100 Subject: [PATCH 02/10] Correcting README and add deploy container into drone.yml --- .drone.yml | 14 +++++++- README.md | 32 +++++++++---------- .../Sources/ApiLol/Program.cs | 8 ++--- 3 files changed, 31 insertions(+), 23 deletions(-) diff --git a/.drone.yml b/.drone.yml index 7fdb81f..89479ad 100644 --- a/.drone.yml +++ b/.drone.yml @@ -46,6 +46,7 @@ steps: from_secret: SECRET_SONAR_LOGIN depends_on: [tests] # docker image build + - name: docker-build-and-push image: plugins/docker settings: @@ -57,6 +58,17 @@ steps: from_secret: SECRET_REGISTRY_USERNAME password: from_secret: SECRET_REGISTRY_PASSWORD + + # container deployment + - name: deploy-container + image: hub.codefirst.iut.uca.fr/thomas.bellembois/codefirst-dockerproxy-clientdrone:latest + environment: + IMAGENAME: hub.codefirst.iut.uca.fr/emre.kartal/lolproject:latest + CONTAINERNAME: lolApi + COMMAND: create + OVERWRITE: true + depends_on: [ docker-build-and-push ] + - name: generate-and-deploy-docs image: hub.codefirst.iut.uca.fr/thomas.bellembois/codefirst-docdeployer failure: ignore @@ -74,4 +86,4 @@ steps: #volumes: #- name: docs - # temp: {} + # temp: {} \ No newline at end of file diff --git a/README.md b/README.md index d8f3407..f6ddbc1 100644 --- a/README.md +++ b/README.md @@ -5,12 +5,12 @@ -**Thème du projet** : Réalisation d'une API et d'un ORM(Entity Framework) qui seront reliés à une base de données dans le thème de League of Legends +**Thème du projet** : Réalisation d'une API et d'un ORM (Entity Framework) qui seront reliés à une base de données dans le thème de League of Legends
-La racine de notre gitlab est composée de deux dossiers essentiels au projet: +La racine de mon GitLab contient deux dossiers essentiels pour le projet : [**src**](src) : **Toute la partie codage de l'application** @@ -23,7 +23,7 @@ La racine de notre gitlab est composée de deux dossiers essentiels au projet: - ### Comment récupérer le projet ? -Tout d'abord si ce n'est pas fait cloner le dépôt de la branche **master/main**, pour cela copier le lien URL du dépôt git : +Tout d'abord, si ce n'est pas déjà fait, clonez le dépôt de la branche **master/main**. Pour ce faire, copiez le lien URL du dépôt git :
@@ -31,7 +31,7 @@ Tout d'abord si ce n'est pas fait cloner le dépôt de la branche **master/main*
-Vous pouvez le cloner via un terminal dans le répertoire que vous souhaitez en tapant la commande : **git clone https://codefirst.iut.uca.fr/git/emre.kartal/LolProject.git** ou utiliser Visual Studio et cloner en entrant le lien : +Vous pouvez le cloner via un terminal dans le répertoire de votre choix en utilisant la commande : **git clone https://codefirst.iut.uca.fr/git/emre.kartal/LolProject.git**. Sinon, vous pouvez utiliser Visual Studio et cloner le dépôt en entrant le lien :
@@ -39,16 +39,14 @@ Vous pouvez le cloner via un terminal dans le répertoire que vous souhaitez en
-:information_source: *Si vous ne disposez pas de Visual Studio, allé sur le site [Microsoft Visual Studio](https://visualstudio.microsoft.com/fr/downloads/) pour pouvoir le télécharger !!!* +:information_source: *Si vous ne disposez pas de Visual Studio, allez sur le site [Microsoft Visual Studio](https://visualstudio.microsoft.com/fr/downloads/) pour pouvoir le télécharger !!!* - ### Comment lancer Le projet Entity Framework ? -Afin de générer les migrations et les tables. -
-Vous devez avoir installé correctement EntityFrameworkCore, pour cela il existe la commande : **dotnet tool install --global dotnet-ef** qui peut être lancé à partir d'un terminal, si il est déjà installer mais n'a pas la bonne version : **dotnet tool update --global dotnet-ef** (oui y que le *install* qui change vous êtes perspicace)! +Afin de générer les migrations et les tables, vous devez avoir installé correctement EntityFrameworkCore. Pour cela il existe la commande : **dotnet tool install --global dotnet-ef**, qui peut être lancé à partir d'un terminal. Si elle est déjà installée mais n'a pas la bonne version : **dotnet tool update --global dotnet-ef** (oui, il n'y a que l'*install* qui change. Vous êtes perspicace !). -Aussi assurer vous d'avoir installé sur Visual Studio au préalable les package Nuget suivants : +Assurez-vous également d'avoir installé les packages Nuget suivants sur Visual Studio au préalable :
@@ -56,13 +54,13 @@ Aussi assurer vous d'avoir installé sur Visual Studio au préalable les package
-Ensuite sur le terminal PowerShell ou Visual Studio, lancer la migration via la commande : **dotnet ef migrations add monNomDeMigration** (n'oublier pas de vous situer dans le dossier "/MyFlib" lorsque vous l'exécuter)! +Ensuite, sur le terminal PowerShell ou Visual Studio, lancer la migration via la commande : **dotnet ef migrations add monNomDeMigration** (n'oubliez pas de vous situer dans le dossier "/MyFlib" lorsque vous l'exécutez)! - ### Comment voir la base de données ? -C'est bien beau toutes ces étapes mais s’il n'y a pas de résultat à quoi cela sert ! +C'est bien beau toutes ces étapes, mais s’il n'y a pas de résultat, à quoi cela sert ! -Tout d'abord veuillez regarder dans l'onglet extension, si l'outil **SQLite and SQL Server Compact Toolbax** est bien installé. +Tout d'abord, veuillez regarder dans l'onglet Extensions si l'outil **SQLite and SQL Server Compact Toolbax** est bien installé. Puis, afin de visualiser la migration dans la base de données, cliquer dans l'onglet **Outils**->**SQLLite/ SQL Server compact Toolbox** : @@ -72,7 +70,7 @@ Puis, afin de visualiser la migration dans la base de données, cliquer dans l'o -Et enfin cliquer sur l'icône ci-dessous pour faire la connexion à la solution courent : +Et enfin cliquez sur l'icône ci-dessous pour établir la connexion à la solution en cours :
@@ -80,14 +78,14 @@ Et enfin cliquer sur l'icône ci-dessous pour faire la connexion à la solution
-Vous pouvez dorénavant voir toutes les tables qui y sont enregistrées ! Si vous souhaitez ajouter des modifications à la base de données et les visualiser, -réaliser à nouveau la migration (ou *updater* celui actuel), puis supprimer toutes les tables et lancer la commande : **dotnet ef database update** et enfin rafraichissez la BD ! +Vous pouvez désormais voir toutes les tables qui y sont enregistrées ! Si vous souhaitez ajouter des modifications à la base de données et les visualiser, +réalisez à nouveau la migration (ou mettez à jour celle actuelle), puis supprimez toutes les tables et lancez la commande : **dotnet ef database update** et enfin rafraîchissez la base de données ! -:information_source: *Notez qu'il est également possible grâce à SQLLite d'ajouter, modifier ou supprimer des données dans les tables.* +:information_source: *Notez qu'il est également possible, grâce à SQLLite, d'ajouter, modifier ou supprimer des données dans les tables.* -Mon environnement de travail se base sur un outil et un langage en particulier :👇 +Mon environnement de travail est basé sur un outil et un langage en particulier : 👇
diff --git a/src/EntityFramework_LoL/Sources/ApiLol/Program.cs b/src/EntityFramework_LoL/Sources/ApiLol/Program.cs index e6ed0a5..0e7a608 100644 --- a/src/EntityFramework_LoL/Sources/ApiLol/Program.cs +++ b/src/EntityFramework_LoL/Sources/ApiLol/Program.cs @@ -14,11 +14,9 @@ builder.Services.AddSingleton(); var app = builder.Build(); // Configure the HTTP request pipeline. -if (app.Environment.IsDevelopment()) -{ - app.UseSwagger(); - app.UseSwaggerUI(); -} +app.UseSwagger(); +app.UseSwaggerUI(); + app.UseHttpsRedirection(); -- 2.36.3 From ec07596ea36f2a05c2346259875b06ec6702bcdb Mon Sep 17 00:00:00 2001 From: Emre Date: Fri, 3 Mar 2023 20:26:56 +0100 Subject: [PATCH 03/10] Realized Logs and pagination --- .../ApiLol/Controllers/ChampionsController.cs | 46 +++++++++++++++---- .../Sources/DTO/PageRequest.cs | 14 ++++++ .../Tests/ApiTests/ChampionsControllerTest.cs | 9 ++-- 3 files changed, 58 insertions(+), 11 deletions(-) create mode 100644 src/EntityFramework_LoL/Sources/DTO/PageRequest.cs diff --git a/src/EntityFramework_LoL/Sources/ApiLol/Controllers/ChampionsController.cs b/src/EntityFramework_LoL/Sources/ApiLol/Controllers/ChampionsController.cs index 1680ad1..ae1ada6 100644 --- a/src/EntityFramework_LoL/Sources/ApiLol/Controllers/ChampionsController.cs +++ b/src/EntityFramework_LoL/Sources/ApiLol/Controllers/ChampionsController.cs @@ -13,16 +13,26 @@ namespace ApiLol.Controllers public class ChampionsController : ControllerBase { private readonly IDataManager _manager; - public ChampionsController(IDataManager dataManager) + public readonly ILogger _logger; + public ChampionsController(IDataManager dataManager, ILogger logger) { + _logger = logger; this._manager = dataManager; } // GET: api/ [HttpGet] - public async Task Get() + public async Task Get([FromQuery] PageRequest pageRequest) { - IEnumerable dtos = (await _manager.ChampionsMgr.GetItems(0, await _manager.ChampionsMgr.GetNbItems())) + int nbTotal = await _manager.ChampionsMgr.GetNbItems(); + if (pageRequest.count + pageRequest.index > nbTotal) + { + _logger.LogWarning($"too many, maximum {nbTotal}"); + pageRequest.count = 10; + } + + _logger.LogInformation($"method Get call"); + IEnumerable dtos = (await _manager.ChampionsMgr.GetItems(pageRequest.index, pageRequest.count)) .Select(x => x.ToDto()); return Ok(dtos); } @@ -31,10 +41,12 @@ namespace ApiLol.Controllers [HttpGet("{name}")] public async Task Get(string name) { - var dtos = (await _manager.ChampionsMgr.GetItemsByName(name,0, await _manager.ChampionsMgr.GetNbItems())) + _logger.LogInformation($"method GetByName call with {name}"); + var dtos = (await _manager.ChampionsMgr.GetItemsByName(name, 0, await _manager.ChampionsMgr.GetNbItems())) .Select(x => x.ToDto()); - if(dtos.IsNullOrEmpty()) + if (dtos.IsNullOrEmpty()) { + _logger.LogWarning($"{name} was not found"); return NotFound(); } return Ok(dtos); @@ -44,6 +56,12 @@ namespace ApiLol.Controllers [HttpPost] public async Task Post([FromBody] ChampionDto champion) { + _logger.LogInformation($"method Post call"); + var dtos = (await _manager.ChampionsMgr.GetItemsByName(champion.Name, 0, await _manager.ChampionsMgr.GetNbItems())); + if (!dtos.IsNullOrEmpty()) + { + return BadRequest("Name is already exist"); + } return CreatedAtAction(nameof(Get), (await _manager.ChampionsMgr.AddItem(champion.ToModel())).ToDto()); } @@ -52,10 +70,20 @@ namespace ApiLol.Controllers [HttpPut("{name}")] public async Task Put(string name, [FromBody] ChampionDto champion) { + _logger.LogInformation($"method Put call with {name}"); var dtos = (await _manager.ChampionsMgr.GetItemsByName(name, 0, await _manager.ChampionsMgr.GetNbItems())); - if(dtos.IsNullOrEmpty()) + if (dtos.IsNullOrEmpty()) { - return BadRequest(); + return BadRequest("Name not exist"); + } + // Checks if the new name exists + if (name != champion.Name) + { + var dtos2 = (await _manager.ChampionsMgr.GetItemsByName(champion.Name, 0, await _manager.ChampionsMgr.GetNbItems())); + if (!dtos.IsNullOrEmpty()) + { + return BadRequest("Name is already exist"); + } } return Ok(await _manager.ChampionsMgr.UpdateItem(dtos.First(), champion.ToModel())); } @@ -64,12 +92,14 @@ namespace ApiLol.Controllers [HttpDelete("{name}")] public async Task Delete(string name) { + _logger.LogInformation($"method Delete call with {name}"); var dtos = (await _manager.ChampionsMgr.GetItemsByName(name, 0, await _manager.ChampionsMgr.GetNbItems())); if (dtos.IsNullOrEmpty()) { + _logger.LogWarning($"{name} was not found"); return BadRequest(); } return Ok(await _manager.ChampionsMgr.DeleteItem(dtos.First())); } } -} +} \ No newline at end of file diff --git a/src/EntityFramework_LoL/Sources/DTO/PageRequest.cs b/src/EntityFramework_LoL/Sources/DTO/PageRequest.cs new file mode 100644 index 0000000..2613958 --- /dev/null +++ b/src/EntityFramework_LoL/Sources/DTO/PageRequest.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 PageRequest + { + public int index { get; set; } = 0; + public int count { get; set; } = 10; + } +} diff --git a/src/EntityFramework_LoL/Sources/Tests/ApiTests/ChampionsControllerTest.cs b/src/EntityFramework_LoL/Sources/Tests/ApiTests/ChampionsControllerTest.cs index 5546a25..590e9e1 100644 --- a/src/EntityFramework_LoL/Sources/Tests/ApiTests/ChampionsControllerTest.cs +++ b/src/EntityFramework_LoL/Sources/Tests/ApiTests/ChampionsControllerTest.cs @@ -1,6 +1,8 @@ using ApiLol.Controllers; using DTO; using Microsoft.AspNetCore.Mvc; +using Microsoft.Extensions.Logging; +using Microsoft.Extensions.Logging.Abstractions; using Model; using StubLib; @@ -14,7 +16,7 @@ namespace ApiTests public ChampionsControllerTest() { stub = new StubData(); - champs = new ChampionsController(stub); + champs = new ChampionsController(stub, new NullLogger()); } [TestMethod] @@ -23,7 +25,8 @@ namespace ApiTests //Arrange //Act - var champion = await champs.Get(); + var total = await stub.ChampionsMgr.GetNbItems(); + var champion = await champs.Get(new PageRequest()); //Assert var objectResult = champion as OkObjectResult; @@ -32,7 +35,7 @@ namespace ApiTests var champions = objectResult?.Value as IEnumerable; Assert.IsNotNull(champions); - Assert.AreEqual(champions.Count(), await stub.ChampionsMgr.GetNbItems()); + Assert.AreEqual(champions.Count(), total); } -- 2.36.3 From 1a8f5c8c6cee4caad98b4eb3233790d65e8cb15d Mon Sep 17 00:00:00 2001 From: Emre Date: Fri, 3 Mar 2023 20:53:32 +0100 Subject: [PATCH 04/10] Add new DTO and mapper --- .../ApiLol/Controllers/ChampionsController.cs | 2 +- .../Sources/ApiLol/Mapper/ChampionMapper.cs | 5 +- .../Sources/ApiLol/Mapper/LargeImageMapper.cs | 21 +++++++ .../Sources/ApiLol/Mapper/RuneMapper.cs | 2 +- .../Sources/ApiLol/Mapper/SkillMapper.cs | 2 +- .../Sources/ApiLol/Mapper/SkinMapper.cs | 11 +++- .../Mapper/enums/ChampionClassMapper.cs | 4 +- .../ApiLol/Mapper/enums/SkillTypeMapper.cs | 58 +++++++++++++++++++ .../Sources/Client/Program.cs | 2 +- .../Sources/DTO/ChampionDto.cs | 2 +- .../Sources/DTO/LargeImageDto.cs | 13 +++++ .../Sources/DTO/SkinDto.cs | 1 + .../Sources/DTO/enums/SkillTypeDto.cs | 16 +++++ .../Tests/ApiTests/ChampionsControllerTest.cs | 2 +- 14 files changed, 129 insertions(+), 12 deletions(-) create mode 100644 src/EntityFramework_LoL/Sources/ApiLol/Mapper/LargeImageMapper.cs create mode 100644 src/EntityFramework_LoL/Sources/ApiLol/Mapper/enums/SkillTypeMapper.cs create mode 100644 src/EntityFramework_LoL/Sources/DTO/LargeImageDto.cs create mode 100644 src/EntityFramework_LoL/Sources/DTO/enums/SkillTypeDto.cs diff --git a/src/EntityFramework_LoL/Sources/ApiLol/Controllers/ChampionsController.cs b/src/EntityFramework_LoL/Sources/ApiLol/Controllers/ChampionsController.cs index ae1ada6..52d7185 100644 --- a/src/EntityFramework_LoL/Sources/ApiLol/Controllers/ChampionsController.cs +++ b/src/EntityFramework_LoL/Sources/ApiLol/Controllers/ChampionsController.cs @@ -28,7 +28,7 @@ namespace ApiLol.Controllers if (pageRequest.count + pageRequest.index > nbTotal) { _logger.LogWarning($"too many, maximum {nbTotal}"); - pageRequest.count = 10; + return BadRequest("Champion limit exceed"); } _logger.LogInformation($"method Get call"); diff --git a/src/EntityFramework_LoL/Sources/ApiLol/Mapper/ChampionMapper.cs b/src/EntityFramework_LoL/Sources/ApiLol/Mapper/ChampionMapper.cs index dbb9679..fed7f20 100644 --- a/src/EntityFramework_LoL/Sources/ApiLol/Mapper/ChampionMapper.cs +++ b/src/EntityFramework_LoL/Sources/ApiLol/Mapper/ChampionMapper.cs @@ -13,13 +13,14 @@ namespace ApiLol.Mapper Bio = champion.Bio, Class = champion.Class.ToDto(), Icon = champion.Icon, - Image = champion.Image.Base64 + Image = champion.Image.ToDto(), + Skins = champion.Skins.Select(e => e.ToDto()) }; } public static Champion ToModel(this ChampionDto championDto) { - return new Champion(championDto.Name, championDto.Class.ToModel(), championDto.Icon, championDto.Image,championDto.Bio); + return new Champion(championDto.Name, championDto.Class.ToModel(), championDto.Icon, championDto.Image.Base64,championDto.Bio); } } diff --git a/src/EntityFramework_LoL/Sources/ApiLol/Mapper/LargeImageMapper.cs b/src/EntityFramework_LoL/Sources/ApiLol/Mapper/LargeImageMapper.cs new file mode 100644 index 0000000..6bebb6f --- /dev/null +++ b/src/EntityFramework_LoL/Sources/ApiLol/Mapper/LargeImageMapper.cs @@ -0,0 +1,21 @@ +using DTO; +using Model; + +namespace ApiLol.Mapper +{ + public static class LargeImageMapper + { + public static LargeImageDto ToDto(this LargeImage largeImage) + { + return new LargeImageDto() + { + Base64 = largeImage.Base64 + }; + } + + public static LargeImage ToModel(this LargeImageDto largeImageDto) + { + return new LargeImage(largeImageDto.Base64); + } + } +} \ No newline at end of file diff --git a/src/EntityFramework_LoL/Sources/ApiLol/Mapper/RuneMapper.cs b/src/EntityFramework_LoL/Sources/ApiLol/Mapper/RuneMapper.cs index fcd88a6..276d0ac 100644 --- a/src/EntityFramework_LoL/Sources/ApiLol/Mapper/RuneMapper.cs +++ b/src/EntityFramework_LoL/Sources/ApiLol/Mapper/RuneMapper.cs @@ -14,7 +14,7 @@ namespace ApiLol.Mapper }; } -/* public static Rune ToModel(this RuneDto rune) +/* public static Rune ToModel(this RuneDto runeDto) { return new Rune(rune.Name) { diff --git a/src/EntityFramework_LoL/Sources/ApiLol/Mapper/SkillMapper.cs b/src/EntityFramework_LoL/Sources/ApiLol/Mapper/SkillMapper.cs index 768caf7..97bec89 100644 --- a/src/EntityFramework_LoL/Sources/ApiLol/Mapper/SkillMapper.cs +++ b/src/EntityFramework_LoL/Sources/ApiLol/Mapper/SkillMapper.cs @@ -14,7 +14,7 @@ namespace ApiLol.Mapper }; } -/* public static Skill ToModel(this SkillDto skill) +/* public static Skill ToModel(this SkillDto skillDto) { return new Skill(skill.Name) { diff --git a/src/EntityFramework_LoL/Sources/ApiLol/Mapper/SkinMapper.cs b/src/EntityFramework_LoL/Sources/ApiLol/Mapper/SkinMapper.cs index a093e12..9925eac 100644 --- a/src/EntityFramework_LoL/Sources/ApiLol/Mapper/SkinMapper.cs +++ b/src/EntityFramework_LoL/Sources/ApiLol/Mapper/SkinMapper.cs @@ -1,18 +1,25 @@ using DTO; +using Model; namespace ApiLol.Mapper { public static class SkinMapper { - public static SkinDto ToDto(this SkinDto skin) + public static SkinDto ToDto(this Skin skin) { return new SkinDto() { Name = skin.Name, Description = skin.Description, Icon = skin.Icon, + Image = skin.Image.ToDto(), Price = skin.Price }; } + + public static Skin ToModel(this SkinDto skinDto) + { + return new Skin(skinDto.Name, null, skinDto.Price, skinDto.Icon, skinDto.Image.Base64, skinDto.Description); + } } -} +} \ No newline at end of file diff --git a/src/EntityFramework_LoL/Sources/ApiLol/Mapper/enums/ChampionClassMapper.cs b/src/EntityFramework_LoL/Sources/ApiLol/Mapper/enums/ChampionClassMapper.cs index c0c52ed..a96d7bf 100644 --- a/src/EntityFramework_LoL/Sources/ApiLol/Mapper/enums/ChampionClassMapper.cs +++ b/src/EntityFramework_LoL/Sources/ApiLol/Mapper/enums/ChampionClassMapper.cs @@ -9,9 +9,9 @@ namespace ApiLol.Mapper { return (ChampionClassDto) championClass; } - public static ChampionClass ToModel(this ChampionClassDto championClass) + public static ChampionClass ToModel(this ChampionClassDto championClassDto) { - return (ChampionClass) championClass; + return (ChampionClass) championClassDto; } } } diff --git a/src/EntityFramework_LoL/Sources/ApiLol/Mapper/enums/SkillTypeMapper.cs b/src/EntityFramework_LoL/Sources/ApiLol/Mapper/enums/SkillTypeMapper.cs new file mode 100644 index 0000000..05689c1 --- /dev/null +++ b/src/EntityFramework_LoL/Sources/ApiLol/Mapper/enums/SkillTypeMapper.cs @@ -0,0 +1,58 @@ +using DTO; +using DTO.enums; +using Model; + +namespace ApiLol.Mapper.enums +{ + public static class SkillTypeMapper + { + public static SkillTypeDto ToDto(this SkillType skillType) + { + if (skillType == SkillType.Unknown) + { + return SkillTypeDto.Unknown; + } + if (skillType == SkillType.Basic) + { + return SkillTypeDto.Basic; + } + if (skillType == SkillType.Passive) + { + return SkillTypeDto.Passive; + } + if (skillType == SkillType.Ultimate) + { + return SkillTypeDto.Ultimate; + } + else + { + return SkillTypeDto.Unknown; + } + + } + public static SkillType ToModel(this SkillTypeDto skillTypeDto) + { + if (skillTypeDto == SkillTypeDto.Unknown) + { + return SkillType.Unknown; + } + if (skillTypeDto == SkillTypeDto.Basic) + { + return SkillType.Basic; + } + if (skillTypeDto == SkillTypeDto.Passive) + { + return SkillType.Passive; + } + if (skillTypeDto == SkillTypeDto.Ultimate) + { + return SkillType.Ultimate; + } + else + { + return SkillType.Unknown; + } + + } + } +} \ No newline at end of file diff --git a/src/EntityFramework_LoL/Sources/Client/Program.cs b/src/EntityFramework_LoL/Sources/Client/Program.cs index 3751555..bfb6ef0 100644 --- a/src/EntityFramework_LoL/Sources/Client/Program.cs +++ b/src/EntityFramework_LoL/Sources/Client/Program.cs @@ -1,2 +1,2 @@ // See https://aka.ms/new-console-template for more information -Console.WriteLine("Hello, World!"); +Console.WriteLine("Hello, World!"); \ No newline at end of file diff --git a/src/EntityFramework_LoL/Sources/DTO/ChampionDto.cs b/src/EntityFramework_LoL/Sources/DTO/ChampionDto.cs index 09f009b..d09bd80 100644 --- a/src/EntityFramework_LoL/Sources/DTO/ChampionDto.cs +++ b/src/EntityFramework_LoL/Sources/DTO/ChampionDto.cs @@ -6,7 +6,7 @@ public string Bio { get; set; } public ChampionClassDto Class { get; set; } public string Icon { get; set; } - public string Image { get; set; } + public LargeImageDto Image { get; set; } public IEnumerable Skins { get; set; } } diff --git a/src/EntityFramework_LoL/Sources/DTO/LargeImageDto.cs b/src/EntityFramework_LoL/Sources/DTO/LargeImageDto.cs new file mode 100644 index 0000000..133ac67 --- /dev/null +++ b/src/EntityFramework_LoL/Sources/DTO/LargeImageDto.cs @@ -0,0 +1,13 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace DTO +{ + public class LargeImageDto + { + public string Base64 { get; set; } + } +} diff --git a/src/EntityFramework_LoL/Sources/DTO/SkinDto.cs b/src/EntityFramework_LoL/Sources/DTO/SkinDto.cs index 2c3962b..8ff7cca 100644 --- a/src/EntityFramework_LoL/Sources/DTO/SkinDto.cs +++ b/src/EntityFramework_LoL/Sources/DTO/SkinDto.cs @@ -11,6 +11,7 @@ namespace DTO public string Name { get; set; } public string Description { get; set; } public string Icon { get; set; } + public LargeImageDto Image { get; set; } public float Price { get; set; } } diff --git a/src/EntityFramework_LoL/Sources/DTO/enums/SkillTypeDto.cs b/src/EntityFramework_LoL/Sources/DTO/enums/SkillTypeDto.cs new file mode 100644 index 0000000..656b59f --- /dev/null +++ b/src/EntityFramework_LoL/Sources/DTO/enums/SkillTypeDto.cs @@ -0,0 +1,16 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace DTO.enums +{ + public enum SkillTypeDto + { + Unknown, + Basic, + Passive, + Ultimate + } +} diff --git a/src/EntityFramework_LoL/Sources/Tests/ApiTests/ChampionsControllerTest.cs b/src/EntityFramework_LoL/Sources/Tests/ApiTests/ChampionsControllerTest.cs index 590e9e1..20a0398 100644 --- a/src/EntityFramework_LoL/Sources/Tests/ApiTests/ChampionsControllerTest.cs +++ b/src/EntityFramework_LoL/Sources/Tests/ApiTests/ChampionsControllerTest.cs @@ -26,7 +26,7 @@ namespace ApiTests //Act var total = await stub.ChampionsMgr.GetNbItems(); - var champion = await champs.Get(new PageRequest()); + var champion = await champs.Get(new PageRequest() { index = 0, count = total }); //Assert var objectResult = champion as OkObjectResult; -- 2.36.3 From afbd78428b2c32e41844af38c419ea2811caee13 Mon Sep 17 00:00:00 2001 From: Emre Date: Fri, 3 Mar 2023 20:59:03 +0100 Subject: [PATCH 05/10] Correct error :white_check_mark: --- .../Sources/Tests/ApiTests/ChampionsControllerTest.cs | 8 ++++++-- 1 file changed, 6 insertions(+), 2 deletions(-) diff --git a/src/EntityFramework_LoL/Sources/Tests/ApiTests/ChampionsControllerTest.cs b/src/EntityFramework_LoL/Sources/Tests/ApiTests/ChampionsControllerTest.cs index 20a0398..61a75a5 100644 --- a/src/EntityFramework_LoL/Sources/Tests/ApiTests/ChampionsControllerTest.cs +++ b/src/EntityFramework_LoL/Sources/Tests/ApiTests/ChampionsControllerTest.cs @@ -3,7 +3,6 @@ using DTO; using Microsoft.AspNetCore.Mvc; using Microsoft.Extensions.Logging; using Microsoft.Extensions.Logging.Abstractions; -using Model; using StubLib; namespace ApiTests @@ -46,7 +45,12 @@ namespace ApiTests var ChampionDto = new ChampionDto { Name = "Sylas", - Bio = "Good" + Bio = "Good", + Class = ChampionClassDto.Tank, + Icon = "", + Image = new LargeImageDto() { Base64 = "" }, + Skins = new List() + }; //Act -- 2.36.3 From c88eac135473e723e9f5e65a8281e0d586e166f0 Mon Sep 17 00:00:00 2001 From: Emre Date: Fri, 3 Mar 2023 22:04:25 +0100 Subject: [PATCH 06/10] Add new functions for ChampionsController and create Skill Dto with mapper --- .../ApiLol/Controllers/ChampionsController.cs | 152 +++++++++++++----- .../Sources/ApiLol/Mapper/ChampionMapper.cs | 5 +- .../Sources/ApiLol/Mapper/SkillMapper.cs | 10 +- .../ApiLol/Mapper/enums/SkillTypeMapper.cs | 3 +- .../Sources/Client/ChampionHttpClient.cs | 6 +- .../Sources/Client/Program.cs | 38 ++++- .../Sources/DTO/ChampionDto.cs | 1 + .../Sources/DTO/SkillDto.cs | 1 + .../Sources/DTO/enums/SkillTypeDto.cs | 2 +- 9 files changed, 164 insertions(+), 54 deletions(-) diff --git a/src/EntityFramework_LoL/Sources/ApiLol/Controllers/ChampionsController.cs b/src/EntityFramework_LoL/Sources/ApiLol/Controllers/ChampionsController.cs index 52d7185..2acbc49 100644 --- a/src/EntityFramework_LoL/Sources/ApiLol/Controllers/ChampionsController.cs +++ b/src/EntityFramework_LoL/Sources/ApiLol/Controllers/ChampionsController.cs @@ -24,82 +24,156 @@ namespace ApiLol.Controllers [HttpGet] public async Task Get([FromQuery] PageRequest pageRequest) { - int nbTotal = await _manager.ChampionsMgr.GetNbItems(); - if (pageRequest.count + pageRequest.index > nbTotal) + try { - _logger.LogWarning($"too many, maximum {nbTotal}"); - return BadRequest("Champion limit exceed"); + int nbTotal = await _manager.ChampionsMgr.GetNbItems(); + if (pageRequest.count + pageRequest.index > nbTotal) + { + _logger.LogWarning($"too many, maximum {nbTotal}"); + return BadRequest($"Champion limit exceed, max {nbTotal}"); + } + + _logger.LogInformation($"method Get call"); + IEnumerable dtos = (await _manager.ChampionsMgr.GetItems(pageRequest.index, pageRequest.count)) + .Select(x => x.ToDto()); + return Ok(dtos); } + catch (Exception e) + { + return BadRequest(e.Message); - _logger.LogInformation($"method Get call"); - IEnumerable dtos = (await _manager.ChampionsMgr.GetItems(pageRequest.index, pageRequest.count)) - .Select(x => x.ToDto()); - return Ok(dtos); + } } // GET api//5 [HttpGet("{name}")] public async Task Get(string name) { - _logger.LogInformation($"method GetByName call with {name}"); - var dtos = (await _manager.ChampionsMgr.GetItemsByName(name, 0, await _manager.ChampionsMgr.GetNbItems())) - .Select(x => x.ToDto()); - if (dtos.IsNullOrEmpty()) + try { - _logger.LogWarning($"{name} was not found"); - return NotFound(); + _logger.LogInformation($"method GetByName call with {name}"); + var dtos = (await _manager.ChampionsMgr.GetItemsByName(name, 0, await _manager.ChampionsMgr.GetNbItems())) + .Select(x => x.ToDto()); + if (dtos.IsNullOrEmpty()) + { + _logger.LogWarning($"{name} was not found"); + return NotFound(); + } + return Ok(dtos); + } + catch (Exception e) + { + return BadRequest(e.Message); + } - return Ok(dtos); } // POST api/ [HttpPost] public async Task Post([FromBody] ChampionDto champion) { - _logger.LogInformation($"method Post call"); - var dtos = (await _manager.ChampionsMgr.GetItemsByName(champion.Name, 0, await _manager.ChampionsMgr.GetNbItems())); - if (!dtos.IsNullOrEmpty()) + try { - return BadRequest("Name is already exist"); + _logger.LogInformation($"method Post call"); + var dtos = (await _manager.ChampionsMgr.GetItemsByName(champion.Name, 0, await _manager.ChampionsMgr.GetNbItems())); + if (!dtos.IsNullOrEmpty()) + { + return BadRequest("Name is already exist"); + } + return CreatedAtAction(nameof(Get), + (await _manager.ChampionsMgr.AddItem(champion.ToModel())).ToDto()); + } + catch (Exception e) + { + return BadRequest(e.Message); + } - return CreatedAtAction(nameof(Get), - (await _manager.ChampionsMgr.AddItem(champion.ToModel())).ToDto()); } // PUT api//5 [HttpPut("{name}")] public async Task Put(string name, [FromBody] ChampionDto champion) { - _logger.LogInformation($"method Put call with {name}"); - var dtos = (await _manager.ChampionsMgr.GetItemsByName(name, 0, await _manager.ChampionsMgr.GetNbItems())); - if (dtos.IsNullOrEmpty()) + try { - return BadRequest("Name not exist"); - } - // Checks if the new name exists - if (name != champion.Name) - { - var dtos2 = (await _manager.ChampionsMgr.GetItemsByName(champion.Name, 0, await _manager.ChampionsMgr.GetNbItems())); - if (!dtos.IsNullOrEmpty()) + _logger.LogInformation($"method Put call with {name}"); + var dtos = (await _manager.ChampionsMgr.GetItemsByName(name, 0, await _manager.ChampionsMgr.GetNbItems())); + if (dtos.IsNullOrEmpty()) { - return BadRequest("Name is already exist"); + return BadRequest("Name not exist"); + } + // Checks if the new name exists + if (name != champion.Name) + { + var dtos2 = (await _manager.ChampionsMgr.GetItemsByName(champion.Name, 0, await _manager.ChampionsMgr.GetNbItems())); + if (!dtos.IsNullOrEmpty()) + { + return BadRequest("Name is already exist"); + } } + return Ok(await _manager.ChampionsMgr.UpdateItem(dtos.First(), champion.ToModel())); + } + catch (Exception e) + { + return BadRequest(e.Message); + + } + } + + [HttpGet("/{name}/skins")] + public async Task> GetChampionsSkins(string name) + { + try + { + var champions = await _manager.ChampionsMgr.GetItemsByName(name, 0, await _manager.ChampionsMgr.GetNbItems()); + //skinsDTO + IEnumerable res = champions.First().Skins.Select(e => e.ToDto()); + + return Ok(res); + } + catch (Exception e) + { + return BadRequest(e.Message); + + } + } + + [HttpGet("/{name}/skills")] + public async Task> GetChampionsSkills(string name) + { + try + { + var champions = await _manager.ChampionsMgr.GetItemsByName(name, 0, await _manager.ChampionsMgr.GetNbItems()); + //SkillDTO + IEnumerable res = champions.First().Skills.Select(e => e.ToDto()); + + return Ok(res); + } + catch (Exception e) + { + return BadRequest(e.Message); } - return Ok(await _manager.ChampionsMgr.UpdateItem(dtos.First(), champion.ToModel())); } // DELETE api//5 [HttpDelete("{name}")] public async Task Delete(string name) { - _logger.LogInformation($"method Delete call with {name}"); - var dtos = (await _manager.ChampionsMgr.GetItemsByName(name, 0, await _manager.ChampionsMgr.GetNbItems())); - if (dtos.IsNullOrEmpty()) + try + { + _logger.LogInformation($"method Delete call with {name}"); + var dtos = (await _manager.ChampionsMgr.GetItemsByName(name, 0, await _manager.ChampionsMgr.GetNbItems())); + if (dtos.IsNullOrEmpty()) + { + _logger.LogWarning($"{name} was not found"); + return BadRequest(); + } + return Ok(await _manager.ChampionsMgr.DeleteItem(dtos.First())); + } + catch (Exception e) { - _logger.LogWarning($"{name} was not found"); - return BadRequest(); + return BadRequest(e.Message); } - return Ok(await _manager.ChampionsMgr.DeleteItem(dtos.First())); } } } \ No newline at end of file diff --git a/src/EntityFramework_LoL/Sources/ApiLol/Mapper/ChampionMapper.cs b/src/EntityFramework_LoL/Sources/ApiLol/Mapper/ChampionMapper.cs index fed7f20..0e9e94c 100644 --- a/src/EntityFramework_LoL/Sources/ApiLol/Mapper/ChampionMapper.cs +++ b/src/EntityFramework_LoL/Sources/ApiLol/Mapper/ChampionMapper.cs @@ -14,13 +14,14 @@ namespace ApiLol.Mapper Class = champion.Class.ToDto(), Icon = champion.Icon, Image = champion.Image.ToDto(), - Skins = champion.Skins.Select(e => e.ToDto()) + Skins = champion.Skins.Select(e => e.ToDto()), + Skills = champion.Skills.Select(e => e.ToDto()) }; } public static Champion ToModel(this ChampionDto championDto) { - return new Champion(championDto.Name, championDto.Class.ToModel(), championDto.Icon, championDto.Image.Base64,championDto.Bio); + return new Champion(championDto.Name, championDto.Class.ToModel(), championDto.Icon, championDto.Image.Base64, championDto.Bio); } } diff --git a/src/EntityFramework_LoL/Sources/ApiLol/Mapper/SkillMapper.cs b/src/EntityFramework_LoL/Sources/ApiLol/Mapper/SkillMapper.cs index 97bec89..20c0787 100644 --- a/src/EntityFramework_LoL/Sources/ApiLol/Mapper/SkillMapper.cs +++ b/src/EntityFramework_LoL/Sources/ApiLol/Mapper/SkillMapper.cs @@ -11,15 +11,13 @@ namespace ApiLol.Mapper { Name = skill.Name, Description = skill.Description, + Type = skill.Type.ToDto() }; } -/* public static Skill ToModel(this SkillDto skillDto) + public static Skill ToModel(this SkillDto skillDto) { - return new Skill(skill.Name) - { - Description = skill.Description - }; - }*/ + return new Skill(skillDto.Name, skillDto.Type.ToModel(), skillDto.Description); + } } } diff --git a/src/EntityFramework_LoL/Sources/ApiLol/Mapper/enums/SkillTypeMapper.cs b/src/EntityFramework_LoL/Sources/ApiLol/Mapper/enums/SkillTypeMapper.cs index 05689c1..ace0c98 100644 --- a/src/EntityFramework_LoL/Sources/ApiLol/Mapper/enums/SkillTypeMapper.cs +++ b/src/EntityFramework_LoL/Sources/ApiLol/Mapper/enums/SkillTypeMapper.cs @@ -1,8 +1,7 @@ using DTO; -using DTO.enums; using Model; -namespace ApiLol.Mapper.enums +namespace ApiLol.Mapper { public static class SkillTypeMapper { diff --git a/src/EntityFramework_LoL/Sources/Client/ChampionHttpClient.cs b/src/EntityFramework_LoL/Sources/Client/ChampionHttpClient.cs index 21155ed..d62b80c 100644 --- a/src/EntityFramework_LoL/Sources/Client/ChampionHttpClient.cs +++ b/src/EntityFramework_LoL/Sources/Client/ChampionHttpClient.cs @@ -18,10 +18,10 @@ namespace Client httpClient.BaseAddress = new Uri("https://localhost:7252;http://localhost:5252"); } - public async Task> GetChampion() + public async Task> GetChampion(int index, int count) { - var champions = await _httpClient.GetFromJsonAsync>(ApiChampions); - return champions; + var url = $"{ApiChampions}?index={index}&count={count}"; + return await _httpClient.GetFromJsonAsync>(url); } public async void Add(ChampionDto champion) { diff --git a/src/EntityFramework_LoL/Sources/Client/Program.cs b/src/EntityFramework_LoL/Sources/Client/Program.cs index bfb6ef0..fdff83d 100644 --- a/src/EntityFramework_LoL/Sources/Client/Program.cs +++ b/src/EntityFramework_LoL/Sources/Client/Program.cs @@ -1,2 +1,38 @@ // See https://aka.ms/new-console-template for more information -Console.WriteLine("Hello, World!"); \ No newline at end of file +using Client; +using DTO; + +Console.WriteLine("Hello, World!"); + +var championClient = new ChampionHttpClient(new HttpClient()); + +// Get all champions +var champions = await championClient.GetChampion(0,6); +Console.WriteLine("All champions:"); +foreach (var champion in champions) +{ + Console.WriteLine($"{champion.Name} ({champion.Bio})"); +} + +/*// Add a new champion +var newChampion = new ChampionDto { Name = "Akali", Role = "Assassin" }; +championClient.Add(newChampion); + +// Delete a champion +var championToDelete = champions.FirstOrDefault(c => c.Name == "Riven"); +if (championToDelete != null) +{ + championClient.Delete(championToDelete); + Console.WriteLine($"{championToDelete.Name} deleted."); +} + +// Update a champion +var championToUpdate = champions.FirstOrDefault(c => c.Name == "Ashe"); +if (championToUpdate != null) +{ + championToUpdate.Role = "Marksman"; + championClient.Update(championToUpdate); + Console.WriteLine($"{championToUpdate.Name} updated."); +} + +*/ \ No newline at end of file diff --git a/src/EntityFramework_LoL/Sources/DTO/ChampionDto.cs b/src/EntityFramework_LoL/Sources/DTO/ChampionDto.cs index d09bd80..e9b002f 100644 --- a/src/EntityFramework_LoL/Sources/DTO/ChampionDto.cs +++ b/src/EntityFramework_LoL/Sources/DTO/ChampionDto.cs @@ -8,6 +8,7 @@ public string Icon { get; set; } public LargeImageDto Image { get; set; } public IEnumerable Skins { get; set; } + public IEnumerable Skills { get; set; } } } \ No newline at end of file diff --git a/src/EntityFramework_LoL/Sources/DTO/SkillDto.cs b/src/EntityFramework_LoL/Sources/DTO/SkillDto.cs index 77372ab..f0e1919 100644 --- a/src/EntityFramework_LoL/Sources/DTO/SkillDto.cs +++ b/src/EntityFramework_LoL/Sources/DTO/SkillDto.cs @@ -10,5 +10,6 @@ namespace DTO { public string Name { get; set; } public string Description { get; set; } + public SkillTypeDto Type { get; set; } } } diff --git a/src/EntityFramework_LoL/Sources/DTO/enums/SkillTypeDto.cs b/src/EntityFramework_LoL/Sources/DTO/enums/SkillTypeDto.cs index 656b59f..f416bdd 100644 --- a/src/EntityFramework_LoL/Sources/DTO/enums/SkillTypeDto.cs +++ b/src/EntityFramework_LoL/Sources/DTO/enums/SkillTypeDto.cs @@ -4,7 +4,7 @@ using System.Linq; using System.Text; using System.Threading.Tasks; -namespace DTO.enums +namespace DTO { public enum SkillTypeDto { -- 2.36.3 From 074892b3a7546ebada4e353241794172cbb729b1 Mon Sep 17 00:00:00 2001 From: Emre Date: Sat, 4 Mar 2023 20:24:38 +0100 Subject: [PATCH 07/10] Changed program.cs for versioning in the swagger, also fixed uniqueness issues and created 3 versions of the ChampionController :white_check_mark: --- .../Sources/ApiLol/ApiLol.csproj | 2 + .../ApiLol/Controllers/SkinsController.cs | 73 ++ .../Controllers/v1/ChampionsController.cs | 84 +++ .../{ => v2}/ChampionsController.cs | 382 +++++----- .../Sources/ApiLol/Mapper/SkinMapper.cs | 14 + .../Sources/ApiLol/Program.cs | 33 +- .../Sources/Client/ChampionHttpClient.cs | 8 +- .../Sources/DTO/RuneDto.cs | 5 +- .../Sources/DTO/SkinDtoC.cs | 20 + .../Sources/DTO/enums/RuneFamilyDto.cs | 15 + .../Sources/StubLib/StubData.Champions.cs | 2 +- .../Tests/ApiTests/ChampionsControllerTest.cs | 2 +- .../Sources/Tests/ConsoleTests/Program.cs | 672 +++++++++--------- 13 files changed, 789 insertions(+), 523 deletions(-) create mode 100644 src/EntityFramework_LoL/Sources/ApiLol/Controllers/SkinsController.cs create mode 100644 src/EntityFramework_LoL/Sources/ApiLol/Controllers/v1/ChampionsController.cs rename src/EntityFramework_LoL/Sources/ApiLol/Controllers/{ => v2}/ChampionsController.cs (77%) create mode 100644 src/EntityFramework_LoL/Sources/DTO/SkinDtoC.cs create mode 100644 src/EntityFramework_LoL/Sources/DTO/enums/RuneFamilyDto.cs diff --git a/src/EntityFramework_LoL/Sources/ApiLol/ApiLol.csproj b/src/EntityFramework_LoL/Sources/ApiLol/ApiLol.csproj index 57d85a9..f765ca4 100644 --- a/src/EntityFramework_LoL/Sources/ApiLol/ApiLol.csproj +++ b/src/EntityFramework_LoL/Sources/ApiLol/ApiLol.csproj @@ -9,6 +9,8 @@ + + diff --git a/src/EntityFramework_LoL/Sources/ApiLol/Controllers/SkinsController.cs b/src/EntityFramework_LoL/Sources/ApiLol/Controllers/SkinsController.cs new file mode 100644 index 0000000..ac1cc2d --- /dev/null +++ b/src/EntityFramework_LoL/Sources/ApiLol/Controllers/SkinsController.cs @@ -0,0 +1,73 @@ +using ApiLol.Mapper; +using DTO; +using Microsoft.AspNetCore.Mvc; +using Model; + +// For more information on enabling Web API for empty projects, visit https://go.microsoft.com/fwlink/?LinkID=397860 + +namespace ApiLol.Controllers +{ + [Route("api/[controller]")] + [ApiController] + public class SkinsController : ControllerBase + { + private readonly IDataManager _manager; + private readonly ILogger _logger; + + public SkinsController(IDataManager dataManager, ILogger logger) + { + _logger = logger; + this._manager = dataManager; + } + + // GET: api/ + [HttpGet] + public async Task Get([FromQuery] PageRequest pageRequest) + { + try + { + int nbTotal = await _manager.ChampionsMgr.GetNbItems(); + if (pageRequest.count + pageRequest.index > nbTotal) + { + _logger.LogWarning($"too many, maximum {nbTotal}"); + return BadRequest($"Champion limit exceed, max {nbTotal}"); + } + + _logger.LogInformation($"method Get call"); + IEnumerable dtos = (await _manager.SkinsMgr.GetItems(pageRequest.index, pageRequest.count)) + .Select(x => x.ToDtoC()); + return Ok(dtos); + + } + catch (Exception e) + { + return BadRequest(e.Message); + } + } + + // GET api//5 + [HttpGet("{name}")] + public async Task Get(string name) + { + return Ok(); + } + + // POST api/ + [HttpPost] + public async void Post([FromBody] string value) + { + } + + // PUT api//5 + [HttpPut("{name}")] + public async void Put(int id, [FromBody] string value) + { + } + + // DELETE api//5 + [HttpDelete("{name}")] + public async void Delete(string name) + { + } + } +} diff --git a/src/EntityFramework_LoL/Sources/ApiLol/Controllers/v1/ChampionsController.cs b/src/EntityFramework_LoL/Sources/ApiLol/Controllers/v1/ChampionsController.cs new file mode 100644 index 0000000..96ecf2b --- /dev/null +++ b/src/EntityFramework_LoL/Sources/ApiLol/Controllers/v1/ChampionsController.cs @@ -0,0 +1,84 @@ +using ApiLol.Mapper; +using DTO; +using Microsoft.AspNetCore.Mvc; +using Microsoft.IdentityModel.Tokens; +using Model; + +// For more information on enabling Web API for empty projects, visit https://go.microsoft.com/fwlink/?LinkID=397860 + +namespace ApiLol.Controllers.v1 +{ + [ApiVersion("1.0")] + [Route("api/v{version:apiVersion}/[controller]")] + [ApiController] + public class ChampionsController : ControllerBase + { + private readonly IDataManager _manager; + private readonly ILogger _logger; + public ChampionsController(IDataManager dataManager, ILogger logger) + { + _logger = logger; + this._manager = dataManager; + } + + // GET: api/ + [HttpGet] + public async Task Get([FromQuery] PageRequest pageRequest) + { + + int nbTotal = await _manager.ChampionsMgr.GetNbItems(); + + _logger.LogInformation($"method Get call"); + IEnumerable dtos = (await _manager.ChampionsMgr.GetItems(pageRequest.index, pageRequest.count)) + .Select(x => x.ToDto()); + return Ok(dtos); + } + + // GET api//5 + [HttpGet("{name}")] + public async Task Get(string name) + { + _logger.LogInformation($"method GetByName call with {name}"); + var dtos = (await _manager.ChampionsMgr.GetItemsByName(name, 0, await _manager.ChampionsMgr.GetNbItems())) + .Select(x => x.ToDto()); + + return Ok(dtos); + + } + + // POST api/ + [HttpPost] + public async Task Post([FromBody] ChampionDto champion) + { + + _logger.LogInformation($"method Post call"); + return CreatedAtAction(nameof(Get), + (await _manager.ChampionsMgr.AddItem(champion.ToModel())).ToDto()); + + } + + // PUT api//5 + [HttpPut("{name}")] + public async Task Put(string name, [FromBody] ChampionDto champion) + { + + _logger.LogInformation($"method Put call with {name}"); + var dtos = (await _manager.ChampionsMgr.GetItemsByName(name, 0, await _manager.ChampionsMgr.GetNbItems())); + + return Ok(await _manager.ChampionsMgr.UpdateItem(dtos.First(), champion.ToModel())); + + } + + // DELETE api//5 + [HttpDelete("{name}")] + public async Task Delete(string name) + { + + _logger.LogInformation($"method Delete call with {name}"); + var dtos = (await _manager.ChampionsMgr.GetItemsByName(name, 0, await _manager.ChampionsMgr.GetNbItems())); + + return Ok(await _manager.ChampionsMgr.DeleteItem(dtos.First())); + + } + } +} \ No newline at end of file diff --git a/src/EntityFramework_LoL/Sources/ApiLol/Controllers/ChampionsController.cs b/src/EntityFramework_LoL/Sources/ApiLol/Controllers/v2/ChampionsController.cs similarity index 77% rename from src/EntityFramework_LoL/Sources/ApiLol/Controllers/ChampionsController.cs rename to src/EntityFramework_LoL/Sources/ApiLol/Controllers/v2/ChampionsController.cs index 2acbc49..1715b6a 100644 --- a/src/EntityFramework_LoL/Sources/ApiLol/Controllers/ChampionsController.cs +++ b/src/EntityFramework_LoL/Sources/ApiLol/Controllers/v2/ChampionsController.cs @@ -1,179 +1,205 @@ -using ApiLol.Mapper; -using DTO; -using Microsoft.AspNetCore.Mvc; -using Microsoft.IdentityModel.Tokens; -using Model; - -// For more information on enabling Web API for empty projects, visit https://go.microsoft.com/fwlink/?LinkID=397860 - -namespace ApiLol.Controllers -{ - [Route("api/[controller]")] - [ApiController] - public class ChampionsController : ControllerBase - { - private readonly IDataManager _manager; - public readonly ILogger _logger; - public ChampionsController(IDataManager dataManager, ILogger logger) - { - _logger = logger; - this._manager = dataManager; - } - - // GET: api/ - [HttpGet] - public async Task Get([FromQuery] PageRequest pageRequest) - { - try - { - int nbTotal = await _manager.ChampionsMgr.GetNbItems(); - if (pageRequest.count + pageRequest.index > nbTotal) - { - _logger.LogWarning($"too many, maximum {nbTotal}"); - return BadRequest($"Champion limit exceed, max {nbTotal}"); - } - - _logger.LogInformation($"method Get call"); - IEnumerable dtos = (await _manager.ChampionsMgr.GetItems(pageRequest.index, pageRequest.count)) - .Select(x => x.ToDto()); - return Ok(dtos); - } - catch (Exception e) - { - return BadRequest(e.Message); - - } - } - - // GET api//5 - [HttpGet("{name}")] - public async Task Get(string name) - { - try - { - _logger.LogInformation($"method GetByName call with {name}"); - var dtos = (await _manager.ChampionsMgr.GetItemsByName(name, 0, await _manager.ChampionsMgr.GetNbItems())) - .Select(x => x.ToDto()); - if (dtos.IsNullOrEmpty()) - { - _logger.LogWarning($"{name} was not found"); - return NotFound(); - } - return Ok(dtos); - } - catch (Exception e) - { - return BadRequest(e.Message); - - } - } - - // POST api/ - [HttpPost] - public async Task Post([FromBody] ChampionDto champion) - { - try - { - _logger.LogInformation($"method Post call"); - var dtos = (await _manager.ChampionsMgr.GetItemsByName(champion.Name, 0, await _manager.ChampionsMgr.GetNbItems())); - if (!dtos.IsNullOrEmpty()) - { - return BadRequest("Name is already exist"); - } - return CreatedAtAction(nameof(Get), - (await _manager.ChampionsMgr.AddItem(champion.ToModel())).ToDto()); - } - catch (Exception e) - { - return BadRequest(e.Message); - - } - } - - // PUT api//5 - [HttpPut("{name}")] - public async Task Put(string name, [FromBody] ChampionDto champion) - { - try - { - _logger.LogInformation($"method Put call with {name}"); - var dtos = (await _manager.ChampionsMgr.GetItemsByName(name, 0, await _manager.ChampionsMgr.GetNbItems())); - if (dtos.IsNullOrEmpty()) - { - return BadRequest("Name not exist"); - } - // Checks if the new name exists - if (name != champion.Name) - { - var dtos2 = (await _manager.ChampionsMgr.GetItemsByName(champion.Name, 0, await _manager.ChampionsMgr.GetNbItems())); - if (!dtos.IsNullOrEmpty()) - { - return BadRequest("Name is already exist"); - } - } - return Ok(await _manager.ChampionsMgr.UpdateItem(dtos.First(), champion.ToModel())); - } - catch (Exception e) - { - return BadRequest(e.Message); - - } - } - - [HttpGet("/{name}/skins")] - public async Task> GetChampionsSkins(string name) - { - try - { - var champions = await _manager.ChampionsMgr.GetItemsByName(name, 0, await _manager.ChampionsMgr.GetNbItems()); - //skinsDTO - IEnumerable res = champions.First().Skins.Select(e => e.ToDto()); - - return Ok(res); - } - catch (Exception e) - { - return BadRequest(e.Message); - - } - } - - [HttpGet("/{name}/skills")] - public async Task> GetChampionsSkills(string name) - { - try - { - var champions = await _manager.ChampionsMgr.GetItemsByName(name, 0, await _manager.ChampionsMgr.GetNbItems()); - //SkillDTO - IEnumerable res = champions.First().Skills.Select(e => e.ToDto()); - - return Ok(res); - } - catch (Exception e) - { - return BadRequest(e.Message); - } - } - - // DELETE api//5 - [HttpDelete("{name}")] - public async Task Delete(string name) - { - try - { - _logger.LogInformation($"method Delete call with {name}"); - var dtos = (await _manager.ChampionsMgr.GetItemsByName(name, 0, await _manager.ChampionsMgr.GetNbItems())); - if (dtos.IsNullOrEmpty()) - { - _logger.LogWarning($"{name} was not found"); - return BadRequest(); - } - return Ok(await _manager.ChampionsMgr.DeleteItem(dtos.First())); - } - catch (Exception e) - { - return BadRequest(e.Message); - } - } - } +using ApiLol.Mapper; +using DTO; +using Microsoft.AspNetCore.Mvc; +using Microsoft.IdentityModel.Tokens; +using Model; + +// For more information on enabling Web API for empty projects, visit https://go.microsoft.com/fwlink/?LinkID=397860 + +namespace ApiLol.Controllers.v2 +{ + [ApiVersion("2.0")] + [ApiVersion("3.0")] + [Route("api/v{version:apiVersion}/[controller]")] + [ApiController] + public class ChampionsController : ControllerBase + { + private readonly IDataManager _manager; + private readonly ILogger _logger; + public ChampionsController(IDataManager dataManager, ILogger logger) + { + _logger = logger; + this._manager = dataManager; + } + + // GET: api/ + [HttpGet] + public async Task Get([FromQuery] PageRequest pageRequest) + { + try + { + int nbTotal = await _manager.ChampionsMgr.GetNbItems(); + if (pageRequest.count * pageRequest.index >= nbTotal) + { + _logger.LogWarning($"too many, maximum {nbTotal}"); + return BadRequest($"Champion limit exceed, max {nbTotal}"); + } + + _logger.LogInformation($"method Get call"); + IEnumerable dtos = (await _manager.ChampionsMgr.GetItems(pageRequest.index, pageRequest.count)) + .Select(x => x.ToDto()); + return Ok(dtos); + } + catch (Exception e) + { + return BadRequest(e.Message); + } + } + + // GET: api/ + [HttpGet, MapToApiVersion("3.0")] + public async Task GetV3([FromQuery] PageRequest pageRequest) + { + try + { + int nbTotal = await _manager.ChampionsMgr.GetNbItems(); + if (pageRequest == null) + { + pageRequest.index = 0; + pageRequest.count = nbTotal; + } + else if (pageRequest.count * pageRequest.index >= nbTotal) + { + _logger.LogWarning($"too many, maximum {nbTotal}"); + return BadRequest($"Champion limit exceed, max {nbTotal}"); + } + + _logger.LogInformation($"method Get call"); + IEnumerable dtos = (await _manager.ChampionsMgr.GetItems(pageRequest.index, pageRequest.count)) + .Select(x => x.ToDto()); + return Ok(dtos); + } + catch (Exception e) + { + return BadRequest(e.Message); + } + } + + // GET api//5 + [HttpGet("{name}")] + public async Task Get(string name) + { + try + { + _logger.LogInformation($"method GetByName call with {name}"); + var dtos = (await _manager.ChampionsMgr.GetItemsByName(name, 0, await _manager.ChampionsMgr.GetNbItems())) + .Select(x => x.ToDto()); + if (dtos.IsNullOrEmpty()) + { + _logger.LogWarning($"{name} was not found"); + return NotFound(); + } + return Ok(dtos); + } + catch (Exception e) + { + return BadRequest(e.Message); + } + } + + // POST api/ + [HttpPost] + public async Task Post([FromBody] ChampionDto champion) + { + try + { + _logger.LogInformation($"method Post call"); + var dtos = (await _manager.ChampionsMgr.GetItemsByName(champion.Name, 0, await _manager.ChampionsMgr.GetNbItems())); + if (!dtos.IsNullOrEmpty()) + { + return BadRequest("Name is already exist"); + } + return CreatedAtAction(nameof(Get), + (await _manager.ChampionsMgr.AddItem(champion.ToModel())).ToDto()); + } + catch (Exception e) + { + return BadRequest(e.Message); + } + } + + // PUT api//5 + [HttpPut("{name}")] + public async Task Put(string name, [FromBody] ChampionDto champion) + { + try + { + _logger.LogInformation($"method Put call with {name}"); + var dtos = (await _manager.ChampionsMgr.GetItemsByName(name, 0, await _manager.ChampionsMgr.GetNbItems())); + if (dtos.IsNullOrEmpty()) + { + return NotFound("Name not exist"); + } + // Checks if the new name exists + if (name != champion.Name) + { + var dtos2 = (await _manager.ChampionsMgr.GetItemsByName(champion.Name, 0, await _manager.ChampionsMgr.GetNbItems())); + if (dtos.IsNullOrEmpty() || dtos2.Count() > 0) + { + return BadRequest("Name is already exist"); + } + } + return Ok(await _manager.ChampionsMgr.UpdateItem(dtos.First(), champion.ToModel())); + } + catch (Exception e) + { + return BadRequest(e.Message); + } + } + + [HttpGet("/{name}/skins")] + public async Task> GetChampionsSkins(string name) + { + try + { + var champions = await _manager.ChampionsMgr.GetItemsByName(name, 0, await _manager.ChampionsMgr.GetNbItems()); + //skinsDTO + IEnumerable res = champions.First().Skins.Select(e => e.ToDto()); + + return Ok(res); + } + catch (Exception e) + { + return BadRequest(e.Message); + } + } + + [HttpGet("/{name}/skills")] + public async Task> GetChampionsSkills(string name) + { + try + { + var champions = await _manager.ChampionsMgr.GetItemsByName(name, 0, await _manager.ChampionsMgr.GetNbItems()); + //SkillDTO + IEnumerable res = champions.First().Skills.Select(e => e.ToDto()); + + return Ok(res); + } + catch (Exception e) + { + return BadRequest(e.Message); + } + } + + // DELETE api//5 + [HttpDelete("{name}")] + public async Task Delete(string name) + { + try + { + _logger.LogInformation($"method Delete call with {name}"); + var dtos = (await _manager.ChampionsMgr.GetItemsByName(name, 0, await _manager.ChampionsMgr.GetNbItems())); + if (dtos.IsNullOrEmpty()) + { + _logger.LogWarning($"{name} was not found"); + return BadRequest(); + } + return Ok(await _manager.ChampionsMgr.DeleteItem(dtos.First())); + } + catch (Exception e) + { + return BadRequest(e.Message); + } + } + } } \ No newline at end of file diff --git a/src/EntityFramework_LoL/Sources/ApiLol/Mapper/SkinMapper.cs b/src/EntityFramework_LoL/Sources/ApiLol/Mapper/SkinMapper.cs index 9925eac..7104d37 100644 --- a/src/EntityFramework_LoL/Sources/ApiLol/Mapper/SkinMapper.cs +++ b/src/EntityFramework_LoL/Sources/ApiLol/Mapper/SkinMapper.cs @@ -17,9 +17,23 @@ namespace ApiLol.Mapper }; } + public static SkinDtoC ToDtoC(this Skin skin) + { + return new SkinDtoC() + { + Name = skin.Name, + Description = skin.Description, + Icon = skin.Icon, + Image = skin.Image.ToDto(), + Price = skin.Price, + ChampionName = skin.Champion.Name + }; + } + public static Skin ToModel(this SkinDto skinDto) { return new Skin(skinDto.Name, null, skinDto.Price, skinDto.Icon, skinDto.Image.Base64, skinDto.Description); } + } } \ No newline at end of file diff --git a/src/EntityFramework_LoL/Sources/ApiLol/Program.cs b/src/EntityFramework_LoL/Sources/ApiLol/Program.cs index 0e7a608..98e6f6c 100644 --- a/src/EntityFramework_LoL/Sources/ApiLol/Program.cs +++ b/src/EntityFramework_LoL/Sources/ApiLol/Program.cs @@ -1,3 +1,5 @@ +using Microsoft.AspNetCore.Mvc.ApiExplorer; +using Microsoft.AspNetCore.Mvc.Versioning; using Model; using StubLib; @@ -9,14 +11,41 @@ builder.Services.AddControllers(); // Learn more about configuring Swagger/OpenAPI at https://aka.ms/aspnetcore/swashbuckle builder.Services.AddEndpointsApiExplorer(); builder.Services.AddSwaggerGen(); + + +builder.Services.AddApiVersioning(opt => + { + opt.DefaultApiVersion = new Microsoft.AspNetCore.Mvc.ApiVersion(1, 0); + opt.AssumeDefaultVersionWhenUnspecified = true; + opt.ReportApiVersions = true; + opt.ApiVersionReader = ApiVersionReader.Combine(new UrlSegmentApiVersionReader(), + new HeaderApiVersionReader("x-api-version"), + new MediaTypeApiVersionReader("x-api-version")); + }); +// Add ApiExplorer to discover versions +builder.Services.AddVersionedApiExplorer(setup => +{ + setup.GroupNameFormat = "'v'VVV"; + setup.SubstituteApiVersionInUrl = true; +}); + builder.Services.AddSingleton(); var app = builder.Build(); // Configure the HTTP request pipeline. -app.UseSwagger(); -app.UseSwaggerUI(); +var apiVersionDescriptionProvider = app.Services.GetRequiredService(); +// Configure the HTTP request pipeline. +app.UseSwagger(); +app.UseSwaggerUI(options => +{ + foreach (var description in apiVersionDescriptionProvider.ApiVersionDescriptions) + { + options.SwaggerEndpoint($"/swagger/{description.GroupName}/swagger.json", + description.GroupName.ToUpperInvariant()); + } +}); app.UseHttpsRedirection(); diff --git a/src/EntityFramework_LoL/Sources/Client/ChampionHttpClient.cs b/src/EntityFramework_LoL/Sources/Client/ChampionHttpClient.cs index d62b80c..deae099 100644 --- a/src/EntityFramework_LoL/Sources/Client/ChampionHttpClient.cs +++ b/src/EntityFramework_LoL/Sources/Client/ChampionHttpClient.cs @@ -23,12 +23,12 @@ namespace Client var url = $"{ApiChampions}?index={index}&count={count}"; return await _httpClient.GetFromJsonAsync>(url); } - public async void Add(ChampionDto champion) +/* public async void Add(ChampionDto champion) { await _httpClient.PostAsJsonAsync(ApiChampions, champion); - } + }*/ - public async void Delete(ChampionDto champion) +/* public async void Delete(ChampionDto champion) { await _httpClient.DeleteAsync(champion.Name); } @@ -36,7 +36,7 @@ namespace Client public async void Update(ChampionDto champion) { await _httpClient.PutAsJsonAsync(ApiChampions, champion); - } + }*/ } } diff --git a/src/EntityFramework_LoL/Sources/DTO/RuneDto.cs b/src/EntityFramework_LoL/Sources/DTO/RuneDto.cs index f5afb80..5f463b6 100644 --- a/src/EntityFramework_LoL/Sources/DTO/RuneDto.cs +++ b/src/EntityFramework_LoL/Sources/DTO/RuneDto.cs @@ -1,4 +1,5 @@ -using System; +using DTO.enums; +using System; using System.Collections.Generic; using System.Linq; using System.Text; @@ -10,6 +11,8 @@ namespace DTO { public string Name { get; set; } public string Description { get; set; } + public RuneFamilyDto Family { get; set; } + public LargeImageDto Image { get; set; } } } diff --git a/src/EntityFramework_LoL/Sources/DTO/SkinDtoC.cs b/src/EntityFramework_LoL/Sources/DTO/SkinDtoC.cs new file mode 100644 index 0000000..656fb33 --- /dev/null +++ b/src/EntityFramework_LoL/Sources/DTO/SkinDtoC.cs @@ -0,0 +1,20 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace DTO +{ + public class SkinDtoC + { + public string Name { get; set; } + public string Description { get; set; } + public string Icon { get; set; } + public LargeImageDto Image { get; set; } + public float Price { get; set; } + public string ChampionName { get; set; } + + + } +} diff --git a/src/EntityFramework_LoL/Sources/DTO/enums/RuneFamilyDto.cs b/src/EntityFramework_LoL/Sources/DTO/enums/RuneFamilyDto.cs new file mode 100644 index 0000000..053249c --- /dev/null +++ b/src/EntityFramework_LoL/Sources/DTO/enums/RuneFamilyDto.cs @@ -0,0 +1,15 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace DTO.enums +{ + public enum RuneFamilyDto + { + Unknown, + Precision, + Domination + } +} diff --git a/src/EntityFramework_LoL/Sources/StubLib/StubData.Champions.cs b/src/EntityFramework_LoL/Sources/StubLib/StubData.Champions.cs index ad19275..c487e45 100644 --- a/src/EntityFramework_LoL/Sources/StubLib/StubData.Champions.cs +++ b/src/EntityFramework_LoL/Sources/StubLib/StubData.Champions.cs @@ -84,7 +84,7 @@ namespace StubLib .Select(tuple => tuple.Item1) .Skip(index*count).Take(count)); - private Func filterByName = (champ, substring) => champ.Name.Contains(substring, StringComparison.InvariantCultureIgnoreCase); + private Func filterByName = (champ, substring) => champ.Name.Equals(substring, StringComparison.InvariantCultureIgnoreCase); public Task GetNbItemsByName(string substring) => parent.champions.GetNbItemsWithFilter(champ => filterByName(champ, substring)); diff --git a/src/EntityFramework_LoL/Sources/Tests/ApiTests/ChampionsControllerTest.cs b/src/EntityFramework_LoL/Sources/Tests/ApiTests/ChampionsControllerTest.cs index 61a75a5..021b773 100644 --- a/src/EntityFramework_LoL/Sources/Tests/ApiTests/ChampionsControllerTest.cs +++ b/src/EntityFramework_LoL/Sources/Tests/ApiTests/ChampionsControllerTest.cs @@ -1,4 +1,5 @@ using ApiLol.Controllers; +using ApiLol.Controllers.v2; using DTO; using Microsoft.AspNetCore.Mvc; using Microsoft.Extensions.Logging; @@ -50,7 +51,6 @@ namespace ApiTests Icon = "", Image = new LargeImageDto() { Base64 = "" }, Skins = new List() - }; //Act diff --git a/src/EntityFramework_LoL/Sources/Tests/ConsoleTests/Program.cs b/src/EntityFramework_LoL/Sources/Tests/ConsoleTests/Program.cs index 28dc26b..80c9d9f 100644 --- a/src/EntityFramework_LoL/Sources/Tests/ConsoleTests/Program.cs +++ b/src/EntityFramework_LoL/Sources/Tests/ConsoleTests/Program.cs @@ -1,338 +1,338 @@ using System.Collections.Immutable; -using System.Diagnostics; -using Microsoft.Extensions.DependencyInjection; -using Model; -using StubLib; -using static System.Console; - -namespace ConsoleTests -{ - static class Program - { - static IDataManager dataManager = null!; - - static async Task Main(string[] args) - { - try - { - using var servicesProvider = new ServiceCollection() - .AddSingleton() - .BuildServiceProvider(); - - dataManager = servicesProvider.GetRequiredService(); - - await DisplayMainMenu(); - - Console.ReadLine(); - } - catch (Exception ex) - { - Debug.WriteLine(ex, "Stopped program because of exception"); - throw; - } - } - - public static async Task DisplayMainMenu() - { - Dictionary choices = new Dictionary() - { - [1] = "1- Manage Champions", - [2] = "2- Manage Skins", - [3] = "3- Manage Runes", - [4] = "4- Manage Rune Pages", - [99] = "99- Quit" - }; - - while(true) - { - int input = DisplayAMenu(choices); - - switch(input) - { - case 1: - await DisplayChampionsMenu(); - break; - case 2: - break; - case 3: - break; - case 4: - break; - case 99: - WriteLine("Bye bye!"); - return; - default: - break; - } - } - } - - private static int DisplayAMenu(Dictionary choices) - { - int input=-1; - while(true) - { - WriteLine("What is your choice?"); - WriteLine("--------------------"); - foreach(var choice in choices.OrderBy(kvp => kvp.Key).Select(kvp => kvp.Value)) - { - WriteLine(choice); - } - if(!int.TryParse(ReadLine(), out input) || input == -1) - { - WriteLine("I do not understand what your choice is. Please try again."); - continue; - } - break; - } - WriteLine($"You have chosen: {choices[input]}"); - WriteLine(); - return input; - } - - public static async Task DisplayChampionsMenu() - { - Dictionary choices = new Dictionary() - { - [0] = "0- Get number of champions", - [1] = "1- Get champions", - [2] = "2- Find champions by name", - [3] = "3- Find champions by characteristic", - [4] = "4- Find champions by class", - [5] = "5- Find champions by skill", - [6] = "6- Add new champion", - [7] = "7- Delete a champion", - [8] = "8- Update a champion", - }; - - int input = DisplayAMenu(choices); - - switch(input) - { - case 0: - int nb = await dataManager.ChampionsMgr.GetNbItems(); - WriteLine($"There are {nb} champions"); - WriteLine("**********************"); - break; - case 1: - { - int index = ReadAnInt("Please enter the page index"); - int count = ReadAnInt("Please enter the number of elements to display"); - WriteLine($"{count} champions of page {index+1}"); - var champions = await dataManager.ChampionsMgr.GetItems(index, count, nameof(Champion.Name)); - foreach(var champion in champions) - { - WriteLine($"\t{champion}"); - } - WriteLine("**********************"); - } - break; - case 2: - { - string substring = ReadAString("Please enter the substring to look for in the name of a champion"); - int index = ReadAnInt("Please enter the page index"); - int count = ReadAnInt("Please enter the number of elements to display"); - var champions = await dataManager.ChampionsMgr.GetItemsByName(substring, index, count, nameof(Champion.Name)); - foreach(var champion in champions) - { - WriteLine($"\t{champion}"); - } - WriteLine("**********************"); - } - break; - case 3: - { - string substring = ReadAString("Please enter the substring to look for in the characteristics of champions"); - int index = ReadAnInt("Please enter the page index"); - int count = ReadAnInt("Please enter the number of elements to display"); - var champions = await dataManager.ChampionsMgr.GetItemsByCharacteristic(substring, index, count, nameof(Champion.Name)); - foreach(var champion in champions) - { - WriteLine($"\t{champion}"); - } - WriteLine("**********************"); - } - break; - case 4: - { - ChampionClass championClass = ReadAnEnum($"Please enter the champion class (possible values are: {Enum.GetNames().Aggregate("", (name, chaine) => $"{chaine} {name}")}):"); - int index = ReadAnInt("Please enter the page index"); - int count = ReadAnInt("Please enter the number of elements to display"); - var champions = await dataManager.ChampionsMgr.GetItemsByClass(championClass, index, count, nameof(Champion.Name)); - foreach(var champion in champions) - { - WriteLine($"\t{champion}"); - } - WriteLine("**********************"); - } - break; - case 5: - { - string substring = ReadAString("Please enter the substring to look for in the skills of champions"); - int index = ReadAnInt("Please enter the page index"); - int count = ReadAnInt("Please enter the number of elements to display"); - var champions = await dataManager.ChampionsMgr.GetItemsBySkill(substring, index, count, nameof(Champion.Name)); - foreach(var champion in champions) - { - WriteLine($"\t{champion}"); - } - WriteLine("**********************"); - } - break; - case 6: - { - WriteLine("You are going to create a new champion."); - string name = ReadAString("Please enter the champion name:"); - ChampionClass championClass = ReadAnEnum($"Please enter the champion class (possible values are: {Enum.GetNames().Aggregate("", (name, chaine) => $"{chaine} {name}")}):"); - string bio = ReadAString("Please enter the champion bio:"); - Champion champion = new Champion(name, championClass, bio: bio); - DisplayCreationChampionMenu(champion); - _ = await dataManager.ChampionsMgr.AddItem(champion); - } - break; - case 7: - { - WriteLine("You are going to delete a champion."); - string name = ReadAString("Please enter the champion name:"); - var somechampions = await dataManager.ChampionsMgr.GetItemsByName(name, 0, 10, nameof(Champion.Name)); - var someChampionNames = somechampions.Select(c => c!.Name); - var someChampionNamesAsOneString = someChampionNames.Aggregate("", (name, chaine) => $"{chaine} {name}"); - string champName = ReadAStringAmongPossibleValues($"Who do you want to delete among these champions? (type \"Cancel\" to ... cancel) {someChampionNamesAsOneString}", - someChampionNames.ToArray()); - if(champName != "Cancel") - { - await dataManager.ChampionsMgr.DeleteItem(somechampions.Single(c => c!.Name == champName)); - } - } - break; - case 8: - { - WriteLine("You are going to update a champion."); - string name = ReadAString("Please enter the champion name:"); - var somechampions = await dataManager.ChampionsMgr.GetItemsByName(name, 0, 10, nameof(Champion.Name)); - var someChampionNames = somechampions.Select(c => c!.Name); - var someChampionNamesAsOneString = someChampionNames.Aggregate("", (name, chaine) => $"{chaine} {name}"); - string champName = ReadAStringAmongPossibleValues($"Who do you want to update among these champions? (type \"Cancel\" to ... cancel) {someChampionNamesAsOneString}", - someChampionNames.ToArray()); - if(champName == "Cancel") break; - ChampionClass championClass = ReadAnEnum($"Please enter the champion class (possible values are: {Enum.GetNames().Aggregate("", (name, chaine) => $"{chaine} {name}")}):"); - string bio = ReadAString("Please enter the champion bio:"); - Champion champion = new Champion(champName, championClass, bio: bio); - DisplayCreationChampionMenu(champion); - await dataManager.ChampionsMgr.UpdateItem(somechampions.Single(c => c!.Name == champName), champion); - } - break; - default: - break; - } - - } - - public static void DisplayCreationChampionMenu(Champion champion) - { - Dictionary choices = new Dictionary() - { - [1] = "1- Add a skill", - [2] = "2- Add a skin", - [3] = "3- Add a characteristic", - [99] = "99- Finish" - }; - - while(true) - { - int input = DisplayAMenu(choices); - - switch(input) - { - case 1: - string skillName = ReadAString("Please enter the skill name:"); - SkillType skillType = ReadAnEnum($"Please enter the skill type (possible values are: {Enum.GetNames().Aggregate("", (name, chaine) => $"{chaine} {name}")}):"); - string skillDescription = ReadAString("Please enter the skill description:"); - Skill skill = new Skill(skillName, skillType, skillDescription); - champion.AddSkill(skill); - break; - case 2: - string skinName = ReadAString("Please enter the skin name:"); - string skinDescription = ReadAString("Please enter the skin description:"); - float skinPrice = ReadAFloat("Please enter the price of this skin:"); - Skin skin = new Skin(skinName, champion, skinPrice, description: skinDescription); - break; - case 3: - string characteristic = ReadAString("Please enter the characteristic:"); - int value = ReadAnInt("Please enter the value associated to this characteristic:"); - champion.AddCharacteristics(Tuple.Create(characteristic, value)); - break; - case 99: - return; - default: - break; - } - } - } - - private static int ReadAnInt(string message) - { - while(true) - { - WriteLine(message); - if(!int.TryParse(ReadLine(), out int result)) - { - continue; - } - return result; - } - } - - private static float ReadAFloat(string message) - { - while(true) - { - WriteLine(message); - if(!float.TryParse(ReadLine(), out float result)) - { - continue; - } - return result; - } - } - - private static string ReadAString(string message) - { - while(true) - { - WriteLine(message); - string? line = ReadLine(); - if(line == null) - { - continue; - } - return line!; - } - } - - private static TEnum ReadAnEnum(string message) where TEnum :struct - { - while(true) - { - WriteLine(message); - if(!Enum.TryParse(ReadLine(), out TEnum result)) - { - continue; - } - return result; - } - } - - private static string ReadAStringAmongPossibleValues(string message, params string[] possibleValues) - { - while(true) - { - WriteLine(message); - string? result = ReadLine(); - if(result == null) continue; - if(result != "Cancel" && !possibleValues.Contains(result!)) continue; - return result!; - } - } - } +using System.Diagnostics; +using Microsoft.Extensions.DependencyInjection; +using Model; +using StubLib; +using static System.Console; + +namespace ConsoleTests +{ + static class Program + { + static IDataManager dataManager = null!; + + static async Task Main(string[] args) + { + try + { + using var servicesProvider = new ServiceCollection() + .AddSingleton() + .BuildServiceProvider(); + + dataManager = servicesProvider.GetRequiredService(); + + await DisplayMainMenu(); + + Console.ReadLine(); + } + catch (Exception ex) + { + Debug.WriteLine(ex, "Stopped program because of exception"); + throw; + } + } + + public static async Task DisplayMainMenu() + { + Dictionary choices = new Dictionary() + { + [1] = "1- Manage Champions", + [2] = "2- Manage Skins", + [3] = "3- Manage Runes", + [4] = "4- Manage Rune Pages", + [99] = "99- Quit" + }; + + while(true) + { + int input = DisplayAMenu(choices); + + switch(input) + { + case 1: + await DisplayChampionsMenu(); + break; + case 2: + break; + case 3: + break; + case 4: + break; + case 99: + WriteLine("Bye bye!"); + return; + default: + break; + } + } + } + + private static int DisplayAMenu(Dictionary choices) + { + int input=-1; + while(true) + { + WriteLine("What is your choice?"); + WriteLine("--------------------"); + foreach(var choice in choices.OrderBy(kvp => kvp.Key).Select(kvp => kvp.Value)) + { + WriteLine(choice); + } + if(!int.TryParse(ReadLine(), out input) || input == -1) + { + WriteLine("I do not understand what your choice is. Please try again."); + continue; + } + break; + } + WriteLine($"You have chosen: {choices[input]}"); + WriteLine(); + return input; + } + + public static async Task DisplayChampionsMenu() + { + Dictionary choices = new Dictionary() + { + [0] = "0- Get number of champions", + [1] = "1- Get champions", + [2] = "2- Find champions by name", + [3] = "3- Find champions by characteristic", + [4] = "4- Find champions by class", + [5] = "5- Find champions by skill", + [6] = "6- Add new champion", + [7] = "7- Delete a champion", + [8] = "8- Update a champion", + }; + + int input = DisplayAMenu(choices); + + switch(input) + { + case 0: + int nb = await dataManager.ChampionsMgr.GetNbItems(); + WriteLine($"There are {nb} champions"); + WriteLine("**********************"); + break; + case 1: + { + int index = ReadAnInt("Please enter the page index"); + int count = ReadAnInt("Please enter the number of elements to display"); + WriteLine($"{count} champions of page {index+1}"); + var champions = await dataManager.ChampionsMgr.GetItems(index, count, nameof(Champion.Name)); + foreach(var champion in champions) + { + WriteLine($"\t{champion}"); + } + WriteLine("**********************"); + } + break; + case 2: + { + string substring = ReadAString("Please enter the substring to look for in the name of a champion"); + int index = ReadAnInt("Please enter the page index"); + int count = ReadAnInt("Please enter the number of elements to display"); + var champions = await dataManager.ChampionsMgr.GetItemsByName(substring, index, count, nameof(Champion.Name)); + foreach(var champion in champions) + { + WriteLine($"\t{champion}"); + } + WriteLine("**********************"); + } + break; + case 3: + { + string substring = ReadAString("Please enter the substring to look for in the characteristics of champions"); + int index = ReadAnInt("Please enter the page index"); + int count = ReadAnInt("Please enter the number of elements to display"); + var champions = await dataManager.ChampionsMgr.GetItemsByCharacteristic(substring, index, count, nameof(Champion.Name)); + foreach(var champion in champions) + { + WriteLine($"\t{champion}"); + } + WriteLine("**********************"); + } + break; + case 4: + { + ChampionClass championClass = ReadAnEnum($"Please enter the champion class (possible values are: {Enum.GetNames().Aggregate("", (name, chaine) => $"{chaine} {name}")}):"); + int index = ReadAnInt("Please enter the page index"); + int count = ReadAnInt("Please enter the number of elements to display"); + var champions = await dataManager.ChampionsMgr.GetItemsByClass(championClass, index, count, nameof(Champion.Name)); + foreach(var champion in champions) + { + WriteLine($"\t{champion}"); + } + WriteLine("**********************"); + } + break; + case 5: + { + string substring = ReadAString("Please enter the substring to look for in the skills of champions"); + int index = ReadAnInt("Please enter the page index"); + int count = ReadAnInt("Please enter the number of elements to display"); + var champions = await dataManager.ChampionsMgr.GetItemsBySkill(substring, index, count, nameof(Champion.Name)); + foreach(var champion in champions) + { + WriteLine($"\t{champion}"); + } + WriteLine("**********************"); + } + break; + case 6: + { + WriteLine("You are going to create a new champion."); + string name = ReadAString("Please enter the champion name:"); + ChampionClass championClass = ReadAnEnum($"Please enter the champion class (possible values are: {Enum.GetNames().Aggregate("", (name, chaine) => $"{chaine} {name}")}):"); + string bio = ReadAString("Please enter the champion bio:"); + Champion champion = new Champion(name, championClass, bio: bio); + DisplayCreationChampionMenu(champion); + _ = await dataManager.ChampionsMgr.AddItem(champion); + } + break; + case 7: + { + WriteLine("You are going to delete a champion."); + string name = ReadAString("Please enter the champion name:"); + var somechampions = await dataManager.ChampionsMgr.GetItemsByName(name, 0, 10, nameof(Champion.Name)); + var someChampionNames = somechampions.Select(c => c!.Name); + var someChampionNamesAsOneString = someChampionNames.Aggregate("", (name, chaine) => $"{chaine} {name}"); + string champName = ReadAStringAmongPossibleValues($"Who do you want to delete among these champions? (type \"Cancel\" to ... cancel) {someChampionNamesAsOneString}", + someChampionNames.ToArray()); + if(champName != "Cancel") + { + await dataManager.ChampionsMgr.DeleteItem(somechampions.Single(c => c!.Name == champName)); + } + } + break; + case 8: + { + WriteLine("You are going to update a champion."); + string name = ReadAString("Please enter the champion name:"); + var somechampions = await dataManager.ChampionsMgr.GetItemsByName(name, 0, 10, nameof(Champion.Name)); + var someChampionNames = somechampions.Select(c => c!.Name); + var someChampionNamesAsOneString = someChampionNames.Aggregate("", (name, chaine) => $"{chaine} {name}"); + string champName = ReadAStringAmongPossibleValues($"Who do you want to update among these champions? (type \"Cancel\" to ... cancel) {someChampionNamesAsOneString}", + someChampionNames.ToArray()); + if(champName == "Cancel") break; + ChampionClass championClass = ReadAnEnum($"Please enter the champion class (possible values are: {Enum.GetNames().Aggregate("", (name, chaine) => $"{chaine} {name}")}):"); + string bio = ReadAString("Please enter the champion bio:"); + Champion champion = new Champion(champName, championClass, bio: bio); + DisplayCreationChampionMenu(champion); + await dataManager.ChampionsMgr.UpdateItem(somechampions.Single(c => c!.Name == champName), champion); + } + break; + default: + break; + } + + } + + public static void DisplayCreationChampionMenu(Champion champion) + { + Dictionary choices = new Dictionary() + { + [1] = "1- Add a skill", + [2] = "2- Add a skin", + [3] = "3- Add a characteristic", + [99] = "99- Finish" + }; + + while(true) + { + int input = DisplayAMenu(choices); + + switch(input) + { + case 1: + string skillName = ReadAString("Please enter the skill name:"); + SkillType skillType = ReadAnEnum($"Please enter the skill type (possible values are: {Enum.GetNames().Aggregate("", (name, chaine) => $"{chaine} {name}")}):"); + string skillDescription = ReadAString("Please enter the skill description:"); + Skill skill = new Skill(skillName, skillType, skillDescription); + champion.AddSkill(skill); + break; + case 2: + string skinName = ReadAString("Please enter the skin name:"); + string skinDescription = ReadAString("Please enter the skin description:"); + float skinPrice = ReadAFloat("Please enter the price of this skin:"); + Skin skin = new Skin(skinName, champion, skinPrice, description: skinDescription); + break; + case 3: + string characteristic = ReadAString("Please enter the characteristic:"); + int value = ReadAnInt("Please enter the value associated to this characteristic:"); + champion.AddCharacteristics(Tuple.Create(characteristic, value)); + break; + case 99: + return; + default: + break; + } + } + } + + private static int ReadAnInt(string message) + { + while(true) + { + WriteLine(message); + if(!int.TryParse(ReadLine(), out int result)) + { + continue; + } + return result; + } + } + + private static float ReadAFloat(string message) + { + while(true) + { + WriteLine(message); + if(!float.TryParse(ReadLine(), out float result)) + { + continue; + } + return result; + } + } + + private static string ReadAString(string message) + { + while(true) + { + WriteLine(message); + string? line = ReadLine(); + if(line == null) + { + continue; + } + return line!; + } + } + + private static TEnum ReadAnEnum(string message) where TEnum :struct + { + while(true) + { + WriteLine(message); + if(!Enum.TryParse(ReadLine(), out TEnum result)) + { + continue; + } + return result; + } + } + + private static string ReadAStringAmongPossibleValues(string message, params string[] possibleValues) + { + while(true) + { + WriteLine(message); + string? result = ReadLine(); + if(result == null) continue; + if(result != "Cancel" && !possibleValues.Contains(result!)) continue; + return result!; + } + } + } } \ No newline at end of file -- 2.36.3 From 0b5a3f1d03608928cd23cbbcd8b8e74d8e976a3e Mon Sep 17 00:00:00 2001 From: Emre Date: Sat, 4 Mar 2023 22:46:18 +0100 Subject: [PATCH 08/10] Updating logs from ChampionsController class and create a new function for ChampionStub --- .../Controllers/v1/ChampionsController.cs | 12 +++---- .../Controllers/v2/ChampionsController.cs | 23 ++++++------ .../Sources/StubLib/StubData.Champions.cs | 35 +++++++++++-------- .../Tests/ApiTests/ChampionsControllerTest.cs | 2 +- 4 files changed, 40 insertions(+), 32 deletions(-) diff --git a/src/EntityFramework_LoL/Sources/ApiLol/Controllers/v1/ChampionsController.cs b/src/EntityFramework_LoL/Sources/ApiLol/Controllers/v1/ChampionsController.cs index 96ecf2b..2186cd5 100644 --- a/src/EntityFramework_LoL/Sources/ApiLol/Controllers/v1/ChampionsController.cs +++ b/src/EntityFramework_LoL/Sources/ApiLol/Controllers/v1/ChampionsController.cs @@ -28,7 +28,7 @@ namespace ApiLol.Controllers.v1 int nbTotal = await _manager.ChampionsMgr.GetNbItems(); - _logger.LogInformation($"method Get call"); + _logger.LogInformation("Executing {Action} with parameters: {Parameters}", nameof(Get), pageRequest); IEnumerable dtos = (await _manager.ChampionsMgr.GetItems(pageRequest.index, pageRequest.count)) .Select(x => x.ToDto()); return Ok(dtos); @@ -38,11 +38,11 @@ namespace ApiLol.Controllers.v1 [HttpGet("{name}")] public async Task Get(string name) { - _logger.LogInformation($"method GetByName call with {name}"); + _logger.LogInformation("method {Action} call with {name}", nameof(Get), name); var dtos = (await _manager.ChampionsMgr.GetItemsByName(name, 0, await _manager.ChampionsMgr.GetNbItems())) .Select(x => x.ToDto()); - return Ok(dtos); + return Ok(dtos.First()); } @@ -51,7 +51,7 @@ namespace ApiLol.Controllers.v1 public async Task Post([FromBody] ChampionDto champion) { - _logger.LogInformation($"method Post call"); + _logger.LogInformation("method {Action} call with {item}", nameof(Post), champion); return CreatedAtAction(nameof(Get), (await _manager.ChampionsMgr.AddItem(champion.ToModel())).ToDto()); @@ -62,7 +62,7 @@ namespace ApiLol.Controllers.v1 public async Task Put(string name, [FromBody] ChampionDto champion) { - _logger.LogInformation($"method Put call with {name}"); + _logger.LogInformation("method {Action} call with {name} and {item}", nameof(Put), name, champion); var dtos = (await _manager.ChampionsMgr.GetItemsByName(name, 0, await _manager.ChampionsMgr.GetNbItems())); return Ok(await _manager.ChampionsMgr.UpdateItem(dtos.First(), champion.ToModel())); @@ -74,7 +74,7 @@ namespace ApiLol.Controllers.v1 public async Task Delete(string name) { - _logger.LogInformation($"method Delete call with {name}"); + _logger.LogInformation("method {Action} call with {name}", nameof(Delete), name); var dtos = (await _manager.ChampionsMgr.GetItemsByName(name, 0, await _manager.ChampionsMgr.GetNbItems())); return Ok(await _manager.ChampionsMgr.DeleteItem(dtos.First())); diff --git a/src/EntityFramework_LoL/Sources/ApiLol/Controllers/v2/ChampionsController.cs b/src/EntityFramework_LoL/Sources/ApiLol/Controllers/v2/ChampionsController.cs index 1715b6a..092347b 100644 --- a/src/EntityFramework_LoL/Sources/ApiLol/Controllers/v2/ChampionsController.cs +++ b/src/EntityFramework_LoL/Sources/ApiLol/Controllers/v2/ChampionsController.cs @@ -1,4 +1,5 @@ using ApiLol.Mapper; +using Azure.Core; using DTO; using Microsoft.AspNetCore.Mvc; using Microsoft.IdentityModel.Tokens; @@ -35,7 +36,7 @@ namespace ApiLol.Controllers.v2 return BadRequest($"Champion limit exceed, max {nbTotal}"); } - _logger.LogInformation($"method Get call"); + _logger.LogInformation("Executing {Action} with parameters: {Parameters}", nameof(Get), pageRequest); IEnumerable dtos = (await _manager.ChampionsMgr.GetItems(pageRequest.index, pageRequest.count)) .Select(x => x.ToDto()); return Ok(dtos); @@ -58,13 +59,13 @@ namespace ApiLol.Controllers.v2 pageRequest.index = 0; pageRequest.count = nbTotal; } - else if (pageRequest.count * pageRequest.index >= nbTotal) + else if (pageRequest.count * pageRequest.index >= nbTotal || pageRequest.count > nbTotal) { _logger.LogWarning($"too many, maximum {nbTotal}"); return BadRequest($"Champion limit exceed, max {nbTotal}"); } - _logger.LogInformation($"method Get call"); + _logger.LogInformation("Executing {Action} with parameters: {Parameters}", nameof(Get), pageRequest); IEnumerable dtos = (await _manager.ChampionsMgr.GetItems(pageRequest.index, pageRequest.count)) .Select(x => x.ToDto()); return Ok(dtos); @@ -81,7 +82,7 @@ namespace ApiLol.Controllers.v2 { try { - _logger.LogInformation($"method GetByName call with {name}"); + _logger.LogInformation("method {Action} call with {name}", nameof(Get), name); var dtos = (await _manager.ChampionsMgr.GetItemsByName(name, 0, await _manager.ChampionsMgr.GetNbItems())) .Select(x => x.ToDto()); if (dtos.IsNullOrEmpty()) @@ -89,7 +90,7 @@ namespace ApiLol.Controllers.v2 _logger.LogWarning($"{name} was not found"); return NotFound(); } - return Ok(dtos); + return Ok(dtos.First()); } catch (Exception e) { @@ -103,7 +104,7 @@ namespace ApiLol.Controllers.v2 { try { - _logger.LogInformation($"method Post call"); + _logger.LogInformation("method {Action} call with {item}", nameof(Post), champion); var dtos = (await _manager.ChampionsMgr.GetItemsByName(champion.Name, 0, await _manager.ChampionsMgr.GetNbItems())); if (!dtos.IsNullOrEmpty()) { @@ -124,11 +125,11 @@ namespace ApiLol.Controllers.v2 { try { - _logger.LogInformation($"method Put call with {name}"); + _logger.LogInformation("method {Action} call with {name} and {item}", nameof(Put), name, champion); var dtos = (await _manager.ChampionsMgr.GetItemsByName(name, 0, await _manager.ChampionsMgr.GetNbItems())); if (dtos.IsNullOrEmpty()) { - return NotFound("Name not exist"); + return NotFound($"Name {name} not exist"); } // Checks if the new name exists if (name != champion.Name) @@ -152,6 +153,7 @@ namespace ApiLol.Controllers.v2 { try { + _logger.LogInformation("method {Action} call with {name}", nameof(GetChampionsSkins), name); var champions = await _manager.ChampionsMgr.GetItemsByName(name, 0, await _manager.ChampionsMgr.GetNbItems()); //skinsDTO IEnumerable res = champions.First().Skins.Select(e => e.ToDto()); @@ -169,6 +171,7 @@ namespace ApiLol.Controllers.v2 { try { + _logger.LogInformation("method {Action} call with {name}", nameof(GetChampionsSkills), name); var champions = await _manager.ChampionsMgr.GetItemsByName(name, 0, await _manager.ChampionsMgr.GetNbItems()); //SkillDTO IEnumerable res = champions.First().Skills.Select(e => e.ToDto()); @@ -187,11 +190,11 @@ namespace ApiLol.Controllers.v2 { try { - _logger.LogInformation($"method Delete call with {name}"); + _logger.LogInformation("method {Action} call with {name}", nameof(Delete), name); var dtos = (await _manager.ChampionsMgr.GetItemsByName(name, 0, await _manager.ChampionsMgr.GetNbItems())); if (dtos.IsNullOrEmpty()) { - _logger.LogWarning($"{name} was not found"); + _logger.LogWarning("{name} was not found", name); return BadRequest(); } return Ok(await _manager.ChampionsMgr.DeleteItem(dtos.First())); diff --git a/src/EntityFramework_LoL/Sources/StubLib/StubData.Champions.cs b/src/EntityFramework_LoL/Sources/StubLib/StubData.Champions.cs index c487e45..58fc925 100644 --- a/src/EntityFramework_LoL/Sources/StubLib/StubData.Champions.cs +++ b/src/EntityFramework_LoL/Sources/StubLib/StubData.Champions.cs @@ -3,19 +3,19 @@ using Model; namespace StubLib { - public partial class StubData - { - private List champions = new() - { - new Champion("Akali", ChampionClass.Assassin), - new Champion("Aatrox", ChampionClass.Fighter), - new Champion("Ahri", ChampionClass.Mage), - new Champion("Akshan", ChampionClass.Marksman), - new Champion("Bard", ChampionClass.Support), - new Champion("Alistar", ChampionClass.Tank), - }; - - public class ChampionsManager : IChampionsManager + public partial class StubData + { + private List champions = new() + { + new Champion("Akali", ChampionClass.Assassin), + new Champion("Aatrox", ChampionClass.Fighter), + new Champion("Ahri", ChampionClass.Mage), + new Champion("Akshan", ChampionClass.Marksman), + new Champion("Bard", ChampionClass.Support), + new Champion("Alistar", ChampionClass.Tank), + }; + + public class ChampionsManager : IChampionsManager { private readonly StubData parent; @@ -82,19 +82,24 @@ namespace StubLib (parent.championsAndRunePages .Where(tuple => tuple.Item2.Equals(runePage)) .Select(tuple => tuple.Item1) - .Skip(index*count).Take(count)); + .Skip(index * count).Take(count)); private Func filterByName = (champ, substring) => champ.Name.Equals(substring, StringComparison.InvariantCultureIgnoreCase); + private Func filterByNameContains = (champ, substring) => champ.Name.Contains(substring, StringComparison.InvariantCultureIgnoreCase); + public Task GetNbItemsByName(string substring) => parent.champions.GetNbItemsWithFilter(champ => filterByName(champ, substring)); public Task> GetItemsByName(string substring, int index, int count, string? orderingPropertyName, bool descending = false) => parent.champions.GetItemsWithFilterAndOrdering(champ => filterByName(champ, substring), index, count, orderingPropertyName, descending); + public Task> GetItemsByNameContains(string substring, int index, int count, string? orderingPropertyName, bool descending = false) + => parent.champions.GetItemsWithFilterAndOrdering(champ => filterByNameContains(champ, substring), index, count, orderingPropertyName, descending); + public Task UpdateItem(Champion? oldItem, Champion? newItem) => parent.champions.UpdateItem(oldItem, newItem); } - } + } } diff --git a/src/EntityFramework_LoL/Sources/Tests/ApiTests/ChampionsControllerTest.cs b/src/EntityFramework_LoL/Sources/Tests/ApiTests/ChampionsControllerTest.cs index 021b773..e7ba998 100644 --- a/src/EntityFramework_LoL/Sources/Tests/ApiTests/ChampionsControllerTest.cs +++ b/src/EntityFramework_LoL/Sources/Tests/ApiTests/ChampionsControllerTest.cs @@ -26,7 +26,7 @@ namespace ApiTests //Act var total = await stub.ChampionsMgr.GetNbItems(); - var champion = await champs.Get(new PageRequest() { index = 0, count = total }); + var champion = await champs.Get(new PageRequest()); //Assert var objectResult = champion as OkObjectResult; -- 2.36.3 From fa57eba9b82d8a01cac72237147d3fa102ffa6da Mon Sep 17 00:00:00 2001 From: Emre Date: Sun, 5 Mar 2023 19:38:58 +0100 Subject: [PATCH 09/10] Updating ChampionsController but not finish :white_check_mark: --- README.md | 17 ++++++++++ doc/Images/Api_Launcher.png | Bin 0 -> 5056 bytes doc/Images/Swagger_Version.png | Bin 0 -> 8276 bytes .../ApiLol/Controllers/SkinsController.cs | 9 +++-- .../Controllers/v1/ChampionsController.cs | 13 +++----- .../Controllers/v2/ChampionsController.cs | 31 ++++++++++-------- .../Sources/DTO/PageRequest.cs | 4 ++- .../Sources/Shared/IGenericDataManager.cs | 3 +- .../Sources/StubLib/StubData.Champions.cs | 6 ++-- .../Sources/StubLib/StubData.RunePages.cs | 8 +++++ .../Sources/StubLib/StubData.Runes.cs | 8 +++++ .../Sources/StubLib/StubData.Skins.cs | 9 ++++- 12 files changed, 77 insertions(+), 31 deletions(-) create mode 100644 doc/Images/Api_Launcher.png create mode 100644 doc/Images/Swagger_Version.png diff --git a/README.md b/README.md index f6ddbc1..b88ddc8 100644 --- a/README.md +++ b/README.md @@ -41,6 +41,23 @@ Vous pouvez le cloner via un terminal dans le répertoire de votre choix en util :information_source: *Si vous ne disposez pas de Visual Studio, allez sur le site [Microsoft Visual Studio](https://visualstudio.microsoft.com/fr/downloads/) pour pouvoir le télécharger !!!* +- ### Comment lancer l'API dotnet ? + +Pour pouvoir utiliser toutes les requêtes de l'API, il est nécessaire de récupérer le projet si cela n'a pas été fait, puis de le lancer à partir de Visual Studio. Vous pouvez directement cliquer sur la solution du projet. Ensuite, dans les projets de démarrage, choisissez "Api-Lol" : + +
+ +![Lancer l'API](doc/Images/Api_Launcher.png) + +
+ +Normalement, tout est bon et vous serez redirigé vers Swagger, qui est l'interface graphique permettant d'effectuer facilement des requêtes. Il vous suffit ensuite de choisir la version en haut à droite. La version 3.0 est normalement la plus récente et la plus performante en termes de gestion d'erreur : + +
+ +![Version API](doc/Images/Swagger_Version.png) + +
- ### Comment lancer Le projet Entity Framework ? diff --git a/doc/Images/Api_Launcher.png b/doc/Images/Api_Launcher.png new file mode 100644 index 0000000000000000000000000000000000000000..dece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RU?BO1 zQ^1bBUm>hJft?8p;i=9dLPOcglBPCt2@644S(OrrMr2L4x!CvM-o1Mx+sX9gBBj|= zYl$Shl4vpk1c>3>w^+=ZH$^Jk2^HVSD(soCNM;06f_*gM*+m94AQjVP+_M6 z`_nTU&xLJ57Fj?bLg4P2{8qmjdB)a?Y-?btC>mX8EiEWWxP)-@MbCF)&;#$H^yKDK zR!O%S{~NOTg>2D;U><%X`(>mM5EVi8;k35T=D4A1N zB@|3>rxWY`rD0TO-(brFj#L-A==FDQ3LhRLb0JU++O{*E>BVK#&SREJBa2&S`*EXQ z9T!%(`(8wS{Eq;SFWN#YD*ylh literal 0 HcmV?d00001 diff --git a/src/EntityFramework_LoL/Sources/ApiLol/Controllers/SkinsController.cs b/src/EntityFramework_LoL/Sources/ApiLol/Controllers/SkinsController.cs index ac1cc2d..bef0ede 100644 --- a/src/EntityFramework_LoL/Sources/ApiLol/Controllers/SkinsController.cs +++ b/src/EntityFramework_LoL/Sources/ApiLol/Controllers/SkinsController.cs @@ -54,20 +54,23 @@ namespace ApiLol.Controllers // POST api/ [HttpPost] - public async void Post([FromBody] string value) + public async Task Post([FromBody] string value) { + return Ok(); } // PUT api//5 [HttpPut("{name}")] - public async void Put(int id, [FromBody] string value) + public async Task Put(int id, [FromBody] string value) { + return Ok(); } // DELETE api//5 [HttpDelete("{name}")] - public async void Delete(string name) + public async Task Delete(string name) { + return Ok(); } } } diff --git a/src/EntityFramework_LoL/Sources/ApiLol/Controllers/v1/ChampionsController.cs b/src/EntityFramework_LoL/Sources/ApiLol/Controllers/v1/ChampionsController.cs index 2186cd5..62b7a03 100644 --- a/src/EntityFramework_LoL/Sources/ApiLol/Controllers/v1/ChampionsController.cs +++ b/src/EntityFramework_LoL/Sources/ApiLol/Controllers/v1/ChampionsController.cs @@ -25,12 +25,9 @@ namespace ApiLol.Controllers.v1 [HttpGet] public async Task Get([FromQuery] PageRequest pageRequest) { - - int nbTotal = await _manager.ChampionsMgr.GetNbItems(); - _logger.LogInformation("Executing {Action} with parameters: {Parameters}", nameof(Get), pageRequest); - IEnumerable dtos = (await _manager.ChampionsMgr.GetItems(pageRequest.index, pageRequest.count)) - .Select(x => x.ToDto()); + IEnumerable dtos = (await _manager.ChampionsMgr.GetItems(pageRequest.index, pageRequest.count, pageRequest.orderingPropertyName, pageRequest.descending)) + .Select(x => x.ToDto()); return Ok(dtos); } @@ -39,7 +36,7 @@ namespace ApiLol.Controllers.v1 public async Task Get(string name) { _logger.LogInformation("method {Action} call with {name}", nameof(Get), name); - var dtos = (await _manager.ChampionsMgr.GetItemsByName(name, 0, await _manager.ChampionsMgr.GetNbItems())) + var dtos = (await _manager.ChampionsMgr.GetItemByName(name, 0, await _manager.ChampionsMgr.GetNbItems())) .Select(x => x.ToDto()); return Ok(dtos.First()); @@ -63,7 +60,7 @@ namespace ApiLol.Controllers.v1 { _logger.LogInformation("method {Action} call with {name} and {item}", nameof(Put), name, champion); - var dtos = (await _manager.ChampionsMgr.GetItemsByName(name, 0, await _manager.ChampionsMgr.GetNbItems())); + var dtos = (await _manager.ChampionsMgr.GetItemByName(name, 0, await _manager.ChampionsMgr.GetNbItems())); return Ok(await _manager.ChampionsMgr.UpdateItem(dtos.First(), champion.ToModel())); @@ -75,7 +72,7 @@ namespace ApiLol.Controllers.v1 { _logger.LogInformation("method {Action} call with {name}", nameof(Delete), name); - var dtos = (await _manager.ChampionsMgr.GetItemsByName(name, 0, await _manager.ChampionsMgr.GetNbItems())); + var dtos = (await _manager.ChampionsMgr.GetItemByName(name, 0, await _manager.ChampionsMgr.GetNbItems())); return Ok(await _manager.ChampionsMgr.DeleteItem(dtos.First())); diff --git a/src/EntityFramework_LoL/Sources/ApiLol/Controllers/v2/ChampionsController.cs b/src/EntityFramework_LoL/Sources/ApiLol/Controllers/v2/ChampionsController.cs index 092347b..531787e 100644 --- a/src/EntityFramework_LoL/Sources/ApiLol/Controllers/v2/ChampionsController.cs +++ b/src/EntityFramework_LoL/Sources/ApiLol/Controllers/v2/ChampionsController.cs @@ -30,13 +30,17 @@ namespace ApiLol.Controllers.v2 try { int nbTotal = await _manager.ChampionsMgr.GetNbItems(); - if (pageRequest.count * pageRequest.index >= nbTotal) + if (pageRequest.count == 0) + { + pageRequest = new PageRequest() { index = 0, count = nbTotal }; + } + else if (pageRequest.count * pageRequest.index >= nbTotal) { _logger.LogWarning($"too many, maximum {nbTotal}"); return BadRequest($"Champion limit exceed, max {nbTotal}"); } - _logger.LogInformation("Executing {Action} with parameters: {Parameters}", nameof(Get), pageRequest); + _logger.LogInformation("Executing {Action} with parameters: {Parameters}", nameof(Get), pageRequest.count); IEnumerable dtos = (await _manager.ChampionsMgr.GetItems(pageRequest.index, pageRequest.count)) .Select(x => x.ToDto()); return Ok(dtos); @@ -54,14 +58,13 @@ namespace ApiLol.Controllers.v2 try { int nbTotal = await _manager.ChampionsMgr.GetNbItems(); - if (pageRequest == null) + if (pageRequest.count == 0) { - pageRequest.index = 0; - pageRequest.count = nbTotal; + pageRequest = new PageRequest() { index = 0, count = nbTotal }; } else if (pageRequest.count * pageRequest.index >= nbTotal || pageRequest.count > nbTotal) { - _logger.LogWarning($"too many, maximum {nbTotal}"); + _logger.LogWarning("too many, maximum {number}", nbTotal); return BadRequest($"Champion limit exceed, max {nbTotal}"); } @@ -83,7 +86,7 @@ namespace ApiLol.Controllers.v2 try { _logger.LogInformation("method {Action} call with {name}", nameof(Get), name); - var dtos = (await _manager.ChampionsMgr.GetItemsByName(name, 0, await _manager.ChampionsMgr.GetNbItems())) + var dtos = (await _manager.ChampionsMgr.GetItemByName(name, 0, await _manager.ChampionsMgr.GetNbItems())) .Select(x => x.ToDto()); if (dtos.IsNullOrEmpty()) { @@ -105,7 +108,7 @@ namespace ApiLol.Controllers.v2 try { _logger.LogInformation("method {Action} call with {item}", nameof(Post), champion); - var dtos = (await _manager.ChampionsMgr.GetItemsByName(champion.Name, 0, await _manager.ChampionsMgr.GetNbItems())); + var dtos = (await _manager.ChampionsMgr.GetItemByName(champion.Name, 0, await _manager.ChampionsMgr.GetNbItems())); if (!dtos.IsNullOrEmpty()) { return BadRequest("Name is already exist"); @@ -126,7 +129,7 @@ namespace ApiLol.Controllers.v2 try { _logger.LogInformation("method {Action} call with {name} and {item}", nameof(Put), name, champion); - var dtos = (await _manager.ChampionsMgr.GetItemsByName(name, 0, await _manager.ChampionsMgr.GetNbItems())); + var dtos = (await _manager.ChampionsMgr.GetItemByName(name, 0, await _manager.ChampionsMgr.GetNbItems())); if (dtos.IsNullOrEmpty()) { return NotFound($"Name {name} not exist"); @@ -134,8 +137,8 @@ namespace ApiLol.Controllers.v2 // Checks if the new name exists if (name != champion.Name) { - var dtos2 = (await _manager.ChampionsMgr.GetItemsByName(champion.Name, 0, await _manager.ChampionsMgr.GetNbItems())); - if (dtos.IsNullOrEmpty() || dtos2.Count() > 0) + var dtos2 = (await _manager.ChampionsMgr.GetItemByName(champion.Name, 0, await _manager.ChampionsMgr.GetNbItems())); + if (dtos2.IsNullOrEmpty() || dtos2.Count() > 0) { return BadRequest("Name is already exist"); } @@ -154,7 +157,7 @@ namespace ApiLol.Controllers.v2 try { _logger.LogInformation("method {Action} call with {name}", nameof(GetChampionsSkins), name); - var champions = await _manager.ChampionsMgr.GetItemsByName(name, 0, await _manager.ChampionsMgr.GetNbItems()); + var champions = await _manager.ChampionsMgr.GetItemByName(name, 0, await _manager.ChampionsMgr.GetNbItems()); //skinsDTO IEnumerable res = champions.First().Skins.Select(e => e.ToDto()); @@ -172,7 +175,7 @@ namespace ApiLol.Controllers.v2 try { _logger.LogInformation("method {Action} call with {name}", nameof(GetChampionsSkills), name); - var champions = await _manager.ChampionsMgr.GetItemsByName(name, 0, await _manager.ChampionsMgr.GetNbItems()); + var champions = await _manager.ChampionsMgr.GetItemByName(name, 0, await _manager.ChampionsMgr.GetNbItems()); //SkillDTO IEnumerable res = champions.First().Skills.Select(e => e.ToDto()); @@ -191,7 +194,7 @@ namespace ApiLol.Controllers.v2 try { _logger.LogInformation("method {Action} call with {name}", nameof(Delete), name); - var dtos = (await _manager.ChampionsMgr.GetItemsByName(name, 0, await _manager.ChampionsMgr.GetNbItems())); + var dtos = (await _manager.ChampionsMgr.GetItemByName(name, 0, await _manager.ChampionsMgr.GetNbItems())); if (dtos.IsNullOrEmpty()) { _logger.LogWarning("{name} was not found", name); diff --git a/src/EntityFramework_LoL/Sources/DTO/PageRequest.cs b/src/EntityFramework_LoL/Sources/DTO/PageRequest.cs index 2613958..c996118 100644 --- a/src/EntityFramework_LoL/Sources/DTO/PageRequest.cs +++ b/src/EntityFramework_LoL/Sources/DTO/PageRequest.cs @@ -9,6 +9,8 @@ namespace DTO public class PageRequest { public int index { get; set; } = 0; - public int count { get; set; } = 10; + public int count { get; set; } = 0; + public string? orderingPropertyName { get; set; } = null; + public bool descending { get; set; } = true; } } diff --git a/src/EntityFramework_LoL/Sources/Shared/IGenericDataManager.cs b/src/EntityFramework_LoL/Sources/Shared/IGenericDataManager.cs index ed3ac48..a3b4ee4 100644 --- a/src/EntityFramework_LoL/Sources/Shared/IGenericDataManager.cs +++ b/src/EntityFramework_LoL/Sources/Shared/IGenericDataManager.cs @@ -5,7 +5,8 @@ public interface IGenericDataManager Task> GetItems(int index, int count, string? orderingPropertyName = null, bool descending = false); Task GetNbItemsByName(string substring); Task> GetItemsByName(string substring, int index, int count, string? orderingPropertyName = null, bool descending = false); - Task UpdateItem(T oldItem, T newItem); + Task> GetItemByName(string substring, int index, int count, string? orderingPropertyName = null, bool descending = false); + Task UpdateItem(T oldItem, T newItem); Task AddItem(T item); Task DeleteItem(T item); } diff --git a/src/EntityFramework_LoL/Sources/StubLib/StubData.Champions.cs b/src/EntityFramework_LoL/Sources/StubLib/StubData.Champions.cs index 58fc925..d7f4bf1 100644 --- a/src/EntityFramework_LoL/Sources/StubLib/StubData.Champions.cs +++ b/src/EntityFramework_LoL/Sources/StubLib/StubData.Champions.cs @@ -92,11 +92,11 @@ namespace StubLib => parent.champions.GetNbItemsWithFilter(champ => filterByName(champ, substring)); public Task> GetItemsByName(string substring, int index, int count, string? orderingPropertyName, bool descending = false) - => parent.champions.GetItemsWithFilterAndOrdering(champ => filterByName(champ, substring), index, count, orderingPropertyName, descending); - - public Task> GetItemsByNameContains(string substring, int index, int count, string? orderingPropertyName, bool descending = false) => parent.champions.GetItemsWithFilterAndOrdering(champ => filterByNameContains(champ, substring), index, count, orderingPropertyName, descending); + public Task> GetItemByName(string substring, int index, int count, string? orderingPropertyName, bool descending = false) + => parent.champions.GetItemsWithFilterAndOrdering(champ => filterByName(champ, substring), index, count, orderingPropertyName, descending); + public Task UpdateItem(Champion? oldItem, Champion? newItem) => parent.champions.UpdateItem(oldItem, newItem); } diff --git a/src/EntityFramework_LoL/Sources/StubLib/StubData.RunePages.cs b/src/EntityFramework_LoL/Sources/StubLib/StubData.RunePages.cs index a08a947..2ec8285 100644 --- a/src/EntityFramework_LoL/Sources/StubLib/StubData.RunePages.cs +++ b/src/EntityFramework_LoL/Sources/StubLib/StubData.RunePages.cs @@ -27,6 +27,9 @@ namespace StubLib => this.parent = parent; private static Func filterByName + = (rp, substring) => rp.Name.Equals(substring, StringComparison.InvariantCultureIgnoreCase); + + private static Func filterByNameContains = (rp, substring) => rp.Name.Contains(substring, StringComparison.InvariantCultureIgnoreCase); private static Func filterByRune @@ -51,6 +54,11 @@ namespace StubLib .Skip(index*count).Take(count)); public Task> GetItemsByName(string substring, int index, int count, string? orderingPropertyName = null, bool descending = false) + => parent.runePages.GetItemsWithFilterAndOrdering( + rp => filterByNameContains(rp, substring), + index, count, orderingPropertyName, descending); + + public Task> GetItemByName(string substring, int index, int count, string? orderingPropertyName = null, bool descending = false) => parent.runePages.GetItemsWithFilterAndOrdering( rp => filterByName(rp, substring), index, count, orderingPropertyName, descending); diff --git a/src/EntityFramework_LoL/Sources/StubLib/StubData.Runes.cs b/src/EntityFramework_LoL/Sources/StubLib/StubData.Runes.cs index f0e8802..5ce8306 100644 --- a/src/EntityFramework_LoL/Sources/StubLib/StubData.Runes.cs +++ b/src/EntityFramework_LoL/Sources/StubLib/StubData.Runes.cs @@ -37,6 +37,9 @@ namespace StubLib = (rune, family) => rune.Family == family; private static Func filterByName + = (rune, substring) => rune.Name.Equals(substring, StringComparison.InvariantCultureIgnoreCase); + + private static Func filterByNameContains = (rune, substring) => rune.Name.Contains(substring, StringComparison.InvariantCultureIgnoreCase); public Task> GetItemsByFamily(RuneFamily family, int index, int count, string? orderingPropertyName = null, bool descending = false) @@ -45,6 +48,11 @@ namespace StubLib index, count, orderingPropertyName, descending); public Task> GetItemsByName(string substring, int index, int count, string? orderingPropertyName = null, bool descending = false) + => parent.runes.GetItemsWithFilterAndOrdering( + rune => filterByNameContains(rune, substring), + index, count, orderingPropertyName, descending); + + public Task> GetItemByName(string substring, int index, int count, string? orderingPropertyName = null, bool descending = false) => parent.runes.GetItemsWithFilterAndOrdering( rune => filterByName(rune, substring), index, count, orderingPropertyName, descending); diff --git a/src/EntityFramework_LoL/Sources/StubLib/StubData.Skins.cs b/src/EntityFramework_LoL/Sources/StubLib/StubData.Skins.cs index ff5fc08..5c44dfe 100644 --- a/src/EntityFramework_LoL/Sources/StubLib/StubData.Skins.cs +++ b/src/EntityFramework_LoL/Sources/StubLib/StubData.Skins.cs @@ -48,7 +48,9 @@ namespace StubLib private static Func filterByChampion = (skin, champion) => champion != null && skin.Champion.Equals(champion!); - private static Func filterByName = (skin, substring) => skin.Name.Contains(substring, StringComparison.InvariantCultureIgnoreCase); + private static Func filterByName = (skin, substring) => skin.Name.Equals(substring, StringComparison.InvariantCultureIgnoreCase); + + private static Func filterByNameContains = (skin, substring) => skin.Name.Contains(substring, StringComparison.InvariantCultureIgnoreCase); public Task> GetItemsByChampion(Champion? champion, int index, int count, string? orderingPropertyName = null, bool descending = false) => parent.skins.GetItemsWithFilterAndOrdering( @@ -56,6 +58,11 @@ namespace StubLib index, count, orderingPropertyName, descending); public Task> GetItemsByName(string substring, int index, int count, string? orderingPropertyName = null, bool descending = false) + => parent.skins.GetItemsWithFilterAndOrdering( + skin => filterByNameContains(skin, substring), + index, count, orderingPropertyName, descending); + + public Task> GetItemByName(string substring, int index, int count, string? orderingPropertyName = null, bool descending = false) => parent.skins.GetItemsWithFilterAndOrdering( skin => filterByName(skin, substring), index, count, orderingPropertyName, descending); -- 2.36.3 From 392fc430cca4d53580f16d5986fbba2ab3190344 Mon Sep 17 00:00:00 2001 From: "emre.kartal" Date: Tue, 7 Mar 2023 19:24:51 +0100 Subject: [PATCH 10/10] Finish Champions Controller (filtrage, pagination ...) and add function for UTChampion :white_check_mark: --- .vs/LolProject/v17/.suo | Bin 13824 -> 12800 bytes .../Controllers/v1/ChampionsController.cs | 7 ++- .../Controllers/v2/ChampionsController.cs | 38 ++++++------ .../Sources/ApiLol/Mapper/ChampionMapper.cs | 7 ++- .../Sources/ApiLol/Mapper/SkinMapper.cs | 4 +- .../Sources/DTO/PageRequest.cs | 4 +- .../Sources/Model/Champion.cs | 4 +- .../Tests/ApiTests/ChampionsControllerTest.cs | 58 ++++++++++++++++++ 8 files changed, 93 insertions(+), 29 deletions(-) diff --git a/.vs/LolProject/v17/.suo b/.vs/LolProject/v17/.suo index cb24cbd2ddbc7d4364303b162eecfeb1a9ccf79e..25c051124196f9ca1e34268cca7c7a9a6f703eec 100644 GIT binary patch delta 1092 zcmZq3X-L`N!^FrwS&>Pev!FmoK`ihlquAt9rgM`Iiy2NnpvN+~g4vswfrWvAffb1V z1HoiQNtMZ8m^ECufdc=40>V%U0U*r*#5_d6ZHwG?XoW$e< zb-{+&0>rz3UB!b7YBI=FJ|J5N$`=LFAXk8FgxL;K!w;1Qu|aakuGqxo!NLJ@5=av4 z#}Yn&UPdOM2uvHq=O9s#Wnw65`2%=BerH1xoTSe(`3HXh)eU7do%~b$6fYylp`h@E zI#^@#4+%jgWm5}dvm|qKQ(a5r)Kpy);}iqk#6&Z5T|+}ti&P8qR3ih^$vV_UPGzotVxAmgPG?o^rVU;s>3 zB0iIkh#5?7Pyhy!h!2k>P=N%pq7u=bNgB>Tn{6jI$T{;ef>N0XvVt#i0X$Mr0hkXa z8M17ykoRB|ILG$3bJ5{~!}{tqOZ*mfIpwBq@zoHAoD@u-&4>K7~{-PAX14;uR z?H~a0kFq~Vk`)w{ER%nVdh;*?S+Y=N5G7*gc^N^84V2Ij8pZv2!HFG|5n!T|q*xe5 zCjV4CMZASxV5KEuU}sEr00oekH&**XIIvhHe;k+ZWkJ5j5uBU9Xz(yj(s9A!SqWf* S2gN#STGJ6`+{|tCl^FmIfRl*; delta 1148 zcmb_b&1(};5YO9eZCZDe&1dteX^i-l#7#`81;N%x2_}$~_U1)XlOl)+c|!4G(5ndD zIp|sZ1Js<06$QbAR`BA*lYhbr&80fC`&Kp{q=zmH@4er=H^2GK%noi1?!0PB%m=g5 z@u}U7w=W-G`p)8TU-}I1r84Z4WZ3jJRQ4M`$>Z_R3SUEcFukYG_z+Ohjta*eCFM)tMnQYM@|+n`Q&4KKeQ?Uj{7Isu9Hw!NqD90xAXcJ9x^Ud$rJLe& z)4!Rn%RVP*OAYt8R1d{;;@BGfEvU_0hDU)b3Wb>wB;+*C%di({A3_*52cu|1p~5+8 z?3`k4MHY<2Zl@G$sf?$NM|L^{96>PYb_|YT>d7X2kaXawCr0k7 zr7q*X!*gF$tI**w^wgR!?E;L5%px!fezJx|m*nAIC@7sM_tq=D?n1e!S2~?ywKv}_ z-n>|@6uay53%y=Pug+DW5dCIkHPCWZg~sK86Vp}nQkj_ z;rRQmEDtv`b*6cKKKo^EKdnCav6^@X*SBCve+X^;9^42o8QB`t@&lDk{PP;jY+IQ` zkOs^N349jYLMNI@2c4kG%P`7({6AH)X60)4t6}Z!7U6$KAshkrRHTrJ+Bv4zB$TQ! zHUXjvL-VY{jC>vH-U9F}-aG_R=NeYu+zkO9va4 dtos = (await _manager.ChampionsMgr.GetItems(pageRequest.index, pageRequest.count, pageRequest.orderingPropertyName, pageRequest.descending)) .Select(x => x.ToDto()); return Ok(dtos); + } // GET api//5 @@ -60,9 +61,9 @@ namespace ApiLol.Controllers.v1 { _logger.LogInformation("method {Action} call with {name} and {item}", nameof(Put), name, champion); - var dtos = (await _manager.ChampionsMgr.GetItemByName(name, 0, await _manager.ChampionsMgr.GetNbItems())); - - return Ok(await _manager.ChampionsMgr.UpdateItem(dtos.First(), champion.ToModel())); + var dtos = (await _manager.ChampionsMgr.GetItemByName(name, 0, await _manager.ChampionsMgr.GetNbItems())); + + return Ok((await _manager.ChampionsMgr.UpdateItem(dtos.First(), champion.ToModel())).ToDto()); } diff --git a/src/EntityFramework_LoL/Sources/ApiLol/Controllers/v2/ChampionsController.cs b/src/EntityFramework_LoL/Sources/ApiLol/Controllers/v2/ChampionsController.cs index 531787e..838fe00 100644 --- a/src/EntityFramework_LoL/Sources/ApiLol/Controllers/v2/ChampionsController.cs +++ b/src/EntityFramework_LoL/Sources/ApiLol/Controllers/v2/ChampionsController.cs @@ -45,9 +45,9 @@ namespace ApiLol.Controllers.v2 .Select(x => x.ToDto()); return Ok(dtos); } - catch (Exception e) + catch (Exception error) { - return BadRequest(e.Message); + return BadRequest(error.Message); } } @@ -69,13 +69,13 @@ namespace ApiLol.Controllers.v2 } _logger.LogInformation("Executing {Action} with parameters: {Parameters}", nameof(Get), pageRequest); - IEnumerable dtos = (await _manager.ChampionsMgr.GetItems(pageRequest.index, pageRequest.count)) + IEnumerable dtos = (await _manager.ChampionsMgr.GetItems(pageRequest.index, pageRequest.count, pageRequest.orderingPropertyName, pageRequest.descending)) .Select(x => x.ToDto()); - return Ok(dtos); + return Ok(new { Data = dtos, index = pageRequest.index, count = pageRequest.count, total = nbTotal}); } - catch (Exception e) + catch (Exception error) { - return BadRequest(e.Message); + return BadRequest(error.Message); } } @@ -95,9 +95,9 @@ namespace ApiLol.Controllers.v2 } return Ok(dtos.First()); } - catch (Exception e) + catch (Exception error) { - return BadRequest(e.Message); + return BadRequest(error.Message); } } @@ -116,9 +116,9 @@ namespace ApiLol.Controllers.v2 return CreatedAtAction(nameof(Get), (await _manager.ChampionsMgr.AddItem(champion.ToModel())).ToDto()); } - catch (Exception e) + catch (Exception error) { - return BadRequest(e.Message); + return BadRequest(error.Message); } } @@ -143,11 +143,11 @@ namespace ApiLol.Controllers.v2 return BadRequest("Name is already exist"); } } - return Ok(await _manager.ChampionsMgr.UpdateItem(dtos.First(), champion.ToModel())); + return Ok((await _manager.ChampionsMgr.UpdateItem(dtos.First(), champion.ToModel())).ToDto()); } - catch (Exception e) + catch (Exception error) { - return BadRequest(e.Message); + return BadRequest(error.Message); } } @@ -163,9 +163,9 @@ namespace ApiLol.Controllers.v2 return Ok(res); } - catch (Exception e) + catch (Exception error) { - return BadRequest(e.Message); + return BadRequest(error.Message); } } @@ -181,9 +181,9 @@ namespace ApiLol.Controllers.v2 return Ok(res); } - catch (Exception e) + catch (Exception error) { - return BadRequest(e.Message); + return BadRequest(error.Message); } } @@ -202,9 +202,9 @@ namespace ApiLol.Controllers.v2 } return Ok(await _manager.ChampionsMgr.DeleteItem(dtos.First())); } - catch (Exception e) + catch (Exception error) { - return BadRequest(e.Message); + return BadRequest(error.Message); } } } diff --git a/src/EntityFramework_LoL/Sources/ApiLol/Mapper/ChampionMapper.cs b/src/EntityFramework_LoL/Sources/ApiLol/Mapper/ChampionMapper.cs index 0e9e94c..094739d 100644 --- a/src/EntityFramework_LoL/Sources/ApiLol/Mapper/ChampionMapper.cs +++ b/src/EntityFramework_LoL/Sources/ApiLol/Mapper/ChampionMapper.cs @@ -21,7 +21,12 @@ namespace ApiLol.Mapper public static Champion ToModel(this ChampionDto championDto) { - return new Champion(championDto.Name, championDto.Class.ToModel(), championDto.Icon, championDto.Image.Base64, championDto.Bio); + var champ = new Champion(championDto.Name, championDto.Class.ToModel(), championDto.Icon, championDto.Image.Base64, championDto.Bio); + foreach(var skin in championDto.Skins) + { + champ.AddSkin(skin.ToModel(champ)); + } + return champ; } } diff --git a/src/EntityFramework_LoL/Sources/ApiLol/Mapper/SkinMapper.cs b/src/EntityFramework_LoL/Sources/ApiLol/Mapper/SkinMapper.cs index 7104d37..9b5273b 100644 --- a/src/EntityFramework_LoL/Sources/ApiLol/Mapper/SkinMapper.cs +++ b/src/EntityFramework_LoL/Sources/ApiLol/Mapper/SkinMapper.cs @@ -30,9 +30,9 @@ namespace ApiLol.Mapper }; } - public static Skin ToModel(this SkinDto skinDto) + public static Skin ToModel(this SkinDto skinDto, Champion champ) { - return new Skin(skinDto.Name, null, skinDto.Price, skinDto.Icon, skinDto.Image.Base64, skinDto.Description); + return new Skin(skinDto.Name, champ, skinDto.Price, skinDto.Icon, skinDto.Image.Base64, skinDto.Description); } } diff --git a/src/EntityFramework_LoL/Sources/DTO/PageRequest.cs b/src/EntityFramework_LoL/Sources/DTO/PageRequest.cs index c996118..a947eb9 100644 --- a/src/EntityFramework_LoL/Sources/DTO/PageRequest.cs +++ b/src/EntityFramework_LoL/Sources/DTO/PageRequest.cs @@ -10,7 +10,7 @@ namespace DTO { public int index { get; set; } = 0; public int count { get; set; } = 0; - public string? orderingPropertyName { get; set; } = null; - public bool descending { get; set; } = true; + public string? orderingPropertyName { get; set; } = "Name"; + public bool descending { get; set; } = false; } } diff --git a/src/EntityFramework_LoL/Sources/Model/Champion.cs b/src/EntityFramework_LoL/Sources/Model/Champion.cs index b8b369b..313e607 100644 --- a/src/EntityFramework_LoL/Sources/Model/Champion.cs +++ b/src/EntityFramework_LoL/Sources/Model/Champion.cs @@ -62,7 +62,7 @@ public class Champion : IEquatable public ImmutableHashSet Skills => skills.ToImmutableHashSet(); private HashSet skills = new HashSet(); - internal bool AddSkin(Skin skin) + public bool AddSkin(Skin skin) { if (skins.Contains(skin)) return false; @@ -70,7 +70,7 @@ public class Champion : IEquatable return true; } - internal bool RemoveSkin(Skin skin) + public bool RemoveSkin(Skin skin) => skins.Remove(skin); public bool AddSkill(Skill skill) diff --git a/src/EntityFramework_LoL/Sources/Tests/ApiTests/ChampionsControllerTest.cs b/src/EntityFramework_LoL/Sources/Tests/ApiTests/ChampionsControllerTest.cs index e7ba998..078a64a 100644 --- a/src/EntityFramework_LoL/Sources/Tests/ApiTests/ChampionsControllerTest.cs +++ b/src/EntityFramework_LoL/Sources/Tests/ApiTests/ChampionsControllerTest.cs @@ -63,6 +63,64 @@ namespace ApiTests var champions = objectResult?.Value as ChampionDto; Assert.IsNotNull(champions); + } + + [TestMethod] + public async Task TestPutChampion() + { + //Arange + var ChampionDto = new ChampionDto + { + Name = "Sylas", + Bio = "Good", + Class = ChampionClassDto.Tank, + Icon = "", + Image = new LargeImageDto() { Base64 = "" }, + Skins = new List() + }; + var ChampionDtoPut = new ChampionDto + { + Name = "Sylas", + Bio = "Bad", + Class = ChampionClassDto.Tank, + Icon = "", + Image = new LargeImageDto() { Base64 = "" }, + Skins = new List() + }; + + //Act + await champs.Post(ChampionDto); + var championsResult = await champs.Put(ChampionDto.Name, ChampionDtoPut); + + //Assert + var objectResult = championsResult as OkObjectResult; + Assert.IsNotNull(objectResult); + + var champions = objectResult?.Value as ChampionDto; + Assert.IsNotNull(champions); + + Assert.AreNotEqual(ChampionDto.Bio, champions.Bio); + Assert.AreEqual(ChampionDtoPut.Bio, champions.Bio); + + } + + [TestMethod] + public async Task TestDeleteChampion() + { + //Arange + + + //Act + var total = await stub.ChampionsMgr.GetNbItems(); + var championsResult = await champs.Delete("Akali"); + + //Assert + var objectResult = championsResult as OkObjectResult; + Assert.IsNotNull(objectResult); + + Assert.AreEqual(objectResult.Value, true); + Assert.AreNotEqual(await stub.ChampionsMgr.GetNbItems(), total); + } } -- 2.36.3