From ed12e92b46f99e5846d1bb59c2fadb251046e751 Mon Sep 17 00:00:00 2001 From: runtenick Date: Sat, 12 Nov 2022 10:12:43 +0100 Subject: [PATCH] Creating a data service, editing pages and registering the data service --- BlazorTp1/BlazorTp1.csproj | 9 +++ BlazorTp1/Pages/Add.razor.cs | 60 ++++--------------- BlazorTp1/Pages/List.razor.cs | 13 +---- BlazorTp1/Program.cs | 2 + BlazorTp1/Services/DataLocalService.cs | 80 ++++++++++++++++++++++++++ BlazorTp1/Services/IDataService.cs | 10 ++++ 6 files changed, 115 insertions(+), 59 deletions(-) create mode 100644 BlazorTp1/Services/DataLocalService.cs create mode 100644 BlazorTp1/Services/IDataService.cs diff --git a/BlazorTp1/BlazorTp1.csproj b/BlazorTp1/BlazorTp1.csproj index c0eacf6..3105fce 100644 --- a/BlazorTp1/BlazorTp1.csproj +++ b/BlazorTp1/BlazorTp1.csproj @@ -6,6 +6,11 @@ enable + + + + + @@ -13,4 +18,8 @@ + + + + diff --git a/BlazorTp1/Pages/Add.razor.cs b/BlazorTp1/Pages/Add.razor.cs index 794e331..fc1fdf9 100644 --- a/BlazorTp1/Pages/Add.razor.cs +++ b/BlazorTp1/Pages/Add.razor.cs @@ -7,25 +7,11 @@ namespace BlazorTp1.Pages { public partial class Add { - [Inject] - public ILocalStorageService LocalStorage { get; set; } - - [Inject] - public NavigationManager NavigationManager { get; set; } - - [Inject] - public IWebHostEnvironment WebHostEnvironment { get; set; } - /// /// The default enchant categories. /// private List enchantCategories = new List() { "armor", "armor_head", "armor_chest", "weapon", "digger", "breakable", "vanishable" }; - /// - /// 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" }; - /// /// The current item model /// @@ -35,44 +21,20 @@ namespace BlazorTp1.Pages RepairWith = new List() }; - private async void HandleValidSubmit() - { - // Get the current data - var currentData = await LocalStorage.GetItemAsync>("data"); - - // Simulate the Id - itemModel.Id = currentData.Max(s => s.Id) + 1; - - // Add the item to the current data - currentData.Add(new Item - { - Id = itemModel.Id, - DisplayName = itemModel.DisplayName, - Name = itemModel.Name, - RepairWith = itemModel.RepairWith, - EnchantCategories = itemModel.EnchantCategories, - MaxDurability = itemModel.MaxDurability, - StackSize = itemModel.StackSize, - CreatedDate = DateTime.Now - }); - - // Save the image - var imagePathInfo = new DirectoryInfo($"{WebHostEnvironment.WebRootPath}/images"); - - // Check if the folder "images" exist - if (!imagePathInfo.Exists) - { - imagePathInfo.Create(); - } + /// + /// 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" }; - // Determine the image name - var fileName = new FileInfo($"{imagePathInfo}/{itemModel.Name}.png"); + [Inject] + public IDataService DataService { get; set; } - // Write the file content - await File.WriteAllBytesAsync(fileName.FullName, itemModel.ImageContent); + [Inject] + public NavigationManager NavigationManager { get; set; } - // Save the data - await LocalStorage.SetItemAsync("data", currentData); + private async void HandleValidSubmit() + { + await DataService.Add(itemModel); NavigationManager.NavigateTo("list"); } diff --git a/BlazorTp1/Pages/List.razor.cs b/BlazorTp1/Pages/List.razor.cs index 4fd69ef..fbab704 100644 --- a/BlazorTp1/Pages/List.razor.cs +++ b/BlazorTp1/Pages/List.razor.cs @@ -12,14 +12,11 @@ namespace BlazorTp1.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; } - private async Task OnReadData(DataGridReadDataEventArgs e) { if (e.CancellationToken.IsCancellationRequested) @@ -27,14 +24,10 @@ namespace BlazorTp1.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(); } } } diff --git a/BlazorTp1/Program.cs b/BlazorTp1/Program.cs index 8d82ec6..99989cb 100644 --- a/BlazorTp1/Program.cs +++ b/BlazorTp1/Program.cs @@ -22,6 +22,8 @@ builder.Services builder.Services.AddBlazoredLocalStorage(); +builder.Services.AddScoped(); + var app = builder.Build(); // Configure the HTTP request pipeline. diff --git a/BlazorTp1/Services/DataLocalService.cs b/BlazorTp1/Services/DataLocalService.cs new file mode 100644 index 0000000..0fc6b16 --- /dev/null +++ b/BlazorTp1/Services/DataLocalService.cs @@ -0,0 +1,80 @@ +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(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 + }); + + // 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(); + } +} \ No newline at end of file diff --git a/BlazorTp1/Services/IDataService.cs b/BlazorTp1/Services/IDataService.cs new file mode 100644 index 0000000..a49c3c5 --- /dev/null +++ b/BlazorTp1/Services/IDataService.cs @@ -0,0 +1,10 @@ +using System; + +public interface IDataService +{ + Task Add(ItemModel model); + + Task Count(); + + Task> List(int currentPage, int pageSize); +}