diff --git a/BlazorProject/BlazorProject.sln b/BlazorProject/BlazorProject.sln index 0719473..933fc96 100644 --- a/BlazorProject/BlazorProject.sln +++ b/BlazorProject/BlazorProject.sln @@ -3,7 +3,7 @@ Microsoft Visual Studio Solution File, Format Version 12.00 # Visual Studio Version 17 VisualStudioVersion = 17.3.32929.385 MinimumVisualStudioVersion = 10.0.40219.1 -Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "BlazorProject", "BlazorProject\BlazorProject.csproj", "{826FD9F1-4474-41B8-AEFB-8CDF2A5CD4FB}" +Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "BlazorProject", "BlazorProject\BlazorProject.csproj", "{826FD9F1-4474-41B8-AEFB-8CDF2A5CD4FB}" EndProject Global GlobalSection(SolutionConfigurationPlatforms) = preSolution diff --git a/BlazorProject/BlazorProject/App.razor b/BlazorProject/BlazorProject/App.razor index 6fd3ed1..2d39f98 100644 --- a/BlazorProject/BlazorProject/App.razor +++ b/BlazorProject/BlazorProject/App.razor @@ -1,12 +1,10 @@ - - - - - - - Not found - -

Sorry, there's nothing at this address.

-
-
-
+ + + + + + +

Sorry, there's nothing at this address.

+
+
+
\ No newline at end of file diff --git a/BlazorProject/BlazorProject/BlazorProject.csproj b/BlazorProject/BlazorProject/BlazorProject.csproj index c0eacf6..64d367c 100644 --- a/BlazorProject/BlazorProject/BlazorProject.csproj +++ b/BlazorProject/BlazorProject/BlazorProject.csproj @@ -8,6 +8,7 @@ + diff --git a/BlazorProject/BlazorProject/Factories/ItemFactory.cs b/BlazorProject/BlazorProject/Factories/ItemFactory.cs new file mode 100644 index 0000000..6124a9f --- /dev/null +++ b/BlazorProject/BlazorProject/Factories/ItemFactory.cs @@ -0,0 +1,48 @@ +using BlazorProject.Models; + +namespace BlazorProject.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; + } + } +} diff --git a/BlazorProject/BlazorProject/Modals/DeleteConfirmation.razor b/BlazorProject/BlazorProject/Modals/DeleteConfirmation.razor new file mode 100644 index 0000000..4ea8989 --- /dev/null +++ b/BlazorProject/BlazorProject/Modals/DeleteConfirmation.razor @@ -0,0 +1,9 @@ +
+

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

+ + + + +
\ No newline at end of file diff --git a/BlazorProject/BlazorProject/Modals/DeleteConfirmation.razor.cs b/BlazorProject/BlazorProject/Modals/DeleteConfirmation.razor.cs new file mode 100644 index 0000000..c43383e --- /dev/null +++ b/BlazorProject/BlazorProject/Modals/DeleteConfirmation.razor.cs @@ -0,0 +1,38 @@ +using Blazored.Modal.Services; +using Blazored.Modal; +using BlazorProject.Models; +using BlazorProject.Services; +using Microsoft.AspNetCore.Components; + +namespace BlazorProject.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(); + } + } +} diff --git a/BlazorProject/BlazorProject/Models/ItemModel.cs b/BlazorProject/BlazorProject/Models/ItemModel.cs new file mode 100644 index 0000000..74b3334 --- /dev/null +++ b/BlazorProject/BlazorProject/Models/ItemModel.cs @@ -0,0 +1,37 @@ +using System.ComponentModel.DataAnnotations; + +namespace BlazorProject.Models +{ + public class ItemModel + { + public int Id { get; set; } + + [Required] + [StringLength(50, ErrorMessage = "Le nom affiché ne doit pas dépasser 50 caractères.")] + public string DisplayName { get; set; } + + [Required] + [StringLength(50, ErrorMessage = "Le nom ne doit pas dépasser 50 caractères.")] + [RegularExpression(@"^[a-z''-'\s]{1,40}$", ErrorMessage = "Seulement les caractères en minuscule sont acceptées.")] + public string Name { get; set; } + + [Required] + [Range(1, 64)] + public int StackSize { get; set; } + + [Required] + [Range(1, 125)] + public int MaxDurability { get; set; } + + public List EnchantCategories { get; set; } + + public List RepairWith { get; set; } + + [Required] + [Range(typeof(bool), "true", "true", ErrorMessage = "Vous devez accepter les conditions.")] + public bool AcceptCondition { get; set; } + + [Required(ErrorMessage = "L'image de l'item est obligatoire !")] + public byte[] ImageContent { get; set; } + } +} diff --git a/BlazorProject/BlazorProject/Pages/Add.razor b/BlazorProject/BlazorProject/Pages/Add.razor new file mode 100644 index 0000000..64b1710 --- /dev/null +++ b/BlazorProject/BlazorProject/Pages/Add.razor @@ -0,0 +1,69 @@ +@page "/add" + +

Add

+ + + + + +

+ +

+

+ +

+

+ +

+

+ +

+

+ Enchant categories: +

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

+

+ Repair with: +

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

+

+ +

+

+ +

+ + +
\ No newline at end of file diff --git a/BlazorProject/BlazorProject/Pages/Add.razor.cs b/BlazorProject/BlazorProject/Pages/Add.razor.cs new file mode 100644 index 0000000..6990fbf --- /dev/null +++ b/BlazorProject/BlazorProject/Pages/Add.razor.cs @@ -0,0 +1,89 @@ +using Blazored.LocalStorage; +using BlazorProject.Models; +using Microsoft.AspNetCore.Components.Forms; +using Microsoft.AspNetCore.Components; +using BlazorProject.Services; + +namespace BlazorProject.Pages +{ + public partial class Add + { + /// + /// The default enchant categories. + /// + 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; } + + private async void HandleValidSubmit() + { + await DataService.Add(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); + } + } + } +} diff --git a/BlazorProject/BlazorProject/Pages/BlazorRoute.razor b/BlazorProject/BlazorProject/Pages/BlazorRoute.razor new file mode 100644 index 0000000..6946924 --- /dev/null +++ b/BlazorProject/BlazorProject/Pages/BlazorRoute.razor @@ -0,0 +1,4 @@ +@page "/BlazorRoute" +@page "/DifferentBlazorRoute" + +

Blazor routing

diff --git a/BlazorProject/BlazorProject/Pages/Edit.razor b/BlazorProject/BlazorProject/Pages/Edit.razor new file mode 100644 index 0000000..ee72c33 --- /dev/null +++ b/BlazorProject/BlazorProject/Pages/Edit.razor @@ -0,0 +1,83 @@ +@page "/edit/{Id:int}" +@using BlazorProject.Models + +

Edit

+ + + + + +

+ +

+

+ +

+

+ +

+

+ +

+

+ Enchant categories: +

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

+

+ Repair with: +

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

+

+ +

+

+ +

+

+ +

+ + +
\ No newline at end of file diff --git a/BlazorProject/BlazorProject/Pages/Edit.razor.cs b/BlazorProject/BlazorProject/Pages/Edit.razor.cs new file mode 100644 index 0000000..41852f4 --- /dev/null +++ b/BlazorProject/BlazorProject/Pages/Edit.razor.cs @@ -0,0 +1,110 @@ +using BlazorProject.Factories; +using BlazorProject.Models; +using BlazorProject.Services; +using Microsoft.AspNetCore.Components; +using Microsoft.AspNetCore.Components.Forms; + +namespace BlazorProject.Pages +{ + public partial class Edit + { + [Parameter] + public int Id { get; set; } + + /// + /// The default enchant categories. + /// + 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); + } + } + } +} diff --git a/BlazorProject/BlazorProject/Pages/List.razor b/BlazorProject/BlazorProject/Pages/List.razor index 3077a5c..29765dc 100644 --- a/BlazorProject/BlazorProject/Pages/List.razor +++ b/BlazorProject/BlazorProject/Pages/List.razor @@ -3,6 +3,12 @@

List

+
+ + Ajouter + +
+ + + + @if (File.Exists($"{WebHostEnvironment.WebRootPath}/images/{context.Name}.png")) + { + @context.DisplayName + } + else + { + @context.DisplayName + } + + @@ -25,4 +43,10 @@ + + + Editer + + + \ No newline at end of file diff --git a/BlazorProject/BlazorProject/Pages/List.razor.cs b/BlazorProject/BlazorProject/Pages/List.razor.cs index 916f19d..2d79d7c 100644 --- a/BlazorProject/BlazorProject/Pages/List.razor.cs +++ b/BlazorProject/BlazorProject/Pages/List.razor.cs @@ -1,5 +1,10 @@ -using Blazorise.DataGrid; +using Blazored.LocalStorage; +using Blazored.Modal; +using Blazored.Modal.Services; +using Blazorise.DataGrid; +using BlazorProject.Modals; using BlazorProject.Models; +using BlazorProject.Services; using Microsoft.AspNetCore.Components; namespace BlazorProject.Pages @@ -11,11 +16,17 @@ namespace BlazorProject.Pages private int totalItem; [Inject] - public HttpClient Http { get; set; } + public IDataService DataService { get; set; } + + [Inject] + public IWebHostEnvironment WebHostEnvironment { get; set; } [Inject] public NavigationManager NavigationManager { get; set; } + [CascadingParameter] + public IModalService Modal { get; set; } + private async Task OnReadData(DataGridReadDataEventArgs e) { if (e.CancellationToken.IsCancellationRequested) @@ -23,15 +34,30 @@ namespace BlazorProject.Pages return; } - // When you use a real API, we use this follow code - //var response = await Http.GetJsonAsync( $"http://my-api/api/data?page={e.Page}&pageSize={e.PageSize}" ); - var response = (await Http.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 + items = await DataService.List(e.Page, e.PageSize); + totalItem = await DataService.Count(); + } + } + + 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/BlazorProject/BlazorProject/Pages/_Layout.cshtml b/BlazorProject/BlazorProject/Pages/_Layout.cshtml index 49685b6..dfa8bc2 100644 --- a/BlazorProject/BlazorProject/Pages/_Layout.cshtml +++ b/BlazorProject/BlazorProject/Pages/_Layout.cshtml @@ -11,6 +11,7 @@ + @@ -28,6 +29,7 @@ + diff --git a/BlazorProject/BlazorProject/Program.cs b/BlazorProject/BlazorProject/Program.cs index bee85f2..56ca99d 100644 --- a/BlazorProject/BlazorProject/Program.cs +++ b/BlazorProject/BlazorProject/Program.cs @@ -1,8 +1,10 @@ using Blazored.LocalStorage; +using Blazored.Modal; using Blazorise; using Blazorise.Bootstrap; using Blazorise.Icons.FontAwesome; using BlazorProject.Data; +using BlazorProject.Services; using Microsoft.AspNetCore.Components; using Microsoft.AspNetCore.Components.Web; @@ -21,6 +23,10 @@ builder.Services builder.Services.AddBlazoredLocalStorage(); +builder.Services.AddScoped(); + +builder.Services.AddBlazoredModal(); + var app = builder.Build(); // Configure the HTTP request pipeline. diff --git a/BlazorProject/BlazorProject/Services/DataLocalService.cs b/BlazorProject/BlazorProject/Services/DataLocalService.cs new file mode 100644 index 0000000..2bbed49 --- /dev/null +++ b/BlazorProject/BlazorProject/Services/DataLocalService.cs @@ -0,0 +1,166 @@ +using Blazored.LocalStorage; +using BlazorProject.Factories; +using BlazorProject.Models; +using Microsoft.AspNetCore.Components; + +namespace BlazorProject.Services +{ + public class DataLocalService : IDataService + { + private readonly HttpClient _http; + private readonly ILocalStorageService _localStorage; + private readonly NavigationManager _navigationManager; + private readonly IWebHostEnvironment _webHostEnvironment; + + public DataLocalService( + ILocalStorageService localStorage, + HttpClient http, + IWebHostEnvironment webHostEnvironment, + NavigationManager navigationManager) + { + _localStorage = localStorage; + _http = http; + _webHostEnvironment = webHostEnvironment; + _navigationManager = navigationManager; + } + + public async Task Add(ItemModel model) + { + // Get the current data + var currentData = await _localStorage.GetItemAsync>("data"); + + // Simulate the Id + model.Id = currentData.Max(s => s.Id) + 1; + + // Add the item to the current data + currentData.Add(ItemFactory.Create(model)); + + // Save the image + var imagePathInfo = new DirectoryInfo($"{_webHostEnvironment.WebRootPath}/images"); + + // Check if the folder "images" exist + if (!imagePathInfo.Exists) + { + imagePathInfo.Create(); + } + + // Determine the image name + var fileName = new FileInfo($"{imagePathInfo}/{model.Name}.png"); + + // Write the file content + await File.WriteAllBytesAsync(fileName.FullName, model.ImageContent); + + // Save the data + await _localStorage.SetItemAsync("data", currentData); + } + + public async Task Count() + { + return (await _localStorage.GetItemAsync("data")).Length; + } + + public async Task> List(int currentPage, int pageSize) + { + // Load data from the local storage + var currentData = await _localStorage.GetItemAsync("data"); + + // Check if data exist in the local storage + if (currentData == null) + { + // this code add in the local storage the fake data + var originalData = await _http.GetFromJsonAsync($"{_navigationManager.BaseUri}fake-data.json"); + await _localStorage.SetItemAsync("data", originalData); + } + + return (await _localStorage.GetItemAsync("data")).Skip((currentPage - 1) * pageSize).Take(pageSize).ToList(); + } + + public async Task GetById(int id) + { + // Get the current data + var currentData = await _localStorage.GetItemAsync>("data"); + + // Get the item int the list + var item = currentData.FirstOrDefault(w => w.Id == id); + + // Check if item exist + if (item == null) + { + throw new Exception($"Unable to found the item with ID: {id}"); + } + + return item; + } + + public async Task Update(int id, ItemModel model) + { + // Get the current data + var currentData = await _localStorage.GetItemAsync>("data"); + + // Get the item int the list + var item = currentData.FirstOrDefault(w => w.Id == id); + + // Check if item exist + if (item == null) + { + throw new Exception($"Unable to found the item with ID: {id}"); + } + + // Save the image + var imagePathInfo = new DirectoryInfo($"{_webHostEnvironment.WebRootPath}/images"); + + // Check if the folder "images" exist + if (!imagePathInfo.Exists) + { + imagePathInfo.Create(); + } + + // Delete the previous image + if (item.Name != model.Name) + { + var oldFileName = new FileInfo($"{imagePathInfo}/{item.Name}.png"); + + if (oldFileName.Exists) + { + File.Delete(oldFileName.FullName); + } + } + + // Determine the image name + var fileName = new FileInfo($"{imagePathInfo}/{model.Name}.png"); + + // Write the file content + await File.WriteAllBytesAsync(fileName.FullName, model.ImageContent); + + // Modify the content of the item + ItemFactory.Update(item, model); + + // Save the data + await _localStorage.SetItemAsync("data", currentData); + } + + public async Task Delete(int id) + { + // Get the current data + var currentData = await _localStorage.GetItemAsync>("data"); + + // Get the item int the list + var item = currentData.FirstOrDefault(w => w.Id == id); + + // Delete item in + currentData.Remove(item); + + // Delete the image + var imagePathInfo = new DirectoryInfo($"{_webHostEnvironment.WebRootPath}/images"); + var fileName = new FileInfo($"{imagePathInfo}/{item.Name}.png"); + + if (fileName.Exists) + { + File.Delete(fileName.FullName); + } + + // Save the data + await _localStorage.SetItemAsync("data", currentData); + } + } +} diff --git a/BlazorProject/BlazorProject/Services/IDataService.cs b/BlazorProject/BlazorProject/Services/IDataService.cs new file mode 100644 index 0000000..1762af5 --- /dev/null +++ b/BlazorProject/BlazorProject/Services/IDataService.cs @@ -0,0 +1,19 @@ +using BlazorProject.Models; + +namespace BlazorProject.Services +{ + public interface IDataService + { + Task Add(ItemModel model); + + Task Count(); + + Task> List(int currentPage, int pageSize); + + Task GetById(int id); + + Task Update(int id, ItemModel model); + + Task Delete(int id); + } +} diff --git a/BlazorProject/BlazorProject/_Imports.razor b/BlazorProject/BlazorProject/_Imports.razor index d2a7987..191f293 100644 --- a/BlazorProject/BlazorProject/_Imports.razor +++ b/BlazorProject/BlazorProject/_Imports.razor @@ -9,3 +9,5 @@ @using BlazorProject @using BlazorProject.Shared @using Blazorise.DataGrid +@using Blazored.Modal +@using Blazored.Modal.Services diff --git a/BlazorProject/BlazorProject/wwwroot/images/default.png b/BlazorProject/BlazorProject/wwwroot/images/default.png new file mode 100644 index 0000000..a7446c9 Binary files /dev/null and b/BlazorProject/BlazorProject/wwwroot/images/default.png differ