Creating a data service, editing pages and registering the data service

tpBlazor
runtenick 2 years ago
parent cf8d880bbe
commit ed12e92b46

@ -6,6 +6,11 @@
<ImplicitUsings>enable</ImplicitUsings> <ImplicitUsings>enable</ImplicitUsings>
</PropertyGroup> </PropertyGroup>
<ItemGroup>
<Content Include="Services\DataLocalService.cs" />
<Content Include="Services\IDataService.cs" />
</ItemGroup>
<ItemGroup> <ItemGroup>
<PackageReference Include="Blazored.LocalStorage" Version="4.2.0" /> <PackageReference Include="Blazored.LocalStorage" Version="4.2.0" />
<PackageReference Include="Blazorise.Bootstrap" Version="1.1.2" /> <PackageReference Include="Blazorise.Bootstrap" Version="1.1.2" />
@ -13,4 +18,8 @@
<PackageReference Include="Blazorise.Icons.FontAwesome" Version="1.1.2" /> <PackageReference Include="Blazorise.Icons.FontAwesome" Version="1.1.2" />
</ItemGroup> </ItemGroup>
<ItemGroup>
<Folder Include="Services\" />
</ItemGroup>
</Project> </Project>

@ -7,25 +7,11 @@ namespace BlazorTp1.Pages
{ {
public partial class Add public partial class Add
{ {
[Inject]
public ILocalStorageService LocalStorage { get; set; }
[Inject]
public NavigationManager NavigationManager { get; set; }
[Inject]
public IWebHostEnvironment WebHostEnvironment { get; set; }
/// <summary> /// <summary>
/// The default enchant categories. /// The default enchant categories.
/// </summary> /// </summary>
private List<string> enchantCategories = new List<string>() { "armor", "armor_head", "armor_chest", "weapon", "digger", "breakable", "vanishable" }; private List<string> enchantCategories = new List<string>() { "armor", "armor_head", "armor_chest", "weapon", "digger", "breakable", "vanishable" };
/// <summary>
/// The default repair with.
/// </summary>
private List<string> repairWith = new List<string>() { "oak_planks", "spruce_planks", "birch_planks", "jungle_planks", "acacia_planks", "dark_oak_planks", "crimson_planks", "warped_planks" };
/// <summary> /// <summary>
/// The current item model /// The current item model
/// </summary> /// </summary>
@ -35,44 +21,20 @@ namespace BlazorTp1.Pages
RepairWith = new List<string>() RepairWith = new List<string>()
}; };
private async void HandleValidSubmit() /// <summary>
{ /// The default repair with.
// Get the current data /// </summary>
var currentData = await LocalStorage.GetItemAsync<List<Item>>("data"); private List<string> repairWith = new List<string>() { "oak_planks", "spruce_planks", "birch_planks", "jungle_planks", "acacia_planks", "dark_oak_planks", "crimson_planks", "warped_planks" };
// Simulate the Id
itemModel.Id = currentData.Max(s => s.Id) + 1;
// Add the item to the current data [Inject]
currentData.Add(new Item public IDataService DataService { get; set; }
{
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 [Inject]
var imagePathInfo = new DirectoryInfo($"{WebHostEnvironment.WebRootPath}/images"); public NavigationManager NavigationManager { get; set; }
// Check if the folder "images" exist private async void HandleValidSubmit()
if (!imagePathInfo.Exists)
{ {
imagePathInfo.Create(); await DataService.Add(itemModel);
}
// Determine the image name
var fileName = new FileInfo($"{imagePathInfo}/{itemModel.Name}.png");
// Write the file content
await File.WriteAllBytesAsync(fileName.FullName, itemModel.ImageContent);
// Save the data
await LocalStorage.SetItemAsync("data", currentData);
NavigationManager.NavigateTo("list"); NavigationManager.NavigateTo("list");
} }

@ -12,14 +12,11 @@ namespace BlazorTp1.Pages
private int totalItem; private int totalItem;
[Inject] [Inject]
public HttpClient Http { get; set; } public IDataService DataService { get; set; }
[Inject] [Inject]
public IWebHostEnvironment WebHostEnvironment { get; set; } public IWebHostEnvironment WebHostEnvironment { get; set; }
[Inject]
public NavigationManager NavigationManager { get; set; }
private async Task OnReadData(DataGridReadDataEventArgs<Item> e) private async Task OnReadData(DataGridReadDataEventArgs<Item> e)
{ {
if (e.CancellationToken.IsCancellationRequested) if (e.CancellationToken.IsCancellationRequested)
@ -27,14 +24,10 @@ namespace BlazorTp1.Pages
return; return;
} }
// When you use a real API, we use this follow code
//var response = await Http.GetJsonAsync<Item[]>( $"http://my-api/api/data?page={e.Page}&pageSize={e.PageSize}" );
var response = (await Http.GetFromJsonAsync<Item[]>($"{NavigationManager.BaseUri}fake-data.json")).Skip((e.Page - 1) * e.PageSize).Take(e.PageSize).ToList();
if (!e.CancellationToken.IsCancellationRequested) if (!e.CancellationToken.IsCancellationRequested)
{ {
totalItem = (await Http.GetFromJsonAsync<List<Item>>($"{NavigationManager.BaseUri}fake-data.json")).Count; items = await DataService.List(e.Page, e.PageSize);
items = new List<Item>(response); // an actual data for the current page totalItem = await DataService.Count();
} }
} }
} }

@ -22,6 +22,8 @@ builder.Services
builder.Services.AddBlazoredLocalStorage(); builder.Services.AddBlazoredLocalStorage();
builder.Services.AddScoped<IDataService, DataLocalServices>();
var app = builder.Build(); var app = builder.Build();
// Configure the HTTP request pipeline. // Configure the HTTP request pipeline.

@ -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<List<Item>>("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<int> Count()
{
return (await _localStorage.GetItemAsync<Item[]>("data")).Length;
}
public async Task<List<Item>> List(int currentPage, int pageSize)
{
// Load data from the local storage
var currentData = await _localStorage.GetItemAsync<Item[]>("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<Item[]>($"{_navigationManager.BaseUri}fake-data.json");
await _localStorage.SetItemAsync("data", originalData);
}
return (await _localStorage.GetItemAsync<Item[]>("data")).Skip((currentPage - 1) * pageSize).Take(pageSize).ToList();
}
}

@ -0,0 +1,10 @@
using System;
public interface IDataService
{
Task Add(ItemModel model);
Task<int> Count();
Task<List<Item>> List(int currentPage, int pageSize);
}
Loading…
Cancel
Save