Skip to content

Commit

Permalink
fix(templates): resolve small issues in Boilerplate #9019 (#9020)
Browse files Browse the repository at this point in the history
  • Loading branch information
ysmoradi authored Oct 27, 2024
1 parent d6e74e2 commit 2501883
Show file tree
Hide file tree
Showing 54 changed files with 321 additions and 267 deletions.
7 changes: 2 additions & 5 deletions .github/workflows/admin-sample.cd.yml
Original file line number Diff line number Diff line change
Expand Up @@ -41,9 +41,10 @@ jobs:
- name: Update core appsettings.json
uses: devops-actions/[email protected]
with:
files: 'AdminPanel/src/Client/AdminPanel.Client.Core/appsettings.json, AdminPanel/src/Shared/appsettings.json'
files: 'AdminPanel/src/Client/AdminPanel.Client.Core/appsettings.json, AdminPanel/src/Client/AdminPanel.Client.Core/appsettings.Production.json, AdminPanel/src/Shared/appsettings.json'
env:
ServerAddress: ${{ env.API_SERVER_ADDRESS }}
WebAppRender.BlazorMode: BlazorWebAssembly
ApplicationInsights.ConnectionString: ${{ secrets.APPLICATION_INSIGHTS_CONNECTION_STRING }}
AdsPushVapid.PublicKey: ${{ secrets.ADMINPANEL_PUBLIC_VAPIDKEY }}

Expand All @@ -53,10 +54,6 @@ jobs:

- name: Install wasm
run: cd src && dotnet workload install wasm-tools

- name: Configure app render mode
run: |
sed -i 's/BlazorAuto;/BlazorWebAssembly;/g' AdminPanel/src/Client/AdminPanel.Client.Core/Services/AppRenderMode.cs

- name: Generate CSS/JS files
run: dotnet build AdminPanel/src/Client/AdminPanel.Client.Core/AdminPanel.Client.Core.csproj -t:BeforeBuildTasks -p:Version="${{ vars.APPLICATION_DISPLAY_VERSION}}" --no-restore -c Release
Expand Down
9 changes: 3 additions & 6 deletions .github/workflows/todo-sample.cd.yml
Original file line number Diff line number Diff line change
Expand Up @@ -43,20 +43,17 @@ jobs:
- name: Update core appsettings.json
uses: devops-actions/[email protected]
with:
files: 'TodoSample/src/Client/TodoSample.Client.Core/appsettings.json, TodoSample/src/Shared/appsettings.json'
files: 'TodoSample/src/Client/TodoSample.Client.Core/appsettings.json, TodoSample/src/Client/TodoSample.Client.Core/appsettings.Production.json, TodoSample/src/Shared/appsettings.json'
env:
ServerAddress: ${{ env.SERVER_ADDRESS }}
WebAppRender.BlazorMode: BlazorWebAssembly
WebAppRender.PreRenderEnabled: true
ApplicationInsights.ConnectionString: ${{ secrets.APPLICATION_INSIGHTS_CONNECTION_STRING }}
AdsPushVapid.PublicKey: ${{ secrets.TODO_PUBLIC_VAPIDKEY }}

- name: Install wasm
run: cd src && dotnet workload install wasm-tools

- name: Configure app render mode
run: |
sed -i 's/public static readonly bool PrerenderEnabled = false;/public static readonly bool PrerenderEnabled = true;/g' TodoSample/src/Client/TodoSample.Client.Core/Services/AppRenderMode.cs
sed -i 's/BlazorAuto;/BlazorWebAssembly;/g' TodoSample/src/Client/TodoSample.Client.Core/Services/AppRenderMode.cs
- name: Generate CSS/JS files
run: dotnet build TodoSample/src/Client/TodoSample.Client.Core/TodoSample.Client.Core.csproj -t:BeforeBuildTasks -p:Version="${{ vars.APPLICATION_DISPLAY_VERSION}}" --no-restore -c Release

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -31,13 +31,6 @@ jobs:
versionSpec: '22.x'
displayName: 'Install Node.js'

# - task: Bash@3
# displayName: 'Enable pre rendering'
# inputs:
# targetType: 'inline'
# script: |
# 'sed -i 's/public static readonly bool PrerenderEnabled = false;/public static readonly bool PrerenderEnabled = true;/g' src/Client/Boilerplate.Client.Core/Services/AppRenderMode.cs'

- task: Bash@3
displayName: 'Install wasm'
inputs:
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -35,9 +35,6 @@ jobs:
with:
node-version: 22

# - name: Enable pre rendering
# run: sed -i 's/public static readonly bool PrerenderEnabled = false;/public static readonly bool PrerenderEnabled = true;/g' src/Client/Boilerplate.Client.Core/Services/AppRenderMode.cs

- name: Update core appsettings.json
uses: devops-actions/[email protected]
with:
Expand Down
Original file line number Diff line number Diff line change
@@ -1,4 +1,6 @@
//+:cnd:noEmit
using Microsoft.AspNetCore.Components.Web;

namespace Boilerplate.Client.Core;

public partial class ClientAppSettings : SharedAppSettings
Expand All @@ -7,24 +9,35 @@ public partial class ClientAppSettings : SharedAppSettings
/// If you're running Boilerplate.Server.Web project, then you can also use relative urls such as / for Blazor Server and WebAssembly
/// </summary>
[Required]
public string? ServerAddress { get; set; }
public string ServerAddress { get; set; } = default!;

//#if (captcha == "reCaptcha")
[Required]
public string? GoogleRecaptchaSiteKey { get; set; }
public string GoogleRecaptchaSiteKey { get; set; } = default!;
//#endif

public WindowsUpdateOptions WindowsUpdate { get; set; } = default!;
public WindowsUpdateOptions? WindowsUpdate { get; set; }

[Required]
public WebAppRenderOptions WebAppRender { get; set; } = default!;

//#if (notification == true)
public AdsPushVapidOptions AdsPushVapid { get; set; } = default!;
public AdsPushVapidOptions? AdsPushVapid { get; set; }
//#endif

public override IEnumerable<ValidationResult> Validate(ValidationContext validationContext)
{
var validationResults = base.Validate(validationContext).ToList();

Validator.TryValidateObject(WindowsUpdate, new ValidationContext(WindowsUpdate), validationResults, true);
if (WebAppRender is null)
throw new InvalidOperationException("WebAppRender is required. Please set WebAppRender in Client.Core's appsettings.json");

Validator.TryValidateObject(WebAppRender, new ValidationContext(WebAppRender), validationResults, true);

if (WindowsUpdate is not null)
{
Validator.TryValidateObject(WindowsUpdate, new ValidationContext(WindowsUpdate), validationResults, true);
}

//#if (notification == true)
if (AdsPushVapid is not null)
Expand All @@ -49,6 +62,54 @@ public override IEnumerable<ValidationResult> Validate(ValidationContext validat
}
}

public partial class WebAppRenderOptions
{
public bool PrerenderEnabled { get; set; }

public BlazorWebAppMode BlazorMode { get; set; }

public IComponentRenderMode? RenderMode
{
get
{
return BlazorMode switch
{
BlazorWebAppMode.BlazorAuto => new InteractiveAutoRenderMode(PrerenderEnabled),
BlazorWebAppMode.BlazorWebAssembly => new InteractiveWebAssemblyRenderMode(PrerenderEnabled),
BlazorWebAppMode.BlazorServer => new InteractiveServerRenderMode(PrerenderEnabled),
BlazorWebAppMode.BlazorSsr => null,
_ => throw new NotImplementedException(),
};
}
}

//-:cnd:noEmit
/// <summary>
/// To enable/disable pwa support, navigate to Directory.Build.props and modify the PwaEnabled flag.
/// </summary>
public bool PwaEnabled =>
#if PwaEnabled
true;
#else
false;
#endif
//+:cnd:noEmit
}

/// <summary>
/// https://learn.microsoft.com/en-us/aspnet/core/blazor/components/render-modes#render-modes
/// </summary>
public enum BlazorWebAppMode
{
BlazorAuto,
BlazorServer,
BlazorWebAssembly,
/// <summary>
/// Pre-rendering without interactivity
/// </summary>
BlazorSsr,
}

public partial class WindowsUpdateOptions
{
public bool AutoReload { get; set; }
Expand All @@ -66,5 +127,5 @@ public class AdsPushVapidOptions
/// Web push's vapid. More info at https://vapidkeys.com/
/// </summary>
[Required]
public string? PublicKey { get; set; }
public string PublicKey { get; set; } = default!;
}
Original file line number Diff line number Diff line change
@@ -1,4 +1,6 @@
namespace Boilerplate.Client.Core.Components;
using System.Runtime.CompilerServices;

namespace Boilerplate.Client.Core.Components;

public partial class AppComponentBase : ComponentBase, IAsyncDisposable
{
Expand Down Expand Up @@ -120,7 +122,10 @@ protected virtual Task OnAfterFirstRenderAsync()
/// <summary>
/// Executes passed action while catching all possible exceptions to prevent app crash.
/// </summary>
public virtual Action WrapHandled(Action action)
public virtual Action WrapHandled(Action action,
[CallerLineNumber] int lineNumber = 0,
[CallerMemberName] string memberName = "",
[CallerFilePath] string filePath = "")
{
return () =>
{
Expand All @@ -130,15 +135,18 @@ public virtual Action WrapHandled(Action action)
}
catch (Exception exp)
{
HandleException(exp);
HandleException(exp, null, lineNumber, memberName, filePath);
}
};
}

/// <summary>
/// Executes passed action while catching all possible exceptions to prevent app crash.
/// </summary>
public virtual Action<T> WrapHandled<T>(Action<T> func)
public virtual Action<T> WrapHandled<T>(Action<T> func,
[CallerLineNumber] int lineNumber = 0,
[CallerMemberName] string memberName = "",
[CallerFilePath] string filePath = "")
{
return (e) =>
{
Expand All @@ -148,15 +156,18 @@ public virtual Action<T> WrapHandled<T>(Action<T> func)
}
catch (Exception exp)
{
HandleException(exp);
HandleException(exp, null, lineNumber, memberName, filePath);
}
};
}

/// <summary>
/// Executes passed function while catching all possible exceptions to prevent app crash.
/// </summary>
public virtual Func<Task> WrapHandled(Func<Task> func)
public virtual Func<Task> WrapHandled(Func<Task> func,
[CallerLineNumber] int lineNumber = 0,
[CallerMemberName] string memberName = "",
[CallerFilePath] string filePath = "")
{
return async () =>
{
Expand All @@ -166,15 +177,18 @@ public virtual Func<Task> WrapHandled(Func<Task> func)
}
catch (Exception exp)
{
HandleException(exp);
HandleException(exp, null, lineNumber, memberName, filePath);
}
};
}

/// <summary>
/// Executes passed function while catching all possible exceptions to prevent app crash.
/// </summary>
public virtual Func<T, Task> WrapHandled<T>(Func<T, Task> func)
public virtual Func<T, Task> WrapHandled<T>(Func<T, Task> func,
[CallerLineNumber] int lineNumber = 0,
[CallerMemberName] string memberName = "",
[CallerFilePath] string filePath = "")
{
return async (e) =>
{
Expand All @@ -184,7 +198,7 @@ public virtual Func<T, Task> WrapHandled<T>(Func<T, Task> func)
}
catch (Exception exp)
{
HandleException(exp);
HandleException(exp, null, lineNumber, memberName, filePath);
}
};
}
Expand All @@ -206,13 +220,16 @@ protected virtual async ValueTask DisposeAsync(bool disposing)
}
}

protected void HandleException(Exception exp, Dictionary<string, object?>? parameters = null)
private void HandleException(Exception exp,
Dictionary<string, object?>? parameters = null,
[CallerLineNumber] int lineNumber = 0,
[CallerMemberName] string memberName = "",
[CallerFilePath] string filePath = "")
{
parameters ??= [];

parameters["ComponentType"] = GetType().FullName;
parameters["Url"] = NavigationManager.Uri;

ExceptionHandler.Handle(exp, parameters);
ExceptionHandler.Handle(exp, parameters, lineNumber, memberName, filePath);
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -52,7 +52,7 @@ private void OnFieldChanged(object? sender, FieldChangedEventArgs eventArgs)
var results = new List<ValidationResult>();

var parent = propertyInfo.DeclaringType!;
var dtoResourceTypeAttr = parent.GetCustomAttribute<DtoResourceTypeAttribute>();
var dtoResourceTypeAttr = parent.GetCustomAttribute<DtoResourceTypeAttribute>(inherit: true);
if (dtoResourceTypeAttr is not null)
{
var resourceType = dtoResourceTypeAttr.ResourceType;
Expand Down Expand Up @@ -117,7 +117,7 @@ private void OnValidationRequested(object? sender, ValidationRequestedEventArgs

var objectType = modelValidationContext.ObjectType;
var objectInstance = modelValidationContext.ObjectInstance;
var dtoResourceTypeAttr = objectType.GetCustomAttribute<DtoResourceTypeAttribute>();
var dtoResourceTypeAttr = objectType.GetCustomAttribute<DtoResourceTypeAttribute>(inherit: true);

validationMessageStore.Clear();
if (dtoResourceTypeAttr is not null)
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -21,16 +21,12 @@ public partial class AppInitializer : AppComponentBase
[AutoInject] private IBitDeviceCoordinator bitDeviceCoordinator = default!;
[AutoInject] private IStorageService storageService = default!;
[AutoInject] private CultureInfoManager cultureInfoManager = default!;
[AutoInject] private ILogger<AuthenticationManager> authLogger = default!;
[AutoInject] private ILogger<AppInitializer> appInitializerLogger = default!;
[AutoInject] private NavigationManager navigationManager = default!;

protected async override Task OnInitAsync()
{
AuthenticationManager.AuthenticationStateChanged += AuthenticationStateChanged;

LogApplicationStarting(appInitializerLogger, AppPlatform.OSDescription, typeof(AppInitializer).Assembly.GetName().Version!.ToString());

AuthenticationStateChanged(AuthenticationManager.GetAuthenticationStateAsync());

if (AppPlatform.IsBlazorHybrid)
Expand Down Expand Up @@ -62,12 +58,6 @@ private async void AuthenticationStateChanged(Task<AuthenticationState> task)
{
try
{
var user = (await task).User;

var (isUserAuthenticated, userId, userName, email, sessionId) = user.IsAuthenticated() ? (user.IsAuthenticated(), user.GetUserId().ToString(), user.GetUserName(), user.GetEmail(), user.GetSessionId()) : default;

LogAuthenticationStateChanged(authLogger, isUserAuthenticated, userId, userName, email, sessionId);

//#if (signalr == true)
if (InPrerenderSession is false)
{
Expand All @@ -88,12 +78,6 @@ private async void AuthenticationStateChanged(Task<AuthenticationState> task)
}
}

[LoggerMessage(Level = LogLevel.Information, Message = "Authentication state changed: {IsUserAuthenticated}, {UserId}, {UserName}, {Email}, {UserSessionId}")]
private static partial void LogAuthenticationStateChanged(ILogger logger, bool isUserAuthenticated, string userId, string userName, string? email, Guid? userSessionId);

[LoggerMessage(Level = LogLevel.Information, Message = "Application starting: {OS}, {AppVersion}")]
private static partial void LogApplicationStarting(ILogger logger, string os, string appVersion);

//#if (signalr == true)
private async Task ConnectSignalR()
{
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -126,7 +126,7 @@ private void SetIsCrossLayout()

var type = currentRouteData.PageType;

if (type.GetCustomAttribute<AuthorizeAttribute>() is not null)
if (type.GetCustomAttribute<AuthorizeAttribute>(inherit: true) is not null)
{
isCrossLayoutPage = false;
return;
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -83,7 +83,7 @@ private async Task ChangeEmail()
{
await userController.ChangeEmail(changeModel, CurrentCancellationToken);

NavigationManager.Refresh(forceReload: true);
NavigationManager.NavigateTo(Urls.SettingsPage, forceLoad: true);
}
catch (KnownException e)
{
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -83,7 +83,7 @@ private async Task ChangePhoneNumber()
{
await userController.ChangePhoneNumber(changeModel, CurrentCancellationToken);

NavigationManager.Refresh(forceReload: true);
NavigationManager.NavigateTo(Urls.SettingsPage, forceLoad: true);
}
catch (KnownException e)
{
Expand Down
Loading

0 comments on commit 2501883

Please sign in to comment.