Skip to content

Commit

Permalink
fix(templates): resolve Boilerplate last seen on issues with timezone #…
Browse files Browse the repository at this point in the history
  • Loading branch information
ysmoradi authored Oct 30, 2024
1 parent 239d52c commit 1c571cb
Show file tree
Hide file tree
Showing 36 changed files with 269 additions and 157 deletions.
2 changes: 1 addition & 1 deletion .github/workflows/todo-sample.cd.yml
Original file line number Diff line number Diff line change
Expand Up @@ -47,7 +47,7 @@ jobs:
env:
ServerAddress: ${{ env.SERVER_ADDRESS }}
WebAppRender.BlazorMode: BlazorWebAssembly
WebAppRender.PreRenderEnabled: true
WebAppRender.PrerenderEnabled: true
ApplicationInsights.ConnectionString: ${{ secrets.APPLICATION_INSIGHTS_CONNECTION_STRING }}
AdsPushVapid.PublicKey: ${{ secrets.TODO_PUBLIC_VAPIDKEY }}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -63,7 +63,7 @@

@if (HttpContext.Request.IsCrawlerClient() is false)
{
<Script src="_framework/blazor.web.js" autostart="false"></Script>
<Script src="_framework/blazor.web.js?v=9.0.0-rc.2.24474.3" autostart="false"></Script>
@if (AppRenderMode.PwaEnabled)
{
<Script src="_content/Bit.Bswup/bit-bswup.js"></Script>
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -20,7 +20,7 @@ public partial class AppComponentBase : ComponentBase, IAsyncDisposable
[AutoInject] protected IPrerenderStateService PrerenderStateService = default!;

/// <summary>
/// <inheritdoc cref="IPubSubService"/>
/// <inheritdoc cref="Services.PubSubService"/>
/// </summary>
[AutoInject] protected PubSubService PubSubService = default!;

Expand All @@ -38,6 +38,8 @@ public partial class AppComponentBase : ComponentBase, IAsyncDisposable

[AutoInject] protected SnackBarService SnackBarService = default!;

[AutoInject] protected ITelemetryContext TelemetryContext = default!;


private readonly CancellationTokenSource cts = new();
protected CancellationToken CurrentCancellationToken => cts.Token;
Expand Down
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
//+:cnd:noEmit
using Microsoft.Extensions.Logging;
//#if (signalr == true)
using Microsoft.AspNetCore.SignalR.Client;
//#endif
Expand All @@ -14,17 +15,18 @@ public partial class AppInitializer : AppComponentBase
//#if (notification == true)
[AutoInject] private IPushNotificationService pushNotificationService = default!;
//#endif
[AutoInject] private Navigator navigator = default!;
[AutoInject] private IJSRuntime jsRuntime = default!;
[AutoInject] private Bit.Butil.Console console = default!;
[AutoInject] private IStorageService storageService = default!;
[AutoInject] private ILogger<AppInitializer> logger = default!;
[AutoInject] private SnackBarService snackBarService = default!;
[AutoInject] private AuthenticationManager authManager = default!;
[AutoInject] private ITelemetryContext telemetryContext = default!;
[AutoInject] private NavigationManager navigationManager = default!;
[AutoInject] private CultureInfoManager cultureInfoManager = default!;
[AutoInject] private IBitDeviceCoordinator bitDeviceCoordinator = default!;

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

Expand All @@ -51,9 +53,12 @@ protected override async Task OnAfterFirstRenderAsync()
{
await base.OnAfterFirstRenderAsync();

TelemetryContext.UserAgent = await navigator.GetUserAgent();
TelemetryContext.TimeZone = await jsRuntime.GetTimeZone();
TelemetryContext.Culture = CultureInfo.CurrentCulture.Name;
if (AppPlatform.IsBlazorHybrid is false)
{
telemetryContext.OS = await jsRuntime.GetBrowserPlatform();
TelemetryContext.OS = await jsRuntime.GetBrowserPlatform();
}
}

Expand All @@ -62,8 +67,8 @@ private async void AuthenticationStateChanged(Task<AuthenticationState> task)
try
{
var user = (await task).User;
telemetryContext.UserId = user.IsAuthenticated() ? user.GetUserId() : null;
telemetryContext.UserSessionId = user.IsAuthenticated() ? user.GetSessionId() : null;
TelemetryContext.UserId = user.IsAuthenticated() ? user.GetUserId() : null;
TelemetryContext.UserSessionId = user.IsAuthenticated() ? user.GetSessionId() : null;

//#if (signalr == true)
if (InPrerenderSession is false)
Expand Down Expand Up @@ -97,7 +102,7 @@ private async Task ConnectSignalR()

hubConnection = new HubConnectionBuilder()
.WithAutomaticReconnect()
.WithUrl($"{Configuration.GetServerAddress()}/app-hub?access_token={access_token}", options =>
.WithUrl($"{HttpClient.BaseAddress}app-hub?access_token={access_token}", options =>
{
options.Transports = Microsoft.AspNetCore.Http.Connections.HttpTransportType.WebSockets;
// Avoid enabling long polling or Server-Sent Events. Focus on resolving the issue with WebSockets instead.
Expand All @@ -123,8 +128,35 @@ private async Task ConnectSignalR()
// You can also leverage IPubSubService to notify other components in the application.
});

hubConnection.Closed += HubConnectionDisconnected;
hubConnection.Reconnected += HubConnectionConnected;
hubConnection.Reconnecting += HubConnectionDisconnected;

await hubConnection.StartAsync(CurrentCancellationToken);

await HubConnectionConnected(null);
}

private async Task HubConnectionConnected(string? arg)
{
TelemetryContext.IsOnline = true;
logger.LogInformation("SignalR connection established.");
}

private async Task HubConnectionDisconnected(Exception? exception)
{
TelemetryContext.IsOnline = false;

if (exception is null)
{
logger.LogInformation("SignalR connection lost."); // Was triggered intentionally by either server or client.
}
else
{
ExceptionHandler.Handle(exception);
}
}

//#endif

private async Task SetupBodyClasses()
Expand Down Expand Up @@ -162,6 +194,9 @@ protected override async ValueTask DisposeAsync(bool disposing)
//#if (signalr == true)
if (hubConnection is not null)
{
hubConnection.Closed -= HubConnectionDisconnected;
hubConnection.Reconnected -= HubConnectionConnected;
hubConnection.Reconnecting -= HubConnectionDisconnected;
await hubConnection.DisposeAsync();
}
//#endif
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -7,13 +7,13 @@
<BitText>@Localizer[nameof(AppStrings.CurrentSession)]</BitText>
<BitCard FullWidth>
<BitPersona PrimaryText="@(currentSession.Device ?? Localizer[nameof(AppStrings.UnknownDevice)])"
SecondaryText="@currentSession.Address"
TertiaryText="@($"{currentSession.IP} - {currentSession.LastSeenOn}")"
Size="BitPersonaSize.Size48"
Presence="@GetPresence(currentSession.LastSeenOn)"
Styles="@(new() { Image = "width:50%;height:50%" })"
ImageInitials=""
ImageUrl="@($"/_content/Boilerplate.Client.Core/images/os/{GetImageUrl(currentSession.Device)}")" />
SecondaryText="@currentSession.Address"
TertiaryText="@($"{currentSession.IP} - {GetLastSeenOn(currentSession.RenewedOn)}")"
Size="BitPersonaSize.Size48"
Presence="@GetPresence(currentSession.RenewedOn)"
Styles="@(new() { Image = "width:50%;height:50%" })"
ImageInitials=""
ImageUrl="@($"/_content/Boilerplate.Client.Core/images/os/{GetImageUrl(currentSession.Device)}")" />
</BitCard>
}

Expand All @@ -28,9 +28,9 @@
<BitStack Horizontal VerticalAlign="BitAlignment.Center">
<BitPersona Class="session-persona"
PrimaryText="@(session.Device ?? Localizer[nameof(AppStrings.UnknownDevice)])"
SecondaryText="@($"{session.Address} ({session.IP}) - {session.LastSeenOn}")"
SecondaryText="@($"{session.Address} ({session.IP}) - {GetLastSeenOn(session.RenewedOn)}")"
Size="BitPersonaSize.Size48"
Presence="@GetPresence(session.LastSeenOn)"
Presence="@GetPresence(session.RenewedOn)"
Styles="@(new() { Image = "width:50%;height:50%" })"
ImageInitials="@(session.IsValid ? "" : "")"
ImageUrl="@($"/_content/Boilerplate.Client.Core/images/os/{GetImageUrl(session.Device)}")" />
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -75,10 +75,17 @@ private static string GetImageUrl(string? device)
return "apple.png";
}

private static BitPersonaPresence GetPresence(string? lastSeenOn)
private BitPersonaPresence GetPresence(DateTimeOffset renewedOn)
{
return lastSeenOn == AppStrings.Online ? BitPersonaPresence.Online
: lastSeenOn == AppStrings.Recently ? BitPersonaPresence.Away
: BitPersonaPresence.Offline;
return DateTimeOffset.UtcNow - renewedOn < TimeSpan.FromMinutes(5) ? BitPersonaPresence.Online
: DateTimeOffset.UtcNow - renewedOn < TimeSpan.FromMinutes(15) ? BitPersonaPresence.Away
: BitPersonaPresence.Offline;
}

private string GetLastSeenOn(DateTimeOffset renewedOn)
{
return DateTimeOffset.UtcNow - renewedOn < TimeSpan.FromMinutes(5) ? Localizer[nameof(AppStrings.Online)]
: DateTimeOffset.UtcNow - renewedOn < TimeSpan.FromMinutes(15) ? Localizer[nameof(AppStrings.Recently)]
: renewedOn.ToLocalTime().ToString("g");
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -86,7 +86,7 @@
Styles="@(new() { Label = todo.IsDone ? "text-decoration:line-through" : "" })"
DefaultValue="todo.IsDone"
OnChange="() => ToggleIsDone(todo)" />
<BitText Typography="BitTypography.Body2">@todo.Date.ToLocalTime().ToString("yyyy MMMM dd, HH:mm:ss")</BitText>
<BitText Typography="BitTypography.Body2">@todo.Date.ToLocalTime().ToString("F")</BitText>
</BitStack>

<BitStack Horizontal AutoWidth Gap="0.5rem">
Expand Down

This file was deleted.

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

Original file line number Diff line number Diff line change
Expand Up @@ -33,7 +33,7 @@ protected override void Up(MigrationBuilder migrationBuilder)
migrationBuilder.InsertData(
table: "Users",
columns: new[] { "Id", "BirthDate", "Email", "FullName", "Gender", "Password", "PhoneNumber", "ProfileImageName", "UserName" },
values: new object[] { new Guid("8ff71671-a1d6-4f97-abb9-d87d7b47d6e7"), 1306790461440000000L, "[email protected]", "Boilerplate test account", 2, "123456", "+31684207362", null, "test" });
values: new object[] { new Guid("8ff71671-a1d6-4f97-abb9-d87d7b47d6e7"), 1306790461440000000L, "[email protected]", "Boilerplate test account", 0, "123456", "+31684207362", null, "test" });
}

/// <inheritdoc />
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,7 @@ partial class OfflineDbContextModelSnapshot : ModelSnapshot
protected override void BuildModel(ModelBuilder modelBuilder)
{
#pragma warning disable 612, 618
modelBuilder.HasAnnotation("ProductVersion", "8.0.7");
modelBuilder.HasAnnotation("ProductVersion", "8.0.0");

modelBuilder.Entity("Boilerplate.Shared.Dtos.Identity.UserDto", b =>
{
Expand Down Expand Up @@ -58,7 +58,7 @@ protected override void BuildModel(ModelBuilder modelBuilder)
BirthDate = 1306790461440000000L,
Email = "[email protected]",
FullName = "Boilerplate test account",
Gender = 2,
Gender = 0,
Password = "123456",
PhoneNumber = "+31684207362",
UserName = "test"
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,11 @@ public static ValueTask<string> GetBrowserPlatform(this IJSRuntime jsRuntime)
return jsRuntime.InvokeAsync<string>("App.getPlatform");
}

public static ValueTask<string> GetTimeZone(this IJSRuntime jsRuntime)
{
return jsRuntime.InvokeAsync<string>("App.getTimeZone");
}

public static ValueTask ApplyBodyElementClasses(this IJSRuntime jsRuntime, List<string> cssClasses, Dictionary<string, string> cssVariables)
{
return jsRuntime.InvokeVoidAsync("App.applyBodyElementClasses", cssClasses, cssVariables);
Expand Down
Loading

0 comments on commit 1c571cb

Please sign in to comment.