Skip to content

doc(Online): update sample code#8042

Merged
ArgoZhang merged 2 commits into
mainfrom
doc-online
May 22, 2026
Merged

doc(Online): update sample code#8042
ArgoZhang merged 2 commits into
mainfrom
doc-online

Conversation

@ArgoZhang
Copy link
Copy Markdown
Member

@ArgoZhang ArgoZhang commented May 22, 2026

Link issues

fixes #8041

Summary By Copilot

Regression?

  • Yes
  • No

Risk

  • High
  • Medium
  • Low

Verification

  • Manual (required)
  • Automated

Packaging changes reviewed?

  • Yes
  • No
  • N/A

☑️ Self Check before Merge

⚠️ Please check all items below before review. ⚠️

  • Doc is updated/provided or not needed
  • Demo is updated/provided or not needed
  • Merge the latest code from the main branch

Summary by Sourcery

Refactor the Online connections page to use a strongly-typed table and an async periodic refresh loop for displaying connection data.

Enhancements:

  • Replace the DataTable-based dynamic context with a strongly-typed List bound directly to the table component.
  • Update the Online page UI to define explicit template columns for connection metadata (times, IP, client info, request URL) with appropriate formatting and masking.
  • Introduce an async periodic refresh mechanism using a cancellation token and periodic timer instead of a manual loop, simplifying lifecycle and disposal handling.

Copilot AI review requested due to automatic review settings May 22, 2026 05:43
@bb-auto bb-auto Bot added the documentation Improvements or additions to documentation label May 22, 2026
@bb-auto bb-auto Bot added this to the v10.6.0 milestone May 22, 2026
@sourcery-ai
Copy link
Copy Markdown
Contributor

sourcery-ai Bot commented May 22, 2026

Reviewer's Guide

Refactors the Online page from a DataTable/ DynamicObject-based sample to a strongly-typed ConnectionItem table with async periodic refresh using PeriodicTimer, simplifying the data model and rendering logic.

Sequence diagram for Online page periodic refresh with PeriodicTimer

sequenceDiagram
    actor User
    participant Browser
    participant Online
    participant ConnectionService
    participant PeriodicTimer

    User->>Browser: Navigate /online
    Browser->>Online: OnAfterRenderAsync(firstRender=true)
    Online->>Online: _cancellationTokenSource ??= new CancellationTokenSource()
    Online->>Online: _refreshTask = RefreshAsync(token)
    activate Online
    Online->>PeriodicTimer: new PeriodicTimer(10s)
    loop every 10s
        PeriodicTimer->>Online: WaitForNextTickAsync(token)
        Online->>Online: BuildContext()
        Online->>ConnectionService: read Connections
        Online->>Online: InvokeAsync(StateHasChanged)
    end
    deactivate Online

    User->>Browser: Leave page / dispose
    Browser->>Online: Dispose()
    Online->>Online: _cancellationTokenSource.Cancel()
    Online->>Online: _refreshTask = null
Loading

File-Level Changes

Change Details Files
Replace DataTable/DynamicObject + DynamicTable usage with a strongly-typed ConnectionItem list and templated Table columns.
  • Remove DataTable, DynamicObjectContext, and related dynamic column configuration and row-class formatting logic.
  • Introduce a private List as the backing collection and sort it via a static Comparison.
  • Update BuildContext to populate and sort the _items list from ConnectionService.Connections.
  • Rewrite Online.razor to use with explicit TableTemplateColumn definitions for each displayed field, including formatting for dates, duration, masked IP, and request URL link rendering.
    src/BootstrapBlazor.Server/Components/Pages/Online.razor.cs
    src/BootstrapBlazor.Server/Components/Pages/Online.razor
    Change the refresh mechanism to an async periodic loop using PeriodicTimer and remove WebClientService/client-id specific behavior.
    • Remove WebClientService injection, client id tracking, and SetRowClassFormatter-based highlighting of the current client row.
    • Replace Task.Run-based polling in OnAfterRender with OnAfterRenderAsync that starts a single RefreshAsync task on first render.
    • Implement RefreshAsync that uses PeriodicTimer with a 10-second interval to rebuild context and trigger StateHasChanged until cancellation.
    • Track the background refresh task in a _refreshTask field and ensure it and the CancellationTokenSource are cleaned up in Dispose.
    src/BootstrapBlazor.Server/Components/Pages/Online.razor.cs

    Assessment against linked issues

    Issue Objective Addressed Explanation
    doc(Online): update sample code #8041 Update the Online component documentation/sample code to include a current, explicit sample demonstrating how to use the Online page with the Table component.

    Possibly linked issues


    Tips and commands

    Interacting with Sourcery

    • Trigger a new review: Comment @sourcery-ai review on the pull request.
    • Continue discussions: Reply directly to Sourcery's review comments.
    • Generate a GitHub issue from a review comment: Ask Sourcery to create an
      issue from a review comment by replying to it. You can also reply to a
      review comment with @sourcery-ai issue to create an issue from it.
    • Generate a pull request title: Write @sourcery-ai anywhere in the pull
      request title to generate a title at any time. You can also comment
      @sourcery-ai title on the pull request to (re-)generate the title at any time.
    • Generate a pull request summary: Write @sourcery-ai summary anywhere in
      the pull request body to generate a PR summary at any time exactly where you
      want it. You can also comment @sourcery-ai summary on the pull request to
      (re-)generate the summary at any time.
    • Generate reviewer's guide: Comment @sourcery-ai guide on the pull
      request to (re-)generate the reviewer's guide at any time.
    • Resolve all Sourcery comments: Comment @sourcery-ai resolve on the
      pull request to resolve all Sourcery comments. Useful if you've already
      addressed all the comments and don't want to see them anymore.
    • Dismiss all Sourcery reviews: Comment @sourcery-ai dismiss on the pull
      request to dismiss all existing Sourcery reviews. Especially useful if you
      want to start fresh with a new review - don't forget to comment
      @sourcery-ai review to trigger a new review!

    Customizing Your Experience

    Access your dashboard to:

    • Enable or disable review features such as the Sourcery-generated pull request
      summary, the reviewer's guide, and others.
    • Change the review language.
    • Add, remove or edit custom review instructions.
    • Adjust other review settings.

    Getting Help

@ArgoZhang ArgoZhang merged commit 03f2385 into main May 22, 2026
6 checks passed
@ArgoZhang ArgoZhang deleted the doc-online branch May 22, 2026 05:44
Copy link
Copy Markdown
Contributor

@sourcery-ai sourcery-ai Bot left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Hey - I've left some high level feedback:

  • In RefreshAsync, BuildContext() is called directly on the background timer thread before InvokeAsync(StateHasChanged), which means component state (_items) is being mutated off the renderer thread; consider wrapping both BuildContext() and StateHasChanged() inside a single await InvokeAsync(() => { BuildContext(); StateHasChanged(); }); to keep state changes on the UI thread.
  • The current refresh logic waits for the first 10-second timer tick before populating _items, so the table will render empty after initial navigation; consider invoking BuildContext() once during initialization/first render (or before starting the timer) so the initial data is shown immediately.
Prompt for AI Agents
Please address the comments from this code review:

## Overall Comments
- In `RefreshAsync`, `BuildContext()` is called directly on the background timer thread before `InvokeAsync(StateHasChanged)`, which means component state (`_items`) is being mutated off the renderer thread; consider wrapping both `BuildContext()` and `StateHasChanged()` inside a single `await InvokeAsync(() => { BuildContext(); StateHasChanged(); });` to keep state changes on the UI thread.
- The current refresh logic waits for the first 10-second timer tick before populating `_items`, so the table will render empty after initial navigation; consider invoking `BuildContext()` once during initialization/first render (or before starting the timer) so the initial data is shown immediately.

Sourcery is free for open source - if you like our reviews please consider sharing them ✨
Help me be more useful! Please click 👍 or 👎 on each comment and I'll use the feedback to improve your reviews.

@codecov
Copy link
Copy Markdown

codecov Bot commented May 22, 2026

Codecov Report

✅ All modified and coverable lines are covered by tests.
✅ Project coverage is 100.00%. Comparing base (52abd8f) to head (9f745c0).
⚠️ Report is 1 commits behind head on main.

Additional details and impacted files
@@            Coverage Diff            @@
##              main     #8042   +/-   ##
=========================================
  Coverage   100.00%   100.00%           
=========================================
  Files          766       766           
  Lines        34154     34154           
  Branches      4696      4696           
=========================================
  Hits         34154     34154           
Flag Coverage Δ
BB 100.00% <ø> (?)

Flags with carried forward coverage won't be shown. Click here to find out more.

☔ View full report in Codecov by Sentry.
📢 Have feedback on the report? Share it here.

🚀 New features to boost your workflow:
  • ❄️ Test Analytics: Detect flaky tests, report on failures, and find test suite problems.
  • 📦 JS Bundle Analysis: Save yourself from yourself by tracking and limiting bundle sizes in JS merges.

Copy link
Copy Markdown
Contributor

Copilot AI left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Pull request overview

Updates the /online page sample to use a strongly-typed Table and simplifies the refresh logic for displaying current connections (Issue #8041).

Changes:

  • Replaces the DataTable/DynamicObject-based table with a Table bound to List<ConnectionItem> and explicit TableTemplateColumns.
  • Refactors periodic UI refresh from a Task.Run loop to an async PeriodicTimer-driven loop.
  • Removes client-id row-highlighting logic and associated WebClientService usage.

Reviewed changes

Copilot reviewed 2 out of 2 changed files in this pull request and generated 1 comment.

File Description
src/BootstrapBlazor.Server/Components/Pages/Online.razor.cs Switches to a typed in-memory list (List<ConnectionItem>) and introduces a PeriodicTimer refresh loop.
src/BootstrapBlazor.Server/Components/Pages/Online.razor Rewrites the table markup to use typed items and template columns for each displayed field.

💡 Add Copilot custom instructions for smarter, more guided reviews. Learn how to get started.

Comment on lines +47 to 60
private async Task RefreshAsync(CancellationToken cancellationToken)
{
_table.Rows.Clear();
var rows = ConnectionService.Connections.Sort(["ConnectionTime"]);
foreach (var item in rows)
{
_table.Rows.Add(
item.Id,
item.ConnectionTime,
item.LastBeatTime,
item.LastBeatTime - item.ConnectionTime,
item.ClientInfo?.Ip ?? "",
item.ClientInfo?.City ?? "",
item.ClientInfo?.OS ?? "",
item.ClientInfo?.Device.ToString() ?? "",
item.ClientInfo?.Browser ?? "",
item.ClientInfo?.Language ?? "",
item.ClientInfo?.Engine ?? "",
item.ClientInfo?.RequestUrl ?? ""
);
}
_table.AcceptChanges();
using var timer = new PeriodicTimer(TimeSpan.FromSeconds(10));

//table
DataTableDynamicContext = new DataTableDynamicContext(_table, (context, col) =>
try
{
col.Text = Localizer[col.GetFieldName()];
if (col.GetFieldName() == "Id")
while (await timer.WaitForNextTickAsync(cancellationToken))
{
col.Ignore = true;
BuildContext();
await InvokeAsync(StateHasChanged);
}
else if (col.GetFieldName() == "ConnectionTime")
{
col.FormatString = "yyyy/MM/dd HH:mm:ss";
col.Width = 118;
}
else if (col.GetFieldName() == "LastBeatTime")
{
col.FormatString = "yyyy/MM/dd HH:mm:ss";
col.Width = 118;
}
else if (col.GetFieldName() == "Dur")
{
col.FormatString = @"dd\.hh\:mm\:ss";
col.Width = 54;
}
else if (col.GetFieldName() == "Ip")
{
col.Template = v => builder => builder.AddContent(0, FormatIp(v));
}
else if (col.GetFieldName() == "RequestUrl")
{
col.Template = v => builder =>
{
if (v is IDynamicObject val)
{
var url = val.GetValue("RequestUrl")?.ToString();
if (!string.IsNullOrEmpty(url))
{
builder.AddContent(0, new MarkupString($"<a href=\"{url}\" target=\"_blank\">{url}</a>"));
}
}
};
}
});
}
catch (OperationCanceledException) { }
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

documentation Improvements or additions to documentation

Projects

None yet

Development

Successfully merging this pull request may close these issues.

doc(Online): update sample code

2 participants