diff --git a/TutoBlazer/Factories/ItemFactory.cs b/TutoBlazer/Factories/ItemFactory.cs new file mode 100644 index 0000000..6b37d6e --- /dev/null +++ b/TutoBlazer/Factories/ItemFactory.cs @@ -0,0 +1,48 @@ +using TutoBlazer.Models; + +namespace TutoBlazer.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/TutoBlazer/Models/ItemModel.cs b/TutoBlazer/Models/ItemModel.cs new file mode 100644 index 0000000..0802731 --- /dev/null +++ b/TutoBlazer/Models/ItemModel.cs @@ -0,0 +1,37 @@ +using System.ComponentModel.DataAnnotations; + +namespace TutoBlazer.Models +{ + public class ItemModel + { + public int Id { get; set; } + + [Required] + [StringLength(50, ErrorMessage = "The display name must not exceed 50 characters.")] + public string DisplayName { get; set; } + + [Required] + [StringLength(50, ErrorMessage = "The name must not exceed 50 characters.")] + [RegularExpression(@"^[a-z''-'\s]{1,40}$", ErrorMessage = "Only lowercase characters are accepted.")] + 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 = "You must agree to the terms.")] + public bool AcceptCondition { get; set; } + + [Required(ErrorMessage = "The image of the item is mandatory!")] + public byte[] ImageContent { get; set; } + } +} diff --git a/TutoBlazer/Pages/Add.razor b/TutoBlazer/Pages/Add.razor new file mode 100644 index 0000000..6ac8bb1 --- /dev/null +++ b/TutoBlazer/Pages/Add.razor @@ -0,0 +1,69 @@ +@page "/add" +@using Models +

Add

+ + + + + +

+ +

+

+ +

+

+ +

+

+ +

+

+ Enchant categories: +

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

+

+ Repair with: +

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

+

+ +

+

+ +

+ + +
diff --git a/TutoBlazer/Pages/Add.razor.cs b/TutoBlazer/Pages/Add.razor.cs new file mode 100644 index 0000000..7b00497 --- /dev/null +++ b/TutoBlazer/Pages/Add.razor.cs @@ -0,0 +1,89 @@ +using Blazored.LocalStorage; +using Microsoft.AspNetCore.Components.Forms; +using Microsoft.AspNetCore.Components; +using TutoBlazer.Models; + + +namespace TutoBlazer.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/TutoBlazer/Pages/Edit.razor b/TutoBlazer/Pages/Edit.razor new file mode 100644 index 0000000..74d3978 --- /dev/null +++ b/TutoBlazer/Pages/Edit.razor @@ -0,0 +1,82 @@ +@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/TutoBlazer/Pages/Edit.razor.cs b/TutoBlazer/Pages/Edit.razor.cs new file mode 100644 index 0000000..c3cd9b8 --- /dev/null +++ b/TutoBlazer/Pages/Edit.razor.cs @@ -0,0 +1,109 @@ +using Microsoft.AspNetCore.Components; +using Microsoft.AspNetCore.Components.Forms; +using TutoBlazer.Factories; +using TutoBlazer.Models; + +namespace TutoBlazer.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/TutoBlazer/Pages/List.razor b/TutoBlazer/Pages/List.razor index 59a1f14..98cba6e 100644 --- a/TutoBlazer/Pages/List.razor +++ b/TutoBlazer/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/TutoBlazer/Pages/List.razor.cs b/TutoBlazer/Pages/List.razor.cs index 8e67d42..bd4a147 100644 --- a/TutoBlazer/Pages/List.razor.cs +++ b/TutoBlazer/Pages/List.razor.cs @@ -1,4 +1,5 @@ -using Blazorise.DataGrid; +using Blazored.LocalStorage; +using Blazorise.DataGrid; using Microsoft.AspNetCore.Components; using TutoBlazer.Models; @@ -11,10 +12,10 @@ namespace TutoBlazer.Pages private int totalItem; [Inject] - public HttpClient Http { get; set; } + public IDataService DataService { get; set; } [Inject] - public NavigationManager NavigationManager { get; set; } + public IWebHostEnvironment WebHostEnvironment { get; set; } private async Task OnReadData(DataGridReadDataEventArgs e) { @@ -23,15 +24,16 @@ namespace TutoBlazer.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 void OnDelete(int id) + { + + } } } diff --git a/TutoBlazer/Program.cs b/TutoBlazer/Program.cs index dad9253..9b55886 100644 --- a/TutoBlazer/Program.cs +++ b/TutoBlazer/Program.cs @@ -1,9 +1,11 @@ +using Blazored.LocalStorage; using Blazorise; using Blazorise.Bootstrap; using Blazorise.Icons.FontAwesome; using Microsoft.AspNetCore.Components; using Microsoft.AspNetCore.Components.Web; using TutoBlazer.Data; +using TutoBlazer.Services; var builder = WebApplication.CreateBuilder(args); @@ -16,6 +18,8 @@ builder.Services .AddBlazorise() .AddBootstrapProviders() .AddFontAwesomeIcons(); +builder.Services.AddBlazoredLocalStorage(); +builder.Services.AddScoped(); var app = builder.Build(); diff --git a/TutoBlazer/Services/DataLocalService.cs b/TutoBlazer/Services/DataLocalService.cs new file mode 100644 index 0000000..32f2a7f --- /dev/null +++ b/TutoBlazer/Services/DataLocalService.cs @@ -0,0 +1,177 @@ +using Blazored.LocalStorage; +using Microsoft.AspNetCore.Components; +using TutoBlazer.Factories; +using TutoBlazer.Models; + +namespace TutoBlazer.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() + { + // 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")).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/TutoBlazer/Services/IDataService.cs b/TutoBlazer/Services/IDataService.cs new file mode 100644 index 0000000..bcd78b0 --- /dev/null +++ b/TutoBlazer/Services/IDataService.cs @@ -0,0 +1,16 @@ +using TutoBlazer.Models; + +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); +} \ No newline at end of file diff --git a/TutoBlazer/TutoBlazer.csproj b/TutoBlazer/TutoBlazer.csproj index 6033f3c..b5ab17c 100644 --- a/TutoBlazer/TutoBlazer.csproj +++ b/TutoBlazer/TutoBlazer.csproj @@ -7,6 +7,8 @@ + + diff --git a/TutoBlazer/wwwroot/images/default.png b/TutoBlazer/wwwroot/images/default.png new file mode 100644 index 0000000..935fc52 Binary files /dev/null and b/TutoBlazer/wwwroot/images/default.png differ diff --git a/TutoBlazer/wwwroot/images/lolol.png b/TutoBlazer/wwwroot/images/lolol.png new file mode 100644 index 0000000..935fc52 Binary files /dev/null and b/TutoBlazer/wwwroot/images/lolol.png differ diff --git a/TutoBlazer/wwwroot/images/lololo.png b/TutoBlazer/wwwroot/images/lololo.png new file mode 100644 index 0000000..935fc52 Binary files /dev/null and b/TutoBlazer/wwwroot/images/lololo.png differ