Skip to content

Commit

Permalink
Updating Blazor Admin (dotnet-architecture#442)
Browse files Browse the repository at this point in the history
* Updating Blazor services

* Adding Settings and Refactoring Services

* WIP - Fighting with DI

* Configuring dependencies in both Web Startup and BlazorAdmin Program.cs has them working again.

* Everything works; need to optimize calls to ListBrands

* LocalStorageBrandService decorator working

* Added cache duration of 1 minute

* Refactoring to reduce token storage
Fixed issue with dropdowns binding to int

* Remove token stuff from login; moved to CustomAuthStateProvider

* Migrated CatalogTypes to separate service
Implemented cache decorator

* Ardalis/blazor refactor (dotnet-architecture#440)

* 1. Migrate CatalogItemServices -> CatalogItemService.
3. Add caching to CatalogItemService.

* change to $"Loading {key} from local storage" ?

* docker settings added. (dotnet-architecture#441)

* docker settings added.

* InDocker Removed

* InDocker removed from web startup.

* removed unused using

* no reload list if close without save

* startup patch for localhost

* file name fixed

* removed docker from launchSettings.

* Configure logging via appsettings

Co-authored-by: Shady Nagy <info@shadynagy.com>
  • Loading branch information
ardalis and ShadyNagy authored Jul 31, 2020
1 parent 98fb0ee commit e9a9dc0
Show file tree
Hide file tree
Showing 77 changed files with 866 additions and 534 deletions.
6 changes: 2 additions & 4 deletions docker-compose.override.yml
Original file line number Diff line number Diff line change
Expand Up @@ -2,19 +2,17 @@ version: '3.4'
services:
eshopwebmvc:
environment:
- ASPNETCORE_ENVIRONMENT=Development
- ASPNETCORE_ENVIRONMENT=Docker
- ASPNETCORE_URLS=http://+:80
- DOTNET_RUNNING_IN_CONTAINER=true
ports:
- "5106:80"
volumes:
- ~/.aspnet/https:/root/.aspnet/https:ro
- ~/.microsoft/usersecrets:/root/.microsoft/usersecrets:ro
eshoppublicapi:
environment:
- ASPNETCORE_ENVIRONMENT=Development
- ASPNETCORE_ENVIRONMENT=Docker
- ASPNETCORE_URLS=http://+:80
- DOTNET_RUNNING_IN_CONTAINER=true
ports:
- "5200:80"
volumes:
Expand Down
1 change: 1 addition & 0 deletions src/BlazorAdmin/BlazorAdmin.csproj
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,7 @@
<PackageReference Include="Microsoft.AspNetCore.Components.WebAssembly.Build" Version="3.2.0" PrivateAssets="all" />
<PackageReference Include="Microsoft.AspNetCore.Components.WebAssembly.DevServer" Version="3.2.0" PrivateAssets="all" />
<PackageReference Include="Microsoft.Extensions.Identity.Core" Version="3.1.5" />
<PackageReference Include="Microsoft.Extensions.Logging.Configuration" Version="3.1.6" />
<PackageReference Include="System.Net.Http.Json" Version="3.2.0" />
</ItemGroup>

Expand Down
33 changes: 23 additions & 10 deletions src/BlazorAdmin/CustomAuthStateProvider.cs
Original file line number Diff line number Diff line change
@@ -1,31 +1,41 @@
using System;
using BlazorAdmin.Services;
using BlazorAdmin.Services;
using BlazorShared.Authorization;
using Microsoft.AspNetCore.Components.Authorization;
using Microsoft.Extensions.Logging;
using System;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Net.Http.Json;
using System.Security.Claims;
using System.Threading.Tasks;
using Microsoft.Extensions.Logging;
using BlazorShared.Authorization;

namespace BlazorAdmin
{
public class CustomAuthStateProvider : AuthenticationStateProvider
{
// TODO: Get Default Cache Duration from Config
private static readonly TimeSpan UserCacheRefreshInterval = TimeSpan.FromSeconds(60);

private readonly AuthService _authService;
private readonly HttpClient _httpClient;
private readonly ILogger<CustomAuthStateProvider> _logger;

private DateTimeOffset _userLastCheck = DateTimeOffset.FromUnixTimeSeconds(0);
private ClaimsPrincipal _cachedUser = new ClaimsPrincipal(new ClaimsIdentity());

public CustomAuthStateProvider(AuthService authService, ILogger<CustomAuthStateProvider> logger)
public CustomAuthStateProvider(AuthService authService,
HttpClient httpClient,
ILogger<CustomAuthStateProvider> logger)
{
_authService = authService;
_httpClient = httpClient;
_logger = logger;
}

public override async Task<AuthenticationState> GetAuthenticationStateAsync() =>
new AuthenticationState(await GetUser(useCache: true));
public override async Task<AuthenticationState> GetAuthenticationStateAsync()
{
return new AuthenticationState(await GetUser(useCache: true));
}

private async ValueTask<ClaimsPrincipal> GetUser(bool useCache = false)
{
Expand All @@ -47,16 +57,17 @@ private async Task<ClaimsPrincipal> FetchUser()

try
{
user = await _authService.GetTokenFromController();
_logger.LogInformation("Fetching user details from web api.");
user = await _httpClient.GetFromJsonAsync<UserInfo>("User");
}
catch (Exception exc)
{
_logger.LogWarning(exc, "Fetching user failed.");
}

if (user == null || !user.IsAuthenticated)
{
return new ClaimsPrincipal(new ClaimsIdentity());
return null;
}

var identity = new ClaimsIdentity(
Expand All @@ -72,6 +83,8 @@ private async Task<ClaimsPrincipal> FetchUser()
}
}

_httpClient.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", user.Token);

return new ClaimsPrincipal(identity);
}
}
Expand Down
8 changes: 4 additions & 4 deletions src/BlazorAdmin/Pages/CatalogItemPage/Create.razor
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
@inject ILogger<Create> Logger
@inject AuthService Auth
@inject IJSRuntime JSRuntime
@inject ICatalogItemService CatalogItemService

@inherits BlazorAdmin.Helpers.BlazorComponent

Expand Down Expand Up @@ -130,7 +131,7 @@
public IEnumerable<CatalogType> Types { get; set; }

[Parameter]
public EventCallback<string> OnCloseClick { get; set; }
public EventCallback<string> OnSaveClick { get; set; }

private string LoadPicture => string.IsNullOrEmpty(_item.PictureBase64) ? string.Empty : $"data:image/png;base64, {_item.PictureBase64}";
private bool HasPicture => !string.IsNullOrEmpty(_item.PictureBase64);
Expand All @@ -142,8 +143,8 @@

private async Task CreateClick()
{
await new BlazorAdmin.Services.CatalogItemServices.Create(Auth).HandleAsync(_item);
await OnCloseClick.InvokeAsync(null);
await CatalogItemService.Create(_item);
await OnSaveClick.InvokeAsync(null);
await Close();
}

Expand Down Expand Up @@ -172,7 +173,6 @@
_modalDisplay = "none";
_modalClass = "";
_showCreateModal = false;
await OnCloseClick.InvokeAsync(null);
}

private async Task AddFile(IFileListEntry[] files)
Expand Down
14 changes: 7 additions & 7 deletions src/BlazorAdmin/Pages/CatalogItemPage/Delete.razor
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
@inject ILogger<Delete> Logger
@inject AuthService Auth
@inject IJSRuntime JSRuntime
@inject ICatalogItemService CatalogItemService

@inherits BlazorAdmin.Helpers.BlazorComponent

Expand Down Expand Up @@ -50,15 +51,15 @@
</dt>

<dd>
@Services.CatalogBrandServices.List.GetBrandName(Brands, _item.CatalogBrandId)
@_item.CatalogBrand
</dd>

<dt>
Type
</dt>

<dd>
@Services.CatalogTypeServices.List.GetTypeName(Types, _item.CatalogTypeId)
@_item.CatalogType
</dd>
<dt>
Price
Expand Down Expand Up @@ -97,7 +98,7 @@
public IEnumerable<CatalogType> Types { get; set; }

[Parameter]
public EventCallback<string> OnCloseClick { get; set; }
public EventCallback<string> OnSaveClick { get; set; }

private bool HasPicture => !string.IsNullOrEmpty(_item.PictureUri);
private string _modalDisplay = "none;";
Expand All @@ -109,9 +110,9 @@
{
// TODO: Add some kind of "are you sure" check before this
await new BlazorAdmin.Services.CatalogItemServices.Delete(Auth).HandleAsync(id);
await CatalogItemService.Delete(id);

await OnCloseClick.InvokeAsync(null);
await OnSaveClick.InvokeAsync(null);
await Close();
}

Expand All @@ -121,7 +122,7 @@

await new Css(JSRuntime).HideBodyOverflow();

_item = await new GetById(Auth).HandleAsync(id);
_item = await CatalogItemService.GetById(id);

_modalDisplay = "block;";
_modalClass = "Show";
Expand All @@ -136,6 +137,5 @@
_modalDisplay = "none";
_modalClass = "";
_showDeleteModal = false;
await OnCloseClick.InvokeAsync(null);
}
}
13 changes: 7 additions & 6 deletions src/BlazorAdmin/Pages/CatalogItemPage/Details.razor
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
@inject ILogger<Details> Logger
@inject AuthService Auth
@inject IJSRuntime JSRuntime
@inject ICatalogItemService CatalogItemService

@inherits BlazorAdmin.Helpers.BlazorComponent

Expand Down Expand Up @@ -53,15 +54,15 @@
</dt>

<dd>
@Services.CatalogBrandServices.List.GetBrandName(Brands, _item.CatalogBrandId)
@_item.CatalogBrand
</dd>

<dt>
Type
</dt>

<dd>
@Services.CatalogTypeServices.List.GetTypeName(Types, _item.CatalogTypeId)
@_item.CatalogType
</dd>
<dt>
Price
Expand Down Expand Up @@ -108,10 +109,10 @@
private bool _showDetailsModal = false;
private CatalogItem _item = new CatalogItem();

public void EditClick()
public async Task EditClick()
{
OnEditClick.InvokeAsync(_item.Id);
Close();
await OnEditClick.InvokeAsync(_item.Id);
await Close();
}

public async Task Open(int id)
Expand All @@ -121,7 +122,7 @@

await new Css(JSRuntime).HideBodyOverflow();

_item = await new GetById(Auth).HandleAsync(id);
_item = await CatalogItemService.GetById(id);

_modalDisplay = "block;";
_modalClass = "Show";
Expand Down
19 changes: 10 additions & 9 deletions src/BlazorAdmin/Pages/CatalogItemPage/Edit.razor
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
@inject ILogger<Edit> Logger
@inject AuthService Auth
@inject IJSRuntime JSRuntime
@inject ICatalogItemService CatalogItemService

@inherits BlazorAdmin.Helpers.BlazorComponent

Expand Down Expand Up @@ -54,25 +55,25 @@
<div class="form-group">
<label class="control-label col-md-6">Brand</label>
<div class="col-md-12">
<InputSelect @bind-Value="_item.CatalogBrandId" class="form-control">
<CustomInputSelect @bind-Value="_item.CatalogBrandId" class="form-control">
@foreach (var brand in Brands)
{
<option value="@brand.Id">@brand.Name</option>
<option value="@brand.Id.ToString()">@brand.Name</option>
}
</InputSelect>
</CustomInputSelect>
<ValidationMessage For="(() => _item.CatalogBrandId)" />
</div>
</div>

<div class="form-group">
<label class="control-label col-md-6">Type</label>
<div class="col-md-12">
<InputSelect @bind-Value="_item.CatalogTypeId" class="form-control">
<CustomInputSelect @bind-Value="_item.CatalogTypeId" class="form-control">
@foreach (var type in Types)
{
<option value="@type.Id">@type.Name</option>
}
</InputSelect>
</CustomInputSelect>
<ValidationMessage For="(() => _item.CatalogTypeId)" />
</div>
</div>
Expand Down Expand Up @@ -130,7 +131,7 @@
public IEnumerable<CatalogType> Types { get; set; }

[Parameter]
public EventCallback<string> OnCloseClick { get; set; }
public EventCallback<string> OnSaveClick { get; set; }

private string LoadPicture => string.IsNullOrEmpty(_item.PictureBase64) ? string.IsNullOrEmpty(_item.PictureUri) ? string.Empty : $"{_item.PictureUri}" : $"data:image/png;base64, {_item.PictureBase64}";
private bool HasPicture => !(string.IsNullOrEmpty(_item.PictureBase64) && string.IsNullOrEmpty(_item.PictureUri));
Expand All @@ -142,7 +143,8 @@

private async Task SaveClick()
{
await new BlazorAdmin.Services.CatalogItemServices.Edit(Auth).HandleAsync(_item);
await CatalogItemService.Edit(_item);
await OnSaveClick.InvokeAsync(null);
await Close();
}

Expand All @@ -152,7 +154,7 @@

await new Css(JSRuntime).HideBodyOverflow();

_item = await new GetById(Auth).HandleAsync(id);
_item = await CatalogItemService.GetById(id);

_modalDisplay = "block;";
_modalClass = "Show";
Expand All @@ -168,7 +170,6 @@
_modalDisplay = "none";
_modalClass = "";
_showEditModal = false;
await OnCloseClick.InvokeAsync(null);
}

private async Task ChangeFile(IFileListEntry[] files)
Expand Down
13 changes: 5 additions & 8 deletions src/BlazorAdmin/Pages/CatalogItemPage/List.razor
Original file line number Diff line number Diff line change
@@ -1,9 +1,6 @@
@page "/admin"
@attribute [Authorize(Roles = BlazorShared.Authorization.Constants.Roles.ADMINISTRATORS)]
@inject AuthService Auth
@inject BlazorAdmin.Services.CatalogItemServices.ListPaged CatalogItemListPaged
@inject BlazorAdmin.Services.CatalogTypeServices.List TypeList
@inject BlazorAdmin.Services.CatalogBrandServices.List BrandList
@inherits BlazorAdmin.Helpers.BlazorComponent
@namespace BlazorAdmin.Pages.CatalogItemPage

Expand Down Expand Up @@ -42,8 +39,8 @@ else
<td>
<img class="img-thumbnail" src="@($"{item.PictureUri}")">
</td>
<td>@Services.CatalogTypeServices.List.GetTypeName(catalogTypes, item.CatalogTypeId)</td>
<td>@Services.CatalogBrandServices.List.GetBrandName(catalogBrands, item.CatalogBrandId)</td>
<td>@item.CatalogType</td>
<td>@item.CatalogBrand</td>
<td>@item.Id</td>
<td>@item.Name</td>
<td>@item.Description</td>
Expand All @@ -63,7 +60,7 @@ else
</table>

<Details Brands="@catalogBrands" Types="@catalogTypes" OnEditClick="EditClick" @ref="DetailsComponent"></Details>
<Edit Brands="@catalogBrands" Types="@catalogTypes" OnCloseClick="ReloadCatalogItems" @ref="EditComponent"></Edit>
<Create Brands="@catalogBrands" Types="@catalogTypes" OnCloseClick="ReloadCatalogItems" @ref="CreateComponent"></Create>
<Delete Brands="@catalogBrands" Types="@catalogTypes" OnCloseClick="ReloadCatalogItems" @ref="DeleteComponent"></Delete>
<Edit Brands="@catalogBrands" Types="@catalogTypes" OnSaveClick="ReloadCatalogItems" @ref="EditComponent"></Edit>
<Create Brands="@catalogBrands" Types="@catalogTypes" OnSaveClick="ReloadCatalogItems" @ref="CreateComponent"></Create>
<Delete Brands="@catalogBrands" Types="@catalogTypes" OnSaveClick="ReloadCatalogItems" @ref="DeleteComponent"></Delete>
}
Loading

0 comments on commit e9a9dc0

Please sign in to comment.