diff --git a/TP Blazor/App.razor b/TP Blazor/App.razor index 6fd3ed1..09ed54d 100644 --- a/TP Blazor/App.razor +++ b/TP Blazor/App.razor @@ -1,12 +1,14 @@ - - - - - - - Not found - -

Sorry, there's nothing at this address.

-
-
-
+ + + + + + + + Not found + +

Sorry, there's nothing at this address.

+
+
+
+
\ No newline at end of file diff --git a/TP Blazor/Factories/ItemFactory.cs b/TP Blazor/Factories/ItemFactory.cs new file mode 100644 index 0000000..c716645 --- /dev/null +++ b/TP Blazor/Factories/ItemFactory.cs @@ -0,0 +1,48 @@ +using TP_Blazor.Models; + +namespace TP_Blazor.Factories; + +public static class ItemFactory +{ + public static ItemModel ToModel(Item item, byte[] imageContent) + { + return new ItemModel + { + Id = item.Id, + DisplayName = item.DisplayName, + Name = item.Name, + RepairWith = item.RepairWith, + EnchantCategories = item.EnchantCategories, + MaxDurability = item.MaxDurability, + StackSize = item.StackSize, + ImageContent = imageContent + }; + } + + public static Item Create(ItemModel model) + { + return new Item + { + Id = model.Id, + DisplayName = model.DisplayName, + Name = model.Name, + RepairWith = model.RepairWith, + EnchantCategories = model.EnchantCategories, + MaxDurability = model.MaxDurability, + StackSize = model.StackSize, + CreatedDate = DateTime.Now + }; + } + + public static void Update(Item item, ItemModel model) + { + item.DisplayName = model.DisplayName; + item.Name = model.Name; + item.RepairWith = model.RepairWith; + item.EnchantCategories = model.EnchantCategories; + item.MaxDurability = model.MaxDurability; + item.StackSize = model.StackSize; + item.UpdatedDate = DateTime.Now; + } + +} \ No newline at end of file diff --git a/TP Blazor/Modals/DeleteConfirmation.razor b/TP Blazor/Modals/DeleteConfirmation.razor new file mode 100644 index 0000000..561147f --- /dev/null +++ b/TP Blazor/Modals/DeleteConfirmation.razor @@ -0,0 +1,10 @@ +
+ +

+ Are you sure you want to delete @item.DisplayName ? +

+ + + + +
\ No newline at end of file diff --git a/TP Blazor/Modals/DeleteConfirmation.razor.cs b/TP Blazor/Modals/DeleteConfirmation.razor.cs new file mode 100644 index 0000000..b46bc18 --- /dev/null +++ b/TP Blazor/Modals/DeleteConfirmation.razor.cs @@ -0,0 +1,37 @@ +using Blazored.Modal; +using Blazored.Modal.Services; +using Microsoft.AspNetCore.Components; +using TP_Blazor.Models; +using TP_Blazor.Services; + +namespace TP_Blazor.Modals; + +public partial class DeleteConfirmation +{ + [CascadingParameter] + public BlazoredModalInstance ModalInstance { get; set; } + + [Inject] + public IDataService DataService { get; set; } + + [Parameter] + public int Id { get; set; } + + private Item item = new Item(); + + protected override async Task OnInitializedAsync() + { + // Get the item + item = await DataService.GetById(Id); + } + + void ConfirmDelete() + { + ModalInstance.CloseAsync(ModalResult.Ok(true)); + } + + void Cancel() + { + ModalInstance.CancelAsync(); + } +} \ No newline at end of file diff --git a/TP Blazor/Pages/Edit.razor b/TP Blazor/Pages/Edit.razor new file mode 100644 index 0000000..9aecaa2 --- /dev/null +++ b/TP Blazor/Pages/Edit.razor @@ -0,0 +1,81 @@ +@page "/edit/{Id:int}" + +

Edit

+ + + + +

+ +

+

+ +

+

+ +

+

+ +

+

+ Enchant categories: +

+ @foreach (var item in enchantCategories) + { + + } +
+

+

+ Repair with: +

+ @foreach (var item in repairWith) + { + + } +
+

+

+ +

+

+ +

+

+ +

+ + +
\ No newline at end of file diff --git a/TP Blazor/Pages/Edit.razor.cs b/TP Blazor/Pages/Edit.razor.cs new file mode 100644 index 0000000..99ee15c --- /dev/null +++ b/TP Blazor/Pages/Edit.razor.cs @@ -0,0 +1,106 @@ +using Microsoft.AspNetCore.Components; +using Microsoft.AspNetCore.Components.Forms; +using TP_Blazor.Factories; +using TP_Blazor.Models; +using TP_Blazor.Services; + +namespace TP_Blazor.Pages; + +public partial class Edit +{ + [Parameter] + public int Id { get; set; } + + private List enchantCategories = new List() { "armor", "armor_head", "armor_chest", "weapon", "digger", "breakable", "vanishable" }; + + /// + /// The current item model + /// + private ItemModel itemModel = new() + { + EnchantCategories = new List(), + RepairWith = new List() + }; + + /// + /// The default repair with. + /// + private List repairWith = new List() { "oak_planks", "spruce_planks", "birch_planks", "jungle_planks", "acacia_planks", "dark_oak_planks", "crimson_planks", "warped_planks" }; + + [Inject] + public IDataService DataService { get; set; } + + [Inject] + public NavigationManager NavigationManager { get; set; } + + [Inject] + public IWebHostEnvironment WebHostEnvironment { get; set; } + + protected override async Task OnInitializedAsync() + { + var item = await DataService.GetById(Id); + + var fileContent = await File.ReadAllBytesAsync($"{WebHostEnvironment.WebRootPath}/images/default.png"); + + if (File.Exists($"{WebHostEnvironment.WebRootPath}/images/{itemModel.Name}.png")) + { + fileContent = await File.ReadAllBytesAsync($"{WebHostEnvironment.WebRootPath}/images/{item.Name}.png"); + } + + // Set the model with the item + itemModel =ItemFactory.ToModel(item, fileContent); + } + + private async void HandleValidSubmit() + { + await DataService.Update(Id, itemModel); + + NavigationManager.NavigateTo("list"); + } + + private async Task LoadImage(InputFileChangeEventArgs e) + { + // Set the content of the image to the model + using (var memoryStream = new MemoryStream()) + { + await e.File.OpenReadStream().CopyToAsync(memoryStream); + itemModel.ImageContent = memoryStream.ToArray(); + } + } + + private void OnEnchantCategoriesChange(string item, object checkedValue) + { + if ((bool)checkedValue) + { + if (!itemModel.EnchantCategories.Contains(item)) + { + itemModel.EnchantCategories.Add(item); + } + + return; + } + + if (itemModel.EnchantCategories.Contains(item)) + { + itemModel.EnchantCategories.Remove(item); + } + } + + private void OnRepairWithChange(string item, object checkedValue) + { + if ((bool)checkedValue) + { + if (!itemModel.RepairWith.Contains(item)) + { + itemModel.RepairWith.Add(item); + } + + return; + } + + if (itemModel.RepairWith.Contains(item)) + { + itemModel.RepairWith.Remove(item); + } + } +} \ No newline at end of file diff --git a/TP Blazor/Pages/List.razor b/TP Blazor/Pages/List.razor index 94fc595..adfbf1f 100644 --- a/TP Blazor/Pages/List.razor +++ b/TP Blazor/Pages/List.razor @@ -2,7 +2,11 @@ @using TP_Blazor.Models

Liste

-@*@if (items!=null) { +@*@if (items!=null) + { +
+ + @@ -10,7 +14,9 @@ - + + + @foreach (var item in items) { @@ -23,8 +29,24 @@ } -
Id Display Name Stack SizeEnchant Categories Repair With Created Date
@item.CreatedDate.ToShortDateString()
}*@ + + + + }*@ + +
+ + Ajouter + +
+ + + + + @context.DisplayName + + @@ -39,4 +61,10 @@ + + + Editer + + + \ No newline at end of file diff --git a/TP Blazor/Pages/List.razor.cs b/TP Blazor/Pages/List.razor.cs index 58790ce..52454df 100644 --- a/TP Blazor/Pages/List.razor.cs +++ b/TP Blazor/Pages/List.razor.cs @@ -2,6 +2,12 @@ using Blazorise.DataGrid; using Microsoft.AspNetCore.Components; using TP_Blazor.Models; +using Blazored; +using Blazored.LocalStorage; +using Blazored.Modal; +using Blazored.Modal.Services; +using TP_Blazor.Modals; +using TP_Blazor.Services; namespace TP_Blazor.Pages; @@ -15,31 +21,73 @@ public partial class List private int totalItem; [Inject] - public HttpClient Http { get; set; } + public HttpClient HttpClient { get; set; } + + [Inject] + public IDataService DataService { get; set; } + + [CascadingParameter] + public IModalService Modal { get; set; } [Inject] public NavigationManager NavigationManager { get; set; } + [Inject] + IWebHostEnvironment WebHostEnvironment { get; set; } + + [Inject] + public ILocalStorageService LocalStorage { get; set; } + private async Task OnReadData(DataGridReadDataEventArgs e) { if (e.CancellationToken.IsCancellationRequested) { return; } - var response = (await Http.GetFromJsonAsync($"{NavigationManager.BaseUri}fake-data.json")).Skip((e.Page - 1) * e.PageSize).Take(e.PageSize).ToList(); + //var response = (await HttpClient.GetFromJsonAsync($"{NavigationManager.BaseUri}fake-data.json")).Skip((e.Page - 1) * e.PageSize).Take(e.PageSize).ToList(); if (!e.CancellationToken.IsCancellationRequested) { - totalItem = (await Http.GetFromJsonAsync>($"{NavigationManager.BaseUri}fake-data.json")).Count; - items = new List(response); // an actual data for the current page + //totalItem = (await HttpClient.GetFromJsonAsync>($"{NavigationManager.BaseUri}fake-data.json")).Count; + //items = new List(response); // an actual data for the current page + items = await DataService.List(e.Page, e.PageSize); + totalItem = await DataService.Count(); } } - protected override void OnAfterRender(bool firstRender) + protected override async Task OnAfterRenderAsync(bool firstRender) { - base.OnAfterRender(firstRender); + if (!firstRender) + { + return; + } + + var currentData = await LocalStorage.GetItemAsync("data"); + + if (currentData==null) + { + var originalData = HttpClient.GetFromJsonAsync($"{NavigationManager.BaseUri}fake-data.json").Result; + await LocalStorage.SetItemAsync("data", originalData); + } } + + private async void OnDelete(int id) + { + var parameters = new ModalParameters(); + parameters.Add(nameof(Item.Id), id); + var modal = Modal.Show("Delete Confirmation", parameters); + var result = await modal.Result; + if (result.Cancelled) + { + return; + } + + await DataService.Delete(id); + + // Reload the page + NavigationManager.NavigateTo("list", true); + } } diff --git a/TP Blazor/Pages/_Host.cshtml b/TP Blazor/Pages/_Host.cshtml index b6b8f8c..cbad39c 100644 --- a/TP Blazor/Pages/_Host.cshtml +++ b/TP Blazor/Pages/_Host.cshtml @@ -16,6 +16,7 @@ + @@ -34,6 +35,7 @@ 🗙 - + + diff --git a/TP Blazor/Program.cs b/TP Blazor/Program.cs index 371def7..7261993 100644 --- a/TP Blazor/Program.cs +++ b/TP Blazor/Program.cs @@ -1,3 +1,4 @@ +using System.Globalization; using Microsoft.AspNetCore.Components; using Microsoft.AspNetCore.Components.Web; using TP_Blazor.Data; @@ -6,6 +7,10 @@ using Blazorise.Icons.FontAwesome; using Microsoft.Extensions.DependencyInjection; using Blazorise.Bootstrap; using Blazored.LocalStorage; +using TP_Blazor.Services; +using Blazored.Modal; +using Microsoft.AspNetCore.Localization; +using Microsoft.Extensions.Options; var builder = WebApplication.CreateBuilder(args); @@ -16,8 +21,18 @@ builder.Services.AddSingleton(); builder.Services.AddHttpClient(); builder.Services.AddBlazorise() .AddBootstrapProviders() - .AddBlazoredLocalStorage() .AddFontAwesomeIcons(); +builder.Services.AddBlazoredLocalStorage(); +builder.Services.AddBlazoredModal(); +builder.Services.AddControllers(); +builder.Services.AddLocalization(opt=>{opt.ResourcesPath="Resources";}); +builder.Services.Configure(option => +{ + option.DefaultRequestCulture = new RequestCulture(new CultureInfo("en-US")); + option.SupportedCultures = new List { new CultureInfo("en-US"), new CultureInfo("fr-FR") }; + option.SupportedUICultures = new List { new CultureInfo("en-US"), new CultureInfo("fr-FR") }; +}); +builder.Services.AddScoped(); var app = builder.Build(); @@ -32,6 +47,18 @@ app.UseStaticFiles(); app.UseRouting(); +var options =((IApplicationBuilder)app).ApplicationServices.GetService>(); + +if (options?.Value != null) +{ + app.UseRequestLocalization(options.Value); +} + +app.UseEndpoints(endpoints => +{ + endpoints.MapControllers(); +}); + app.MapBlazorHub(); app.MapFallbackToPage("/_Host"); diff --git a/TP Blazor/Services/DataLocalService.cs b/TP Blazor/Services/DataLocalService.cs new file mode 100644 index 0000000..f8ebdf0 --- /dev/null +++ b/TP Blazor/Services/DataLocalService.cs @@ -0,0 +1,134 @@ +using Blazored.LocalStorage; +using Microsoft.AspNetCore.Components; +using TP_Blazor.Factories; +using TP_Blazor.Models; + +namespace TP_Blazor.Services; + +public class DataLocalService:IDataService +{ + private readonly HttpClient _httpClient; + private readonly ILocalStorageService _localStorageService; + private readonly NavigationManager _navigationManager; + private readonly IWebHostEnvironment _webHostEnvironment; + + public DataLocalService(HttpClient httpClient, ILocalStorageService localStorageService, NavigationManager navigationManager, IWebHostEnvironment webHostEnvironment) + { + _httpClient = httpClient; + _localStorageService = localStorageService; + _navigationManager = navigationManager; + _webHostEnvironment = webHostEnvironment; + } + + public async Task Add(ItemModel item) + { + var currentItems = await _localStorageService.GetItemAsync>("data"); + item.Id = currentItems.Max(s=>s.Id)+1; + // currentItems.Add(new Item + // { + // Id = item.Id, + // Name = item.Name, + // DisplayName = item.DisplayName, + // RepairWith = item.RepairWith, + // EnchantCategories = item.EnchantCategories, + // MaxDurability = item.MaxDurability, + // StackSize = item.StackSize, + // CreatedDate = DateTime.Now + // }); + currentItems.Add(ItemFactory.Create(item)); + + var imagePathsInfo = new DirectoryInfo(Path.Combine($"{_webHostEnvironment.ContentRootPath}/images")); + if (!imagePathsInfo.Exists) + { + imagePathsInfo.Create(); + } + + var fileName = new FileInfo($"{imagePathsInfo}/{item.Name}.png"); + await File.WriteAllBytesAsync(fileName.FullName, item.ImageContent); + await _localStorageService.SetItemAsync("data", currentItems); + } + + public async Task Count() + { + var currentItems = _localStorageService.GetItemAsync("data"); + if (currentItems== null) + { + var originalItems = _httpClient.GetFromJsonAsync($"f{_navigationManager.BaseUri}ake-data.json"); + await _localStorageService.SetItemAsync("data", originalItems); + } + return (await _localStorageService.GetItemAsync("data")).Length; + } + + public async Task> List(int page, int pageSize) + { + var currentItems = _localStorageService.GetItemAsync("data"); + if (currentItems == null) + { + var originalItems = _httpClient.GetFromJsonAsync($"f{_navigationManager.BaseUri}ake-data.json"); + _localStorageService.SetItemAsync("data", originalItems); + } + return (await _localStorageService.GetItemAsync("data")).Skip((page-1)*pageSize).Take(pageSize).ToList(); + } + + public async Task GetById(int id) + { + var currentItems =await _localStorageService.GetItemAsync>("data"); + var item = currentItems.FirstOrDefault(s => s.Id == id); + if (item == null) + { + throw new Exception($"Item with id {id} not found"); + } + return item; + } + + public async Task Update(int id, ItemModel item) + { + var currentItems = await _localStorageService.GetItemAsync>("data"); + var itemToUpdate = currentItems.FirstOrDefault(s => s.Id == id); + + if (itemToUpdate == null) + { + throw new Exception($"Item with id {id} not found"); + } + var imagePathsInfo = new DirectoryInfo($"{_webHostEnvironment.ContentRootPath}/images"); + if (!imagePathsInfo.Exists) + { + imagePathsInfo.Create(); + } + + if (itemToUpdate.Name != item.Name) + { + var oldFileName = new FileInfo($"{imagePathsInfo}/{itemToUpdate.Name}.png"); + if (oldFileName.Exists) + { + oldFileName.Delete(); + } + } + + var fileName = new FileInfo($"{imagePathsInfo}/{item.Name}.png"); + await File.WriteAllBytesAsync(fileName.FullName, item.ImageContent); + // itemToUpdate.Name = item.Name; + // itemToUpdate.DisplayName = item.DisplayName; + // itemToUpdate.RepairWith = item.RepairWith; + // itemToUpdate.EnchantCategories = item.EnchantCategories; + // itemToUpdate.MaxDurability = item.MaxDurability; + // itemToUpdate.StackSize = item.StackSize; + // itemToUpdate.UpdatedDate = DateTime.Now; + ItemFactory.Update(itemToUpdate, item); + await _localStorageService.SetItemAsync("data", currentItems); + } + + public async Task Delete(int id) + { + var currentItems =await _localStorageService.GetItemAsync>("data"); + var itemToDelete = currentItems.FirstOrDefault(s => s.Id == id); + currentItems.Remove(itemToDelete); + var imagePathsInfo = new DirectoryInfo($"{_webHostEnvironment.ContentRootPath}/images"); + var fileName = new FileInfo($"{imagePathsInfo}/{itemToDelete.Name}.png"); + if (fileName.Exists) + { + File.Delete(fileName.FullName); + } + await _localStorageService.SetItemAsync("data", currentItems); + } +} \ No newline at end of file diff --git a/TP Blazor/Services/IDataService.cs b/TP Blazor/Services/IDataService.cs new file mode 100644 index 0000000..c7266f1 --- /dev/null +++ b/TP Blazor/Services/IDataService.cs @@ -0,0 +1,13 @@ +using TP_Blazor.Models; + +namespace TP_Blazor.Services; + +public interface IDataService +{ + public Task Add(ItemModel item); + Task Count(); + Task> List(int page, int pageSize); + Task GetById(int id); + Task Update(int id,ItemModel item); + Task Delete(int id); +} \ No newline at end of file diff --git a/TP Blazor/TP Blazor.csproj b/TP Blazor/TP Blazor.csproj index 4859a02..4b0372b 100644 --- a/TP Blazor/TP Blazor.csproj +++ b/TP Blazor/TP Blazor.csproj @@ -16,10 +16,12 @@ + + diff --git a/TP Blazor/_Imports.razor b/TP Blazor/_Imports.razor index a029dcc..8bd9121 100644 --- a/TP Blazor/_Imports.razor +++ b/TP Blazor/_Imports.razor @@ -9,3 +9,5 @@ @using TP_Blazor @using TP_Blazor.Shared @using Blazorise.DataGrid +@using Blazored.Modal +@using Blazored.Modal.Services