Adding DataApi Log and Debug logs

arthur_logs
Arthur VALIN 2 years ago
parent 9c7c0d044e
commit d078305d4f

@ -1,4 +1,5 @@
@using CraftSharp.Models; @using CraftSharp.Models;
<CascadingBlazoredModal> <CascadingBlazoredModal>
<Router AppAssembly="@typeof(App).Assembly"> <Router AppAssembly="@typeof(App).Assembly">
<Found Context="routeData"> <Found Context="routeData">
@ -14,4 +15,3 @@
</NotFound> </NotFound>
</Router> </Router>
</CascadingBlazoredModal> </CascadingBlazoredModal>

@ -1,4 +1,5 @@
using CraftSharp.Models; using CraftSharp.Models;
using CraftSharp.Pages;
using CraftSharp.Services; using CraftSharp.Services;
using Microsoft.AspNetCore.Components; using Microsoft.AspNetCore.Components;
using Microsoft.AspNetCore.Localization; using Microsoft.AspNetCore.Localization;
@ -12,6 +13,7 @@ namespace CraftSharp.Controllers
[Microsoft.AspNetCore.Mvc.Route("[controller]/[action]")] [Microsoft.AspNetCore.Mvc.Route("[controller]/[action]")]
public class UserController : Controller public class UserController : Controller
{ {
[HttpPost] [HttpPost]
public IActionResult SetUser([FromBody] String user) public IActionResult SetUser([FromBody] String user)
{ {

@ -8,6 +8,7 @@ namespace CraftSharp.Pages
{ {
public partial class Add public partial class Add
{ {
/// <summary> /// <summary>
/// The default enchant categories. /// The default enchant categories.
/// </summary> /// </summary>
@ -36,7 +37,6 @@ namespace CraftSharp.Pages
private async void HandleValidSubmit() private async void HandleValidSubmit()
{ {
await DataService.Add(itemModel); await DataService.Add(itemModel);
NavigationManager.NavigateTo("list"); NavigationManager.NavigateTo("list");
} }

@ -24,8 +24,6 @@ namespace CraftSharp.Pages
[Inject] [Inject]
public HttpClient httpClient { get; set; } public HttpClient httpClient { get; set; }
[Inject]
public ILogger<Connexion> Logger { get; set; }
private string error { get; set; } private string error { get; set; }
private ConnexionModel loginRequest { get; set; } = new ConnexionModel(); private ConnexionModel loginRequest { get; set; } = new ConnexionModel();
@ -44,7 +42,6 @@ namespace CraftSharp.Pages
try try
{ {
await AuthStateProvider.Login(loginRequest); await AuthStateProvider.Login(loginRequest);
Logger.Log(LogLevel.Information, $"Login : {loginRequest.UserName}");
var stringified = JsonConvert.SerializeObject(loginRequest); var stringified = JsonConvert.SerializeObject(loginRequest);
var response = await httpClient.PostAsJsonAsync($"{NavigationManager.BaseUri}User/SetUser", stringified); var response = await httpClient.PostAsJsonAsync($"{NavigationManager.BaseUri}User/SetUser", stringified);
NavigationManager.NavigateTo("index"); NavigationManager.NavigateTo("index");
@ -52,7 +49,6 @@ namespace CraftSharp.Pages
} }
catch (Exception ex) catch (Exception ex)
{ {
Logger.Log(LogLevel.Error, $"Login Failure : {ex}");
error = ex.Message; error = ex.Message;
} }
} }

@ -1,18 +0,0 @@
@page "/counter"
<PageTitle>Counter</PageTitle>
<h1>Counter</h1>
<p role="status">Current count: @currentCount</p>
<button class="btn btn-primary" @onclick="IncrementCount">Click me</button>
@code {
private int currentCount = 0;
private void IncrementCount()
{
currentCount++;
}
}

@ -39,6 +39,7 @@ namespace CraftSharp.Pages
[Inject] [Inject]
public IWebHostEnvironment WebHostEnvironment { get; set; } public IWebHostEnvironment WebHostEnvironment { get; set; }
protected override async Task OnInitializedAsync() protected override async Task OnInitializedAsync()
{ {
var item = await DataService.GetById(Id); var item = await DataService.GetById(Id);
@ -52,7 +53,6 @@ namespace CraftSharp.Pages
private async void HandleValidSubmit() private async void HandleValidSubmit()
{ {
await DataService.Update(Id, itemModel); await DataService.Update(Id, itemModel);
NavigationManager.NavigateTo("list"); NavigationManager.NavigateTo("list");
} }

@ -1,48 +0,0 @@
@page "/fetchdata"
<PageTitle>Weather forecast</PageTitle>
@using CraftSharp.Data
@inject WeatherForecastService ForecastService
<h1>Weather forecast</h1>
<p>This component demonstrates fetching data from a service.</p>
@if (forecasts == null)
{
<p><em>Loading...</em></p>
}
else
{
<table class="table">
<thead>
<tr>
<th>Date</th>
<th>Temp. (C)</th>
<th>Temp. (F)</th>
<th>Summary</th>
</tr>
</thead>
<tbody>
@foreach (var forecast in forecasts)
{
<tr>
<td>@forecast.Date.ToShortDateString()</td>
<td>@forecast.TemperatureC</td>
<td>@forecast.TemperatureF</td>
<td>@forecast.Summary</td>
</tr>
}
</tbody>
</table>
}
@code {
private WeatherForecast[]? forecasts;
protected override async Task OnInitializedAsync()
{
forecasts = await ForecastService.GetForecastAsync(DateTime.Now);
}
}

@ -21,9 +21,6 @@ namespace CraftSharp.Pages
[Inject] [Inject]
public HttpClient httpClient { get; set; } public HttpClient httpClient { get; set; }
[Inject]
public ILogger<Inscription> Logger { get; set; }
private string error { get; set; } private string error { get; set; }
private InscriptionModel registerRequest { get; set; } = new InscriptionModel(); private InscriptionModel registerRequest { get; set; } = new InscriptionModel();
@ -31,7 +28,6 @@ namespace CraftSharp.Pages
{ {
if (AuthStateProvider.GetCurrentUser() != null && AuthStateProvider.GetCurrentUser().IsAuthenticated) if (AuthStateProvider.GetCurrentUser() != null && AuthStateProvider.GetCurrentUser().IsAuthenticated)
{ {
Logger.Log(LogLevel.Information, $"Automatic login : {AuthStateProvider.GetCurrentUser().UserName}");
NavigationManager.NavigateTo("index"); NavigationManager.NavigateTo("index");
} }
} }
@ -40,7 +36,6 @@ namespace CraftSharp.Pages
{ {
await AuthStateProvider.Register(registerRequest); await AuthStateProvider.Register(registerRequest);
Logger.Log(LogLevel.Information, $"Register : {registerRequest.UserName}");
var stringified = JsonConvert.SerializeObject(new ConnexionModel() { var stringified = JsonConvert.SerializeObject(new ConnexionModel() {
Password=registerRequest.Password, Password=registerRequest.Password,
UserName=registerRequest.UserName} UserName=registerRequest.UserName}

@ -5,6 +5,7 @@ using Blazorise.DataGrid;
using CraftSharp.Modals; using CraftSharp.Modals;
using CraftSharp.Models; using CraftSharp.Models;
using CraftSharp.Services; using CraftSharp.Services;
using CraftSharp.Shared;
using Microsoft.AspNetCore.Components; using Microsoft.AspNetCore.Components;
using Microsoft.Extensions.Localization; using Microsoft.Extensions.Localization;
@ -34,10 +35,14 @@ namespace CraftSharp.Pages
[Inject] [Inject]
public IWebHostEnvironment WebHostEnvironment { get; set; } public IWebHostEnvironment WebHostEnvironment { get; set; }
[Inject]
public ILogger<List> Logger { get; set; }
private async Task OnReadData(DataGridReadDataEventArgs<Item> e) private async Task OnReadData(DataGridReadDataEventArgs<Item> e)
{ {
if (e.CancellationToken.IsCancellationRequested) if (e.CancellationToken.IsCancellationRequested)
{ {
Logger.Log(LogLevel.Critical, $"Failed to get api data ! - {e}");
return; return;
} }
@ -59,7 +64,6 @@ namespace CraftSharp.Pages
{ {
return; return;
} }
await DataService.Delete(id); await DataService.Delete(id);
// Reload the page // Reload the page

@ -29,14 +29,16 @@ namespace CraftSharp.Pages
[Inject] [Inject]
public IStringLocalizer<Opening> Localizer { get; set; } public IStringLocalizer<Opening> Localizer { get; set; }
[Inject]
public ILogger<Opening> Logger { get; set; }
int totalItem; int totalItem;
List<Item> items; List<Item> items;
protected override async Task OnInitializedAsync() protected override async Task OnInitializedAsync()
{ {
totalItem = await DataService.Count(); totalItem = await DataService.Count();
items = await DataService.List(0, totalItem);
items = await DataService.List(0, totalItem);
} }
bool canOpen() bool canOpen()
@ -59,7 +61,6 @@ namespace CraftSharp.Pages
AuthStateProvider.GetCurrentUser().addItem(randomItem); AuthStateProvider.GetCurrentUser().addItem(randomItem);
} }
} }
Console.WriteLine(randomItem.Name);
openingAnimation(); openingAnimation();
} }
else else

@ -15,6 +15,9 @@ namespace CraftSharp.Pages
[Inject] [Inject]
public IStringLocalizer<Shop> Localizer { get; set; } public IStringLocalizer<Shop> Localizer { get; set; }
[Inject]
public ILogger<Shop> Logger { get; set; }
List<ShopOfferModel> offers = new List<ShopOfferModel>() List<ShopOfferModel> offers = new List<ShopOfferModel>()
{ {
new ShopOfferModel() new ShopOfferModel()
@ -54,6 +57,7 @@ namespace CraftSharp.Pages
{ {
if (offer.InputAmount <= AuthService.GetCurrentUser().numberOfEmeralds) if (offer.InputAmount <= AuthService.GetCurrentUser().numberOfEmeralds)
{ {
Logger.Log(LogLevel.Information, $"User {AuthService.GetCurrentUser().UserName} bought {offer.OutputAmount} keys for {offer.InputAmount} emeralds.");
AuthService.GetCurrentUser().numberOfEmeralds -= offer.InputAmount; AuthService.GetCurrentUser().numberOfEmeralds -= offer.InputAmount;
AuthService.GetCurrentUser().NumberOfKeys += offer.OutputAmount; AuthService.GetCurrentUser().NumberOfKeys += offer.OutputAmount;
} }

@ -21,6 +21,7 @@ using Microsoft.JSInterop;
using CraftSharp.Controllers; using CraftSharp.Controllers;
var builder = WebApplication.CreateBuilder(args); var builder = WebApplication.CreateBuilder(args);
builder.Logging.AddConfiguration(builder.Configuration.GetSection("Logging"));
// Add services to the container. // Add services to the container.
builder.Services.AddRazorPages(); builder.Services.AddRazorPages();
@ -41,7 +42,6 @@ builder.Services.AddScoped<UserController>();
builder.Services.AddHttpClient(); builder.Services.AddHttpClient();
builder.Services.AddBlazoredModal(); builder.Services.AddBlazoredModal();
builder.Logging.AddConfiguration(builder.Configuration.GetSection("Logging"));
builder.Services builder.Services
.AddBlazorise() .AddBlazorise()

@ -8,8 +8,10 @@ namespace CraftSharp.Services
{ {
private static readonly List<AppUser> CurrentUser; private static readonly List<AppUser> CurrentUser;
static AuthService() static AuthService()
{ {
CurrentUser = new List<AppUser> CurrentUser = new List<AppUser>
{ {
new AppUser { UserName = "Admin", Password = "123456", Roles = new List<UserRoles> { UserRoles.Admin }, numberOfKeys=999 } new AppUser { UserName = "Admin", Password = "123456", Roles = new List<UserRoles> { UserRoles.Admin }, numberOfKeys=999 }
@ -49,6 +51,18 @@ namespace CraftSharp.Services
} }
} }
public void Logout(CurrentUser user)
{
var idx = CurrentUser.FindIndex(u => u.UserName == user.UserName);
if(idx != -1)
{
CurrentUser[idx].numberOfEmeralds = user.numberOfEmeralds;
CurrentUser[idx].numberOfKeys = user.NumberOfKeys;
CurrentUser[idx].inventory = user.Inventory;
}
}
public void Register(InscriptionModel registerRequest) public void Register(InscriptionModel registerRequest)
{ {
CurrentUser.Add(new AppUser { UserName = registerRequest.UserName, Password = registerRequest.Password, Roles = new List<UserRoles> { UserRoles.User } }); CurrentUser.Add(new AppUser { UserName = registerRequest.UserName, Password = registerRequest.Password, Roles = new List<UserRoles> { UserRoles.User } });

@ -13,12 +13,14 @@ namespace CraftSharp.Services
public class CustomStateProvider : AuthenticationStateProvider public class CustomStateProvider : AuthenticationStateProvider
{ {
private readonly IAuthService _authService; private readonly IAuthService _authService;
private readonly ILogger<CustomStateProvider> _logger;
private CurrentUser _currentUser { get; set; } private CurrentUser _currentUser { get; set; }
public CustomStateProvider(IAuthService authService) public CustomStateProvider(IAuthService authService, ILogger<CustomStateProvider> logger)
{ {
this._authService = authService; this._authService = authService;
this._logger = logger;
} }
public override async Task<AuthenticationState> GetAuthenticationStateAsync() public override async Task<AuthenticationState> GetAuthenticationStateAsync()
@ -35,7 +37,7 @@ namespace CraftSharp.Services
} }
catch (HttpRequestException ex) catch (HttpRequestException ex)
{ {
Console.WriteLine("Request failed:" + ex); _logger.Log(LogLevel.Error, $"Auth Request failed : {ex}");
} }
return new AuthenticationState(new ClaimsPrincipal(identity)); return new AuthenticationState(new ClaimsPrincipal(identity));
@ -48,12 +50,14 @@ namespace CraftSharp.Services
CurrentUser user; CurrentUser user;
user = _authService.GetUser(loginParameters.UserName); user = _authService.GetUser(loginParameters.UserName);
_currentUser = user; _currentUser = user;
_logger.Log(LogLevel.Information, $"Login : {_currentUser.UserName}");
NotifyAuthenticationStateChanged(GetAuthenticationStateAsync()); NotifyAuthenticationStateChanged(GetAuthenticationStateAsync());
} }
public async Task Logout() public async Task Logout()
{ {
_logger.Log(LogLevel.Information, $"Logout : {_currentUser.UserName}");
_authService.Logout(_currentUser);
_currentUser = new CurrentUser(); _currentUser = new CurrentUser();
NotifyAuthenticationStateChanged(GetAuthenticationStateAsync()); NotifyAuthenticationStateChanged(GetAuthenticationStateAsync());
} }
@ -65,12 +69,12 @@ namespace CraftSharp.Services
// No error - Login the user // No error - Login the user
var user = _authService.GetUser(registerParameters.UserName); var user = _authService.GetUser(registerParameters.UserName);
_currentUser = user; _currentUser = user;
_logger.Log(LogLevel.Information, $"Register : {_currentUser.UserName}");
NotifyAuthenticationStateChanged(GetAuthenticationStateAsync()); NotifyAuthenticationStateChanged(GetAuthenticationStateAsync());
} }
public CurrentUser GetCurrentUser() public CurrentUser GetCurrentUser()
{ {
if (_currentUser != null && _currentUser.IsAuthenticated) if (_currentUser != null && _currentUser.IsAuthenticated)
{ {
return _currentUser; return _currentUser;

@ -1,17 +1,20 @@
using CraftSharp.Components; using CraftSharp.Components;
using CraftSharp.Factories; using CraftSharp.Factories;
using CraftSharp.Models; using CraftSharp.Models;
using Microsoft.Extensions.Logging;
namespace CraftSharp.Services namespace CraftSharp.Services
{ {
public class DataApiService : IDataService public class DataApiService : IDataService
{ {
private readonly HttpClient _http; private readonly HttpClient _http;
private readonly ILogger<DataApiService> _logger;
public DataApiService( public DataApiService(
HttpClient http) HttpClient http, ILogger<DataApiService> logger)
{ {
_http = http; _http = http;
_logger = logger;
} }
public async Task Add(ItemModel model) public async Task Add(ItemModel model)
@ -21,6 +24,7 @@ namespace CraftSharp.Services
// Save the data // Save the data
await _http.PostAsJsonAsync("https://localhost:7234/api/Crafting/", item); await _http.PostAsJsonAsync("https://localhost:7234/api/Crafting/", item);
_logger.Log(LogLevel.Information, $"ADDITION OF ITEM : {model.Id} - {model.Name}");
} }
public async Task<int> Count() public async Task<int> Count()
@ -42,13 +46,14 @@ namespace CraftSharp.Services
{ {
// Get the item // Get the item
var item = ItemFactory.Create(model); var item = ItemFactory.Create(model);
await _http.PutAsJsonAsync($"https://localhost:7234/api/Crafting/{id}", item); await _http.PutAsJsonAsync($"https://localhost:7234/api/Crafting/{id}", item);
_logger.Log(LogLevel.Information, $"UPDATING ITEM : {model.Id} - {model.Name}");
} }
public async Task Delete(int id) public async Task Delete(int id)
{ {
await _http.DeleteAsync($"https://localhost:7234/api/Crafting/{id}"); await _http.DeleteAsync($"https://localhost:7234/api/Crafting/{id}");
_logger.Log(LogLevel.Information, $"DELETION ON ITEM : {id}");
} }
public async Task<List<CraftingRecipe>> GetRecipes() public async Task<List<CraftingRecipe>> GetRecipes()

@ -6,6 +6,7 @@ namespace CraftSharp.Services
{ {
CurrentUser GetUser(string userName); CurrentUser GetUser(string userName);
void Login(ConnexionModel loginRequest); void Login(ConnexionModel loginRequest);
void Logout(CurrentUser user);
void Register(InscriptionModel registerRequest); void Register(InscriptionModel registerRequest);
} }
} }

@ -6,6 +6,9 @@ namespace CraftSharp.Shared
{ {
public partial class CultureSelector public partial class CultureSelector
{ {
[Inject]
ILogger<CultureSelector> Logger { get; set; }
private CultureInfo[] supportedCultures = new[] private CultureInfo[] supportedCultures = new[]
{ {
new CultureInfo("en-US"), new CultureInfo("en-US"),
@ -28,6 +31,7 @@ namespace CraftSharp.Shared
var uri = new Uri(this.NavigationManager.Uri).GetComponents(UriComponents.PathAndQuery, UriFormat.Unescaped); var uri = new Uri(this.NavigationManager.Uri).GetComponents(UriComponents.PathAndQuery, UriFormat.Unescaped);
var query = $"?culture={Uri.EscapeDataString(culture)}&" + $"redirectUri={Uri.EscapeDataString(uri)}"; var query = $"?culture={Uri.EscapeDataString(culture)}&" + $"redirectUri={Uri.EscapeDataString(uri)}";
Logger.Log(LogLevel.Debug, $"Culture change - {culture}");
// Redirect the user to the culture controller to set the cookie // Redirect the user to the culture controller to set the cookie
this.NavigationManager.NavigateTo("/Culture/SetCulture" + query, forceLoad: true); this.NavigationManager.NavigateTo("/Culture/SetCulture" + query, forceLoad: true);

@ -23,8 +23,6 @@ namespace CraftSharp.Shared
[Inject] [Inject]
public HttpClient httpClient { get; set; } public HttpClient httpClient { get; set; }
[Inject]
public ILogger<HeaderLayout> Logger { get; set; }
[CascadingParameter] [CascadingParameter]
private Task<AuthenticationState> AuthenticationState { get; set; } private Task<AuthenticationState> AuthenticationState { get; set; }
@ -48,7 +46,6 @@ namespace CraftSharp.Shared
private async Task LogoutClick() private async Task LogoutClick()
{ {
await AuthStateProvider.Logout(); await AuthStateProvider.Logout();
Logger.Log(LogLevel.Information, $"Logout : {AuthStateProvider.GetCurrentUser().UserName}");
await httpClient.DeleteAsync($"{NavigationManager.BaseUri}User/DeleteUser"); await httpClient.DeleteAsync($"{NavigationManager.BaseUri}User/DeleteUser");
NavigationManager.NavigateTo("/inscription"); NavigationManager.NavigateTo("/inscription");

Loading…
Cancel
Save